Swift 3 銀行金額驗證

weixin_33866037發表於2017-01-08

給String寫一個分類,對外提供一個方法,判斷輸入數字是否>0

extension String {
    func enteredCorrectly() -> Bool {
        if characters.count == 0 {
            return false
        }
        
        let scan = Scanner(string: self)
        let isNotZero = Double(self)
        
        guard let isNum = isNotZero  else {
            return false
        }
        if isNum > 0 {
            if contains(".") {
                
                if let rangeOfZero = range(of: ".", options: .backwards) {
                    
                    let suffix = String(characters.suffix(from: rangeOfZero.lowerBound))
                    if (suffix.characters.count > 2) {
                       // showAlert(controller, message: "您輸入的金額有誤")
                        return false
                    }
                }
                var float: Float = 0
                guard !(scan.scanFloat(&float) && scan.isAtEnd) else { return true }
            } else {
                var int: Int64 = 0
                guard !(scan.scanInt64(&int) && scan.isAtEnd) else { return true }
            }
        }
        return false
    }
}

相關文章