Add extension for Optional

extension Optional where Wrapped == String { var safeValue: String { return self ?? "" } } var name: String? = "Swift" print(name ?? "") name = nil print(name!) // Crash print(name.safevalue) does not need to be unpackedCopy the code

Advantages: No unpacking is required, thus reducing code problems caused by forced unpacking.

Add unit tests for Optional

XCTUnwrap(::file:line:) : If the expression is nil, the test fails; If it is not nil, the test succeeds and the unpacked value is returned.

func testNameValue() throws {
    let name: String? = "Swift"
    let unwrappedTitle = try XCTUnwrap(name, "Title should be set")
    XCTAssertEqual(unwrappedTitle, "Swift")
}
Copy the code

Optional Protocol

Implement optional Protocol through Extension.

protocol Eat {
    func eatFish()
    func eatApple() //Optional
}

extension Eat {
    func eatApple() { }
}

struct Cat: Eat {
    func eatFish() {
        print("Dog eat fish")
    }
}
Copy the code

Avoid embedded Optional

Optional can be used repeatedly, as in the following code:

var name: String?? 🤣 print(name!!)Copy the code

Here’s a more likely way to use it:

let nameAndVersion: [String:Int?]  = ["Swift": 5] let swiftVersion = nameAndVersion["Swift"] print(swiftVersion) // Optional(Optional(5)) print(swiftVersion!) // Optional(5) print(swiftVersion!!) / / 5Copy the code

We should try to avoid similar uses as above.