2016-06-22 1 views
0

iOSコードを書いてから長い時間が経っていますが、iOSアプリケーションで次のモデルを持っていて、うまくいきましたが、今はdetailがオプションですゼロ値を許可する必要があります。これをサポートするためにイニシャライザを調整するにはどうすればよいですか?申し訳ありませんが、私は選択肢を把握するのが少し難しいと感じています(コンセプトは意味があります - 実行は難しい)。次の呼び出しで属性を作成する方法(つまり、nilを許可する)

class Item{ 
    var id:Int 
    var header:String 
    var detail:String 

    init?(dictionary: [String: AnyObject]) { 
    guard let id = dictionary["id"] as? Int, 
     let header = dictionary["header"] as? String, 
     let detail = dictionary["detail"] as? String else { 
     return nil 
    } 
    self.id = id 
    self.header = header 
    self.detail = detail 
    } 

と作成:

var items = [Item]() 
if let item = Item(dictionary: dictionary) { 
    self.items.append(item) 
} 

答えて

1

@AMomchilovによる上記の回答のように、initメソッドに存在する場合にのみ値を割り当てることができます。 しかし、また、あなたが値をチェックして、以下のようにアクセスできます。

class Item { 
    var id:Int 
    var header:String 
    var detail: String? 

    init?(dictionary: [String: AnyObject]) { 
     guard let id = dictionary["id"] as? Int, 
      let header = dictionary["header"] as? String else { 
       return nil 
     } 
     self.id = id 
     self.header = header 
     self.detail = dictionary["detail"] as? String //if there is value then it will assign else nil will be assigned. 
    } 
} 

let dictionary = ["id": 10, "header": "HeaderValue"] 
var items = [Item]() 
if let item = Item(dictionary: dictionary) { 
    items.append(item) 

    print(item.id) 
    print(item.detail ?? "'detail' is nil for this item") 
    print(item.header) 
}else{ 
    print("No Item created!") 
} 

とコンソールは次のとおりです。

10 
'detail' is nil for this item 
HeaderValue 

と `詳細」の値が、その後が存在する場合:

let dictionary = ["id": 10, "header": "HeaderValue", "detail":"DetailValue"] 
var items = [Item]() 
if let item = Item(dictionary: dictionary) { 
    items.append(item) 

    print(item.id) 
    print(item.detail ?? "'detail' is nil for this item") 
    print(item.header) 
}else{ 
    print("No Item created!") 
} 

コンソール:

10 
DetailValue 
HeaderValue 
+0

私は 'のように忘れてしまったのですか?これは非常にいいです、アップボートを持って – Alexander

+0

あなたはあなたの問題を解決するのに役立ちました答えを受け入れることができます:) – Santosh

1

(現在nil値が許容可能であるように)ガードからdetailを取り外し、dictionary["detail"] as? Stringself.detailを割り当てます。

class Item { 
    var id: Int 
    var header: String 
    var detail: String? 

    init?(dictionary: [String: AnyObject]) { 
    guard let id = dictionary["id"] as? Int, 
     let header = dictionary["header"] as? String else { 
     return nil 
    } 
    self.id = id 
    self.header = header 

    self.detail = dictionary["detail"] as? String 
    } 

編集:Santoshの回答に基づいて改善されました。

関連する問題