如何为不同版本的Xcode编写条件语句

3
我正在使用两台不同的计算机开发一个应用程序。一台是我的家用机器,它是一台较旧的MacBook Pro,但拥有最新的操作系统和运行Xcode 7.3。我使用的第二台机器是我的工作机器,它是全新的,速度非常快,但被限制在Yosemite和Xcode 7.2.1上。
最近,在运行Xcode 7.2.1的机器上遇到了构建错误,但在运行更新版本Xcode的机器上,该应用程序可以成功构建和运行。由于不可改变的IT政策,我无法升级工作机器,而我也不想将我的家用机器降级到Xcode 7.2.1。
因此,我想编写类似以下伪代码的条件语句:
if Xcode.version == 7.3
   // Run this version of the statement
   refreshControl.addTarget(self, action: #selector(ReadingTVC.pullToRefreshTableView), forControlEvents: UIControlEvents.ValueChanged)
if Xcode.version == 7.2.1
   // Run this different version of the statement
   // I still need to figure out how to rewrite the statement for 7.2.1

这是可能的吗?我在苹果文档中找到了以下内容,但没有Xcode版本选项,只有swift()、os()或arch():

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html#//apple_ref/doc/uid/TP40014097-CH33-ID539

提前感谢!

希望这能对你有所帮助 - https://dev59.com/vF0a5IYBdhLWcg3wCEww#46080904 - Krunal
3个回答

2

一个小提示,例如针对烦人的字符串历史记录...

        #if swift(>=4.0)
            let len = text.count
        #else
            let len = text.characters.count
        #endif

适用于Xcode 8.0及更高版本(也在Xcode 9 beta中进行了测试)


1
我目前无法进行测试,但我认为7.3和7.2.1也有不同的Swift版本,因此您可以使用swift()。除此之外,我认为错误是由于Swift的更改(#selector语法?),因此这个检查更适合。
PS:与#selector(...)不同,旧版本只需要将"pullToRefreshTableView"作为选择器。

如何确定正在运行的 Xcode 版本捆绑了哪个 Swift 版本?在“关于 Xcode”或“偏好设置”中,我都找不到相关信息。 - zeeple

1
你应该只使用swift()来检查Swift的版本,因为Xcode 7.3附带了Swift 2.2,而Xcode 7.2.1则附带了Swift 2.1.x。
对于你的代码,由于swift()是在Swift 2.2中引入的,你需要更改使用适用于两个版本的代码,如下所示(假设ReadingTVCself):
// For both swift 2.1.x and swift 2.2. In swift 2.2, this will pop a 
// warning and ask you to fix. But you can wait until you work computer
// updated Xcode version to 7.3. You will be force to change when 
// upgrade to swift 3.0 since the old string based api will be removed.
// Currently it is just marked as deprecated.
refreshControl.addTarget(self, action: "pullToRefreshTableView", forControlEvents: UIControlEvents.ValueChanged)

我尝试了这个解决方案。在我的工作电脑上,运行Xcode 7.2.1时,我遇到了错误:"意外的目标配置表达式(预期为'os'或'arch')"。 - zeeple
1
啊,抱歉我忘了Xcode 7.2.1(带有Swift 2.1.x)不支持swift(),这个只在Swift 2.2中引入。我已经更新了我的答案。请告诉我它是否有效。你可以在这里查看Xcode发布代码关于这些变化:https://developer.apple.com/library/mac/releasenotes/DeveloperTools/RN-Xcode/Chapters/Introduction.html - Zhao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接