前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Swift3.0 - 流控制

Swift3.0 - 流控制

作者头像
酷走天涯
发布2018-09-14 14:51:43
4330
发布2018-09-14 14:51:43
举报

介绍
  • if...else
if true{
 // code
 }else{
// code
 }

let  (x,y) = (1,2)
if x = y{  // 这是一个错误的用法
}

提示:

判断的条件必须为 true 或者false 不能是1,2 或者存在的对象,不然系会编译错误,这点和OC 是有区别的

  • 三目运算符(?)
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
  • ?? 的使用

先看下面的例子

let a:Int! = 3
let b = 4
 // 如果a不为nil则对a进行解包,赋值将b的值付给c
let c = a != nil ? a! : b

我们使用?? 可以很方便实现上面的功能

 let c = a ?? b // 如果a为nil则使用b的值替换a的值,如果a不为nil,则对a解包然后将值付给b

我们再看一个例子

let a:Int??? = 3
let b = 4
let c = a ?? b
print(a)
print(c)

运行结果:

Optional(Optional(Optional(3))) Optional(Optional(3))

分析:

对a进行一次解包,得到的值不为nil,所以把解包后的值付给c

我们再看一个例子

let a:Int??? = nil
let b = 4
let c = a ?? b
print(a)
print(c)

可能有些人已经猜到答案了

nil 4

但我告诉你答案不是这样的,先来分析一下

首先a,有三个包Optional(Optional(Optional(nil))),当我们解掉第一次包后,发现值为nil,此时,我们需要将b的值替换给a,Optional(Optional(4))

所以我们的最终显示结果为:

nil Optional(Optional(4))

  • 范围操作符 ... ..<
for index in 1..<5 {
    print("\\(index) times 5 is \\(index * 5)")
 }
  • 多种逻辑操作符的结合
 if enteredDoorCode && passedRetinaScan || hasDoorKey ||     knowsOverridePassword {
  print("Welcome!")
} else {
  print("ACCESS DENIED")
}
  • for ... in
   // 遍历数组
   let names = ["Anna", "Alex", "Brian", "Jack"]
   for name in names {
       print("Hello, \\(name)!")
    }
  // 遍历字典
   let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
  for (animalName, legCount) in numberOfLegs {
       print("\\(animalName)s have \\(legCount) legs")
   }
  • while
var i = 100 
while i >0{
   i-= 1
}
  • repeat ... while
var i = 10
repeat {
    i -= 1
    print(i)
}while i >= 0
  • switch

需求1: 根据输入的成绩判断学生是否及格

a. 间隔法

enum TestResult{
    case Pass
    case NoPass
}

b. 条件判断法

 func inputStudentScore(score:Float) -> TestResult{
    switch score {
    case 0..<59:
        return .NoPass
    default:
        return .Pass
    }
}

需求二: 输入一个顶点 判断是否在X轴上,或者Y轴上,或者既不在x轴,也不再Y轴上

c.元组法

func inputPoint(point : (Float,Float)) {
    switch point {
    case (_,0):
        print("在x轴上")
    case (0,_):
        print("在y轴上")
    case (_,_):
        print("既不在x轴,也不在y轴上")
    }
}

d.值绑定法

func inputPoint(point : (Float,Float)) {
switch point {
case (let x ,0):
    print("在x轴上\\(x)")
case (0,let y):
    print("在y轴上\\(y)")
case let (x,y):
    print("既不在x轴,也不在y轴上\\(x),\\(y)")
} 
}

需求: 判断顶点是否在X,Y轴上

  • 混合法
func inputPoint(point : (Float,Float)) {
 switch point {
 case (let x ,0),(0,let x):  // 注意必须每种模式类型相同
 print("在x轴或者y轴上\\(x)")
 case let (x,y):
      print("既不在x轴,也不在y轴上\\(x),\\(y)")
  }
}
  • 控制转移声明

a.continue

let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput.characters {
    switch character {
    case "a", "e", "i", "o", "u", " ":
        continue
    default:
        puzzleOutput.append(character)
    }
}

b.break

let numberSymbol: Character = "三"  // Chinese symbol for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
    possibleIntegerValue = 1
case "2", "٢", "二", "๒":
    possibleIntegerValue = 2
case "3", "٣", "三", "๓":
    possibleIntegerValue = 3
case "4", "٤", "四", "๔":
    possibleIntegerValue = 4
default:
    break
}

c.fallthrough

  let integerToDescribe = 5
var description = "The number \\(integerToDescribe) is"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
    description += " a prime number, and also"
    fallthrough // 打穿继续向下执行  
default:
    description += " an integer."
}
print(description)

运行结果:

The number 5 is a prime number, and also an integer.

d.return

需求:在一个数组中查找是否存在一个整数,如果找到返回true 没有返回false

let nums = [1,2,3,6,7,9,10]
func findNum(num:Int)-> Bool{
    for number in nums{
        if num == number{
            return true
        }
    }
    return false
}

e.throw

f.标签用法

需求: 让一个a数字从0开始,每次增加一个随机数,直到数字a=1000 结束循环,如果大于1000 则继续从0 开始循环增加

var start:Int = 0
var final = 1000
whileLabel: while start != final {
    start += Int(arc4random_uniform(100)) // 随机增加一个数字
    switch start {
    case final:  // 如果== 最终值结束循环
        break whileLabel
    case let x where x > final: //如果值大于1000 则初始化为0 继续开始循环
        start = 0
        continue whileLabel
    default:
        break
    =  }
  print(start)
}
  • guard ...else

需求: 输入学生姓名,查询学生成绩

a.原始写法(if):

let studentScoreDic = ["小明":30.0,"小摩纳哥":99.0]
func getScoreByName(name:String!)->Double{ // 先检测姓名是否为空
    if let n = name {
        if let score = studentScoreDic[n] {// 检测学生是否存在
            return score
        }
    }
 return 0.0
}

b.guard ... else

let studentScoreDic = ["小明":30.0,"小摩纳哥":99.0]
func getScoreByName(name:String!)->Double{
    // 检测姓名是否为空
    guard let n = name else {
        return 0.0
    }
    // 检测学生是否存在
     guard let score = studentScoreDic[n] else{
        return 0.0
      }
   return score
  }

c.使用?? 简化写法

let studentScoreDic = ["小明":30.0,"小摩纳哥":99.0]
func getScoreByName(name:String!)->Double{
guard let n = name else {
      return 0.0
}
  return studentScoreDic[n] ?? 0.0
}

d. 多条件简化法- guard 版

let studentScoreDic = ["小明":30.0,"小摩纳哥":99.0]
func getScoreByName(name:String!)->Double{
  guard let n = name ,let score = studentScoreDic[n] else {
      return 0.0
}
  return score
}

e.多条件简化法- if 版

let studentScoreDic = ["小明":30.0,"小摩纳哥":99.0]
func getScoreByName(name:String!)->Double{
    if let n = name ,let score = studentScoreDic[n]{
        return score
    }
    return 0.0
}
中级
  • 多条件判断

需求:

输入两个数字,如果两个数字都小于100 并且第一个数字小于第二数字,按照顺序输出他们

方式1:

func inputFirstNum(num1:String,num2:String){
    if let n1 = Int(num1){
        if let n2 = Int(num2){
            if n1 < n2 && n2 < 100 {
                print("\\(n1)<\\(n2)<\\(100)")
            }
        }
    }
}

方式2:

func inputFirstNum(num1:String,num2:String){
    if let n1 = Int(num1),let n2 = Int(num2),n1 < n2,n2 < 100{
        print("\\(n1)<\\(n2)<\\(100)")
    }  
}
  • 元组判断
if (1, "zebra") < (2, "apple") { // 先判断第一个,在判断第二个
 // 结果为true
} 

你必须注意的几点

1.转换出现可选值

if let n = Int(3.3){
} // 编译报错

if let n = Int("3.3"){
    print(n)
} // 编译通过

运行结果:

1.第一个if报错 2.第二个print(n) 不执行

问题:为什么第一个if会报错?

答:Swift编译器要求我们右边必须为可选值类型Int(3.3) 产生的结果不是可选值,我在swift3.0-数据类型 中讲过数据类型之间转换不可能出现可选值,但是字符串转数字结果为可选值,所以第二个if是正确的

我们修改上面的代码

if let n:Int  = Int(3.3) {
print(n)
} // 编译警告

if let n :Int = Int("3.3"){
    print(n)
} // 编译通过

if let n:Int?  = Int(3.3) {
    print(n)
} // 编译警告-说总是成功的

if let n :Int? = Int("3.3"){
    print(n)
} // 编译通过 - 说总是成功的

if let n:Int! = Int(3.3){
    print(n)
}// 编译报错 - 非可选值不能解包


if let n :Int! = Int("3.3"){
    print(n)
} // 编译报错-解包的时机不对

2.注意可选值的判断逻辑

let name1:String! = "酷走天涯" // 定义一个需要解封的可选值
let name2:String? = "酷走天涯" // 定义可选值
let name3:String = "酷走天涯"  // 定义非可选值

if name1 != nil {
} // 编译成功
if let myName = name1{
} // 编译错误

if name2 != nil {
} // 编译成功
if let myName = name2{
} // 编译错误

if name3 != nil {
} // 编译警告 - 总是成功
if let myName = name3{
} // 编译错误 - name3 不是可选值

结论:

只有可选值或者解包过的可选值,判断是否为nil是有意义的,非可选值不可能为nil,判断总是成功的,判断没有意义。 对非可选值使用解包判断方式总是失败的。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016.10.07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 中级
  • 你必须注意的几点
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档