Swift Types inside Parentheses

China☆狼群 提交于 2019-12-23 17:04:19

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/24422108/swift-types-inside-parentheses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!