快速警告:表达式隐含地从'String?'强制转换去任何

时间:2018-06-14 23:58:48

标签: 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的书,所以我只是搞乱了所有不同的数据类型和数据结构。完成这本书。

2 个答案:

答案 0 :(得分:0)

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

print,正式名称为print(_:separator:terminator:),可以使用任意数量的Any个参数。当您传递String?(从字典中下标的值)时,您将隐式地将其转换为Any,这会掩盖该值确实是可选的这一事实。警告建议您明确说明,如果模糊选项实际上是您想要的(例如print(array["one"] as Any))。通过明确表达这一点,你会说&#34;是的,我知道这个演员Any掩盖了选项,这就是我想要的。&#34;

您的更大问题是此代码需要进行主要代码审核:

  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>(a.k.a。[String: String])。
  6. 使用所有这些英语拼写单词作为字典的键是没有意义的。只需使用Array<String>(a.k.a。[String])!
  7. 以下是我建议如何实现这一点:

    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)")
    

答案 1 :(得分:0)

经过一小段休息后,我碰巧找到了解决办法。该解决方案仅涉及“展开”。可选的。在这种情况下,选项包括answer["zero"]answer["nineteen"]。因此,修复该错误所需的只是将!运算符添加到可选项中,代码将在没有警告的情况下运行。示例:answer["zero"]!。这是我修复错误的代码:

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)

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

如果有其他人偶然发现此错误消息,我希望我的帖子有帮助!