从零开始的8-bit迷宫探险【Level 5】Swift 基础语法 (三)

今日目标

  • 认识 for-in
  • 认识 if-else
  • 认识 switch
  • 认识 function

for-in

  • for-in 的使用方式如下:
    1...3 代表的是从 1 到 3的整数范围,回圈内的程序会执行 3 次
    item 代表每次的值,可以自己定义名称
for item in 1...3 {
    print(item)
}
印出结果:
1
2
3
  • 若是希望不包含 3,则可以使用 1..<3
for item in 1..<3 {
    print(item)
}
印出结果:
1
2
  • 若不需要取得值,则可以使用 _
for _ in 1..<3 {
    print("hello")
}
印出结果:
hello
hello
  • 可以搭配 where 使用,加上想要的条件,让程序更简洁
    例如:印出 1 到 10 中的偶数
for item in 1...10 where item%2 == 0 {
    print(item)
}
印出结果:
2
4
6
8
10
  • for-in 也可以用在集合型别 (Array、Dictionary、Set) 上,先前已经有做过介绍,这边就不再详述

if-else

  • if-else 可以依照给定的条件,判断是否符合,并执行不同的程序
    swift 的 if-else 省略了一般常见的 ()
    例如:判断一个阵列是否为空,分别印出不同的语句
if ["hiking", "ski", "diving"].isEmpty {
    print("Empty")
} else {
    print("Colorful life!")
}
印出结果:
Colorful life!
  • 若是有多种条件,可以使用 else if
let number = 75
if number < 60 {
    print("fail")
} else if number >= 60 && number < 85 {
    print("good")
} else {
    print("excellent")
}
印出结果:
good

switch

  • switch 可以让我们依照不同条件,执行不同的程序
    在 swift 中,switch 较特别的地方在於可以省略 break,只要进到某个条件之後,switch 就不会再跑进别的条件中。
let name = "Kevin"
switch name {
case "Yoyo":
    print("female")
case "Kevin":
    print("male")
default:
    print("unknown")
}
印出结果:
male
  • case 可以支援范围类型
    例如:依照不同数字的范围,印出不同结果
let number = 75
switch number {
case 0..<60:
    print("fail")
case 60..<85:
    print("good")
default:
    print("excellent")
}
印出结果:
good
  • 可以使用 where 带入条件类型的 case
    例如:只要有包含 apple,就印出这是我最喜欢的水果。若是包含 pineapple,就印出还不错。若是都没有符合的条件,则印出我都不喜欢:
let fruit = ["apple", "orange", "banana"]
switch fruit {
case _ where fruit.contains("apple"):
    print("This is my favorite fruit.")
case _ where fruit.contains("pineapple"):
    print("Not bad.")
default:
    print("I don't like these.")
}
印出结果:
This is my favorite fruit.

function

我们可以自订方法 (function),来做某项特定的事情。

  • 宣告方法可以使用 func
    • doMath 代表的是方法的名称
    • num: Int 是可以带入的参数名称及其型态
    • { } 内为执行的程序
func doMath(num: Int) {
    print(num * 2)
}
doMath(num: 4)
印出结果:
8
  • 方法的回传值 ->
    • -> Int 代表此方法回传的值为整数型态
    • return 後写上回传的值
func doMath(num1: Int, num2: Int) -> Int {
    return num1 + num2
}
print(doMath(num1: 4, num2: 3))
印出结果:
7
  • 参数的预设值
    • 例如:num2: Int = 5 ,代表给予参数预设值 5
    • 当呼叫方法时,若没有带入此参数,则使用预设值
func doMath(num1: Int, num2: Int = 5) -> Int {
    return num1 + num2
}
print(doMath(num1: 4))
印出结果:
9

今日小结:
今天认识了一些流程控制的方式,以及如何宣告一个方法
明日继续努力!/images/emoticon/emoticon33.gif


<<:  Day 11 | 嵌套元件(二)

>>:  Day13 Lab 2 - Object storage API层

高防CDN如何防御日益迭代的网络攻击?

随着互联网的日新月异,人们对於服务器租用要求也是越来越高,其中高防CDN就是受到大家关注的一种服务类...

你便利 我超伤

曾经跟在便利商店工作过的学弟聊天,从他分享的经验谈,谈到加盟便利超商连锁店,并非每一家都像加盟广告那...

大数据平台:分散式计算

Spark 支援批次资料、查询分析、资料流、机器学习及图处理(Graph Processing),...

Day1: 开始学习演算法和资料结构的契机

近期面试掀起了一波考演算法的风气,就好像回到大学指考那样,老师说这题会考一定要记起来,因此掀起了一...

Day11 测试写起乃-FactoryBot-create、build、build_stubbed

建立bot 官方文件有说有以下建立方式至於差别在哪呢? # Returns a User insta...