2017-09-14 168 views
1

lyricsForName函數不打印任何東西。 shortNameFromName確實有效,我檢查了第二個功能有什麼問題。lyricsForName函數不打印任何東西

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

你好 - 你的函數應該是遞歸的(你在函數聲明中調用lyricsForName)?如果您打印歌詞,會發生什麼情況? – Sparky

+0

它不應該遞歸 – vishnu

+0

我現在在外面使用該函數它只打印\ n,相同的結果,當我嘗試打印歌詞 – vishnu

回答

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

輸出:

毗溼奴,毗溼奴,博比什努 香蕉煩啊佛Fishnu 我我莫Mishnu 毗溼奴

我認爲你是對功能範圍問題頗爲困惑。您在函數的實現中聲明瞭常量bananaFanaTemplate,其中該參數應該已傳遞給該函數。同樣,你從函數體內調用函數,除非它是一個遞歸函數,否則你通常不會這樣做。

看看:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html

希望有所幫助。