LoginSignup
36
34

More than 5 years have passed since last update.

文字列と数値の相互変換

Last updated at Posted at 2015-01-03

Swiftに組み込まれているユーティリティだと何もできないに等しいので、諦めてCの関数(Darwinモジュール)やFoundationモジュールの関数を使うといいようです。

なお文字列化についてはsprintf的なものを pure Swiftで実装 もしてみたのですが、非常に遅いので素直にFoundationによるString拡張である String(format:arguments:) を使うのがよさそうです。

String -> Int

String#toInt():Int? だとInt32を、 Darwin.atoll() だとInt64に対応できます。ただし挙動が微妙に異なります。

また、Cの関数はエラーの通知をerrnoで行うため忘れがちだということに注意してください。

// swift playground
import Darwin
"123".toInt() // {Some 123}
atoll("123") // 123

// 大きすぎる値の場合
"10000000000000000000".toInt() // nil
atoll("10000000000000000000") // 9,223,... (黙ってオーバーフロー)

// 整数でない文字列
"foo".toInt() // nil
atoll("foo") // 0
errno == EINVAL // true (errnoでエラーを通知する)

// 整数から始まるが厳密な整数ではない文字列
"12.3".toInt() // nil
atoll("12.3") // 12

String -> Double

Darwin.atofが使えます。

import Darwin

atof("12.34") // 12.34
atof("1e2") // 100.0

Int -> String

10進法なら文字列の式展開が、16進法ならFoundationがString型に型拡張で追加するString(format:arguments:)が使えます。

import Foundation

let x = 0xcafe
"\(x)" // "51966"

String(format:"%08x", 0xcafe)  //   "0000cafe"
String(format:"%08X", 0xcafe)  //   "0000CAFE"
String(format:"%#08x", 0xcafe) // "0x0000cafe"

Double -> String

適当でよければ文字列の式展開が、精度などを細かく指定したいならString(format:arguments:)が使えます。

import Foundation

let x = 1.0

"\(x)" // "1.0"
String(format:"%.2f", x) // "1.00"
String(format:"%g", x)   // "1"
String(format:"%e", x)   // "1.000000e+00"
36
34
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
36
34