Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[swift2objc] Support failable initializers #1734

Merged
merged 2 commits into from
Nov 19, 2024
Merged

[swift2objc] Support failable initializers #1734

merged 2 commits into from
Nov 19, 2024

Conversation

liamappelbe
Copy link
Contributor

A failable initializer in Swift is an initializer that can return nil:

public class MyClass {
    public let someInt: Int

    public init?(outerLabel x: Int) {
        if x == 0 {
            return nil
        } else {
            self.someInt = x
        }
    }
}

They show up in the symbolgraph with a ?( token in their second fragment instead of a (:

"declarationFragments": [
    {
        "kind": "keyword",
        "spelling": "init"
    },
    {
        "kind": "text",
        "spelling": "?("
    },

When wrapping these constructors, we have to declare the wrapper initializer as failable, and check if the wrapped initializer returned nil.

@objc public class MyClassWrapper: NSObject {
  var wrappedInstance: MyClass

  @objc init?(outerLabel x: Int) {
    if let instance = MyClass(outerLabel: x) {
      wrappedInstance = instance
    } else {
      return nil
    }
  }
}

@coveralls
Copy link

Coverage Status

coverage: 90.197% (+0.002%) from 90.195%
when pulling 82f41c5 on failinit
into 8165cbb on main.

@liamappelbe liamappelbe merged commit b2aca7e into main Nov 19, 2024
6 checks passed
@liamappelbe liamappelbe deleted the failinit branch November 19, 2024 22:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants