2014-10-01 65 views
2

我正嘗試在Swift中爲我的某個模型創建某種initWithDictionary初始值設定項。這就是我想要做的事:Swift中的便捷初始值設定程序

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 

我怕我不知道我做錯了。任何想法?

回答

3

更改您的dict聲明:

dict: Dictionary<String, Any> 

這是因爲你使用的類型,包括非類類型的混合。

在這裏斯威夫特文檔的更多信息: https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html#//apple_ref/doc/uid/TP40014097-CH22-XID_505

這「額外的參數」的錯誤消息是紅鯡魚。我發現它通常抱怨參數的類型不匹配。

+1

它解決了這個問題。謝謝。 – 2014-10-02 08:23:37

相關問題