Missing argument for parameter #1 in call when setting initial value

时光总嘲笑我的痴心妄想 提交于 2019-12-11 12:09:17

问题


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

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