Search code examples
iosoopobjectswift3xcode8

Swift: create two objects each of them inside another


I developed an iOS app which have two objects, each of one inside another, as below: first one:

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

and 2nd one:

    class Item
    {

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

How to resolve that in such away where I can call each object in another?


Solution

  • You must read about references in Swift. Automatic Reference Counting link

    Here is your example:

    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)
    

    Result: 1 Optional(10)

    I hope to help you with my answer above!