Get n random objects (for example 4) from nsarray

后端 未结 3 679
礼貌的吻别
礼貌的吻别 2020-12-29 11:31

I have a large NSArray of names, I need to get random 4 records (names) from that array, how can I do that?

3条回答
  •  感情败类
    2020-12-29 11:58

    If you prefer a Swift Framework that also has some more handy features feel free to checkout HandySwift. You can add it to your project via Carthage then use it like this:

    import HandySwift    
    
    let names = ["Harry", "Hermione", "Ron", "Albus", "Severus"]
    names.sample() // => "Hermione"
    

    There is also an option to get multiple random elements at once:

    names.sample(size: 3) // => ["Ron", "Albus", "Harry"]
    

    I hope this helps!

提交回复
热议问题