CoreLocation関連で結構困ったのでまとめておく。
といっても内容としては大した話ではない。
How to convert NSNumber to Uint16
let hoge: Int16 = 78
let num = NSNumber(short: hoge)
let uint_num = UInt16(bitPattern: num.shortValue)
結論だけ言うと、上記のようにすればNSNumber
をUInt16
に変換できる。
背景
CLBeaconRegion
のinit()
において、引数major
、minor
の型CLBeaconMajorValue
、CLBeaconMinorValue
基底型はUInt16
である。
CLBeaconRegion Initializer
init(proximityUUID proximityUUID: NSUUID,
major major: CLBeaconMajorValue,
minor minor: CLBeaconMinorValue,
identifier identifier: String)
しかし、CLBeaconRegion
、CLBeacon
のメンバー変数major
、minor
を取り出してみると、その型はNSNumber?
である。
Declaration
var major: NSNumber { get }
例えばlocationManager(_:didRangeBeacons:inRegion:)
なんかで受け取ったinRegion
からmajor
やminor
なんかを取り出して、改めてCLBeaconRegion
としてなんかしようと思った時に、大変苦労した覚えがある。
cast
しようとしてみたり、辞書型を使って解決しようと試みたが失敗に終わり、上記のような変換に至った。
一般的な情報科学の常識に則って考えると、上記はとても簡潔でわかりやすい変換なのだが、そういうのをすぽーんと忘れて小手先だけで言語を扱うと痛い目に遭う。
そういうお話。