A string represents textual data.
In Swift, a String is an ordered collection of Character values, where each character represents a Unicode character.
You create a string using a string literal, which is a sequence of characters surrounded by double quotation marks (").
For multi-line strings, use three double quotation marks ("""):
let hello: String = "Hello, World!"
let poem: String = """
Roses are red,
Violets are blue.
Sugar is sweet,
And so are you.
"""
Swift strings bridge seamlessly with the Foundation framework's NSString class, providing access to extensive text-processing capabilities.
A Character represents a single extended grapheme cluster—a human-readable character composed of one or more Unicode scalar values.
A Unicode scalar value is a 21-bit code point in the range U+0000 to U+D7FF inclusive or U+E000 to U+10FFFF inclusive.
let aChar: Character = "A"
When you write a string literal, Swift automatically infers its type as String.
To store a single character as a Character, you must provide an explicit type annotation:
let aString = "A" // Inferred as String
let aChar: Character = "A" // Explicitly typed as Character
print(type(of: aString)) // Prints String
print(type(of: aChar)) // Prints Character
// The following code will not compile:
let badChar: Character = "Too many characters"
// Error: Cannot convert value of type 'String' to specified type 'Character'
You can join strings together using the addition operator (+):
print("honey" + "comb")
// Prints "honeycomb"
You cannot directly concatenate a Character to a String using + without first converting the character to a string.
However, you can use the append(_:) method to append either a string or a character directly to a mutable string:
var greeting = "Hello"
let world = ", world"
let period: Character = "."
greeting.append(world)
print(greeting) // Prints "Hello, world"
greeting.append(period)
print(greeting) // Prints "Hello, world."
String interpolation allows you to construct a string by embedding constants, variables, literals, and expressions inside string literals.
Wrap each expression in parentheses preceded by a backslash (\( ... )):
let radius = 5.0
let circle = "The area of a circle with radius \(radius) is \(Double.pi * radius * radius)"
print(circle) // Prints "The area of a circle with radius 5.0 is 78.53981633974483"
Strings and characters offer several properties to inspect their content.
Common string properties include:
| Property | Description | Example |
|---|---|---|
isEmpty |
Returns true if the string has no characters |
"Hello".isEmpty evaluates to false
|
count |
Returns the number of characters in the string |
"Hello".count evaluates to 5
|
For a complete list of properties, see the Apple String documentation.
Common character properties include:
| Property | Description | Example |
|---|---|---|
isLowercase |
Returns true if the character is lowercase |
"a".isLowercase evaluates to true
|
isUppercase |
Returns true if the character is uppercase |
"A".isUppercase evaluates to true
|
isNumber |
Returns true if the character is a digit |
"1".isNumber evaluates to true
|
isWhitespace |
Returns true if the character is whitespace |
" ".isWhitespace evaluates to true
|
For a complete list of properties, see the Apple Character documentation.
You can convert other types into strings by using the String(_:) initializer, which supports standard types like Int, Double, and Character:
let charX: Character = "x"
print(String(charX)) // Prints "x"
print(String(110)) // Prints "110"
print(String(Double.pi)) // Prints "3.141592653589793"
Swift string literals support several escape sequences for special characters:
| Sequence | Description |
|---|---|
\0 |
Null character |
\\ |
Backslash |
\t |
Horizontal tab |
\n |
Line feed (newline) |
\r |
Carriage return |
\' |
Single quotation mark |
\" |
Double quotation mark |
\u{n} |
Arbitrary Unicode scalar (hexadecimal) |
let quote: String = "\"Hello\", he said."
print(quote) // Prints "Hello", he said.
let unicode: Character = "\u{1F496}"
print(unicode) // Prints 💖
In this exercise you'll be writing code to help a sign company create custom messages for their signs.
Define the following constant strings which will be used to create signs:
birthday: This holds the value "Birthday"valentine: This holds the value "Valentine's Day"anniversary: This holds the string "Anniversary"Define the following constant characters which will be used to create signs:
space: This holds the value " " (a single space)exclamation: This holds the value "!"Implement the function buildSign(for:name:), which takes the argument for which holds one of the three strings you defined in the first task and the argument name which is a string that holds the name of the person the sign is for.
You shall use concatenation to build up the message for the sign and remember to reuse the already defined constants.
The function should return the sign message as a string.
buildSign(for: birthday, name: "Otto")
// returns "Happy Birthday Otto!"
buildSign(for: anniversary, name: "Valentina")
// returns "Happy Anniversary Valentina!"
Implement the function graduationFor(name:year:) which takes the argument name which is a string that holds the name of the person the sign is for and the argument year which is an integer that holds the year the person is graduating.
You shall use template strings to build up the message for the sign.
The function should return the sign message as a string.
graduationFor(name: "Padma", year: 2023)
// returns "Congratulations Padma!\nClass of 2023"
Implement the function costOf(sign:) which takes the argument sign which is a string that holds the message for the sign.
The sign has a base price of 20 in the given currency. Additionally each letter costs 2 (Whitespaces are included in the calculation).
The function should return the cost of the sign as an integer.
costOf(sign: "Happy Birthday Grandma!")
// returns 66
Sign up to Exercism to learn and master Swift with 35 concepts116 exercises, and real human mentoring, all for free.