title: Convenience Failable Initializers assign self
body: <p>I'm trying to write a initializer for NSURL which can throw on failure.</p>
  
  <p>I would very much like it to look like <a href="https://developer.apple.com/swift/blog/?id=17" rel="nofollow">this</a>.</p>
  
  <pre><code>extension NSURL {
      convenience init?(string: String, throwOnNil: Bool) throws {
          if let URL = NSURL(string: string) {
              self = URL
          } else if throwOnNil {
              throw MyURLError(string: string)
          } else {
              return nil
          }
      }
  }
  </code></pre>
  
  <p><strike>But that syntax is no longer supported: <code>error: cannot assign to value: 'self' is immutable</code>.</strike></p>
  
  <p><em>That syntax only works for struct and enum.</em></p>
  
  <p>Here is the only thing I've come up with</p>
  
  <pre><code>extension NSURL {
      convenience init?(string: String, throwOnNil: Bool) throws {
          if throwOnNil &amp;&amp; NSURL(string: string) == nil {
              throw MyURLError(string: string)
          }
  
          self.init(string: string)
      }
  }
  </code></pre>
  
  <p>Which constructs the URL twice.</p>
  
  <p><strong><em>HELP!</em></strong> There must be a better approach that I'm not finding.</p>
  
  <hr>
  
  <p><strong>UPDATE</strong></p>
  
  <p>It turns out that self assignment in an initializer works for structs and enums but not for classes. The example I was basing my ideal code from was a struct.</p>