首页 > 代码库 > Swift学习——使用if和switch来进行条件操作,使用for,while,和do-while来进行循环(三)

Swift学习——使用if和switch来进行条件操作,使用for,while,和do-while来进行循环(三)

Swift学习——使用if和switch来进行条件操作,使用for,while,和do-while来进行循环


//switch支持任意类型的数据以及各种比较操作——不仅仅是整数以及测试相等

//注意如果去掉default程序会报错

let strings = "hello3"
switch strings{
    case "hello1":
    let stringsComment = "say hello1"
    println("stringsComment is \(stringsComment)")
    break
    case "hello2","hello3":
    let stringsComment = "say hello2 and hello3"
    println("stringsComment is \(stringsComment)")
    break
    case let x where x.hasSuffix("hello4"):
    let stringsComment = "Is it a spicy \(x)?"
    println("stringsComment is \(stringsComment)")
    break
    default:
    let stringsComment = "say everything"
    println("stringsComment is \(stringsComment)")
}


简单的while和do-while循环


// while循环
var n = 3
while n < 100{
    n = n*2
}
println("n is \(n)")

//do-while循环
var m = 3
do{
    m = m*2
}while m < 100

println("m is \(m)")

打印结果

stringsComment is say hello2 and hello3

n is 192

m is 192