Swift的語法非常好,從這篇譯自normi的同名文章就能看出來。
❌ 不推薦的寫法
✅ 推薦的寫法
❌
func doSome(result: (Bool) -> ()) {}
✅
typealias BoolBlock = (Bool) -> ()
/// ....
func doSome(result: BoolBlock) {}
func logSome(_ msg: String, detail: String = "default detail") {}
logSome("this is msg")
❌
func doSome(info: Info) {
if let name = info.name {
doOther(name: name)
}
}
✅
func doSome(info: Info) {
guard let name = info.name else {
return
}
doOther(name: name)
}
❌
public override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blue
let testView = UIView.init()
self.view.addSubview(testView)
}
✅
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .blue
let testView = UIView()
view.addSubview(testView)
}
✅
enum Style {
case cancel
case `default`
}
class LogProvider {
static let `default` = LogProvider()
}
✅
func doSome(info: Info) {
let name = info.name ?? "default name"
}
❌
var text: String?
if isMe {
text = "Me"
} else {
text = "other"
}
✅
let text = isMe ? "Me" : "other"
❌
view.backgroundColor = UIColor.blue
✅
view.backgroundColor = .blue
❌
class LoginVC: UIViewController, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
}
✅
class LoginVC: UIViewController {
/// …
}
extension LoginVC: UITextFieldDelegate {
/// …
}
extension LoginVC: UITableViewDataSource, UITableViewDelegate {
/// …
}
❌
let name = info.name!
✅
guard let name = info.name else {
print("name is nil")
return
}
❌
var items = Array<String>()
var map = Dictionary<String, String>()
func doSome() -> Void
let callback: () -> Void
✅
var items = [String]()
var map = [String : String]()
func doSome()
let callback: () -> ()
❌
func doSome() -> Int {}
let index = doSome()
if index == -1 {
/// fail
} else {
/// success
}
✅
func doSome() -> Int? {}
guard let index = doSome() else {
print("fail")
return
}
/// success
更多精彩资讯请关注tft每日頭條,我们将持续为您更新最新资讯!