2014-11-23 61 views
10

在Swift類中,我想將屬性用作同一類的方法的默認參數值。使用屬性作爲同一類中方法的默認參數值

這裏是我的代碼:

class animal { 
    var niceAnimal:Bool 
    var numberOfLegs:Int 

    init(numberOfLegs:Int,animalIsNice:Bool) { 
     self.numberOfLegs = numberOfLegs 
     self.niceAnimal = animalIsNice 
    } 

    func description(animalIsNice:Bool = niceAnimal,numberOfLegs:Int) { 
     // I'll write my code here 
    } 
} 

的問題是,我不能用我的niceAnimal屬性作爲默認函數值,因爲它觸發了我一個編譯時錯誤:

'animal.Type' 沒有一個名爲 'niceAnimal'

我是樂隊成員有什麼問題?或者在Swift中不可能?如果這是不可能的,你知道爲什麼嗎?

回答

6

我不認爲你做錯了什麼。

語言規範只說默認參數應該在非默認參數(p169)之前,並且默認值由表達式(p637)定義。

它沒有說明允許引用的表達式。似乎不允許引用您調用方法的實例,即self,這似乎有必要引用self.niceAnimal。

作爲一種解決方法,您可以將默認參數定義爲默認參數爲nil的默認參數,然後使用在默認情況下引用成員變量的「if let」來設置實際值,如下所示:

class animal { 
    var niceAnimal:Bool 
    var numberOfLegs:Int 

    init(numberOfLegs:Int,animalIsNice:Bool) { 
     self.numberOfLegs = numberOfLegs 
     self.niceAnimal = animalIsNice 
    } 

    func description(numberOfLegs:Int,animalIsNice:Bool? = nil) { 
     if let animalIsNice = animalIsNice ?? self.niceAnimal { 
     // println 

     } 
    } 
} 
+0

非常感謝您的回答。作爲開發者,你對這種行爲有什麼看法? – 2014-11-23 06:37:33

+2

我不確定。我認爲默認的參數值是一個很好的方便,但是它們也可能會導致關於何時評估默認表達式的令人驚訝和複雜的角落案例。我知道它在Python中變得混亂。所以我可以看到保持清晰和有限的美德。我認爲解決方法並不是很糟糕。 – algal 2014-11-23 06:41:09

+0

好吧,我明白,蘋果可能想保持簡單,然後... – 2014-11-23 06:46:40

0

我認爲現在你只能使用文字和類型屬性作爲默認參數。

最好的選擇是重載方法,你可以通過調用完整的方法來實現較短的版本。我只在這裏使用了一個結構來省略初始化器。

struct Animal { 

    var niceAnimal: Bool 
    var numberOfLegs: Int 

    func description(#numberOfLegs: Int) { 
     description(niceAnimal, numberOfLegs: numberOfLegs) 
    } 

    func description(animalIsNice: Bool, numberOfLegs: Int) { 
     // do something 
    } 

}