游乐场与项目之间的差异

时间:2015-06-14 14:46:25

标签: xcode swift swift-playground

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

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 Yosemite

1 个答案:

答案 0 :(得分:0)

不是那个错误的原因(看起来确实很奇怪)但...... 您将需要使用可选链接,因为值可以是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>

  • 虽然Array是一个结构:

    struct Array<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer

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