20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift コンビニエンスイニシャライザ

Posted at

コンビニエンスイニシャライザを使用する事で
クラスの初期化でオーバーロードのような処理ができます


class Food {
    var name: String
    var weight:Int
    
    init(name: String,weight: Int) {
        self.name = name
        self.weight = weight
    }
    
    convenience init() {
        self.init(name:"[Unnamed]",weight:0)
    }
    
    convenience init(name:String) {
        self.init(name:name,weight:0)
    }
}

let meat = Food()
let bacon = Food(name:"Bacon")
let baconWithWeight = Food(name:"Bacon",weight:5)
20
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
20
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?