47
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[iOS8] Swiftで文字列と数値の型変換する方法

Last updated at Posted at 2014-12-05

Swiftで文字列と数値の相互変換する方法をサンプルコードを利用して説明します。
・数値 --> String
・String --> 数値

数値 --> String

let num  = -1.23
let str  = num.description // "-1.23"
String(num)でも文字列化はできますが、少数やマイナス値にはエラーになるため、descriptionを利用します。

その他、数値の型の変換は型名()で変換可能です。

let num = 123
float_t(num)   // 123.0
double_t(num)  // 123.0
 

String --> 数値

let str = "123"
let intFromStr   = str.toInt()! + 1  // 124
let intFromOpStr = str.toInt()       // Optional(123)

toString()に対して「!」を付けない場合は、optional型に変換されます。
 
47
38
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
47
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?