gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 22:16:52 26 4
gpt4 key购买 nike

我创建了 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/

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