2

I have an array like :

dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]

Need to split the strings and get the response as :

time = ["05:32:30","02:37","05:32:50","06:30:30"]

Can anyone please help on this.

1
  • could you please tell me why you changed my answer as not accepted? Commented Nov 13, 2018 at 6:24

3 Answers 3

2

you can use flatMap:

let dates = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]
let times = dates.flatMap({ $0.split(separator: " ").last ?? nil })
print(times)
// prints: ["05:32:30", "02:37", "05:32:50", "06:30:30"]
Sign up to request clarification or add additional context in comments.

Comments

2

Use this below solution to get the times from all elements.

let dateTime = ["2018/06/25 05:32:30","2018/05/25 02:37","2018/04/25 05:32:50","2018/07/25 06:30:30"]  
let array = dateTime.map { $0.components(separatedBy: " ")[1] }
 //["05:32:30", "02:37", "05:32:50", "06:30:30"]

1 Comment

Just want to note, that using subscript [1] may cause a null pointer if the second element is not found. That's why flatMap is better. Check my answer.
2

Loops each items & use split function

let times = dateTime.compactMap { $0.split(separator: " ").last }

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.