[swift-users] Can't initialise using a UTF8 string from within 'withUnsafeBufferPointer' expression

Karl razielim at gmail.com
Mon Jul 18 00:17:11 CDT 2016


As I understand it, we are supposed to use withUnsafe{Mutable/Buffer}Pointer or withExtendedLifetime to guarantee that objects we take pointers of will exist and won’t be optimised out by the compiler.

However, this leads to a problem when trying to initialise something which expects a UTF8 string using only the standard library (not Foundation’s equivalent cStringUsingEncoding):

> extension DispatchIO {
> 
> 	convenience init(type: DispatchIO.StreamType, path: String, oflag: Int32, mode: mode_t, queue: DispatchQueue, cleanupHandler: (error: Int32) -> Void) {
> 
> 		let utf8Path = path.nulTerminatedUTF8
> 		utf8Path.withUnsafeBufferPointer {
> 			self.init(type: type, path: UnsafePointer($0.baseAddress!), oflag: oflag, mode: mode, queue: queue, cleanupHandler: cleanupHandler)
> 		}
> 	}
> }

ERROR: Initializer delegation ('self.init') cannot be nested in another expression

I don’t really understand why that isn’t allowed for a non-capturing closure, but if we accept that, how do I actually use those pointer/extended lifetime functions to initialise things?

Thanks

Karl



More information about the swift-users mailing list