Strings - free Swift example code
About 8 min
Strings - free Swift example code 관련
Strings - free Swift example code
Learn Swift coding for iOS with these free tutorials – learn Swift, iOS, and Xcode
Found 31 articles in the Swift Knowledge Base for this category.
How do you make raw strings in Swift?
Raw strings place hash signs –
#
– before and after their quote mark, and modify the way Swift handles strings in two ways.... How to calculate the ROT13 of a string
ROT13 is a simple algorithm that shifts letters in a string forward 13 places. It’s obviously not suitable for any serious encryption, but it’s very useful for hiding text so its meaning is not obvious – posting spoilers on a forum, for example, is best done using ROT13 to avoid someone getting annoyed....
How to capitalize the first letter of a string
If you want to capitalize the first letter of a string without touching the rest of the letters, add this simple extension of
String
:... How to capitalize words in a string using capitalized
Swift offers several ways of adjusting the letter case of a string, but if you're looking for title case – that is, Text Where The First Letter Of Each String Is Capitalized - then you need to use the
capitalized
property, like this:... How to check whether a string contains any words from an array
You should already know that you can check whether a string contains a single word like this:...
How to concatenate strings to make one joined string
Swift offers three different ways of joining strings. The first is using the
+
operator to join two strings to make a third:... How to convert a string to a safe format for URL slugs and filenames
Swift strings are extraordinarily complex beasts, allowing you to mix in characters from any language – including emoji – freely. While this is really important to display text, it can also cause havoc while trying to create URLs and filenames, so if you need to refer to a string in those places you should first convert it to a slug....
How to convert a string to lowercase letters
You can convert any string to lowercase – that is, going from 'HELLO' to 'hello' – by calling its
lowercased()
method, like this:... How to convert a string to uppercase letters
If you want to convert a string to uppercase – that is, WHERE EVERY LETTER IS A CAPITAL LETTER – you should use the
uppercased()
method of your string, like this:... How to detect a URL in a String using NSDataDetector
The
NSDataDetector
class makes it easy to detect URLs inside a string using just a few lines of code. This example loops through all URLs in a string, printing each one out:... How to display different strings based on available space using variantFittingPresentationWidth()
It’s surprisingly easy to configure your project with multiple strings then have it choose one at runtime based on available space....
How to get the length of a string
Swift strings can be treated as an array of individual characters. So, to return the length of a string you can use
yourString.count
to count the number of items in the characters
array.... How to get the lines in a string as an array
Swift’s strings have their lines separated by the
character, which is a line break on Unix operating systems. Using that plus the components(separatedBy:)
method, you can get an array of all the lines in a string like this:... How to load a string from a file in your bundle
If you have an important text file built into your app bundle that want to load it at runtime fact,
String
has an initializer just for this purpose. It’s called contentsOfFile
, and here it is in action:... How to load a string from a website URL
It takes just a few lines of Swift code to load the contents of a website URL, but there are three things you need to be careful with:...
How to loop through letters in a string
You can loop through every character in a string by treating it as an array. Thanks to Swift's extended support for international languages and emoji, this works great no matter what kind of language you're using....
How to measure a string for Objective-C code
Regular Swift code can treat strings like other kinds of sequence, so you can use its
count
property to read the number of characters it contains:... How to parse a sentence using NSLinguisticTagger
If you're looking to parse natural language entered by a user, you're looking for
NSLinguisticTagger
: it automatically recognizes English words (and words in other languages too, if you ask) and tells you what kind of word it is. That is, this magic little class distinguishes between verbs, nouns, adjectives and so on, so you can focus on the important stuff: how do I (verb) this (noun)?... How to read a single character from a string
Swift’s strings are stored in a specific way that stops you from indexing into then easily. In fact, reading one letter from part-way through the string means starting at the beginning of the string and counting through letters until you find the one you want, so if you try reading all the characters in the string this way you could accidentally create extremely slow code....
How to remove a prefix from a string
Swift’s string have a built-in
hasPrefix()
method that returns true if the string starts with specific letters, but they don’t have a way to remove those letters if they exist.... How to repeat a string
Swift strings have a built-in initializer that lets you create strings by repeating a string a certain number of times. To use it, just provide the string to repeat and a count as its two parameters, like this:...
How to reverse a string using reversed()
Reversing a string in Swift is done by using the
reversed()
method on its characters, then creating a new string out of the result. Here's the code:... How to run a case-insensitive search for one string inside another
You can search for one string inside another using the
range(of:)
method, like this:... How to save a string to a file on disk with write(to:)
All strings have a
write(to:)
method that lets you save the contents of the string to disk. You need to provide a filename to write to, plus two more parameters: whether the write should be atomic, and what string encoding to use. The second parameter should nearly always be true
because it avoids concurrency problems. The third parameter should nearly always be String.Encoding.utf8
, which is pretty much the standard for reading and writing text.... How to specify floating-point precision in a string
Swift's string interpolation makes it easy to put floating-point numbers into a string, but it lacks the ability to specify precision. For example, if a number is 45.6789, you might only want to show two digits after the decimal place....
How to split a string into an array: components(separatedBy:)
You can convert a string to an array by breaking it up by a substring using the
components(separatedBy:)
method. For example, you can split a string up by a comma and space like this:... How to test localization by setting a debug locale and double length pseudolanguage
If you want to check how your app works when running on devices with other languages, you have two options: you can either instruct the simulator to use a specific language where you have a localization in place, or you can have it use a special 'Double length pseudolanguage' that basically acts as a stress test....
How to trim whitespace in a string
It's not hard to trim whitespace from a string in Swift, but the syntax is a little wordy – or 'self-descriptive' if you're feeling optimistic. You need to use the
trimmingCharacters(in:)
method and provide a list of the characters you want to trim. If you're just using whitespace (tabs, spaces and new lines) you can use the predefined whitespacesAndNewlines
list of characters, like this:... How to use string interpolation to combine strings, integers and doubles
String interpolation is Swift's way of letting you insert variables and constants into strings. But at the same time, you can also perform simple operations as part of your interpolation, such as changing letter case and basic mathematics. Swift is also smart enough to understand how to bring values into strings, meaning that you can use other strings, integers and floating-point numbers just fine....
NSRegularExpression: How to match regular expressions in strings
The
NSRegularExpression
class lets you find and replace substrings using regular expressions, which are concise and flexible descriptions of text. For example, if we wanted to pull 'Taylor Swift' out of the string 'My name is Taylor Swift', we could write a regular expression that matches the text 'My name is' followed by any text, then pass that to the NSRegularExpression
class.... Replacing text in a string using replacingOccurrences(of:)
It's easy to replace text inside a string thanks to the method
replacingOccurrences(of:)
. This is a string method, and you tell it what to look for and what to replace it with, and you're done....