我正在尝试创建一种简单的用户登录方式,但目前它似乎不起作用。我不断收到错误消息,并在 .Email(LoginUser)
enum LoginProvider {
case Facebook
case Email(String, String)
func login() {
switch self {
case .Email(LoginUser) where LoginUser.isValid():
break
case .Facebook:
break
}
}
}
struct LoginUser {
let email: String
let password: String
func isValid() -> Bool {
return email != "" && password != ""
}
}
最佳答案
你在代码中犯了一些错误,这是修复后的版本:
enum LoginProvider {
case Facebook
case Email(LoginUser) // note that LoginUser is used as Type here
func login() {
switch self {
// And here, loginUser is an instance of type LoginUser
case .Email(let loginUser) where loginUser.isValid():
break
case .Email(let loginUser):
// Switch has to be exhaustive,
// in this case you should handle invalid user
break
case .Facebook:
break
}
}
}
struct LoginUser {
let email: String
let password: String
func isValid() -> Bool {
return !email.isEmpty && !password.isEmpty
}
}
我还建议您查看 Apple's Swift book 中有关关联值的章节.
关于swift - 使用枚举登录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625019/