How to Convert Any to Int in Swift

How to convert Any to Int in Swift

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

How to convert Any to Int in swift?

Less verbose answer:

let key = "result"
let stateCode = tResult?[key] as? Int ?? Int(tResult?[key] as? String ?? "")

Results:

let tResult: [String: Any]? = ["result": 123] // stateCode: 123
let tResult: [String: Any]? = ["result": "123"] // stateCode: 123
let tResult: [String: Any]? = ["result": "abc"] // stateCode: nil

How to convert AnyObject type to Int in Swift

I don't know your code but this will be helpful for you.

You can get your AnyObject value in this way...

let data :AnyObject = "100"
let score = Int(data as! String)! //Force Unwrap optional value it will be dengerious for nil condition.
print(score)

Or try this way also

let hitCount = "100"
let data :AnyObject = hitCount as AnyObject //sometime Xcode will ask value type
let score = Int(data as? String ?? "") ?? 0
print(score)


Output -

result



Swift 3.1 & Swift 4

let hitCount = "100"
let data :Any = hitCount //Any type Value passing here
let score = Int(data as? String ?? "") ?? 0
print(score)


Output -

Sample Image

Cast Array Any to Array Int in Swift

You need to create an Array from the ArraySlice created by dropFirst.

let timestamps = Array(xAxisData.dropFirst())
if let timestamps = timestamps as? [Int] {
}

Failing cast from Any to Int

If you don't know whether the id value is coming in as a String or an Int, you could try handling both:

switch fbValues["id"] {
case nil:
print("no id given")
case let string as String:
if let id = Int(string) { print("id = \(id)") }
else { print("non-numeric id \(string)") }
case let id as Int:
print("id = \(id)")
default:
print("what is this I don't even")
}

Casting Any? to Int, String or Bool

You don't want a function to return Any?. It is a nightmare of a type. Instead, you want to use generics to make sure the value is the type you want. For example:

static func value<T>(ofType: T.Type, forKey: SettingKeys) -> T? {
return settingManager.settings.filter({$0.key == forKey.rawValue}).first?.value as? T
}

Then this would be:

let printingEnabled = AppSettings().value(ofType: Int.self, forKey:"printingEnabled")

printingEnabled will in this case be Int?.

You can also, of course, wrap this up in helpers like:

static func int(forKey: SettingKeys) -> Int? {
return value(ofType: Int.self, forKey: forKey)
}

(BTW, while you definitely want to avoid Any? and use this kind of approach, I can't actually reproduce your issue. printingEnabled is Int? for me, and is Optional(1) as expected. I don't see any case where it's nil. But I can't make your code compile as written, either, since it's not clear what SettingKeys and settings are, so my code is probably significantly different than yours.)

Converting String to Int with Swift

Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

    // toInt returns optional that's why we used a:Int?
let a:Int? = firstText.text.toInt() // firstText is UITextField
let b:Int? = secondText.text.toInt() // secondText is UITextField

// check a and b before unwrapping using !
if a && b {
var ans = a! + b!
answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
} else {
answerLabel.text = "Input values are not numeric"
}

Update for Swift 4

...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...

Swift - Cast Any IntegerType to Int

Your problem is that you allowed Any to come into the picture. At that point, you lose a lot of power.

The other problem you're facing is that your code as written is poorly defined and Swift resists you writing code that way (basically by forcing you to be explicit). If you are passed a UInt64, there is no guarantee that size will have the same value as value. This is a very common problem when people seek an automatic way to convert between number types. Swift encourages you to think about numeric conversions because they are a common source of bugs.

There are several things you can do depending on what you're trying to solve. If you want a data structure that holds either an Int64 or a UInt64, that's easy. Just create the type you mean.

enum ParsedNumber {
case Signed(Int64)
case Unsigned(UInt64)
}

let numbers: [String: ParsedNumber] = [:]

Then all your values will fit in that. If you need to keep track of the width for later, that's no problem either:

struct ParsedNumber {
enum Value {
case Signed(Int64)
case Unsigned(UInt64)
}
let width: Int
let value: Value
}

let n = ParsedNumber(width: 32, value: .Signed(2))

This feels like the problem you're solving. If on the other hand you know your type at one point (i.e. it's Int8, not Any) and just want to be able to pass it to functions, just make the functions generic on IntegerType:

func calc<Num: IntegerType>(num: Num) { ... }

A useful tool on IntegerType is its toIntMax() method. This will trap (crash) if the value is too large, so be aware, but it's a useful way to convert arbitrary values to a known integer type. There are also SignedIntegerType and UnsignedIntegerType if you know your sign already. (You can't convert Any to these, though. You need to already have a known type somewhere.)



Related Topics



Leave a reply



Submit