Create an optional block as a variable

前端 未结 2 975
臣服心动
臣服心动 2021-01-17 16:35

I have a simple class where I declare a block as a variable:

class MyObject : NSObject 
{
    var progressBlock:(progress:Double) -> ()?

    init() { }
}         


        
相关标签:
2条回答
  • 2021-01-17 17:03

    The way you have written it, the compiler assumes progressBlock is a closure that returns an optional empty tuple instead of an optional closure that returns an empty tuple. Try writing it like this instead:

    class MyObject:NSObject {
        var progressBlock:((progress:Double) -> ())?
        init() {
            progressBlock = nil
            progressBlock = { (Double) -> () in /* code */ }
        }
    }
    
    0 讨论(0)
  • 2021-01-17 17:11

    Adding to connor's reply. An optional block can be written as:

    var block : (() -> ())? = nil
    

    Or as an explicit Optional:

    var block : Optional<() -> ()> = nil
    

    Or better yet, with a custom type

    typealias BlockType = () -> ()
    
    var block : BlockType? = nil
    
    0 讨论(0)
提交回复
热议问题