我怎么能在Swift中混淆一个单词

时间:2015-01-03 20:30:08

标签: python swift

我正在尝试使用Swift为iPhone创建一个单词jumbler游戏。我对编程和Swift比较陌生,但以前用Python创建过这个游戏。

这是我的伪代码:

//从数组中选择RANDOM WORD

//确定RANDOMLY SELECTED WORD中的字符数

//在字符数的边界内随机选择一个数字(即如果单词是“apple”,则选择0到4之间的数字)

//选择与随机选择的NUMBER

对应的CHARACTER

//将CHARACTER添加到新字符串(JUMBLE)

//从RANDOMLY SELECTED WORD中删除CHARCATER

//重复直到RANDOM WORD为空

到目前为止,这是我的代码:

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)]

我的问题是我无法弄清楚如何从所选单词中删除所选字符。如果可以的话,我只需创建一个循环,然后重复上面的过程,直到原始单词为空。

2 个答案:

答案 0 :(得分:1)

要获取字符串中的第n个字符,请执行数组(" STRING")[n] 现在只需用字符串替换字符串,用随机数替换n。将其粘贴在for循环中并继续从字符串中取出随机字母,然后将它们更换为新字母直到不再存在。

答案 1 :(得分:1)

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"