Python 我怎么能把Swift中的一个词弄乱呢
我正在尝试使用Swift为iPhone创建一个单词混乱游戏。我对编程和Swift相对来说比较陌生,但之前已经用Python创建了这个游戏 这是我的伪代码:Python 我怎么能把Swift中的一个词弄乱呢,python,swift,Python,Swift,我正在尝试使用Swift为iPhone创建一个单词混乱游戏。我对编程和Swift相对来说比较陌生,但之前已经用Python创建了这个游戏 这是我的伪代码: import UIKit //this is my array/word bank var words = ["Apple", "Orange", "Pear"] //this selects a random word in the array var selectedWord = words[Int(arc4random_uniform
import UIKit
//this is my array/word bank
var words = ["Apple", "Orange", "Pear"]
//this selects a random word in the array
var selectedWord = words[Int(arc4random_uniform(UInt32(words.count)))]
//this counts the number of characters in the string
var length = (countElements(selectedWord))
//this randomly selects a position within the string
var position = Int(arc4random_uniform(UInt32(length)))
//this creates a new string consiting of the letter found in the position from the previous line of code
var subString = selectedWord[advance(selectedWord.startIndex, position)]
//从数组中选择随机字
//确定随机选择的单词中的字符数
//在字符数范围内随机选择一个数字(即,如果单词为“apple”,则选择一个介于0和4之间的数字)
//选择与随机选择的数字对应的字符
//将字符添加到新字符串(混杂)
//从随机选择的单词中删除字符
//重复,直到随机单词为空
这是到目前为止我的代码:
import UIKit
//this is my array/word bank
var words = ["Apple", "Orange", "Pear"]
//this selects a random word in the array
var selectedWord = words[Int(arc4random_uniform(UInt32(words.count)))]
//this counts the number of characters in the string
var length = (countElements(selectedWord))
//this randomly selects a position within the string
var position = Int(arc4random_uniform(UInt32(length)))
//this creates a new string consiting of the letter found in the position from the previous line of code
var subString = selectedWord[advance(selectedWord.startIndex, position)]
我的问题是,我不知道如何从所选单词中删除所选字符。如果可以的话,我只需创建一个循环,重复上述过程,直到原始单词为空。获取字符串do数组(“字符串”)中的第n个字符[n] 现在用字符串替换字符串,用随机数替换n。将其粘贴到for循环中,并不断从字符串中取出随机字母,然后将它们添加到新字母,直到不再保留。
扩展数组{
extension Array {
var shuffle:[T] {
var elements = self
for index in 0..<elements.count {
swap(&elements[index], &elements[ Int(arc4random_uniform(UInt32(elements.count))) ])
}
return elements
}
var chooseOne: T {
return self[Int(arc4random_uniform(UInt32(count)))]
}
}
extension String {
var jumble:String {
return String(Array(self).shuffle)
}
}
let myWords:[String] = ["python", "jumble", "easy", "difficult", "answer", "xylophone"]
let myWordJumble = myWords.chooseOne.jumble // "asey"
var shuffle:[T]{
变量元素=自
对于0中的索引..嘿,欢迎来到堆栈溢出。这不是您应该在这里问的问题。您应该问与编程相关的特定问题,而不仅仅是“为我翻译这个”。如果是这样的话,我很抱歉。我只是问是否有人能指引我去一个地方,在那里我可以得到帮助我解决问题的工具。代码翻译问题通常都是离题的。请参阅@JoeSmith:我知道如何在数组中选择随机元素,但如何在字符串中随机选择字符?这是真的吗最简单的方法是什么?我对编程比较陌生,而我用Python编程的方法要简单得多。老实说,我不太理解你的代码……相信我,没有简单的方法可以解决。但是一旦你理解了如何使用扩展,没有它你就做不到。如果你确定你不会有一个空的单词数组,我可以让它变得简单一点更容易理解我的单词数组绝对不会让我空我已经编辑了问题来演示我已经做了什么谢谢你的帮助!欢迎你。你必须向你的项目中添加一个新的swift源文件,并将其命名为Main.swift。在那里添加扩展名,你将能够在任何地方使用它。