簡體   English   中英

如何返回 swift 中 function 的頂部?

[英]How do I return to the top of a function in swift?

我有這個 function 從列表中選擇一個隨機值:

func pickAttraction(attractionType: Array<Attraction>) -> Attraction {
  var randAttr = attractionType.randomElement()
  if favoritesNames.contains(randAttr!.attractionName) {
    return pickAttraction(attractionType: attractionType)
  } else {
    return randAttr!
  }
}

如果隨機值在數組 favoritesName 中,我希望它 go 回到 function 的頂部並選擇一個新值。

我怎樣才能使它更有效率?

此外,如果attractionType類型始終具有至少 8 個值,程序是否可能在強制展開 randAttr(第 3 行)時崩潰?

這個問題不值得問。 它永遠不會讓你到達那里。

func pickAttraction(from attractions: [Attraction]) -> Attraction? {
  attractions.filter { !favoritesNames.contains($0.name) }
    .randomElement()
}

這是操場上的示例

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM