6

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

5
  • 4
    There's nothing wrong with the code you provided. Could you add more details explaining exactly what the problem is? Commented Dec 17, 2014 at 9:12
  • 1
    @kove: By default the size of the array is dynamic in Swift. If you want to use a fixed size array then the above properties (count, repeatedValue) can be set. The creation of dynamic sized array is simple, var arrayEingabe : [Int] Commented Dec 17, 2014 at 9:20
  • 1
    @Suresh I disagree with the fixed/dynamic array description. Array created with Array(count, repeatedValue) is still dynamic and can grow/shrink, it just has creates array with specific length and initial values (unless you mark it with let, of course). Commented Dec 17, 2014 at 9:27
  • Forgot to say that "If you declare with 'let'" :P , Apparently array variable is dynamic by default in Swift unless we specify it to be fixed. Agree? Commented Dec 17, 2014 at 9:30
  • It's exceptionally helpful on Stack Overflow if you never use words like "does not work". Instead, describe what you were expecting the code to do, and describe what it does that's different, including the exact text of any error messages. Commented Dec 17, 2014 at 11:15

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.