kove
kove

Reputation: 61

create dynamic size array swift

I want to create an Array, if i make it like this it works:

var arrayEingabe = Array(count:30, repeatedValue:0)

If i make it like this it does not work:

var sizeArray = 30
var arrayEingabe = Array(count:sizeArray, repeatedValue:0)

At the end i want to change the size of my Array depending on what the user typed in.

I was searching the web for one hour now, but i could not find the answer.

Thanks for your help guys

Greets

Kove

Upvotes: 6

Views: 18555

Answers (2)

Vinod Supnekar
Vinod Supnekar

Reputation: 153

On Swift 3.0.2 :- Use Array initializer method give below:-

override init(){
let array = Array(repeating:-1, count:6)
}

Here, repeating :- a default value for Array. count :- array count.

Upvotes: 0

jwlaughton
jwlaughton

Reputation: 925

Actually both your examples compiled OK for me, but you should be more specific about types. Something like:

var arrayCount:Int = 30
var arrayEingabe = Array(count:arrayCount, repeatedValue:Int())

actually this might be better for you:

var arrayEingabe = [Int]()

This creates an empty array, and as mentioned in the comments Swift arrays are mutable. You can add, replace and delete members as you want.

Upvotes: 12

Related Questions