在Swift中,下面是哪种语法?
let (hello, world):(String,String) = ("hello","world")
print(hello) //prints "hello"
print(world) //prints "world"它是以下的简写吗:
let hello = "hello"
let world = "world"如果它是速记,那么这个速记叫什么?这种类型的styntax是否有任何Swift文档?
发布于 2016-05-17 15:07:20
正如@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")这完全取决于你--这是个人喜好的问题。
https://stackoverflow.com/questions/37266465
复制相似问题