Skip to content

Instantly share code, notes, and snippets.

@wildthink
Last active October 25, 2017 22:21
Show Gist options
  • Save wildthink/e5d9b96f4bcaa0d355318bd53ba21a08 to your computer and use it in GitHub Desktop.
Save wildthink/e5d9b96f4bcaa0d355318bd53ba21a08 to your computer and use it in GitHub Desktop.
//
// 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