[英]How do I return to the top of a function in swift?
I have this function that picks a random value from a list:我有这个 function 从列表中选择一个随机值:
func pickAttraction(attractionType: Array<Attraction>) -> Attraction {
var randAttr = attractionType.randomElement()
if favoritesNames.contains(randAttr!.attractionName) {
return pickAttraction(attractionType: attractionType)
} else {
return randAttr!
}
}
If the random value is in the array favoritesName, I want it to go back to the top of the function and pick a new value.如果随机值在数组 favoritesName 中,我希望它 go 回到 function 的顶部并选择一个新值。
How can I make this more efficient?我怎样才能使它更有效率?
In addition, is it possible for the program to crash while force-unwrapping randAttr (on line 3) if attractionType
always has at least 8 values?此外,如果
attractionType
类型始终具有至少 8 个值,程序是否可能在强制展开 randAttr(第 3 行)时崩溃?
The question is not worth asking.这个问题不值得问。 It'll never get you there.
它永远不会让你到达那里。
func pickAttraction(from attractions: [Attraction]) -> Attraction? {
attractions.filter { !favoritesNames.contains($0.name) }
.randomElement()
}
Here is a sample in playground这是操场上的示例
import UIKit
class RandomAttraction:Hashable{
static func == (lhs: RandomAttraction, rhs: RandomAttraction) -> Bool {
return lhs.attractionName == rhs.attractionName
}
func hash(into hasher: inout Hasher) {
hasher.combine(attractionName)
}
init(attractionName:String) {
self.attractionName = attractionName
}
var attractionName:String
}
var favoritesNames = [RandomAttraction.init(attractionName: "a"),RandomAttraction.init(attractionName: "b")]
var otherNames = [RandomAttraction.init(attractionName: "c"),RandomAttraction.init(attractionName: "d")]
func pickAttraction(attractionType: Array<RandomAttraction>) -> RandomAttraction? {
//Filters the content of the favoritesNames from attractionType
let filteredArray = Array(Set(attractionType).subtracting(favoritesNames))
//If count is zero return nil
if filteredArray.count == 0{
return nil
}
let randAttr = filteredArray.randomElement()
return randAttr
}
//MARK: Usage
if let pickedAttraction = pickAttraction(attractionType: otherNames){
print(pickedAttraction.attractionName)
}else{
print("No attractions")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.