2
3

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.

Swiftでobjc_setAssociatedObjectのパラメータにclosureを使う時

Last updated at Posted at 2015-05-02

#Swiftでruntimeのobjc_setAssociatedObject()のパラメータにclosureを使う時
runtimeのパラメータにclosureを設定する時の方法を記す。

何故ビルドエラーになるのか?

SwiftではclosureがAnyObjectでないため。一方objc_setAssociatedObjectは第一引数にAnyObject型を要求する。ゆえに設定するとビルドエラーとなり設定できない。

static char const * const Tag = "Tag";

- (void)hoge
{
    Block block = ^(BOOL isConnected) {
      is (isConnected) {
        NSLog(@"connected")
      } else {
        NSLog(@"not connected")
      }
    };
    objc_setAssociatedObject(block, Tag, @1, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

対応方法

Swiftに於いて、ジェネリクスをもつBlockクラスを設け、そのプロパティとしてclosureを設定する。
そして、closureをfを設ける(詳細下記)。

class Block<T> {
    let f : T
    init (_ f: T) { self.f = f }
}
typealias Block = Bool -> Void

let block: Block = { isConnected -> Void in
    if isConnected {
        println("connected")
    } else {
        println("not connected")
    }
    block(portConnected)
 }
var closure = Block(block)
var tag = "Tag"
var hoge = "hoge"
objc_setAssociatedObject(closure, &tag, hoge, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC));
2
3
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
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?