我正在使用 Swift,使用字典,然后尝试将信息放入数组中,并访问数组中的值。这就是我的代码中的内容:
// I have abbreviated the actual dictionary to not waste question space...
var plateIssuers: Dictionary<String,String> = [
"Alberta": "Canada",
"British Columbia": "Canada",
"Manitoba":"Canada",
"VERMONT":"USA",
"WASHINGTON":"USA",
"WISCONSIN":"USA",
"WEST VIRGINIA":"USA",
"WYOMING]":"USA"]
// This is an attempt that seems to work to create an Array of unique values (turning into sets and then back to array
let countries:Array = NSSet(array: Array<String>(plateIssuers.values)).allObjects
let issuers:Array = NSSet(array: Array<String>(plateIssuers.keys)).allObjects
后来,在 tableView 函数中,我有以下代码:
println(countries[1])
cell.textLabel.text = countries[(indexPath.row)]
println 工作正常(打印“加拿大”),但 cell.textLabel 行给出以下错误(不会构建):
Could not find an overload for 'subscript' that accepts the supplied arguments
如何 println 可以工作,但下一行不能工作。我还应该提到,如果我只是引用一个我以简单方式构建的带有字符串的数组,那么第二行就可以工作。我的问题是我创建“国家”数组的方式吗?还是我引用它的方式有问题?谢谢
最佳答案
这样做:
let countries = NSSet(array: Array<String>(plateIssuers.values)).allObjects as Array<String>
Swift 的编译器一如既往地在表达问题时含糊其辞。这里的意思是,对 AnyObject 数组(从 allObjects
返回的内容)进行下标是可能的,但不会为您提供一个 String,即标签的 text
属性期望。
关于arrays - 使用 NSSet 构造可用的 Swift 数组时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24601346/