在 Xcode Playground 中将 NSString 转换为 CString
Posted
技术标签:
【中文标题】在 Xcode Playground 中将 NSString 转换为 CString【英文标题】:Converting NSString to CString in Xcode Playground 【发布时间】:2014-06-05 18:52:44 【问题描述】:当我尝试时:
import Cocoa
var ns: NSString = "whatever"
var cs: CString = ns.UTF8String
println(cs)
在 Playground 中执行 var cs: CString = ns.UTF8String 语句时会报告此异常:
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...
但是,相同的代码在编译到应用中时会按预期工作。它看起来像一个 Playground 错误,但有人知道在 Playground 中将 NSString 转换为 Cstring 的解决方法吗?
【问题讨论】:
ns.cString() 怎么样? ns.cString() 导致同样的错误。 【参考方案1】:通过将 cs 设置为可选的 CString,我能够让它在操场上工作。
import Cocoa
var ns: NSString = "whatever"
println(ns)
var cs: CString? = ns.UTF8String
println(cs)
如果你需要解开可选的
if let str = cs
println(str)
【讨论】:
好答案!不幸的是,在我的实际用例中(将字符串传递给 glShaderSource),我需要一个非可选的 CString。当我添加“var cs2:CString = cs!”回到这个例子,我又回到了异常:( 我添加了一个片段,可以让你打开可选的以上是关于在 Xcode Playground 中将 NSString 转换为 CString的主要内容,如果未能解决你的问题,请参考以下文章
将 iPad Playground 转换为 Xcode 10 Playground
如何在 Xcode 11 Playground 中使用图像?