簡體   English   中英

Swift 錯誤:無法將“字符”類型的值轉換為預期的參數類型“Unicode.Scalar”

[英]Swift error: Cannot convert value of type 'Character' to expected argument type 'Unicode.Scalar'

我是 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)

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

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

shortName(from: "Brian")  // "ian"    
shortName(from: "Bill")   // "ill"

關於代碼中的問題,請通過下面的代碼檢查注釋:

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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM