Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@FuruyamaTakeshi

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

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
3
Help us understand the problem. What are the problem?