Problem with arc4random method

Hi, on my textbook I am using to learn Swift, report a method from the Swift library to generate random numbers. They are in the chapter where the protocols are explained. How come it gives me error on the arc4random method? Thank you 😉



EDIT: sorry , I forgot to post the code, convinced I did: /


// Sanseverino Raffaele
// Random Generator

protocol numeroRandom {
    func random()-> Double
}

class Generatore : numeroRandom {
    func random() -> Double {
        let n = Double(arc4random())
        return n
    }
}
let num = Generatore()
num.random()

Accepted Reply

Are you keeping all the `import` which was in the Playground template, such as `import UIKit` or `import Cocoa`?

At least you need to `import Foundation`. (The actual least may be `import Darwin`, which is rarely found.)

Replies

Please show exact code which causes error. `arc4random` is sort of obsolete, but works fine if you use it in the right way.

Instead of Arc4Random, you should use now calls as:


Int.random(in: 0..<10)


which replaces


Int(arc4random_uniform(UInt32(10)))


You can also use it on other than Int:


Double.random(in: 0..<10.0)

As far as I tried with Xcode 10.2, Command Line Tool project, your code does not cause error.


The only warning is

Result of call to 'random()' is unused


Of course, this is because your code is not using the return value of `random()`.


With a slight change, I get no errors, no warnings:

let num = Generatore()
let rndNum = num.random()
print(rndNum)


What sort of error have you found?

I also have Xcode 10.2 (10E125) but give me this error :

rror: NumeroRandomProtocollo.playground:10:24: error: use of unresolved identifier 'arc4random'

let n = Double(arc4random())


I tried to change with another costant , let rndNum = num.random() and then print(rndNum) but nothing .... same error :/

Are you keeping all the `import` which was in the Playground template, such as `import UIKit` or `import Cocoa`?

At least you need to `import Foundation`. (The actual least may be `import Darwin`, which is rarely found.)

mmmm I'll try ASAP , thanks 😉

Thanks 😉 with import Uikit and Foundation now work , but with import Cocoa I have an error ... beacuse Xcode say that not exist this module :/

but with import Cocoa I have an error ... beacuse Xcode say that not exist this module :/

Seems you are using the iOS mode of Playground.


Sometimes, tutorials or sample code may omit some imports, but you may need to find what you need to import.