swift – 可选闭包,并检查它是否为nil

前端之家收集整理的这篇文章主要介绍了swift – 可选闭包,并检查它是否为nil前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
所以我想要的是一个类,可能会得到一个闭包传递给它在一个函数,它也可能在某些时候想忽略一个闭包。如何检查闭包变量是否设置和hwo可以删除它,当我完成它?

Cannot invoke ‘!=’ with an argument list of type ‘(@lvalue (sucsess:
Bool!,products: [AnyObject]!) -> ()?,NilLiteralConvertible)’ Type
‘(sucsess: Bool!,products: [AnyObject]!) -> ()?’ does not conform to
protocol ‘NilLiteralConvertible’

class someClass{
    //typealias completionHandlerClosureType = (sucsess:Bool!,items:[AnyObject]!)->()
    var completionHandler:(sucsess:Bool!,items:[AnyObject]!)->()?
    var hitpoints = 100
    var someset = ["oh no!","avenge me!"]
    init(){}

    func getHitFunc(impact:Int,passedCompletionsHandler:(sucsess:Bool!,items:[AnyObject]!)->()){
        completionHandler = passedCompletionsHandler
        hitpoints = hitpoints - impact
    }

    func checkIfDead{
        if hitpoints<=0 {               // The error received
            if completionHandler != nil{// Cannot invoke '!=' with an argument list of type 
                                        //'(@lvalue (sucsess: Bool!,NilLiteralConvertible)' 
                //run the handler if dead
                completionHandler(sucsess: true,items: someset)
                //do not run it again
                completionHandler = nil     //Type '(sucsess: Bool!,products: [AnyObject]!) -> ()?' does not conform to protocol 'NilLiteralConvertible'
            }
        }
        else{
            completionHandler = nil      //Type '(sucsess: Bool!,products: [AnyObject]!) -> ()?' does not conform to protocol 'NilLiteralConvertible'
        }
    }
}
你需要在括号中包装你的闭包签名,使闭包本身是可选的。现在写的方式,闭包返回一个可选的Void(这不是真的有意义)。
var completionHandler: ((sucsess:Bool!,items:[AnyObject]!)->())?

您的示例代码的一些样式点和修订版本:

// Capitalize class names so it's clear what's a class 
class SomeClass {
    // "success" has two "c"s
    var completionHandler: ((success:Bool!,items:[AnyObject]!)->())?
    var hitpoints = 100
    var someset = ["oh no!","avenge me!"]

    init() { }

    func getHitFunc(impact:Int,passedCompletionsHandler:(success:Bool!,items:[AnyObject]!)->()){
        completionHandler = passedCompletionsHandler
        hitpoints = hitpoints - impact
    }

    // You were missing the argument list here:
    func checkIfDead() {
        if hitpoints <= 0 {

            // Rather than checking to see if the completion handler exists,you can
            // just call it using optional Syntax like this:
            completionHandler?(success: true,items: someset)
        }
        completionHandler = nil
    }
}

猜你在找的Swift相关文章