问题
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