1

So I have Full Name text field, I created nameComponents Array by splitting full Name by space. Now I want to take 0 index element as first name and rest of components as last name. I like this approach of joining string array in Swift. Is there any way to join the array starting from a particular index (in my case index 1). I don't want to use loop.

0

4 Answers 4

2

You can use dropFirst() or dropFirst(_:)

dropFirst()

  let names = "Steve Jobs Nojobs".components(separatedBy: " ")
  let firstName = names.first!
  let lastName = names.dropFirst().joined(separator: " ")
  print(firstName)//Steve
  print(lastName)//Jobs Nojobs

dropFirst(_:)

 let names = "It is a long name".components(separatedBy: " ")
 let lastName = names.dropFirst(2).joined(separator: " ")        
 print(lastName)//a long name
Sign up to request clarification or add additional context in comments.

Comments

1

There is no need to fully split the string into an array if you only want to separate it at the first space. You can locate the first space and determine the parts preceding and following it directly. Example (Swift 3):

let string = "foo bar baz"

if let range = string.range(of: " ") {
    let firstPart = string.substring(to: range.lowerBound)
    let remainingPart = string.substring(from: range.upperBound)

    print(firstPart)        // foo
    print(remainingPart)    // bar baz
}

In Swift 4 you would extract the parts with

    let firstPart = String(string[..<range.lowerBound])
    let remainingPart = String(string[range.upperBound...])

2 Comments

Is there any equivalent Objective-C Solution?
@RajeshkumarR: Sure. NSString has rangeOfString, substringToIndex and substringFromIndex methods.
0

Try this for Swift3:

let array = ["zero", "one", "two", "three"]
let str = array[1..<array.count].joined(separator: "-")
// po str
// "one-two-three"

Comments

0

For particular this question you can do this way:

  1. Remove first element of array to you variable;
  2. Now, last part is your last name.

Example:

var nameComponents = ["My", "name", "is"]

let firstName = nameComponents.remove(at: 0) // "My"
let lastName = nameComponents.joined(separator: " ") // "name is"

But more practical way is to use array subscript by passing Range to it.

let firstName = nameComponents.first!

// Swift 3
let lastName = nameComponents[1..<nameComponents.count].joined(separator: " ")

// Swift 4
let lastName = nameComponents[1...].joined(separator: " ")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.