gpt4 book ai didi

xcode - Playground 和 Project 之间的差异

转载 作者:行者123 更新时间:2023-11-30 14:18:28 27 4
gpt4 key购买 nike

在回答另一个问题的过程中,我在 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com