Basic knowledge
Declare variables or constants
Variables are defined with var and constants are defined with let.
var myVariable = 42 myVariable = 50 let myConstant = 42
When the type variable or constant type is not specified, the system automatically infers the type of the variable or constant. If the type==myVariable=== is inferred as an integer.
Specified type
Use a colon when specifying a type.
let explicitDouble: Double = 70
Type conversion
let label = "The width is " let width = 94 let widthLabel = label + String(width)
String(width) converts an integer to a string.
let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit."
\ () Embedding variables into strings.
let quotation = """ I said "I have \(apples) apples." And then I said "I have \(apples + oranges) pieces of fruit." """
== ""== Multi-line nested string.
array
Create an array and modify the value of the corresponding index of the array by index.
var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water"
Dictionaries
Create a dictionary and modify the corresponding values
var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations"
Define empty arrays and dictionaries
let emptyArray = [String]() let emptyDictionary = [String: Float]()
control flow
Use if and switch as conditions, use for-in, while, and repeat-while as loops.
let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } print(teamScore)
Optional value
var optionalString: String? = "Hello" print(optionalString == nil) var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }
Represents that optionalString can be nil.
let nickName: String? = nil let fullName: String = "John Appleseed" let informalGreeting = "Hi \(nickName ?? fullName)"
NickName?? fullName: If nickName is nil, output fullName, otherwise output 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.") }
The case condition of switch must have=== default===, otherwise compile error.
for-in
for-in traverses dictionaries, and arrays.
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: A range of 0 to 4 (excluding 4)
var total = 0 for i in 0..<4 { total += i } print(total)
While and repeat-while
var n = 2 while n < 100 { n *= 2 } print(n) var m = 2 repeat { m *= 2 } while m < 100 print(m)
Functions and Closures
Declare a function with == func ==, -> separate parameters and return values
func greet(person: String, day: String) -> String { return "Hello \(person), today is \(day)." } greet(person: "Bob", day: "Tuesday")
Use what parameters have no label name.
func greet(_ person: String, on day: String) -> String { return "Hello \(person), today is \(day)." } greet("John", on: "Wednesday")
Functions can be nested
func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen()
Functions can also return a function.
func makeIncrementer() -> ((Int) -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7)
The parameters of a function can also be functions.
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)
closure
Closures are functions that can read the internal variables of other functions. Generally speaking, they are internal functions, also known as anonymous functions.
In the code block {}, the function body and parameters are separated by in, and the returner
numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
The parameter type and return value type of the internal function can be omitted because they can be inferred.
let mappedNumbers = numbers.map({ number in 3 * number }) print(mappedNumbers)
Even, you can use $0, $1,... To represent parameters in sequence.
let mappedNumbers = numbers.map{3 * $0} print(mappedNumbers)