Search code examples
swiftswift-array

Create an Array of multiple Arrays in Swift


i have an object with some proprieties, arrays of classes or structs

I want to put those proprieties in an array so i can access them easily in TableDataSource ( because of section, indexpath etc.. )

I've tried writing this initialization

var dataStructure = Array<Any>()

    var tweet : Tweet?{
        didSet{
            dataStructure.removeAll()
            dataStructure.append(tweet?.media)
            dataStructure.append(tweet?.urls )
            dataStructure.append(tweet?.hashtags)
            dataStructure.append(tweet?.userMentions)


        }
    }

and then retrieving it

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    let arr = dataStructure[section] as? NSArray

    if arr != nil{
        println(arr!)
        return arr!.count
    }else{
        return 0
    }
}

but the arr is always nil

maybe is because i'm casting to NSArray? but i can't cast to "Array"

media , urls , hastags, and userMentions are initialized in the "Tweet" class

public var media = [MediaItem]()
public var hashtags = [IndexedKeyword]()
public var urls = [IndexedKeyword]()
public var userMentions = [IndexedKeyword]()

so they are pretty normal arrays


Solution

  • Basically there is a few problems with your code:

    1) didSet is not calling during init. This cause dataStructure array to be empty;

    2) Are you sure that you need cast to NSArray? You can get count without it.

    3) It's will be much better to use computed property in Tweet class to receive required data.

    public class Tweet {
        public var media = [MediaItem]()
        public var hashtags = [IndexedKeyword]()
        public var urls = [IndexedKeyword]()
        public var userMentions = [IndexedKeyword]()
    
        public var dataStructure:[Any] {
            return [media, hashtags, urls, userMentions]
        }
    }