[英]Swift Error Cannot convert value of type '[String.Element]' (aka 'Array<Character>') to expected argument type '[String]'
I am trying to create an array of letters from a given word by using the following Swift code (I have an array of words for allWords, but for simplicity I've just added an example word there for now):我正在尝试使用以下 Swift 代码从给定的单词创建一个字母数组(我有一个 allWords 的单词数组,但为了简单起见,我现在只是在那里添加了一个示例单词):
let allWords = ["Leopards"]
var arrayOfLetters = Array(allWords[0])
let everyPossibleArrangementOfLetters = permute(list: arrayOfLetters)
func permute(list: [String], minStringLen: Int = 3) -> Set<String> {
func permute(fromList: [String], toList: [String], minStringLen: Int, set: inout Set<String>) {
if toList.count >= minStringLen {
set.insert(toList.joined(separator: ""))
}
if !fromList.isEmpty {
for (index, item) in fromList.enumerated() {
var newFrom = fromList
newFrom.remove(at: index)
permute(fromList: newFrom, toList: toList + [item], minStringLen: minStringLen, set: &set)
}
}
}
var set = Set<String>()
permute(fromList: list, toList:[], minStringLen: minStringLen, set: &set)
return set
}
I obtained this code from: Calculate all permutations of a string in Swift我从以下位置获得此代码: Calculate all permutations of a string in Swift
But the following error is presented: Cannot convert value of type '[String.Element]' (aka 'Array') to expected argument type '[String]'但是会出现以下错误:无法将类型“[String.Element]”(又名“Array”)的值转换为预期的参数类型“[String]”
I attempted the following, which works, but it takes over 10 seconds per word (depending on number of repeat letters) and I was hoping to find a better solution.我尝试了以下方法,它有效,但每个单词需要超过 10 秒(取决于重复字母的数量),我希望找到更好的解决方案。
var arrayOfLetters: [String] = []
for letter in allWords[0] {
arrayOfLetters.append(String(letter))
}
let everyPossibleArrangementOfLetters = permute(list: arrayOfLetters)
I wasn't able to get the following solution to work, although I think is has promise I couldn't get past the productID name of items in the array whereas my array items aren't named... Migration from swift 3 to swift 4 - Cannot convert String to expected String.Element我无法使以下解决方案起作用,尽管我认为它有 promise 我无法通过数组中项目的 productID 名称,而我的数组项目未命名... 从 swift 3 迁移到 swift 4 - 无法将 String 转换为预期的 String.Element
I'm also creating another array and checking each of those words to ensure their validity, and I run into the same error which I correct in the same way with array.append which is adding a lot more time in that location as well.我还创建了另一个数组并检查每个单词以确保它们的有效性,并且我遇到了相同的错误,我以与 array.append 相同的方式更正了该错误,这也在该位置增加了更多时间。
var everyPossibleArrangementOfLettersPartDeux: [String] = []
for word in everyPossibleArrangementOfLetters {
everyPossibleArrangementOfLettersPartDeux.append(word)
}
numberOfRealWords = possibleAnagrams(wordArray: everyPossibleArrangementOfLettersPartDeux)
func possibleAnagrams(wordArray: [String]) -> Int {
func isReal(word: String) -> Bool {
let checker = UITextChecker()
let range = NSMakeRange(0, word.utf16.count)
let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")
return misspelledRange.location == NSNotFound
}
var count = 0
for word in wordArray {
if isReal(word: word) {
count += 1
//print(word)
}
}
return count
}
I'm hoping the same replacement for array.append will work in both spots.我希望 array.append 的相同替换将在两个位置都有效。
The problem is that Array(allWords[0])
produces [Character]
and not the [String]
that you need. 问题是Array(allWords[0])
生成[Character]
而不是所需的[String]
。
You can call map
on a String
(which is a collection of Character
s and use String.init
on each character to convert it to a String
). 您可以在String
上调用map
(这是Character
的集合,并在每个字符上使用String.init
将其转换为String
)。 The result of the map
will be [String]
: map
的结果为[String]
:
var arrayOfLetters = allWords[0].map(String.init)
Notes: 笔记:
Fatal error: Only BidirectionalCollections can be advanced by a negative amount
. 当我在Playground中尝试此操作时,我得到了一条神秘的消息: Fatal error: Only BidirectionalCollections can be advanced by a negative amount
。 This seems to be a Playground issue, because it works correctly in an app. 这似乎是一个Playground问题,因为它可以在应用程序中正常工作。 "Leopards"
produces 109,536
permutations. 仅"Leopards"
一词就产生109,536
个排列。 Another Approach 另一种方法
Another approach to the problem is to realize that permute
doesn't have to work on [String]
. 解决该问题的另一种方法是意识到permute
不必对[String]
起作用。 It could use [Character]
instead. 它可以改用[Character]
。 Also, since you are always starting with a String
, why not pass that string to the outer permute
and let it create the [Character]
for you. 另外,由于您始终以String
开头,所以为什么不将该字符串传递给外部permute
并让它为您创建[Character]
。
Finally, since it is logical to think that you might just want anagrams of the original word, make minStringLen
an optional with a value of nil
and just use word.count
if the value is not specified. 最后,由于逻辑上认为您可能只想要原始单词的字谜,因此将minStringLen
可选值,其值为nil
,如果未指定该值,则仅使用word.count
。
func permute(word: String, minStringLen: Int? = nil) -> Set<String> {
func permute(fromList: [Character], toList: [Character], minStringLen: Int, set: inout Set<String>) {
if toList.count >= minStringLen {
set.insert(String(toList))
}
if !fromList.isEmpty {
for (index, item) in fromList.enumerated() {
var newFrom = fromList
newFrom.remove(at: index)
permute(fromList: newFrom, toList: toList + [item], minStringLen: minStringLen, set: &set)
}
}
}
var set = Set<String>()
permute(fromList: Array(word), toList:[], minStringLen: minStringLen ?? word.count, set: &set)
return set
}
Examples: 例子:
print(permute(word: "foo", minStringLen: 1))
["of", "foo", "f", "fo", "o", "oof", "oo", "ofo"]
print(permute(word: "foo"))
["foo", "oof", "ofo"]
This line is returning a Character
array, not a String
one: 此行返回一个Character
数组,而不是String
数组:
var arrayOfLetters = Array(allWords[0])
You can convert this to a String
array like so: 您可以将其转换为String
数组,如下所示:
var arrayOfLetters = Array(allWords[0]).map{String($0)}
You could alternatively write: 您也可以这样写:
var arrayOfLetters = allWords[0].characters.map{String($0)}
If, it is optional character or string如果,它是可选的字符或字符串
usedLetters.append(currentWord.randomElement().map(String.init)!)
Here usedLetters is Array[String] currentWord is Optional string这里usedLetters是Array[String] currentWord是Optional string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.