Search code examples
iosswiftrandomswiftui

How to set a custom random range in SwiftUI/Swift


I need to create a custom range for random int in SwiftUI (or Swift).

Now I have two custom ints (minValue & maxValue, I will set them using TextField). So mainNum need to be ranged by them. I thought this would work, but no

@State var minValue: Int = 0
@State var maxValue: Int = 100
@State var mainNum: Int = Int.random(in: minValue...maxValue)

Solution

  • You can't use Int.random(in:) like that, because self isn't available. Instead, you should create the initial random number from the init where you have the range passed in - or you could create a default range in the initializer by changing it to this:

    init(range: ClosedRange<Int> = 0 ... 100) {
        /* ... */
    }
    

    Here is an example of how you could do this, where the random number only is updated when you choose to (in this case, pressing a button).

    struct ContentView: View {
        var body: some View {
            RandomNumberView(range: 0 ... 100)
        }
    }
    
    struct RandomNumberView: View {
        @State var range: ClosedRange<Int>
        @State var randomNumber: Int
    
        init(range: ClosedRange<Int>) {
            self.range = range
            randomNumber = .random(in: range)
        }
    
        var body: some View {
            List {
                Text("Random number: \(randomNumber)")
    
                Stepper(
                    "Minimum: \(range.lowerBound)",
                    value: Binding<Int>(
                        get: { range.lowerBound },
                        set: { range = $0 ... range.upperBound }
                    ),
                    in: 0 ... range.upperBound
                )
    
                Stepper(
                    "Maximum: \(range.upperBound)",
                    value: Binding<Int>(
                        get: { range.upperBound },
                        set: { range = range.lowerBound ... $0 }
                    ),
                    in: range.lowerBound ... 100
                )
    
                Button("Randomize") {
                    randomNumber = .random(in: range)
                }
            }
        }
    }
    

    Result:

    Result