Sha*_*tel 1 int ios swift swift2
我正在访问天气API,当我解析JSON时,结果是一个字符串.因为,我访问的值是一个数字,我想将其转换为整数,但是当字符串具有十进制值时,该字符串不会转换为int.我的代码:
let UVIndex = swiftyJSON["current_observation"]["UV"].stringValue
let cityName = swiftyJSON["current_observation"]["display_location"]["full"].stringValue
if let UVIndexInt = Int(UVIndex) {
print("Successfully converted! \(UVIndexInt)")
self.UVIndexString = String(stringInterpolationSegment: UVIndex)
}
dispatch_async(dispatch_get_main_queue()) {
self.UVIndexButton.setTitle(self.UVIndexString, forState: UIControlState.Normal)
self.cityName.text = cityName
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试将转换String为Double然后转换为Int.
let text = "1.1"
if let textAsDouble = Double(text) {
let textAsInt = Int(textAsDouble)
print(textAsInt)
}
Run Code Online (Sandbox Code Playgroud)