【问题标题】:Get Int from String in Swift在 Swift 中从字符串中获取 Int
【发布时间】:2014-07-04 15:06:23
【问题描述】:

我想从一个字符串中创建一个 Int,但找不到方法。

这是我的func

func setAttributesFromDictionary(aDictionary: Dictionary<String, String>) {
    self.appId = aDictionary["id"].toInt()
    self.title = aDictionary["title"] as String
    self.developer = aDictionary["developer"] as String
    self.imageUrl = aDictionary["imageUrl"] as String
    self.url = aDictionary["url"] as String
    self.content = aDictionary["content"] as String
}

使用toInt() 时,我收到错误消息Could not find member 'toInt'。我也不能使用Int(aDictionary["id"])

【问题讨论】:

  • 您确定您的aDictionary["id"] 将始终是数字字符串,并且数字将始终适合 Int?

标签: string int swift


【解决方案1】:

使用dict[key] 方法为字典下标总是返回一个可选。例如,如果您的字典是Dictionary&lt;String,String&gt;,那么subscript 将返回一个类型为String? 的对象。因此,您看到“找不到成员 'toInt()'”的错误是因为 String?(可选)不支持 toInt()。但是,String 可以。

您可能还注意到toInt() 返回Int?,这是一个可选的。

根据您的需要推荐的方法是:

func setAttributesFromDictionary(aDictionary: Dictionary<String, String>) {
  if let value = aDictionary["id"]?.toInt() {
    self.appId = value
  }
  // ...
}

如果aDictionary 具有id 映射并且其值可转换为Int,则分配将发生。

在行动:

【讨论】:

  • 啊,我明白了。你的答案写得很好。
猜你喜欢
  • 1970-01-01
  • 2019-02-02
  • 2021-04-16
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多