Swift: Split first name and last name from full name string

Try using this code

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

What about:

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

Usage (e.g. 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

​​​​Simple solution and fewer lines:

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

Tags:

Ios

Split

Swift