Swift中的便捷初始化程序

时间:2014-10-01 21:44:49

标签: ios swift

我正在尝试为Swift中的某个模型创建某种initWithDictionary初始值设定项。这就是我想要做的事情:

class CityModel: NSObject {

    var country: String
    var mapLat: String
    var mapLng: String
    var mapZoom: Int
    var name: String
    var nameShort: String
    var timezone: String
    var token: String

    init(country: String, mapLat: String, mapLng: String, mapZoom: Int, name: String, nameShort: String, timezone: String, token: String) {
        self.country = country
        self.mapLat = mapLat
        self.mapLng = mapLng
        self.mapZoom = mapZoom
        self.name = name
        self.nameShort = nameShort
        self.timezone = timezone
        self.token = token
    }

    convenience init(dict: Dictionary<String, AnyObject>) {
        self.init(
            country: (dict["country"] as String),
            mapLat: (dict["mapLat"] as String), // error
            mapLng: (dict["mapLng"] as String),
            mapZoom: (dict["mapZoom"] as Int),
            name: (dict["name"] as String),
            nameShort: (dict["nameShort"] as String),
            timezone: (dict["timezone"] as String),
            token: (dict["token"] as String)
        )
    }
}

我收到以下错误:

CityModel.swift:34:18: Extra argument 'mapLat' in call

而且我害怕我不知道自己做错了什么。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

将您的dict声明更改为:

dict: Dictionary<String, Any>

这是因为您使用了包括非类型类型在内的各种类型。

Swift文档中的更多信息: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-XID_505

那&#34;额外的论点&#34;错误信息是一个红鲱鱼。我发现它经常抱怨论证的类型不匹配。