others - ios - swift :从full name字符串中拆下名字和姓

如何将全名拆分为姓氏和名字。虽然我已经完成了以下代码,有没有更好的方法考虑fullName的以下值?

全名可以具有以下任意值:


let fullName:String! //(No first or last name)


let fullName ="" //(No first or last name)


let fullName ="Micky" //(fName = Micky, no lName)


let fullName ="Micky Arthur" //(fName = Micky, lName = Arther)


let fullName ="Micky Arthur Test" //(fName = Micky, lName = Arther Test)



我的代码:


if let fullName = name{


 let nameParts = fullName(separatedBy:"")


 if nameParts.count > 0{


 let fName = nameParts[0]


 var lName =""


 if nameParts.count > 1{


 for i in 1 ..< nameParts.count{


 lName = lName + nameParts[i] +""


 }


 }


 print("First Name: (fName) Last Name: (lName)")


}



时间:

尝试使用此代码


 let fullName ="testing abducio medina"


 var components = fullName.components(separatedBy:"")


 if(components.count > 0)


 {


 let firstName = components.removeFirst()


 let lastName = components.joined(separator:"")


 debugPrint(firstName)


 debugPrint(lastName)


 } 




struct Name {


 let first: String


 let last: String



 init(first: String, last: String) {


 self.first = first


 self.last = last


 }


}



extension Name {


 init(fullName: String) {


 var names = fullName.components(separatedBy:"")


 let first = names.removeFirst()


 let last = names.joined(separator:"")


 self.init(first: first, last: last)


 }


}



extension Name: CustomStringConvertible {


 var description: String { return"(first) (last)" }


}



用法(例如Playground )


func testName(fullName: String) {


 let name = Name(fullName: fullName)


 print(name.first)


 print(name.last)


 print(name)


}



testName(fullName:"Jane Doe Foo")


//prints


// Jane


// Doe Foo


// Jane Doe Foe



testName(fullName:"John Doe")


//prints


// John


// Doe


// Jane Doe



我这样做过


var Name ="first name"


var fullNameArr = split(fullName) {$0 ==""}


var firstName: String = fullNameArr[0]


let middlename: String = fullNameArr.indices.contains(2)? fullNameArr[1] :""


if fullNameArr.count > 1 {


 var lastName: String? = fullNameArr.last



}



尝试这个:


func parseName(_ fullName: String) -> (String, String) {


 let components = fullName.characters.split(separator:"", maxSplits: 1).map(String.init)


 return (components.first ??"", components.count > 1 ? components.last! :"")


}


let (fName, lName) = parseName("Micky Arthur Test")


print("First Name: (fName) Last Name: (lName)")



简单的解决方案和更少的行:


let firstName = name.components(separatedBy:"")[0]


let secondName = name.components(separatedBy:"")[1]



...