2016-08-17 21 views
0

我正在學Swift並在操場上玩耍。我有以下的解釋:當我使用字典條目作爲變量打印字符串時,爲什麼會添加單詞「可選」?

​​

我使用下面的行打印輸出:

"Your first name is \(person["first"]) and you are \(person["age"]) years old." 

有了這個代碼,我得到以下輸出:

// -> "Your first name is Optional(John) and you are Optional(21) years old." 

我預期收到以下內容作爲輸出:

// -> "Your first name is John and you are 21 years old." 

可選來自哪裏?爲什麼這不是簡單地在指定的鍵上打印值?我需要做些什麼來解決這個問題?

+5

你應該真的閱讀的語言指南,其中涵蓋選項,字典,和其他語言的基礎知識我非常詳細。 – Alexander

+0

@AlexanderMomchliov我已經下載了它,但是我正在閱讀這個https://www.hackingwithswift.com/,以便快速瞭解語言並啓動語言指南。 –

+0

這已被反覆詢問和回答。只搜索'[swift]可選打印' –

回答

4

從字典中檢索給定鍵的值始終是可選的,因爲該鍵可能不存在,那麼值爲nil。使用字符串插值"\(...)"可選包含在文字字符串中。

爲了避免串插字面Optional(...)你必須拆開包裝在一個安全的方式首選自選

if let first = person["first"] as? String, age = person["age"] as? Int { 
    print("Your first name is \(first) and you are \(age) years old.") 
} 
+2

空合併運算符'??'在這裏也可以很方便,以便在屬性爲'nil'的情況下提供默認值。例如'print(「你的名字是\(person [」first「] ??」unknown「),而你是\(person [」age「] ??」未知數量「)歲。「)' –

+1

事實上,但在現實生活中,任何人都應該有一個名字和一個年齡(我知道這打破了使用可選綁定的建議);-) – vadian

+0

@ JesseAmano的解決方案也適用,但只有當」age「被保存爲'String',如果它保持爲'Int',則'Optional'仍然存在。 –

1

您的字符串尚未解包,並且是可選字段,因此您會看到可選字詞和括號。如果你想讓他們離開,你可以放一個!打開它。不過,我會建議以不同的方式處理,所以你不要試圖解開零值。

例如,

var person = [ 
"first": "John", 
"last": "Smith", 
"age": 21 
] 

print("Your first name is \(person["first"]) and you are \(person["age"]) years old.") 
// prints: "Your first name is Optional(John) and you are Optional(21) years old." 

print("Your first name is \(person["first"]!) and you are \(person["age"]!) years old.") 
// prints: "Your first name is John and you are 21 years old." 

let name = person["first"]! 
let age = person["age"]! 
print("Your first name is \(name) and you are \(age) years old.") 
// prints: "Your first name is John and you are 21 years old." 

Vadian有如何正確地打印出來作爲他的例子,如果你得到的東西是零不會崩潰一個很好的例子。

+0

會將該值存儲在一個變量中,然後使用該變量修復此問題? –

+0

否變量仍然需要解包 –

-1

儘量做到這樣

"Your first name is \(person["first"]!) and you are \(person["age"]!) years old." 

,然後嘗試看看在這裏的完美解釋Printing optional variable

相關問題