簡體   English   中英

swift無法將類型“ [Liquor]”的值轉換為預期的參數類型“ inout _”

[英]swift Cannot convert value of type '[Liquor]' to expected argument type 'inout _'

我遇到了一些類似的問題,但仍然無法弄清楚為什么會發生這種情況。

var liquors = [Liquor]()

func loadSampleLiquors(){
    let photo1 = UIImage(named: "Chateau Lafite Rothschild 1993")
    let liquor1 = Liquor(name: "Chateau Lafite Rothschild", year: "1993", photo: photo1, rating: 7)
    liquors += [liquor1] // Here is the error happen     
}

錯誤消息是:無法將類型“ [Liquor]”的值轉換為預期的參數類型“ inout _”

這可能是因為“年份”可能為零,但是我遍歷了代碼,認為它應該可以正常工作,我嘗試使用“ if let liquors = xxx”來修復它,但是在解碼函數上將有一個EXC_BAD_INSTRUCTION,所以我將所有代碼發布在這里:

這是我的酒課:

var name: String
var year: String
var photo: UIImage?
var rating: Int

struct PropertyKey {
    static let nameKey = "name"
    static let yearKey = "year"
    static let photoKey = "photo"
    static let ratingKey = "rating"
}

我使用NSCoding存儲數據:

func encode(with aCoder: NSCoder) {
    aCoder.encode(name, forKey: PropertyKey.nameKey)
    aCoder.encode(year, forKey: PropertyKey.yearKey)
    aCoder.encode(photo, forKey: PropertyKey.photoKey)
    aCoder.encode(rating, forKey: PropertyKey.ratingKey)
}

required convenience init?(coder aDecoder: NSCoder) {
    let name = aDecoder.decodeObject(forKey: PropertyKey.nameKey) as! String
    let year = aDecoder.decodeObject(forKey: PropertyKey.yearKey) as! String
    let photo = aDecoder.decodeObject(forKey: PropertyKey.photoKey) as? UIImage
    let rating = aDecoder.decodeInteger(forKey: PropertyKey.ratingKey)
    self.init(name: name, year:year, photo: photo, rating: rating)
}

您缺少解包運算符。 嘗試這個:

let liquor1 = Liquor(name: "Chateau Lafite Rothschild", year: "1993", photo: photo1, rating: 7)!

注意“!” 在末尾

您需要解包的原因是因為Liquor init可以返回nil,因此它返回可選值。 多數民眾贊成在? 在初始化結束時

required convenience init?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM