括号内的 Swift 类型 [英] Swift Types inside Parentheses

查看:23
本文介绍了括号内的 Swift 类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在玩 Swift,一些奇怪的类型开始出现:

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

如果我在 Xcode 6 (Beta 2) 中输入 flip,自动完成会弹出,并说 flip 的类型是 (Int) 而不是 Int.

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

这很容易改变:

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

现在触发器和触发器的类型是 Int 而不是 (Int)

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.

那么,我的问题是:这些括号类型(例如 (Int)Int 类型之间有什么区别?>

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

推荐答案

部分原因在于括号是有意义的.

Partly it's that parentheses are meaningful.

let g = (5)

...意味着 g 将成为 元组 由一个 Int 组成,符号化 (Int).它是 (5,6) 的单元素版本,符号为 (Int,Int).

...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).

一般来说,你需要非常小心 Swift 中的括号;它们不能只是用于任何旧地方.它们是有意义的.

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

然而,部分原因是代码完成机制存在缺陷.如果您有可重现的案例,请向 Apple 提交报告.

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

这篇关于括号内的 Swift 类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆