[Swift] Perform error handling with Optional <Wrapped> type

For error handling, in addition to processing using ** Optional \ type ** There are also processing using ** Result \ <Success, Failure> type ** and ** do-catch statement **.

To be honest, I'm not good at error handling because I don't understand it well.

However, because it is an absolutely necessary process for writing code ** I hope I can share the memorandum with everyone.

Error handling by Optional \ type

As you may know, the Optional \ type is You can express ** whether the value exists **.

The Optional \ type allows nil, so Returns the stored value if it exists, nil if it does not exist.

When using for error handling ** If the existence of the value is regarded as success / the absence of the value is regarded as failure **, It is a story that it works as an error handling mechanism.

This seems pretty easy!

Implementation method

For example, if the function is error-prone Error handling can be performed by setting the return value to Optional \ type.

In the sample code below If there is an instance corresponding to the id of the argument, that instance is returned. If not, nil is returned.


struct User {
    var id: Int
    var name: String
}

//Instantiation
let user1 = User(id: 1, name: "Tarou")
let user2 = User(id: 2, name: "Zirou")

//Store instances in an array
var users = [user1, user2]

//Functions that can cause errors
//Returns nil if there is no corresponding id of the argument
func findUserById(id: Int) -> User? {
    for user in users {
        if user.id == id {
            return user
        }
    }
    return nil
}

//If the value exists
if let user = findUserById(id: 1) {
    print(user.name)
} else {
    print("Error: User not found")
}

//If the value does not exist
if let user = findUserById(id: 3) {
    print(user.name)
} else {
    print("Error: User not found")
}

Execution result
Tarou
Error: User not found

An example of using the Optional \ type for success or failure of processing is Others include the ** Failable Initializer **.

In the following sample code If the argument email address cannot be split in two The instantiation is failing because it is regarded as invalid data.

The item of let item = mail.split (separator:" @ ") is It is an array that stores the two values ​​when mail is divided into two.


struct User {
    var name: String
    var mail: String
    
    init?(name: String, mail: String) {
        let item = mail.split(separator: "@")
        guard item.count == 2 else {
            return nil
        }
        self.name = name
        self.mail = mail
    }
}

let user1 = User(name: "Tarou", mail: "[email protected]")
let user2 = User(name: "Zirou", mail: "Zirou.com")

var users = [user1, user2]

for user in users {
    if let user = user {
        print("Name: \(user.name)\nMail: \(user.mail)")
    } else {
        print("Error: Invalid data")
    }
}

Execution result
Name: Tarou
Mail: [email protected]
Error: Invalid data

Timing to use

The timing to use it is when the result can be sufficiently expressed only by the presence or absence of the ** value. ** **

As before, when searching for a match by id Simple things like checking if the email address format is correct I think the Optional \ type is fine!

However, when searching for id, I could not connect to the database It's probably difficult to ** increase the types of errors **, such as when data is duplicated.

So you can display a message depending on the cause of the failure Optional \ type is not enough if you want to perform recovery process!

In conclusion, let's make the Optional \ type only a simple case!

Also, I introduced at the beginning, Processing using ** Result \ <Success, Failure> type ** and ** do-catch statement **, I plan to write a separate article, so please have a look!

-[Swift] Perform error handling with Result \ <Success, Failure> type -[Swift] Perform error handling with do-catch statement (Part 1) -[Swift] Termination of program by fatalError function[Swift] End of program by assertion

Thank you for watching until the end.

Recommended Posts

[Swift] Perform error handling with Optional <Wrapped> type
[Swift] Perform error handling with do-catch statement (Part 3)
[Swift] Perform error handling with do-catch statement (Part 2)
[Swift] Perform error handling with do-catch statement (Part 1)
[Swift] Perform error processing with Result <Success, Failure> type
[Swift] Error handling
Compare Java 8 Optional with Swift
Let's understand the Optional (Wrapped) type!
No qualifying bean of type error handling
[Swift / For beginners] Write smartly with type inference
error code 400 appears when deploying with release: perform
[Swift] Type type ~ Enumeration type ~
Java Optional type
[Swift] Type type ~ Structure ~