Int type Random number generator function

Dear forum members,

It’s not my intention to re-invent the wheel creating this Function with an int type input parameter (the max int number to choose), e.g. 40
The chosen random number will be from 1 to 40 in this example. The exit variable will be int type as well.

How would you code such a function for a Swift Library?

Thank you for your suggestions or pointing links to this piece of code.

Yours sincerely

Jorge Guillermo

You are looking for:

// Any integer from 1 to 40 included

You can also use

Int.random(in: 0...40)

this will return an Int type instead of an optional


That’s it.

Int.random(in: 1...40), since OP wants to exclude zero. But this is what you should use.


Pls explain what is an optional?

Feel free to ask questions after reading (ideally start a new thread for that).

Thank for your previous help. I tried to implement this random generation function (Int) to look for a random subscript in an array of Strings so then I could print the subscripted new Value I used the following code but to no avail. Still does not compile. Please….Where are the error issues?
// Playground

import Cocoa


var declars : [String] = [“txt0”,….,”txt29”]

subscript(index:Int) -> Int {

get {

Int.random(in 0…29) -> Int



set (NewValue) {




You can format code blocks by surrounding them with groups of three ASCII grave accents like this:


// Playground
import Cocoa
// ...


It makes it easier for the rest of us to read.

Do you just want the following?

var declars : [String] = (0...29).map { "txt\($0)" }
print("All: \(declars)") // ["txt0", "txt1", "txt2", /* ... */ "txt29"]

if let randomEntry = declars.randomElement() {
    print("Random: \(randomEntry)") // e.g. “txt19”

Hi Jeremy,
Yes, it does compile! Great!! But at runtime the ‘prints' don't work. It also appears the random number generator does not execute. It’s expected this experimental app will offer the user some more real-life random chat inducers such as: Hullo there, you alright? or I can’t understand your chat. or Give me please some more hints. etc (up to 30 different inducers), coming up at him randomly and automatically.

Yours sincerely

Jorge Guillermo

Dear forum members

Is there in Swift any elegant and simple function such as those found in Python or similars? Something that perform on an user defined data structure type, as follows:

// data structure and definition with initiation values
client[(1,”any text here”),(2,”any other text”),…..,(40,”some text")]
import random
repeat until exit_char {
r = random.randint(1…40)
// whatever other action here

Thank you

Jorge Guillermo Forero

Terms of Service

Privacy Policy

Cookie Policy