2017-01-01 49 views
1

目前,我正在爲我的'Note'對象編寫'encode'(),以備序列化。我已經看了很多關於如何在Swift 3.0中進行序列化的教程以及這個錯誤消息,但都無濟於事。Swift 3'encode'產生'Void'(aka'()'),而不是預期的上下文結果類型XYZ?

此代碼從一個不相關的,以前的項目(從雨燕2.2至3.0的轉換),作品精絕:

//Serialise the object. 

    func encode(with aCoder: NSCoder) 
    { 
     aCoder.encodeCInt(personIDNumber, forKey: "personIDNumber") 
     aCoder.encode(staffName, forKey: "staffName") 
     aCoder.encode(userName, forKey: "userName") 
     aCoder.encode(age, forKey: "age") 
    } 

但是,如果我試圖做我的當前項目(同樣這是在開始雨燕3.0):

public func encode(with aCoder: NSCoder) 
{ 
    noteText = aCoder.encode(noteText, forKey: "noteText") 
} 

這是發生錯誤:

'encode' produces 'Void' (aka '()'), not the expected contextual result type String? ***Bizzarely, this also causes every 'encode' function that's available with NSCoder-type objects to be struck-through, as though deprecated, which obviously isn't true***. 

我 '解碼'()如下所示,編譯器是滿意的:

required public init (coder aDecoder: NSCoder) 
    { 
     noteText = aDecoder.decodeObject(forKey: "noteText") as! String? 
    } 

所以,我後是這樣的:

•一套關於如何解決這個錯誤(只是因爲我清楚的步驟對斯威夫特來說,這仍然是一個新的東西,並且我對這個信息絕對難過,對於追隨我的人也是如此)。

•這是爲什麼發生,爲什麼(如果可能的話)的說明,我的「解碼()」是兩個我給的情況下完全可以接受的,但「編碼()」

任何幫助非常感謝並提前感謝。

回答

0

noteText,類encode(with:)的屬性屬於(Note?),是一個給定類型的,說XYZ。的aCoderencode(, forKey:)方法(S)(NSCoder型的),但是,是一個(是)非返回函數with signatures looking like

func encode(_ realv: Double, 
    forKey key: String) 

注缺乏明確的返回類型這種方法。它確實是而不是返回類型爲XYZ的值(如您所期望的),並且當您嘗試將調用結果分配給屬性(noteText)時,您將得到預期的類型不匹配,因爲noteText不是類型Void(空元組,()),這是沒有指定返回類型的函數的默認返回值。

我不知道你想在這裏實現什麼,但你不能指定encode(_:forKey:)調用的任何形式的返還財產(除()類型的無用的屬性),因此刪除這個任務會趕走你的問題標題的錯誤信息。

// change this 
noteText = aCoder.encode(noteText, forKey: "noteText") 

// into 
aCoder.encode(noteText, forKey: "noteText") 
+0

非常感謝!在回答你的問題時,我想要做的是將此屬性作爲Note對象的一部分編碼爲二進制文件。在Swift 2.2中,據我所知,你可以做我最初做的事情。 – Paul

+0

@Paul樂意幫忙。 – dfri

相關問題