In Swift, there's a String initialiser that takes an UnsafePointer<Int8>
(or UnsafePointer<CChar>
which is the same I think) as an argument.
However, there's no initialiser that takes an optional UnsafePointer
, e.g. a pointer that's NULL
(or nil, speaking swifty), which can be extremely helpful when working with a C API.
I'd like to extend the String class to accept optional unsafe pointers.
This is what my extension looks like. Is that correct? Is this how one would implement that feature?
extension String {
init?(cString: UnsafePointer<Int8>?) {
guard let cString = cString else { return nil }
self = String(cString: cString)
}
}