0
extension Array where Element: StringLiteralConvertible{

    func spliteByPrefix() -> [Element]{

        for item in self{

        }

        return []
    }

}

I want to write an extension of Array whose Element is always a String. And in my spliteByPrefix() function, i want to use maybe item.characters or something else which a String has. How?

jhd
  • 1,243
  • 9
  • 21

2 Answers2

1

As for now, you cannot write an extension of Array "whose Element is always a String" in Swift.

But you can write some extension which has nearly the same functionality.

Write your own protocol, which String can conform to:

protocol MyStringType {
    var characters: String.CharacterView { get }

    //You may need some other properties or methods to write your extension...
}
// Make `String` the only type conforming to `MyStringType`.
extension String: MyStringType {}

And write an extension where Element conforms to the protocol.

extension Array where Element: MyStringType {

    func spliteByPrefix() -> [Element]{ //You really want to return, `Array<Element>`?
        for item in self {
            for ch in item.characters {
                //Do something with `ch`.
                _ = ch
            }
        }
        return []
    }

}
OOPer
  • 47,149
  • 6
  • 107
  • 142
0

In this example Element is always a Int. I use the elements themselves of the array

extension Array where Element: IntegerType {
    func toString() -> [String] {
        var result = [String]()
        for value in self {
            result.append(String(value))
        }
        return result;
    }
}

Example of use:

let numberInt = [23, 10, 79, 3]
let numberString = numberInt.toString()
David
  • 1,152
  • 16
  • 24