masters3d
(Chéyo Jiménez)
1
Hi,
Is escaping part of the closure's type? Is so, how can I check if a closure is escaping vs nonescaping?
typealias CaptureClosure = () -> ()
func testEscaping (
nonEscapingByDefault:CaptureClosure, escapingByDefault:CaptureClosure?
) {
//NONESCAPING
print(type(of: nonEscapingByDefault)) // // How can I see if this is nonescaping?
//ESCAPING Optional Clousure
if let escapingByDefault = escapingByDefault {
let _ = Mirror(reflecting: escapingByDefault) // I know is escaping because no error here
print(type(of: escapingByDefault)) // How can I see if this is escaping?
}
// ESCAPING LOCAL Closure
let escapingLocalClosure:CaptureClosure = {}
let _ = Mirror(reflecting: escapingLocalClosure) // I know is escaping because no error here
print(type(of: escapingLocalClosure)) // How can I see if this is escaping?
// ESCAPING local func
func escapingLocalFunc() {}
let _ = Mirror(reflecting: escapingLocalFunc) // I know is escaping because no error here
print(type(of: escapingLocalFunc)) // How can I see if this is escaping?
}
testEscaping(nonEscapingByDefault: {}, escapingByDefault: {})
cukr
2
It is not. If it was part of the type, I would expect this code to work, but it doesn't:
func identity<T>(_ arg: T) -> T { arg }
func test(arg: () -> Void) {
identity(arg) // Converting non-escaping parameter 'arg' to generic parameter 'T' may allow it to escape
}
The simplest way is to attempt to escape it!
func escapingArgument<T, U>(_ arg: @escaping (T) -> U) { }
func testEscaping (
nonEscapingByDefault:CaptureClosure, escapingByDefault:CaptureClosure?
) {
escapingArgument(nonEscapingByDefault) // Passing non-escaping parameter 'nonEscapingByDefault' to function expecting an @escaping closure
escapingArgument(escapingByDefault!) // works
}
cukr
4
if escaping was part of the closure type, then T in identity function would become @nonescaping () -> () and there would be no problem with passing nonEscapingByDefault to it
identity function works with normal subtyping
class Closure {}
class EscapingClosure: Closure {}
func identity<T>(_ arg: T) -> T { arg }
func test(arg: Closure) {
identity(arg) // compiles without an error
}