2014-06-13 60 views
1

我有一些SWIFT代碼看起來像這樣:如何將字符串值分配給Swift中另一個類中的屬性?

class GeoRssItem 
{ 
    var title = "" 
    var description = "" 
} 

在另一類我宣佈的這一個變量爲:

var currentGeoRssItem : GeoRssItem? // The current item that we're processing 

我分配這個成員變量爲:

 self.currentGeoRssItem = GeoRssItem(); 

然後當我嘗試在self.currentGeoRssItem上分配一個屬性Xcode自動完成到這個:

 self.currentGeoRssItem.?.description = "test" 

隨後與生成錯誤失敗,像這樣:

"Expected member name following '.'" 

如何設置該屬性?我已閱讀文檔,但他們不是很有幫助。

回答

1

問號在錯誤的地方。應該是:

self.currentGeoRssItem?.description = "test" 

但是,您可能會收到:"Cannot assign to the result of this expression"。 在這種情況下,你需要檢查零這樣的:

if let geoRssItem = self.currentGeoRssItem? { 
    geoRssItem.description = "test" 
} 
+0

OK第二個代碼示例工作。 Yup; – Lee

+0

Yup; 「...您可以使用可選鏈接訪問可選值上的屬性,並檢查該屬性訪問是否成功。 *但是,您不能通過可選鏈接*來設置屬性的值。「 - Swift編程語言,」可選鏈接「。 –

0

如果要斷言值是非零,你可以這樣做:

self.currentGeoRssItem!.description = "test" 

如果你想聲明如果變量爲零,則爲空操作,則

self.currentGeoRssItem?.description = "test" 
+0

該!作品,但使用?導致錯誤「無法分配給此表達式的結果」 – Lee

相關問題