0

I've been practicing blocks a bit and would like some help converting this one from Objective C to Swift.

The below Objective C code works just fine... logging a random number every second

- (void)viewDidLoad {
[super viewDidLoad];


NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(returnNumberMethod) userInfo:nil repeats:YES];

}

 - (void)returnNumberMethod {

[self returnRandomInt:^(NSInteger randNum) {

    NSLog(@"%ld", (long)randNum);
}];

}

- (void)returnRandomInt:(void (^)(NSInteger randNum)) completion {

NSInteger number = arc4random_uniform(100);

completion(number);

}

My swift attempt, but it didn't work, I know the syntax is wrong but would someone be able to help with translating the above code? Thank you!

override func viewDidLoad() {
    super.viewDidLoad()

    let timer = NSTimer(timeInterval: 1, target: self, selector: "getRandomNumber", userInfo: nil, repeats: true)

}

//block practice

func getRandomNumber() {

    self.randomNumber { (number) -> NSInteger in

        let numberString = NSString(format: "%ld", number)

        print(numberString)
    }
}

func randomNumber(completion: (number: NSInteger) -> NSInteger) {

    let numero = arc4random_uniform(100)

}

1 Answer 1

1

You are close: make the completion callback a method accepting an UInt32 (since that is the type returned by arc4random_uniform) and return void. Additionally change the syntax you are calling the function with. The following works:

func getRandomNumber() {
    randomNumber { number in
        let numberString = NSString(format: "%ld", number)
        print(numberString)
    }
}

func randomNumber(completion: (UInt32 -> Void)) {
    let numero = arc4random_uniform(100)
    completion(numero)
}

You can make use of the string magic in swift by using print("\(number)") instead of the string format.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.