Recently, I have read many tutorials and daishen’s blog during my study of Swift. Finally, I put my notes here for easy review
W3cschool -Swift tutorial, YungFan’s brief book (recommended to have a look, some knowledge summary is simply easy to understand)
1. Optional
1, the introduction
In layman’s terms, the option in Swift has to do with nil.
Since Swift is strongly typed, nil is also a special type, so data of other types cannot be directly assigned to nil
If you encounter a type that is not sure whether it has a value, you can use the optional option. The type can only take on two values: ni or have a definite value
2, format
Regular writing
var name: Optional<String>
Copy the code
Common grammar sugar writing
// Note: Between type and? Var name: String?Copy the code
3. Simple use
Assign a value to an optional type
// Declare an optional var STR: String? // set STR = "hello"Copy the code
The values
print(str) //Optional("hello")
Copy the code
Force unpack (!) The values
Print (STR!) //helloCopy the code
Enforce unpack security practices
if str ! = nil { print(str!) //hello }Copy the code
Implicit solution package
Print (newStr) //hello}else{print(" this value is nil")}Copy the code
Guard statement unpack
Let newStr = STR else{return} print(newStr)Copy the code
4. Application Scenarios
Accept urls with optional options to make your code more rigorous
// Use the optional type to receive let url: url? Let url1 = URL(string: "https://www.baidu.com") "https://www.baidu.com") // Create the request object from the URL: check whether there is a value before using the optional type // This syntax becomes optional binding (if the URL has a value, unpackage it to the tempURL and execute {}) if let tempUrl = url { let request = URLRequest(url: tempUrl) }Copy the code
5. Code examples
/* The nil optional flag is used in swift only for optional constants or variables: /* The nil optional flag is used in swift only for optional constants or variables: Nil: oc, indicating a pointer to a nonexistent object. Swift, indicating a special type, missing the value (not just the object type, but any type optional can be set to nil) */ var code: Int? = 100 code = nil /* var name: Int = 1000 name = nil Once we know that the alternative must have a value, in order to get that value, we add "!" after the alternative. */ var age: Int? \(age!) = 18 print(" ")Copy the code
Two, optional chain
1, the introduction
Optional Chaining is a procedure by which attributes, methods, and subscripts can be requested and invoked with a possible nil target for the request or invocation.
The optional chain returns two values:
- If the target has a value, the call succeeds, returning that value
- If the target is nil, the call will return nil
Multiple requests or calls can be linked into a chain, and if any node is nil the whole chain will fail.
2, use,
By placing a question mark (?) after the optional value of a property, method, or subscript. To define an optional chain.
2.1 Optional chain can replace forced parsing
Use optional chain ‘? ‘:’? ‘after the optional value to call methods, properties, subscripts, and output a friendly error message when the optional is nil
Using forced parsing ‘! ‘:’! ‘after the optional value to call methods, properties, subscripts, used to force the value to expand, force expansion will perform an error if the optional is nil
Code examples:
class Residence { var numberOfRooms = 1 } class Person { var residence: Residence? } let john = Person() // ! Will result in runtime errors: Fatal error: Unexpectedly found nil while unwrapping an Optional value (Fatal error: Unexpectedly found nil while unwrapping an Optional value) Let roomCount = John.residence! NumberOfRooms / /? Link optional residence? Property to retrieve the value of numberOfRooms if let roomCount = John.residence? NumberOfRooms {print("John's room number is \(roomCount)." } else {print(" cannot view room number ")} Print: cannot view room numberCopy the code
2.2 Optional chain invocation
First, four classes are defined, containing a multi-layer optional chain
Class Person {var residence: residence? } class Residence {// defines a variable rooms, which is initialized to an empty array of type Room[] var rooms = [Room]() var numberOfRooms: Int { return rooms.count } subscript(i: Int) -> Room {return rooms[I]} func printNumberOfRooms() {print(" Room number = \(numberOfRooms)")} var address: address? } class Room {let name: String init(name: String) {self.name = name}} // The final class in the model is called Address class Address {// buildingName: Var buildingNumber: String? String? func buildingIdentifier() -> String? { if (buildingName ! = nil) { return buildingName } else if (buildingNumber ! = nil) { return buildingNumber } else { return nil } } }Copy the code
2.2.1 Calling a method through an optional chain
let john = Person() if john.residence? .printNumberOfRooms() ! = nil {print(" print room number ")} else {print(" print room number ")} Print: cannot print room numberCopy the code
2.2.2 Invoke subscript through optional chain
We can get the value of the subscript through the optional chain, but we cannot set the subscript through the optional chain
Let John = Person() // The reason for this location is that john.residence is the optional value that the optional chain is trying to get if let firstRoomName = John.residence? [0].name {print(" firstRoomName \(firstRoomName).")} else {print(" firstRoomName \(firstRoomName) ")}Copy the code
Let’s give John a value
let john = Person() let johnsHouse = Residence() johnsHouse.rooms.append(Room(name: Append (Room(name: "Kitchen")) John residence = johnsHouse let johnsAddress = Address () johnsAddress. BuildingName = "A123" johnsAddress. Street = "A123 Street" john.residence! .address = johnsAddress // If let firstRoomName = john.residence? [0].name {print(" firstRoomName ")} else {print(" firstRoomName ")} // print: If let johnsStreet = John.residence?.address?. Street {print("John's street is \(johnsStreet)." } else {print(" Unable to retrieve address. ")} // Print: John's Street is A123 StreetCopy the code