Swift超初心者がひとまず10分勉強した。
オプショナルの入り口の備忘録。
ちょっとずつ付け足すつもり。
*.swift
// nilを取り扱えない通常の変数を宣言
var suji_A: Int8 = 10
var moji_A: String = "moji_A"
// nilを取り扱えるオプショナル変数を宣言
var suji_B: Int8? = nil
var moji_B: String? = nil
// 型名をデバッグ表示
print(type(of: suji_A)) // => Int8
print(type(of: moji_A)) // => String
print(type(of: suji_B)) // => Optional<Int8>
print(type(of: moji_B)) // => Optional<String>
//print( suji_A + suji_B )
// => Error : Value of optional type 'Int8?' must be unwrapped to a value of type 'Int8'
//print( moji_A + moji_B )
// => Error : Value of optional type 'String?' must be unwrapped to a value of type 'String'
// アンラップ
// nilなので実行時エラー
//print( suji_A + suji_B! )
/* 実行時エラー
error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
*/
// => Fatal error: Unexpectedly found nil while unwrapping an Optional value
// nilを解消
suji_B = 20
moji_B = "moji_B"
//print( suji_A + suji_B )
// => Error : Value of optional type 'Int8?' must be unwrapped to a value of type 'Int8'
//print( moji_A + moji_B )
// => Error : Value of optional type 'String?' must be unwrapped to a value of type 'String'
// アンラップ
print( suji_A + suji_B! ) // => 30
print( moji_A + moji_B! ) // => moji_Amoji_B
/////////////////////////////////////////////////////////////////////////////////
// おまけ(マークアップコメント)
// マークダウン形式でコメントをつけることができる。
// 表示の切り替えは、
// [Editor] - [Show Raw Markup]
/*:
- - -
# 設計文書(クラス設計)
## マークアップコメント
1. Step1
1. Step2
1. Step3
* 箇条書き1
* 箇条書き2
* 箇条書き2
## 参考記事
[XcodeでSwiftの型を把握する](https://qiita.com/bannzai/items/bc6e286dc590e30d3714)
[どこよりも分かりやすいSwiftの"?"と"!"](https://qiita.com/maiki055/items/b24378a3707bd35a31a8)
*/
/////////////////////////////////////////////////////////////////////////////////