- TOP>
- iOS Objective-C, Swift Tips>
- 文字列と数値の変換(Swift)
文字列と数値の変換(Swift)数値から文字列への変換はStringのイニシャライザを使うと可能である。
1 2 | let m1 = 99
print( "m1 = " + String(m1))
|
m1 = 99
文字列からInt、Doubleへの変換はそれぞれのイニシャライザを使うと可能である。ただし、変換対象の文字列に数値以外が含まれていたり、Intを実数値で初期化したりするとエラーになってしまう。
1 2 3 4 5 6 7 8 9 10 11 12 | if let n1 = Int( "99" ) {
print( "n1 = \(n1 + 1)" )
} else {
print( "変換に失敗しました。" )
}
if let n2 = Double( "99.9" ) {
print( "n2 = \(n2 + 0.1)" )
} else {
print( "変換に失敗しました。" )
}
|
n1 = 100
n2 = 100.0
NSStringであればintegerValue、doubleValueプロパティも利用できる。こちらは変換対象の文字列中に数値以外が含まれていても、可能な限り変換してくれる。
1 2 3 4 5 6 | let s1 = "99.9です。"
let n3 = (s1 as NSString).integerValue
print( "n3 = \(n3 + 1)" )
let n4 = (s1 as NSString).doubleValue
print( "n4 = \(n4 + 0.1)" )
|
n3 = 100
n4 = 100.0
(2015/01/28) () Swift 3.0対応。
Copyright© 2004-2019 モバイル開発系(K) All rights reserved.
|