Last active
May 17, 2016 20:24
-
-
Save adajos/2f6ca368a4396c5ab55a7faa236ce072 to your computer and use it in GitHub Desktop.
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
import Foundation | |
public protocol ComputedPropertyProvider { | |
var computedProperty:String { get} | |
} | |
public extension ComputedPropertyProvider { | |
var computedProperty: String { | |
return "this is computed property" | |
} | |
} | |
public protocol FuncProvider { | |
func someFunc() | |
} | |
public extension FuncProvider { | |
func someFunc() { | |
print("someFunc") | |
} | |
} | |
//SomeType does not provide its own implementations of the property and func on these protocols, relying | |
//on the implementations provided via the protocol extensions. | |
public class SomeType: ComputedPropertyProvider, FuncProvider { | |
func usefulStuffNotOnAProtocol() { | |
print("imagine useful functionality here") | |
} | |
} | |
//AnotherType uses protcol extensions to conform to ComputedPropertyProvider and FuncProvider | |
//but also provides its own implementations of the property and func. | |
public class AnotherType {} | |
extension AnotherType: ComputedPropertyProvider { | |
public var computedProperty: String { | |
return "computedProperty from AnotherType" | |
} | |
} | |
extension AnotherType: FuncProvider { | |
public func someFunc() { | |
print("someFunc from AnotherType") | |
} | |
} | |
//This will not compile just fine without the following constraints after T: SomeType: | |
//where T: ComputedPropertyProvider, T: FuncProvider. Go ahead and remove those and watch it fail. | |
//Doesn't seem like it should be needed because Swift knows at compile time that SomeType conforms | |
//to the appropriate protocols. | |
func doSomething<T: SomeType where T: ComputedPropertyProvider, T: FuncProvider>(parameter: T) { | |
print("computedProperty is \(parameter.computedProperty)") | |
parameter.someFunc() | |
parameter.usefulStuffNotOnAProtocol() | |
} | |
//This func doesn't need the where constraints to compile because AnotherType declares its own property and func | |
//even though they are declared in an extension along with AnotherType's conformance to the same | |
//two protocols. | |
func doSomethingElse<T: AnotherType>(parameter: T) { | |
print("computedProperty is \(parameter.computedProperty)") | |
parameter.someFunc() | |
} | |
let someType = SomeType() | |
doSomething(someType) | |
let anotherType = AnotherType() | |
doSomethingElse(anotherType) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment