Reputation: 25
I currently have a random number generator in my url that is used to assign new numbers to the page parameter of the url. When I fetch a new image and print the url, it uses the same url. I do not know how to approach removing the existing random number in the url.
Here is my declaration:
public static var random = Int.random(in: 0..<450)
static let ImageURL = "https://api.unsplash.com/search/photos/?client_id=\(UnsplashClient.apiKey)&page=\(random))"
Upvotes: 0
Views: 786
Reputation: 156
Do not use static for your array. Static variables only generated once. So it does not generate random numbers for you. read this: When to use static constant and variable in Swift?
Upvotes: 1
Reputation: 16361
Since you're using a static property
and it's value is not gonna change each time you call it, unless you update it manually. You can fix this issue by using static computed property
whose value is computed everytime it's used.
public static var random: Int { .random(in: 0..<450) }
public static var ImageURL: String { "https://api.unsplash.com/search/photos/?client_id=\(UnsplashClient.apiKey)&page=\(random))" }
Or you can combine them as @leo has mentioned in the comments, if you don't have any other purpose for random
, like this:
public static var imageURL: String { "https://api.unsplash.com/search/photos/?client_id=\(UnsplashClient.apiKey)&page=\(Int.random(in: 0..<450)))" }
Upvotes: 0
Reputation: 470
According to me, You have to create a array of numbers that contains integers from 0 to 450 like this var array = Array(0...450)
and and then can select random number from that array using array.randomElement()!
. And after selecting, remove that number from that array.
Upvotes: 0