2017-05-01 6 views
1

私は既定値と便利初期化子で指定された初期化子を読んでいると私はそれらについて少し混乱しています。 Initializerですべてのことをデフォルト値で達成できるのであれば、なぜ便利なイニシャライザを作成する必要がありますか?どのような利便性イニシャライザの利点デフォルトの値でクラスメンバを初期化して同じ仕事をする場合

両方のシナリオで例を作成して比較しました。デフォルト値で

イニシャライザ:

class Cat { 

var color:String 
var age:Int 

init(color:String = "black",age:Int = 1) { 
    self.color = color 
    self.age = age 
} 

} 

利便イニシャライザ:

class Cat { 
var color: String 
var age: Int 

//If both parameters color and age are given: 
init (color: String, age: Int) { 
     self.color = color 
     self.age = age 
} 

//If only age is given: 
convenience init (age: Int) { 
     self.init(color: "black", age: age) 
} 

//if only color is given: 
convenience init (color: String) { 
     self.init(color: color, age: 1) 
} 

//if nothing given 
convenience init() { 
     self.init(color: "black", age: 1) 
} 

} 

初期化子varientの呼び出し:

//作成オットー:

var Otto = Cat(color: "white", age: 10) 
print("Otto is \(Otto.color) and \(Otto.age) year(s) old!") 

//作成マフィン:

var Muffins = Cat(age: 5) 
print("Muffins is \(Muffins.color) and \(Muffins.age) year(s) old!") 

//ブルーノを作成します。

var Bruno = Cat(color: "red") 
print("Bruno is \(Bruno.color) and \(Bruno.age) year(s) old!") 

//作成ピコ:

var Pico = Cat() 
print("Pico is \(Pico.color) and \(Pico.age) year(s) old!") 

答えて

1

時々クラスを初期化することはないのでそれは簡単です。このRectangleクラスを見てみましょう。

convenience init(sideLength: Double) { 
    self.init(width: sideLength, height: sideLength) 
} 

あるいは、aFourthOfパラメータとり利便初期化子:

convenience init(aFourthOf rect: Rectangle) { 
    self.init(width: rect.width/2, height: rect.height/2) 
} 
をそれが sideLengthパラメータを取り初期化剤あなたが利便性を追加することができ、ここで

class Rectangle { 
    let width: Double 
    let height: Double 

    init(width: Double, height: Double) { 
     self.width = width 
     self.height = height 
    } 
} 

:それはwidthheightを持っています

このような状況がたくさんあります。

+0

okありがとう:) –

関連する問題