本文介绍了是否应该使用条件编译来应对不同架构上 CGFloat 的差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在回答这个之前关于获得使用的问题时CGFloat 上的 ceil() 为所有架构编译,我建议了一个解决方案:

In answering this earlier question about getting a use of ceil() on a CGFloat to compile for all architectures, I suggested a solution along these lines:

    var x = CGFloat(0.5)

    var result: CGFloat

    #if arch(x86_64) || arch(arm64)
        result = ceil(x)
    #else
        result = ceilf(x)
    #endif

    // use result

(对于那些已经感到困惑的人的背景信息:CGFloat 是 32 位架构的float"类型,64 位架构(即编译目标)的double"类型,这就是为什么只使用 ceil 之一()ceilf() 不会总是编译,具体取决于目标架构.请注意,您似乎无法使用 CGFLOAT_IS_DOUBLE 用于条件编译,只有架构标志...)

(Background info for those already confused: CGFloat is a "float" type for 32-bit architecture, "double" for 64-bit architecture (i.e. the compilation target), which is why just using either of ceil() or ceilf() on it won't always compile, depending on the target architecture. And note that you don't seem to be able to use CGFLOAT_IS_DOUBLE for conditional compilation, only the architecture flags...)

现在,这在关于在编译时修复与运行时修复的评论中引起了一些争论,等等.我认为我的回答被接受得太快了,以至于无法引起关于这个问题的一些很好的辩论.

Now, that's attracted some debate in the comments about fixing things at compile time versus run time, and so forth. My answer was accepted too fast to attract what might be some good debate about this, I think.

那么,我的新问题是:如果您希望您的 iOS 和 OS X 代码在 32 位和 64 位设备上运行,上述做法是否安全且明智?如果它理智和明智,还有没有更好的(至少一样有效,而不是讨厌"的)解决方案?

So, my new question: is the above a safe, and sensible thing to do, if you want your iOS and OS X code to run on 32- and 64-bit devices? And if it is sane and sensible, is there still a better (at least as efficient, not as "icky") solution?

推荐答案

Matt,

以您的解决方案为基础,如果您在多个地方使用它,那么稍微扩展一下可能会使其更可口:

Building on your solution, and if you use it in several places, then a little extension might make it more palatable:

extension CGFloat {
    var ceil: CGFloat {
        #if arch(x86_64) || arch(arm64)
            return ceil(x)
        #else
            return ceilf(x)
        #endif
    }
}

剩下的代码会更简洁:

var x = CGFloat(0.5)
x.ceil

这篇关于是否应该使用条件编译来应对不同架构上 CGFloat 的差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 12:54