1.参数标签
swift2.x版本第一个参数标签可以不用指定,调用时,不需要添加,swift3默认会将第一个参数名作为参数标签,意味着不做改动很多调用都需要修改。
// Swift 2
func handleError(error: NSError) { }
let error = NSError()
handleError(error) // Looks like Objective-C
// Swift 3
func handleError(error: NSError) { }
let error = NSError()
handleError(error: error)
可以这么做来解决这个问题:
// Swift 3
func handleError(_ error: NSError) { }
// 🖐 Notice the underscore!
let error = NSError()
handleError(error) // Same as in Swift 2
2.API改动
// swift2
NSBundle.mainBundle().infoDictionary
// swift3
Bundle.main.infoDictionary
// swift2
NSSearchPathDirectory.DocumentDirectory
NSSearchPathDomainMask.UserDomainMask
// swift3
FileManager.SearchPathDirectory.documentDirectory
FileManager.SearchPathDomainMask.userDomainMask
//
UIScreen.mainScreen()
UIScreen.main
//
NSFileManager.defaultManager()
FileManager.default
//
NSFileManager.defaultManager().fileExistsAtPath(path)
FileManager.default.fileExists(atPath: path)
3.Xcode8 Use Legacy Swift Language Version的错误解决
pod 使用了swift
库,直接修改podfile
到新版本的三方库,执行pod install
时提示多个target
的swift
版本不匹配。
4.枚举小写开头
// swift2
enum ActivityStatus { // 开关
case UnKnow
case OnSwitch
case OffSwitch
}
// swift3
enum ActivityStatus { // 开关
case unKnow
case onSwitch
case offSwitch
}
5.Any vs AnyObject
将项目里的 AnyObject 转成 Any 可能是大家遇到的第一件适配大事。如何解释这个变化呢?在 Swift 3 之前,我们可以写完一个项目都只用 AnyObject 来代表大多数实例,好像不用与 Any 类型打交道。但事实上,Any 和 AnyObject 是有明显区别的,因为 Any 可以代表 struct、class、func 等等几乎所有类型,而 AnyObject 只能代表 class 生成的实例。
那为什么之前我们在 Swift 2 里可以用 [AnyObject] 声明数组,并且在里面放 Int、String 等 struct 类型呢?这是因为 Swift 2 中,会针对这些 Int、String 等 struct 进行一个 Implicit Bridging Conversions,在 Array 里插入他们时,编译器会自动将其 bridge 到 Objective-C 的 NSNumber、NSString 等类型,这就是为什么我们声明的 [AnyObject] 里可以放 struct 的原因。
但在 Swift 3 当中,为了达成一个门真正的跨平台语言,相关提案将 Implicit Bridging Conversions 给去掉了。所以如果你要把 String 这个 struct 放进一个 [AnyObject] 里,一定要 as NSString,这些转换都需要显示的进行了——毕竟 Linux 平台默认没有 Objective-C runtime。这样各平台的表现更加一致。当然这是其中一个目标,具体可见 0116-id-as-any和相关提案的讨论。
6. typealias Closure (闭包)
// swift2
public typealias URLRequestClosure = (response: URLResponse?, data: Data?, error: Error?) -> Void
func requestData(callback: @escaping URLRequestClosure) -> Void {
// do request and get result
callback(response: response, data: data, error: error)
}
// swift3
public typealias URLRequestClosure = (URLResponse?, Data?, Error?) -> Void
func requestData(callback: @escaping URLRequestClosure) -> Void {
// do request and get result
callback(response, data, error)
}
7.默认参数
错误
ambiguous use of 'yy_setTextHighlight'
text.yy_setTextHighlight(range, color: UIColor.clear, backgroundColor: UIColor.clear, tapAction: { [weak self] (view: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) in
^
__ObjC.NSMutableAttributedString:561:15: note: found this candidate
open func yy_setTextHighlight(_ range: NSRange, color: UIColor?, backgroundColor: UIColor?, userInfo: [AnyHashable : Any]? = nil, tapAction: __ObjC.YYTextAction?, longPressAction: __ObjC.YYTextAction? = nil)
^
__ObjC.NSMutableAttributedString:570:15: note: found this candidate
open func yy_setTextHighlight(_ range: NSRange, color: UIColor?, backgroundColor: UIColor?, tapAction: __ObjC.YYTextAction? = nil)
// swift2
text.yy_setTextHighlight(range, color: UIColor.clear, backgroundColor: UIColor.clear, tapAction: { [weak self] (view: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) in
self?.showFormAffix(affixModel)
})
// swift3
text.yy_setTextHighlight(range, color: UIColor.clear, backgroundColor: UIColor.clear, tapAction: { [weak self] (view: UIView, text: NSAttributedString, range: NSRange, rect: CGRect) in
self?.showFormAffix(affixModel)
}, longPressAction: nil)
原因是系统将YYKit从OC转换到swift时,第一个方法存在默认参数longPressAction = nil
,在swift3中调用方法时,可以不写默认参数,直接调用第二个方法是系统不知道是要调用第二个方法,还是要调用第一个方法。
/**
Convenience method to set text highlight
@param range text range
@param color text color (pass nil to ignore)
@param backgroundColor text background color when highlight
@param userInfo user information dictionary (pass nil to ignore)
@param tapAction tap action when user tap the highlight (pass nil to ignore)
@param longPressAction long press action when user long press the highlight (pass nil to ignore)
*/
open func yy_setTextHighlight(_ range: NSRange, color: UIColor?, backgroundColor: UIColor?, userInfo: [AnyHashable : Any]? = nil, tapAction: YYText.YYTextAction?, longPressAction: YYText.YYTextAction? = nil)
/**
Convenience method to set text highlight
@param range text range
@param color text color (pass nil to ignore)
@param backgroundColor text background color when highlight
@param tapAction tap action when user tap the highlight (pass nil to ignore)
*/
open func yy_setTextHighlight(_ range: NSRange, color: UIColor?, backgroundColor: UIColor?, tapAction: YYText.YYTextAction? = nil)
8.GDC
swift3
Creating a concurrent queue
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {
}
Create a serial queue
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
}
Get main queue asynchronously
DispatchQueue.main.async {
}
Get main queue synchronously
DispatchQueue.main.sync {
}
To get one of the background thread
DispatchQueue.global(attributes: .qosDefault).async {
}
To get one of the background thread
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
}
DispatchQueue.global().async {
// qos' default value is ´DispatchQoS.QoSClass.default`
}
9.String vs NSString
// swift2
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
let str = (textField.text ?? "" as NSString).stringByReplacingCharactersInRange(range, withString: string)
return str.characters.count <= 11
}
// swift3
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let originalStr = (textField.text ?? "") as NSString
let str = originalStr.replacingCharacters(in: range, with: string)
return str.characters.count <= 11
}
10. 指针
// swift2
FMDBDatabaseTool.sharedInstance.dbQueue.inTransaction { db, rollback in
rollback?.memory = true
}
// swwift3
queue.inTransaction { db, rollback in
do {
try db!.executeUpdate("INSERT INTO myTable VALUES (?)", values: [1])
try db!.executeUpdate("INSERT INTO myTable VALUES (?)", values: [2])
try db!.executeUpdate("INSERT INTO myTable VALUES (?)", values: [3])
if whoopsSomethingWrongHappened {
rollback!.pointee = true
return
}
try db!.executeUpdate("INSERT INTO myTable VALUES (?)", values: [4])
} catch {
rollback!.pointee = true
print(error)
}
}
11.swiftLint
假如你使用了swiftLint等代码风格检查工具,你最好暂时把它禁用掉,它以往的代码风格可能和swift3不符合,比如旧版swiftLint约定枚举是大写开头,而swift3约定是小写开头。
12.类前缀
NSBundle -> Bundle
NSTimeInterval -> TimeInterval
NSURL -> URL
NSURLRequest/NSMutableURLRequest -> URLRequest
13. 可选类型比较
// FIXME: comparison operators with optionals were removed from the Swift Standard Libary.
// Consider refactoring the code to use the non-optional operators.
14. UIControlState
// swift2
button.setImage(UIImage(named: "btnBookDownload"), for: .Normal)
// swift3
button.setImage(UIImage(named: "btnBookDownload"), for: .normal)
button.setImage(UIImage(named: "btnBookDownload"), for: UIControlState())
15. NSNotification.Name
//swift2
// swift3
extension NSNotification {
public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
// swift2
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(markDataIsDirty), name: MPJournalSubscribeChangedNotification, object: nil)
// swift3
NotificationCenter.default.addObserver(self, selector: #selector(markDataIsDirty), name: NSNotification.Name(rawValue: MPJournalSubscribeChangedNotification), object: nil)
16. leastNormalMagnitude
// swift2
CGFloat.min
// swift3
CGFloat.leastNormalMagnitude