How can I use Realm with Swift 4?

2019-02-16 14:02发布

问题:

I'm trying to run my current project in the new Xcode 9 beta, but when I do so it says Module compiled with Swift 3.1 cannot be imported in Swift 4.0. How can I solve this problem? I'm not using cocoapods.

回答1:

Update: As of v2.10.1, released 2017-09-14, Realm's prebuilt binaries include frameworks built with Xcode 9 for Swift 3.2 and 4.0. It's no longer necessary to build them yourself.

The information below remains relevant to anyone looking to use Realm with prerelease versions of Xcode in the future.


If you're currently integrating Realm's prebuilt binaries, you'll need to switch to building Realm from source in order to support Swift 3.2 and 4.0, as Realm does not publish prebuilt binaries for prerelease versions of Xcode. You can build Realm from source in one of three ways:

  1. Using CocoaPods.

    CocoaPods always builds dependencies from source.

  2. Using Carthage.

    By default Carthage will attempt to download prebuilt binaries, but will fall back to building from source if the prebuilt binaries are for a different Swift version than the version of Xcode in use.

  3. Build Realm manually from source, and then integrate the built frameworks as you would the prebuilt binaries that Realm provides.

    You can do this by checking out a release tag from Git:

    git clone --recursive https://github.com/realm/realm-cocoa.git
    cd realm-cocoa
    git checkout v2.10.0
    

    Then run whichever of the following commands corresponds to the platform you care about to build the Realm Swift framework for that platform:

    REALM_SWIFT_VERSION=4.0 sh build.sh ios-swift
    REALM_SWIFT_VERSION=4.0 sh build.sh osx-swift
    REALM_SWIFT_VERSION=4.0 sh build.sh watchos-swift
    REALM_SWIFT_VERSION=4.0 sh build.sh tvos-swift
    

    The built frameworks will be placed in the build directory within the Realm source, where you can then integrate them as you did the prebuilt binaries that Realm provides.

    These built frameworks should also work with apps using Swift 3.2 due to it using the same compiler as Swift 4.0.



回答2:

As a followup to bdash's item 3 about how to build Realm manually from source, and to answer addzo's question about the xcodebuild error (that I ran into as well): Be sure that the iPhone 6 simulator is set up for your Xcode 9 to avoid that error. I suppose Realm's build scripts must target it. This solved it for me, anyhow.