Swift Tutorial: Introduction 10 - Variables: Strings

Written by Paul Napier on . Posted in Swift Tutorials: Introduction

Hello everyone and welcome to the tenth tutorial in programming with swift brought to you by MadApper. My name is Paul Napier and in this session we will be covering Strings.

In the last session we introduced the concept of characters. You may remember that if you tried to create a character variable with more than one letter, it would throw an error. This is because what you are actually trying to do in this instance is create a string. Strings are simply an array of characters.

In Objective C, when defining a string you were required to use the @ sign before the parentheses. In Objective C, this sign was used as a way to allow the compiler to define an objective c string literal. In swift, however, this is no longer required. You define a string by simply setting the value to a set of parentheses. You can write almost any character inside these parentheses and the compiler will understand that this is a string. i.e.

var string:String = "Hello"
var string = "world"

You can actually see the characters that compose the string by writing

for character in string{

Don't worry about this too much as we will cover loops and arrays soon, but what this will do is print each of the characters in the string on a new line for you to see.

As you can imagine, strings are exceptionally useful. We as humans, or at least most of us, don't interpret things as 1s and 0s. We tend to need a little more description behind us, so as an example setting a variable as name and a value of the relative bytes of information would not mean anything to us, whereas the string "Paul Napier" does.

There is one concept that we really should touch upon before we move further with strings. Strings are whats know as a value type. What this means is that when you pass the string across to another function, the value is copied and when it is passed back you receive a copy. So if you manipulate this string in any way, you can be sure that you are not manipulating the original string. If you have come from Objective C, this is a change, as this only occurred if you requested the value to be copied.

There are lots of methods associated with strings, such as getting uppercase and lowercase versions, accessing substrings within the string, concatenation and interpolation

Add comment

Security code