NEW: Pre-order my Vapor book and learn server-side Swift! >>

Language

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

 

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 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 2.2 introduced a new #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 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 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 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 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 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 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 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 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 4.0 with Xcode 9, and try out Swift development releases alongside.... 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 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 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 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 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 >>

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 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 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 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 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 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?

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 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 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 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 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 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 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 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 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 >>

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.

Go from iOS to macOS the easy way!

If you like Hacking with Swift, you'll love Hacking with macOS – learn to build macOS apps today, using 18 real-world projects!

Click here to visit the Hacking with Swift store >>