快速警告 : expression implicitly coerced from 'String?' to Any

标签 swift

我目前正在自学 Swift 编程,但遇到了一条我不知道如何摆脱的错误消息。错误消息如下:

warning: expression implicitly coerced from 'String?' to Any

据我了解,此警告消息是由于我在代码中调用的 print() 函数需要“Any”类型的参数,而是传递“String”类型的参数,但我不确定如何抑制或防止此错误或消息。我的程序是一个简单的 Magic 8 Ball 命令行程序:

import Foundation

// Greet user, and then prompt he or she to ask his or her question
print("Welcome to Magic 8 Ball!")
print("What is your question? ")
var question = readLine()!

// Initialize a dictionary named 'answer', this array will contain all 20 of the
// standard Magic 8 Ball responses.
let answer = ["zero": "It is certain.",
    "one": "It is decidedly so.",
    "two": "Without a doubt.",
    "three": "Yes, definitely.",
    "four": "You may rely on it.",
    "five": "As I see it, yes.",
    "six": "Most likely.",
    "seven": "Outlook good.",
    "eight": "Yes.",
    "nine": "Signs point to yes.",
    "ten": "Reply hazy, try again.",
    "eleven": "Ask again later.",
    "twelve": "Better not tell you now.",
    "thirteen": "Cannot predict now.",
    "fourteen": "Concentrate and ask again.",
    "fifteen": "Don't count on it.",
    "sixteen": "My reply is no.",
    "seventeen": "My sources say no.",
    "eightteen": "Outlook not so good.",
    "nineteen": "Very doubtful."]

// Generate a random number between 0 and 19.
// We will use this number to choose chick answer to show the user
var randomUInt32:UInt32 = arc4random_uniform(20)
// Convert UInt32 datatype to Int
var randomInt: Int = Int(randomUInt32)

switch (randomInt) {
    case 0:
        print(answer["zero"]) // tell fortune
    case 1:
        print(answer["one"]) // tell fortune
    case 2:
        print(answer["two"]) // tell fortune
    case 3:
        print(answer["three"]) // tell fortune
    case 4:
        print(answer["four"]) // tell fortune
    case 5:
        print(answer["five"]) // tell fortune
    case 6:
        print(answer["six"]) // tell fortune
    case 7:
        print(answer["seven"]) // tell fortune
    case 8:
        print(answer["eight"]) // tell fortune
    case 9:
        print(answer["nine"]) // tell fortune
    case 10:
        print(answer["ten"]) // tell fortune
    case 11:
        print(answer["eleven"]) // tell fortune
    case 12:
        print(answer["twelve"]) // tell fortune
    case 13:
        print(answer["thirteen"]) // tell fortune
    case 14:
        print(answer["fourteen"]) // tell fortune
    case 15:
        print(answer["fifteen"]) // tell fortune
    case 16:
        print(answer["sixteen"]) // tell fortune
    case 17:
        print(answer["seventeen"]) // tell fortune
    case 18:
        print(answer["eightteen"]) // tell fortune
    case 19:
        print(answer["nineteen"]) // tell fortune
    default:
        print("ERROR: PC LOAD LETTER") // tell fortune
}

程序输出:

Optional("Yes, definitely.")

注意:我知道字典对于这个特定的程序来说并不是一个很好的选择,但我正在阅读一本关于 Swift 的书,所以我只是在处理所有不同的数据类型和数据结构。通读这本书。

最佳答案

当您调用 answer["one"] 之类的电话时,您正在调用 Dictionary.subscript(_:) 。这会返回一个可选值(在本例中为 String? ,又名 Optional<String> ),因为据编译器所知,给定键 ( "one" ) 可能没有值。

print ,正式名称为 print(_:separator:terminator:) 取任意数量的Any论据。当您通过String?时(字典下标的值),您将其隐式转换为 Any ,这掩盖了该值确实是可选的这一事实。该警告建议您明确这一点,如果模糊可选性确实是您想要的(例如 print(array["one"] as Any) )。通过像这样明确地表达出来,你会说“是的,我知道这个强制转换为 Any 掩盖了可选性,而这就是我想要的。”

您更大的问题是此代码需要主要代码审查:

  1. // Greet user, and then prompt he or she to ask his or her question
    • 是的。我们可以看到这一点。 print("Welcome to Magic 8 Ball!")清晰地打印出问候语。
    • 是的,print("What is your question?")显然是在问问题。
  2. print(answer["four"]) // tell fortune
    • 这条评论也是显而易见的,没有理由写。
  3. print("ERROR: PC LOAD LETTER") // tell fortune
    • "ERROR: PC LOAD LETTER"这是一个奇怪的算命。
  4. 如果您只是使用更好的变量名称,则无需注释明显的内容,以便可以直接从代码中读取意图。对需要解释的部分写下注释。不要编写仅仅让 Swift 传达给读者的评论。
  5. 您的array实际上是一个Dictionary<String, String> (又名 [String: String] )。
  6. 使用所有这些英文拼写的单词作为字典的关键字是没有意义的。只需使用 Array<String> (又名 [String] )!

以下是我建议的实现方式:

import Foundation

let magic8BallAnswers = [
    "It is certain.",
    "It is decidedly so.",
    "Without a doubt.",
    "Yes, definitely.",
    "You may rely on it.",
    "As I see it, yes.",
    "Most likely.",
    "Outlook good.",
    "Yes.",
    "Signs point to yes.",
    "Reply hazy, try again.",
    "Ask again later.",
    "Better not tell you now.",
    "Cannot predict now.",
    "Concentrate and ask again.",
    "Don't count on it.",
    "My reply is no.",
    "My sources say no.",
    "Outlook not so good.",
    "Very doubtful.",
]

extension Array {
    func randomElement() -> Element? {
        if self.isEmpty { return nil }
        return self[Int(arc4random_uniform(UInt32(self.count)))]
    }
}

print("Welcome to Magic 8 Ball!")
print("What is your question?")
var question = readLine()!

// Forceunwrap is justified here, because we know the array is not empty.
let answer = magic8BallAnswers.randomElement()!
print("Magic 8 Ball says: \(answer)")

关于快速警告 : expression implicitly coerced from 'String?' to Any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867469/

相关文章:

swift text.draw 方法搞乱了 CGContext

ios - 在 Swift iOS 中单击按钮将 View 移动到另一个 View

swift - Poisson Disk Generator 排除了四个 View 象限中的三个

ios - 如何修复 : "Expression is Ambiguous".

ios - 截取当前未打开的 ViewController 的屏幕截图

swift - 在 SQLite 数据库中返回行时出现 "unexpectedly found nil while unwrapping an Optional value"错误

ios - Swift: "Any"没有名为元素的成员

ios - 在后台模式下监听设备摇动事件

ios - 使用 JSONDecoder 解码古怪的日期格式

ios - 实例方法 'mapView(_:didFailToLocateUserWithError:)'几乎符合可选要求