这是一个常见问题,但我找不到解决我具体问题的答案。我正在创建一个程序,它接收用户输入的信用卡并返回信用卡类型。一切似乎都要检查,除了我不断收到错误" ViewController没有会员名称&all;所有价值'。有谁知道如何解决这个问题?
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var typeLabel: UILabel!
@IBOutlet weak var creditCardTextField: UITextField!
@IBAction func CardTypePressed(sender: AnyObject) {
enum CardType: String {
case None = "None"
case Visa = "Visa"
case AmericanExpress = "American Express"
case Mastercard = "Mastercard"
case Discover = "Discover"
private func regularExpression() -> NSRegularExpression {
switch self {
case .Visa:
return NSRegularExpression(pattern: "^4[0-9]{12}(?:[0-9]{3})?$", options: nil, error: nil)!
case .AmericanExpress:
return NSRegularExpression(pattern: "^3[47][0-9]{13}$", options: nil, error: nil)!
case .Mastercard:
return NSRegularExpression(pattern: "^5[1-5][0-9]{14}$", options: nil, error: nil)!
case .Discover:
return NSRegularExpression(pattern: "^6(?:011|5[0-9]{2})[0-9]{12}$", options: nil, error: nil)!
default:
return NSRegularExpression(pattern: ".*", options: nil, error: nil)!
}
}
func isValidFor(cardNumber: String) -> Bool {
let re = self.regularExpression()
let range = NSRange(0..<cardNumber.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let matches = re.numberOfMatchesInString(cardNumber, options: nil, range: range)
return matches > 0
}
static let allValues = [Visa, AmericanExpress, Mastercard, Discover]
}
func from(cardNumber: String) -> CardType {
for type in CardType.allValues {
if type.isValidFor(cardNumber) {
return type
}
}
return CardType.None
}
var creditCardType = CardType.from(creditCardTextField).toRaw()
typeLabel.text = "Credit Card Type: \(creditCardType)"
}
}
答案 0 :(得分:1)
allValues
self
你可能意味着CardType.allValues
。像这样:
func from(cardNumber: String) -> CardType {
for type in CardType.allValues {
if type.isValidFor(cardNumber) {
return type
}
}
return CardType.None
}