gpt4 book ai didi

swift - 如何在编码函数中修复此 if/let 语句?

转载 作者:行者123 更新时间:2023-11-28 07:46:40 25 4
gpt4 key购买 nike

class story: NSObject, NSCoding {

var label = UILabel()
var title = String()
var index = Int()
var cover = UIImage()
var frame = CGRect()

func encode(with aCoder: NSCoder) {
if let label = label { aCoder.encodeObject(label, forKey: "label") as! UILabel }
if let title = title { aCoder.encodeObject(title, forKey: "title") }
if let index = index { aCoder.encodeObject(index, forKey: "index") }
if let cover = cover { aCoder.encodeObject(cover, forKey: "cover") }
if let frame = frame { aCoder.encodeObject(frame, forKey: "frame") }
}

required convenience init?(coder aDecoder: NSCoder) {
self.init()
self.label = aDecoder.decodeObject(forKey: "label") as! UILabel
self.title = aDecoder.decodeObject(forKey: "title") as! String
self.index = aDecoder.decodeObject(forKey: "index") as! Int
self.cover = aDecoder.decodeObject(forKey: "cover") as! UIImage
self.frame = aDecoder.decodeObject(forKey: "frane") as! CGRect
}

func formatStorySize() {
let newWidth = self.frame.width * 0.8
let newHeight = self.frame.height * 0.9
let newX = self.frame.origin.x + newWidth / 2
let newY = self.frame.origin.y + newHeight / 2

self.frame = CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
}

func addLabel(text: String) -> UILabel {
let label = UILabel()
label.backgroundColor = UIColor.white
label.text = text
label.textAlignment = .center
let width = self.frame.width
let height: CGFloat = 40
let xPos = self.frame.origin.x
let yPos = self.frame.origin.y + self.frame.height - height
label.frame = CGRect(x: xPos, y: yPos, width: width, height: height)
self.title = label.text!
return(label)
}
}

有人告诉我,为了将一组自定义类实例保存到 UserDefaults,我必须添加编码函数和解码函数。但是,我收到错误:

Initializer for conditional binding must have Optional type, not 'UILabel'

在编码函数中的第一行之后,以及所有连续行之后的类似错误。我需要更改什么?

最佳答案

None 这些属性是可选的,因此您在 encode 方法中根本不需要 if let

func encode(with aCoder: NSCoder) {
aCoder.encode(label, forKey: "label")
aCoder.encode(title, forKey: "title")
aCoder.encode(index, forKey: "index")
aCoder.encode(cover, forKey: "cover")
aCoder.encode(frame, forKey: "frame")
}

解决该问题后,您不应使用 UserDefaults 来保存数据。将编码数据写入文件。

关于swift - 如何在编码函数中修复此 if/let 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50807531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com