Swift语法—— where语句使用
类型约束中描述的类型约束确保你定义关于类型参数的需求和一泛型函数或类型有关联。 对于关联类型的定义需求也是非常有用的。你可以通过这样去定义where语句作为一个类型参数队列的一部分。一个 下面的列子定义了一个名为 这两个容器可以被检查出是否是相同类型的容器(虽然它们可以是),但它们确实拥有相同类型的元素。这个需求通过一个类型约束和 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 } 这个函数用了两个参数: 这个函数的类型参数列紧随在两个类型参数需求的后面:
第三个和第四个要求被定义为一个 这些要求意思是:
第三个和第四个要求结合起来的意思是 这些要求能够使
检查完之后,函数通过 如果循环体结束后未发现没有任何的不匹配,那表明两个容器匹配,函数返回 这里演示了allItemsMatch函数运算的过程: var stackOfStrings = Stack<String>() stackOfStrings.push("uno") stackOfStrings.push("dos") stackOfStrings.push("tres") var arrayOfStrings = ["uno","dos","tres"] if allItemsMatch(stackOfStrings,arrayOfStrings) { println("All items match.") } else { println("Not all items match.") } // 输出 "All items match." 上面的例子创建一个 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |