Joseph Astrahan Joseph Astrahan - 1 year ago 190
Swift Question

Swift 2 to 3 Migration String.fromCString

I'm attempting to convert the following code from this library ( into Swift 3 Compatible code.

There are a multitude of errors regarding the

function that was previously available on the String in Swift 2

The error is roughly the same everywhere:

'fromCString' is unavailable: Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.

Seeing as I have 2 choices to choose from I'm not sure the correct one given the original authors intentions.

For example here is a snippet with the error.

extension JSON : CustomStringConvertible {
/// stringifies self.
/// if pretty:true it pretty prints
public func toString(pretty:Bool=false)->String {
switch _value {
case is NSError: return "\(_value)"
case is NSNull: return "null"
case let o as NSNumber:
switch String.fromCString(o.objCType)! {
case "c", "C":
return o.boolValue.description
case "q", "l", "i", "s":
return o.int64Value.description
case "Q", "L", "I", "S":
return o.uint64Value.description
switch o.doubleValue {
case 0.0/0.0: return "0.0/0.0" // NaN
case -1.0/0.0: return "-1.0/0.0" // -infinity
case +1.0/0.0: return "+1.0/0.0" // infinity
return o.doubleValue.description
case let o as NSString:
return o.debugDescription
let opts = pretty ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions()
if let data = (try?
withJSONObject: _value, options:opts)) as NSData? {
if let result = NSString(
data:data as Data, encoding:String.Encoding.utf8.rawValue
) as? String {
return result
public var description:String { return toString() }

Notice fromCString in the above code. What is the correct way to simulate the Swift 2 behavior correctly?

Answer Source

As error suggest use init(cString:) like this way.


Check Apple Documentation for more detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download