检查String是否为Number(Double)

时间:2016-01-28 11:46:14

标签: swift swift2

问题。有必要检查String是否是Number(Double)? 例:

var s1:String = "df1231"
var s2:String = "1231,3123"
If s1.isDouble {
  Println("True.This Number!")
} else {
  Println("False.This not Number!") //Will give it
}
If s2.isDouble {
  Println("True.This Number!") //Will give it
} else {
  Println("False.This not Number!")
}

1 个答案:

答案 0 :(得分:2)

不确定您的需求是什么,但最简单的方法可能是:

func isDouble(text:String) -> Bool {
    guard let _ = Double(text.stringByReplacingOccurrencesOfString(",", withString: ".")) else { return false }
    return true
}

isDouble("df1231") // returns false
isDouble("1231,3123") // returns true

您可以将其粘贴到Playground以查看其是否有效。