ios - swift : create two objects each of them inside another

标签 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()
}

如何解决这个问题,让我可以在另一个对象中调用每个对象?

最佳答案

您必须阅读 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)

以上的回答希望对您有所帮助!

关于ios - swift : create two objects each of them inside another,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50098798/

相关文章:

Javascript |对象、数组和函数

php - Laravel 中将对象转换为数组

ios - 按顺序排列的 NSMutableArray - 按顺序替换中断

ios - 如何使用 Multipack Texture Atlas 加载 CCSpriteBatchNode

iphone - iPhone应用程序中的tesseract OCR

javascript - 不可设置和不可写的属性仍然是可变的

java - Cucumber 特征文件 - 解析为对象

ios - 由于未捕获的异常 'FirebaseShutdown' 而终止应用程序,原因 : 'Firebase error

具有自定义元类行为的 Python 元类

c# - C# 中的 override 和 new 关键字有什么区别?