【问题标题】:Swift error: Cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'Swift 错误:无法将“字符”类型的值转换为预期的参数类型“Unicode.Scalar”
【发布时间】:2020-05-20 22:28:22
【问题描述】:

我是 Swift 新手,在使用下面的这个函数时遇到了问题。我正在使用 SWIFT 5/Xcode 11.3。该功能旨在删除元音之前的任何字母。例如,“Brian”将返回“ian”,“Bill”将返回“ill”等。我在下面的 2 行中得到了错误。

import Foundation

func shortNameFromName(_ name: String) -> String {

    // Definition of characters
    let vowels = CharacterSet(charactersIn: "aeiou")
    var shortName = ""
    let start = name.startIndex

    // Loop through each character in name
    for number in 0..<name.count {

        // If the character is a vowel, remove all characters before current index position
        if vowels.contains(name[name.index(start, offsetBy: number)]) == true { //**ERROR: Cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'**
            var shortName = name.remove(at: shortName.index(before: shortName.number)) //**ERROR: Cannot use mutating member on immutable value: 'name' is a 'let' constant**
        }
    }

    //convert returned value to lowercase
    return name.lowercased()
}

var str = "Brian" // Expected result is "ian"

shortNameFromName(str)

【问题讨论】:

    标签: swift string substring character


    【解决方案1】:

    您可以使用集合的方法func drop(while predicate: (Character) throws -&gt; Bool) rethrows -&gt; Substring,而字符串“aeiou”不包含字符并返回子字符串:

    func shortName(from name: String) -> String { name.drop{ !"aeiou".contains($0) }.lowercased() }
    
    shortName(from: "Brian")  // "ian"    
    shortName(from: "Bill")   // "ill"
    

    关于代码中的问题,请通过以下代码检查 cmets:

    func shortName(from name: String) -> String {
        // you can use a string instead of a CharacterSet to fix your first error
        let vowels =  "aeiou"
        // to fix your second error you can create a variable from your first parameter name
        var name = name
        // you can iterate through each character using `for character in name`
        for character in name {
            // check if the string with the vowels contain the current character
            if vowels.contains(character) {
                // and remove the first character from your name using `removeFirst` method
                name.removeFirst()
            }
        }
        // return the resulting name lowercased
        return name.lowercased()
    } 
    
    shortName(from: "Brian")  // "ian"
    

    【讨论】:

    • Leo - 感谢您的帮助。我喜欢前两个替代方案的优雅,所以我打算使用它而不是我更“蛮力”的方法。不过,我确实有一个后续问题。我一直在尝试在您的示例中添加一个返回语句,例如“return name.lowercased()”。这引发了另一个错误。有什么想法吗?
    • 您只需要返回String 而不是Substring。检查可能最后一次编辑
    • 完美!非常感谢狮子座。
    猜你喜欢
    • 2016-05-03
    • 2017-04-03
    • 1970-01-01
    • 2017-12-30
    • 2017-02-07
    • 1970-01-01
    • 2017-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多