[英]swift Cannot convert value of type '[Liquor]' to expected argument type 'inout _'
I go through some similar questions but still cannot figure out why this happen. 我遇到了一些类似的问题,但仍然无法弄清楚为什么会发生这种情况。
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
}
the error messageis : Cannot convert value of type '[Liquor]' to expected argument type 'inout _' 错误消息是:无法将类型“ [Liquor]”的值转换为预期的参数类型“ inout _”
This is probably because the "year" may be nil, but I go through my code that it should work well, I try to fix it using "if let liquors = xxx", but then there will be a EXC_BAD_INSTRUCTION on the decode function, So I post all my code under here: 这可能是因为“年份”可能为零,但是我遍历了代码,认为它应该可以正常工作,我尝试使用“ if let liquors = xxx”来修复它,但是在解码函数上将有一个EXC_BAD_INSTRUCTION,所以我将所有代码发布在这里:
here is my liquor 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"
}
I use NSCoding to store data: 我使用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)
}
You're missing the unwrap operator. 您缺少解包运算符。 Try this:
尝试这个:
let liquor1 = Liquor(name: "Chateau Lafite Rothschild", year: "1993", photo: photo1, rating: 7)!
notice the "!" 注意“!” at the end
在末尾
The reason you need to unwrap is because Liquor init can return nil, so it returns an optional. 您需要解包的原因是因为Liquor init可以返回nil,因此它返回可选值。 Thats the ?
多数民众赞成在? at the end of init
在初始化结束时
required convenience init?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.