How to protect the initialization of property that could fail

My class has a type property NSURLthat is initialized from a string. The string is known at compile time.

In order for the class to work properly, it must be set to its intended value during initialization ( no later ), so it makes no sense to define it as optional (implicitly expanded or otherwise):

class TestClass: NSObject {

    private let myURL:NSURL

    ...

Assuming that NSURL(string:)(which returns NSURL?) it never crashes if a valid URL string is passed that is known at compile time, I can do something like this:

    override init() {

        myURL = NSURL(string: "http://www.google.com")!

        super.init()
    }

- - URL. :

    guard myURL = NSURL(string: "http://www.google.com") else {
        fatalError()
    }

"NSURL?" ; '!' '?'?

(: ! ? , . guard let... guard var..., myURL )

, : NSURL(string:) () NSURL, NSURL?, - myURL ( , as-is).

, :

    guard let theURL = NSURL(string: "http://www.google.com") else {
        fatalError()
    }

    myURL = theURL

... .

?

+4
1

. , guard, switch, Optional:

init?() {
    switch URL(string: "http://www.google.com") {
    case .none:
        myURL = NSURL()
        return nil
    case let .some(url):
        myURL = url
    }
}

url.


nil url, , . , - . guard.

init?() {

    guard let url = URL(string: "http:www.google.com") else {
        // need to set a dummy value due to a limitation of the Swift compiler
        myURL = URL()
        return nil
    }
    myURL = url

}

, , , , . NSObject, init (init?).

Swift blog, Apple SO.

+6

Source: https://habr.com/ru/post/1624384/


All Articles