実現したいこと
ここに実現したいことを箇条書きで書いてください。
- Swiftのリファレンスにあるオプショナルバインディングの短い書き方を理解したい。
前提
ここに質問の内容を詳しく書いてください。
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/thebasics#Optional-Binding
を見ながらswiftを学習しているのですが、ドキュメントに書いてあるコードがエラーになってしまい、何が原因なのかわからないので、質問します。
Swift
1let myNumber = Int(possibleNumber) 2// Here, myNumber is an optional integer 3if let myNumber = myNumber { 4 // Here, myNumber is a non-optional integer 5 print("My number is \(myNumber)") 6} 7// Prints "My number is 123"
This code starts by checking whether myNumber contains a value, just like the code in the previous example.
このコードは前の例と同じように、myNumberに値があるかどうかをチェックすることから始まってます。
If myNumber has a value, the value of a new constant named myNumber is set to that value.
もし、myNumberに値があれば、myNumberと名付けられた新しい定数の値はその値にセットされます。
Inside the body of the if statement, writing myNumber refers to that new non-optional constant.
if文のbodyの中で、myNumberを書くことでその新しい非オプショナルの定数を参照します。
Before the beginning of the if statement and after its end, writing myNumber refers to the optional integer constant.
myNumberを書くことで、if文の始まる前と、終わったあとでその定数のオプショナルな整数を参照します。
Because this kind of code is so common, you can use a shorter spelling to unwrap an optional value:
このようなコードはよく使われるので、オプショナル値をアンラップするためのコードをもう少し短くできます。
write just the name of the constant or variable that you’re unwrapping.
アンラップする定数名または変数名を書くだけです。
The new, unwrapped constant or variable implicitly uses the same name as the optional value.
新しい、アンラップされた定数または変数は黙ってオプショナル値と同じ名前を使います。
Swift
1if let myNumber { 2 print("My number is \(myNumber)") 3} 4// Prints "My number is 123"
とありますが、このように書いて試してみるとエラーになってしまいます。
発生している問題・エラーメッセージ
エラーメッセージ Variable binding in a condition requires an initializer.
該当のソースコード
swift
1let possibleNumber = "123" 2let myNumber = Int(possibleNumber) 3if let myNumber = myNumber { 4 print("My number is \(myNumber)") 5} 6 7if let myNumber { 8 print("My number is \(myNumber)") 9} 10
試したこと
上記のコードを書いてみて、3行目のはちゃんとアンラップされるのを確認しましたが、7行目のはバインディングの条件にはイニシャライザが必要だと言われます。
補足情報(FW/ツールのバージョンなど)
Playgrounds Version 4.0 (1567.22)
回答1件
あなたの回答
tips
プレビュー