我经历了一些类似的问题,但仍然无法弄清楚为什么会发生这种情况。
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 _'
这可能是因为“年份”可能是零,但我通过我的代码它应该运行良好,我尝试使用“如果让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)
}
答案 0 :(得分:2)
您错过了解包操作员。试试这个:
let liquor1 = Liquor(name: "Chateau Lafite Rothschild", year: "1993", photo: photo1, rating: 7)!
注意"!"最后
你需要解包的原因是因为Liquor init可以返回nil,所以它返回一个可选项。多数民众赞成在?在init结束时
required convenience init?