我开发了一个 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/