lyricsForName
功能不会打印任何内容。 shortNameFromName
确实有效,我已经检查了第二个函数的错误。
func shortNameFromName(name : String) ->String{
var shortName = ""
let lowercaseNmae = name.lowercased()
let vowelSet = CharacterSet(charactersIn: "aeiou")
if let range = lowercaseNmae.rangeOfCharacter(from: vowelSet, options: String.CompareOptions.caseInsensitive)
{
shortName = name.substring(from: range.lowerBound)
}
return shortName
}
func lyricsForName(lyricsTemplate : String , fullName : String) ->String{
let bananaFanaTemplate = ["<FULL_NAME>, <FULL_NAME>, Bo B<SHORT_NAME",
"Banana Fana Fo F<SHORT_NAME>",
"Me My Mo M<SHORT_NAME>",
"<FULL_NAME>"].joined(separator: "\n")
let shortName = shortNameFromName(name: fullName)
let lyrics = lyricsTemplate
.replacingOccurrences(of: "<FULL_NAME>", with: fullName)
.replacingOccurrences(of: "<SHORT_NAME>", with: shortName)
print(lyricsForName(lyricsTemplate:bananaFanaTemplate , fullName: "vishnu"))
return lyrics
}
第一个功能完美,但我猜第二个功能不能正常工作。我该怎么做才能让它发挥作用?
答案 0 :(得分:0)
我现在在办公桌前,所以快速浏览一下你的代码。这现在有效(请注意bananaFanaTemplate中的拼写错误):
func shortNameFromName(name : String) ->String{
var shortName = ""
let lowercaseNmae = name.lowercased()
let vowelSet = CharacterSet(charactersIn: "aeiou")
if let range = lowercaseNmae.rangeOfCharacter(from: vowelSet, options: String.CompareOptions.caseInsensitive) {
shortName = name.substring(from: range.lowerBound)
}
return shortName
}
func lyricsForName(lyricsTemplate : String , fullName : String) -> String {
let shortName = shortNameFromName(name: fullName)
let lyrics = lyricsTemplate
.replacingOccurrences(of: "<FULL_NAME>", with: fullName)
.replacingOccurrences(of: "<SHORT_NAME>", with: shortName)
print(lyrics)
return lyrics
}
let bananaFanaTemplate : String = ["<FULL_NAME>, <FULL_NAME>, Bo B<SHORT_NAME>",
"Banana Fana Fo F<SHORT_NAME>",
"Me My Mo M<SHORT_NAME>",
"<FULL_NAME>"].joined(separator: "\n")
print(lyricsForName(lyricsTemplate:bananaFanaTemplate , fullName: "vishnu"))
输出:
vishnu,vishnu,Bo Bishnu 香蕉Fana Fo Fishnu 我是我的Mishnu 毗我认为你对功能范围问题很困惑。您在函数的实现中声明了常量bananaFanaTemplate,其中该参数应该已传入函数。同样,你从函数体内部调用了函数,除非它应该是一个递归函数,否则你通常不会这样做。
希望有所帮助。