Day 1: Variables, Simple Data Types, and String Interpolation

Jimmy Liu
Kuo’s Funhouse

--

Here I will give a brief introduction to the types and variables in Swift. Later, I will dig a litter bit deeper into data types and hopefully I will give you a better insight on Swift’s structure.

Brief Intro

In Swift, there are two kinds of types : named types and compound types .

  • A named type is a type that can be given a particular name when it’s defined, including:
classes
structures
enumerations
protocols
// Defined in Swift Standard Library
arrays
dictionaries
optional values
// data types that represent
numbers
characters
strings
  • A compound type is a type without a name, defined in Swift language itself. It can be divided into two types : function type and tuple type . A compound type may contain named types, tuple(Int, (Int, Int)) .
Example : 
let someTuple: (Double, Double) = (3.14159, 2.71828)
func someFunction(a: Int) { /* ... */ }

Note : A named type can be extended using Extensions and a compound type can not.

Variables and Data Type :

In Swift, we can define variables with var and constant with let . There are numbers of data types, including Int, Double, Float, Bool and String . Here are some examples on how to declare them, you can simply replace var by let to make them constant:

// Ways to declare Int
var intVar0: Int= 0
var intVar1 = 1
var intVal2 = 1_000_000
// Binary, Octal
var intVar3 = 0b10001
var intVar4 = 0o21
var intVar5 = 0x11
// Ways to declare Double and Float
var dbVar0: Double = 3.14
var dbVar1 = 3.14
var dbVar2 = Double(1)
var dbVar3 = 1.1e11
// HexadecimalDouble
var dbVar4 = 0xC.3p0
var dbVar5 = 0xFp2
var flVar0: Float = 3.14
var flVar1 = Float(1)
// Ways to declare Bool
var isTrue = true
var isTrue: Bool = true
// Ways to declare String
var str0 = "String"

Of course, you can also define other types, such as UInt8, Int8 and Float80.

You can also get the maximum or minimum of numeric type by .min and .max .

Also, it is not required to use String as the name, we can also use emoji to define value and names, as long as it can be represented by utf8, even your mother tongue.

let 😁 = "cat"

You can get the emoji in your Mac by holding these buttons : Command-CTRL-Space. However, this is highly not recommended.

String interpolation :

*String interpolations*

are string literals that evaluate any included expressions and convert the results to string form.
String interpolations give you an easy way to build a string from multiple pieces. Wrap each expression in a string interpolation in parentheses, prefixed by a backslash.

Swift.String

In Swift, we use String a lot, especially when we want to print stuff on the screen. Typically we only print variables, but we can print more than that. Here are some examples :

Basic String
"Hello, \(name)"
Numbers
"Hello, \(name.count)"
Functions
"Hello, \({ name })"
Optionals
"Hello, \(Optional.some(name))"
Classes / Struct
"Hello, \(MyStruct())"

Now that is the end of the brief introduction to Variables, Data Types and String Interpolation.

Next, we shall dig deeper in String Interpolation.

Let’s Start Digging

To understand String Interpolation, we should take a look at the struct String .

By holding ⌘ and click on the struct name String , you should now be at Swift.String .

We can see that String has multiple extensions. The one we are interested in is StringProtocol .

It is a type that could represent a string as a collection of characters.

Among the protocol that it implemented, we can find keywords like ExpressibleByStringInterpolation, Self.StringInterpolation and DefaultStringInterpolation .

Let’s take a closer look at these keywords.

ExpressibleByStringInterpolation

It is a protocol that contains the followings :

associatedtype StringInterpolation : 
StringInterpolationProtocol = DefaultStringInterpolation where Self.StringLiteralType == Self.StringInterpolation.StringLiteralType
init(stringInterpolation: Self.StringInterpolation)

These two lines of code only tell us that it can be initiated with StringInterpolation type or DefaultStringInterpolation .

So the secret of string interpolation might lie in DefaultStringInterpolation.

DefaultStringInterpolation

DefaultStringInterpolation is a struct that implemented StringInterpolationProtocol .

StringInterpolationProtocol

If we take a look at this protocol, we can see Apple left us a little note that you can find here.

The note explains that when we type "Time is \(time)" . This string is actually broken down into chunks that is similar to these statements :

var interpolation = MyString.StringInterpolation(literalCapacity: 13, interpolationCount: 1)interpolation.appendLiteral("The time is ")
interpolation.appendInterpolation(time)
interpolation.appendLiteral(".")
MyString(stringInterpolation: interpolation)

Therefore, by stating "\(time)" it will translate to appendInterpolation(time) and append the value to the string.

So now you know how String Interpolation works, what now?

EXTENSION comes to the rescue

Here are some examples given by Apple showing other ways we can make use of String Interpolation :

- `\(x)` translates to `appendInterpolation(x)`
- `\(x, y)` translates to `appendInterpolation(x, y)`
- `\(foo: x)` translates to `appendInterpolation(foo: x)`
- `\(x, foo: y)` translates to `appendInterpolation(x, foo: y)`

You might ask what is going on? Normally, these code shouldn’t work in your project.

In order to make something similar, we need to extends StringInterpolation from a String struct as follow:

extension MyString.StringInterpolation {
mutating func appendInterpolation(validating input: String)
{
//Perform validation of `input` and store for later use}
}

The code above allow us to use String Interpolation like this:

let myString = "The user typed '\(validating: userInput)'." as MyString

Of course, this is only a simple implementation, for more info please check out the links below.

RESOURCES

StringInterpolation explained

More on StringInterpolation Doc

--

--

Jimmy Liu
Kuo’s Funhouse

App Developer who enjoy learning from the ground up.