Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring of the first 4 characters from a textField in Swift 4

I'm trying to create a substring of the first 4 characters entered in a textField in Swift 4 on my iOS app.

Since the change to Swift 4 I'm struggling with basic String parsing.

So based on Apple documentation I'm assuming I need to use the substring.index function and I understand the second parameter (offsetBy) is the number of characters to create a substring with. I'm just unsure how I tell Swift to start at the beginning of the string.

This is the code so far:

  let postcode = textFieldPostcode.text

  let newPostcode = postcode?.index(STARTATTHEBEGININGOFTHESTRING, offsetBy: 4)

I hope my explanation makes sense, happy to answer any questions on this.

Thanks,

like image 607
JamMan9 Avatar asked Jul 28 '17 11:07

JamMan9


2 Answers

In Swift 4 you can use

let string = "Hello World"
let first4 = string.prefix(4) // Hell

The type of the result is a new type Substring which behaves very similar to String. However if first4 is supposed to leave the current scope – for example as a return value of a function – it's recommended to create a String explicitly:

let first4 = String(string.prefix(4)) // Hell

See also SE 0163 String Revision 1

like image 53
vadian Avatar answered Oct 13 '22 21:10

vadian


In Swift 4:

let postcode = textFieldPostcode.text!
let index = postcode.index(postcode.startIndex, offsetBy: 4)
let newPostCode = String(postcode[..<index])
like image 42
Mohammad Sadegh Panadgoo Avatar answered Oct 13 '22 22:10

Mohammad Sadegh Panadgoo