0

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))"

iGatiTech
  • 2,306
  • 1
  • 21
  • 45
Sola
  • 25
  • 6

3 Answers3

1

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?

Mehdi Gilanpour
  • 156
  • 2
  • 13
  • "Static variables only generated once" ??? This has nothing to do with being declared static or not https://stackoverflow.com/a/56762161/2303865 – Leo Dabus Jul 07 '20 at 19:27
0

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.

iOS Developer
  • 464
  • 6
  • 24
  • 1
    it would be better to randomize an index and get the element when you remove it. `if let index = array.indices.randomElement() {` `let value = array.remove(at: index)` `}` – Leo Dabus Jul 07 '20 at 06:21
  • Considering the low probability of repeating a random value I don't think it would be necessary to remove the value from the array. This way OP doesn't need to check if the array is empty to fill it up again – Leo Dabus Jul 07 '20 at 06:26
  • Yes the probability is very less but as per the question requirement, I added this. – iOS Developer Jul 07 '20 at 06:39
0

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)))" }
Frankenstein
  • 15,732
  • 4
  • 22
  • 47