多年来我一直在使用 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/