arrays - Swift 数组标识 "Type does not conform to protocol ' AnyObject'"错误

标签 arrays swift identity swift-playground

我创建了 Playground 并编写了这段代码:

var a = [1, 2, 3]
var b = a

a === b

Playground 给我错误 Type '[Int]' does not conform to protocol 'AnyObject'

我做错了什么?

我正在使用 XCode 6 GM Seed。

更新

此代码摘自“The Swift Programming Language”一书,其中指出:

“Check whether two arrays or subarrays share the same storage and elements by comparing them with the identity operators (=== and !==).”

在“类和结构”一章中。

更新 2 摘录自早期 Swift 规范的旧版书籍。我下载了新的,没有这个字。因此身份运算符只能应用于类实例。

最佳答案

根据The Swift Programming Language:

”Identical to” [represented by three equals signs, or ===] means that two constants or variables of class type refer to exactly the same class instance.

在 Swift 中,数组是结构体。因此,您不能尝试使用 === 将一个数组与另一个数组进行比较。否则,以下代码 - 使用 NSArray - 工作正常并且不会在 Playground 中给出任何错误消息:

var a = [1, 2, 3] as NSArray //NSArray is not a Struct
var b = a
a === b //true

The Swift Programming Language 给出了对此的解释:

Structure instances are always passed by value, and  class instances are always passed by reference.

当然,Identical to (===) 与 Equal to (==) 的目标不同,它可以帮助您检查两个实例是否被视为“值(value)相等”或“等价”。例如,以下代码将在 Playground 中编译而不会出现任何错误消息:

var a = [1, 2, 3]
var b = a
a == b //true

关于arrays - Swift 数组标识 "Type does not conform to protocol ' AnyObject'"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25787045/

相关文章:

authentication - 如何在 Blazor WebAssembly 中实现 OIDC 身份验证?

Java,对构成有向图的节点 ArrayList 执行深拷贝

java - 给定一个字符串如何将其转换为数组 : Java

ios - 将约束设置为以编程方式完成的 arc UIBezierPath

swift 3 : how to check if cookies for particular URL are configured?

oauth-2.0 - Apache Syncope 与 OAuth 2

c# - 我可以使用 GetHashCode 跟踪对象标识吗?

sql - 使用 hql 将列从列表转换为数组,以及将数组转换为 hive 中的列表

Java - 将返回 boolean 值和索引的 int 数组

ios - 无法在名称处存储类型为 _SwiftValue 的对象。只能存储 NSNumber、NSString、NSDictionary 和 NSArray 类型的对象。