- Swift中用
var
代表变量,let
代表常量 - 不必一定要显式声明数据的类型,Swift可以自己去通过赋值去判断
let imInt = 10
let imInt: Int = 10
这两种声明方式是相同的
但是,不能将两种不同类型的变量直接做运算
let imInt = 10
let imFloat = 3.4
let imSum = imInt + imFloat //报错
let imSum = (Double)imInt + imFloat //正确,需要强制进行转换
- 元组(适合轻量级的数据集合)
//隐式声明
var point = (2, 3)
var httpResponse = (404, "Not Found") //每个值可以式任意类型
//显式声明
var point2: (Int, Int, Int) = (10, 5, 2)
var httpResponse: (Int , String) = (404, "Not Found")
//使用元组
//1. 解包
let (x , y) = point // x = 2, y = 3
//2. 点方法(不直观)
point.0 // 2
point.1 // 3
//因此可以定义元组每个值的名字
var point3 = (x: 2, y: 3) // 等同于 var point3 : (x: Int, y: Int) = (2, 3)
point3.x //2
point3.y //3
//只对单一值解包(使用下划线来忽略某个值)
let loginResult = (true , "qtoq")
let (isLoginResult, _) = loginResult
if isLoginResult {
print("Login Success!")
}else {
print("Login Failed!")
}
- print函数
let x = 1, y = 2, z = 3, b = true
print(x, y, z, b) // 1 2 3 true
print(x, y, z, separator: ",") // 1,2,3
print(x, y, z, separator: ",", terminator: ":)") //1,2,3:)
print("!!") //1,2,3:)!! (不换行)
print("\(y) * \(z) = \(y*z)") // 使用\()进行插值运算,后续会用的很多 2 * 3 = 6
print("y * z =", y*z) // y * z = 6
- for循环
for i in a...b // [a, b]
for i in a..<b // [a, b)
for _ in 1...num { // 循环省略
result *= n
}
- 控制转移
findAnswer:
for i in 1...300 {
for j in 1...300 {
if i*i*i*i - j*j = 15*i*j {
print(i, j)
break findAnswer
}
}
}
- Case的强大用法
let age = 18
if case 10...19 = age, age == 18 {
print("he is a teenage and in a college.")
}
let vetor = (2, 3)
if case (let x, _) = vector, x > 1 && x < 5 {
print("This is a vector.")
}
for case let i in 1...100 where i % 3 == 0 {
// for i in 1...100 where i % 3 == 0 {
print(i)
}
- guard用法
func buy(money: Int, price: Int, capacity: Int, volume: Int) {
guard money >= price else { //确保一个条件为真
print("Not enough money!")
return
}
guard capacity >= volume else {
print("Not enough capacity!")
return
}
print("I can buy it.")
print("\(money - price) yuan left.")
print("\(capacity - volume) cubic meters left.")
}
- String
let greeting = "Guten Tag!"
jgreeting.count // 10 :元素的数量
for index in greeting.indices { //遍历字符串
print(greeting[index], terminator: "") // Guten Tag!
}
greeting[greeting.startIndex] // G
greeting[greeting.index(after: greeting.startIndex)] // u
greeting[greeting.index(before: greeting.endIndex)] // !
greeting[greeting.index(greeting.starIndex, offsetBy: 7)] // a
greeting[greeting.index(greeting.startIndex, offsetBy: 0)] // G
e.g:
var c = myFancyCollection([10, 20, 30, 40, 50])
var i = c.startIndex
while i != c.endIndex { //循环遍历每一个元素
c[i] /= 5
i = c.index(after: i)
}
// c == myFancyCollection([2, 4, 8, 10])
greeting.uppercased() //全部大写
greeting.lowercased() //全部小写
greeting.capitalized //全部首字母大写
greeting.contains("Gu") //字符串中是否有此子串
greeting.hasPrefix("Gu") //此字符串是否以此子串作为前缀
greeting.hasSuffix("g!") //此字符串是否以此子串作为后缀
let str = String.init(format: "one third is %.2f", 1.0/3.0) //one third is 0.33
网友评论