问题
I'm trying to set current locale country as initial value:
class Location: RLMObject {
dynamic var country = currentCountry()
func currentCountry() -> String!{
let locale = NSLocale.currentLocale()
let countryCode = locale.objectForKey(NSLocaleCountryCode) as String
let countryName = locale.displayNameForKey(NSLocaleCountryCode, value: countryCode)
return countryName
}
}
回答1:
The problem is that country is an instance variable and currentCountry is an instance function as well. When you want to initialize country, there is no instance yet, so you cannot reference the currentCountry function. But if you change like:
dynamic var country = YOUR_CLASS_NAME.currentCountry()
class func currentCountry() -> String!{
let locale = NSLocale.currentLocale()
let countryCode = locale.objectForKey(NSLocaleCountryCode) as String
let countryName = locale.displayNameForKey(NSLocaleCountryCode, value: countryCode)
return countryName
}
it will work, beacuse now currentCountry is a class function, and that is available at initialization.
Or if you don't want to define an explicit function for that, just use a closure for the computed property syntax:
dynamic var country: String {
let locale = NSLocale.currentLocale()
let countryCode = locale.objectForKey(NSLocaleCountryCode) as String
let countryName = locale.displayNameForKey(NSLocaleCountryCode, value: countryCode)
return countryName!
}
Or the third option, if you want the keep your function, you have to set the county variable after the initialization, like:
dynamic var country: String!
override func viewDidLoad() {
super.viewDidLoad()
country = currentCountry()
}
回答2:
It is bug with Xcode Simulator iOS 8.1.
It returns nil for locale.displayNameForKey(NSLocaleCountryCode, value: countryCode)
来源:https://stackoverflow.com/questions/27544642/missing-argument-for-parameter-1-in-call-when-setting-initial-value