27

I have an array:

let individualScores = [75, 43, 103, 87, 12]

And I iterate like this:

for score in individualScores {

}

However, is there a way to declare the object type explicitly? I think it would come in handy later w/ custom objects, or other reasons. Something like:

for Integer score in individualScores {

}

4 Answers 4

49

When you type a variable, you do:

var score: Int

And you do the same in a loop:

for score: Int in individualScores {

}

It seems to be pretty consistent in that regard.

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

5 Comments

Anybody else getting a segfault 11 from the compiler when doing this in Swift 2.0? I find I have to cast it myself in a subsequent line...
@elsurudo A segfault in a compiler is a compiler bug (probably a "we haven't yet implemented parsing this syntax" bug).
Yeah for sure. I've been finding a bunch of these, although slightly less with the latest Xcode GM. If I wasn't so lazy and had the time I'd file some radars, but alas...
@elsurudo Yep same segfault 11 here when I do this iteration... What the hell Swift :(
Simple types (like Int) work but anything more complex segfaults the compiler in Xcode 7.0
5

yes its possible

let individualScores:Int[] = [75, 43, 103, 87, 12]

for score:Int in individualScores {

}

1 Comment

At some point, Swift must have changed because a tutorial had me doing let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20] but your example fixed my error when I used let possibleTipsExplicit:Double[] = [0.15, 0.18, 0.20]. Even the example on Apple's own site is the incorrect version.
2

Yes. You can explicitly specify the type if you wish.

let individualScores = [75, 43, 103, 87, 12]

for score: Int in individualScores {
    println(score)
}

Comments

1

Explicit type declarations follow an identifier declaration with a colon.

for score: Int in individualScores {
    // ...
}

let π: Double = 3.1415926535897932
var x: Int = 10

You can read it "x is an Int". See A Swift Tour.

The loop variable (score) is explicitly and strongly typed whether you declare the type or not — it comes from the type of the array you're iterating through. Swift knows individualScores is an Int[], short for an Array<Int> because you declared it with integer literals. See Generics for more about how that works.

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.