Swift NSString 检查数字
Swift NSString check for Numbers
我有一个 Array:NSString 看起来像
[X1],[Tester],[123],[456],[0]
现在我必须检查一个位置(总是相同的)是数字还是字符串
所以我尝试了
var test = Array[0].intValue
print(test)
但由于 [0] 是一个字符串,它不应该是 return 0,因为它也可以是 [4]
0
有没有办法检查 NSString 是否只是一个数字(return 或 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
在 swift2 中:
您可以使用 Int(<your variable>)
它 return 是数字,如果它可以投射,否则它 return 零,你可以检查 returned 值。
使用可选条件的示例:
let s = "Some String"
if let _ = Int(s) {
print("it is a number")
}else{
print("it is not a number")
}
这个例子应该return"it is not a number"
如果要收集数组元素为数字的索引,可以使用映射并返回元素可以转换为数字的索引。
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([=10=] as String) != nil }
print("numbers: \(numbers)")
我有一个 Array:NSString 看起来像
[X1],[Tester],[123],[456],[0]
现在我必须检查一个位置(总是相同的)是数字还是字符串
所以我尝试了
var test = Array[0].intValue
print(test)
但由于 [0] 是一个字符串,它不应该是 return 0,因为它也可以是 [4]
0
有没有办法检查 NSString 是否只是一个数字(return 或 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
在 swift2 中:
您可以使用 Int(<your variable>)
它 return 是数字,如果它可以投射,否则它 return 零,你可以检查 returned 值。
使用可选条件的示例:
let s = "Some String"
if let _ = Int(s) {
print("it is a number")
}else{
print("it is not a number")
}
这个例子应该return"it is not a number"
如果要收集数组元素为数字的索引,可以使用映射并返回元素可以转换为数字的索引。
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([=10=] as String) != nil }
print("numbers: \(numbers)")