在 Swift 中:Array VS NSArray VS [AnyObject] 之间的区别 [英] in Swift: Difference between Array VS NSArray VS [AnyObject]
问题描述
正如标题所说,Array vs NSArray vs [AnyObject] 有什么区别?
As the title says, what's the difference between Array vs NSArray vs [AnyObject]?
此外,最推荐的处理方法是什么.我的意思是推荐的是,什么是最简单的实现.谢谢.
Also, what is most recommended way of approaching this. What i mean recommended is, what's the easiest implementation. Thank you.
推荐答案
Array
是一个 struct,因此它是一个值类型迅速.NSArray
是一个不可变的 Objective C 类,因此它是 Swift 中的引用类型,并且它被桥接到 Array
NSMutableArray
是 NSArray
的可变子类.
Array
is a struct, therefore it is a value type in Swift.
NSArray
is an immutable Objective C class, therefore it is a reference type in Swift and it is bridged to Array<AnyObject>
.
NSMutableArray
is the mutable subclass of NSArray
.
var arr : NSMutableArray = ["Pencil", "Eraser", "Notebook"]
var barr = ["Pencil", "Eraser", "Notebook"]
func foo (var a : Array<String>)
{
a[2] = "Pen"
}
func bar (a : NSMutableArray)
{
a[2] = "Pen"
}
foo(barr)
bar(arr)
println (arr)
println (barr)
打印:
(
Pencil,
Eraser,
Pen
)
[Pencil, Eraser, Notebook]
因为foo
改变了a
的本地值,而bar
改变了引用.如果你像其他引用类型一样使用 let arr
而不是 var
,它也可以工作.
Because foo
changes the local value of a
and bar
changes the reference.
It will also work if you do let arr
instead of var
as with other reference types.
这篇关于在 Swift 中:Array VS NSArray VS [AnyObject] 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!