2016-05-17 105 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") 

這絕對給你 - 這是個人喜好的問題。