swift 数组

  个人觉得对于已经有过oc开发经验的人来说,学习swift最快的就是学好基础!基础学好,学扎实了,到后面基本就感觉很容易了。

      

import Foundation

 

//1.数组的基本认识

var 数组1 = [1,2,3,4,5,6,7]

 

数组1[0] = 3

 

数组1

 

 

//求指定半径的圆的面积 S = pi*r^2

struct Square {

    subscript(radius:Double)->Double{

        //pow函数:2个参数a和b,求a的b次方

        

        return M_PI*pow(radius, 2)

        

    }

}

 

let s1 = Square()

s1[5]

 

//2.多参数下标:

// 一个2*2的矩阵,变成数组[5,6,2,8]

//通过下标矩阵[行,列]来访问

 

/*

        第0列   第1列

  第0行    5      6     元素序号:所在列+【所在行*总列数】

  第1行    2      8     元素序号:所在列+【所在行*总列数】

*/

struct Matrix {

    var rows,columns:Int

    var grid:[Int]

    

    init(rows: Int, columns: Int){

        self.rows = rows

        self.columns = columns

        

        grid = Array(count: rows * columns, repeatedValue: 0)

    }

    //检查索引是否超越数组大小

    func indexIsValid(row:Int, column:Int)->Bool{

        return row >= 0 && row < rows && column >= 0 && column < columns

    }

    //用下标方法 来存取矩阵对应的数组

    subscript(row:Int, column:Int) ->Int{

        //取回矩阵对应的数组中的值

        get {

            assert(indexIsValid(row, column: column), "下标越界")

            return grid[(row * columns) + column]

        }

        //根据索引设置矩阵值到数组中

        set {

            assert(indexIsValid(row, column: column), "下标越界")

            grid[(row * columns) + column] = newValue

        }

    }

}

var aMatrix = Matrix(rows: 3, columns: 3)

 

aMatrix[0,0] = 1

aMatrix[0,1] = 2

aMatrix[0,2] = 3

aMatrix[1,0] = 4

aMatrix[1,1] = 5

aMatrix[1,2] = 6

aMatrix[2,0] = 7

aMatrix[2,1] = 8

aMatrix[2,2] = 9

 

for i in aMatrix.grid{

    println(i)

}

 

posted @ 2015-05-17 11:27  殇卜泣  阅读(133)  评论(0编辑  收藏  举报