We know that Swift can extend existing classes or structures that can exist in a standard library (or a core library). If a struct is a collection type (such as an array), it is more interesting. We want to try to write an extension of a qualified type array so we take array< Int > For example.
This cat wants to be able to write like this:
Array<Int>{ //....}
However, it is clearly not possible to: [
Turned to Apple's official swift programming language and got nothing. So he went online and found a workable solution, a drop that must be used in the WHERE clause:
extension _ArrayType where Element == Int{ count(index:Int)->Int{ print("In _ArrayType") return11*11 }}[1,2,3].count(2)["1"].count(2//error!!!
The main idea is that we can't operate directly with an array, but indirectly with the _arraytype type, you can see that the last line of code is wrong because it is an array of [String] type.
But don't be happy too early, the above code does not work in Swift3, because there is no way to find the _arraytype type in Swit3;(
Be okay, however, cannot start with an array, and we can indirectly start with the protocol it follows. So there are two ways to achieve this in Swift3:
extension Sequence where Iterator.Element == Int{ count(index:Int)->Int{ print("In Sequence") returnindexindex }}extension Collection where Iterator.Element == Int{ count(index:Int)->Int{ print("In Collection") returnindexindex }}
It is important to note that if you want to use the above code in swift2.x, you need to add type after sequence and collection:
SequenceTypeCollectionType
It is worth mentioning that if we want elements in an array extension to follow a protocol, rather than a certain type, you can write this:
protocol lovable{func fallinlove (with name : String)}struct Love : lovable{func fallinlove (with name : String) {print ( "fall in love with \ (name)" )}}extension Array where element : lovable{func count (index:int) -> int{print ( "in Array" ) return Index * index}}let loves = [Love (), Love ()]loves.count (index : 12 )
How to write an extension of a qualified type for an array in Swift3