swift基础语法

来源:互联网 发布:windows 10 live mail 编辑:程序博客网 时间:2024/05/21 17:14

枚举:

个人感觉这个定义有点像结构体。

枚举相当于定义了一个新的类型,所以我们需要大写枚举名首字母:

enum PointRect{    case top(Int,Int)    case buttom(Int,Int)    case left(Int,Int)    case right(Int,Int)}var samplePoint=PointRect.top(10, 0)

控制流:

也叫做控制结构:顺序结构,条件结构,循环结构,转向结构

switch:

let weeDay = 3switch weekDay{case 1,2,3,4,5:    println("今天是工作日,星期\(weekDay)")    case 6,7    println("今天是周末,好好放松一下吧")default:    println("输入有误,请告知今天是周几")}

不难发现,这个switch比c语言中的可以更加节省代码,可以将多个switch的值放在一起

但是值得注意的是,case块中都必须包含至少一条语句,不能为空。

值绑定:

var anotherPoint = (2,0)switch anotherPoint {case(var x,0):x--    println("\(x) on the x-axis")case(0,var y):    y++pintln("\(y) on the y-axis")case let (x,y) where x==y:    println("\(x),\(y) is on the line x==y")  //当x==y的时候执行此语句case let (x,y):    println("point at (\(x), \(y))") //这个case中包含所有可能出现的院元组值匹配    }

循环结构相对比较简单:可使用关键字 for-in for while 和do-while

println("Hello, World!")for chare in "hello World"{    // 使用for in 遍历字符串中的字符    println(chare)}for var index=1;index<100;++index {     //使用for找出100以内的奇数    if (index % 2) !=0{        println("odd is \(index)")    }}for i in 1..<100{    if (index%2) !=0{            //使用..<找出100以内的奇数        println("odd is \(index)")    }}var i=1var oddSum=0do{if i%2 !=0{    oddSum+=i}i++}while i<100

现在还不明白为何会出现一些错误。


0 0
原创粉丝点击