【问题标题】:How to make a function accessible to a specific platform? [duplicate]如何使特定平台可以访问功能? [复制]
【发布时间】:2017-04-07 00:45:09
【问题描述】:

我正在创建一个具有执行类似任务的函数的类,但其中一个使用的是仅在该平台上可用的 API。是否可以在为特定平台构建时使该功能无法访问?

例子:

class myClass {

    // How can I hide this function when I'm building for macOS?
    class func myFunctionForIOS() {

    }
    // And hide this when building for iOS?
    class func myFunctionForMACOS() {

    }
}

【问题讨论】:

    标签: ios swift xcode macos


    【解决方案1】:

    Swift 有 Preprocessor Directives 可以做到这一点:

    func myFunction() {
      #if os(macOS)
        // do something
      #elseif os(iOS)
        // do something else
      #else
        // do a final thing
      #endif
    }
    

    更多信息here too

    【讨论】:

      【解决方案2】:
      class ClassA{
        //define common method
        virtual void MethodA() = 0;
      }
      
      class ClassA_iOS_Impl: public ClassA{
        //override your implement for iOS
        void MethodA() override {//call iOS specific API}
      }
      
      class ClassA_Mac_Impl: public ClassA{
        //override your implement for Mac
        void MethodA() override {//call Mac specific API}
      }
      

      然后根据您的平台构建不同的文件。

      【讨论】:

      • 这也是一个很好的方法,它用定制的局部性换取了模块化。预处理器指令和虚拟方法都有一些参数。
      猜你喜欢
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 2017-11-25
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      相关资源
      最近更新 更多