저는 Swift를 처음 사용하며 아래에서이 기능에 문제가 있습니다. SWIFT 5 / Xcode 11.3을 사용하고 있습니다. 이 기능은 모음 앞의 모든 문자를 제거하도록 설계되었습니다. 예를 들어, "Brian"은 "ian"을, "Bill"은 "ill"을 반환합니다. 아래 두 줄에 오류가 발생합니다.
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"
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다