Error when trying to store random element from array in variable Swift 2

房东的猫 提交于 2019-12-12 03:18:13

问题


I have an array of area codes and I am trying store a random element from the array in a variable and I get an error "instance member 'areaCodes' can not be used on type 'ViewController' ". Any suggestions?

var areaCodes = [209, 213, 310, 323, 408, 415]
var firstThree = areaCodes[Int(arc4random_uniform(UInt32(areaCodes.count)))]

回答1:


You can not access your array at initialization time. Change your property to a read only computed property:

var firstThree: Int { return areaCodes[Int(arc4random_uniform(UInt32(areaCodes.count)))] }



回答2:


You have to assign the firstThree variable inside a function of your class.



来源:https://stackoverflow.com/questions/35076934/error-when-trying-to-store-random-element-from-array-in-variable-swift-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!