0

I would like to extend Array to create a contact list.

One of the new methods would looks like:

extension Array {
    func contactWithChatId<Contact>(chat_id: String) -> Contact? {
        for contact in self {
            if contact.chat_id == chat_id {
                return contact
            }
        }
        return nil
    }
}

However, I didn't found any way to express this in Swift. Is it possible to do it, and how to ?

Solution:

extension Array {
    func contactWithChatId<T>(chat_id: String) -> Contact? {
        if self.isEmpty {
            return nil
        }
        precondition(self.first is Contact , "Should be a Contact list")
        for contact in self {
            let contact = contact as! Contact
            if contact.chat_id == chat_id {
                return contact
            }
        }
        return nil
    }
}
Community
  • 1
  • 1
Antzi
  • 12,831
  • 7
  • 48
  • 74
  • You *cannot* write extension methods that apply only to a restricted type of the generic element type, compare http://stackoverflow.com/questions/24938948/array-extension-to-remove-object-by-value. – Martin R Jun 05 '15 at 04:53
  • @MartinR I guess this is an answer :) – Antzi Jun 05 '15 at 04:55
  • Also answered here: [Is it possible to make an Array extension in Swift that is restricted to one class?](http://stackoverflow.com/questions/27350941/is-it-possible-to-make-an-array-extension-in-swift-that-is-restricted-to-one-cla) – Martin R Jun 05 '15 at 04:57

0 Answers0