数组的结构体本质,对比NSArray

Swift中的数组要求在创建时其存储的类型是确定的,这点与Oc中的数组有一些不同;

当然,这也不是绝对的,因为有时候数组可以使用范型来约束其类型,只需遵循相应的协议即可,类型并不是完全一致的.

Swift中的数组相比于Oc的数组,功能更加强大;使用更加简便;当然也更加复杂了(光是Array的代码就有9800多行)

1.数组的本质,查看官方的API可以知道数组实际上是一个 结构体.

struct Array<T> : MutableCollectionType, Sliceable {/// The type of element stored by this `Array`typealias Element = T/// Always zero, which is the index of the first element when non-empty.var startIndex: Int { get }/// A "past-the-end" element index; the successor of the last valid/// subscript argument.var endIndex: Int { get }subscript (index: Int) -> T/// Return a *generator* over the elements.////// Complexity: O(1)func generate() -> IndexingGenerator<[T]>/// A type that can represent a sub-range of an `Array`typealias SubSlice = Slice<T>subscript (subRange: Range<Int>) -> Slice<T>/// Initialization from an existing buffer does not have "array.init"/// semantics because the caller may retain an alias to buffer.init(_ buffer: _ArrayBuffer<T>)}

可以看到数组的构成包括:范型类型,计算属性,下标,构造器等

2.声明数组的两种方式

(1)使用范型(学过java的应该不会陌生)来约束数组的类型

方式;

var arr :Array<类型>

var arr : Array<Int>(2) 符号简写方式定义数组变量

方式:

var arr :[类型]

var arr2 :[String]

(3)定义隐式的数组类型,自动推断

方式:

var arr3 = [数组元素1,元素2,…..]

var arr3 = [1,2,3]上述的arr3不用声明类型,系统可以自动推断为 Int类型

3.数组的创建方式

(1)使用系统提供的init()构造器

使用示例:

arr = Array<Int>()(

示例,创建一个 元素个数为10,重复值的值为2的数组

arr = Array<Int>(count: 10, repeatedValue: 2)(3)使用直接赋值法

var arr3 = [1,2,3]

4.数组的几种遍历方式

(1)利用 数组的count属性来遍历,count是数组元素的个数;并且使用数组的下标来访问数组中的元素

var arr3 = [1,2,3]for var i = 0;i<arr3.count;i++{arr3[i]+=1print(arr3[i])}

(2)使用for in快速遍历

for elem in arr3{println(elem)}注意: elem默认是 let常量类型的,不可修改 elem的值

5.数组的方法,数组这个结构体,通过拓展增加了很多方法:

extension Array {/// Construct an empty Arrayinit()/// Construct from an arbitrary sequence with elements of type `T`init<S : SequenceType where T == T>(_ s: S)/// Construct a Array of `count` elements, each initialized to/// `repeatedValue`.init(count: Int, repeatedValue: T)/// How many elements the Array storesvar count: Int { get }/// How many elements the `Array` can store without reallocationvar capacity: Int { get }/// `true` if and only if the `Array` is emptyvar isEmpty: Bool { get }/// The first element, or `nil` if the array is emptyvar first: T? { get }/// The last element, or `nil` if the array is emptyvar last: T? { get }/// Reserve enough space to store minimumCapacity elements.////// PostCondition: `capacity >= minimumCapacity` and the array has/// mutable contiguous storage.////// Complexity: O(`count`)mutating func reserveCapacity(minimumCapacity: Int)/// Append newElement to the Array////// Complexity: amortized O(1) unless `self`'s storage is shared with another live array; O(`count`) if `self` does not wrap a bridged `NSArray`; otherwise the efficiency is unspecified.mutating func append(newElement: T)/// Append the elements of `newElements` to `self`.////// Complexity: O(*length of result*)///mutating func extend<S : SequenceType where T == T>(newElements: S)/// Remove an element from the end of the Array in O(1)./// Requires: count > 0mutating func removeLast() -> T/// Insert `newElement` at index `i`.////// Requires: `i <= count`////// Complexity: O(\ `count`\ ).mutating func insert(newElement: T, atIndex i: Int)/// Remove and return the element at index `i`////// Invalidates all indices with respect to `self`.////// Complexity: O(\ `count`\ ).mutating func removeAtIndex(index: Int) -> T/// Remove all elements.////// Postcondition: `capacity == 0` iff `keepCapacity` is `false`.////// Complexity: O(\ `countElements(self)`\ ).mutating func removeAll(keepCapacity: Bool = default)/// Interpose `self` between each consecutive pair of `elements`,/// and concatenate the elements of the resulting sequence. For/// example, `[-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]])`/// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]`func join<S : SequenceType where [T] == [T]>(elements: S) -> [T]/// Return the result of repeatedly calling `combine` with an/// accumulated value initialized to `initial` and each element of/// `self`, in turn, i.e. return/// `combine(combine(…combine(combine(initial, self[0]),/// self[1]),…self[count-2]), self[count-1])`.func reduce<U>(initial: U, combine: (U, T) -> U) -> U/// Sort `self` in-place according to `isOrderedBefore`. Requires:/// `isOrderedBefore` induces a `strict weak ordering/// <#Strict_weak_orderings>`__/// over the elements.mutating func sort(isOrderedBefore: (T, T) -> Bool)/// Return a copy of `self` that has been sorted according to/// `isOrderedBefore`. Requires: `isOrderedBefore` induces a/// `strict weak ordering/// <#Strict_weak_orderings>`__/// over the elements.func sorted(isOrderedBefore: (T, T) -> Bool) -> [T]/// Return an `Array` containing the results of calling/// `transform(x)` on each element `x` of `self`func map<U>(transform: (T) -> U) -> [U]/// A Array containing the elements of `self` in reverse orderfunc reverse() -> [T]/// Return an `Array` containing the elements `x` of `self` for which/// `includeElement(x)` is `true`func filter(includeElement: (T) -> Bool) -> [T]}

包括构造器,判空,排序,追加,移除等方法;方法使用简单,在此 只举一例:

使用append追加元素

var arr3 = [1,2,3]arr3.append(4)arr3.append(5)for var i = 0;i<arr3.count;i++{arr3[i]+=1print(arr3[i])}不能接受失败,也意味太想去成功了,从心理学上解释,

数组的结构体本质,对比NSArray

相关文章:

你感兴趣的文章:

标签云: