简体   繁体   English

为什么此快捷功能不起作用?

[英]Why doesn't this swift function work?

This function takes two string arguments. 该函数带有两个字符串参数。 It is supposed to return the first one as dashes except where the character is somewhere inside of the second argument. 它应该返回第一个破折号,除非字符在第二个参数的内部。 Example: 例:

dashes_except("hello", except: "lo") -> --llo

The function works fine when the except argument is only one letter but fails when it is longer than one. 当except参数仅是一个字母时,该函数可以正常工作,但是当其长度大于一个字母时,该函数将失败。 It just returns dashes. 它只是返回破折号。 I'm pretty new to Swift so some help would be super appreciated! 我是Swift的新手,所以对您的帮助非常感谢!

Here is the code: 这是代码:

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

In the inner loop 在内循环中

    for y in 0..<loc_except.count {
        if loc[x] != loc_except[y] {
            loc[x] = "-"
        }
    }

loc[x] is replaced by the dash "-" if it is different from any characters in loc_except . loc[x]loc_except 任何字符不同,则用破折号“-” loc_except This will always be the case if the exception string has at least two different characters. 如果异常字符串至少包含两个不同的字符,则情况总是如此。

You can solve this using contains() : 您可以使用contains()解决此问题:

for x in 0..<loc.count {
    if !contains(loc_except, loc[x]) {
        loc[x] = "-"
    }
}

That being said, your function can be concisely written as 话虽如此,您的函数可以简写为

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

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

Here, 这里,

  • Array(word) creates an array with all the characters in the string (what you did with the enumerate() loop), Array(word)创建一个包含字符串中所有字符的数组(您对enumerate()循环所做的操作),
  • map { } replaces all characters which are not contained in the exception string by a dash, and map { }用破折号替换异常字符串中未包含的所有字符,并且
  • String( ... ) converts the character array to a string again (what you did with "".join() ). String( ... )再次将字符数组转换为字符串(使用"".join() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM