2

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

1 Answer 1

1

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]
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

2) How ? selecting an item from dataStructure:[Any] will return an item of type Any , but it has not the method .count 3) nice suggestion :)
Yes, you are right about 2). Actually you need switch your mind from objective-c styled code. Swift is strictly typed language and obj-c manner will cause problems to you. I suggest you to conform all custom types to some protocol and work with this protocol.
never used obj :) i'll try to figure something :)
If answer helped you you can vote or even accept it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.