FREE: Read a new Swift article every day – click here! >>

Language

Found 206 articles in the Swift Knowledge Base for this category:

 

Check whether all items in an array match a condition

Swift has built-in way of checking whether all items in an array match a condition: the allSatisfy() method. Give this thing a condition to check, and it will apply that condition on all items until it finds one that fails, at which point it will return false. If it reaches the end of the array and all have passed the condition, it will return true.... Continue Reading >>

Checking all array elements match a condition: allSatisfy()

If you have a collection of objects and want to check that all of them match a specific condition, you should use the allSatisfy() method.... Continue Reading >>

Fixing "Ambiguous reference to member when using ceil or round"

If you've ever come across the error message "No 'ceil' candidates produce the expected contextual result type 'Int'" – which can happen with calls to ceil(), floor(), and round() – it's usually down to Swift being unable to satisfy type requirements you have asked for.... Continue Reading >>

Fixing "Class ViewController has no initializers"

This is a common error, and one you can fix in just a few seconds. Swift has very strict rules about property initialization: if you give a class any properties without a default value, you must create an initializer that sets those default values.... Continue Reading >>

How to add a custom initializer to a struct without losing its memberwise initializer

All structs in Swift come with a default memberwise initializer, which is an initializer that accepts values for all the properties in the struct. However, as soon as you add your own initializer to the struct that memberwise initializer goes away, because it’s possible you’re doing special work that the default initializer isn’t aware of.... Continue Reading >>

How to add associated values to enums

Enums with associated values let you associate extra data with an enum case. This helps make them significantly more useful, because we can create gradations of cases rather than have them be absolute.... Continue Reading >>

How to add Markdown comments to your code

Swift has special syntax that lets you embed Markdown-formatted text into your source code, which gets parsed by Xcode and displayed in the Quick Help system pane. Using specially formatted code comments, you can document what parameters should be passed in, what the return value will contain, any errors that can be thrown, and more.... Continue Reading >>

How to add raw values to enums

Raw values for enums are primitive values that sit behind each case. For example, you might create an enum for the planets in our solar system, and want to refer to each planet by a number as well as its name:... Continue Reading >>

How to add warnings and errors to your code using #warning and #error

Sometimes it’s important to add warnings and even errors to your code. For example, you might want to mark code as needing to be fixed, or mark placeholder values that must be filled in by whoever is using your code.... Continue Reading >>

How to append one array to another array

There are three ways of adding one array to another, and you can use whichever syntax you prefer.... Continue Reading >>

How to break out of multiple loop levels using labeled statements

Swift has a built-in break keyword that escapes the current loop you’re in, but what happens if you’re in two loops or more and want to break out of them all?... Continue Reading >>

How to calculate division remainder using modulo

Swift has a dedicated remainder operator in the form of %, and it’s used to return the remainder after dividing one number wholly into another. For example, 14 % 3 is 2, because you can fit four 3s into 14, and afterwards you have the remainder 2.... Continue Reading >>

How to check for valid method input using the guard keyword

The guard keyword was introduced in Swift to signal early returns, which is a coding technique that effectively means "make sure all these things are set up before I start doing the real work in my function, others bail out."... Continue Reading >>

How to check the Swift version at compile time

Swift gives us the #if swift build configuration option, which lets you compile certain code only if a specific version of the Swift compiler is detected. This is particularly useful for libraries that need to support multiple incompatible versions of Swift at the same time, because only one version of their code will ever be compiled.... Continue Reading >>

How to check whether a date is inside a date range

Everyone knows you can create ranges from two integers such as 1...5, but few people realize the same applies to dates. This means you can create a date range using the same closed-range operator (...) and half-open range operator (..<) you already know, allowing you to check whether one date lies inside a range.... Continue Reading >>

How to check whether a module is available using canImport()

Writing multi-platform code has its own challenges, but if you use the canImport() compiler test then one big challenge is solved for you: you can write one chunk code to run if a specific module is available, and another chunk otherwise.... Continue Reading >>

How to check whether an integer lies inside a range

All Swift’s ranges come with a built-in contains() method that lets us check whether one value lies inside or outside the range. For example, given this range:... Continue Reading >>

How to check your program state using precondition()

You should already know that the assert() function lets you check the state of your program at runtime, and crash if things aren’t how they should be. One of the neat features of assert() is that it automatically gets removed when you build your app in release mode, but if you don’t want that to happen – if you want your app to crash if something is seriously wrong – then you should use the precondition() function instead.... Continue Reading >>

How to compare dates

Swift’s Date struct conforms to both Equatable and Comparable, which means you check two dates for equality and compare them to see which is earlier.... Continue Reading >>

How to compare two tuples for equality

Swift 2.2 introduced the ability to compare two tuples up to arity six, which means the tuples can contain no more than six elements. To compare tuples, just use the == operator, like this:... Continue Reading >>

How to conform to the Comparable protocol

The Comparable protocol allows use to use the <, >, <=, and >= operators with conforming data types, which in turn means that Swift knows how to sort arrays of those types. Most of Swift’s built-in types support Comparable out of the box, but if you want your own type to conform to them then you need to implement < – from that Swift can provide default implementations of the other three operators.... Continue Reading >>

How to conform to the Equatable protocol

The Equatable protocol is what allows two objects to be compared using ==, and it’s surprisingly easy to implement because Swift does most of the work for you by default.... Continue Reading >>

How to conform to the Hashable protocol

In Swift, conforming to the Hashable protocol is often just as easy as adding Hashable to your conformance list. However, if you have custom requirements, or use properties that don’t all conform to Hashable, it takes a little more work.... Continue Reading >>

How to constrain a protocol associated type

Protocol associated types let you add a huge amount of flexibility to your protocols, but sometimes you want a little less flexibility. For example, you might say that all types conforming to an Identifiable protocol must specify the id of their object and also what type that ID must be:... Continue Reading >>

How to convert a float to a CGFloat

The Float and CGFloat data types sound so similar you might think they were identical, but they aren't: CGFloat is flexible in that its precision adapts to the type of device it's running on, whereas Float is always a fixed precision. Thus, you never lose precision converting from Float to CGFloat, whereas you might going the other way.... Continue Reading >>

How to convert a float to an int

You can convert between a Float and an Int just by using the integer's constructor, like this:... Continue Reading >>

How to convert a string to a double

Swift strings don't have a built-in way to convert to a Double, but their NSString counterparts do. To convert between strings and doubles, just do this:... Continue Reading >>

How to convert a string to a float

There are several ways to convert between a string and a Float, but the easiest way is to use NSString as an intermediate because that comes with several helpers built right in:... Continue Reading >>

How to convert a string to an int

If you have an integer hiding inside a string, you can convert between the two just by using the integer's constructor, like this:... Continue Reading >>

How to convert a string to an NSString

When Swift originally launched, NSString (older iOS strings) and native Swift strings were completely interchangeable, as were NSArray and Swift arrays, plus NSDictionary and Swift dictionaries. This got changed in Swift 1.2 so that you need to explicitly cast between these data types, and this remains the same in Swift today.... Continue Reading >>

How to convert a String to Data

Many APIs, such as Codable, rely on their text input being provided as a Data rather than a String, but fortunately it only takes one line of code to make that conversion:... Continue Reading >>

How to convert a Substring to a String

Swift has a dedicated Substring type (String.SubSequence) that is designed to hold slices of strings, which is a performance optimization: when you store part of a string in a different variable, Swift can simply point the substring at the parent string rather than copy all the data.... Continue Reading >>

How to convert an int to a float

Swift's Float data type has a built-in constructor that can convert from integers with no extra work from you. For example, to convert the integer 556 into its Float equivalent, you'd use this:... Continue Reading >>

How to convert an int to a string

Swift's string interpolation means you can convert all sorts of data – including integers – to a string in just one line of code:... Continue Reading >>

How to convert an NSRange to a Swift string index

Swift strings have changed in every release since the language was first announced, but even after so much change its older counterpart, NSRange, still appears in many UIKit APIs.... Continue Reading >>

How to convert Data to a String

If you know an instance of Data contains a String and you want to convert it, you should use the String(decoding:as:) initializer, like this:... Continue Reading >>

How to convert degrees to radians

Most users think about angles in terms of degrees from 0 to 360, but internally most of iOS works in radians so you’ll need to do some conversion. The equation to convert between the two is simple enough: multiply the number by Pi, then divide the result by 180.... Continue Reading >>

How to convert JSON into Swift objects using Codable

Swift’s Codable protocol makes it easy to convert JSON to native Swift structs and classes – just design data types that hold the same keys and values as your JSON, then use JSONDecoder to convert.... Continue Reading >>

How to convert radians to degrees

Most angles in iOS are measured using radians rather than degrees, but the majority of users prefer to see degrees so you’ll need to do some conversion. The equation to convert between the two is simple enough: multiply the number by 180, then divide the result by Pi.... Continue Reading >>

How to count element frequencies in an array

If you have an array containing various elements and you want to count how often each item appears, you can do so by combining the map() method with a Dictionary initializer.... Continue Reading >>

How to count matching items in an array

If you want to count how many items in an array (or any collection) match a test you specify, the easiest thing to do is run the collection through a call to filter() then count the remainder.... Continue Reading >>

How to create a custom debug description

Swift lets you print all types of data, but some data is more useful than others thanks to the CustomDebugStringConvertible protocol. If you write a type conforming to that protocol, you must include a debugDescription string property that describes how instances of this type should be represented while debugging.... Continue Reading >>

How to create a custom OptionSet

Option sets are similar to enums, but they are designed to work as a set so you can use more than one at a time. For example, when using the range(of:) method of a string, you can specify .caseInsensitive to have the search ignore case, you can specify .backwards to have the search start from the end of the string, or you can combine the two:... Continue Reading >>

How to create an array by repeating an item

If you need to create an array of a specific size holding some default values, Swift has a built-in initializer called repeating:count:. You tell it what to repeat, and how often, and Swift will generate an array of that size.... Continue Reading >>

How to create an Objective-C bridging header to use code in Swift

If you want to use Objective-C code in your Swift app – and let's face it, that's going to happen quite a lot! – then you need to create a bridging header that allows your Swift code to work with your Objective-C code.... Continue Reading >>

How to create hash values from objects using Hasher

Hash values are an invaluable way of identifying data uniquely, and any type that conforms to the Hashable protocol can be used to create all or part of a hash value by using the Hasher struct.... Continue Reading >>

How to create multi-line string literals

By default Swift strings can’t span more than one line. One simple way around this is to use the new line character \n, but that only works for strings that are displayed – if you’re just trying to format your string nicely, you should use multi-line strings instead.... Continue Reading >>

How to delay execution of code using the defer keyword

The defer keyword is new in Swift 2 and lets you schedule some code to be run at a later date. That later date is when your code exits its current scope, which might be when a function returns or at the end of a loop, for example.... Continue Reading >>

How to detect when the system is under pressure and you should reduce your work

You can – and should – read the thermal state of your device before doing any intensive work, because if the system is already under pressure you might find your app becomes unresponsive, even with basic things like animations.... Continue Reading >>

How to filter a loop using a where clause

A regular for-in loop goes over all the items in an array, allowing you to manipulate them as you need. However, sometimes you don’t need all items and instead only want a subset, and in those circumstances the where keyword is useful.... Continue Reading >>

How to find the difference between two arrays

If you have two arrays that contain similar items and want to find out their differences – i.e., which items exist in one or the other, but not both – the easiest thing to do is use a Set. Sets have a symmetricDifference() method that does exactly this, so you just need to convert both arrays to a set, then convert the result back into an array.... Continue Reading >>

How to find the first matching element in an array

The first() method exists on all sequences, and returns the first item in a sequence that passes a test you specify.... Continue Reading >>

How to find the highest value in an array

All arrays have a built-in method called max(), which returns the highest item in the array. This comes with a default implementation if the elements of the array conform to Comparable: it will simply compare all items until it finds the one that compares highest.... Continue Reading >>

How to find the index of the first matching array element

If you have an array of items and want to find the first item that matches a specific condition, you should use the index(where:) method. This accepts a closure of code to use as a test, applies that test to all elements in an array, then returns the index of the first item to match it. If no item matches you’ll get back nil, so be prepared to unwrap the optional you get sent back.... Continue Reading >>

How to find the longest initial sequence in an array

One of Swift’s lesser-known functions is prefix(while:): call this on an array along with a test to apply, and it will return as many items from the start of the array as it can, stopping only when it reaches the first element that fails your test.... Continue Reading >>

How to find the maximum of three numbers

The easiest way to find the maximum of three numbers is to use the max() function twice: once with your first two numbers, and again with your third number and the result of the first call. Here's an example:... Continue Reading >>

How to find the maximum of two numbers

To find the largest of any two integers, use the max() function like this:... Continue Reading >>

How to find the minimum of three numbers

You can find the minimum of three numbers by using the min() function twice. This function takes either two integers or two floating-point numbers, but can't accept mixed types. Here's an example:... Continue Reading >>

How to find the minimum of two numbers

To find the minimum of two numbers, either both integer or both floating point (not mixed!), use the min() function. For example:... Continue Reading >>

How to fix “argument of #selector refers to instance method that is not exposed to Objective-C”

Swift 4 changed the way Swift interacts with Objective-C in a way that will impact the code of most developers. Fortunately, there are a couple of fixes available, neither of which take too long to implement.... Continue Reading >>

How to fix the error “Expression was too complex to be solved in reasonable time”

Swift’s use of type inference makes our code shorter and easier to read, but it also chews up a lot of CPU time. Sometimes a value could be one of several types, and if it gets used with another things that could be one of several types then the amount of work Swift has to do multiplies. If Swift encounters something with so many possibilities that it simply can’t figure it out after about 15 seconds, it throws an error instead: “Expression was too complex to be solved in reasonable time; consider breaking up the expression into distinct sub-expressions.”... Continue Reading >>

How to fix the error “protocol can only be used as a generic constraint because it has Self or associated type requirements”

Protocols with associated types are a powerful, if somewhat treacherous, feature of Swift. Sometimes it’s fair to say that the only winning move is not to play – i.e., to avoid them entirely – but if that isn’t the case you are sometimes likely to find yourself facing a difficult error: “protocol can only be used as a generic constraint because it has Self or associated type requirements.”... Continue Reading >>

How to force a crash using fatalError()

Swift has a built-in function called fatalError(), which forces your application to crash. This might sound useful, but bear with me – this is an indispensable function for anyone serious about writing good Swift.... Continue Reading >>

How to force your program to crash with assert()

This might seem like a strange topic – after all, why would anyone want their program to crash? Well, the answer is two-fold.... Continue Reading >>

How to format JSON using Codable and pretty printing

When you use JSONEncoder and Codable to create JSON from your Swift data, it comes out in a compressed format by default – it has all its excess whitespace removed. This makes it efficient for transferring over the network, but hard to debug because it’s just a big jumble of words.... Continue Reading >>

How to generate a random number

You can generate random numbers by calling the random() method on whatever numeric type you’re using, providing the range you want to work with. For example, this generates a random number in the range 1 through 5, inclusive on both sides:... Continue Reading >>

How to get a random element from an array using randomElement()

Swift’s arrays, sets, and dictionaries have a randomElement() method that returns one random item from the collection. Because your collection might be empty, the return type will be optional and you’ll get back nil if the collection had nothing in it.... Continue Reading >>

How to group arrays using dictionaries

If you have an array of items and want to group them according to some criteria, Swift has a special dictionary initializer just for you.... Continue Reading >>

How to handle unknown properties and methods using @dynamicMemberLookup

Swift has always had strong focus on type safety, but sometimes you need to be able to work with data where the structure isn’t known ahead of time.... Continue Reading >>

How to ignore return values using @discardableResult

Many functions return values, but sometimes you don’t care what the return value is – you might want to ignore it sometimes, and use it other times.... Continue Reading >>

How to install a beta version of Swift

Xcode ships with a fixed version of Swift, but that doesn't mean you need to use that version. In fact, it's possible to install multiple versions of the Swift toolchain, and switch between them as often as you need. At the time of writing, that means you can use Swift 5.0 with Xcode 10, and try out Swift development releases alongside.... Continue Reading >>

How to list all cases in an enum using CaseIterable

Swift 4.2 introduced a new CaseIterable protocol that automatically generates an array property of all cases in an enum. To enable it, all you need to do is make your enum conform to the CaseIterable protocol and at compile time Swift will automatically generate an allCases property that is an array of all your enum’s cases, in the order you defined them.... Continue Reading >>

How to loop over non-nil items in an array

Consider an array of items containing some optionals, like this one:... Continue Reading >>

How to make a custom sequence

When you use a for-in loop, Swift maps that code to a while loop that generates an iterator for your data. Swift then calls next() on that iterator repeatedly until it gets back nil to signal that the loop has ended.... Continue Reading >>

How to make a number positive using abs()

The abs() function returns the absolute value of a number, which is a way of describing how far away from zero it is without thinking about whether it’s positive or negative. It’s most commonly used if you have a number that you need to be positive, because whether you pass 30 or -30 to abs() you get back 30.... Continue Reading >>

How to make a variadic function

Variadic functions are functions that accept any number of parameters. The most common one in Swift is print() – most people use it to print a single value, but you can actually pass as many as you want, like this:... Continue Reading >>

How to make array access safer using a custom subscript

Swift likes to be safe, but one problematic area can be reading from arrays and dictionaries. In the case of dictionaries, reading a missing key will return nil rather than the value you might have expected, but in the case of arrays it’s worse: your app will crash.... Continue Reading >>

How to make custom types from strings using ExpressibleByStringLiteral

Swift’s ExpressibleByStringLiteral protocol lets us create any type directly from a string – as long as Swift understands what type you mean, you can create whatever you want.... Continue Reading >>

How to make optional protocol methods

By default, all methods listed in a Swift protocol must be implementing in a conforming type. However, there are two ways you can work around this restriction depending on your need.... Continue Reading >>

How to multiply an int and a double

Swift’s type safety means code to multiply an integer and a double won’t compile:... Continue Reading >>

How to pass the Fizz Buzz test

The Fizz Buzz test is a simple coding test used in some coding interviews. It’s not designed to be hard, in fact quite the opposite – it’s designed to be easy enough that most folks can solve it without feeling too pressured.... Continue Reading >>

How to print debug text in Swift

You can write text to the Xcode debug console using the print() function in Swift, like this:... Continue Reading >>

How to remove duplicate items from an array

There are several ways of removing duplicate items from an array, but one of the easiest is with the following extension on Array:... Continue Reading >>

How to remove items from an array using filter()

The filter() method goes over all the items in an array (or indeed any kind of collection), and returns a new array containing items that pass a test you specify.... Continue Reading >>

How to remove the first or last item from an array

Arrays have built-in methods for removing the first or last items, but there’s a subtle difference between them.... Continue Reading >>

How to restrict a protocol to classes

There are some occasions when your protocol relies on reference semantics to work, which in practice means it can be adopted only by classes. For example, you might want to use the identity operator (===) to compare two instances of a conforming type, or you might want to change properties inside the type without relying on mutating methods.... Continue Reading >>

How to reverse sort an array

Regular sorting on comparable data is as easy as calling the sort() method, but if you want a reverse sort – e.g. highest to lowest numbers, or Z-A alphabetically – there are two options.... Continue Reading >>

How to run code when an object is destroyed

All structs and classes can have initializers, which are special methods that run when those types are created. However, classes can also have deinitializers – code that gets run when an instance of the class is destroyed. This isn’t possible with structs because they only ever have one owner.... Continue Reading >>

How to safely use reference types inside value types with isKnownUniquelyReferenced()

Working with value types like structs and enums makes your code easier to write, easier to test, and easier to reason about. However, they aren’t always possible: classes and closures are both reference types, and are used extensively in Swift for the handful of times when sharing data is important, or perhaps because you’re using them through someone else’s Swift code.... Continue Reading >>

How to sort the keys of your JSON using Codable

When you use JSONEncoder and Codable to create JSON from your Swift data, your properties get written out in the order they appear inside your class. This is nearly always fine, because relying on key ordering in your JSON is almost certainly a bad idea.... Continue Reading >>

How to specify default values for dictionary keys

Reading a dictionary key returns an option value by default, because the key you asked for might not exist. However, there’s a slightly different subscript you can call that eliminates optionality: when you read a key, you can also provide a default value to use if the key doesn’t exist.... Continue Reading >>

How to specify your own date format with Codable and JSONEncoder

When using JSONEncoder to encode dates, there are a handful of built-in date formats you can choose from. If none of them fit your needs, why not make your own? You can configure a DateFormatter using whatever date and time format you want, then pass that to the JSONEncoder as its dateEncodingStrategy property, like this:... Continue Reading >>

How to split an array into chunks

If you have an array of elements and you want to split them into chunks of a size you specify, here’s a useful extension you can add to your code:... Continue Reading >>

How to split an integer into an array of its digits

You can take any integer number and convert it to array of integer digits using this extension:... Continue Reading >>

How to store NSCoding data using Codable

Broadly speaking, NSCoding is the Objective-C way of archiving data and Codable is the Swift way. However, that doesn’t mean the two can’t work together – with a little work you can save any NSCoding data right inside Codable, which is helpful because many Apple types such as UIColor and UIImage conform to NSCoding but not Codable.... Continue Reading >>

How to sum an array of numbers using reduce()

The reduce() method is designed to convert a sequence into a single value, which makes it perfect for calculating the total of an array of numbers.... Continue Reading >>

How to swap two items in an array using swapAt()

If you need to have two items in an array change places, the swapAt() method is exactly what you want: provide it two indexes inside your array, and the items at those positions will be swapped.... Continue Reading >>

How to throw errors using strings

Throwing functions in Swift are the main way we have of signaling that an operation failed, but sometimes it can be annoying to define a whole new error enum just to report a simple failure.... Continue Reading >>

How to toggle a boolean value

Swift’s booleans have a toggle() method that flip them between true and false. That might sound simple, but the end result makes for much more natural Swift code:... Continue Reading >>

How to transform a dictionary using mapValues()

Although dictionaries have a general map() method, they also have a specialized form of map() called mapValues() – it transforms just the values of the dictionary, leaving the keys untouched.... Continue Reading >>

How to unwrap an optional in Swift

Optional values are a central concept in Swift, although admittedly they can be a little hard to understand at first. Put simply, an optional value is one that may or may not exist, which means Swift won't let you use it by accident – you need to either check whether it has a value and unwrap it, or force unwrap. Of the two options the first is definitely preferable, because it's significantly safer.... Continue Reading >>

How to use @available to deprecate old APIs

Swift availability checking is most commonly used to mark sections of code that should target specific versions of iOS or other platforms. However, it’s also useful when you make Swift APIs for others to use, because you can use it to mark certain calls as deprecated or even obsoleted as needed.... Continue Reading >>

How to use #available to check for API availability

One of my favorite Xcode features is the ability to have Xcode automatically check API availability for you, which means it will refuse to run code that is not available on the minimum iOS version you support.... Continue Reading >>

How to use Codable to load and save custom data types

Swift 4 introduced a new way to load and save data, replacing the old NSCoding protocol with something that’s more flexible, safer, and easier to write: Codable.... Continue Reading >>

How to use compactMap() to transform an array

The compactMap() method lets us transform the elements of an array just like map() does, except once the transformation completes an extra step happens: all optionals get unwrapped, and any nil values get discarded.... Continue Reading >>

How to use compiler directives to detect the iOS Simulator

Swift makes it easy to write special code that should be executed only in the iOS Simulator. This is helpful to test situations where the simulator and devices don't match, for example testing the accelerometer or camera.... Continue Reading >>

How to use conditional conformance in Swift

Conditional conformances were introduced in Swift 4.1, and refined in Swift 4.2 to allow you to query them at runtime. They allow types to conform to a protocol only when certain conditions are met – hence “conditional conformance”.... Continue Reading >>

How to use flatMap() with an optional value

The flatMap() method of optionals allows you to transform the optional if it has a value, or do nothing if it is empty. This makes for shorter and more expressive code than doing a regular unwrap, and doesn’t require you to change your data type.... Continue Reading >>

How to use ISO-8601 dates with JSONDecoder and Codable

Encoding and decoding dates using the Codable protocol isn’t hard to do, but it does produce some unexpected data by default: Date stores its information as a floating-point number counting the number of seconds since January 1st 2001, rather than something standard involved days, months, and years.... Continue Reading >>

How to use local variable observers

You should already be familiar with the concept of property observers in Swift – those willSet and didSet blocks you can attach to property on classes and structs. Well, those same blocks can be attached to local and global variables as well, allowing you to respond to changes easily.... Continue Reading >>

How to use map() to transform an array

The map() method allows us to transform arrays (and indeed any kind of collection) using a transformation closure we specify. The return value will be an array of the same size, containing your transformed elements.... Continue Reading >>

How to use map() with an optional value

The map() method of optionals allows you to transform the optional if it has a value, or do nothing if it is empty. This makes for shorter and more expressive code than doing a regular unwrap, and doesn’t require you to change your data type.... Continue Reading >>

How to use one-sided ranges

One-sided ranges allow us to skip either the start or end of a range to have Swift infer the starting point for us. As an example, consider this array:... Continue Reading >>

How to use operator overloading

Operator overloading is the practice of adding new operators and modifying existing ones to do different things. Operators are those little symbols like +, *, and /, and Swift uses them in a variety of ways depending on context – a string plus another string equals a combined string, for example, whereas an integer plus another integer equals a summed integer.... Continue Reading >>

How to use reduce() to condense an array into a single value

The reduce() method iterates over all items in array, combining them together somehow until you end up with a single value. The “somehow” is specified by a closure you provide, for example you might want to count how many characters are provided in an array of names, which looks like this:... Continue Reading >>

How to use reflection to inspect type data

Swift has a built-in Mirror struct that lets us query any kind of data in our code. It’s most commonly used to read through the list of properties that are available, but it’s also used in playgrounds to print out user-readable values inside types.... Continue Reading >>

How to use the forEach method to loop over an array

In Swift we normally loop over arrays like this:... Continue Reading >>

How to use the rethrows keyword

The rethrows keyword is used when you write a function (let’s call it A) that accepts a throwing function as a parameter (let’s call it B). If function B throws errors, then the function A becomes a throwing function too, but if function B doesn’t throw errors then neither does function A.... Continue Reading >>

How to use the zip() function to join two arrays

The zip() function is designed to merge two sequences into a single sequence of tuples. For example, here is an array of wizards:... Continue Reading >>

How to use try/catch in Swift to handle exceptions

The try/catch syntax was added in Swift 2.0 to make exception handling clearer and safer. It's made up of three parts: do starts a block of code that might fail, catch is where execution gets transferred if any errors occur, and any function calls that might fail need to be called using try.... Continue Reading >>

How to use typealias to make it easier to use complex types

Although it’s generally a good idea to use structs or classes for defining your types, sometimes you’ll find yourself using tuples. If this happens to you, it’s quite tedious having to type the full definition of your tuple whenever you want to use it, so the typealias lets you create a specific name for it:... Continue Reading >>

How to write a closure that returns a value

Like regular functions, closures can accept values and return values of your choosing: just write them out at the start of your closure, followed by the word in.... Continue Reading >>

Optional vs implicitly unwrapped optional: what’s the difference?

When you’re just learning Swift, the difference between an optional (String?), an implicitly unwrapped optional (String!), and a regular type (String) can seem awfully confusing. Here’s a quick summary that should explain the difference:... Continue Reading >>

Private vs fileprivate: what’s the difference?

These two forms of access control are similar, but there are two differences.... Continue Reading >>

Remove all instances of an object from an array

Arrays already have methods to find and remove a single item, or remove all items at once, but they don’t have a built-in way to remove all instances of a single item. For example, how would you remove all the 2s in the following array?... Continue Reading >>

Removing matching elements from a collection: removeAll(where:)

The removeAll(where:) method performs a high-performance, in-place filter for collections. You give it a closure condition to run, and it will strip out all objects that match your condition.... Continue Reading >>

Self vs self - what's the difference?

When you’re writing protocols and protocol extensions, there’s a difference between Self (capital S) and self (lowercase S). When used with a capital S, Self refers to the type that conform to the protocol, e.g. String or Int. When used with a lowercase S, self refers to the value inside that type, e.g. “hello” or 556.... Continue Reading >>

Tips for Android developers switching to Swift

Here are my top ten tips to help you switch from coding Java on Android to coding Swift on iOS:... Continue Reading >>

Using stride() to loop over a range of numbers

Swift has a helpful stride(), which lets you move from one value to another using any increment – and even lets you specify whether the upper bound is exclusive or inclusive.... Continue Reading >>

What are class and subtype existentials?

You should already know that Swift lets you specify a concrete type as a function parameter, meaning that you can say “this parameter must be a string.” Swift also lets you specify protocols types for function parameters, meaning that you can say “this parameter must conform to Codable.”... Continue Reading >>

What are convenience initializers?

Designated initializers are the default way of creating new instances of a type. There are others, known as convenience initializers, that are there to help you accomplish common tasks more easily, but those are in addition to your designated initializers rather than a replacement.... Continue Reading >>

What are designated initializers?

Designated initializers are the default way of creating new instances of a type. There are others, known as convenience initializers, that are there to help you accomplish common tasks more easily, but those are in addition to your designated initializers rather than a replacement.... Continue Reading >>

What are generics?

Generics are a way of making one data type act in a variety of ways depending on how it is created. You’ve already used them whether you realized or not: Swift has an Array type, but it is generic – it doesn’t contain any sort of specific data. Instead, you ask for arrays that hold specific kinds of data by using things like [String] to get a string array.... Continue Reading >>

What are implicitly unwrapped optionals?

Regular Swift optionals, e.g. String?, may contain a value, but may also contain nil – they might have no value at all – so before we can use them we must check to see what they contain. These are a useful way of expressing uncertainty, because a full String (not optional) must always contain a string.... Continue Reading >>

What are keypaths?

Swift keypaths are a way of storing uninvoked references to properties, which is a fancy way of saying they refer to a property itself rather than to that property’s value.... Continue Reading >>

What are KeyValuePairs?

KeyValuePairs, somewhat confusingly known as DictionaryLiteral before Swift 5.0, is a useful data type that provides dictionary-like functionality with a handful of benefits:... Continue Reading >>

What are lazy variables?

It's very common in iOS to want to create complex objects only when you need them, largely because with limited computing power at your disposal you need to avoid doing expensive work unless it's really needed.... Continue Reading >>

What are property observers?

Property observers are Swift's way of letting you attach functionality to changes in property values. For example, you might want to say, "whenever the player's score changes, update this label to show their new score." Here's a basic example that prints message to the debug console when a variable changes:... Continue Reading >>

What are protocol extensions?

This might sound obvious, but protocol extensions are extensions to protocols as opposed to concrete types. For example, the BinaryInteger protocol is adopted by all integer types: Int, Int64, UInt8, and so on. If you wanted to add a method to all of those at once, you’d use a protocol extension to modify BinaryInteger, like this:... Continue Reading >>

What are sets?

Sets are a type of sequence similar to arrays, except they may not store any item more than once and are unordered. This eliminates them from many places where you would use an array, but they do have one special super-power: it’s extremely fast to check whether a set contains a specific value. In fact, sets perform this operation at the same speed whether they contain 10 items or 10,000 items.... Continue Reading >>

What are static methods and variables?

Static methods and variables belong to the type that defined them, rather than instances of that type. For example, we could create a struct to track taxis in a city, like this:... Continue Reading >>

What are the changes in Swift 1.2?

Swift 1.2 was an interim release that fixed some early confusions and annoyances in the language. Its changes weren't big, but they did help clean up and clarify Swift, and helped tide us all over until the release of Swift 2.... Continue Reading >>

What are the changes in Swift 2.0?

Swift 2.0 introduced a lot of major language changes. You can read my full article explaining the changes with code examples by clicking here, but here are the highlights:... Continue Reading >>

What are the changes in Swift 2.2?

Swift 2.2 introduced a lot of major language changes. You can read my full article explaining the changes with code examples by clicking here, but here are the highlights:... Continue Reading >>

What are the changes in Swift 3?

Swift 3.0 introduced the biggest changes to the language since it was released, and it’s 100% guaranteed to cause your current code to break unless you had written some extraordinarily trivial apps.... Continue Reading >>

What does an exclamation mark mean?

Swift uses exclamation marks to signal both force unwrapping of optionals and explicitly unwrapped optionals. The former means "I know this optional variable definitely has a value, so let me use it directly." The latter means "this variable is going to be nil initially then will definitely have a value afterwards, so don't make me keep unwrapping it."... Continue Reading >>

What does override mean?

The override is used when you want to write your own method to replace an existing one in a parent class. It's used commonly when you're working with UIViewControllers, because view controllers already come with lots of methods like viewDidLoad() and viewWillAppear(). When you want to override these default methods, you need to specify this with the override keyword.... Continue Reading >>

What does the AppDelegate class do?

If you create your app using one of Xcode’s built-in templates, you’ll automatically get an AppDelegate class in AppDelegate.swift, which comes with a handful of empty methods.... Continue Reading >>

What does the open keyword do?

When working with code from another module – e.g., UIKit or a module you wrote separate from your main app – Swift differentiates between public accessibility and public overridability. That is, someone can be public for folks to use, but not public for them to extend.... Continue Reading >>

What does unowned mean?

Unowned variables are similar to weak variables in that they provide a way to reference data without having ownership. However, weak variables can become nil – they are effectively optional. In comparison, unowned variables must never be set to nil once they have been initialized, which means you don't need to worry about unwrapping optionals.... Continue Reading >>

What does weak mean?

Unless you specific otherwise, all Swift properties are strong, which means they will not be removed from RAM until whatever owns them is removed from RAM. So, if you create an array in your view controller and you want it to stick around until the view controller is destroyed, that's what strong does.... Continue Reading >>

What is a CGFloat?

A CGFloat is a specialized form of Float that holds either 32-bits of data or 64-bits of data depending on the platform. The CG tells you it's part of Core Graphics, and it's found throughout UIKit, Core Graphics, Sprite Kit and many other iOS libraries.... Continue Reading >>

What is a closure?

If you're here because you find closures hard, that's OK: most people find closures hard. But in truth, closures aren't actually that complicated, so I hope I can explain them to you quickly and easily.... Continue Reading >>

What is a computed property?

Swift offers us two kinds of property: a stored property is one that saves a value for use later, and a computed property is one that runs some code in order to calculate the value.... Continue Reading >>

What is a delegate in iOS?

Delegates are extremely common in iOS development, but fortunately they are easy to understand: a delegate is any object that should be notified when something interesting has happened. What that "something interesting" means depends on the context: for example, a table view's delegate gets notified when the user taps on a row, whereas a navigation controller's delegate gets notified when the user moves between view controllers.... Continue Reading >>

What is a dictionary?

A dictionary is a collection of values stored at named positions. Whereas you would access values in an array using myArray[5], with a dictionary you use named positions such as myDict["Paul"] or myDict["Scotland"]. You don't even need to use strings for the positions – you can use another object if you choose, such as dates.... Continue Reading >>

What is a double?

The Double data type is the standard Swift way of storing decimal numbers such as 3.1, 3.14159 and 16777216.333921. Whenever you create a variable or constant that holds a number like this, Swift automatically assumes it's a Double rather than a Float, because it has a higher precision and therefore less likely to lose valuable accuracy.... Continue Reading >>

What is a float?

The Float data type stores low-precision decimal numbers such as 3.1, 3.14159 and 556.9. It is not used that often in Swift, partly because Double is the default for these kinds of numbers (it has a higher precision), and partly because when you come across libraries that use regular floats they are more likely to want CGFloat instead.... Continue Reading >>

What is a functor?

A functor is any data type that can be mapped over using map(), as long it abides by two laws:... Continue Reading >>

What is a lazy sequence?

Lazy sequences are regular sequences where each item is computed on demand rather than up front. For example, consider this array of numbers:... Continue Reading >>

What is a monad?

A monad is any data type that can be mapped over using map() and flat mapped over using flatMap(), as long it abides by three laws. Arrays, sets, optionals, and more are all monads.... Continue Reading >>

What is a nested class or nested struct?

Nested types – i.e. nested structs and nested classes – are a useful way of organizing your code, and perhaps even restricting what others can do with it. In essence, a nested type is just one data type defined inside another, like this:... Continue Reading >>

What is a nib?

NIBs and XIBs are files that describe user interfaces, and are built using Interface Builder. In fact, the acronym "NIB" comes from "NeXTSTEP Interface Builder", and "XIB" from "Xcode Interface Builder". NIBs and XIBs are effectively the same thing: XIBs are newer and are used while you're developing, whereas NIBs are what get produced when you create a build.... Continue Reading >>

What is a protocol associated type?

Associated types are a powerful way of making protocols generic, but they can be a bit confusing at first. In essence, they mark holes in protocols that must be filled by whatever types conform to those protocols.... Continue Reading >>

What is a protocol?

A protocol is a collection of methods that describe a specific set of similar actions or behaviors. I realize that probably didn't help much, so I'll try to rephrase in more detail: how many rows should a table view have? How many sections? What should the section titles be? Can the user move rows? If so, what should happen when they do?... Continue Reading >>

What is a selector?

Selectors are effectively the names of methods on an object or struct, and they are used to execute some code at runtime. They were common in Objective-C, but the earliest versions of Swift didn't include some core selector functionality so their use declined for a while. That functionality (things like performSelector(inBackground:)) has since been restored.... Continue Reading >>

What is a singleton?

Singletons are objects that should only ever be created once, then shared everywhere they need to be used. They are common on Apple’s platforms: FileManager, UserDefaults, UIApplication, and UIAccelerometer are all mostly used through their singleton implementations.... Continue Reading >>

What is a storyboard?

Storyboards were introduced way back in iOS 5 as a way to revamp interface design for iOS. At the time they didn't add much in the way of features that weren't available with the older XIBs, but in subsequent releases Apple have added helpful new features such as layout guides that make them much more useful – and arguably indispensable since iOS 7.... Continue Reading >>

What is a throwing function?

Throwing functions are those that will flag up errors if problems happen, and Swift requires you to handle those errors in your code.... Continue Reading >>

What is a tuple?

Tuples in Swift occupy the space between dictionaries and structures: they hold very specific types of data (like a struct) but can be created on the fly (like dictionaries). They are commonly used to return multiple values from a function call.... Continue Reading >>

What is an enum?

“Enum” is short for “enumeration”, and it’s a way of letting you use fixed names for special values rather than relying on strings or integers.... Continue Reading >>

What is an escaping closure?

Swift’s closures are reference types, which means if you point two variables at the same closure they share that closure – Swift just remembers that there are two things relying on it by incrementing its reference count.... Continue Reading >>

What is an optional value in Swift?

Swift optionals are one of the most confusing parts of the language for beginners, but actually are fairly easy to understand. Put simply, if I declare a variable as an integer, that means it must hold a number. That number might be 0, 1, -1, 159, -758119, or whatever, but it's definitely a number. This works great for telling me, for example, where in an array a certain element can be found.... Continue Reading >>

What is AnyObject?

This is one of those things that sounds obvious in retrospect: AnyObject is Swift's way of saying, "I don't mind what type of object you pass in here, it could be a string, it could be a string, it could be a number, it could be an array, or it could be a custom type you defined yourself.... Continue Reading >>

What is Automatic Reference Counting (ARC)?

Automatic Reference Counting (ARC) is Swift’s system of tracking memory you’re using. When you create an object from a class, Swift remembers that instance is being referenced precisely once. If you then point another variable at that object, Swift will increment the reference count to 2, because two variables are pointing at the same object. If you now destroy the first variable (perhaps it was inside a function and that function ended), Swift takes the reference count back down to 1.... Continue Reading >>

What is class inheritance?

Swift allows you to define a custom class as inheriting from another, which means it gains the functionality of the original class while being able to add its own. This is used extensively on Apple platforms: UIButton inherits from UIControl, which inherits from UIView, which inherits from UIResponder, which inherits from NSObject, for example.... Continue Reading >>

What is copy on write?

Copy on write is a common computing technique that helps boost performance when copying structures. To give you an example, imagine an array with 1000 things inside it: if you copied that array into another variable, Swift would have to copy all 1000 elements even if the two arrays ended up being the same.... Continue Reading >>

What is destructuring?

Destructuring is the practice of pulling a tuple apart into multiple values in a single assignment. For example, consider a trivial function that accepts names in the format “FirstName LastName” and returns a tuple containing the first and last names separated:... Continue Reading >>

What is function composition?

Function composition is the ability to combine small functions together to make bigger functions.... Continue Reading >>

What is key-value observing?

Key-value observing is the ability for Swift to attach code to variables, so that whenever the variable is changed the code runs. It’s similar to property observers (willSet and didSet ), except KVO is for adding observers outside of the type definition.... Continue Reading >>

What is MVC?

MVC – short for Model-View-Controller – is Apple’s preferred way of architecting apps for its platforms, and so it’s the default approach used by most developers on Apple platforms.... Continue Reading >>

What is MVVM?

MVVM stands for “Model View ViewModel”, and it’s a software architecture often used by Apple developers to replace MVC.... Continue Reading >>

What is NSNumber?

NSNumber is an Objective-C class designed to store a variety of types of numbers. It was important in Objective-C because its primitive number types – integers, doubles, etc – could not be used in most of Apple’s APIs without wrapping them in an object such as NSNumber, but mostly Swift does a good job of automatically converting its numbers to NSNumber when you need it.... Continue Reading >>

What is optional chaining?

Optional chaining is a Swift feature that allows execution of a statement to stop and return nil at any point. For example, all views have an optional superview property that stores whichever UIView contains it, all UIView has an optional gestureRecognizer array that stores the gesture recognizers it has, and all arrays have an optional first property that returns the first item.... Continue Reading >>

What is protocol-oriented programming?

One powerful feature of Swift is its ability to extend protocols – to be able to add new functionality not only to one type, but to a whole collection of types that all conform to the same protocol.... Continue Reading >>

What is the @objc attribute?

By default Swift generates code that is only available to other Swift code, but if you need to interact with the Objective-C runtime – all of UIKit, for example – you need to tell Swift what to do.... Continue Reading >>

What is the @objcMembers attribute?

By default Swift generates code that is only available to other Swift code, but if you need to interact with the Objective-C runtime – all of UIKit, for example – you need to tell Swift what to do.... Continue Reading >>

What is the autoclosure attribute?

The @autoclosure attribute can be applied to a closure parameter for a function, and automatically creates a closure from an expression you pass in. When you call a function that uses this attribute, the code you write isn't a closure, but it becomes a closure, which can be a bit confusing – even the official Swift reference guide warns that overusing autoclosures makes your code harder to understand.... Continue Reading >>

What is the Never return type?

The Never return type is a special one in Swift, and tells the compiler that execution will never return when this function is called. It’s used by Swift’s fatalError() and preconditionFailure() functions, both of which cause your app to crash if they are called.... Continue Reading >>

What is the nil coalescing operator?

Optionals are a powerful source of safety in Swift, but can also be annoying if you find them littered throughout your code. Swift's nil coalescing operator helps you solve this problem by either unwrapping an optional if it has a value, or providing a default if the optional is empty.... Continue Reading >>

What is the ternary operator?

The ternary operator allows you to run a check and return one of two values depending on the result of that check – it has the name “ternary” because it works with three values rather than two or one like other operators. You’ll often see it written as ?: but in practice the ? and : are used separately.... Continue Reading >>

What is trailing closure syntax?

Trailing closure syntax is a little piece of syntactic sugar that makes particularly common code more pleasant to read and write. Many functions in iOS accept multiple parameters where the final parameter is a closure. For example, if you've done animation in iOS you'll be familiar with this method:... Continue Reading >>

What is typecasting?

One of the many safety features of Swift is its type safety, which means it must know what kind of data is being held by all values at all times. However, sometimes you know information that Swift doesn’t: you know that the UIViewController you have a reference to is in fact your custom PictureViewController subclass, and you want to treat it like one.... Continue Reading >>

What is whole module optimization?

Whole module optimization is a compiler pass that can add significant performance gains, and so it's always worth enabling when doing a release build of your app for the App Store. How it works is quite simple: when Swift builds the final version of your app it combines all your source files together and can evaluate the whole structure of your program at once. This lets it make extra optimizations that would be impossible before, when every file was optimized individually.... Continue Reading >>

What's the difference between let and var?

Swift lets you create both variables and constants as ways to reference your data, but there's a strong push (even Xcode warnings!) if you create things as variables then never change them. To make a constant, use let like this:... Continue Reading >>

What’s the difference between == and ===?

Swift gives us two equality operators, == and ===, that do slightly different things. You will almost certainly need to use both of them so it’s worth taking the time to learn them.... Continue Reading >>

What’s the difference between a class and a struct?

Classes and structures (structs) are so similar in Swift that it's easy to get them confused at first, but actually there are some important underlying differences:... Continue Reading >>

What’s the difference between a function and a closure?

Closures and functions are very similar in Swift, but there are some subtle differences. When you’re learning, it’s easiest to think of a closure as being a function that doesn’t have a name of its own, and captures any values from its environment.... Continue Reading >>

What’s the difference between a function and a method?

Some folks use “function” and “method” interchangeably, but there’s a small difference: both of them are reusable chunks of code, but methods belong to classes, structs, and enums, whereas functions do not.... Continue Reading >>

What’s the difference between a protocol and a class?

When writing protocol-oriented Swift, protocols and classes become fairly similar, but they are never the same.... Continue Reading >>

What’s the difference between a static variable and a class variable?

Both the static and class keywords allow us to attach variables to a class rather than to instances of a class. For example, you might create a Student class with properties such as name and age, then create a static numberOfStudents property that is owned by the Student class itself rather than individual instances.... Continue Reading >>

What’s the difference between Any and AnyObject?

Swift has two anonymous types: Any and AnyObject. They are subtly different, and you will need to use both sooner or later.... Continue Reading >>

What’s the difference between init?() and init()?

It’s the job of a regular Swift initializer to create a fully fledged instance of a new type, however sometimes the data that has been provided is insufficient or incorrect, and creation can’t proceed.... Continue Reading >>

When is it safe to force unwrap optionals?

Some developers force unwrap optionals regularly, and some never do it, but it won’t surprise you to learn that both of those are pretty extreme and will cause you problems.... Continue Reading >>

When to use a set rather than an array

Sets an arrays both store objects of your choosing, but they have four important differences:... Continue Reading >>

Why is immutability important?

Swift developers rely heavily on constants rather than variables, to the point where Xcode even warns you if you create a variable then never change it. There are three main reasons why immutability is important in Swift, and I want to walk through them briefly.... Continue Reading >>

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions, all written for Swift 4.2.

Get the ultimate experience

The Swift Power Pack includes my first six books for one low price, helping you jumpstart a new career in iOS development – check it out!

MASTER SWIFT NOW
Buy Testing Swift Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>