# Swift中where的用法
###### tags: `Swift`
你可以在許多情境裡使用where,對型別進行限制,從而讓程式碼更簡潔。
## extension
當陣列中的元素是UIColor時,才可以調用toCgColors函式,將UIColor轉換為CGColor
```
extension Array where Element == UIColor {
func toCgColors() -> [CGColor] {
var cgColors: [CGColor] = []
for color in self {
cgColors.append(color.cgColor)
}
return cgColors
}
}
```
在extension中的init,針對泛型去限制類別,判斷型別為合法的類別才做動作
```
extension String {
init(collection: T) where T.Element == String {
self = collection.joined(separator: ",")
}
}
let companies = String(collection: ["Apple", "Google", "Tesla"])
print(companies) // "Apple, Google, Tesla"
```
## for loop
```
let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for number in numbers where number % 3 == 0 {
print(number) // 0, 3, 6, 9
}
```
## switch case
```
enum Action {
case createUser(age: Int)
case createPost
case logout
}
func printAction(action: Action) {
switch action {
case .createUser(let age) where age < 21:
print("Young and wild!")
case .createUser:
print("Older and wise!")
case .createPost:
print("Creating a post")
case .logout:
print("Logout")
}
}
printAction(action: Action.createUser(age: 18)) // Young and wild
printAction(action: Action.createUser(age: 25)) // Older and wise
```
## guard
```
let input:String? = "Answer"
guard let str = input where str == "Answer" else {
print("False")
}
print("True")
```
除了guard let外,if let和while let的unwrap也同樣適用
## first 和 contains
```
// first
let names = ["Henk", "John", "Jack"]
let firstJname = names.first(where: { (name) -> Bool in
return name.first == "J"
}) // Returns John
// contains
let fruits = ["Banana", "Apple", "Kiwi"]
let containsBanana = fruits.contains(where: { (fruit) in
return fruit == "Banana"
}) // Returns true
```