我想声明几个数组并将它们指定为字典中键的值.
这是代码:
class ViewController: UIViewController { let colorsArray = ["Blue", "Red", "Green", "Yellow"] let numbersArray = ["One", "Two", "Three", "Four"] let myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray] override func viewDidLoad() { super.viewDidLoad() // etc.
这会产生以下错误:
ViewController.Type does not have a member named 'colorsArray'
所以....
我尝试修改我的字典声明,如下所示:
let myDictionary:Dictionary= ["Colors" : colorsArray, "Numbers" : numbersArray]
这给了我一个更好的错误:
Reference to generic type 'Array' requires arguments in <...>
我尝试了各种其他修复 - 没有任何作用.
这在Objective-C中是小菜一碟,但在Swift ......?
解决方案:
将字典声明语句移动到viewDidLoad
固定它:
class ViewController: UIViewController { let colorsArray = ["Blue", "Red", "Green", "Yellow"] let numbersArray = ["One", "Two", "Three", "Four"] override func viewDidLoad() { super.viewDidLoad() let myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray] // etc.
我不明白为什么会这样,但现在确实有效.
在您的代码中,您没有初始化colorsArray
,numbersArray
并且myDictionary
您正在指定一个默认值,如果init()
没有设置默认值.您不允许在属性的默认值中引用其他属性,因为(我推测一点)它们的设置顺序无法保证.
简单的事情
class Test { let a = 3 let b = 5 let c = a * b }
以与初始代码相同的方式失败.要设置c
或myDictionary
根据需要,我们必须在初始化程序中执行此操作,而不是使用默认值:
class Test { let a = 3 let b = 5 let c: Int init () { c = a*b } }
(请注意,不可变属性在内部是可变的init
,这是我们使用它的方式let c
.)
因此,与您的初始代码最接近的解决方案是:
class ViewController : UIViewController { let colorsArray = ["Blue", "Red", "Green", "Yellow"] let numbersArray = ["One", "Two", "Three", "Four"] let myDictionary: Dictionary<String, Array<String>> init() { myDictionary = ["Colors" : colorsArray, "Numbers" : numbersArray] super.init() } // etc }