【问题标题】:How can I tie independent values to strings in an array (Swift)?如何将独立值绑定到数组中的字符串(Swift)?
【发布时间】:2021-04-24 10:17:33
【问题描述】:

所以我正在练习编码并设置了一个字符串数组。我想要发生的是让一个函数随机选择一个字符串,如果选择了某个字符串,它将打印出一条消息,如果选择了任何其他字符串,它将打印出另一条消息。我认为可以使用 if-else 函数来设置消息,但我一直停留在弄清楚如何识别调用哪个字符串的较早步骤上。

我做了一些搜索,发现了这个线程Get Random String from an Array,我从中复制了随机化代码。我有点不知所措。

我需要设置什么类型的函数/标识符等以便唯一标识字符串?

class ViewController: UIViewController {
    
    // Make collection of games and if Monsters is called, print "Take a break." If a diff string is called, print "Do your homework."
    @IBAction func random(_ sender: UIButton) {
        let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
        let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
        _ = games[randomNumber]
    }
} // end of class

【问题讨论】:

    标签: arrays swift string random


    【解决方案1】:

    从你的问题中你的期望不是很清楚,但我猜你是初学者,需要帮助处理随机选择的字符串。

    @IBAction func random(_ sender: UIButton) {
                let games = ["Cards Against Humanity", "Mario Kart", "Halo", "Pixeljunk Monsters"]
                let randomNumber = Int(arc4random_uniform(UInt32(games.count)))
                let randomlyPickedString = games[randomNumber]
                if randomlyPickedString == "Cards Against Humanity" {
                    print("Print anything you want about Cards Against Humanity")
                }
                else if randomlyPickedString == "Mario Kart" {
                    print("Print anything you want about Mario Kart")
                }
                else if randomlyPickedString == "Halo" {
                    print("Print anything you want about Halo")
                }
                else {
                    print("Print anything you want about Pixeljunk Monsters")
                }
            }
    

    如果它是数组中的一组有限值,您甚至可以决定使用switch

    【讨论】:

    • 谢谢,我明天试试!
    • @ILoveChickenWings:有用吗?如果是,请考虑接受答案:)
    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 2021-09-05
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多