Cast closures/blocks

前端 未结 4 1825
粉色の甜心
粉色の甜心 2020-12-05 15:35

In Objective-C, I often pass around blocks. I use them very often to implement patterns that help avoid storing stuff into instance variables, thus avoiding threading/timing

4条回答
  •  爱一瞬间的悲伤
    2020-12-05 15:44

    How about a generic Block parameterized with the function type?

    class Block {
      let f : T
      init (_ f: T) { self.f = f }
    }
    

    Allocate one of these; it will be a subtype of AnyObject and thus be assignable into dictionaries and arrays. This doesn't seem too onerous especially with the trailing closure syntax. In use:

      5> var b1 = Block<() -> ()> { print ("Blocked b1") }
    b1: Block<() -> ()> = {
      f = ...
    }
      6> b1.f()
    Blocked b1
    

    and another example where the Block type is inferred:

     11> var ar = [Block { (x:Int) in print ("Block: \(x)") }]
    ar: [Block<(Int) -> ()>] = 1 value {
      [0] = {
        f = ...
      }
    }
     12> ar[0].f(111)
    Block: 111
    

提交回复
热议问题