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

Objective-C bridging #22

Closed
maxsz opened this issue Nov 17, 2016 · 5 comments
Closed

Objective-C bridging #22

maxsz opened this issue Nov 17, 2016 · 5 comments

Comments

@maxsz
Copy link
Contributor

maxsz commented Nov 17, 2016

I'd like to partly re-open the discussion on #1 🙈

I understand that it makes the most sense to create a new codegen target for an Objective-C only environment instead of crippling the beautiful Swift version. One thing we came across though, is the need to have some kind of Objective-C bridging. I guess other projects, at least older ones, will come across this, too.

The goal is to write most part in Swift, but there are still some parts of the code/UI that are too costly to rewrite and that need data from the backend.

One general solution to expose model objects to Objective-C code would be to pass dictionaries, instead of the generated GraphQLNamedFragment structs to @objc functions:

extension GraphQLNamedFragment {
  func dictionary() -> [String:Any]? {
    // Note: this would be simpler, if the parsed dictionary would be kept/exposed
    return try? wrap(self) // See: https://github.com/JohnSundell/Wrap
  }
}

// Function that can be called from Objective-C with a result of Array<Dictionary<String,Any>> instead of `struct User: GraphQLNamedFragment`
@objc
func fetchUsers(accessToken: String, completion: @escaping (([[String:Any]]?, NSError?) ->())) {
  _ = client.fetchUsers(dematerializeResult(completion)) // Swift-only function returning Users struct
}

// Call `completion` with `User struct` converted to dictionary.
private
func dematerializeResult<T: GraphQLNamedFragment, E: Error>(
  _ completion: @escaping (([[String:Any]]?, NSError?) ->())
) -> ((Result<[T], E>) -> ()) {
  return { (result: Result<[T], E>) in
    switch result {
      case .success(let value): completion(value.flatMap({ $0.dictionary() }), nil)
      case .failure(let error): completion(nil, error as NSError?)
    }
  }
}

This has a few downsides. One of them is that any type-safety and compile-time guarantees are completely lost.

Another one would be also generate Objective-C compatible model classes that can be initialized with the GraphQLNamedFragment structs.

public struct UserDetails: GraphQLNamedFragment {
  // [...]
  public let name: String
  // [...]
}

public class UserDetailsObjc: NSObject {
  public let name: String
  public init(userDetails: UserDetails) {
    name = userDetails.name
  }
}

Let's discuss 🎱

@martijnwalraven
Copy link
Contributor

Happy to re-open discussion, because actual use cases and proposals are exactly what we need.

@KieranLafferty has been working on an apollo-codegen Objective-C target.

We haven't thought about how this interacts with the runtime and which parts of the Swift code we can reuse however, and mixed language environments seem like a good use case to keep in mind.

I would definitely be in favor of a bridging solution, where we can reuse most of the runtime code and also share a single cache between languages.

Passing dictionaries seems like the easiest option. Using a reflection-based library like Wrap works, but we may be able to do better by having the generated GraphQLMappable types expose a dictionary method (similar to how input objects currently expose graphQLMap).

Of course, typed model classes would be a lot nicer. And if we can have them initialize themselves from the corresponding GraphQLMappable (like the GraphQLNamedFragment in your example) they won't have to contain much logic.

The benefit of this over a stand-alone Objective-C implementation is that result parsing relies on Swift typing magic, so keeping that in Swift and then bridging to Objective-C on demand means we don't have to reimplement this.

I'm also wondering if there is anything we can do to make bridging transparent by using _ObjectiveCBridgeable, similar to how other value types are bridged in Swift 3.

@maxsz
Copy link
Contributor Author

maxsz commented Nov 18, 2016

I only included the dictionary example as a simple, hacky workaround that one can actually use now to have a general way of exposing . I think it's not the right way to go forward. Exposing the dictionary on GraphQLMappable enables or even encourages unsafe usage of the API.

The proposal for ObjectiveCBridgeable is really awesome, very unfortunate that it is currently deferred. But, quoting the authors of the proposal:

For framework and library authors it presents an awful choice:

  1. Write mountains of glue code to convert between Swift and Objective-C versions of your types.
  2. Write your shiny new framework in Swift, but in an Objective-C style using only @objc types.
  3. Write your shiny new framework in Objective-C.

Choice #1 is not practical in the real world with ship dates, resulting in most teams choosing #2 or #3.

I think that their conclusion (choice 1 being impractical) is not completely relevant in our case, as we have the option to generate that code.

@martijnwalraven
Copy link
Contributor

martijnwalraven commented Nov 18, 2016

Although it is private and not well documented, it seems you should be able to use _ObjectiveCBridgeable to bridge Swift structs and Objective-C classes even in the current Swift version (see this post for example).

@Ewg777
Copy link

Ewg777 commented Sep 21, 2018

Happy to re-open discussion, because actual use cases and proposals are exactly what we need.

@KieranLafferty has been working on an apollo-codegen Objective-C target.

@KieranLafferty any update?

@designatednerd
Copy link
Contributor

Just as a heads up: Given that it's been a few years and Swift has finally reached ABI stability (and module stability when 5.1 lands), we've officially decided not to move forward with Objective-C code generation on our end. You're definitely welcome to work on it on your own, but at this point it's just not on the priority list for Apollo directly.

Thanks very much for your patience, and sorry we weren't able to help here. I'm going to close this issue out.

BobaFetters pushed a commit that referenced this issue Nov 2, 2023
Co-authored-by: Anthony Miller <anthonymdev@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants