Updated
I just realized DictionaryLiteralConvertible can be used here.
extension Array where Element: DictionaryLiteralConvertible, Element.Key == String, Element.Value == Int {
mutating func addCharacterWithIndex(char: String, index: Int)
{
self.append(Element.init(dictionaryLiteral: (char, index)))
}
}
Original answer...
Since Array
in Swift is a generic struct, it's not possible (at least right now) to extend the Array with a specific type constraint.
For you question, one way to do is to make it optional.
extension Array
{
mutating func addCharacterWithIndex(char: String, index: Int)
{
if let dict = [
"char": char,
"index": index
] as? Element {
self.append(dict)
}
}
}
So you can use it like this:
var symbols: [[String: AnyObject]] = []
symbols.addCharacterWithIndex("*", index: 9)
However, this is not consistent. For other arrays such as [Int], [String]
this method is accessible but does nothing.
Another way, given that you're only using append
method, you can extend RangeReplaceableCollectionType
instead.
extension RangeReplaceableCollectionType where Generator.Element == NSDictionary {
mutating func addCharacterWithIndex(char: String, index: Int)
{
let dict = [
"char": char,
"index": index
]
self.append(dict)
}
}
And use it like this:
var symbols: [NSDictionary] = []
symbols.addCharacterWithIndex("*", index: 9)