我经历了一些类似的问题,但仍然无法弄清楚为什么会这样。
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/