聲明變量或常量
用var定義變量,用let定義常量。
var myVariable = 42
myVariable = 50
let myConstant = 42
不指定類型變量或常量類型時,系統(tǒng)回自動推斷變量或常量的類型。如果==myVariable==的類型會被推斷為整型。
指定類型
指定類型時使用冒號。
let explicitDouble: Double = 70
類型轉(zhuǎn)換
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
String(width)把整型轉(zhuǎn)換為字符串。
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."
"""
"""多行嵌套字符串。
數(shù)組
創(chuàng)建數(shù)組,并按索引修改數(shù)組對應(yīng)索引的值。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
字典
創(chuàng)建字典,并修改對應(yīng)的值
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
定義空的數(shù)組和字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
控制流
使用if和switch做條件,使用for-in, while, 和 repeat-while做循環(huán)。
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遍歷字典,和數(shù)組。
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
不指定類型變量或常量類型時,系統(tǒng)回自動推斷變量或常量的類型。如果==myVariable==的類型會被推斷為整型。
指定類型
指定類型時使用冒號。
let explicitDouble: Double = 70
類型轉(zhuǎn)換
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
String(width)把整型轉(zhuǎn)換為字符串。
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."
"""
=="""==多行嵌套字符串。
數(shù)組
創(chuàng)建數(shù)組,并按索引修改數(shù)組對應(yīng)索引的值。
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
字典
創(chuàng)建字典,并修改對應(yīng)的值
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
定義空的數(shù)組和字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
控制流
使用if和switch做條件,使用for-in, while, 和 repeat-while做循環(huán)。
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遍歷字典,和數(shù)組。
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)
函數(shù)和閉包
使用==func==聲明一個函數(shù),->分開參數(shù)和返回值
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet(person: "Bob", day: "Tuesday")
使用_什么沒有標(biāo)簽名的參數(shù)。
func greet(_ person: String, on day: String) -> String {
return "Hello \(person), today is \(day)."
}
greet("John", on: "Wednesday")
函數(shù)可以嵌套
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
函數(shù)也可以返回一個函數(shù)。
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
函數(shù)的參數(shù)也可以是函數(shù)
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)
閉包
閉包就是能夠讀取其他函數(shù)內(nèi)部變量的函數(shù),一般來說就是內(nèi)部函數(shù),也叫匿名函數(shù)。
在代碼塊{}中,用in分開函數(shù)體和參數(shù),返回者
numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
內(nèi)部函數(shù)的參數(shù)類型,返回值類型,由于可以推斷出來,所以可以省略掉。
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
甚至,可以使用$0,$1,...按順序表示參數(shù)
let mappedNumbers = numbers.map{3 * $0}
print(mappedNumbers)
無戒365挑戰(zhàn)營 48