Skip to content

Instantly share code, notes, and snippets.

@externvoid
Created December 17, 2015 12:59
Show Gist options
  • Select an option

  • Save externvoid/d87f51560b2cf6c0b7d3 to your computer and use it in GitHub Desktop.

Select an option

Save externvoid/d87f51560b2cf6c0b7d3 to your computer and use it in GitHub Desktop.
asとas!
asの用途
1. 乗り継ぎタイプへのキャスト、即値から参照値へ変換、Swiftで導入された構造体からFoundationで定義されたクラスへ変換。
string -> nsstring
array -> NSArray
dictionary -> nsdictionary
// Brigded type casting
let string = "3"
let nsString = string as NSString
let value = nsString.floatValue // 3
逆は、クラスのコンストラクタで可能。例:NSString(string: "Convertion")
2. 親クラスへキャスト
// Up casting
let button = UIButton()
let view = button as UIView
as!の用途
❌Optional -> raw value
let a:String? = "conversion"
let b = a! as String
//let b = a as! String error: downcast from 'String?' to 'String' only unwraps optionals; did you mean to use '!'?
String?からStringへのdowncastはOptionalsの剥ぎ取りだけをします。➡️Optionalsの剥ぎ取りは、forced unwrappingといって別の操作でおこないます。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment