xcode 如何将我的 swift 1.2 项目迁移到 2.0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31603557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to migrate my swift 1.2 project into 2.0?
提问by Mehul Chuahan
I have a project developed when swift was introduced but recently Apple has new version of swift 2.0 with xCode 7.0. So how can i migrate my project from swift 1.2 to 2.0?
我在引入 swift 时开发了一个项目,但最近 Apple 推出了带有 xCode 7.0 的新版本 swift 2.0。那么如何将我的项目从 swift 1.2 迁移到 2.0?
回答by Manav Gabhawala
In the new Xcode 7 beta go to the Edit menu -> Convert -> To Latest Swift Syntax
在新的 Xcode 7 beta 中,转到编辑菜单 -> 转换 -> 到最新的 Swift 语法
This will run the code converter for you and show you the changes it is going to make. These are automatic changes (like changing println to print and so on).
这将为您运行代码转换器并向您显示它将要进行的更改。这些是自动更改(例如将 println 更改为 print 等)。
Then to refactor the code to make it more Swift-like here are some tips:
然后重构代码以使其更像 Swift,这里有一些提示:
Ensure you are using the new error handling functionality wherever possible (the code conversion tool does this for the most part but sometimes it gets it wrong).
Use guard statements where appropriate. In general use it to reduce indentation and nested if statements. These are really nice when used properly.
Almost all your global functions can be refactored into protocol extensions. Move generic functions to extensions.
When converting to/from a type (for instance String -> NSData and vice versa) use failable initializers with the parameter as the type to convert from instead of having properties on the type. So instead of doing
someString.dataUsingEncoding(NSUTF8StringEncoding)
do something likeNSData(someString, encoding: NSUTF8StringEncoding)
. Note this is not how the API is implemented but I used it as an example to show how things can be more "Swifty".Use availability checking where useful.
- Move clean up code to defer blocks as much as possible. This can help redundant duplicated clean up code like file closing, etc.
确保您尽可能使用新的错误处理功能(代码转换工具在大多数情况下会这样做,但有时会出错)。
在适当的地方使用保护语句。通常使用它来减少缩进和嵌套 if 语句。如果使用得当,这些真的很好。
几乎所有的全局函数都可以重构为协议扩展。将通用函数移至扩展。
当转换到/从一个类型(例如 String -> NSData ,反之亦然)使用可失败的初始化器,将参数作为要转换的类型,而不是在类型上有属性。所以不要做
someString.dataUsingEncoding(NSUTF8StringEncoding)
类似的事情NSData(someString, encoding: NSUTF8StringEncoding)
。请注意,这不是 API 的实现方式,但我使用它作为示例来展示如何变得更“Swifty”。在有用的地方使用可用性检查。
- 移动清理代码以尽可能推迟块。这可以帮助清理多余的重复代码,例如文件关闭等。