[英]How to convert NSString to Int so I can add in swift 3.0
我有一個似乎是Int的值,但是當我輸入type(of:value)時,它返回Optional,在嘗試了許多事情之后,我發現數據類型為NSString。
let sum = data[0]["total1"] + data[0]["total2"]
我有兩個這樣的值,但我想將它們相加,但是它不允許我說“二進制運算符+無法應用於兩個“任何”操作數”或“類型為“任何”的值沒有成員'intValue' ”。
如何將“任何”轉換為Int,以便可以添加它們?
提前致謝。
使用可選綁定確保值是非nil字符串,並且可以將它們轉換為Int
。
if let str1 = data[0]["total1"] as? String, let str2 = data[0]["total2"] as? String {
if let int1 = Int(str1), let int2 = Int(str2) {
let sum = int1 + int2
} else {
// One or more of the two strings doesn't represent an integer
}
} else {
// One or more of the two values is nil or not a String
}
由於基礎對象是NSString
,因此您還可以執行以下操作:
if let num1 = (data[0]["total1"] as? NSString)?.intValue,
let num2 = (data[0]["total2"] as? NSString)?.intValue {
let sum = num1 + num2
}
正如@rmaddy在評論中指出的那樣,如果值不是整數(例如"hello"
),它將轉換為0
。 根據您對應用程序正在接收的數據的了解以及在這種情況下要發生的情況,該結果可能合適也可能不合適。
與Int(str)
相比, .intValue
更能容忍字符串數據格式。 前導空格和尾隨空格將被忽略,浮點值(如13.1
將轉換為整數。 同樣,這取決於您想要在應用程序中發生什么。
這是我的方法:
extension String {
var asInt: Int? {
return Int(self)
}
var isInt: Bool {
return Int(self) != nil
}
}
call it as follows (assuming a property called result):
let stringOne = "14"
let stringTwo = "12"
if stringOne.isInt && stringTwo.isInt {
self.result = stringOne.asInt + stringTwo.asInt
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.