protocol Container {
associatedtype ItemType // Here it is.
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
struct IntStack: Container {
typealias ItemType = Int // Here again.
mutating func append(item: Int) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Int {
return items[i]
}
var items = [Int]()
mutating func push(item: Int) {
items.append(item)
}
mutating func pop() …Run Code Online (Sandbox Code Playgroud) 我对Swift中灵活的通用服务定位器设计模式实现感兴趣.
一种天真的方法可能如下:
// Services declaration
protocol S1 {
func f1() -> String
}
protocol S2 {
func f2() -> String
}
// Service Locator declaration
// Type-safe and completely rigid.
protocol ServiceLocator {
var s1: S1? { get }
var s2: S2? { get }
}
final class NaiveServiceLocator: ServiceLocator {
var s1: S1?
var s2: S2?
}
// Services imlementation
class S1Impl: S1 {
func f1() -> String {
return "S1 OK"
}
}
class S2Impl: S2 {
func …Run Code Online (Sandbox Code Playgroud) 我看到了许多private init在Swift中使用来限制对象构造的引用(例如这个),但是当我尝试时(在Xcode 7.2.1 Playground中)它似乎不可能:
class C {
private init() {}
}
var c = C() // No errors.
Run Code Online (Sandbox Code Playgroud)
我错过了什么或这实际上是一个错误吗?
我观看了"Swift中面向协议的编程"并阅读了相关的文档,但我仍然认为以下示例代码存在冲突(在Playground中尝试).
protocol X {
// The important part is "static" keyword
static var x: String { get }
}
extension X {
// Here "static" again
static var x: String {
get {
return "xxx"
}
}
}
// Now I'm going to use the protocol in a class, BUT
// in classes "static" is like "final class",
// i.e. CAN'T BE OVERRIDDEN, right?
// But I'd prefer to have the ability to override that property,
// so …Run Code Online (Sandbox Code Playgroud)