let a1 = [1,3,2].sorted(by: { (l: Int, r: Int) -> Boolin return l < r }) // 如果闭包是唯一的参数并在表达式最后可以使用结尾闭包语法,写法简化为 let a2 = [1,3,2].sorted { (l: Int, r: Int) -> Boolin return l < r } // 已知类型可以省略 let a3 = [1,3,2].sorted { l, r in return l < r } // 通过位置来使用闭包的参数,最后简化如下: let a4 = [1,3,2].sorted { $0<$1 }
let s1 ="I am not a good painter" print(s1.ranges(of: /good/)) do { let regGood =tryRegex("[a-z]ood") print(s1.replacing(regGood, with: "bad")) } catch { print(error) } print(s1.trimmingPrefix(/i am /.ignoresCase()))
// Text to parse: // CREDIT 03/02/2022 Payroll from employer $200.23 // CREDIT 03/03/2022 Suspect A $2,000,000.00 // DEBIT 03/03/2022 Ted's Pet Rock Sanctuary $2,000,000.00 // DEBIT 03/05/2022 Doug's Dugout Dogs $33.27
import RegexBuilder let fieldSeparator =/\s{2,}|\t/ let transactionMatcher =Regex { /CREDIT|DEBIT/ fieldSeparator One(.date(.numeric, locale: Locale(identifier: "en_US"), timeZone: .gmt)) // 👈🏻 we define which data locale/timezone we want to use fieldSeparator OneOrMore { NegativeLookahead { fieldSeparator } // 👈🏻 we stop as soon as we see one field separator CharacterClass.any } fieldSeparator One(.localizedCurrency(code: "USD").locale(Locale(identifier: "en_US"))) }
在正则表达式中捕获数据,使用 Capture:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
let fieldSeparator =/\s{2,}|\t/ let transactionMatcher =Regex { Capture { /CREDIT|DEBIT/ } // 👈🏻 fieldSeparator
// 原始字符串在字符串前加上一个或多个#符号。里面的双引号和转义符号将不再起作用了,如果想让转义符起作用,需要在转义符后面加上#符号。 let s8 =#"\(s7)\#(s7) "one" and "two"\n. \#nThe second line."# print(s8) /// \(s7)hi "one" and "two"\n. /// The second line.
// 原始字符串在正则使用效果更佳,反斜杠更少了。 let s9 ="\\\\[A-Z]+[A-Za-z]+\\.[a-z]+" let s10 =#"\\[A-Z]+[A-Za-z]+\.[a-z]+"# print(s9) // \\[A-Z]+[A-Za-z]+\.[a-z]+ print(s10) // \\[A-Z]+[A-Za-z]+\.[a-z]+
// 递归枚举 enumRE { case v(String) indirectcase node(l:RE, r:RE) }
let lNode =RE.v("left") let rNode =RE.v("right") let pNode =RE.node(l: lNode, r: rNode)
switch pNode { case .v(let string): print(string) case .node(let l, let r): print(l,r) switch l { case .v(let string): print(string) case .node(let l, let r): print(l, r) } switch r { case .v(let string): print(string) case .node(let l, let r): print(l, r) } }
@unknown 用来区分固定的枚举和可能改变的枚举的能力。@unknown 用于防止未来新增枚举属性会进行提醒提示完善每个 case 的处理。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// @unknown enumE3 { case e1, e2, e3 }
funcfe1(e: E3) { switch e { case .e1: print("e1 ok") case .e2: print("e2 ok") case .e3: print("e3 ok") @unknowndefault: print("not ok") } }
let url =URL(string: "https://ming1016.github.io/")!
// 以前网络请求 let t1 =URLSession.shared.dataTask(with: url) { data, _, error in iflet err = error { print(err) } elseiflet data = data { print(String(decoding: data, as: UTF8.self)) } } t1.resume()
// 使用 Result 网络请求 let t2 =URLSession.shared.dataTaskWithResult(with: url) { result in switch result { case .success(let data): print(String(decoding: data, as: UTF8.self)) case .failure(let err): print(err) } } t2.resume()
var a = [S0]() a.append(S1()) a.append(S2()) for e in a { // 类型判断 if e isS1 { print("Type is S1") } elseif e isS2 { print("Type is S2") } // 使用 as 关键字转换成子类 iflet s1 = e as?S1 { print("As S1 \(s1)") } elseiflet s2 = e as?S2 { print("As S2 \(s2)") } }
// 类型遵循 Comparable let a1 = ["a", "b", "c", "call my name.", "get it?"] let a2 = a1.sorted() let a3 = a1.sorted(by: >) let a4 = a1.sorted(by: <)
print(a2) // Hey u, a b c call my name. get it? print(a3) // ["get it?", "call my name.", "c", "b", "a"] print(a4) // ["a", "b", "c", "call my name.", "get it?"]
// 类型不遵循 Comparable structS { var s: String var i: Int } let a5 = [S(s: "a", i: 0), S(s: "b", i: 1), S(s: "c", i: 2)] let a6 = a5 .sorted { l, r in l.i > r.i } .map { $0.i }
// if let s ="hi" if s.isEmpty { print("String is Empty") } else { print("String is \(s)") }
// 三元条件 s.isEmpty ?print("String is Empty again") : print("String is \(s) again")
// if let-else funcf(s: String?) { iflet s1 = s { print("s1 is \(s1)") } else { print("s1 is nothing") } // nil-coalescing let s2 = s ??"nothing" print("s2 is \(s2)") } f(s: "something") f(s: nil)
// if case let enumE { case c1(String) case c2([String]) funcdes() { switchself { case .c1(let string): print(string) case .c2(let array): print(array) } } }
funcf1(pa: String, t:(String, Int)) { var p1 =0 var p2 =10 switch pa { case"one": p1 =1 case"two": p1 =2 fallthrough// 继续到下个 case 中 default: p2 =0 } print("p1 is \(p1)") print("p2 is \(p2)") // 元组 switch t { case ("0", 0): print("zero") case ("1", 1): print("one") default: print("no") } }
f1(pa: "two", t:("1", 1)) /* p1 is 2 p2 is 0 one */
// 枚举 enumE { case one, two, three, unknown(String) }
funcf2(pa: E) { var p: String switch pa { case .one: p ="1" case .two: p ="2" case .three: p ="3" caselet .unknown(u) whereInt(u) ??0>0 : // 枚举关联值,使用 where 增加条件 p = u case .unknown(_): p ="negative number" } print(p) }
let a1 = ["one", "two", "three"] let a2 = ["three", "four"]
// 找两个集合的不同 let dif = a1.difference(from: a2) // swift的 diffing 算法在这 http://www.xmailserver.org/diff2.pdf swift实现在 swift/stdlib/public/core/Diffing.swift for c in dif { switch c { case .remove(let o, let e, let a): print("offset:\(o), element:\(e), associatedWith:\(String(describing: a))") case .insert(let o, let e, let a): print("offset:\(o), element:\(e), associatedWith:\(String(describing: a))") } } /* remove offset:1, element:four, associatedWith:nil insert offset:0, element:one, associatedWith:nil insert offset:1, element:two, associatedWith:nil */ let a3 = a2.applying(dif) ?? [] // 可以用于添加删除动画 print(a3) // ["one", "two", "three"]
dif 有第三个 case 值 .insert(let offset, let element, let associatedWith) 可以跟踪成对的变化,用于高级动画。
for (k, v) in d1 { print("key is \(k), value is \(v)") } /* key is k1, value is v1 key is k2, value is v2 key is k3, value is v3 */ if d1.isEmpty ==false { print(d1.count) // 3 }
let i1 =1 let i2 = i1 print((i1 + i2 -1) *10/2%3) // 2 print("i"+"1") // i1
// 一元运算符 print(-i1) // -1
比较运算符
遵循 Equatable 协议可以使用 == 和 != 来判断是否相等
1 2 3 4 5 6 7 8 9 10 11 12 13 14
print(1>2) // false
structS: Equatable { var p1: String var p2: Int } let s1 =S(p1: "one", p2: 1) let s2 =S(p1: "two", p2: 2) let s3 =S(p1: "one", p2: 2) let s4 =S(p1: "one", p2: 1)