Convert A String To Lowercase In Swift
Code snippet for how to Convert A String To Lowercase In Swift with sample and detail explanation
Handling string data in the right format is a common task in any programming language. In this article, we will discuss how to convert a string to lowercase in Swift, Apple’s programming language used for iOS and macOS app development.
Code snippet to Convert A String To Lowercase In Swift
Here is a Swift code snippet that will help you transform a string to its lowercase equivalent:
let originalString = "Hello World!"
let lowercasedString = originalString.lowercased()
print(lowercasedString)
When you run this code, it will print out: hello world!
.
Code Explanation for Convert A String To Lowercase In Swift
Now, let’s dissect the code snippet above to understand it thoroughly:
- First, we define a
String
variable namedoriginalString
and assign the text"Hello World!"
to it. This is the string data that we want to modify.
let originalString = "Hello World!"
- The next line is where we transform
originalString
into lowercase. Swift’sString
type has a method calledlowercased()
. When called on a string, it returns a new string that is a lowercase version of the original. That’s why, when we sayoriginalString.lowercased()
, we get the lowercased version of"Hello World!"
, which is"hello world!"
. We assign this new lowercase string to a newString
variable calledlowercasedString
.
let lowercasedString = originalString.lowercased()
- The last line of the code prints the
lowercasedString
. Theprint
statement is a function that sends the output to the Swift standard output (which is typically your console or terminal).
print(lowercasedString)
If you follow these steps correctly, you will be able to easily convert any string in Swift into lowercase. Understanding these basic methods for string manipulation is crucial when dealing with text data in any Swift application.