无法在Swift

时间:2016-03-20 10:10:16

标签: swift

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

然而,在我的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
}

查看控制器:

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

有人可以告诉我,我做错了吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

像这样定义你的模型类:

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 =
//      ........

    }
}