天天看點

Swift - Swift4新特性介紹2(下标支援泛型,Codable序列化)

http://www.hangge.com/blog/cache/detail_1824.html

三、下标支援泛型

1,下标的傳回類型支援泛型

有時候我們會寫一些資料容器,Swift 支援通過下标來讀寫容器中的資料。但是如果容器類中的資料類型定義為泛型,過去下智語法就隻能傳回 Any,在取出值後需要用 as? 來轉換類型。現在 Swift4 定義下标也可以使用泛型了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

struct

GenericDictionary

<

Key

Hashable

Value

> {

private

var

data: [

Key

Value

]

init

(data: [

Key

Value

]) {

self

.data = data

}

subscript<

T

>(key: 

Key

) -> 

T

? {

return

data[key] 

as

T

}

}

//字典類型: [String: Any]

let

earthData = 

GenericDictionary

(data: [

"name"

"Earth"

"population"

: 7500000000, 

"moons"

: 1])

//自動轉換類型,不需要在寫 "as? String"

let

name: 

String

? = earthData[

"name"

]

print

(name)

//自動轉換類型,不需要在寫 "as? Int"

let

population: 

Int

? = earthData[

"population"

]

print

(population)

Swift - Swift4新特性介紹2(下标支援泛型,Codable序列化)

2,下标類型同樣支援泛型

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

extension 

GenericDictionary

{

subscript<

Keys

Sequence

>(keys: 

Keys

) -> [

Value

where

Keys

.

Iterator

.

Element

== 

Key

{

var

values: [

Value

] = []

for

key 

in

keys {

if

let

value = data[key] {

values.append(value)

}

}

return

values

}

}

// Array下标

let

nameAndMoons = earthData[[

"moons"

"name"

]]        

// [1, "Earth"]

// Set下标

let

nameAndMoons2 = earthData[

Set

([

"moons"

"name"

])]  

// [1, "Earth"]

四、Codable 序列化

如果要将一個對象持久化,需要把這個對象序列化。過去的做法是實作 NSCoding 協定,但實作 NSCoding 協定的代碼寫起來很繁瑣,尤其是當屬性非常多的時候。

Swift4 中引入了 Codable 協定,可以大大減輕了我們的工作量。我們隻需要讓需要序列化的對象符合 Codable 協定即可,不用再寫任何其他的代碼。

1

2

3

4

struct

Language

Codable

{

var

name: 

String

var

version: 

Int

}

1,Encode 操作

我們可以直接把符合了 Codable 協定的對象 encode 成 JSON 或者 PropertyList。

1

2

3

4

5

6

7

8

let

swift = 

Language

(name: 

"Swift"

, version: 4)

//encoded對象

let

encodedData = try 

JSONEncoder

().encode(swift)

//從encoded對象擷取String

let

jsonString = 

String

(data: encodedData, encoding: .utf8)

print

(jsonString)

Swift - Swift4新特性介紹2(下标支援泛型,Codable序列化)

2,Decode 操作

1

2

let

decodedData = try 

JSONDecoder

().decode(

Language

.

self

, from: encodedData)

print

(decodedData.name, decodedData.version)

Swift - Swift4新特性介紹2(下标支援泛型,Codable序列化)

原文出自:www.hangge.com  轉載請保留原文連結:http://www.hangge.com/blog/cache/detail_1824.html