Home > front end >  Random way to select a song / Swift
Random way to select a song / Swift

Time:11-11

enter image description here

I'm creating an application that when the user clicks a button, a random favorite song will appear. Everything works perfectly, but I don't know how to create a random way so that when the user clicks, a random song will appear. As you see in the image just that song appears. Thank you

import UIKit

class Song: Equatable, Codable {

var name: String
var minutesOfSong: String?
var artist: String?
let dateCreated: Date

let songKey: String

init(name: String, artist: String?, minutesOfSong: String?) {
    self.name = name
    self.minutesOfSong = minutesOfSong
    self.artist = artist
    self.dateCreated = Date()
    self.songKey = UUID().uuidString
}

convenience init(random: Bool = false) {
    if random {
        
        self.init(name: "Cinema",
                  artist: "Skirllex",
                  minutesOfSong: "5:07")

        self.init(name: "Songnumber1",
                  artist: "Songnumber1",
                  minutesOfSong: "Songnumber1")

        self.init(name: "Songnumber2",
                  artist: "Songnumber2",
                  minutesOfSong: "Songnumber2")

// etc } else {

        self.init(name: "", artist: nil, minutesOfSong: nil)
    }
}

static func ==(lhs: Song, rhs: Song) -> Bool {
    return lhs.name == rhs.name
        && lhs.artist == rhs.artist
        && lhs.minutesOfSong == rhs.minutesOfSong
        && lhs.dateCreated == rhs.dateCreated
}

}

CodePudding user response:

As far as I understood, you're just looking for a good way to pick a random element from an array. If so, Swift's Array has a built-in method for this purpose – randomElement().

CodePudding user response:

You can add an id field to your songs and start giving them id's from 1 and further. Then in the select button press run a random number generator function which generates a random number from 1 to count of the no. of songs. Then select corresp. id song from your list and play that!

let songId = Int(arc4random_uniform(songs.count))

  • Related