My class has a property of type NSURL
that is initialized from a string. The string is known at compile time.
For the class to operate appropriately, it must be set to its intended value at initialization (not later), so there is no point in defining it as an optional (implicitly unwrapped or otherwise):
class TestClass: NSObject {
private let myURL:NSURL
...
Assuming that NSURL(string:)
(which returns NSURL?
) will never fail if passed a valid URL string that is known at compile time, I can do something like this:
override init() {
myURL = NSURL(string: "http://www.google.com")!
super.init()
}
However, I somehow don't feel comfortable around the forced unwrapping and would like to guard the URL initialization somehow. If I try this:
guard myURL = NSURL(string: "http://www.google.com") else {
fatalError()
}
Value of optional type 'NSURL?' not unwrapped; did you mean to use '!' or '?'?
(Note: there's no way to add a !
or ?
anywhere the code above that will fix the error. Conditional unwrapping only happens with guard let...
guard var...
, and myURL
is already defined)
I understand why this fails: Even a successful call to NSURL(string:)
is returning the (valid) NSURL
wrapped inside an optional NSURL?
, so I still need to unwrap it somehow before assigning to myURL
(which is non-optional, hence not compatible for assignment as-is).
I can get around this by using an intermediate variable:
guard let theURL = NSURL(string: "http://www.google.com") else {
fatalError()
}
myURL = theURL
...but this is obviously not elegant at all.
What should I do?