Swift编程指南——基础语法和流程控制

319 阅读4分钟

1. 基础语法

Swift不用编写main函数,Swift将全局范围内的首句可执行代码作为程序入口。一句代码尾部可以省略分号(;),多句代码写到同一行时必须使用分号(;)分割。用var定义变量,let定义常量,编译器能自动推断出变量/常量的类型。

var str = "Hello"
var myVariable = 42
myVariable = 50
let explicitDouble:Double = 70
let letCount:Float = 4
let strLetCount = str + String(letCount)
let strFloatCount = str + "my \(letCount + letCount/2)"
let quotation = ""

1.1 常量

  • 只能赋值一次
  • 它的值不要求在编译时确定,但使用之前必须赋值一次。常量变量在初始化之前都不能使用

1.2 标识符

  • 标识符(比如常量名,变量名,函数名)几乎可以使用任何字符
  • 标识符不能以数字开头,不能包含空白字符,制表符,箭头等特殊字符
func 🐂🍺(){
    print("666")
}
🐂🍺()
let 👽 = "ET"
let 🥛 = "milk"

1.3 常见数据类型

  • 值类型:
    • 枚举(enum):Optional
    • 结构体(struct):Bool,Int,Float,Double,Character,String,Array,Dictionary,Set
      • 整数类型:Int8,Int16,Int32,Int64,UInt8,UInt16,UInt32,UInt64
      • 在32bit平台下,Int等价于Int32;在64bit平台下,Int等价于Int64
      • 整数的最值,UInt8.max,Int16.min
      • 浮点类型:Float,32位,精度只有6位;Double,64位,精度至少15位
  • 引用类型:类(class)

1.4字面量

  • 布尔
let bool = true //取反是false
  • 字符串
let string = "yanxue"
  • 字符(可存储ASCII字符和Unicode字符)
let character:Character = "🐶"
  • 整数
let intDecimal = 17 //十进制
let intBinary = 0b10001 //二进制
let intOctal = 0o21 //八进制
let intHexadecimal = 0x11 //十六进制
  • 浮点数
let doubleDeccimal  = 125.0 //十进制,等价于1.25e2,0.0125等价于1.25e-2
let doubleHexadecimal1 = 0xFp2 //十六进制,意味着15x2^2,相当于十进制的60.0
let doubleHexadecimal2 = 0xFp-2 //十六进制,意味着15x2^-2, 相当于十进制的3.75
//整数和浮点数都可以添加额外的0或者下划线来增加可读性
100_0000
1_000_000.000_1
000123.456
  • 数组
let array = [1,3,5,7,9]
  • 字典
let dictionary = ["age":18,"height":168,"height":120]

1.4 类型转换

  • 整数转换
let int1:UInt16 = 2_000
let int2:UInt8 = 1
let int3 = int1+UInt16(int2)
  • 整数浮点数转换
let int = 3
let double = 0.14159
let pi = Double(int)+double
let intPi = Int(pi)
  • 字面量可以直接相加,因为数字字面量本身没有明确的类型
let result = 3+0.14159

1.5 元组

let http404Error = (404,"Not Found")
print("the status code is \(http404Error.0)")
let (statusCode,statusmessage) = http404Error
print("the status code is \(statusCode)")
let (justTheStatusCode,_) = http404Error
let http200Stats = (statusCode:200,description:"ok")
print("the status code is \(http200Stats.statusCode)")

2.流程控制

2.1 if-else

  • if后面的条件类型只能是bool
  • if后面的条件可以省略小括号
  • 条件后面的大括号不可以省略
var population: Int = 50001
var message: String
var hasPostOffice: Bool = true

if population < 10000 {
    message = "\(population) is a small town!"
}else if population >= 10000 && population < 50000 {
    message = "\(population) is medium big!"
}else{
    message = "\(population) is pretty big!"
}

message = population < 10000 ? "\(population) is a small town!" : "\(population) is pretty big!"

if !hasPostOffice {
    print("where do we buy stamp?")
}
print(message)

2.2 while

  • repeat-while相当于c语言的do-while
  • 从swift3开始,去除了自增(++),自减(--)运算符
var num = 5
while num > 0 {
    print("num is \(num)")
    num -= 1
}//打印了5次

var num1 = -1
repeat{
    print("num1 is (\(num1))")
}while num1 > 0 //打印了1次

2.3 for

  • 闭区间运算符:a...b,a <= 取值 <= b
let names = ["Anna","Alex","Brian","Jack"]
for i in 0...3{
    print(names[i])
}//Anna Alex Brian Jack
let range = 1...3
for i in range {
    print(names[i])
}//Alex Brian Jack

let a = 1
let b = 2
for i in a...b {
    print(names[i])
}//Alex Brian

//i默认是let,有需要时可以声名为var
for var i in 1...3 {
    i += 5
    print(i)
}//6 7 8

for _ in 1...3 {
    print("for")
}//打印了三次
  • 半开区间运算a..<b,a<= 取值 <b
for i in 1..<5 {
    print(i)
} // 1 2 3 4
  • for-区间运算符用在数组上
let names = ["Anna","Alex","Brian","Jack"]
for name in names[0...3] {
    print(name)
}//Anna Alex Brian Jack
//单侧区间:让区间朝一个方向尽可能的远
for name in names[2...] {
    print(name)
}//Brian Jack
for name in names[...2] {
    print(name)
}//Anna Alex Brian
for name in names[..<2] {
    print(name)
}//Anna Alex

2.4 区间类型

let range1:ClosedRange<Int> = 1...3
let range2:Range<Int> = 1..<3
let range3:PartialRangeThrough<Int> = ...5
  • 字符,字符串也能使用区间运算符,但默认不能使用在for-in中
  let stringRange1 = "cc"..."ff" //ClosedRange<String>
  stringRange1.contains("cb") //fale
  stringRange1.contains("dz") //true
  
  let characterRange = "\0"..."~" //所有可能要用到的的ASCII码字符
  characterRange.contains("G")//true
  • 带间隔的区间值
let hours = 11
let hourInterval = 2
//tickMark的取值:从4开始,累加2,不超过11
for tickMark in stride(from: 4, through: hours, by: hourInterval) {
    print(tickMark)
}//4 6 8 10

2.5 switch

  • case,default后面不能写大括号{}。默认可以不写break,并不会贯穿到后面的条件
var num = 1
switch num {
case 1:
    print("num is 1");
case 2:
    print("num is 2");
default:
    print("num is other");
}
  • 使用fallthrough可以实现贯穿效果
var num1 = 1
switch num1 {
case 1:
    print("num1 is 1");
    fallthrough
case 2:
    print("num1 is 2");
default:
    print("num1 is other");
}//num1 is 1 num1 is 2
  • switch必须保证能处理所有的情况。case,default后面至少要有一条语句,如果不想做任何事,加个break即可。
var number = 1
switch number {
case 1:
    print("number is 1")
default:
    break
}
  • 如果能保证已处理所有情况,也可以不必使用default
enum Answer {case right,wrong}
let answer = Answer.right
switch answer {
case .right:
    print("right")
case .wrong:
    print("wrong")
}
  • 复合条件,switch也支持Character,String类型
let string = "Jack"
switch string {
case "Jack":
    fallthrough
case "Rose":
    print("Right person")
default:
    break
}//Right person
  
switch string {
case "Jack","Rose":
    print("Right person")
default:
    break
}//Right person
  
let character = "a"
switch character {
case "a","A":
    print("The letter A")
default:
    print("Not the letter A")
}//The letter A
  • 区间匹配,元组匹配。可以使用_忽略某个值。关于case匹配问题,属于模式匹配的范畴。
let count = 62
switch count {
case 1..<5:
    print("a few")
case 5..<12:
    print("several")
case 12..<100:
    print("dozens of")
default:
    print("many")
}//dozens of
               
let ponit = (1,1)
switch ponit {
case (0,0):
    print("the origin")
case (_,0):
    print("on the x-axis")
case (-2...2,-2...2):
    print("inside the box")
default:
    print("outside of the box")
}//inside the box
  • 值绑定(必要时let也可改成var)
let point = (2,0)
switch point {
case (let x,0):
    print("on the x-axis with an x value of \(x)")
case (0,let y):
    print("on the y-axis with an y value of \(y)")
case (let x,let y):
    print("somewhere else at (\(x),\(y))")
}

2.6 where

let point1 = (1,-1)
switch point1 {
case let (a,b) where a == b:
    print("on the line a == b")
case let (a,b) where a == -b:
    print("on the line a==-b")
case let (a,b):
    print("(\(a),\(b)) is the just some arbitrary point")
}
var numbers = [10,20,-10,-20,30,-30]
var sum = 0

for num in numbers where num > 0 {//使用where过滤num
    sum += num
}
print(sum)//60

2.7 标签语句

outer: for i in 1...4 {
    for k in 1...4 {
        if k == 3 {
            continue outer
        }
        if i == 3 {
            break outer
        }
        print("i == \(i),k== \(k)")
    }
}