Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 820
cpimhoff Avatar asked Jan 11 '23 08:01

cpimhoff


2 Answers

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.

like image 66
matt Avatar answered Jan 16 '23 21:01

matt


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

like image 26
newacct Avatar answered Jan 16 '23 20:01

newacct