By default in Swift, parameters with function type (such as
delegate) are "non-escaping," which means that they aren't permitted to be used outside the body of the function itself. This is useful because it allows you to make assumptions like "this method won't retain a reference to the closure I pass it, so I won't accidentally create a reference cycle."
However, the compiler only really performs this analysis for function types. This means that other types are assumed to always be escaping—you are free to store class references however you like, copy value types around, etc. The signature of
withUnsafePointer(to:_:) looks like this:
func withUnsafePointer<T, Result>(to value: T, _ body: (UnsafePointer<T>) throws -> Result) rethrows -> Result
value parameter has type
T, and not a function type, the compiler must assume that within the body of
value parameter may escape. This means it's invalid to pass an escaping closure as the argument for the
There are two workarounds here. One is to make the
delegate parameter to
myOtherFunc escaping, which would allow you to use it in potentially-escaping contexts within the body of
myOtherFunc. The other is to make use of the
withoutActuallyEscaping(_:do:) function, which allows a non-escaping closure to be used in escaping contexts (as long as the closure doesn't actually escape in practice).
From what you have here, it looks like
withoutActuallyEscaping(_:do:) would be acceptable (since the pointer in
withUnsafePointer is never supposed to escape the body of the closure anyway), but depending on what you expect
myOtherFunc in the future you will have to be careful that
delegate never escapes.