ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

【Swift】Optional型を理解したい

いまいちピンときていない。とりあえずログをメモ

let first: [String] = ["10", "20"]

// 足し算する
// でも当たり前だが、型が違うのでエラーになる
// main.swift:6:25: error: cannot convert value of type 'String' to expected argument type 'Int'
//let result1: Int = first[0] + first[1]

// キャストしてあげる
// しかしそれでもエラーとなる
// main.swift:12:20: error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
// main.swift:12:36: error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
//let result1: Int = Int(first[0]) + Int(first[1])

// 覗いてご覧
print(first[0]) // 10
print(Int(first[0])) // Optional(10) <- ?!!
// let first2: Int = Int(first[0]) // main.swift:17:19: error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
let first2: Int = Int(first[0])!  // 10
let first3: Int? = Int(first[0])  // Optional(10)
let first4: Int? = Int(first[0])! // Optional(10)

// ということは、アンラップしてあげればおk
let result1: Int = Int(first[0])! + Int(first[1])!
print(result1) // 30

// Intで足し算してOptional型へ
let result2: Int? = Int(first[0])! + Int(first[1])!
print(result2) // Optional(30)

どうやらIntは勝手にOptional型になるようです。(本当かな。。。?)

しかし、宣言の型は?を付与しないとOptional型にならないっぽい

【Swift】Swiftのswitch文エラー

// ths -> 1000, hnd -> 100, ten -> 10
// こんな感じのswitch文を用意した
var multiplication: Int
switch input {
  case "ths":
    multiplication = 1000
  case "hnd":
    multiplication = 100
  case "ten":
    multiplication = 10
} 

が、エラー発生

Main.swift:16:1: error: switch must be exhaustive, consider adding a default clause

どうやら、値のすべてを網羅しないとエラーとなるらしい。今回は「それら以外のもの」に対しての文がなかったのでdefaultを追加する

var multiplication: Int
switch input {
  case "ths":
    multiplication = 1000
  case "hnd":
    multiplication = 100
  case "ten":
    multiplication = 10
  default:
    multiplication = 0
} 

これでよし