Last active
August 21, 2019 08:45
-
-
Save pofat/72c92b8798c916df117fee06b81bb769 to your computer and use it in GitHub Desktop.
weak self podcast episode 1 附錄: 用 generic struct 取代 Protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Standard library 有個 protocol `CustomStringConvertible`,需要實作 `description: String` 來將一個物件轉化成 description string | |
* 但是若你對同一個物件想要有兩種描述方式,比如 | |
* 想要用 JSON 的方式印出來 model 的所有 property,且希望有的時候是 pretty printed 有的時候是 sorted key 怎麼辦? | |
* 你會需要有兩個物件來遵守 CustomStringConvertible,因為一個 protocol 在一個物件裡只能有一種實作 | |
* 然而用 generic struct 的話就能做到這件事 | |
* 下面的實例中你可以宣告兩個不同的 instance ,`prettyPrintedDescribing` 和 `sortedKeyDescribing` | |
* 想用哪個就用哪個,方便多了,也讓 compiler 有更多參與最佳化的空間 | |
* | |
*/ | |
import Foundation | |
struct Describer<T> { | |
var describe: (T) -> String | |
} | |
let prettyPrintedDesc = Describer<[String: String]> { dict in | |
guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted), | |
let string = String(data: data, encoding: .utf8) else { | |
return "" | |
} | |
return string | |
} | |
let sortedKeyDesc = Describer<[String: String]> { dict in | |
guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .sortedKeys), | |
let string = String(data: data, encoding: .utf8) else { | |
return "" | |
} | |
return string | |
} | |
let albumDict = [ | |
"title" : "Slippery When Wet", | |
"author" : "Bon Jovi", | |
"date" : "August 18, 1986", | |
"priceTag" : "$20.00" | |
] | |
print(prettyPrintedDesc.describe(albumDict)) | |
print(sortedKeyDesc.describe(albumDict)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment