xcode - 在 Xcode Playground 中将 NSString 转换为 CString

标签 xcode nsstring swift swift-playground

当我尝试时:

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 的解决方法吗?

最佳答案

通过将 cs 设为 CString 可选,我能够让它在 Playground 上工作。

import Cocoa
var ns: NSString = "whatever"
println(ns)
var cs: CString? = ns.UTF8String
println(cs)

如果你需要打开可选的

if let str = cs{
println(str)
}

关于xcode - 在 Xcode Playground 中将 NSString 转换为 CString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24068017/

相关文章:

iphone - 在 NSString 中将 NSData 显示为二进制

swift - 在 Swift 中使用具有关联值的枚举是否违反里氏替换原则?

ios - 在用户点击它们之前在后台处理通知 - Swift 3

ios,在其他所有内容之前显示警报,通知用户我们需要 "some"权限

ios - 服务器收不到iOS发送的数据

ios - 如何使用 Xcode/Swift 创建横跨屏幕的横幅图像?

ios - Swift 3 tableView 不在 reloadData() 上更新

iPhone 构建问题 : MapKit/MKPolyline. h:没有这样的文件或目录

iphone - UISearchBar 取消按钮崩溃

ios - 将数学方程转换为字符串