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.
Add a comment
|
4 Answers
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
Comments
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
RajeshKumar R
Is there any equivalent Objective-C Solution?
Martin R
@RajeshkumarR: Sure. NSString has rangeOfString, substringToIndex and substringFromIndex methods.
For particular this question you can do this way:
- Remove first element of array to you variable;
- 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: " ")