2016-03-20 13 views
0

ユーザーがメインView Controllerで作成し、prepareForSegue経由で他のView Controllerに渡したデータモデルが必要です。Swiftでモデルを初期化できません

しかし、私の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 

を誰も私が間違ってやっているものを私にしてください教えてください。 ありがとうございました!

+0

あなたは 'Collection'の初期化子を呼んでいましたか? – Sweeper

+0

View Controllerにはい。 var collection =コレクション(ID: ""、写真: ""、リンゴ:0、オレンジ:0、レモン:0) それは動作しますが、プロパティにアクセスしてドット表記で変更できません。 – Dazzle

+0

なぜ 'NSObject'サブクラスですか?あなたは構造体を使うことができます。 – Abizern

答えて

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

    } 
} 
+0

ありがとう。私はそれを試み、私は "Nilは引数型Intと互換性がありません"というエラーを取得します – Dazzle

+0

しかし、私はプレイグラウンドで私のコードをチェックして答えを投稿する前に。あなたのエラーを共有できますか? – iMuzahid

+0

私のエラーは、Nilが予想される引数型 "int"と互換性がないことです。 – Dazzle

関連する問題