Skip to content

Instantly share code, notes, and snippets.

@yutailang0119
Last active March 16, 2016 08:08
Show Gist options
  • Save yutailang0119/1397430aa3e7e3b031d0 to your computer and use it in GitHub Desktop.
Save yutailang0119/1397430aa3e7e3b031d0 to your computer and use it in GitHub Desktop.
struct Hoge {
let id: Int
let title: String
let fuga: Fuga? //更にstructを内包
//メンバワイズイニシャライザ
init(id: Int, title: String,fuga: Fuga?) {
self.id = id
self.title = title
self.fuga = fuga
}
//カスタムイニシャライザ
init(dictionary: [String : AnyObject]) {
let id = dictionary["id"] as! Int
let title = dictionary["title"] as! String
var fuga: Fuga?
if let fugaDictionary = dictionary["fuga"] as? [String : AnyObject] {
fuga = Fuga(dictionary: fugaDictionary)
}
self.init(id: id, title: title, fuga: fuga)
}
//Return from initializer without initializing all stored properties => イニシャライザの中では、Optional型にも初期値が必要
init(dictionary: [String : AnyObject]) {
id = dictionary["id"] as! Int
title = dictionary["title"] as! String
if let fugaDictionary = dictionary["fuga"] as? [String : AnyObject] {
fuga = Fuga(dictionary: fugaDictionary)
} else {
fuga = nil
}
}
@yutailang0119
Copy link
Author

これで合ってるのだろうか

@yutailang0119
Copy link
Author

解決した、イニシャライザの中ではOptional型にも初期値突っ込む必要がある。
(letで宣言すると初期値しか入んないけど)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment