public struct Array<Element> : CollectionType, MutableCollectionType, _DestructorSafeContainer public class NSArray : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSFastEnumeration
// Array 轉 NSArray // Array 轉換成 NSArray<AnyObject> 型 let nsArray1:NSArray = array // Array 轉換成 NSArray<AnyObject> 型 let nsArray2:NSArray = array as NSArray // NSArray 轉 Array // NSArray 轉換成 Array<AnyObject> 型 let swiftArray1:Array = nsArray1 as Array // NSArray 轉換成 Array<AnyObject> 型 let swiftArray2:Array = nsArray1 as [AnyObject] // NSArray 轉換成 Array<Int> 型 let swiftArray3:Array = nsArray1 as! [Int]
// Array 型數組 // 不賦初值,指定數組內數據爲 String 型 let array1 = [String]() // 不賦初值,Array<String> 等價於 [String] let array2 = Array<String>() // 不指定數組內數據類型,自動推斷 let array3:Array = ["bei", "jing"] // 指定數組內數據類型爲 String 型 let array4:Array<String> = ["huan", "ying", "ni"] // 不指定數組內數據類型,自動推斷 let array5 = ["bei", "jing", "huan", "ying", "ni"] // 指定數組內數據類型爲 Int 型 let array6:[Int] = [1, 2, 3, 4, 5, 6] // 指定數組內數據類型爲 AnyObject 型 let array7:[AnyObject] = [1, 2, 3, 4, 5, 6, "happy"] // 建立二維數組 let array8:Array<Array<Int>> = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] // NSArray 型數組 let swiftArray:Array = ["bei", "jing", "nin", "hao"] let nsArray1:NSArray = swiftArray let nsArray2:NSArray = swiftArray as NSArray let nsArray3 = NSArray() // array: [AnyObject] let nsArray4 = NSArray(array: array7) // array: [AnyObject] let nsArray6 = NSArray(array: ["bei", "jing", "huan", "ying", "ni"]) // array: NSArray let nsArray5 = NSArray(array: nsArray2) // object: AnyObject let nsArray7 = NSArray(object: "qian") // objects: AnyObject... let nsArray8 = NSArray(objects: "bei", "jing", "huan", "ying", "ni") // 從 文件 建立字符串 let nsArray9:NSArray? = NSArray(contentsOfFile: NSHomeDirectory() + "/Desktop/test.txt") // 從 Url 建立字符串 let nsArray10:NSArray? = NSArray(contentsOfURL: NSURL(fileURLWithPath: NSHomeDirectory() + "/Desktop/test.txt"))
// Array 或 NSArray 型數組 let array = ["bei", "jing", "huan", "ying", "ni"] let num:Int = array.count
// Array 型字符串 let array = ["bei", "jing", "huan", "ying", "ni"] // 獲取起始位置,即 0 let startIndex = array.startIndex // 獲取結束位置,指 數組最後一個元素的位置 let endIndex = array.endIndex // 獲取指定位置下標值 let index = array.startIndex.advancedBy(2) // 獲取下標區間值 let range = array.startIndex.advancedBy(4)...array.startIndex.advancedBy(6) // 獲取指定位置下標的 前一個值 let predecessorIndex = array.startIndex.advancedBy(2).predecessor() // 獲取指定位置下標的 後一個值 let successorIndex = array.startIndex.advancedBy(2).successor()
// Array 型數組 let array:Array = ["bei", "jing", "huan", "ying", "ni"] // 獲取數組指定下標的元素 let obj1:String = array[1] // 獲取數組的第一個元素 let obj2:String? = array.first // 獲取數組的最後一個元素 let obj3:String? = array.last // 獲取數組指定範圍內的元素 let obj4 = array[2...4] // NSArray 型數組 let nsArray:NSArray = ["bei", "jing", "huan", "ying", "ni"] // 獲取指定下標元素,NSArray 中數據類型爲 AnyObject let obj5:String = nsArray[2] as! String // 獲取數組指定下標的元素 let obj6:String = nsArray.objectAtIndex(2) as! String // 獲取數組的第一個元素 let obj7:String = nsArray.firstObject as! String // 獲取數組的最後一個元素 let obj8:String = nsArray.lastObject as! String // 獲取數組指定範圍內的元素 let obj9 = nsArray.objectsAtIndexes(NSIndexSet(indexesInRange: NSMakeRange(2, 2))) // 獲取數組指定範圍內的元素 let obj10 = nsArray.subarrayWithRange(NSMakeRange(2, 3))
// Array 型數組 let array:Array = ["bei", "jing", "huan", "ying", "ni"] // 獲取指定元素的下標,若元素不存在,返回 nil let indexNum1:Int? = array.indexOf("huan") // NSArray 型數組 let nsArray:NSArray = ["bei", "jing", "huan", "ying", "ni"] // 獲取指定元素的下標,若元素不存在,返回 Int.max let indexNum2:Int = nsArray.indexOfObject("hun")
// Array 型數組 let arr1:Array = [1, 3, 5, 8] let arr2:Array = [1, 3, 7, 8] // 判斷兩個數組是否相等 let bl1:Bool = arr1 == arr2 // 判斷數組是否爲空 let bl2:Bool = arr1.isEmpty // 判斷數組中是否存在指定的元素 let bl3:Bool = arr1.contains(55) // NSArray 型數組 let nsArr1:NSArray = [2, 3, 5, 8] let nsArr2:NSArray = [1, 4, 7, 9] // 判斷兩個數組是否相等 let bl4:Bool = nsArr1.isEqualToArray(nsArr2 as [AnyObject]) // 判斷數組中是否存在指定的元素 let bl5:Bool = nsArr1.containsObject(7) // 返回兩個數組中第一個相同的元素,沒有時返回 nil let firstObj:AnyObject? = nsArr1.firstObjectCommonWithArray(nsArr2 as [AnyObject])
// NSArray 型數組 let arr1:NSArray = ["bei", "jing", "huan", "ying", "nin"] let arr2:NSArray = ["Users", "JHQ0228", "Desktop"] // 按指定字符組合 let str1:String = arr1.componentsJoinedByString(" ") // 按路徑組合 let str2:String = NSString.pathWithComponents(arr2 as! [String])
// Array 型數組 var arr1:Array = ["bei", "jing"] // 使用 "+" 號鏈接兩個數組 let arr2 = arr1 + ["huan", "ying", "ni"] // 在數組末尾追加一個元素 arr1.append("hao") // 在指定位置插入一個元素 arr1.insert("ni", atIndex: 2) // NSArray 型數組 let nsArray:NSMutableArray = ["jing", "huan"] // 向數組添加一個元素,返回一個新的數組 let nsArray1 = nsArray.arrayByAddingObject("ma") // 在數組末尾追加一個元素 nsArray.addObject("ni") // 在數組末尾追加一個數組 nsArray.addObjectsFromArray(["ni", "hao"]) // 在指定位置追加一個元素 nsArray.insertObject("bei", atIndex: 0)
// Array 型數組 var arr1:Array = ["bei", "jing", "huan", "ying", "ni"] // 刪除指定位置的數組元素 arr1.removeAtIndex(3) // 刪除數組中的最後一個元素 arr1.removeLast() // 刪除指定範圍內的數組元素 arr1.removeRange(0...1) // 刪除全部數組元素 arr1.removeAll(keepCapacity: true) // NSArray 型數組 let nsArr1:NSMutableArray = ["nan", "jing", "huan", "ying", "nin", "bei", "jing", "ni", "hao"] // 刪除指定下標的元素 nsArr1.removeObjectAtIndex(2) // 刪除指定元素,刪除全部指定元素 nsArr1.removeObject("ying") // 刪除指定元素 nsArr1.removeObjectIdenticalTo("nan") // 刪除最後一個元素 nsArr1.removeLastObject() // 刪除指定範圍的元素 nsArr1.removeObjectsInRange(NSMakeRange(2, 1)) // 刪除全部元素 nsArr1.removeAllObjects()
// NSArray 型數組 let nsArr:NSMutableArray = ["nan", "jing", "huan", "ying", "nin"] // 替換指定下標元素 nsArr.replaceObjectAtIndex(0, withObject: "bei") // 替換的元素個數與被替換的元素個數需相等 nsArr.replaceObjectsAtIndexes(NSIndexSet(indexesInRange: NSMakeRange(2, 3)), withObjects: ["ni", "hao", "ma"]) // 用數組替換 nsArr.replaceObjectsInRange(NSMakeRange(2, 3), withObjectsFromArray: ["huan", "ying"]) nsArr.replaceObjectsInRange(NSMakeRange(0, 2), withObjectsFromArray: ["huan", "ying", "nin", "nan", "jing", "huan"], range: NSMakeRange(3, 2))
// NSArray 型數組 let nsArr:NSMutableArray = ["bei", "jing", "huan", "ying", "nin"] nsArr.exchangeObjectAtIndex(2, withObjectAtIndex: 4)
// Array 型數組 var arr:Array = ["bei", "jing", "huan", "ying", "ni"] arr[0] = "nan" // NSArray 型數組 let nsArr:NSMutableArray = ["bei", "jing", "huan", "ying", "nin"] // 修改數組中的某個元素 nsArr[4] = "ni" // 修改整個數組(覆蓋重寫) nsArr.setArray(["ni", "hao"])
// Array 型數組 let arr:Array = [1, 9, 2, 8, 45] let array:[Int] = arr.filter { (obj:Int) -> Bool in // 過濾掉不能被 3 整除的數 return obj % 3 == 0 } // NSArray 型數組 let nsArr:NSMutableArray = [1, 9, 2, 8, 45] let nsArray:[AnyObject] = nsArr.filter { (obj:AnyObject) -> Bool in // 過濾掉不能被 3 整除的數 return (obj as! Int) % 3 == 0 }
用 for...in 循環遍歷swift
// Array 或 NSArray 型數組 let arr = ["bei", "jing", "huan", "ying", "ni"] // tmp 無需定義,在 Swift 2.2 中 C 語言樣式的 for 循環語句被廢棄 for tmp in arr { print(tmp) }
用閉包循環遍歷數組
// NSArray 型數組 let arr:NSArray = ["bei", "jing", "huan", "ying", "ni"] arr.enumerateObjectsUsingBlock { (obj:AnyObject, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in print(obj) if obj.isEqualTo("huan") { // 中止繼續遍歷 stop.initialize(true) } }
用迭代器遍歷閉包
// NSArray 型數組 let arr:NSArray = ["bei", "jing", "huan", "ying", "ni"] // 正序遍歷 let enu1:NSEnumerator = arr.objectEnumerator() // 反序遍歷 let enu2:NSEnumerator = arr.reverseObjectEnumerator() // AnyObject 後不要加 ?,不然會致使一直循環 while let obj:AnyObject = enu1.nextObject() { print(obj) }
條件遍歷app
// NSArray 型數組 let arr:NSArray = ["bei", "jing", "huan", "ying", "huan", "ni"] // 1. indexesOfObjectsPassingTest 找出數組中全部知足條件的值 let indexSet:NSIndexSet = arr.indexesOfObjectsPassingTest { (obj:AnyObject, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) -> Bool in // 條件知足時返回知足的數組元素的下標 return obj.isEqualTo("huan") ? true : false } indexSet.enumerateIndexesUsingBlock { (idx:Int, stop:UnsafeMutablePointer<ObjCBool>) in print(idx) } // 2. indexOfObjectPassingTest 找出數組中第一個知足條件的值 let index:Int = arr.indexOfObjectPassingTest { (obj:AnyObject, idx:Int, stop:UnsafeMutablePointer<ObjCBool>) -> Bool in // 條件知足時返回知足的數組元素的下標 return obj.isEqualTo("huan") ? true : false } print(index)
冒泡排序ide
// NSArray 型數組 let array:NSMutableArray = ["bei", "jing", "huan", "ying", "ni"] for i in 0 ..< array.count - 1 { for j in 0 ..< array.count - 1 - i { // 大小判斷 升序 if (array[j] as! String).compare(array[j + 1] as! String) == NSComparisonResult.OrderedAscending { // 位置交換 array.exchangeObjectAtIndex(j, withObjectAtIndex: j + 1) } } } print(array)
用閉包排序code
// Array 型數組 // 1. 利用閉包進行排序,可變數組排序 var varArray:Array = ["sunday", "sunny", "summer", "sun"]; varArray.sortInPlace { (obj1:String, obj2:String) -> Bool in return obj1 < obj2 } print(varArray) // 2. 利用閉包進行排序,不可變數組排序 let letArray:Array = ["sunday", "sunny", "summer", "sun"]; let array = letArray.sort { (obj1:String, obj2:String) -> Bool in return obj1 < obj2 } print(array) // NSArray 型數組 // 1. 利用閉包進行排序,可變數組排序 let nsMArray1:NSMutableArray = ["sunday", "sunny", "summer", "sun"]; nsMArray1.sortUsingComparator { (obj1:AnyObject, obj2:AnyObject) -> NSComparisonResult in let result:NSComparisonResult = (obj1 as! String).compare(obj2 as! String) return result } print(nsMArray1) // 2. 利用閉包進行排序,不可變數組排序 let nsArray1:NSArray = ["sunday", "sunny", "summer", "sun"]; let array1:NSArray = nsArray1.sortedArrayUsingComparator { (obj1:AnyObject, obj2:AnyObject) -> NSComparisonResult in let result:NSComparisonResult = (obj1 as! String).compare(obj2 as! String) return result } print(array1)
用指定的方法排序component
// Array 型數組 // 1. 用指定的方法排序,可變數組排序 var varArray:Array = ["sunday", "sunny", "summer", "sun"]; // 直接使用 Swift 數組類型中定義的小於號 (<) 實現,public func <(lhs: String, rhs: String) -> Bool varArray.sortInPlace( < ) print(varArray) // 2. 用指定的方法排序,不可變數組排序 let letArray:Array = ["sunday", "sunny", "summer", "sun"]; // 直接使用 Swift 數組類型中定義的小於號 (<) 實現,public func <(lhs: String, rhs: String) -> Bool let array = letArray.sort( < ) print(array) // NSArray 型數組 // 1. 用指定的方法排序,可變數組排序 let nsMArray1:NSMutableArray = ["sunday", "sunny", "summer", "sun"]; // 原數組的順序改變,指定元素的比較方法:compare:,默認爲升序排列, // #selector(NSNumber.compare(_:)) 代替 Selector("compare:") nsMArray1.sortUsingSelector(#selector(NSNumber.compare(_:))) print(nsMArray1) // 使排序結果 降序 排列 let enu:NSEnumerator = nsMArray1.reverseObjectEnumerator() while let obj:AnyObject = enu.nextObject() { print(obj) } // 2. 用指定的方法排序,不可變數組排序 let nsArray1:NSArray = ["sunday", "sunny", "summer", "sun"]; // 返回一個排好的數組,原數組的順序不變,指定元素的比較方法:compare: let array1:NSArray = nsArray1.sortedArrayUsingSelector(#selector(NSNumber.compare(_:))) print(array1) // 3. 用指定的方法排序,自定義類 // Student.swift class Student: NSObject { var firstName:String var lastName:String init(firstName:String, lastName:String ) { self.firstName = firstName self.lastName = lastName } func compareStudent(stu:Student) -> NSComparisonResult { // 先按照姓排序 var result:NSComparisonResult = self.lastName.compare(stu.lastName) if result == NSComparisonResult.OrderedSame { // 若是有相同的姓,就比較名字 result = self.firstName.compare(stu.firstName) } return result; } // 需遵照協議 Printable override var description: String{ return String(format: "%@, %@", self.lastName, self.firstName) } } // main.swift let stu1:Student = Student(firstName: "MingJie", lastName: "Li") let stu2:Student = Student(firstName: "LongHu", lastName: "Huang") let stu3:Student = Student(firstName: "LianJie", lastName: "Li") let stu4:Student = Student(firstName: "Jian", lastName: "Xiao") // 用指定的方法排序,可變數組排序 let nsMArray2:NSMutableArray = NSMutableArray(objects: stu1, stu2, stu3, stu4) // 代替 Selector("compareStudent:") nsMArray2.sortUsingSelector(#selector(Student.compareStudent(_:))) print(nsMArray2) // 用指定的方法排序,不可變數組排序 let nsArray2:NSArray = NSArray(objects: stu1, stu2, stu3, stu4) let array2:NSArray = nsArray2.sortedArrayUsingSelector(#selector(Student.compareStudent(_:))) print(array2)
按描述器排序orm
// Student.swift class Student: NSObject, Printable { var firstName:String var lastName:String init(firstName:String, lastName:String ) { self.firstName = firstName self.lastName = lastName } override var description: String{ return String(format: "%@, %@", self.lastName, self.firstName) } } // main.swift let stu1:Student = Student(firstName: "MingJie", lastName: "Li") let stu2:Student = Student(firstName: "LongHu", lastName: "Huang") let stu3:Student = Student(firstName: "LianJie", lastName: "Li") let stu4:Student = Student(firstName: "Jian", lastName: "Xiao") // 先按照姓進行排序 let lastnNmeDesc:NSSortDescriptor = NSSortDescriptor(key: "lastName", ascending: true) // 再按照名進行排序 let firstNameDesc:NSSortDescriptor = NSSortDescriptor(key: "firstName", ascending: true) // 1.按描述器排序,可變數組排序 let array1 = NSMutableArray(objects: stu1, stu2, stu3, stu4) // 按順序添加排序描 let descs1 = NSArray(objects: lastnNmeDesc, firstNameDesc) array1.sortUsingDescriptors(descs1 as! [NSSortDescriptor]) print(array1) // 2.按描述器排序,不可變數組排序 let array2 = NSArray(objects: stu1, stu2, stu3, stu4) // 按順序添加排序描 let descs2 = NSArray(objects: lastnNmeDesc, firstNameDesc) let array3 = array2.sortedArrayUsingDescriptors(descs2 as! [NSSortDescriptor]) print(array3)