For error handling, in addition to processing using ** Optional \
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.
As you may know, the Optional \
The Optional \
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!
For example, if the function is error-prone
Error handling can be performed by setting the return value to Optional \
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 \
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
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 \
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 \
In conclusion, let's make the Optional \
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