Last active
October 25, 2017 22:21
-
-
Save wildthink/e5d9b96f4bcaa0d355318bd53ba21a08 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// | |
// Adaptable.swift | |
// | |
// Created by Jason Jobe on 5/2/17. | |
// Copyright © 2017 WildThink. All rights reserved. | |
// | |
import Foundation | |
public protocol Adaptable { | |
func canAdapt<T> (to: T.Type) -> Bool | |
func adapt<T> (to: T.Type) -> T? | |
func adapt<T> () -> T? | |
} | |
public extension Adaptable | |
{ | |
public func canAdapt<T> (to: T) -> Bool { | |
return self is T | |
} | |
public func adapt<T> (to: T) -> T? { | |
return self as? T | |
} | |
public func adapt<T> () -> T? { | |
return self.adapt(to: T.self) | |
} | |
} | |
// Example use | |
struct Wrapper { | |
var name: String | |
} | |
struct Foo: Adaptable { | |
var name: String = "fred" | |
public func adapt<T> (to: T.Type) -> T? { | |
if T.self is Wrapper.Type { | |
return Wrapper (name: "wrap \(name)") as? T | |
} | |
return self as? T | |
} | |
public func adapt<T> () -> T? { | |
return self.adapt(to: T.self) as? T | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment