一.swift是啥?答:百度。
二.swift基础知识。
1.输出函数:print
print("Hello, world!")
2.简单数据类型
变量声明:var
常量声明:let
var myVariable =
myVariable =
let myConstant =
如果没有变量或者常量的类型(如下1、2行),定义的变量或者常量的类型是在第一次赋值时自动判定的。
如果声明了类型(如下第3行),则必须赋值指定类型。
let implicitInteger =
let implicitDouble = 70.0
let explicitDouble: Double = 70
变量转换:
let label = "The width is "
let width =
let widthLabel = label + String(width)
字符串拼接
字符串插入变量方法:\()
将变量放入括号里面就ok了
let apples =
let oranges =
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
数组和字典:
数组和字典对象都放在 [] 里面,用 ","分隔,并且最后一个对象后面可以加 逗号。
创建有对象的字典和数组:
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[] = "bottle of water" var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
创建空数组和字典:
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
或者
shoppingList = []
occupations = [:]
3.控制流(Control Flow)
条件控制:if 和 switch
循环控制:for-in,for,while 和 repeat-while
用于条件判断的语句的圆括号是可选的。
for-in:
let individualScores = [, , , , ]
var teamScore =
for score in individualScores {
if score > {
teamScore +=
} else {
teamScore +=
}
}
print(teamScore)
if:
var optionalString: String? = "Hello"
print(optionalString == nil) var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
类型后面加“?”表示 可选类型(optional value)。
if 和 let 一起使用判断值是否为nil,如果是nil,那么就会跳过这个模块。
使用 if let 可以操作可选类型。
?,??:
?? 后面是 默认值
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
使用 ?? 也可以操作可选类型。如果 可选类型值为nil 那么就使用 ?? 后面的默认值。
switch:
switch 支持多种类型的数据类型和比较运算。 不仅仅数值类型和相等判断。
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
程序执行完 switch 的某个 case 后,会跳出switch,无需添加 break。
for-in:
for-in 遍历字典:
let interestingNumbers = [
"Prime": [, , , , , ],
"Fibonacci": [, , , , , ],
"Square": [, , , , ],
]
var largest =
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
while 和 repeat-while:
var n =
while n < {
n *=
}
print(n) var m =
repeat {
m *=
} while m <
print(m)
..< 和 ...
循环起止边界判断,使用 ..< 是包含最小值而不包含最大值。使用 ... 是最小值和最大值都包含。
var total =
for i in ..< {
total += i
}
print(total)