Reference Materials
Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Swift String hasPrefix()
In this tutorial, we will learn about the Swift String hasPrefix() method with the help of examples.
The hasPrefix() method checks whether the string begins with the specified string or not.
Example
var str = "Kathmandu"
// checks if "Kathmandu" starts with "Kath"
print(str.hasPrefix("Kath"))
// Output: true
hasPrefix() Syntax
The syntax of the string hasPrefix() method is:
string.hasPrefix(str: String)
Here, string is an object of the String class.
hasPrefix() Parameters
The hasPrefix() method takes a single parameter:
- str - check whether string starts with str or not
hasPrefix() Return Value
The hasPrefix() method returns:
- true - if the string begins with the given string
- false - if the string doesn't begin with the given string
Note: The hasPrefix() method is case-sensitive.
Example 1: Swift string hasPrefix()
var str = "Swift Programming"
print(str.hasPrefix("Swift")) // true
print(str.hasPrefix("S")) // true
print(str.hasPrefix("Swift Program")) // true
print(str.hasPrefix("swift")) // false
print(str.hasPrefix("wif")) // false
Output
true true true false false
Example 2: Using hasPrefix() With if...else
var song = "For the good times"
// true because song has "For the" prefix
if(song.hasPrefix("For the")) {
print ("Penned by Kris")
}
else {
print ("Some Other song ")
}
// false because song doesn't have "Good time" prefix
if(song.hasPrefix("Good times")){
print ("Penned by Bernard")
}
else{
print ("Some other artist ")
}
Output
Penned by Kris Some other artist
Did you find this article helpful?