func someMethod(x: Int) {
if x > 1 {
} else if x > 0 {
} else {
}
}
// 可选绑定
if let zero = Int("0") {
}
let result = Result<Int, NSError>.success(1)
// case 模式匹配
if case let .success(x) = result {
print(x)
}
let dualOption: Int?? = 1
if case let x?? = dualOption {
print(x)
}
switch UIDevice.current.userInterfaceIdiom {
case .mac:
print("mac")
case .phone:
print("phone")
case .pad:
print("pad")
default:
break
}
func someMethod(string: String) {
if string.hasPrefix("a") {
print("a")
} else if string.hasPrefix("b") {
print("b")
} else if string.hasPrefix("c") {
print("c")
} else {
print("unknown")
}
}
// case let where 模式匹配替换if else
func someMethod(string: String) {
switch string {
case let string where string.hasPrefix("a"):
print("a")
case let string where string.hasPrefix("b"):
print("b")
case let string where string.hasPrefix("c"):
print("c")
default:
print("unknown")
}
}
do {
try String(contentsOfFile: "")
} catch let error {
print(error) // Error Domain=NSCocoaErrorDomain Code=258 "The item couldn’t be opened because the file name “” is invalid." UserInfo={NSFilePath=}
}
// 引入一个新的作用域,分隔代码块的界限,不会损失性能
do {
print("Hello, world!")
}