swift 如何寻址数组中的当前随机元素?

u3r8eeie  于 2022-12-17  发布在  Swift
关注(0)|答案(2)|浏览(139)

我有一系列不同的游戏任务:

var tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]

此任务文本显示在标签中并随机选取:

myLabel.text = tasksArray.randomElement()

我如何寻址随机选取的同一个元素?我应该插入什么来代替我放在数组指针后面的“??????”?

startLabel.text = "WRONG! TRY AGAIN. \(tasksArray.???????)"

如果我这样输入:

startLabel.text = "WRONG! TRY AGAIN. \(tasksArray.randomElement()!)"

它给出一个新的随机元素。

o2gm4chl

o2gm4chl1#

不要将randomElement的结果直接存储到标签中,而是将其保存到示例变量中,以便以后使用。

class Foo {

   let tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]
   var randomString = ""

    func updateRandom {
        randomString = tasksArray.randomElement()
        myLabel.text = randomString
    }

    func badGuess {
        startLabel.text = "WRONG! TRY AGAIN. \(randomString)"
    }
}

(我把东西 Package 在一个类中,这样我就有地方放一个示例变量,并把代码放在函数中,这样就有意义了。你的代码结构会有所不同,但这说明了我的想法。)
如果记住特定的数组项而不仅仅是保存它的字符串值很重要,你可以保存一个整数索引而不是字符串(假设你的任务是一个结构体而不是字符串数组)。

class Foo {

   let tasksArray = ["Find a star", "Find a cloud", "Find a book", "Find a sun", "Find a moon", "Find a flame", "Find eyes", "Find a case", "Find a globe"]
   var randomIndex = 0

    func updateRandom {
        let randomIndex = Int.random(0..<tasksArray.count))
        randomString = tasksArray[randomIndex]
        myLabel.text = randomString
    }

    func badGuess {
        startLabel.text = "WRONG! TRY AGAIN. \(tasksArray[randomIndex])"
    }
}
vohkndzv

vohkndzv2#

你可以像下面这样得到随机元素的索引

let yourArray : [String] = ["as","dsa","asd","dfsdf"]
    
let yourRandomString = yourArray.randomElement()
    
if let indexOfRandomString = yourArray.firstIndex(of: yourRandomString ?? "") {
    //here you have the index of your random element and you can access it like below
    let b = yourArray[indexOfRandomString]

    }

相关问题