1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swiftの型変換まとめ

1
Last updated at Posted at 2025-12-25

1. 数値 ↔ 数値(Int / Double / Float)

Int → Double

let a: Int = 3
let b: Double = Double(a)      // 3.0

Double → Int(小数点切り捨て)

let x: Double = 3.9
let y: Int = Int(x)            // 3

四捨五入してIntにする

let x: Double = 3.5
let y = Int(x.rounded())       // 4

切り上げ / 切り下げ

let x: Double = 3.1
Int(x.rounded(.up))            // 4
Int(x.rounded(.down))          // 3

2. 文字列 → 数値(String → Int / Double)

文字列から数値への変換は失敗する可能性があるため、結果はOptionalになります。

String → Int

let s = "123"
let n = Int(s)                 // Int?  -> Optional(123)

変換に失敗する例

let s = "12a"
let n = Int(s)                 // nil

nilのときの値を決める(nilなら0)

let s = "12a"
let n = Int(s) ?? 0            // 0

guardで安全に取り出す

let s = "123"
guard let n = Int(s) else {
    print("数字ではない")
    return
}
print(n)

注意:小数を含む文字列はIntに変換できない

Int("...") は整数として読める文字列しか受け付けないため、 "3.5" のような小数を含む文字列は nil になります。

let s = "3.5"

let n = Int(s)         // nil
let d = Double(s)      // Double? -> Optional(3.5)
let n2 = Int(d ?? 0)   // 3(小数点は切り捨て)

3. 数値 → 文字列(Int / Double → String)

String(...) で変換する

let n = 42
let s = String(n)              // "42"

文字列補間を使う

let n = 42
let s = "\(n)"                 // "42"

Doubleの小数点桁を整える(例:小数2桁)

let x = 3.14159
let s = String(format: "%.2f", x)  // "3.14"

Swift 5.5+ の formatted を使う

let x = 3.14159
let s = x.formatted(.number.precision(.fractionLength(2))) // "3.14"

4. Bool ↔ String / Int

Bool → String

let flag = true
let s = String(flag)           // "true"

String → Bool

let s = "true"
let b = Bool(s)                // Bool? -> Optional(true)

UI表示用の文字列に変換する

let flag = true
let text = flag ? "ON" : "OFF"

Int ↔ Bool(直接変換はできない)

let n = 1
let b = (n != 0)               // true

let flag = true
let m = flag ? 1 : 0           // 1

5. Optionalの扱い(重要)

String → Int のようにOptionalが絡む変換が多いため、Optionalの取り出しが必要になります。

Optionalをそのまま表示すると "Optional(...)" になる

let n = Int("123")
print(n)                       // Optional(123)

取り出してから使う(if let)

if let n = Int("123") {
    print(n + 1)
}

nilのときの値を決める(??)

let n = Int("abc") ?? 0        // 0

6. as / as? / as!(型キャスト)

Int(...) のような値変換とは別に、as 系は型キャストです。Any やクラス階層、プロトコルでよく登場します。

as?(失敗したらnil)

let value: Any = "hello"
let s = value as? String       // String?

as!(失敗したらクラッシュ)

let value: Any = "hello"
let s = value as! String

7. よくあるミス

StringとIntをそのまま + しようとする

let a = "10"
let b = 20

print(a + b)                   // エラー
print(a + String(b))           // "1020"

Int? をそのまま計算に使おうとする

let n = Int("10")              // Int?

print(n + 1)                   // エラー
print((n ?? 0) + 1)            // 11

小数の文字列をIntにしようとして失敗する

let s = "10.5"
let n = Int(s)                 // nil

let d = Double(s)              // Double?
let m = Int(d ?? 0)            // 10

まとめ

ここまで読んでくださった皆さんありがとうございます。
最後に簡単なまとめを載せておきます。

  • 数値変換:Double(i), Int(d)
  • 文字→数値:Int(str) / Double(str) はOptional
  • 数値→文字:String(n) または "\(n)"
  • Optional解除:if let, guard let, ??
  • 型キャスト:as?(安全) / as!(危険)
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?