Swift将UInt转换为Int [英] Swift convert UInt to Int

查看:445
本文介绍了Swift将UInt转换为Int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个表达式返回 UInt32

let randomLetterNumber = arc4random()%26

我希望能够使用此if语句中的数字:

I want to be able to use the number in this if statement:

if letters.count > randomLetterNumber{
    var randomLetter = letters[randomLetterNumber]
}

这个问题是控制台给我这个

This issue is that the console is giving me this

Playground execution failed: error: <REPL>:11:18: error: could not find an overload for '>' that accepts the supplied arguments
if letters.count > randomLetterNumber{
   ~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~

问题是 UInt32 无法与 Int 。我想将 randomLetterNumber 转换为 Int 。我试过了:

The problem is that UInt32 cannot be compared to an Int. I want to cast randomLetterNumber to an Int. I have tried:

let randomLetterUNumber : Int = arc4random()%26
let randomLetterUNumber = arc4random()%26 as Int

这两个原因找不到'%'的重载接受提供的参数。

如何转换值或在if语句中使用它?

How can I cast the value or use it in the if statement?

推荐答案

Int(arc4random_uniform(26))做两件事,一件它消除了当前方法的负面结果,其次应该从结果中正确创建一个Int。

Int(arc4random_uniform(26)) does two things, one it eliminates the negative results from your current method and second should correctly creat an Int from the result.

这篇关于Swift将UInt转换为Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆