0

I have a method that init my class object from JSON. The method like this:

func getList (dic : Array<[String:AnyObject]>)  -> Array<Dog> {
    let dogs : NSMutableArray = NSMutableArray()
    for myDic in dic {
        let dog = Dog.init(dog: myDic)
        dogs.addObject(dog)
    }
    return NSArray(dogs) as! Array<Dog>
}

And I can present it on tableview without issue. But right now I want to make pagination for the list. If I run the method getList again it will be init new object and replacing my old one. How can I to add a new object to exisiting. I don't want to create separate object with the same property.

1
  • 1
    Just use Swift arrays, no need for Foundation collections anymore in Swift. Using an Array as input then using an NSMutableArray then converting to Array again makes no sense. Commented Nov 10, 2016 at 9:20

1 Answer 1

1

You need to add a member variable which you will append to. So:

var dogs: [Dog] = []

And then call getList like this:

dogs += getList(dic: myDic)

By the way, you can make your getList method much simpler, like this:

func getList(dic: [[String: AnyObject]]) -> [Dog] {
  return dic.map(Dog.init)
}
Sign up to request clarification or add additional context in comments.

2 Comments

Good answer. But probably AnyObject should become Any (in order to include String(s), Int(s) and other structs without the need of a manual casting)
AnyObject was defined in the original question. We do not know if the Dog initializer has a particular reason for requiring a dictionary of AnyObject types.

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.