0
1

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 3 years have passed since last update.

スイフト勉強_データ型変換

Posted at

前文に続いてデータの型変換について調べてみようと思う。

IntとDoubleの型変換

まず、Int と Double は共に演算されないため、二つのうち一つを変換しなければならない。
Int が自動的に Double に変換されないことである。

var intValue:Int = Int(123.45) // error
print(intValue)
var price:Int = 100
var totalPrice = Double(price) * 1.1  //
print(Int(totalPrice))

ここで見られるように変換するタイプを記載し、括弧を生成してその中に変換する変数を入れればよい。

数字を文字列に変換

文字+文字に文字ではない他の資料型を入れる場合、エラーが発生するため、型変換を行う必要がある。
やはりやり方の上のようだ。

var maskCount:Int = 100
var message:String = "mask " + String(maskCount) + " remains"	
print(message)

print("maks " + String(maskCount) +  " remains")	
print("maks \(maskCount)" + " remains")
print("maks \(maskCount) remains")

文字を数字で

やはり上記の通りだ。

但し、注意すべき点は、変換しようとする文字に数字以外の値が入るとエラーが発生する。

var str = "3.1"

var intOtherValue : Int = Int(str) //nil
var doubleValue : Double = Double(str) //3.1

var intValue : Int = NSString(string: str).integerValue //3
var floatValue : Float = NSString(string: str).floatValue //3.09999
var doubleValue : Double = NSString(string: str).doubleValue //3.1

is

isとasに区別され、isはインスタンスのタイプを確認(チェック)に使用する。
そしてas はインスタンスの型変換作業に用いられる。
isはBoolタイプをReturnし、指定されたインスタンスが特定のClassであるかを判別。

as, as!, as?

「as」は「as, as?, as!」の3つに使われるんですが、

as は上位に変換(Upcast)するときにのみ使用され、下位に変換(Downcast)するときは?あるいは!のように使用される。

as?は文字通り選択的で、Optional ValueをReturnする。 Downcastが可能でなければ、nilが返される。 したがって、Downcastが不確実ならばas?を選択した方が良い。 as?によって型変換されたインスタンスをそのまま出力するとOptional() Valueが表示されるのが分かる。

as!は強制的にDowncastする。 そのため、Downcast が成功でない場合エラーを起こす。 また、as! によってDowncast されたインスタンスを出力するとき、Optional 値が強制的にunwrap されたことが分かる。

Upcastの場合には「as, as!, as?」が全部使われますが、

Upcastが失敗した場合、as、as!はエラーが発生する反面、as?はnil値として処理される。

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?