2

How can I use a Mutable Strongly Type array in Swift? I am adding ShoppingList object to an Array like this:

 func getAllShoppingLists() -> Array<ShoppingList> {

        let shoppingLists = Array<ShoppingList>()

        db.open()

        let results = try! db.executeQuery("SELECT * from ShoppingLists", values: nil)

        defer {

            db.close()
        }

        while(results.next()) {

            let shoppingList = ShoppingList()
            shoppingList.title = results.stringForColumn("title")

            shoppingLists.append(shoppingList)
        }

        return shoppingLists
    }

The problem comes that the shoppingLists is declared as "let". If I change to "var" it works fine. The reason of course is that I am changing the number of items in the array. Is this the best way?

3 Answers 3

2

You can create this code,

var shoppingArray = [ShoppingList]()
shoppingArray.append(yourInstance)
Sign up to request clarification or add additional context in comments.

Comments

1

That is the only way to make an array mutable, to understand the difference between let and var, see this post, as the answer explains it in detail.

What is the difference between `let` and `var` in swift?

Comments

-1

That's because let represents a constant.

You have to use var if you want to be able to change the shoppingLists content.

1 Comment

You're just repeating what the other answers already say.

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.