如何求解与初始化器有关的确切匹配?
func hasUniqueDigits(number: String) -> Bool {
var numbers = [1, 2, 3, 4, 5, 6, 7]
for i in 1...6 {
var partOne = number.firstIndex(of: String.Element("\(i)"))
var partTwo = String(numbers.firstIndex(of: Int(partOne))!)
numbers.remove(at: partTwo)
}
if numbers.count == 1 {
return true
} else {
return false
这是确定仅包含数字1-7的六位数数字是否包含所有唯一数字的函数。 示例:145327作品,114723不是因为它有两个,而183427不是因为它包含8个。 我已经随机键入!看看这是否是一个可选的问题,但这无效。您能让我知道热门解决此错误吗?
func hasUniqueDigits(number: String) -> Bool {
var numbers = [1, 2, 3, 4, 5, 6, 7]
for i in 1...6 {
var partOne = number.firstIndex(of: String.Element("\(i)"))
var partTwo = String(numbers.firstIndex(of: Int(partOne))!)
numbers.remove(at: partTwo)
}
if numbers.count == 1 {
return true
} else {
return false
This is a function for determining whether a six-digit number containing only the digits 1-7 contains all unique digits.
Examples: 145327 works, 114723 doesn't because it has two ones, and 183427 doesn't because it contains an 8.
I have typed in random !'s to see if it was an optional problem and that didn't work. Can you please let me know hot to fix this error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这不是您问题的直接答案,但是使用集合会容易得多。要检查字符串是否具有重复数字,您需要的只是检查字符串计数是否相同。要检查字符串是否只有允许的数字,您可以简单地检查数字字符集是否是数字字符集的子集:
请注意,这也将返回一个空字符串的true。如果要确保此方法返回false,只需添加一个支票即可返回false,如果数字为空:
Not a direct answer to your question but it would be much easier to use sets. To check if the string have duplicated digits all you need is to check if the string count is the same of the character set count. To check if the string has only the allowed digits you can simply check if the number character set is a subset of the numbers character set:
Note that this would return true for an empty string as well. If you want to make sure this method returns false just add a check to return false if number is empty: