Difference between Array and NSArray
Apr 28, 2022Array and NSArray are very similar and core constructs in iOS Development, and cause of this similarities we sometime forget how different this two construct works, these are some major difference that you must know about Array and NSArray.
Array
Array
is a struct which means it is value type in Swift.
var arr = ["Taylor", "Swift", "Taylor's", "Version"]
func modifyArr(a : Array<String>) {
a[2] = "Not Taylor's"
}
modifyArr(arr)
print(arr)
/* This prints - ["Taylor", "Swift", "Taylor's", "Version"]
The arr is not modified since array is a struct hence, the values are not modified outside the function.
*/
NSArray
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 = ["Taylor", "Swift", "Taylor's", "Version"]
func modifyArr(a : NSMutableArray) {
a[2] = "Not Taylor's"
}
modifyArr(arr)
print(arr)
/* This prints - ["Taylor", "Swift", "Not Taylor's", "Version"]
The arr is modified since NSMutableArray of reference type. Thus, the change in values are reflected outside the function.
*/
Conclusion
Array
is a Swift construct, and generic struct, which means that it can be an array of any specific type (Int, String, etc.) [T]
is syntactic sugar for Array<T>
.
NSArray
is an Objective-C construct that can hold any Objective-C object and is transparently mapped to and from Array<AnyObject>