String 为什么';这个快捷的功能不起作用吗?

String 为什么';这个快捷的功能不起作用吗?,string,function,swift,String,Function,Swift,此函数接受两个字符串参数。它应该以破折号的形式返回第一个参数,除非字符位于第二个参数的内部。例如: dashes_except("hello", except: "lo") -> --llo 当except参数仅为一个字母时,该函数工作正常,但当其长度超过一个字母时,该函数将失败。它只返回破折号。我是斯威夫特的新手,所以非常感谢您的帮助 代码如下: func dashes_except(word: String,except: String) -> String { v

此函数接受两个字符串参数。它应该以破折号的形式返回第一个参数,除非字符位于第二个参数的内部。例如:

dashes_except("hello", except: "lo") -> --llo
当except参数仅为一个字母时,该函数工作正常,但当其长度超过一个字母时,该函数将失败。它只返回破折号。我是斯威夫特的新手,所以非常感谢您的帮助

代码如下:

func dashes_except(word: String,except: String) -> String { 

    var loc = [String]()
    for (index, character) in enumerate(word) {
        loc.append(String(character))
    }
    var loc_except = [String]()
    for (index, character) in enumerate(except) {     
        loc_except.append(String(character))
    }
    for x in 0..<loc.count {
        for y in 0..<loc_except.count {
            if loc[x] != loc_except[y] {
                loc[x] = "-"
            }  
        }   
    }
    return "".join(loc)
}
func破折号\u except(word:String,except:String)->String{
var loc=[String]()
用于枚举(word)中的(索引、字符){
loc.append(字符串(字符))
}
var loc_except=[String]()
对于枚举中的(索引、字符)(除{
loc_除.append外(字符串(字符))
}
对于内环中的x,0..

    for y in 0..<loc_except.count {
        if loc[x] != loc_except[y] {
            loc[x] = "-"
        }
    }
也就是说,您的函数可以简洁地写为

func dashes_except(word: String,except: String) -> String {

    return String(Array(word).map( { contains(except, $0) ? $0 : "-" } ))
}
这里,

  • Array(word)
    创建一个包含所有字符的数组 字符串(您对
    enumerate()
    循环所做的操作)
  • map{}
    替换未包含在 破折号表示异常字符串,并且
  • String(…)
    再次将字符数组转换为字符串 (您对
    “”.join()所做的操作
在内部循环中

    for y in 0..<loc_except.count {
        if loc[x] != loc_except[y] {
            loc[x] = "-"
        }
    }
也就是说,您的函数可以简洁地写为

func dashes_except(word: String,except: String) -> String {

    return String(Array(word).map( { contains(except, $0) ? $0 : "-" } ))
}
这里,

  • Array(word)
    创建一个包含所有字符的数组 字符串(您对
    enumerate()
    循环所做的操作)
  • map{}
    替换未包含在 破折号表示异常字符串,并且
  • String(…)
    再次将字符数组转换为字符串 (您对
    “”.join()所做的操作

好的,所以我理解它为什么不起作用,但我找不到解决方案。我尝试使用break,但我想不出来。你能告诉我如何更好地找到某个列表值是否在另一个列表值中吗?在python中,我只会使用'In'关键字来表示类似的内容,Swift是否有类似的内容?在这些情况下,我通常会推荐使用使用正则表达式。@jonathanlv7:如果您需要更多信息,请告诉我。谢谢!我已经解决了这个问题,但我还有另一个问题。我正在尝试使用数组(string),它一直告诉我需要使用数组(ArrayTerral:string),但这不起作用。为什么不让我使用数组(string)?@jonathanlv7:您使用的是哪个Xcode版本?上面的代码已经用Xcode 6.3.2进行了测试。好吧,我明白它为什么不起作用,但我找不到解决方案。我尝试使用break,但我找不到。您能告诉我如何更好地找到某个列表值是否在另一个列表值中吗?在python中,我只会使用'In'键d对于类似的事情,Swift有类似的东西吗?在这种情况下,我通常建议使用正则表达式。@jonathanlv7:如果您需要更多信息,请告诉我。谢谢!我解决了这个问题,但我有另一个问题。我正在尝试使用数组(string),它一直告诉我需要使用数组(ArrayTerral:string)但是那不行。为什么不让我使用数组(字符串)?@jonathanlv7:你使用的是哪个Xcode版本?上面的代码已经用Xcode 6.3.2测试过了。