Swift将UInt转换为Int

67c*_*ies 48 integer uint32 swift

我有这个表达式返回一个UInt32:

let randomLetterNumber = arc4random()%26
Run Code Online (Sandbox Code Playgroud)

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

if letters.count > randomLetterNumber{
    var randomLetter = letters[randomLetterNumber]
}
Run Code Online (Sandbox Code Playgroud)

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

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

问题是UInt32无法与之相提并论Int.我想投randomLetterNumber一个Int.我试过了:

let randomLetterUNumber : Int = arc4random()%26
let randomLetterUNumber = arc4random()%26 as Int
Run Code Online (Sandbox Code Playgroud)

这两个原因 could not find an overload for '%' that accepts the supplied arguments.

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

Dav*_*rry 81

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

  • 谢谢.我有一个类似的问题与arc4random_uniform(someArray.count)转换修复问题arc4random_uniform(UInt32(someArray.count)) (7认同)
  • 您可以在**[Apple的Swift文档]中阅读有关数字类型转换的更多信息(https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/TheBasics.html#//apple_ref/doc/UID/TP40014097-CH5-XID_420)**. (3认同)
  • 谢谢你,Int()初始化器似乎可以解决问题. (2认同)

Jos*_*osh 12

比这更简单,不可能:

Int(myUInteger)
Run Code Online (Sandbox Code Playgroud)


Fir*_*iro 11

只需用它创建一个新的int

let newRandom: Int = Int(randomLetterNumber)
if letters.count > newRandom {
    var randomLetter = letters[newRandom]
}
Run Code Online (Sandbox Code Playgroud)

或者如果您从不关心UInt32,您可以立即创建一个Int:

let randomLetterNumber = Int(arc4random() % 26)
Run Code Online (Sandbox Code Playgroud)


小智 6

你可以做

let u: UInt32 = 0x1234abcd
let s: Int32 = Int32(bitPattern: u)
Run Code Online (Sandbox Code Playgroud)