【发布时间】:2016-10-29 02:31:22
【问题描述】:
我遇到了一些类似的问题,但仍然无法弄清楚为什么会发生这种情况。
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 _”
这可能是因为“年份”可能为零,但我检查了我的代码,它应该可以正常工作,我尝试使用“如果让酒 = xxx”来修复它,但随后会有一个 EXC_BAD_INSTRUCTION decode 函数,所以我把我所有的代码贴在这里:
这是我的酒类:
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)
}
【问题讨论】:
-
liquors的声明在哪里? -
@AlexanderMomchliov 我只是添加它
-
我要求声明
liquors,而不是liquor -
我的错,改变它@AlexanderMomchliov
-
顺便说一句,如果您只是存储静态常量,最好使用没有案例的枚举。
标签: ios swift casting nscoding