【问题标题】:How to convert AnyObject type to Int in Swift如何在 Swift 中将 AnyObject 类型转换为 Int
【发布时间】:2016-11-17 02:18:02
【问题描述】:

我在DictionarysArray 中搜索一个键,我想将结果值转换为Int 值。这是我尝试过的。

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)
    }
}

但是if let number = result as? NSNumber 没有按预期工作。转换此值的正确方法是什么?

【问题讨论】:

  • 作为回应,您收到的是 StringInt 请检查一下?
  • var num = Int(result) if num != nil { println("Valid Integer") } else { println("Not Valid Integer") }
  • 第 1 步:干净地格式化您的代码。
  • @SubinKKuriakose 无法在 var num = Int(result) 处使用类型为 (AnyObject) 的参数列表调用 Int 类型的初始化程序

标签: ios swift int


【解决方案1】:

我不知道您的代码,但这会对您有所帮助。

您可以通过这种方式获取您的 AnyObject 值...

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

或者也试试这个方法

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

输出 -


斯威夫特 3.1 和斯威夫特 4

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

输出 -

【讨论】:

  • 那么将可选值变为非可选值的最佳方法是什么。告诉我@dfri ??
  • 阅读this excellent canonical answer 的主题。引用:“作为一般规则,您永远不应该使用 ! 运算符显式强制解开可选项
  • @dfri 在你的Or try this way also:如果data:Anyobject的值为“abc”,可以用你的方法吗?
  • @aircraft 对不起,我不关注。 “在你的 Or try this way also”是什么意思?请注意,我链接到的线程通常是关于可选选项的(很好的)规范答案,但我不是写它的人。
  • 需要进行大量转换才能获得所要求的内容。为什么是斯威夫特!!..
【解决方案2】:

如果您的数据是从 JSON 字符串解码的,它将被解码为 NSNumber 或 NSString。

你可以使用这个功能:

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)
    }
}

【讨论】:

    【解决方案3】:

    这里我给出了将 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)
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2017-04-07
      • 2016-04-05
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多