Swift blocks not working

前端 未结 2 1186
轻奢々
轻奢々 2020-12-29 14:58

I\'ve been trying to figure out how to use JavaScriptCore in swift. I\'m running into problems however when I have to deal with blocks as arguments, seems like the block is

2条回答
  •  没有蜡笔的小新
    2020-12-29 15:41

    It has something to do with how Swift implement closure. You need to use @convention(block) to annotate that the closure is ObjC block. Use unsafeBitCast to force cast it

    var block : @convention(block) (NSString!) -> Void = {
       (string : NSString!) -> Void in 
        println("test")
    }
    
    ctx.setObject(unsafeBitCast(block, AnyObject.self), forKeyedSubscript: "test")
    

    from REPL

    swift
    Welcome to Swift!  Type :help for assistance.
      1> import Foundation
      2> var block : @convention(block)(NSString!) -> Void = {(string : NSString!) -> Void in println("test")}
    block: @convention(block)(NSString!) -> Void =
      3> var obj: AnyObject = reinterpretCast(block) as AnyObject
    obj: __NSMallocBlock__ = {} // familiar block type
    

提交回复
热议问题