美文网首页iOS Developer
04 Swift逻辑分支

04 Swift逻辑分支

作者: 猴子的救兵520 | 来源:发表于2017-07-05 19:31 被阅读37次

1.if分支语句

和OC中if语句有一定的区别:

  • 判断句可以不加()
  • 在Swift的判断句中必须有明确的真假
    • 不再有非0即真/非空即真
    • 必须有明确的Bool值
// 演练一:
let a = 10

// 错误写法:
//if a {
//    print("a")
//}

// 正确写法
if a > 9 {
    print(a)
}

// 演练二:
let score = 87

if score < 60 {
    print("不及格")
} else if score <= 70 {
    print("及格")
} else if score <= 80 {
    print("良好")
} else if score <= 90 {
    print("优秀")
} else {
    print("完美")
}

// 演练三:
// 这个是可选类型,因为只有声明成可选类型后,才可以判断是否为空
// 可选类型会在后续讲解,可先了解即可
let view : UIView? = UIView()

// 判断如果view有值,则设置背景
// 错误写法
//if view {
//    view.backgroundColor = UIColor.redColor()
//}

if view != nil {
    view!.backgroundColor = UIColor.redColor()
}

2.三目运算

Swift 中的 三目 运算保持了和 OC 一致的风格

var a = 10
var b = 50

var result = a > b ? a : b
println(result)

3.guard

  • guard是Swift2.0新增的语法
  • guard与if语句非常类似,它设计的目的是提高程序的可读性
  • guard语句必须带有else语句,它的语法如下:
    • 当条件表达式为true时候跳过else语句中的内容,执行语句组内容
    • 条件表达式为false时候执行else语句中的内容,跳转语句一般是return、break、continue和throw
guard 条件表达式 else {
    // 条换语句
    break
}
语句组
  • 例子
var age = 18

func online(age : Int) -> Void {
    guard age >= 18 else {
        print("禁止入内")
        return
    }

    print("可以上网")
}

online(age)

4.switch分支

Swift对Switch进行了增强,基本用法和OC用法一致

  • switch后可以不跟()
  • case后可以不跟break(默认会有break)
let sex = 0

switch sex {
case 0 :
    print("男")
case 1 :
    print("女")
default :
    print("其他")
}
  • 一个case判断中,可以判断多个值
  • 多个值以,隔开
let sex = 0

switch sex {
case 0, 1:
    print("正常人")
default:
    print("其他")
}
  • 使用关键字fallthrough,可以实现OC中出现的case穿透
let sex = 0

switch sex {
case 0:
    fallthrough
case 1:
    print("正常人")
default:
    print("其他")
}
  • Switch支持多种数据类型

浮点型的switch判断

let f = 3.14
switch f {
case 3.14:
    print("π")
default:
    print("not π")
}

字符串类型的switch判断

let m = 5
let n = 10
var result = 0

let opration = "+"

switch opration {
    case "+":
        result = m + n
    case "-":
        result = m - n
    case "*":
        result = m * n
    case "/":
        result = m / n
default:
    result = 0
}

print(result)
  • switch支持区间判断

    swift中的区间常见有两种
    1.半开半闭区间:0..<10 表示:0~9,不包括10
    2.闭区间:0..10 表示:0~10

// 此例中,90..100是闭区间,其他都是半开半闭区间
let score = 88

switch score {
case 0..<60:
    print("不及格")
case 60..<80:
    print("几个")
case 80..<90:
    print("良好")
case 90..100:
    print("优秀")
default:
    print("其他")
}

相关文章

网友评论

    本文标题:04 Swift逻辑分支

    本文链接:https://www.haomeiwen.com/subject/pnpmqxtx.html