func repeatItem<Item>(item:Item, numberOfTimes:Int) -> [Item]{
var result = [Item]()
for _ in 0..<numberOfTimes{
result.append(item)
}
return result
}
let res = repeatItem("knock", 4)
for i in res{
print(" (i)")
}
guard
像 if 语句一样, guard 的执行取决于一个表达式的布尔值。我们可以使用 guard 语句来要求条件必须为真
时,以执行 guard 语句后的代码。不同于 if 语句,一个 guard 语句总是有一个 else 分句,如果条件不为真则执
行 else 分局中的代码。
func greet(person:[String:String]){
guard let name = person["name"] else{
return
}
print("Hello, (name)")
guard let location = person["location"] else{
print("I hope the weather is nice near you.")
return
}
print("I hope the weather is nice in (location).")
}
greet(["name":"John"])
greet(["name":"Jane", "location":"Cupertino"])