Jason Leach
Jason Leach

Reputation: 4229

Call same function on two different objects in Swift

I have two unrelated objects (3rd party API) that have the some of the same properties. I'd like one helper method to call that will extract the data from the properties and build a NSDate object but theObject.valueForKey does not seem to work.

I've tried this function signature func foo<T: NSObject where T: NSObjectProtocol>(record: T) -> NSDate? { ... } but no luck.

Any thoughts?

Upvotes: 3

Views: 1324

Answers (2)

zoul
zoul

Reputation: 104075

If you just want to get a type that will apply to both classes and expose the common property, you can use a protocol and implement the protocol using an extension:

class Foo {
    let name = "foo"
}

class Bar {
    let name = "bar"
}

protocol HasName {
    var name: String { get }
}

extension Foo: HasName {}
extension Bar: HasName {}

func getName(x: HasName) -> String {
    return x.name
}

getName(Foo()) // "foo"
getName(Bar()) // "bar"

Upvotes: 2

JAL
JAL

Reputation: 42459

This is what protocols are for:

class ClassOne {
    var dateInfo: String = ""
}

class ClassTwo {
    var otherDateInfo: String = ""
}

protocol DateBuildingProtocol {
    func buildDateFromDateInfo() -> NSDate
}

extension ClassOne: DateBuildingProtocol {
    func buildDateFromDateInfo() -> NSDate {
        // do something with self.dateInfo
        return NSDate()
    }
}

extension ClassTwo: DateBuildingProtocol {
    func buildDateFromDateInfo() -> NSDate {
        // do something with self.otherDateInfo
        return NSDate()
    }
}

Protocols give you the power of multiple-inheritance that some other languages have. Basically you declare a method that both classes should have, and implement the method on each class to use the specific variable you need.

Upvotes: 5

Related Questions