How to convert string to UInt32? - swift

I am a beginner in swift and I am having a problem with convering string to UInt32.
let Generator = (ReadableJSON ["People"] [Person]["F1"].string! as NSString).doubleValue
if Generator == 1 {
NameLabel1 = ReadableJSON ["People"] [Person]["A1"].string as String!
NameImeNaObekt = ReadableJSON ["People"] [Person] ["B1"].string as String!
Picture = ReadableJSON ["People"] [Person] ["E1"].string as String!
} else {
let RGen = arc4random_uniform ("\(Generator)") // here is the error
}
Would you advise me how to fix it. The problem is in the last line, which is red and it says Cannot convert value of type String to UInt32.
The main idea is that I am reading the number from a JSON file and I have to populate this number into the arc4random_uniform.

arc4random_uniform(UInt32)
accept an UInt32 value but you are passing an String value to it
this converts your number to string
"\(Generator)"
the last line should be like this
let RGen = arc4random_uniform (UInt32(Generator))
and if you want to 'RGen' is an String you can do it this way
"\(RGen)"
String(RGen)

var RGen= 0
let RGen =int( arc4random_uniform ("\(Generator)") )
or
let RGen =( arc4random_uniform ("(Generator)") ).toInt
Look here

Related

Swift randomizer with variables

I have two String Type values as Int number.
I like to randomize between these two.
With this code:
let random = Int.random(in: myvar1...myvar2)
it does not work. How can i fix it?
I assume your variables look like this?
let myvar1: String = "1"
let myvar2: String = "10"
Those are both Strings, so myvar1...myvar2 becomes a range of String.
However, the random(in:) method takes in a range of Int, so you'll first need to convert them to Ints.
if let myvar1Int = Int(myvar1), let myvar2Int = Int(myvar2) {
let random = Int.random(in: myvar1Int...myvar2Int)
print(random) /// Result: 6
}

Cannot convert value of type Substring to expected argument type String - Swift 4

Trying to get substring of String and append it to array of Strings:
var stringToSplit = "TEST TEXT"
var s = [String]()
let subStr = anotherString[0 ..< 6]
s.append(subStr) // <---- HERE I GET THE ERROR
As #Leo Dabus mentioned, you need to initialize a new String with your substring:
Change:
s.append(subStr)
To:
s.append(String(subStr))
my two cents for serro in different context.
I was trying to get an array of "String" splitting a string.
"split" gives back "Substring", for efficiency reason (as per Swift.org litre).
So I ended up doing:
let buffer = "one,two,three"
let rows = buffer.split(separator:",")
let realStrings = rows.map { subString -> String in
return String(subString)
}
print(realStrings)
Ape can help someone else.

User input in swift toInt() returning nil

i'm trying to create a simple user input but the only function that i have found in swift is this one
func input() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
return NSString(data: inputData, encoding:NSUTF8StringEncoding) as String!
}
then i'm trying to convert input() to an Int for a mathematic operation (i'm using 1 as the input) with this
var inputToInt = input().toInt()!
in this point i get only nil i don't know what to do.
Swift 2.0 has a function called readLine() - using it is a much better idea than rolling your own.
http://swiftdoc.org/swift-2/func/readLine/
Your conversion to Int fails because the string contains newline. You can use this to clean it up:
let s = NSString(data: inputData, encoding:NSUTF8StringEncoding) as String!
if s.hasSuffix("\n") {
return s.substringToIndex(x.endIndex.predecessor())
} else {
return s
}

How to convert string in JSON to int Swift

self.event?["start"].string
The output is = Optional("1423269000000")
I want to get 1423269000000 as an Int
How can we achieve this? I have tried many ways such NSString (but it changed the value)
Your value: 1,423,269,000,000 is bigger than max Int32 value: 2,147,483,647. This may cause unexpected casting value. For more information, check this out: Numeric Types.
Try to run this code:
let maxIntegerValue = Int.max
println("Max integer value is: \(maxIntegerValue)")
In iPhone 4S simulator, the console output is:
Max integer value is: 2147483647
And iPhone 6 simulator, the console output is:
Max integer value is: 9223372036854775807
This information may help you.
But normally to convert Int to String:
let mInt : Int = 123
var mString = String(mInt)
And convert String to Int:
let mString : String = "123"
let mInt : Int? = mString.toInt()
if (mInt != null) {
// converted String to Int
}
Here is my safe way to do this using Optional Binding:
var json : [String:String];
json = ["key":"123"];
if var integerJson = json["key"]!.toInt(){
println("Integer conversion successful : \(integerJson)")
}
else{
println("Integer conversion failed")
}
Output:
Integer conversion successful :123
So this way one can be sure if the conversion was successful or not, using Optional Binding
I'm not sure about your question, but say you have a dictionary (Where it was JSON or not) You can do this:
var dict: [String : String]
dict = ["key1" : "123"]
var x : Int
x = dict["key1"].toInt()
println(x)
Just in case someone's still looking for an updated answer, here's the Swift 5+ version:
let jsonDict = ["key": "123"];
// Validation
guard let value = Int(jsonDict["key"]) else {
print("Error! Unexpected value.")
return
}
print("Integer conversion successful: \(value)")
// Prints "Integer conversion successful: 123"

How to convert Any to Int in Swift

I get an error when declaring i
var users = Array<Dictionary<String,Any>>()
users.append(["Name":"user1","Age":20])
var i:Int = Int(users[0]["Age"])
How to get the int value?
var i = users[0]["Age"] as Int
As GoZoner points out, if you don't know that the downcast will succeed, use:
var i = users[0]["Age"] as? Int
The result will be nil if it fails
Swift 4 answer :
if let str = users[0]["Age"] as? String, let i = Int(str) {
// do what you want with i
}
If you are sure the result is an Int then use:
var i = users[0]["Age"] as! Int
but if you are unsure and want a nil value if it is not an Int then use:
var i = users[0]["Age"] as? Int
“Use the optional form of the type cast operator (as?) when you are
not sure if the downcast will succeed. This form of the operator will
always return an optional value, and the value will be nil if the
downcast was not possible. This enables you to check for a successful
downcast.”
Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks.
https://itun.es/us/jEUH0.l
This may have worked previously, but it's not the answer for Swift 3. Just to clarify, I don't have the answer for Swift 3, below is my testing using the above answer, and clearly it doesn't work.
My data comes from an NSDictionary
print("subvalue[multi] = \(subvalue["multi"]!)")
print("as Int = \(subvalue["multi"]! as? Int)")
if let multiString = subvalue["multi"] as? String {
print("as String = \(multiString)")
print("as Int = \(Int(multiString)!)")
}
The output generated is:
subvalue[multi] = 1
as Int = nil
Just to spell it out:
a) The original value is of type Any? and the value is: 1
b) Casting to Int results in nil
c) Casting to String results in nil (the print lines never execute)
EDIT
The answer is to use NSNumber
let num = subvalue["multi"] as? NSNumber
Then we can convert the number to an integer
let myint = num.intValue
if let id = json["productID"] as? String {
self.productID = Int32(id, radix: 10)!
}
This worked for me. json["productID"] is of type Any.
If it can be cast to a string, then convert it to an Integer.