I keep seeing different syntax for how to extend an array. Here are the two that I'm seeing. Can someone explain what the difference is?
extension Array where Element == StringProtocol {
func foo(){}
}
extension Array where Element:StringProtocol {
func foo(){}
}
So what's the difference?
Bonus:
I'm trying to write an extension that works with [String]
and [Substring]
and it was suggested that I base it on StringProtocol
, hence the above. However, if I try doing something like the following...
func foo(separator:Character)
for line in self{
let components = line.split(separator: separator, maxSplits: 1, omittingEmptySubsequences: false)
let prefix = components[0].replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression) // Only trim the end of the prefix
let suffix = components.count > 1
? components[1].trimmingCharacters(in: .whitespaces) // Perform full trim on the suffix
: nil
...
}
}
I get this...
Member 'split' cannot be used on value of protocol type 'StringProtocol'; use a generic constraint instead
So how do you say Element
is a T
where T
conforms to StringProtocol
?