声明变量或常量
用var定义变量,用let定义常量。
var myVariable = 42
myVariable = 50
let myConstant = 42
不指定类型变量或常量类型时,系统回自动推断变量或常量的类型。如果==myVariable==的类型会被推断为整型。
指定类型
指定类型时使用冒号。
let explicitDouble: Double = 70
类型转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
String(width)把整型转换为字符串。
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.”
\()把变量嵌入到字符串中.
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
"""多行嵌套字符串。
数组
创建数组,并按索引修改数组对应索引的值。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
字典
创建字典,并修改对应的值
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
定义空的数组和字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
控制流
使用if和switch做条件,使用for-in, while, 和 repeat-while做循环。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
可选值
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
表示optionalString可以是nil。
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
nickName ?? fullName:如果nickName为nil时,输出fullName,否则输出nickName。
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条件中必须要有==default==,否则编译报错。
for-in
for-in遍历字典,和数组。
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
0..<4:表示 0到4(不包括4)的一个范围
var total = 0
for i in 0..<4 {
total += i
}
print(total)
while和repeat-while
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
基本知识
声明变量或常量
用var定义变量,用let定义常量。
var myVariable = 42
myVariable = 50
let myConstant = 42
不指定类型变量或常量类型时,系统回自动推断变量或常量的类型。如果==myVariable==的类型会被推断为整型。
指定类型
指定类型时使用冒号。
let explicitDouble: Double = 70
类型转换
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
String(width)把整型转换为字符串。
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.”
\()把变量嵌入到字符串中.
let quotation = """
I said "I have \(apples) apples."
And then I said "I have \(apples + oranges) pieces of fruit."
"""
=="""==多行嵌套字符串。
数组
创建数组,并按索引修改数组对应索引的值。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
字典
创建字典,并修改对应的值
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
定义空的数组和字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
控制流
使用if和switch做条件,使用for-in, while, 和 repeat-while做循环。
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
可选值
var optionalString: String? = "Hello"
print(optionalString == nil)
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
表示optionalString可以是nil。
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
nickName ?? fullName:如果nickName为nil时,输出fullName,否则输出nickName。
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条件中必须要有==default==,否则编译报错。
for-in
for-in遍历字典,和数组。
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
0..<4:表示 0到4(不包括4)的一个范围
var total = 0
for i in 0..<4 {
total += i
}
print(total)
while和repeat-while
var n = 2
while n < 100 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
} while m < 100
print(m)
函数和闭包
使用==func==声明一个函数,->分开参数和返回值
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
使用_什么没有标签名的参数。
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
函数可以嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
函数也可以返回一个函数。
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
函数的参数也可以是函数
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
let re = hasAnyMatches(list: numbers, condition: lessThanTen)
闭包
闭包就是能够读取其他函数内部变量的函数,一般来说就是内部函数,也叫匿名函数。
在代码块{}中,用in分开函数体和参数,返回者
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
内部函数的参数类型,返回值类型,由于可以推断出来,所以可以省略掉。
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
甚至,可以使用$0,$1,...按顺序表示参数
let mappedNumbers = numbers.map{3 * $0}
print(mappedNumbers)
无戒365挑战营 48