Home > Net >  Swift data missing in optional array
Swift data missing in optional array

Time:12-30

I'm totally confused about this. I append data to an optional array, but it's just gone. Here's the code to explain further:

Where the problem:

private func toObject(from data: GetOldDistrSrvMenuQuery.Data.GetOldDistrSrvMenu) -> GetOldDistrSrvMenu {
    let obj = GetOldDistrSrvMenu()
    obj.title = data.title
    obj.subtitle = data.subtitle
    obj.buttonText = data.buttonText
    obj.buttonShow = data.buttonShow ?? false
    obj.buttonUrl = data.buttonUrl
    
    if let items = data.items {
        for item in items {
            if let item = item {
                let aa = toDataObject(from: item)
                obj.items?.append(aa)
                
                print("Debug1: \(aa.name)") // data exist as expected
                print("Debug2: \(obj.items)") // nil in obj, why?
            }
        }
    }
    
    return obj
}

the toDataObject function:

private func toDataObject(from data: GetOldDistrSrvMenuQuery.Data.GetOldDistrSrvMenu.Item) -> GetOldDistrSrvMenuItem {
    let obj = GetOldDistrSrvMenuItem()
    obj.sourceUrl = data.sourceUrl
    obj.thumbnailUrl = data.thumbnailUrl
    obj.name = data.name
    
    return obj
}

GetOldDistrSrvMenu object:

class GetOldDistrSrvMenu: Object {
   @objc dynamic var _id: String = UUID().uuidString
   @objc dynamic var title: String?
   @objc dynamic var subtitle: String?
   @objc dynamic var buttonText: String?
   @objc dynamic var buttonShow: Bool = false
   @objc dynamic var buttonUrl: String?
   var items: [GetOldDistrSrvMenuItem]?

   override class func primaryKey() -> String? {
      return "_id"
   }
}

class GetOldDistrSrvMenuItem: Object {
   @objc dynamic var thumbnailUrl: String?
   @objc dynamic var name: String?
   @objc dynamic var sourceUrl: String?
}

Why is it missing in the obj array? I'm totally confused and don't know what's wrong.

CodePudding user response:

You are not initializing the array.

An optional array means it's a nil. Calling append (or any function) on a nil will not do anything.

You have to initialize the array to an empty array at some point.

obj.items = []


I highly recommend against using optional arrays, rather always default to a non-optional empty array.

There is very few situations where there's a difference between [] and nil array.

You can just do var items: [GetOldDistrSrvMenuItem] = []

  • Related