Where Clauses

Type constraints, enable you to define requirements on the type parameters associated with a generic function or type.

It can also be useful to define requirements for associated types. You do this by defining where clauses as part of a type parameter list. A where clause enables you to require that an associated type conforms to a certain protocol, and/or that certain type parameters and associated types be the same. You write a where clause by placing the where keyword immediately after the list of type parameters, followed by one or more constraints for associated types, and/or one or more equality relationships between types and associated types.

The example below defines a generic function called allItemsMatch, which checks to see if two Container instances contain the same items in the same order. The function returns a Boolean value of true if all items match and a value of false if they do not.

The two containers to be checked do not have to be the same type of container (although they can be), but they do have to hold the same type of items. This requirement is expressed through a combination of type constraints and where clauses:

func allItemsMatch<C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>(someContainer: C1, _ anotherContainer: C2)->Bool {
    // check that both containers contain the same number of items
    if someContainer.count != anotherContainer.count {
        return false
    }

    // check each pair of items to see if they are equivalent
    for i in 0..<someContainer.count {
         if someContainer[i] != anotherContainer[i] {
              return false
          }
    }

    // all items match, so return true
    return true
}

This function takes two arguments called someContainer and anotherContainer. The someContainer argument is of type C1, and the anotherContainer argument is of type C2. Both C1 and `C2 are type parameters for two container types to be determined when the function is called.

The function's type parameter list places the following requirements on the two type parameter:

  • C1 must conform to the Container protocol (written as C1: Container).
  • C2 must also conform to the Container protocol (written as C2: Container).
  • The ItemType for C1 must be the same as the ItemType for C2 (written as C1.ItemType == C2.ItemType).
  • The ItemType for C1 must conform to the Equatable protocol (written as `C1.ItemType: Equatable).

The third and fourth requirements are defined as part of a where clause, and are written after the where keyword as part of the function's type parameter list.

These requirements mean:

  • someContainer is a container of Type C1.
  • anotherContainer is a container of type C2.
  • someContainer and anotherContainer contain the same type of items.
  • The items in someContainer can be checked with the not equal operator (!=) to see if they are different from each other.

The third and fourth requirements combine to mean that the items in anotherContainer can also be checked with the != operator, because they are exactly the same type as the items in someContainer.

These requirements enable the allItemsMatch(_:_:) function to compare the two containers, even if they are of a different container type.

The allItemsMatch(_:_:) function starts by checking that both containers contain the same number of items. If they contain a different number of items, there is no way that they can match, and the function returns false.

After making this check, the function iterates over all of the items in someContainer with a for-in loop and the half-open range operator (..<). For each item, the function checks whether the item from someContainer is not equal to the corresponding item in anotherContainer. If the two items are not equal, then the two containers do not match, and the function returns false.

If the loop finishes without finding a mismatch, the two containers match, and the function returns true.

Here's how the allItemsMatch(_:_:) function looks in action:

var stackOfStrings = Stack<String>()
stackOfStrings.push("uno")
stackOfStrings.push("dos")
stackOfStrings.push("tres")

var arrayOfStrings = ["uno", "dos", "tres"]

if allItemsMatch(stackOfStrings, arrayOfStrings) {
    print("All items match.")
}else {
    print("Not all items match.")
}
// prints "All items match."

The example above creates a Stack instance to store String values, and pushes three strings onto the stack. The example also creates an Array instance initialized with an array literal containing the same three strings as the stack. Even though the stack and the array are of a different type, they both conform to the Container protocol, and both contain the same type of values. You can therefore call the allItemsMatch(_:_:) function with these two container as its arguments. In the example above, the allItemsMatch(_:_:) function correctly reports that all of the items in the two containers match.

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末忽你,一起剝皮案震驚了整個濱河市译株,隨后出現的幾起案子,更是在濱河造成了極大的恐慌按灶,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件甜橱,死亡現場離奇詭異萨驶,居然都是意外死亡,警方通過查閱死者的電腦和手機灿意,發(fā)現死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來崇呵,“玉大人缤剧,你說我怎么就攤上這事∮蚩叮” “怎么了荒辕?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長犹褒。 經常有香客問我抵窒,道長,這世上最難降的妖魔是什么叠骑? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任李皇,我火速辦了婚禮,結果婚禮上座云,老公的妹妹穿的比我還像新娘疙赠。我一直安慰自己付材,他們只是感情好朦拖,可當我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著厌衔,像睡著了一般璧帝。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上富寿,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天睬隶,我揣著相機與錄音锣夹,去河邊找鬼。 笑死苏潜,一個胖子當著我的面吹牛银萍,可吹牛的內容都是我干的。 我是一名探鬼主播恤左,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼贴唇,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了飞袋?” 一聲冷哼從身側響起戳气,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎巧鸭,沒想到半個月后瓶您,有當地人在樹林里發(fā)現了一具尸體,經...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡纲仍,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年呀袱,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片巷折。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡压鉴,死狀恐怖,靈堂內的尸體忽然破棺而出锻拘,到底是詐尸還是另有隱情油吭,我是刑警寧澤,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布署拟,位于F島的核電站婉宰,受9級特大地震影響,放射性物質發(fā)生泄漏推穷。R本人自食惡果不足惜心包,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望馒铃。 院中可真熱鬧蟹腾,春花似錦、人聲如沸区宇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽议谷。三九已至炉爆,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背芬首。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工赴捞, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人郁稍。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓赦政,卻偏偏與公主長得像,于是被迫代替她去往敵國和親耀怜。 傳聞我的和親對象是個殘疾皇子昼钻,可洞房花燭夜當晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內容