cpimhoff
cpimhoff

Reputation: 675

Swift Types inside Parentheses

I was playing around with Swift today, and some strange types started to crop up:

let flip = Int(random()%2)  //or arc4random(), or rand(); whatever you prefer

If I type flip into Xcode 6 (Beta 2), the auto-complete pops up, and says flip is of type (Int) instead of Int.

This can easily be changed:

let flip : Int = Int(random()%2)
let flop = random()%2

Now flip and flop are of type Int instead of (Int)

Playing around with it more, these "parentheses types" are predictable and you can cause them by adding extra parentheses in any part of the variable's assignment.

let g = (5)      //becomes type (Int)

You can even cause additional parentheses in the type!

let h = ((5))    //becomes type ((Int))
let k = (((5)))  //becomes type (((Int)))
//etc.

So, my question is: What is the difference between these parentheses types such as (Int) and the type Int?

Upvotes: 4

Views: 3678

Answers (2)

newacct
newacct

Reputation: 122429

There is no difference, as far as I can tell. (Int) and Int are the same type; it can be written either way.

Upvotes: 3

matt
matt

Reputation: 534966

Partly it's that parentheses are meaningful.

let g = (5)

...means that g is to be a tuple consisting of one Int, symbolized (Int). It's a one-element version of (5,6), symbolized (Int,Int).

In general you need to be quite careful about parentheses in Swift; they can't just be used any old place. They have meaning.

However, it's also partly that the code completion mechanism is buggy. If you have a reproducible case, file a report with Apple.

Upvotes: 6

Related Questions