概念
Array
是Swift中的結(jié)構(gòu)體類型(struct
), 屬于是值類型
.
NSArray
是OC中的類型, 屬于引用類型
.
var aarr = ["happy", "every", "day"]
var barr : NSMutableArray = ["happy", "every", "day"]
//1
aarr[2] = "minute" //直接改變了aarr第二個元素的值
barr[2] = "minute" //讓barr第二個元素指向"minute"
print("1---\(aarr)")
print("1---\(barr)")
/*輸出:
1---["happy", "every", "minute"]
1---(
happy,
every,
minute
)
*/
//2
func changeA (var a:Array<String>) {
a[2] = "second" //a是對aarr的拷貝
}
func changeB (a : NSMutableArray) {
a[2] = "second" //a是對barr的引用
}
changeA(aarr) //值類型賦值時進行拷貝, 改變是a[2]的值, aarr并沒有影響
changeB(barr) //引用類型賦值時傳遞的是引用, a[2]和barr[2]都指向同一個地址.
print("2---\(aarr)")
print("2---\(barr)")
/*輸出:
2---["happy", "every", "minute"]
2---(
happy,
every,
second
)
*/
Array和NSArray之間相互轉(zhuǎn)換
Swift在數(shù)組方面Array很好的兼容了OC中的NSArray,可以直接進行賦值轉(zhuǎn)換.
(1) 可以直接聲明Array或者NSArray, 并進行遍歷
let swiftArray: Array<String> = ["10", "20","30","40","50"]
for element in swiftArray{
print(element)
}
let OCNSArray: NSArray = ["10", "20","30","40","50"]
for element in OCNSArray{
print(element)
}
(2)可以聲明一個NSArray數(shù)組拴清,轉(zhuǎn)化為Array數(shù)組靶病,再進行遍歷
let OCNSArray: NSArray = ["10", "20","30","40","50"]
let swiftArray:[String] = OCNSArray as! [String]
for index in swiftArray{
print(index)
}
(3)可以聲明一個Array數(shù)組,轉(zhuǎn)化為NSArray口予,再進行遍歷
let swiftArray: Array<String> = ["10", "20","30","40","50"]
let OCNSArray:NSArray = swiftArray
for index in OCNSArray{
print(index)
}