我有一个看起来像
的数组:NSString[X1],[Tester],[123],[456],[0]
现在我必须检查一个位置(总是相同的)是数字还是字符串
所以我试过
var test = Array[0].intValue
print(test)
但是[0]是一个字符串,它不应该返回0,因为它也可能是[4]
0
有没有办法检查NSString是否只是一个数字(返回true / false就足够了)?
完整代码示例
var Array: [NSString] = ["X1","Fabian","100","200","not avaible"]
/* could also be Array:
var Array0: [NSString] = ["X2","Timo","200","300","300"]
*/
//need to check if Array[4] is a number or not so its "text" or "number"
var test = Array[4].intValue
print(test)
//return 0
答案 0 :(得分:4)
在swift2中:
你可以使用Int(<your variable>)
如果它可以强制转换它返回数字,否则它返回nil,你可以检查返回的值。
使用可选条件的示例:
let s = "Some String"
if let _ = Int(s) {
print("it is a number")
}else{
print("it is not a number")
}
此示例应返回&#34;它不是数字&#34;
答案 1 :(得分:0)
如果您想收集数组元素为数字的索引,您可以使用映射并返回可以将元素转换为数字的索引。
var Array0: [NSString] = ["X1","Fabian","100","200","not avaible"]
var numbersAt: [Int] = Array0.enumerate().map{ (index, number) in
return (Int(number as String) == nil ? -1 : index)
}
print("indexes: \(numbersAt)") //numbersAt will have the indexes unless they're not numbers in which case it'll have -1
//Another option will be to filter the array and collect only the number strings
var numbers = Array0.filter { Int($0 as String) != nil }
print("numbers: \(numbers)")