设置初始值时调用中的参数#1缺少参数 [英] Missing argument for parameter #1 in call when setting initial value

查看:122
本文介绍了设置初始值时调用中的参数#1缺少参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将当前语言环境国家/地区设置为初始值:

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
    }
}

推荐答案

问题是国家/地区是 instance 变量,而currentCountry也是 instance 函数.当您要初始化国家/地区时,尚无实例,因此您无法引用currentCountry函数.但是,如果您进行如下更改:

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
}

它将起作用,因为现在currentCountry是一个 class 函数,并且在初始化时可用.

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()
}

这篇关于设置初始值时调用中的参数#1缺少参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆