简体   繁体   English

如何在Swift中将AnyObject类型转换为Int

[英]How to convert AnyObject type to Int in Swift

I am searching a key in an Array of Dictionarys and I want to convert the result value into an Int value. 我在一个Dictionarys Array中搜索一个键,我想将结果值转换为Int值。 This is what I tried. 这是我试过的。

if let result = lasrIDArray.flatMap( {$0["\(self.selectedTitle)"]} ).first {      
    print(result)

    if let number = result as? NSNumber {
        let tag = number.integerValue
        let currentScroll = view.viewWithTag(Int(api.selectedCatID)!) as! UIScrollView
        let lastImgVw = currentScroll.viewWithTag(tag) as! UIImageView
        print(lastImgVw.frame.origin.y)
    }
}

But if let number = result as? NSNumber 但是if let number = result as? NSNumber if let number = result as? NSNumber doesn't work as expected. if let number = result as? NSNumber无法按预期工作。 What is the correct way to convert this value? 转换此值的正确方法是什么?

I don't know your code but this will be helpful for you. 我不知道你的代码,但这对你有帮助。

You can get your AnyObject value in this way... 您可以通过这种方式获取AnyObject值...

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 - 输出 -

结果


Swift 3.1 & Swift 4 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 - 输出 -

在此输入图像描述

If your data is decoded from JSON string, it will be decoded as NSNumber or NSString. 如果您的数据是从JSON字符串解码的,它将被解码为NSNumber或NSString。

You can use this function: 你可以使用这个功能:

func intValueForKey(key: String, inDictionary dictionary: [String: AnyObject]) throws -> Int {
    if let value = dictionary[key]?.integerValue {
        return value
    } else {
        throw NSError(domain: "Invalid key", code: -1, userInfo: nil)
    }
}

Here i have given example to convert Anyobject to Int and String 这里我给出了将Anyobject转换为Int和String的示例

var idInt : Int = 0
if let ids: AnyObject = responseDict["id"] {
    if let idsInt = ids as? Int{
        idInt  = idsInt
        print(idInt)
    }
}


var nameString : String = ""
    if let name: AnyObject = responseDict["name"] {
        if let nameStr = name as? String{
            nameString  = nameStr
            print(nameString)
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Swift中的NSDictionary:不能下标“AnyObject”类型的值吗? 索引类型为'Int' - NSDictionary in Swift:Cannot subscript a value of type 'AnyObject?' with a index of type 'Int' 将AnyObject转换为Int - Convert AnyObject to an Int 无法转换类型为“任何对象!”的值 到预期的参数类型“ Int” - cannot convert value of type 'Anyobject!' to expected argument type 'Int' 如何将[AnyObject]数组快速转换为字符串 - How to convert the [AnyObject] Array to string in swift 如何在Swift 2.3中将UInt8转换为Anyobject - How to Convert UInt8 to Anyobject in Swift 2.3 类型'Int32'不符合协议'AnyObject'Swift? - Type 'Int32' does not conform to protocol 'AnyObject' Swift? Swift类别:“无法将类型的值转换为预期的参数类型'AnyObject!' - Swift category: "Cannot convert value of type to expected argument type 'AnyObject!' Swift 2无法将'[AnyObject]'类型的值转换为预期的参数类型'[UIViewController]?' - Swift 2 Cannot convert value of type '[AnyObject]' to expected argument type '[UIViewController]?' Swift 2.2 AnyObject类型 - Swift 2.2 AnyObject Type Swift错误无法转换类型'(AFHTTPRequestOperation ?, AnyObject?)->()的值 - Swift error Cannot convert value of type '(AFHTTPRequestOperation?, AnyObject?) -> ()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM