String and character
1. The significance of
-
A String is a collection of characters, whereas the implementation of String in Swift is fast and modern. Each string is composed of encoding independent Unicode characters and supports access to multiple Unicode representations of characters.
-
Swift’s String type Bridges seamlessly with the Foundation NSString class. Foundation also extends String to access methods defined in the NSString type. That means that when you call those NSString methods, you don’t have to do any type casting.
String literals
- A string literal is a set of characters in a fixed order surrounded by a pair of double quotes
3. Special characters for string literals
-
Escape character \ 0 (null character), \ (backslash), \ t tabs (level), (newline), \ r \ n (carriage return), “(double quotes), the ‘(single quotation marks).
-
Unicode scalar, written as \u{n}(u is lowercase), where n is any one to eight hexadecimal number and available Unicode bitcode.
4. String variability
- You can modify a particular string by assigning it to a variable, or assign it to a constant to ensure that it will not be modified
- In Objective-C and Cocoa, you specify whether a string can be modified by selecting two different classes (NSString and NSMutableString).
Strings are value types
String interpolation
- String interpolation is a way of constructing new strings that can contain constants, variables, literals, and expressions
Multiplier = 1 let message = "multipliers "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5) 7.5"Copy the code
String index
- Use the startIndex property to get the index of the first Character of a String. Use the endIndex property to get the index after the last Character. Therefore, the endIndex attribute cannot be used as a valid index for a string. If String is empty, startIndex and endIndex are equal.
Set types
1. Collection types
- Swift provides three basic collection types: Array, Set and Dictionary to store collection data. An array is an ordered set of data. A set is an unordered set with no duplicate data. A dictionary is an unordered set of key-value pairs.
2, arrays,
- Arrays use ordered lists to store multiple values of the same type. The same value can appear multiple times in different places in an array.
- Creates an array with default values
Var threeDoubles = Array(repeating: 0.0, count: 3) // threeDoubles is a [Double] Array, equivalent to [0.0, 0.0, 0.0]Copy the code
-
Construct arrays with array literals
Var shoppingList: [String] = ["Eggs", "Milk"] // The shoppingList is constructed and has two initial items.Copy the code
3. Set
- Collections are used to store values of the same type in an undefined order. You can use collections instead of arrays when the order of collection elements is not important or when you want to ensure that each element appears only once.
- Creates and constructs an empty collection
Var letters = Set<Character>() print(" Letters is of type Set<Character> with \(letters.count) items." Of type Set<Character> with 0 items."Copy the code
- Create collections with array literals
Var favoriteGenres: Set<String> = ["Rock", "Classical", "Hip hop"] // favoriteGenres are constructed into a Set of three initial values Set = ["Rock", "Classical", "Hip hop"]Copy the code
- Basic set operation
- Use the intersection(_:) method to create a new collection from the intersection of two collections.
- Use the symmetricDifference(_:) method to create a new collection based on the disjoint values of the two collections.
- Use the union(_:) method to create a new collection based on all the values of both collections.
- Use the subtracting(_:) method to create a new collection based on values that are not in another collection.
let oddDigits: Set = [1, 3, 5, 7, 9] let evenDigits: Set = [0, 2, 4, 6, 8] let singleDigitPrimeNumbers: Set = [2, 3, 5, 7] oddDigits.union(evenDigits).sorted() // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] oddDigits.intersection(evenDigits).sorted() // [] oddDigits.subtracting(singleDigitPrimeNumbers).sorted() // [1, 9] oddDigits.symmetricDifference(singleDigitPrimeNumbers).sorted() // [1, 2, 9] let houseAnimals: The Set = [" 🐶 🐱 ", ""] let farmAnimals: Set = [" 🐮", "🐔", "🐑", "🐶", "🐱"] let cityAnimals: Set = ["🐦", "🐭"] houseAnimals. IsSubset (of: farmAnimals) houseAnimals) // true farmAnimals.isDisjoint(with: cityAnimals) // trueCopy the code
4, the dictionary
- A dictionary is an unordered collection that stores the relationships between key-value pairs. All the key values need to be of the same type, and all the values need to be of the same type. Each value is associated with a unique key, which acts as an identifier for the value data in the dictionary. Unlike the items in an array, the items in a dictionary have no specific order.
- Create a dictionary with a dictionary literal
var airports: [String: String] = ["YYZ": "Toronto Pearson", "DUB": "Dublin"]
Copy the code
- Create an empty dictionary
Var namesOfIntegers = [Int: String]() // namesOfIntegers is an empty [Int: String] dictionaryCopy the code
Fourth, control flow
1. For-in loops
let names = ["Anna", "Alex", "Brian", "Jack"] for name in names { print("Hello, \(name)!" ) } // Hello, Anna! // Hello, Alex! // Hello, Brian! // Hello, Jack! // If you do not need the value of each item in the interval sequence, you can ignore the value by using the underscore (_) instead of the variable name: let base = 3 let power = 10 var answer = 1 for _ in 1... Power {answer *= base} print("\(base) to the power of \(power) is \(answer)") // output "3 to the power of 10 is 59049"Copy the code
2. While loop
-
While loop, each time at the beginning of the loop to evaluate whether the condition is met;
-
A repeat-while loop (similar to the do-while in OC) computs whether the condition is met at the end of the loop each time.
3. Conditional statements
-
Swift provides two types of conditional statements: if statements and switch statements. In general, if statements are used when conditions are simple and the number of possible cases is small. The switch statement is more suitable for more complex conditions with more permutations and combinations. And switch is more useful in cases where pattern-matching is needed.
-
Value Bindings: Case branches allow matching values to be declared as temporary constants or variables and used inside the case branch — this behavior is called value binding because the matched value is inside the case branch, Let anotherPoint = (2, 0) switch anotherPoint {case (let x, 0): print(“on the x-axis with an x value of (x)”) case (0, let y): print(“on the y-axis with a y value of (y)”) case let (x, y): Print (” Somewhere else at ((x), (y))”)} on the X-axis with an x value of 2
// The pattern of the case branch can use the WHERE statement to determine additional conditions. let yetAnotherPoint = (1, -1) switch yetAnotherPoint { case let (x, y) where x == y: print("(\(x), \(y)) is on the line x == y") case let (x, y) where x == -y: print("(\(x), \(y)) is on the line x == -y") case let (x, y): Print ("(\(x), \(y)) is just some arbitrary point")} "(1, -1) is on the line x == -y"Copy the code
4. Control the transfer statement
- Continue: Tells a loop body to stop this loop immediately and start the next loop again
- Break: Immediately ends the execution of the entire control flow
- Fallthrough: The fallthrough keyword does not check for matches that will fall into the next case to be executed. Fallthrough simply makes code continue to connect to code in the next case, which is the same switch statement feature in the C language standard.
- return
- throw
5. Quit early
-
A GUARD statement always has an else clause, and if the condition is not true the code in the else clause is executed. func greet(person: [String: String]) { guard let name = person[“name”] else { return }
print("Hello \(name)!" ) guard let location = person["location"] else { print("I hope the weather is nice near you.") return } print("I hope The weather is nice in \(location).")} greet(person: ["name": "John"]) // "I hope the weather is nice near you." greet(person: ["name": "Jane", "location": "Cupertino"]) // Output "I hope the weather is nice in Cupertino."Copy the code
Five, the function
1. Function definition and call
- When you define a function, you can define one or more values with names and types as input to the function, called parameters, or values of some type as output at the end of the function, called return types.
- Each function has a function name that describes the task it performs. When you want to use a function, you “call” the function by its name and pass it the matching input values (called arguments). The arguments to a function must be in the same order as the arguments in the function argument list.
Function parameters and return values
- Parametric function
- Multiparameter function
- No return value function
- Multiple return value functions
// Find the minimum and maximum value in an array of type Int. func minMax(array: [Int]) -> (min: Int, max: Int) { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count] { if value < currentMin { currentMin = value } else if value > currentMax { currentMax = value } } return (currentMin, currentMax) }Copy the code
- Optional tuple return type
- Optional tuple types such as (Int, Int)? And tuples contain optional types such as (Int? , Int?) It’s different. Optional tuple type. The entire tuple is optional, not just the value of each element in the tuple.
- A function that returns implicitly
- Reture can be omitted
3. Function parameter label and parameter name
- Each function argument has an argument label and a parameter name. Parameter tags are used when calling functions; The parameter label of the function must be written in front of the corresponding parameter. Parameter names are used in the implementation of functions. By default, function parameters use parameter names as their parameter labels.
func someFunction(firstParameterName: Int, secondParameterName: } someFunction(firstParameterName) {firstParameterName (firstParameterName) {firstParameterName (firstParameterName) {firstParameterName (firstParameterName); 1, secondParameterName: 2) - Inout func swapTwoInts(_ a: inout Int, _ b: inout Int) { let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherint) print("someInt is now \(someInt), and anotherInt is now \(anotherInt)") And anotherInt is now 3"Copy the code
4. Function types
- Each function has a specific function type, which consists of the parameter type and return type of the function.
- In Swift, function types are used just like any other type. For example, you can define a constant or variable of type function and assign the appropriate function to it: var mathFunction: (Int, Int) -> Int = addTwoInts
- Function types as parameter types
- You can use a function type like (Int, Int) -> Int as an argument type to another function
func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { print("Result: \(mathFunction(a, b))")} printMathResult(addTwoInts, 3, 5)Copy the code
- Function type as return type
- You can use a function type as the return type of another function. All you need to do is write a full function type after the return arrow (->)
func stepForward(_ input: Int) -> Int { return input + 1 } func stepBackward(_ input: Int) -> Int { return input - 1 } func chooseStepFunction(backward: Bool) -> (Int) -> Int { return backward ? stepBackward : stepForward } var currentValue = 3 let moveNearerToZero = chooseStepFunction(backward: CurrentValue > 0) // moveNearerToZero now points to the stepBackward() function. print(moveNearerToZero(1)) //0Copy the code
5. Nested functions
- Defined functions in another function body, called nested functions
func chooseStepFunction(backward: Bool) -> (Int) -> Int { func stepForward(input: Int) -> Int { return input + 1 } func stepBackward(input: Int) -> Int { return input - 1 } return backward ? stepBackward : stepForward } var currentValue = -4 let moveNearerToZero = chooseStepFunction(backward: currentValue > 0) // moveNearerToZero now refers to the nested stepForward() function while currentValue ! = 0 { print("\(currentValue)... ") currentValue = moveNearerToZero(currentValue) } print("zero!" ) / / - 4... / / - 3... / / - 2... / / - 1... // zero!Copy the code