Reputation:
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. It just returns dashes. I'm pretty new to Swift so some help would be super appreciated!
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)
}
Upvotes: 0
Views: 161
Reputation: 539795
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
. This will always be the case if the
exception string has at least two different characters.
You can solve this using 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), map { }
replaces all characters which are not contained in
the exception string by a dash, andString( ... )
converts the character array to a string again
(what you did with "".join()
).Upvotes: 4