繁体   English   中英

如何将独立值绑定到数组中的字符串(Swift)?

[英]How can I tie independent values to strings in an array (Swift)?

所以我正在练习编码,我已经设置了一个字符串数组。 我想要发生的是有一个 function 随机 select 一个字符串,如果选择了某个字符串,它将打印出一条消息,如果选择了任何其他字符串,它将打印出不同的消息。 我认为设置消息可以使用 if-else function 来完成,但我被困在弄清楚如何识别调用哪个字符串的较早步骤上。

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

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

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

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

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM