美文网首页
How Do I Declare a Closure in Sw

How Do I Declare a Closure in Sw

作者: tom__zhu | 来源:发表于2023-04-04 11:29 被阅读0次

    As a variable:

    var closureName: (ParameterTypes) -> ReturnType = { ... }

    As an optional variable:

    var closureName: ((ParameterTypes) -> ReturnType)?

    As a type alias:

    typealias ClosureType = (ParameterTypes) -> ReturnType

    As a constant:

    let closureName: ClosureType = { ... }

    As a parameter to another function:

    funcName(parameter: (ParameterTypes) -> ReturnType)

    Note: if the passed-in closure is going to outlive the scope of the method, e.g. if you are saving it to a property, it needs to be annotated with @escaping.

    As an argument to a function call:

    funcName({ (ParameterTypes) -> ReturnType in statements })

    As a function parameter:

    array.sorted(by: { (item1: Int, item2: Int) -> Bool in return item1 < item2 })

    As a function parameter with implied types:

    array.sorted(by: { (item1, item2) -> Bool in return item1 < item2 })

    As a function parameter with implied return type:

    array.sorted(by: { (item1, item2) in return item1 < item2 })

    As the last function parameter:

    array.sorted { (item1, item2) in return item1 < item2 }

    As the last parameter, using shorthand argument names:

    array.sorted { return $0 < $1 }

    As the last parameter, with an implied return value:

    array.sorted { $0 < $1 }

    As the last parameter, as a reference to an existing function:

    array.sorted(by: <)

    As a function parameter with explicit capture semantics:

    array.sorted(by: { [unowned self] (item1: Int, item2: Int) -> Bool in return item1 < item2 })

    As a function parameter with explicit capture semantics and inferred parameters / return type:

    array.sorted(by: { [unowned self] in return $0 < $1 })

    This site is not intended to be an exhaustive list of all possible uses of closures.

    Unable to access this site due to the profanity in the URL? http://goshdarnclosuresyntax.com is a more work-friendly mirror.

    相关文章

      网友评论

          本文标题:How Do I Declare a Closure in Sw

          本文链接:https://www.haomeiwen.com/subject/cgcsddtx.html