gpt4 book ai didi

swift - 无法在 Swift 中初始化模型

转载 作者:行者123 更新时间:2023-11-30 13:35:34 28 4
gpt4 key购买 nike

我希望有一个由用户在主视图 Controller 中创建的数据模型,然后通过prepareForSegue传递到其他 View Controller 。

但是,在我的 View Controller 中,我无法使用该模型,并且由于未包装的可选值而出现错误。

我有:

Class Collection: NSObject {
var id: String!
var image: String!
var apples: Int?
var oranges: Int?
var lemons: Int?
}

init(id: String, image: String, apples: Int, oranges: Int, lemons: Int) {
super.init()
self.id = id
self.photo = photo
self.apples = apples
self.oranges = oranges
self.lemons = lemons
}

View Controller :

var collection: Collection!
...
// if user selects a number ..
self.collection.oranges = usersSelection
self.collection.apples = usersSelection
etc

谁能告诉我我做错了什么?谢谢!

最佳答案

像这样定义你的模型类:

class Collection: NSObject {
var id: String!
var image: String!
var apples: Int?
var oranges: Int?
var lemons: Int?

init(id: String, image: String, apples: Int?, oranges: Int?, lemons: Int?) {

super.init()
self.id = id
self.image = image

if let _ = apples{
self.apples = apples
}
if let _ = oranges{
self.oranges = oranges
}
if let _ = lemons{
self.lemons = lemons
}

}

}

然后在你的 ViewController 中实现如下:

    class ViewController: UIViewController {
var collection: Collection!

override func viewDidLoad() {
collection = Collection(id: "user selection", image: "useselection", apples: nil, oranges: nil, lemons: nil)
// collection.image =
// colection.oranges =
// ........

}
}

关于swift - 无法在 Swift 中初始化模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36112452/

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