Photo by Gunnar Ridderström on Unsplash
Singleton 模式可確保應用程式中的指定型別只會出現一個物件
import Foundation
class DataItem {
enum ItemType: String {
case Email = "Email Address";
case Phone = "Telephone";
case Card = "Credit Card Number";
}
var type: ItemType;
var data: String;
init(type: ItemType, data: String) {
self.type = type;
self.data = data;
}
}
class BackupServer {
let name: String;
private var data = [DataItem]();
init(name: String) {
self.name = name;
}
func backup(item: DataItem) {
data.append(item)
}
func getData() -> [DataItem] {
return data;
}
}
var server = BackupServer(name: "Server#1");
server.backup(item: DataItem(type: DataItem.ItemType.Email, data: "joe@example.com"));
server.backup(item: DataItem(type: DataItem.ItemType.Phone, data: "555-123-1133"));
var otherServer = BackupServer(name: "Server#2");
otherServer.backup(item: DataItem(type: DataItem.ItemType.Email, data: "bob@example.com"));
// 程式列 6-3
class Logger {
private var data = [String]()
func log(msg: String) {
data.append(msg);
}
func printLog() {
for msg in data {
print("Log: \(msg)")
}
}
}
程式列 6-4 pass
程式列 6-5 pass
程式列 6-6 init() 不加 private
程式列 6-7 pass
程式列 6-8 pass
程式列 6-9 init() 不加 private
程式列 6-10 pass
程式列 6-11 //歡迎提供 issue feedback, thank you.
var server = BackupServer.server;
let queue = DispatchQueue(label: "workQueue", qos: .default, attributes: .concurrent);
let group = DispatchGroup();
for _ in 0 ..< 100 {
queue.async {
BackupServer.server.backup(item: DataItem(type: DataItem.ItemType.Email, data: "bob@example.com"))
}
_ = group.wait(timeout: .now())
print("\(server.getData().count)")
}
用底線消除 Swift 3 的忽略回傳值警告
https://www.appcoda.com.tw/grand-central-dispatch/
程式列 6-13 黑體字
private let arratyQ = DispatchQueue(label: "arrayQ");
DispatchQueue.main.sync(execute: {
data.append(item);
globalLogger.log(msg: "\(name) backed up item of type \(item.type.rawValue)");
})
小鴨鴨妳是不是也遇到難解的bug
Photo by CS50