Vous êtes sur la page 1sur 34

What’s new in

Swift?
- Part II -

iOS Team, July 2019


Hello!
I AM TIEN LE P.

2
Contents
⋆ None case
⋆ Matching enum
⋆ Orderd collection diffing
⋆ Creating array
⋆ Dynamic Member Lookup
⋆ Static subscripts

3
Part I
Init()
struct Titan {
var name: String
var height: Int = 0
var weight: Float = 0
}

let kong = Titan(name: "King Kong", height: 100, weight: 30)


let godzilla = Titan(name: "Godzilla", height: 120)
let gindora = Titan(name: "Gindora")

5
return
let double1 = [1, 2, 3].map { $0 * 2 }
let double2 = [1, 2, 3].map { return $0 * 2 }

func hello(name: String) -> String {


"Hello, \(name)"
}

6
Self
class NetworkManager {
class var maximunActiveRequests: Int {
4
}

func printDebugData() {
print("Maximum network requests: \(Self.maximunActiveRequests)")
}
}

7
Opaque return type
// ---- World of Bird ---- //
protocol Bird {}
final class LeLe: Bird {}
final class Eagle: Bird {}
final class Penguin: Bird {}

// ---- somewhere in the world ---- //


protocol Place {
associatedtype B: Bird
var bird: Self.B { get }
}

struct VietNam : Place {


var bird: some Bird {
return Eagle()
}
}

8
Part II

9
1. None case
⋆ Khó khăn với việc 1 giá trị của enum là
⋆ Nil
⋆ Không có
⋆ Swift cung cấp thêm 1 case
⋆ .none
⋆ Áp dung cho Optional

11
enum FileType {
case none
case doc
case exe
case txt
}
none
nil
let file: FileType = .none
print(file)

let file2: FileType? = .none


print(file2)

12
2. Matching enum
⋆ Với Swift 5.0 trở về trước thì không thể so
sánh giữa 2 enum optional và non-optional
được với nhau
⋆ Muốn so sánh thì phải thêm dấu “?” vào
case
⋆ Swift 5.1 thì tự động match 2 tụi nó với nhau

14
enum BuildStatus { enum BuildStatus {
case starting case starting
case inProgress case inProgress
case complete case complete
} }

let status: BuildStatus? = .inProgress let status: BuildStatus? = .inProgress

switch status { switch status {


case .inProgress?: case .inProgress:
print("Build is starting…") print("Build is starting…")
case .complete?: case .complete:
print("Build is complete!") print("Build is complete!")
default: default:
print("Some other build status") print("Some other build status")
} }

15
3. Ordered collection
diffing
difference(:)
⋆ Tìm ra sự khác nhau giữa 2 collection
⋆ Kiểu trả về là : CollectionDifference<T>
⋆ Insertions
⋆ removals

17
var scores1 = [100, 91, 95, 98, 100]
let scores2 = [100, 98, 95, 91, 100]

let diff = scores2.difference(from: scores1)

for change in diff {


switch change {
case .remove(let offset, _, _):
scores1.remove(at: offset)
case .insert(let offset, let element, _):
scores1.insert(element, at: offset)
}
}

18
applying(:)

let result = scores1.applying(diff) ?? []

19

Tạo 1 array Int 10 phần tử,
các phần tử random từ 0 đến
10

20
let randomNumbers = Array<Int>(unsafeUninitializedCapacity: 10) { buffer, initializedCount
in
for x in 0..<10 {
buffer[x] = Int.random(in: 0...10)
}

initializedCount = 10
}

Đoạn code trên có gì không ổn?

21
4. Creating
uninitialized
arrays

22
let randomNumbers2 = (0...9).map { _ in Int.random(in: 0...10) }

23
5. Dynamic Member
Lookup
Nó được tạo ra với 1 mục đích là làm
có code swift được an toàn hơn
@dynamicMemberLookup
@dynamicMemberLookup struct Dyn {
static subscript(dynamicMember name: String) -> String {
return "type \(name)"
}
subscript(dynamicMember name: String) -> String {
return "instance \(name)"
}
}

print(Dyn.foo)
print(Dyn().foo)

25
subscript(_:)

26
class Class {
var menbers = [String: String]()
subscript(_ name: String) -> String? {
get {
menbers[name]
}

set {
menbers[name] = newValue
}
}
}

let iOS = Class()


iOS.menbers["Lớp trưỡng"] = "Tèo đại ca”
iOS["Lớp phó"] = "Tí đú đỡn"

print(iOS.menbers["Lớp trưỡng"] ?? "unknown")


print(iOS["Lớp phó"] ?? "unknown")

27
class T {
var number: Int = 0
subscript(value: Int) -> Int {
get {
number
}

set {
self.number = newValue * value
}
}
}

let t = T()
t.number = 10
t[10] = 20
print("T : number: \(t.number)")

28
t.Type
instance

T.t.type
static/class

T.Type
29
6. Static and class
subscripts
which means they apply to types rather than
instances of a type.
class iOSClass {
private static var menbers = [String: String]()
public static subscript(_ name: String) -> String? {
get {
menbers[name]
}

set {
menbers[name] = newValue
}
}
}
iOSClass["Lớp trưỡng"] = "Hoàng lão tà"
iOSClass["Lớp phó"] = "Lão động vật"
print(iOSClass["Lớp phó"] ?? "n/a")
let iOS = Class()
iOS.menbers["Lớp trưỡng"] = "Tèo đại ca”
iOS["Lớp phó"] = "Tí đú đỡn"

print(iOS.menbers["Lớp trưỡng"] ?? "unknown")


print(iOS["Lớp phó"] ?? "unknown")
31
public class NewSettings {
public class OldSettings { private static var values = [String: String]()
private static var values = [String: String]()
public static subscript(_ name: String) -> String? {
static func get(_ name: String) -> String? { get {
values[name] return values[name]
} }

static func set(_ name: String, to newValue: String?) { set {


print("Adjusting \(name) to \(newValue ?? "nil")") print("Adjusting \(name) to \(newValue ?? "nil")")
values[name] = newValue values[name] = newValue
} }
} }
}

OldSettings.set("Captain", to: "Gary")


OldSettings.set("Friend", to: "Mooncake") NewSettings["Captain"] = "Gary"
NewSettings["Friend"] = "Mooncake”
print(OldSettings.get("Captain") ?? "Unknown")
print(NewSettings["Captain"] ?? "Unknown")

32
DEMO

33
Thanks!
ANY QUESTIONS?
You can find at google.com & stackoverflow.com

34

Vous aimerez peut-être aussi