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 _'

这可能是因为 "year" 可能为零,但我仔细检查了我的代码,认为它应该可以正常工作,我尝试使用 "if let liquors = xxx" 修复它,但随后会出现 EXC_BAD_INSTRUCTION 关于解码函数,所以我 post 我所有的代码都在这里:

这是我的酒class:

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 可以 return nil,所以它 return 是一个可选的。那是?在初始化结束时

required convenience init?