从Swift中的String获取Int

Pau*_*len -1 string int swift

我想从String中创建一个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
}
Run Code Online (Sandbox Code Playgroud)

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

GoZ*_*ner 6

使用该dict[key]方法订阅字典始终返回可选字典.例如,如果你的字典Dictionary<String,String>,然后subscript会返回一个对象类型String?.因此,您看到"无法找到成员'toInt()'"的错误,因为String?,可选,不支持toInt().但是,String确实如此.

您还可以注意toInt()返回Int?,可选.

建议的方法是满足您的需求:

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

如果iff aDictionary具有id映射并且其值可转换为a,则将进行赋值Int.

在行动: 在此输入图像描述