Skip to content

Instantly share code, notes, and snippets.

@mcomisso
Last active February 15, 2018 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcomisso/38d9723eb30dd558875fd4dcbe2cffd6 to your computer and use it in GitHub Desktop.
Save mcomisso/38d9723eb30dd558875fd4dcbe2cffd6 to your computer and use it in GitHub Desktop.
/// Both objects will have a shared set of features to be used in the generic function
protocol HasSomeSharedFeatures {
func performSharedThing()
}
/// Extends the base class with some shared features
class PFObject: NSObject, HasSomeSharedFeatures {
func performSharedThing() { }
}
// Swift 4.1 - 5 ?
// extension Dictionary: HasSomeSharedFeatures where Key == String, Value: Any { }
// Adds overhead, but wraps a typed dict with a protocol
struct SupportingDict: HasSomeSharedFeatures {
let dict: [AnyHashable: Any]
func performSharedThing() { }
}
// Array yay
typealias ArrayOfPFObjects = [PFObject]
typealias ArrayOfSupportingDicts = [SupportingDict]
let pfobjects: ArrayOfPFObjects = []
let arrObjects: ArrayOfSupportingDicts = []
/// Generic function
///
/// - Parameter input: Takes an input with the function constraint as
/// - Returns: Something out after processing
func doSomething<T: HasSomeSharedFeatures>(input: [T]) -> Any? {
// Do your job here
input.forEach {
$0.performSharedThing()
}
return nil
}
func execute() {
_ = doSomething(input: pfobjects)
_ = doSomething(input: arrObjects)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment