Swift:在另一个内部创建两个对象

时间:2018-04-30 10:39:20

标签: ios oop object swift3 xcode8

我开发了一个iOS应用程序,它有两个对象,每个对象在另一个内部,如下所示: 第一个:

class OfferItem
 {
var _id : Int? = 0
var _OfferId : Int? = 0
var _ItemId : Int? = 0
var _Discount : Int? = 0
var _item = Item()
..
functions()
}

和第二个:

    class Item
    {

        var _id : Int! = 0
        var _RateCount : Int? = 0   
        var _Offer = OfferItem() 
         ..
    functions()
}

如何在我可以调用另一个对象的地方解决这个问题?

1 个答案:

答案 0 :(得分:1)

您必须阅读 Swift 中的参考资料。 Automatic Reference Counting link

以下是您的示例:

class OfferItem {
  var id: Int?
  var discount: Int?
  var item: Item!

  init(id: Int? = nil, discount: Int? = nil, itemId: Int, itemRateCount: Int) {
    self.id = id
    self.discount = discount
    self.item = Item(id: itemId, rateCount: itemRateCount, offer: self)
  }

}


class Item {
  var id = 0
  var rateCount = 0
  unowned var offer: OfferItem

  init(id: Int, rateCount: Int, offer: OfferItem) {
    self.id = id
    self.rateCount = rateCount
    self.offer = offer
  }
}


var offerItem = OfferItem(id: 10, discount: 2, itemId: 1, itemRateCount: 20)

print(offerItem.item.id, offerItem.item.offer.id)

结果: 1 可选(10)

我希望能帮助你解决上面的问题!