[swift-evolution] [stdlib] CString.swift initializers
Ben Rimmington
me at benrimmington.com
Thu Feb 25 11:45:22 CST 2016
The new initializers in "CString.swift" have a precondition:
> public init(cString: UnsafePointer<CChar>) {
> _precondition(cString != nil, "cString must not be nil")
> }
>
> public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
> _precondition(cString != nil, "cString must not be nil")
> }
<https://github.com/apple/swift/blob/swift-3-api-guidelines/stdlib/public/core/CString.swift>
The old `String.fromCString` function was convenient for wrapping inessential C function calls, if the `nil` coalescing operator can provide a fallback:
> let message =
> String.fromCString(sqlite3_errmsg(handle)) ??
> String.fromCString(sqlite3_errstr(result)) ?? ""
I also think the `validatingUTF8` argument label is misleading, because neither initializer allows ill-formed UTF-8 data to be copied.
If the precondition is removed, it should be possible to combine the initializers:
> /// Create a new `String` by copying the nul-terminated UTF-8 data
> /// referenced by a `cString`.
> ///
> /// Fails if the `cString` is `NULL`; or if it contains ill-formed code
> /// units and no repairing has been requested. Otherwise replaces
> /// ill-formed code units with replacement characters (U+FFFD).
> public init?(
> cString: UnsafePointer<CChar>,
> repairingInvalidCodeUnits isRepairing: Bool = true
> ) {
> guard let (result, _) = String.decodeCString(
> UnsafePointer(cString),
> as: UTF8.self,
> repairingInvalidCodeUnits: isRepairing) else {
> return nil
> }
> self = result
> }
-- Ben
More information about the swift-evolution
mailing list