قالب وردپرس درنا توس
Home / IOS Development / From opportunities to mistakes

From opportunities to mistakes



When working with optional values, it is common to look for null using a guard statement. In cases where the value is not present, this results in an early exit. By using an example from our recently published Swift Talk backend, we often write code that casts an error in null the case:

  guard give gift = g else {
throw ServerError (privateMessage: "No such gift")
}
// ... the rest of the code that uses "gift"

There are many reasons why we can enter a value null ; For example, the user may enter an invalid URL or the database connection may fail. When we meet zero we leave the happy path and have to leave early.

Since this pattern repeats itself in several places throughout the code base, we can write an extension on Optional which abstracts this pattern away:

  extension Optional {
func or (_ err: Error) throws -> Wrapped {
guard la value = confidence else {
make a mistake
}
return value
}
}

Using this extension we can write our first example like this:

  la gift = g.or (ServerError (privateMessage: "No such gift"))

We can also choose to use a custom operator, which can stand out more when you read the code:

  infix operator?!: NilCoalescingPrecedence
public func ?!  (lhs: A?, Rhs: Error) throws -> A {
guard let value = lhs other {
throw rhs
}
return value
}

NilCoalescingPrecedence group indicates that our new operator has the same precedence as ? .

With this operator, the example now looks like this:

  leave gift = g ?! ServerError (privateMessage: "No such gift")

We find that small abstractions of common patterns can remove some of the noise from our code, making it more readable everywhere.

For those cases where you care less about the specific error message, try making a postfix operator

To learn more about our Swift Talk backend, see the first episode of our latest series or check full source code on GitHub.

Our book, Advanced Swift, discusses options and troubleshooting in more depth. We are preparing an update for Swift 5, free for all Ebook readers.


Source link