Help us understand the problem. What is going on with this article?

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

More than 5 years have passed since last update.

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));
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした