2016-05-17 271 views
1

在Swift中,下面是什么样的语法?让(你好,世界)的Swift语法:(字符串,字符串)=(“你好”,“世界”)

let (hello, world):(String,String) = ("hello","world") 
print(hello) //prints "hello" 
print(world) //prints "world" 

是它的简写:

let hello = "hello" 
let world = "world" 

如果它是一个缩写,所谓这个速记?这种类型的styntax是否有任何Swift文档?

+0

hm。那么我怎样才能打印出每个变种,就像它们被单独声明一样:print(hello)//打印“hello”print(world)//打印“world” –

+1

从文档:*你可以将一个元组的内容分解成单独的常量或变量,然后像往常一样访问:* – vadian

回答

2

正如@vadian所指出的那样,您正在做的是创建一个元组 - 然后立即将decomposing its contents分成不同的常量。

如果拆分的表达,你可以看到这是怎么回事更好:

// a tuple – note that you don't have to specify (String, String), just let Swift infer it 
let helloWorld = ("hello", "world") 

print(helloWorld.0) // "hello" 
print(helloWorld.1) // "world" 

// a tuple decomposition – hello is assigned helloWorld.0, world is assigned helloWorld.1 
let (hello, world) = helloWorld 

print(hello) // "hello" 
print(world) // "world" 

但是因为你在创建的元组立即分解元组的内容,它种违背了一个目的元组开始。我总是喜欢只写:

let hello = "hello" 
let world = "world" 

但如果你喜欢写:

let (hello, world) = ("hello", "world") 

这绝对给你 - 这是个人喜好的问题。