swift - 如何打开选项,我怎样才能编写这段代码以使其没有任何选项?或者 !在其中,或者有可能吗?

标签 swift

我很难重写这段代码,这样就没有选项了?放入其中或强制解开!到目前为止,我能够让它工作,但输出中有可选内容。我希望输出中不包含可选内容。

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 将是一个有效的实例,您可以使用它。

使用 guardif 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/

相关文章:

swift - 如何从内存中清除 SKSpriteNode?

ios - 如何在 ARKit 中制作自然光?

ios - 使用 J2ObjC 和 GSON 库将 Swift 类序列化为 JSON

ios - 如何从 Swift 中删除 Parse 中的对象

swift - 使用 swift 添加 NSNotification Observer

ios - 获取 UIButton 的长触力

ios - 在解除分配时尝试加载 View Controller 的 View

ios - 最初从 firebase 获取无效的推送 token ,最后获取有效的推送 token

ios - 如何在swift3 ios中以横向模式强制调用webview

arrays - 传递结构以构造结构数组