ios - Swift 中的 Objective-C 宏替换?

标签 ios swift

多年来我一直在使用 Objective-C,现在我正在迈出使用 Swift 的第一步。

在我现有的项目中,我一直在使用很多不同的宏,比如

#define IS_IPAD      ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
#define IS_IPHONE    ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)

由于 Swift 不支持此类宏,Apple 推荐给 use functions and generics instead .这也是其他线程中推荐的解决方案(例如 here )。

所以我可以简单地创建一些 Tools 类并将宏作为方法添加到其中:

class Tools {
    static func IS_IPAD() -> Bool {
        return UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad
    }
}

class OtherClass {
    func doSomething() {
        if (Tools.IS_IPAD())
            ...
    }
}

但是,我发现的示例似乎使用了没有任何类的函数,就像在上面链接的线程中一样:

func FLOG(message:String, method:String = __FUNCTION__) {
    println("\(method): \(message)")
}

FLOG("Illegal value: \(value)")

由于我是 Swift 的新手,我想知道这是否只是为了让示例简短,或者是否可以在没有类的情况下定义和使用类似函数的宏。

最佳答案

您可以创建全局计算属性来实现类似的目的。

示例:

var isIPad: Bool {
    return UIDevice.current.userInterfaceIdiom == .pad
}

var isIPhone: Bool {
    return UIDevice.current.userInterfaceIdiom == .phone
}

你可以像这样使用它:

class OtherClass {
    func doSomething() {
        if isIPad {
            print("It is an iPad")
        } else if isIPhone {
            print("It is an iPhone")
        }
    }
}

关于ios - Swift 中的 Objective-C 宏替换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56632974/

相关文章:

ios - 我可以使用 eBay 上便宜的 nRF51822 模块与 iOS 设备通信以获取通知 (ANCS) 吗?

iphone - 如何在iPhone应用程序中根据用户登录显示按钮

ios - 滚动时表格 View 单元格复选标记会更改位置

swift - NSPredicate 获取第一个数字

objective-c - CSStickyHeaderFlowLayout swift

ios - 移除覆盖 :overlay not working

iphone - 在iPhone中添加两个UITextView问题?

ios - 禁用 TableView 中所有 subview 的用户交互

swift - 为什么导航 Controller 不使用 Swift 在回调中导航?

ios - UIImageView图层边框问题