简体   繁体   中英

Preprocessor directives not working in Package.swift?

In my Swift Package, I'm trying to exclude some directories from being compiled for certain targets like this:

import PackageDescription

let package = Package(
    name: "SPMUIKit",
    products: [
        .library(
            name: "SPMUIKit",
            targets: ["SPMUIKit"]
        )
    ],
    targets: [
        .target(
            name: "SPMUIKit",
            exclude: {
                var exclude = [String]()

                #if !os(iOS) || !canImport(UIKit)
                exclude.append("UIKit")
                #endif

                return exclude
            }()
        )
    ]
)

It's not working as expected. As an example, my Swift Package has this in UIKit/UILabel.swift :

import UIKit

public extension UILabel {

    static func spmUIKitTest() {
        print("UILabel.spmUIKitTest from Swift package")
    }
}

To test it, I drag it to a new Xcode 11 iOS app and link the library in the project info, then I added this code to the ViewController :

import UIKit
import SPMUIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        UILabel.spmUIKitTest()
    }
}

Compile error: // Type 'UILabel' has no member 'spmUIKitTest'

If I remove #if !os(iOS) || !canImport(UIKit) #if !os(iOS) || !canImport(UIKit) from Package.swift , it compiles fine. It seems the preprocessor macro doesn't do anything in Package.swift and I've tried it with watchOS and tvOS , etc.

Is preprocessors directives like #if os(iOS) supposed to work in Package.swift ? Is there a working example some where?

Have not found a way yet of doing this but did find it helpful to start gating individual files with platform checks. It adds a negligible amount of size to your binary and makes it easier to include or exclude files for compilation, especially when you're supporting multiple dependency managers. Agreed though that this is something that should be supported.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM