Swift3升级到Swift4.2主要还是一些写法上的改变,这里不一一列举了,直接点击报错选择“Fix”即可。
Range 方法失效,替换为以下方法:
Range.init(NSRange(location: location, length: length), in: String)对于Swift和Objectice-C混编的代码都需要在声明前加上“@objc”关键字。
-
还有一种是在Swift文件中自己定义的函数,且重写该方法也在Swift文件的子类中,但是在重写的时候报以下错误,如图:
对于以上问题的解释和解决方案:stackoverflow中的一个回答
This error has to do with the way Swift 4 compiles classes and the new way it treats Objective-C classes and functions. Under Swift 3, if a class is derived from NSObject, then all the variables and functions in that class would use Objective-C's dynamic naming and lookup conventions. This approach inhibited Swift's ability to optimise the code and improve code performance and size.
To overcome these penalties, in Swift 4, only variables and functions explicitly tagged with @objc get the Objective-C treatment, everything else uses standard Swift conventions: hence the error.
Armed with this knowledge, the solution to your problem is to tag the functions in the extension you wish to be overridden as @objc, then in the child classes, override the function, but remember to include the @objc tag so your code will get called at runtime.
WARNING The is a little gotcha here: if you forget to include the @objc in the override, the compiler will not complain, but your code lacks the dynamic lookup, so never gets called at runtime.
大概意思是:
这个错误与Swift 4编译类的方式以及它处理Objective-C类和函数的新方式有关。在Swift 3下,如果类派生自NSObject,那么该类中的所有变量和函数都将使用Objective-C的动态命名和查找约定。这种方法抑制了Swift优化代码、提高代码性能和大小的能力。
为了克服这些缺点,在Swift 4中,只有显式标记为@objc的变量和函数才能得到Objective-C处理,其他所有东西都使用标准Swift约定:因此产生错误。
有了这些知识,您的问题的解决方案是在希望被重写为@objc的扩展中标记函数,然后在子类中重写该函数,但是记住要包含@objc标记,以便在运行时调用代码。
警告:如果您忘记在覆盖中包含@objc,编译器将不会抱怨,但是您的代码缺少动态查找,所以在运行时永远不会被调用。
其他:类似问题
Swift4.2与Swift4.0不兼容的部分语法对照
Swift 4.2 新特性更新
升级 Swift 4.2 教程
升级到Swift 4.0可能遇到的坑总结
Swift3升级到Swift4后String的API升级