swift學習之數組(一)

來源:互聯網
上載者:User

標籤:swift   編程   

  首先數組的定義:以有序的方式儲存相同類型的值

(1)數組的速寫(shorthand)文法

你可以通過Array<Element>,在這裡,Element時數組儲存元素的值的類型,也可以通過中括弧來寫[Element]

(2)建立一個空數組

        var emptyArr = [Int]()(這裡使用初始化方法建立一個Int型的空數組)
        emptyArr.append(3)
        emptyArr = [] (這裡是用字面語句建立空數組)
note:emptyArr is now an empty array,but is still an type of [Int]

另外,就是我直接用var emptyArr = []建立一個空數組會產生一個錯誤,報了這是一個不可變數組,大家可以試試

(3)建立一個帶有預設值的數組

swift提供了一種初始化一個數組,並且這個數組帶有相同的預設值

    var defaultArr = [Double](count: 3, repeatedValue: 0.0)(值類型是double型的)
    println(defaultArr)

//the println is [0.0, 0.0, 0.0]

(4)通過add兩個數組建立一個新的數組

通過(+)號操作將兩個已經存在的相同類型的數組建立一個新的數組

        var anotherArr = [Double](count: 3, repeatedValue: 2.5)
        var newArr = defaultArr + anotherArr
        println(newArr)

//the result is [0.0, 0.0, 0.0, 2.5, 2.5, 2.5]





借鑒:https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

swift學習之數組(一)

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.