Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

method
swift
communitycreator
hasprefix

What is the hasPrefix() method in Swift?

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

The hasPrefix() method of a string instance in Swift checks if a string begins with a specified prefix. If true, it returns true. Otherwise, it returns false.

Syntax

string.hasPrefix(prefix)

Parameters

prefix: This is the sub-string we want to check to see if it begins the string, string.

Return value

This method returns a Boolean value. It returns a true value if the prefix string prefix begins the string string. Otherwise, it returns a false value.

Code example

// Create strings
let str1 = "Edpresso is the best"
let str2 = "Best place to be"
let str3 = "Learn all you need"
// Check if the following prefixes exist
print(str1.hasPrefix("Edpresso"))
print(str2.hasPrefix("great"))
print(str3.hasPrefix("Learn"))
Checking if a string contains specified prefixes

Explanation

  • Lines 2 to 4: We create some strings.
  • Lines 7 to 9: We check if the strings begin with the specified prefixes. Then, we print the results.

RELATED TAGS

method
swift
communitycreator
hasprefix

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring