BadmintonCat
BadmintonCat

Reputation: 9586

Referring constants in a different Xcode target between ObjC and Swift

I have two targets in a Xcode project:

  1. Objective-C app target
  2. Swift UI automation target

And I have many global constants with accessibility IDs in a header file in the app target that I want to use in the automation code, e.g. the header file contains:

static NSString *const APP_TUTORIAL_VIEW_ACI = @"tutorial_view";
static NSString *const APP_TUTORIAL_SCROLL_VIEW_ACI = @"tutorial_scroll_view";

but if I try to access for example APP_TUTORIAL_VIEW_ACI in the automation Swift code it can't find it.

How do I link this so that the global constants can be used in the Swift automation target?

Upvotes: 0

Views: 400

Answers (1)

Puneet Sharma
Puneet Sharma

Reputation: 9484

  1. Create Objective-C Bridging Header file in your Objective-C target by adding a temp swift file. The Xcode will prompt you to add Objective-C bridger header file. The name of the bridging header would be

[YourTargetName]-Bridging-Header.h

enter image description here

  1. Add your constants file in ths bridging header:

    #import "ConstantsHeader.h"

  2. Go to build settings of your Objective-C target. Search for "bridging" and copy the value from SWIFT_OBJC_BRIDGING_HEADER

enter image description here

  1. Go to build settings of your Swift Test Target. Again search for "bridging" and paste the copied value in Objective-C Bridging Header

enter image description here

  1. You can use the constant directly now in Swift Test Target.

    func testExample() {
            let str = APP_TUTORIAL_VIEW_ACI
            XCTAssert(!str.isEmpty, "str should not be empty")
            XCTAssert(str == "tutorial_view", "str should match")
            // This is an example of a functional test case.
            // Use XCTAssert and related functions to verify your tests produce the correct results.
        }
    

Upvotes: 1

Related Questions