2015-07-04 42 views
2

吸氣劑計算屬性和返回值的變量之間是否有區別?例如。以下兩個變量有什麼區別?吸氣劑計算屬性與返回值的變量

var NUMBER_OF_ELEMENTS1: Int { 
    return sampleArray.count 
} 

var NUMBER_OF_ELEMENTS2: Int { 
    get { 
     return sampleArray.count 
    } 
} 
+0

爲什麼標題與身體不同? – rounak

+0

對不起,我的壞。更新它。 – Daniel

回答

5

的計算機屬性與getter和setter具有這種形式:

var computedProperty: Int { 
    get { 
     return something // Implementation can be something more complicated than this 
    } 
    set { 
     something = newValue // Implementation can be something more complicated than this 
    } 
} 

在某些情況下不需要二傳手,所以計算出的屬性被聲明爲:

var computedProperty: Int { 
    get { 
     return something // Implementation can be something more complicated than this 
    } 
} 

注意一個計算財產必須總是有一個吸氣 - 所以不可能只用一個setter聲明。

由於頻繁地發生計算性能有一個getter只,斯威夫特讓我們通過省略get塊,使得代碼更簡單簡化其實施寫,更易於閱讀:

var computedProperty: Int { 
    return something // Implementation can be something more complicated than this 
} 

語義上有什麼區別在兩個版本之間,所以無論你使用什麼,結果都是一樣的。

3

他們是相同的,因爲都定義了只讀屬性計算。但前者更可取,因爲它比後者更短,更易讀。