xcode - Playground 和 Project 之间的差异

标签 xcode swift swift-playground

在回答另一个问题的过程中,我在 Playground 中遇到了一个奇怪的错误。我有以下代码来测试对象是否是 ArrayDictionarySet:

import Foundation

func isCollectionType(value : AnyObject) -> Bool {
    let object = value as! NSObject

    return object.isKindOfClass(NSArray)
        || object.isKindOfClass(NSDictionary)
        || object.isKindOfClass(NSSet)
}

var arrayOfInt = [1, 2, 3]
var dictionary = ["name": "john", "age": "30"]
var anInt      = 42
var aString    = "Hello world"

println(isCollectionType(arrayOfInt)) // true
println(isCollectionType(dictionary)) // true
println(isCollectionType(anInt))      // false
println(isCollectionType(aString))    // false

当我将代码放入 Swift 项目或从命令行运行它时,代码按预期工作。但是 Playground 不会编译并在向下转换为 NSObject 时给出以下错误:

Playground execution failed: Execution was interrupted, reason: EXC_BAD_ACCESS (code=2, address=0x7fb1d0f77fe8).
* thread #1: tid = 0x298023, 0x00007fb1d0f77fe8, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=2, address=0x7fb1d0f77fe8)
  * frame #0: 0x00007fb1d0f77fe8
    frame #1: 0x000000010ba46e12 libswiftCore.dylib`Swift._EmptyArrayStorage._withVerbatimBridgedUnsafeBuffer (Swift._EmptyArrayStorage)<A>((Swift.UnsafeBufferPointer<Swift.AnyObject>) -> A) -> Swift.Optional<A> + 50

在这三种情况下,构建平台都是 OS X。有谁知道如何让 Playground 一起玩吗?

Xcode 6.3.2。 swift 1.2。 OS X 10.10.3 优胜美地

最佳答案

并不是那个错误的真正原因(它看起来确实很奇怪)但是...... 您将需要使用可选链接,因为值可以是 AnyObject:

import Foundation

func isCollectionType(value : AnyObject) -> Bool {
    if let object = value as? NSObject {
        return object.isKindOfClass(NSArray)
            || object.isKindOfClass(NSDictionary)
            || object.isKindOfClass(NSSet)
        }
    return false
}

var arrayOfInt = [1, 2, 3]
var dictionary = ["name": "john", "age": "30"]
var anInt      = 42
var aString    = "Hello world"

isCollectionType(arrayOfInt)
isCollectionType(dictionary)
isCollectionType(anInt)
isCollectionType(aString)

Playground

还值得注意的是,NSArray 和 Array 是不同的东西:

  • NSArray 是一个不可变的类:

    @interface NSArray : NSObject <NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration>

  • 虽然数组是一个结构:

    struct Array<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer

考虑到这一点,isCollectionType(arrayOfInt) 返回 true 可能会令人惊讶 - 但发生了转换。

关于xcode - Playground 和 Project 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830713/

相关文章:

ios - 多个按钮使用唯一标识符连接到同一个 View Controller

ios - 使用 iOS/swift 对 OAuth2 和 Eventbrite 进行身份验证时出现 “Oops, something went wrong” 错误

ios - 使单元测试等待另一个方法中的异步调用

ios - 值没有出现在我的其余代码中

ios - Swift- 'For' 循环不向总结果添加变量

swift - 无法暗示 _Reflectable 协议(protocol)

ios - 如何将 NSAppTransportSecurity 添加到我的 info.plist 文件中?

ios - 查看 UICollectionViewCell 的调试?

ios - preferredStatusBarStyle 不工作

ios - 如何检查 Playground 的 swift 版本?