ios - swift 无法将类型 '[Liquor]' 的值转换为预期的参数类型 'inout _'

标签 ios swift casting nscoding

我经历了一些类似的问题,但仍然无法弄清楚为什么会这样。

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解码功能,所以我把我所有的代码都贴在这里:

这是我的酒类类(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 可以返回 nil,所以它返回一个可选的。那是?在初始化结束时

required convenience init?

关于ios - swift 无法将类型 '[Liquor]' 的值转换为预期的参数类型 'inout _',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40315487/

相关文章:

Swift 初始化规则困惑

c++ - reinterpret_cast< > 从一个结构到另一个

iphone - 带有三个按钮的 iOS 推送通知警报

ios - 在移动 Safari 上关闭软件键盘后,带有选项的 <select> 标签位置错误

ios - 我应该在哪里在iOS中加载数据库值

ios - Safari Web 检查器不显示重定向

ios - Xcode 7 iOS 应用程序无法在设备上运行

swift - 生成随机 Int64 + swift 3

java - 反序列化时如何找到对象所属的正确子类?

string - F# 中有用于将字符串解析为 int 的函数吗?