我有一个数字数组
var shoppingList: [String] = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"]
我想在我的标签中显示 shoppingList
中的 3 个随机词。
我还有 10 个带有数字 1,2,3,4,5,6,7,8,9,0
的按钮。我想在我的 textField
中输入等于数组中 3 个随机单词的数字,如果我成功或得到 print("不是”)
。怎么做?
示例:例如我得到这 3 个单词 one , five , three
这意味着我应该按下带有数字 1,5,3
的按钮并输入这些数字在 textField
中。
@IBAction func numerals(_ sender: UIButton) {
let number = sender.currentTitle
textField.text = textField.text! + number!
if (textField.text?.count)! > 2 {
}
}
更新
var rand1 = ""
var rand2 = ""
var rand3 = ""
var textField1 = [Int]()
var code = [String]()
override func viewDidLoad() {
super.viewDidLoad()
var shoppingList: [String] = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "zero"]
rand1 = shoppingList[Int(arc4random()%(UInt32(shoppingList.count)))]
rand2 = shoppingList[Int(arc4random()%(UInt32(shoppingList.count)))]
rand3 = shoppingList[Int(arc4random()%(UInt32(shoppingList.count)))]
//ensures rand1 and rand2 are not the same
while(rand2 == rand1){
rand2 = shoppingList[Int(arc4random()%(UInt32(shoppingList.count)))]
}
//ensures rand3 is different from rand1 and rand2
while(rand3 == rand1 || rand3 == rand2){
rand3 = shoppingList[Int(arc4random()%(UInt32(shoppingList.count)))]
}
code = ["\(rand1), \(rand2), \(rand3)"]
label?.text = "\(rand1), \(rand2), \(rand3)"
}
func wordToNumber(with word: String) -> Int? {
switch word {
case "zero":
return 0
case "one":
return 1
case "two":
return 2
case "three":
return 3
case "four":
return 4
case "five":
return 5
case "six":
return 6
case "seven":
return 7
case "eight":
return 8
case "nine":
return 9
default:
return nil
}
}
func checkIfCodeIsCorrect() -> Bool {
let codeAsNumbers = code.map { return wordToNumber(with: $0) }
print(codeAsNumbers)
return codeAsNumbers == textField1
}
@IBAction func control(_ sender: UIButton) {
let number = sender.currentTitle
textField.text = textField.text! + number!
textField1.append(Int(number!)!)
print(textField1)
if (textField.text?.count)! > 2 {
print(checkIfCodeIsCorrect())
}
}
最佳答案
所以,既然你改了问题,我会重新提交一个答案。
您需要做的只是将 String
转换为 Int
,这样您就可以比较数字了。这是您需要的代码:
import Foundation
import UIKit
func wordToNumber(with word: String) -> Int? {
switch word {
case "zero":
return 0
case "one":
return 1
case "two":
return 2
case "three":
return 3
case "four":
return 4
case "five":
return 5
case "six":
return 6
case "seven":
return 7
case "eight":
return 8
case "nine":
return 9
default:
return nil
}
}
var textFieldInts = [3, 2, 6, 7, 1]
var code = ["three", "two", "six", "seven", "one"]
func checkIfCodeIsCorrect() -> Bool {
let codeAsNumbers = code.map { return wordToNumber(with: $0) }
return codeAsNumbers == textFieldInts
}
print(checkIfCodeIsCorrect()) // Perform task if they are equal by placing an if or guard statement
textFieldInts
是用户输入的值,如[Int]
。code
是您显示给用户输入的数字,如[String]
。
关于ios - swift:数组中的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51407180/