JamMan9
JamMan9

Reputation: 776

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,

Upvotes: 8

Views: 10520

Answers (2)

Mohammad Sadegh Panadgoo
Mohammad Sadegh Panadgoo

Reputation: 3989

In Swift 4:

let postcode = textFieldPostcode.text!
let index = postcode.index(postcode.startIndex, offsetBy: 4)
let newPostCode = String(postcode[..<index])

Upvotes: 1

vadian
vadian

Reputation: 285079

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

Upvotes: 30

Related Questions