How to get first four letters from string in Swift 3?

The easiest way to get a string's prefix is with

// Swift 3
String(string.characters.prefix(4))

// Swift 4 and up
string.prefix(4)

// Objective-C
NSString *firstFour = [string substringToIndex:4];

This is a simple validation using regular expression. The pattern represents:

  • ^ must be the beginning of the string
  • [A-Za-z]{4} = four characters A-Z or a-z
  • 0one zero
  • .{6} six arbitrary characters
  • $ must be the end of the string

Updated to Swift 4

func validateIFSC(code : String) -> Bool {
  let regex = try! NSRegularExpression(pattern: "^[A-Za-z]{4}0.{6}$")
  return regex.numberOfMatches(in: code, range: NSRange(code.startIndex..., in: code)) == 1
}

PS: To answer your question, you get the first 4 characters in Swift 3 with

let first4 = code.substring(to:code.index(code.startIndex, offsetBy: 4))

and in Swift 4 simply

let first4 = String(code.prefix(4))

Tags:

Swift3