我很难重写这段代码,这样就没有选项了?放入其中或强制解开!到目前为止,我能够让它工作,但输出中有可选内容。我希望输出中不包含可选内容。
class CeaserCipher {
var secret: Int? = 0
func setSecret(_ maybeString: String?) {
guard let stringSecret = maybeString else {
return
}
self.secret = Int(stringSecret)
}
}
let cipher = CeaserCipher()
cipher.setSecret(nil)
print(cipher.secret)
cipher.setSecret("ten")
print(cipher.secret)
cipher.setSecret("125")
print(cipher.secret)
最佳答案
所以,你有一只猫,有很多方法可以剥它的皮。
例如,您“可以”通过提供可失败的构造函数来使密码不可变......
struct CeaserCipher {
let secret: Int
init?(string: String) {
guard let value = Int(string) else { return nil }
secret = value
}
}
这并不能阻止您处理可选值,但这意味着 CeaserCipher
的实例将是有效的。
struct
至少有一个要求,即您有一个非可选的String
,因此您需要首先验证它
所以如果你做了类似的事情......
let cipher = CeaserCipher(string: "Bad")
cipher
将是 nil
并且您需要处理它,但是如果您做了类似的事情...
let cipher = CeaserCipher(string: "123456789")
cipher
将是一个有效的实例,您可以使用它。
使用 guard
和 if let
在这里很重要,因为它们可以让您避免代码崩溃,您将根据您的需要使用哪种代码。
guard let cipher = CeaserCipher(string: "123456789") else {
// Cipher is invalid, deal with it...
return
}
// Valid cipher, continue to work with it
或
if let cipher = CeaserCipher(string: "123456789") {
// Valid cipher, continue to work with it
} else {
// Cipher is invalid, deal with it...or not
}
这个例子的要点是,你要么得到一个有效的CeaserCipher
实例,要么得到一个nil
,这“通常”比拥有一个在无效状态,通常更容易处理
关于swift - 如何打开选项,我怎样才能编写这段代码以使其没有任何选项?或者 !在其中,或者有可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55602926/