Reputation: 9257
When I attempt:
import Cocoa
var ns: NSString = "whatever"
var cs: CString = ns.UTF8String
println(cs)
in an Playground it reports this exception when executing the var cs: CString = ns.UTF8String statement:
fatal error: Can't unwrap Optional.None
Playground execution failed: error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
* thread #1: tid = 0xbf05a5, 0x000000010401b02d libswift_stdlib_core.dylib`Swift._StringCore._growBuffer (@inout Swift._StringCore)(Swift.Int, minElementWidth : Swift.Int) -> Swift.COpaquePointer + 813, queue = 'com.apple.main-thread', stop reason = EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
* frame #0: 0x000000010401b02d libswift_stdlib_core.dylib`Swift._StringCore._growBuffer (@inout Swift._StringCore)(Swift.Int, minElementWidth : Swift.Int) -> Swift.COpaquePointer + 813
frame #1: 0x000000010401643f libswift_stdlib_core.dylib`Swift._StringCore.append (@inout Swift._StringCore)(Swift._StringCore) -> () + 607
frame #2: 0x0000000104016fa5 libswift_stdlib_core.dylib`Swift.+ @infix (Swift.String, Swift.String) -> Swift.String + 117
...truncated...
However the same code works as expected when compiled into an app. It looks like a Playground bug but does anyone know a workaround to convert an NSString to Cstring in the Playground?
Upvotes: 1
Views: 1913
Reputation: 64684
I was able to get it to work in the playground by making cs a CString optional.
import Cocoa
var ns: NSString = "whatever"
println(ns)
var cs: CString? = ns.UTF8String
println(cs)
and if you need to unwrap the optional
if let str = cs{
println(str)
}
Upvotes: 1