UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

That page doesn't exist, but based on searching the site here are some pages that might be what you're looking for…

How to cache data using NSCache

Example Code Here's an easy win for you that will make your apps immediately much better: NSCache is a specialized class that behaves similarly to a mutable dictionary with one major difference: iOS will automatically remove objects from the cache if the device is running low on memory. Helpfully, if the system does encounter memory pressure ... Read more >>

NSAttributedString by example

Article ... most likely to want to use them with UILabel and UITextView, both of which accept attributed strings directly. In this article I'll walk you through examples of what NSAttributedString is capable of: creating strings by hand, adding and enumerating attributes, adding links and images, and more. All these code samples are written to work with a Swi... Read more >>

UIActivityViewController by example

Article ...ng text, URLs, image, and more, and is also able to add our app’s own services alongside the others. In this article I'll walk through some complete examples of using UIActivityViewController, partly so you can see what it’s capable of, and partly also so you have one reference guide to refer back to in the future. Sharing basic content Let’s ... Read more >>

SwiftUI by Example: Now updated for iOS 16

Article This week I published the biggest ever update to SwiftUI by Example, adding lots of new sample code plus 100 new Xcode projects to download. The initial goal was to update the book for iOS 16, but I ended up going back and adding coverage of functionality intr... Read more >>

Learn SwiftUI with SwiftUI By Example

Article Many people are keen to learn SwiftUI in the fastest way possible, which is why I wrote SwiftUI By Example: a comprehensive, free collection of example code that helps you get started with SwiftUI today. Not only does SwiftUI By Example walk you through well over 100 common coding problems and solu... Read more >>

How to render example content using prepareForInterfaceBuilder()

Example Code Whenever you create a custom UIView subclass using @IBDesignable, it’s usually a good idea to provide it with some sample content so it can render meaningfully at design time. For example, here’s a simple ShapeView class that renders a UIBezierPath inside a view, using CAShapeLayer: @IBDesignable class ShapeView: UIView { @IBInspectable var strokeColor: UIColor = UIColor.... Read more >>

UIStackView by example

Project ...UIKit component UIStackView gives us: a flexible, Auto Layout-powered view container that makes it even easier to build complex user interfaces. As an example, lets say you want users to fill in a short form: you have a label saying "Name" then a UITextField to the right of it; beneath that you have another label saying "Address" and a UITextView be... Read more >>

What’s new in Swift 5.7

Article ... deal of consistency clean ups around the any and some keywords. In this article I want to introduce you to the major changes, providing some hands-on examples along the way so you can see for yourself what’s changing. Many of these changes are complex, and many of them are also interlinked. I’ve done my best to break things down into a sensible... Read more >>

Expanding the Swift Knowledge Base

Article I've just added 270 articles to my Swift Knowledge Base, taking it up to 576 tips, techniques, and answers for Swift developers – all updated for the latest version of Xcode and Swift. Click here to browse the knowledge base b... Read more >>

Lightweight same-type requirements for primary associated types

Article SE-0346 adds newer, simpler syntax for referring to protocols that have specific associated types. As an example, if we were writing code to cache different kinds of data in different kinds of ways, we might start like this: protocol Cache { associatedtype Content var items: [Content] { get set ... Read more >>

How to create and use an actor in Swift

Example Code ...ternally. Swift takes care of everything else for us, including ensuring that properties and methods must be accessed safely. Let’s look at a simple example: a URL cache that remembers the data for each URL it downloads. Here’s how that would be created and used: actor URLCache { private var cache = [URL: Data]() func data(for url: URL)... Read more >>

How to combine Core Data and SwiftUI

Project ...ked you to not check the Use Core Data box, because although it gets some of the boring set up code out of the way it also adds a whole bunch of extra example code that is just pointless and just needs to be deleted. So, instead you’re going to learn how to set up Core Data by hand. It takes three steps, starting with us defining the data we want ... Read more >>

What's new in Swift 5.5?

Article ...on handlers are commonly used in Swift code to allow us to send back values after a function returns, but they had tricky syntax as you’ll see. For example, if we wanted to write code that fetched 100,000 weather records from a server, processes them to calculate the average temperature over time, then uploaded the resulting average back to a ser... Read more >>

Build your first app with SwiftUI and SwiftData

Article ... what $person means. When we're using a local property with @State or similar, SwiftUI automatically creates three ways of accessing the property. For example, if we had an integer called age, then: If we read age directly, we can get or set the integer. If we use $age, we access a binding to the data, which is a two-way connection to the data that... Read more >>

Learn essential Swift in one hour

Article ... by using contains(), like this: print(colors.contains("Octarine")) Dictionaries Dictionaries store multiple values according to a key we specify. For example, we could create a dictionary to store information about a person: let employee = [ "name": "Taylor", "job": "Singer" ] To read data from the dictionary, use the same keys you used whe... Read more >>

Fixing the bugs: Running out of memory

Project Now, why does the app crash when you go the detail view controller enough times? There are two answers to this question, one code related and one not. For the second question, I already explained that we’re working with supremely over-sized images here – far larger than we actually need. But there'... Read more >>

Get started with Vapor 3 for free

Article ...ebrew/install/master/install)" Note: installing Homebrew will ask for your password. Now we can go ahead and create a new project for Vapor 3. In this example we’re going to build a simple web chat called WaffleSpot: users can enter a username and a message into a web form, which we’ll then save to an SQLite database. They’ll also be able to r... Read more >>

Sending and receiving Codable data with URLSession and SwiftUI

Project ...ompletes we can immediately assign its data to properties in SwiftUI views, causing our user interface to update. To demonstrate this we can load some example music JSON data from Apple’s iTunes API, and show it all in a SwiftUI List. Apple’s data includes lots of information, but we’re going to whittle it down to just two types: a Result will... Read more >>

One-to-many relationships with Core Data, SwiftUI, and @FetchRequest

Project ...Relationships come in four forms: A one to one relationship means that one object in an entity links to exactly one object in another entity. In our example, this would mean that each type of candy has one country of origin, and each country could make only one type of candy. A one to many relationship means that one object in an entity links to m... Read more >>

What’s new in Swift 5.0

Article ...um cases, a Result type, checking for integer multiples and more. Try it yourself: I created an Xcode Playground showing what's new in Swift 5.0 with examples you can edit. A standard Result type Watch the video SE-0235 introduces a Result type into the standard library, giving us a simpler, clearer way of handling errors in complex code su... Read more >>

What’s new in iOS 12?

Article ...omes through huge improvements to Xcode, but I'll be covering it all here. In this article I'll walk you through the major changes, complete with code examples, so you can try it for yourself. Note: you will need macOS Mojave if you want to use the new Create ML tools. You might also want to read what’s new in Swift 4.2. I also published API diff... Read more >>

The Complete Guide to Optionals in Swift

Article ...ing our way forward to topics that will interest more experienced developers. What are optionals? Optionals represent something that has no value. For example, consider this code: let names = ["Margaret", "Matthew", "Megan"] let position = names.index(of: "Mxyzptlk") That creates an array of names and looks up the position of a name that doesn’t e... Read more >>

How to store ordered data in arrays

Tutorial ...e place, whether that’s the days of the week, a list of students in a class, a city’s population for the last 100 years, or any of countless other examples. In Swift, we do this grouping using an array. Arrays are their own data type just like String, Int, and Double, but rather than hold just one string they can hold zero strings, one string, t... Read more >>

How to move data sources and delegates out of your view controllers

Article ...nt objects in the same view controller to get different behavior at runtime – it’s a huge improvement. In this article I want to walk you through examples of getting common data sources and delegates out of view controllers in a way you should be able to apply to your own projects without much hassle. Before we begin, please use Xcode to create... Read more >>

Swiftoberfest 2019

Article ... whole month. So I thought to myself: what if I could write a 100 Days of SwiftUI article, a new knowledge base article, and an addition to SwiftUI by Example – three articles every day for a month? Could I do that while also speaking at Mobiconf in Poland and Pragma Conference in Italy? More importantly, should I do that? Of course you know the ... Read more >>

How to store and find data in dictionaries

Tutorial ...em, or when you might have duplicate items in there, but very often accessing data by its position in the array can be annoying or even dangerous. For example, here’s an array containing an employee’s details: var employee = ["Taylor Swift", "Singer", "Nashville"] I’ve told you that the data is about an employee, so you might be able to guess ... Read more >>

How to configure Core Data to work with SwiftUI

Example Code ... a pretty good job of getting you towards a working configuration. Specifically, it: Creates an empty YourProjectName.xcdatamodeld model file with an example configuration. Adds a Persistence.swift file that wraps up Core Data neatly in one place. Injects the context into the initial content view’s environment using the managedObjectContext key. ... Read more >>

What’s new in Vapor 3?

Article ...t does cause headaches for developers. A non-blocking architecture means that any operation that takes more than a tiny amount of time to run – for example a network request, a database request, or even rendering templates – is now run asynchronously. That is, your network request code returns immediately even though the work itself has not co... Read more >>

How to Become an iOS Developer in 2021

Article ...r motivating while you’re learning. SwiftUI was built for Swift, using language features to help you avoid problems and get maximum performance. For example, if you change some data on one screen of an app, SwiftUI will automatically make sure that new data is updated anywhere else in your app that uses it – you don’t need to write code to ke... Read more >>

Core Data: Wrap up

Project ...een how it can add, delete, sort, filter, and more, all with relatively simple code. Yes, a few parts are a little murky in Swift – NSPredicate, for example, could do with some refinement, and NSSet is never pleasant to deal with – but with a little work on our behalf this stops being a problem. Perhaps the most important thing about Core Data ... Read more >>

Types of Data

Project ...ow by introducing another important data type, called Int, which is short for "integer." Integers are round numbers like 3, 30, 300, or -16777216. For example: var name: String name = "Tim McGraw" var age: Int age = 25 That declares one variable to be a string and one to be an integer. Note how both String and Int have capital letters at the start... Read more >>

Adding Core Data entity relationships: lightweight vs heavyweight migration

Project It's time to take your Core Data skills up a notch: we're going to add a second entity called Author, and link that entity to our existing Commit entity. This will allow us to attach an author to every commit, ... Read more >>

Loading Core Data objects using NSFetchRequest and NSSortDescriptor

Project ...the cell’s textLabel and detailTextLabel. There are lots of ways to convert dates to and from strings – you already saw ISO8601DateFormatter, for example – but here we’re just going to use the simplest: every Date object has a description property that converts it to a human-readable string. For a change, we’re also going to write a thir... Read more >>

Ensuring Core Data objects are unique using constraints

Project By default Core Data will add any object you want, but this can get messy very quickly, particularly if you know two or more objects don’t make sense at the same time. For example, if you stored details of contacts using their email address, it wouldn’t make sense to have two or three different contacts attached to the same email address. To help resolve this, Core Da... Read more >>

Optimizing Core Data Performance using NSFetchedResultsController

Project ...nly in a different place? Well, no. That new delegate method we just wrote could be called from anywhere: if we delete an object in any other way, for example in the detail view, that method will now automatically get called and the table will update. In short, it means our data is driving our user interface, rather than our user interface trying to... Read more >>

How to pass data between two view controllers

Example Code ...ckwards you can either use a delegate or a block. Passing data forward is used when you want to show some information in a detail view controller. For example, view controller A might contain a list of names that the user can select, and view controller B might show some detailed information on a single name that the user selected. In this case, you... Read more >>

Adding Core Data to our project: NSPersistentContainer

Project A Core Data model defines what your data should look like, but it doesn't actually store the real data anywhere. To make our app work, we need to load that model, create a real working database from it, load that database, then prepare what’s called a “managed object context” ?... Read more >>

How to delete Core Data objects from SwiftUI views

Example Code ...Environment(\.managedObjectContext) var managedObjectContext Next, create a fetch request that reads some data from your managed object context. In my example setup there’s a ProgrammingLanguage entity, so we can read out all items like this: @FetchRequest( sortDescriptors: [ SortDescriptor(\.name) ] ) var languages: FetchedResults... Read more >>

Designing a Core Data model

Project A data model is a description of the data you want Core Data to store, and is a bit like creating a class in Swift: you define entities (like classes) and give them attributes (like properties). But Core Data takes it a step further by allowing you to describe ... Read more >>

How to use @EnvironmentObject to share data between views

Example Code ...ses. Warning: Now that our views rely on an environment object being present, it’s important that you also update your preview code to provide some example settings to use. For example, using something like ScoreView().environmentObject(GameSettings()) for your preview ought to do it. If you need to add multiple objects to the environment, you sh... Read more >>

How to use sets for fast data lookup

Tutorial ...ally get turned into an advantage. First, not storing duplicates is sometimes exactly what you want. There’s a reason I chose actors in the previous example: the Screen Actors Guild requires that all its members have a unique stage name to avoid confusion, which means that duplicates must never be allowed. For example, the actor Michael Keaton (Sp... Read more >>

Summary: Simple data

Tutorial We’ve covered a lot about the basics of data in the previous chapters, so let’s recap: Swift lets us create constants using let, and variables using var. If you don’t intend to change a value, make sure you use let so that Swift can help you avoid mistakes. Swift’s strings contain text, from short strings up to whole novels. They work great with emoji and any world lang... Read more >>

Saving and loading data with UserDefaults

Project ... out when the app is relaunched, which doesn’t make it much use for remembering who we met. We can fix this by making the Prospects initializer able to load data from UserDefaults, then write it back when the data changes. This time our data is stored using a slightly easier format: although the Prospects class uses the @Published property wrapper... Read more >>

Why do copies of a class share their data?

Article ...re reference types, which means they refer to a value somewhere else. For value types, this is easy enough to understand that it’s self-evident. For example, look at this code: var message = "Welcome" var greeting = message greeting = "Hello" When that code runs, message will still be set to “Welcome”, but greeting will be set to “Hello”. ... Read more >>

How to add a search bar to filter your data

Example Code ...= "" var body: some View { NavigationStack { Text("Searching for \(searchText)") .navigationTitle("Searchable Example") } .searchable(text: $searchText) } } Tip: By attaching searchable() to NavigationStack or NavigationSplitView, we’re leaving it to the system to decide wh... Read more >>

Hiding and grouping accessibility data

Project ...ews from the accessibility system. Grouping several views as one. All of these are simple changes to make, but they result in a big improvement. For example, we can tell SwiftUI that a particular image is just there to make the UI look better by using Image(decorative:). Whether it’s a simple bullet point or an animation of your app’s mascot c... Read more >>

What’s new in Swift 5.9?

Article ...g in Swift 5.9, making yet another mammoth release. In this article I’ll walk you through the most important changes in this release, providing code examples and explanations so you can try it all yourself. You’ll need the latest Swift 5.9 toolchain installed in Xcode 14, or the Xcode 15 beta. if and switch expressions SE-0380 adds the ability f... Read more >>

Writing data to the documents directory

Project Previously we looked at how to read and write data to UserDefaults, which works great for user settings or small amounts of JSON, and we also looked at SwiftData, which is a great choice for times when you want relationships bet... Read more >>

How to make a Core Data attribute unique using constraints

Project After such a huge amount of work getting Core Data up and running, you'll probably run your app a few times to enjoy it all working. But it's not perfect, I'm afraid: first, you'll see GitHub commits get duplicated each time the app runs, and second you'll notice that tapping on a commit doesn’t do anythi... Read more >>

How to store NSCoding data using Codable

Example Code ...ide Codable, which is helpful because many Apple types such as UIColor and UIImage conform to NSCoding but not Codable. Here’s a simple struct as an example: struct Person { var name: String var favoriteColor: UIColor } That stores one Codable type (the string) and one NSCoding type (the color), and we’re going to make them all work thro... Read more >>

Vapor + Leaf templating cheat sheet

Article ...this command: vapor new LeafTest --template=twostraws/vapor-clean cd LeafTest That creates a new Vapor project called LeafTest, asking it to clone my example project from GitHub. Don’t worry: that example project contains the absolute least amount of code required to set up a Vapor server. Adding Leaf to your project Adding Leaf takes two steps. ... Read more >>

Sharing data across tabs using @Environment

Project ...iew that contains three instances of ProspectsView, and we want all three of those to work as different views on the same shared data. This is a great example of where SwiftUI’s environment makes sense: we can define a class that stores one prospect, then place an array of those prospects into the environment so all our views can read it if needed... Read more >>

How to filter Core Data fetch requests using a predicate

Example Code ...instances of NSPredicate that you would use without SwiftUI, which means you can use the same variety of string operations you would normally use. For example, using the example data from my setup instructions we could create a predicate like this: NSPredicate(format: "name == %@", "Python") That will show details about Python, while ignoring other ... Read more >>

How to create a Core Data fetch request using @FetchRequest

Example Code ...requires two pieces of information: the entity you want to query, and a sort descriptor that determines the order in which results are returned. In my example setup we created a ProgrammingLanguages entity that had name and creator attributes, so we could create a fetch request for it like this: @FetchRequest(sortDescriptors: [SortDescriptor(\.name)... Read more >>

The Ultimate Guide to WKWebView

Article ... URL to some HTML file that you know is in your bundle, along with another URL that stores any other files you want to allow the web view to read. For example, if you wanted to load a file called "help.html" you might use code like this: if let url = Bundle.main.url(forResource: "help", withExtension: "html") { webView.loadFileURL(url, allowingR... Read more >>

How to add Core Data objects from SwiftUI views

Example Code ...agedObjectContext Next, go ahead and create an instance of your Core Data entity class wherever you need, referencing that managedObjectContext. In my example setup, we have a ProgrammingLanguage entity with name and creator properties, so we could create one of those inside a SwiftUI button action like this: Button("Insert example language") { ... Read more >>

How to support low data mode networking using allowsConstrainedNetworkAccess

Example Code ...he user’s low data mode setting, but you can change that by setting the allowsConstrainedNetworkAccess property to false for a given URLRequest. For example: var request = URLRequest(url: someURL) request.allowsConstrainedNetworkAccess = false When that request executes iOS will immediately return an error if low data mode is enabled, which might ... Read more >>

UICollectionView data sources

Project We’ve now modified the user interface so that it considers ViewController to be a collection view controller, but we haven’t implemented any of the data source methods to make that work. This works just like table views, so we get questions like “how many items are ther... Read more >>

Important: Do not use an actor for your SwiftUI data models

Example Code ...n the main actor, which means when we make a class conform to ObservableObject we’re agreeing that all our work will happen on the main actor. As an example, any time we modify an @Published property that must happen on the main actor, otherwise we’ll be asking for changes to be made somewhere that isn’t allowed. Now think about what would ha... Read more >>

Downloading data from Wikipedia

Project To make this whole app more useful, we’re going to modify our EditView screen so that it shows interesting places. After all, if visiting London is on your bucket list, you’d probably want some su... Read more >>

Super-powered string interpolation in Swift 5.0

Article ...the way string interpolation handles parameters. You see, appendInterpolation() so that we can handle various different data types in unique ways. For example, we could write some code to handle Twitter handles, looking specifically for the twitter parameter name like this: mutating func appendInterpolation(twitter: String) { appendLiteral("@\(t... Read more >>

How to calculate the SHA hash of a String or Data instance

Example Code ...ld!" let inputData = Data(inputString.utf8) You then call the hash(data:) method of whichever kind of hash you want: SHA-256, SHA-384, or SHA-512. For example, if you wanted to calculate the SHA-256 hash of your data you’d use this: let hashed = SHA256.hash(data: inputData) Finally, you can print out the textual representation of the hash – wha... Read more >>

How does Swift let us compare many types of data?

Article Swift lets us compare many kinds of values out of the box, which means we can check a variety of values for equality and comparison. For example, if we had values such as these: let firstName = "Paul" let secondName = "Sophie" let firstAge = 40 let secondAge = 10 Then we could compare them in various ways: print(firstName == secondNam... Read more >>

Summary: Complex data

Tutorial We’ve gone beyond simple data types now, and started looking at ways to group them together and even create our own using enums. So, let’s recap: Arrays let us store lots of values in one place, then read them out using integer indices. Arrays must always be special... Read more >>

How to handle missing data with optionals

Tutorial Swift likes to be predictable, which means as much as possible it encourages us to write code that is safe and will work the way we expect. You’ve already met throwing functions, but Swift has another important... Read more >>

Introduction to using Core Data with SwiftUI

Example Code As two massive pieces of Apple’s software platform, it won’t surprise you to learn that Core Data and SwiftUI have been written to work well together: we get property wrappers, environment support, and more, all to make sure we can integrate Core Data into our SwiftUI apps ... Read more >>

All SwiftUI property wrappers explained and compared

Example Code ...ns, and even local instances of structs. In comparison, @Binding is used for simple data that you want to change, but is not owned by your view. As an example, think of how the built-in Toggle switch works: it needs to move between on and off states, but it doesn’t want to store that value itself so instead it has a binding to some external value ... Read more >>

How to compress and decompress data

Example Code Apple gives us dedicated API for compressing binary data, although annoyingly it exists on NSData without being bridged neatly to Swift’s native Data type. Fortunately, that conversion is trivial, so this functionality isn’t hard to use. Here’s how to use it: do { let compressedData = try (yourData as NSData).compre... Read more >>

Encoding and decoding data using Codable

Article We know value types are great, but we also know they interact terribly with Objective-C APIs such as NSCoding – you either need to write a shim layer or give in and use classes, both of which are unpleasant. Worse, even if you give in and switch to classes, you still need to write your encoding and decoding methods by hand, wh... Read more >>

Designing a simple watchOS app to receive data

Project So far we have a fully working iOS app that shows cards players can flip over, has a cheat in place for 3D Touch users so you can always guess correctly, and communication happening from iOS to watchOS. The next step is to write a simple watchOS app that is able to receive that data and make the device buz... Read more >>

Working with hierarchical Codable data

Project The Codable protocol makes it trivial to decode flat data: if you’re decoding a single instance of a type, or an array or dictionary of those instances, then things Just Work. However, in this project we’re goin... Read more >>

Navigating to different data types using NavigationPath

Project ...that's being shown, because here things are straightforward: just add navigationDestination() multiple times, once for each type of data you want. For example, we could show five numbers and five strings and navigate to them differently: NavigationStack { List { ForEach(0.. Read more >>

Loading a specific kind of Codable data

Project ...e file can’t be found, loaded, or decoded the app will crash. As before, though, this will never actually happen unless you’ve made a mistake, for example if you forgot to copy the JSON file into your project. Now, you might wonder why we used an extension here rather than a method, but the reason is about to become clear as we load that JSON in... Read more >>

How to use Codable to load and save custom data types

Example Code ... want a custom implementation, just making your data type conform to Codable is all it takes to allow it to be saved to property list XML or JSON. For example, here’s a custom struct that conforms to Codable, along with a few instances of it: struct Language: Codable { var name: String var version: Int } let swift = Language(name: "Swift"... Read more >>

Why many developers prefer Swift to Objective-C

Article ...age I sometimes still encounter in the work setting and in useful Stack Overflow answers. Objective-C's positive influence on Swift is evident in, for example, named parameters, reference counting, and single inheritance. Joachim Bondo: It’s frightening how quickly you loose the touch! I never had problems with the square brackets, but it’s sudd... Read more >>

Using generics to load any kind of Codable data

Project ... Sadly, Apollo 1 never launched because a launch rehearsal cabin fire destroyed the command module and killed the crew. Let’s start converting that to code. Crew roles need to be represented as their own struct, storing the name string and role string. So, create a new Swift file called Mission.swift and give it this code: struct CrewRole: Codabl... Read more >>

How to delete a Core Data object

Project Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or ... Read more >>

How to limit access to internal data using access control

Tutorial By default, Swift’s structs let us access their properties and methods freely, but often that isn’t what you want – sometimes you want to hide some data from external access. For example, maybe you have some logic you need to apply before touching your properties, or maybe you know that some methods need to be called in a certain way or order, and so shouldn’t be touched ext... Read more >>

How to build your first SwiftUI app with Swift Playgrounds

Article ...ifiers. There are lots of these built right in to SwiftUI, and you’ll often find yourself using several at once to get exactly the right effect. For example, try changing your text to include these modifiers below: Text("Hello, world!") .font(.largeTitle) .foregroundColor(.blue) That will give the text a large font and a blue color. Yo... Read more >>

Core Data: Introduction

Project ...ile. Failing that, restart Xcode! All set? Let’s go! Tip: Sometimes you’ll see a heading titled “Want to go further?” This contains some bonus examples that help take your knowledge further, but you don’t need to follow here unless you want to – think of it as extra credit. Read more >>

Storing our data with SwiftData

Project Lots of apps are great candidates for SwiftData, and most of the time it takes surprisingly little work to get it all set up. In our app we have a TabView that contains three instances of ProspectsView, and we want all three of those to work as different views on the same shared data. In SwiftData terms... Read more >>

Loading our data and splitting up words: filter()

Project ...hat Swift code executes quickly, but it's also quick to write. So, there are a few shortcuts it offers to help reduce that long code down in size. For example, all that (testString: String) -> Bool definition isn't really needed: Swift can see that filter() wants a closure that accepts a string and returns true or false, so we don't need to repeat o... Read more >>

15 tips to optimize your SpriteKit game

Article ...raw, which is extremely inefficient. So, create multiple texture atlases to fit your actual content: all the animations for a player in one atlas, for example, and all the sprites for a particular world in another. 2. Preload textures as needed It shouldn’t surprise you when I say that there is a performance cost to loading textures from your app ... Read more >>

10 Quick Swift Tips

Article ...tures, and quirks to take advantage of if you know they exist. In this article I want to walk you through ten of them quickly, including hands-on code examples so you can try them immediately. 1. Existentials of classes and protocols An “existential type” allows us to say what kind of functionality we want a type to have rather than requesting s... Read more >>

How to access a Core Data managed object context from a SwiftUI view

Example Code If you followed my Core Data and SwiftUI set up instructions, you’ve already injected your managed object context into the SwiftUI environment. If not, make sure you add this code to your scene delegate: ContentView() .environment(\.managedObjectContext, yourCoreDataContext) That passes our view context directl... Read more >>

How ScrollView lets us work with scrolling data

Project ... When we place views inside scroll views, they automatically figure out the size of that content so users can scroll from one edge to the other. As an example, we could create a scrolling list of 100 text views like this: ScrollView { VStack(spacing: 10) { ForEach(0.. Read more >>

How to let the user paste data into your app

Example Code New in iOS 16 SwiftUI has a dedicated PasteButton view that lets us receive any kind of data that conforms to the Transferable protocol, such as String and Data. For example, we could let the user type into a text field, or add a PasteButton to update the text directly: struct ContentView: View { @State private var username = "@twostraws" var body: some V... Read more >>

How to use Core Motion to read accelerometer data

Example Code ...tartAccelerometerUpdates() Finally, read the accelerometer data as often as you want. It's optional, though, so make sure you unwrap it carefully. For example, if you want to change the gravity of a SpriteKit physics world so that tipping your device makes things roll around, you'd look for something like this in your update() method: if let acceler... Read more >>

8 Common SwiftUI Mistakes - and how to fix them

Article ...??s also sometimes a matter of slipping back into old habits, particular if you’ve come from UIKit or other user interface frameworks. As a starting example, how might you fill the screen with a red rectangle? You might write this: Rectangle() .fill(Color.red) And honestly that works great – it gets the exact result you want. But half that ... Read more >>

Build a unit converter for watchOS

Article ...icked out the most important. So, this property needs to store the human-readable name of the conversions – “Distance” or “Temperature”, for example – along with an array of the various measurements inside each conversion group, all of which descend from the Dimension class. You might think that could be represented using a dictionary li... Read more >>

What’s new in Swift 4.2

Article ...introduces raw strings, count(where:), isMultiple(of:), and more. Try it yourself: I created an Xcode Playground showing what's new in Swift 4.2 with examples you can edit. Derived collections of enum cases SE-0194 introduces a new CaseIterable protocol that automatically generates an array property of all cases in an enum. Prior to Swift 4.2 thi... Read more >>

How to find and fix slow code using Instruments

Article ...nstruments: time profiler and system trace. You don’t need to have completed the two previous parts of this tutorial, but you do need to download my example Xcode project from GitHub. I should repeat the large and important warning… Warning: That project is specifically written to be bad – please don’t use it as a learning exercise, other t... Read more >>

How to use reflection to inspect type data

Example Code ...aylor, like this: var mirror = Mirror(reflecting: taylor) That mirror isn’t a copy of taylor, a reflection of it – something you can inspect. For example, you can loop over all the properties inside taylor and print out their names and values like this: for case let (label?, value) in mirror.children { print (label, value) } Read more >>

The complete guide to routing with Vapor 3

Article ... block of any web application, so it won’t surprise you to learn it can do a lot depending on your needs. In this article we’re going to set up an example web project using Vapor, then experiment with various ways of handling routes. We’re going to start off with the basics for folks who haven’t tried Vapor before, but quickly ramp up to mor... Read more >>

How to refactor your app to add unit tests

Article ...specifically for this tutorial series, and contains mistakes and problems that we’ll be examining over this tutorial series. If you’re looking for example code to learn from, this is the wrong place. To get started, download the project from GitHub here. The app is designed to store and display famous quotes, and I recommend you give it a quick ... Read more >>

The Complete Guide to SF Symbols

Article ...IKit you need to activate these by name – e.g. “bell.slash” – but in SwiftUI there’s a symbolVariant() modifier that makes this easier. For example, this renders a bell icon with a slash through it: Image(systemName: "bell") .symbolVariant(.slash) And this surrounds the bell with a square: Image(systemName: "bell") .symbolVariant(... Read more >>

A new Set data structure

Article ...larly to NSSet except with value semantics. Sets work similarly to arrays except they are not ordered and do not store any element more than once. For example: var starships = Set() starships.insert("Serenity") starships.insert("Enterprise") starships.insert("Executor") starships.insert("Serenity") starships.insert("Serenity") Even though that code ... Read more >>

Handling missing data

Tutorial ...ut it might have no value at all – it might literally be missing, which is nil in Swift. To make a type optional, add a question mark after it. For example, we can make an optional integer like this: var age: Int? = nil That doesn’t hold any number – it holds nothing. But if we later learn that age, we can use it: age = 38 Read more >>

How to convert a String to Data

Example Code 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: let data = Data(someString.utf8) Read more >>

How to convert Data to a String

Example Code 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: let str = String(decoding: data, as: UTF8.self) If the Data instance can’t be converted to a UTF-8 string, you’ll get... Read more >>

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.