BLACK FRIDAY SALE: Save 50% on all my Swift books and bundles! >>

Xcode UI Testing Cheat Sheet

Article User interface testing is the ultimate integration test, because you’re seeing the app exactly how users do – there’s no special internal knowledge of how your code is structured as we get with unit tests, an... Read more >>

User interface testing with XCTest

Project ...rash your test. Xcode uses the iOS accessibility system to navigate around these user interface tests. This is good because it means any application that is accessibility aware is ready for UI testing, but also because it encourages developers to add accessibility to their apps – which makes the world a better place for everyone. However, it's bad because the accessibility system has to r... Read more >>

Testing Swift + Instabug winners

Article Last week I announced that Instabug were sponsoring the Hacking with Swift knowledge base, and to celebrate they were giving away 50 free copies of my book Testing Swift. All you had to do to win was quote my tweet and answer this question: what's your #1 tip to create a bug-free app? Well, the winners have now been randomly selected, so if you see your ... Read more >>

Build configuration import testing

Article Swift 4.1 implemented SE-0075, which introduced a new canImport condition that lets us check whether a specific module can be imported when our code is compiled. This is particularly important for cro... Read more >>

Target environment testing

Article Swift 4.1 implemented SE-0190, which introduced a new targetEnvironment condition that lets us differentiate between builds that are for physical devices and those that are for a simulated environment... Read more >>

How to refactor your app to add unit tests

Article ...ed a fresh app it wouldn't have been anywhere near as realistic – this way you'll get to work with a real app and see how even badly written code can be drastically improved with Xcode unit testing framework, XCTest. This is part 1 in a series of tutorials on modern app infrastructure: How to refactor your code to add tests How to add CocoaPods to your project How to clean up your code ... Read more >>

How to test your user interface using Xcode

Article User interface testing can be tricky to get right, so in this tutorial we’re going to take an app that has no UI tests and upgrade it so you can see exactly how the process work. The project we’ll be using is a ... Read more >>

What’s new in iOS 12?

Article ...of those, create new folders for each thing you want to identify. Now drag your photos into the appropriate folders. That's it! The training data is used to create your trained model, and the testing data is there just to see how well the trained model does with pictures it hasn't seen before. Warning: Do not put the same image into both training data and test data. As an example, n my exa... Read more >>

How to Become an iOS Developer in 2021

Article ...rom your good place up to being in a fantastic place – you become even more employable, and the range of apps you’re able to build will grow even further. The skills are: UIKit Core Data Testing Software architecture Multithreading As before, I want to explain each of those in more detail so you can understand why I think they are important – and why I consider them extension skil... Read more >>

The 15 Best WWDC Videos of All Time

Article ...ependency injection. Yes, I know for many of us DI is old news, but this session was the first time I had heard “dependency injection” mentioned by Apple – and this is a great primer. 3. Testing Tips & Tricks Year: 2018 Difficulty: Intermediate Watch here Apple developers don’t have the best reputation for taking testing seriously, but if there’s one talk that can make us do b... Read more >>

Interview: Antoine van der Lee

Article ..., and his work at Dutch digital giant WeTransfer. As he’s been active on the Swift scene for some years, and a programmer for much longer, I got in touch with Antoine to ask for his views on testing, mentoring, and the future of Swift… Hacking with Swift: I want to start by asking you about WeTransfer, where you work on the Collect app. This is clearly a huge piece of software – what ... Read more >>

Wrap up

Project This has been the longest technique project by a long way, but I think you've learned a lot about the importance of good unit testing. We also managed to cover some functional programming techniques, discussed private setters, used functions as parameters, and even tried NSCountedSet, so I hope you're happy with the result! ... Read more >>

WWDC20: Wrap up and recommended talks

Article ...pecific – Build document-based apps in SwiftUI was very good, for example. 8: Write Tests to Fail Apart from having a catchy title, this talk was also a really great walkthrough of many core testing best practices, all presented hands-on so you can see the results for yourself. There is always one stand out WWDC talk on testing, and this was it for 2020. 7: Unsafe Swift This is a talk spe... Read more >>

How to implement singletons in Swift the smart way

Article Few design patterns have been scrutinized more closely than singletons, and with good reason: although the idea might seem sensible at first, they all too often become an anti-pattern that hinders testing, gets in the way of concurrent code, and makes your code harder to reason about. However, like so many parts of development, singletons aren’t universally good or bad – they are a gray ar... Read more >>

Tips for Android developers switching to Swift

Example Code ...he Android Emulator is poor. The iOS Simulator is excellent, and you should use it. Be warned, though: the iOS Simulator runs at the full speed of your Mac, so you should always do performance testing on devices. If you're looking for LinearLayout, use UIStackView. If you're looking for Fragments, use UIViewController. If you're looking for Volley, use Alamofire. If you're looking for Java,... Read more >>

How to validate code changes using CircleCI

Article ...aster branch? Or what happens if someone writes code that causes a test to fail? In this final installment of our mini-series on modern app infrastructure, I want to introduce you to automated testing using CircleCI. This is a company that hosts its own macOS servers running various Xcode builds, and can connect directly to your GitHub repository so that every time you make changes they wil... Read more >>

Xcode tips and tricks – part one

Article This is part one of a series on Xcode tips and tricks, this time covering faster testing, generating, interfaces, identifying constraints, and more! Xcode tips and tricks – part one Xcode tips and tricks – part two Xcode tips and tricks – part three Xcode tips and tricks ?... Read more >>

Interview: Carola Nitz

Article ...nd a lot of open source and media-related events – but that’s pretty much the extend of it. HWS: With such a popular app, you must have a pretty strong setup for continuous integration and testing – can you walk us through what you use and why? “As you heard we don’t have many developers, which leads to people directly committing to master with occasional patch reviews.” CN: T... Read more >>

Xcode tips and tricks – part three

Article ...e tips and tricks – part two Xcode tips and tricks – part three Xcode tips and tricks – part four If you have some favorite Xcode tips of your own, let me know on Twitter! 21. Enhanced testing Use parallel testing to make Xcode run multiple tests simultaneously to save time, and use random order testing to make Xcode run tests in a different order each time – a simple way to stop ... Read more >>

Loading our data and splitting up words: filter()

Project ...ll be run again and will fail this time because we haven't written the loading code – XCTest expects allWords to contain 384,001 strings, but it contains 0. This is good, honest! Let's put testing to one side for now and fill in some of our program – we'll be back with the testing soon enough, don't worry. Add this to PlayData.swift: init() { if let path = Bundle.main.path(forRes... Read more >>

How to cancel a task group

Example Code ... group in order to generate a string: func printMessage() async { let result = await withThrowingTaskGroup(of: String.self) { group -> String in group.addTask { return "Testing" } group.addTask { return "Group" } group.addTask { return "Cancellation" } group.cancelAll() var collected =... Read more >>

Xcode 10 wish list: native iOS support, codegen, and more

Article ...ion, and of course a screen that rivals even 15-inch MacBook Pros. If Apple were able to leverage all that power to build a native iOS version of Xcode then it would in theory massively reduce testing time for apps – you could press play and have your app running in only a second or two, because all deployment time is effectively removed. At the same time, there are more than a few compli... Read more >>

Why many developers prefer Swift to Objective-C

Article go. I find it a friendlier language than Go or Rust or even Ruby or JavaScript. I hope what the web server working group produces is a good mix of powerful with approachable. Bruno Scheele: Testing and support for referencing generics or associated types in other classes. Creating the AnyGeneric gets tedious. Joe Fabisevich: Tooling is the biggest downfall. I'm not pushing for ABI stabil... Read more >>

Syncing SwiftData with CloudKit

Project ...ll thing, but it does help smooth over the rest of your code, and making it read-only prevents you trying to change a missing array by accident. Important: Although the simulator is created at testing local SwiftData applications, it's pretty terrible at testing iCloud – you might find your data isn't synchronized correctly, quickly, or even at all. Please use a real device to avoid problems! Read more >>

What’s new in Swift 4.1

Article ...e all three classes just for consistency, but if you preferred you could leave BoardMember as a class and make both SeniorDeveloper and JuniorDeveloper into structs. Build configuration import testing Swift 4.1 implements SE-0075, which introduces a new canImport condition that lets us check whether a specific module can be imported when our code is compiled. This is particularly important ... Read more >>

Get started with Vapor 3 for free

Article ...c server To get started, open a macOS terminal window and run this command: brew install vapor/tap/vapor That will install the Vapor 3 toolbox, which is responsible for creating, building, and testing projects. If you don’t have Homebrew installed on your Mac already, you’ll need to install that first to get the “brew” command: /usr/bin/ruby -e "$(curl -fsSL https://raw.githubuserco... Read more >>

Learn what's new in Swift 4.1 with a playground

Article ...d and apply in your own work: Synthesized Equatable and Hashable Key decoding strategy in Codable Conditional conformances Recursive constraints on associated types Build configuration import testing Target environment testing flatMap() is now (partly) compactMap() The playground is available on GitHub, so I hope you'll try it for yourself: what's new in Swift 4.1? I should add that the t... Read more >>

How to wrap a C library in Swift

Article ...imple as replacing the // .package comment with this: .package(url: "../Cgd", from: "0.0.1"), That tells SPM to copy the dependency from the Cgd directory, then look for the 0.0.1 tag we made. Testing the wrapper The last step is to write some Swift code to take our library for a test drive. Yes, Swift code: Swift has done the hard work of reading the C header file we specified, and has aut... Read more >>

Building a list we can delete from

Project ...ach expense item uniquely by its name, then prints the name out as the list row. We’re going to add two more things to our simple layout before we’re done: the ability to add new items for testing purposes, and the ability to delete items with a swipe. We’re going to let users add their own items soon, but it’s important to check that our list actually works well before we continue.... Read more >>

How to streamline your development with Fastlane

Article ... confusing, so rather than follow Fastlane’s instructions I suggest you follow these instead: Go to the File menu and choose New > Target. Scroll through the list of targets, select iOS UI Testing Bundle, then click Next and Finish. Open Finder and browse to your workspace directory, then press Cmd+2 to activate list view. Look for the file SnapshotHelper.swift in the fastlane directory... Read more >>

SwiftUI tips and tricks

Example Code ...undedBorderTextFieldStyle() rather than .roundedBorder. And this creates a slider with a constant value of 0.5: Slider(value: .constant(0.5)) Note: Constant bindings like this one are just for testing and illustration purposes – you can’t change them at runtime. Presenting test views Another useful tip while you’re prototyping is that you can present any kind of view rather than a ful... Read more >>

Black Friday 2018: Save money on Swift books

Article ...riteKit 50% off Advanced iOS: Volume One 50% off Advanced iOS: Volume Two 50% off Hacking with macOS 50% off Hacking with watchOS Click here for the full sale selection. Note: my latest book, Testing Swift, is not included in the sale because it was only released this month, but I still wanted to offer some sort of discount so click here to save $5 on Testing Swift. NSScreencast Ben Scheir... Read more >>

Unleash the bananas: SpriteKit texture atlases

Project ...because it needs to do quite a few things: Figure out how hard to throw the banana. We accept a velocity parameter, but I'll be dividing that by 10. You can adjust this based on your own play testing. Convert the input angle to radians. Most people don't think in radians, so the input will come in as degrees that we will convert to radians. If somehow there's a banana already, we'll remove... Read more >>

How to perform regression analysis using Create ML

Article ...eate ML did a good job, we’re going to have it split our data into two parts: 80% will be training data that it can use to try to find correlations in our data, and the remaining 20% will be testing data that it can use to evaluate the results of its training. Add this third line of code to your playground now: let (trainingData, testingData) = data.randomSplit(by: 0.8) Now that we have d... Read more >>

How to test iOS networking code the easy way

Article ...east because it’s easy to find yourself in a hole where you’re relying heavily on the way your mock works. In this article I’m going to show you a smart and simple alternative to network testing that lets you get fast, repeatable unit tests without having to subclass URLSession or wrap it in a protocol. Controlling network requests Apple designed URLSession to be highly extensible. Wh... Read more >>

Wrap up

Project ...urn this into a production app, you should ensure that you handle such errors gracefully – just printing something to the log isn’t good enough, because users won’t see it. While you're testing, don't be afraid to reset the iOS simulator as often as you need to in order to clean out old models. If you want to take the app further, here are some suggestions for homework: Fun: Try cre... Read more >>

Creating an NSManagedObject subclass with Xcode

Project ... @NSManaged public var sha: String @NSManaged public var url: String } If you build your code now, it should work again because we have a Commit class again. Before we continue, delete the testing code we had in viewDidLoad() – it’s time for real Core Data work! Time for some useful code Now that we have Core Data objects defined, we can start to write our very first useful Core Da... Read more >>

Save 50% in the Hacking with Swift Black Friday sale

Article ... on Sundays Volume One – pre-order now! 50% off Hacking with iOS – now includes a massive SwiftUI update! 50% off SwiftUI by Example 50% off Pro Swift 50% off Swift Design Patterns 50% off Testing Swift 50% off Server-side Swift: Vapor Edition 50% off Advanced iOS: Volume One 50% off Advanced iOS: Volume Two 50% off Advanced iOS: Volume Three 50% off Hacking with macOS – free SwiftUI ... Read more >>

What you learned

Guide ...Motion to read the accelerometer. Make sure you call startAccelerometerUpdates() before you try to read the accelerometerData property. The #targetEnvironment(simulator) code allowed us to add testing code for using the simulator, while also keeping code to read the accelerometer on devices. Xcode automatically compiles the correct code depending on your build target. And then there’s Co... Read more >>

Setting up

Project ...ave a table view showing how often each word is used. Easy, right? Right. But here's why it's a technique project: while building this app you'll be learning all about XCTest, which is Xcode's testing framework. Although this isn't a tutorial on test-driven development, I will at least walk you through the concepts and apply them with you. Even better, I'll also be introducing you to some f... Read more >>

Creating our first unit test using XCTest

Project ...hoose iOS > Source > Swift File. Click Next, then name it PlayData. We'll be using this to store all the words in the plays. The goal right now is to write just enough code for us to return to testing, so for now just put this text into the file: class PlayData { var allWords = [String]() } That's it: there's a class called PlayData, and we've given it a property called allWords that wi... Read more >>

measure(): How to optimize our slow code and adjust the baseline

Project ...layData object to be created. This is why we can't create it inside the setup() method: we need to create it as part of a measurement in this next test, as you'll see. XCTest makes performance testing extraordinarily easy: you give it a closure to run, and it will execute that code 10 times in a row. You'll then get a report back of how long the call took on average, what the standard devia... Read more >>

What’s new in Swift 5.3?

Article ...latforms and configurations. For example, we might say that we need some specific extra frameworks when compiling for Linux, or that we should build in some debug code when compiling for local testing. It’s worth adding that the “Future Directions” section of SE-0271 mentions the possibility of type-safe access to individual resource files – the ability for SPM to generate specific... Read more >>

24 Quick Xcode Tips

Article ...ow, there’s a good chance you’ll paste in something with incorrect indentation. Xcode can fix this with one shortcut: select the code you want to fix, then press Ctrl+I to reindent it. 22. Testing in-app purchases You can test in-app purchases without App Store Connect. Make a new StoreKit Config File, and add your IAP. Now go to the Product menu, hold down Option, and click Run. From t... Read more >>

Reimagining Hacking with Swift

Article ...’d much rather publish everything for free so that everyone can benefit from that work – I’d love to release all my macOS or watchOS tutorials, for example, or Swift Design Patterns, or Testing Swift, and more, but I hope you can appreciate that just isn’t financially feasible. So, I single-handedly run this huge site and do as much as I can to help folks learn for free or to benef... Read more >>

Hacking with Swift+ turns 1!

Article ..., you’ll automatically gain access to 15 complete books to read online, for as long as your membership remains active. That includes all the big hitters – Pro Swift, Swift Design Patterns, Testing Swift, Swift Coding Challenges, Hacking with macOS, and more, all available for free to read online. Why 18 months? Because by that point you’ve already done a huge amount to support my work... Read more >>

How to document your project with DocC

Article ...omeone for review, or if you want to publish it online. Now, if you’re anything like me you’re probably aware that Python has a built-in web server module that’s really helpful for quick testing – you would run python3 -m http.server in the directory. However, that doesn’t work: the package they generate requires a very specific server configuration. It needs to be served at the w... Read more >>

Disabling user interactivity with allowsHitTesting()

Project SwiftUI has an advanced hit testing algorithm that uses both the frame of a view and often also its contents. For example, if you add a tap gesture to a text view then all parts of the text view are tappable – you can’t tap ... Read more >>

How to install Xcode and create a playground

Project ... that looks and works almost exactly like a real iPhone, iPad, Apple TV, or Apple Watch. It lets you test apps very quickly without having to use a real device. Playgrounds are miniature Swift testing environments that let you type code and see the results immediately. You don’t build real apps with them, but they are great for learning. We’ll be using playgrounds in this introduction. ... Read more >>

Ending the app with allowsHitTesting()

Project SwiftUI lets us disable interactivity for a view by setting allowsHitTesting() to false, so in our project we can use it to disable swiping on any card when the time runs out by checking the value of timeRemaining. Start by adding this modifier to the innermost ZStack ... Read more >>

Making iPhones vibrate with UINotificationFeedbackGenerator

Project ...s of cans and bottles, where people actually preferred Coke. The reason I’m saying this is because we added two haptic notifications to our app that will get played a lot. And while you’re testing out in small doses these haptics probably feel great – you’re making your phone buzz, and it can be really delightful. However, if you’re a serious user of this app then our haptics mig... Read more >>

Building a UIKit user interface programmatically

Project ...nchor), buttonsView.topAnchor.constraint(equalTo: submit.bottomAnchor, constant: 20), buttonsView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -20) Just for testing purposes, give that new view a green background color: buttonsView.backgroundColor = .green We haven’t added the buttons inside that view just yet, but please run the app now – I think yo... Read more >>

Posting notifications to the lock screen

Project ...ionTrigger for the trigger, which lets us specify a custom DateComponents instance. I set it to have an hour component of 9, which means it will trigger the next time 9am comes about. Tip: For testing purposes, I recommend you comment out that trigger code and replace it with the following, which shows the alert five seconds from now: let trigger = UNTimeIntervalNotificationTrigger(timeInte... Read more >>

What’s new in Xcode 14?

Article ...built-in variants. A renewed focus on speed Apple made a big splash about the build performance improvements in Xcode 14, including up to 2x faster linking, 25% faster building, and 30% faster testing, but the one thing that’s most likely to impact big projects is the new Build Timeline feature that shows exactly how Xcode spent its time building your projects. Try it yourself by going to... Read more >>

Now available to pre-order: Swift Against Humanity

Article ...ft Evolution brings back Objective-C! I can literally write anything on these cards and people will buy them, we’re going to be so rich! Wait… are you recording this?” We’ve been busy testing Swift Against Humanity for months now. Even Ed Kermenek, the Swift project lead, took a few hours out of his busy schedule to try it out, and had this to say: “Swift Against Humanity is neat... Read more >>

What’s new in Swift 5.9?

Article ...clock.sleep(for: .seconds(1)) print("Saving…") } } Because that uses any Clock, it’s now possible to use something like ContinuousClock in production but your own DummyClock in testing, where you ignore all sleep() commands to keep your tests running quickly. In older versions of Swift the equivalent code would in theory have been try await clock.sleep(until: Read more >>

How to handle function failure with optionals

Tutorial ...g { throw UserError.networkFailed } if let user = try? getUser(id: 23) { print("User: \(user)") } The getUser() function will always throw a networkFailed error, which is fine for our testing purposes, but we don’t actually care what error was thrown – all we care about is whether the call sent back a user or not. This is where try? helps: it makes getUser() return an optional... Read more >>

How to adopt iOS 11 user interface changes in your app

Article ...content at the forefront. If you’d rather have the search bar visible all the time, add this line: navigationItem.hidesSearchBarWhenScrolling = false At the very least that’s helpful while testing! Rethinking the edges Screen edges have been problematic in iOS for some years: when the notification center was introduced swiping from the top edge conflicted with some apps, when the contro... Read more >>

How to configure your Mac for server-side Swift development

Article ...ating system, there are four options you can take: Use virtualization software such as VMware Fusion or Parallels. This lets you install a full version of Ubuntu Linux locally, for coding and testing. Set up a cloud server using something like Digital Ocean. This costs about $5 per month, or less if you pause the instance when you don’t need it. Use Docker, which is a bit like an invisib... Read more >>

Swift Package Manager gains binary dependencies, resources, and more

Article ...latforms and configurations. For example, we might say that we need some specific extra frameworks when compiling for Linux, or that we should build in some debug code when compiling for local testing. It’s worth adding that the “Future Directions” section of SE-0271 mentions the possibility of type-safe access to individual resource files – the ability for SPM to generate specific... Read more >>

Developers react to iPhone X, the notch, and more

Article ...ntil November to fix all those status bar bugs #iPhoneX— Javi (@Javi) September 12, 2017 Don’t let that lull you into a false sense of security, though – download Xcode 9 now and start testing out your app! More new features: Animoji and wireless charging The iPhone X features some incredibly advanced facial scanning and recognition hardware, backed up by new Metal 2 pipelines for s... Read more >>

Setting up

Project .... Before we start, please configure your project so that it runs only for iPads in landscape mode. Warning: When working with SpriteKit projects, I strongly recommend you use a real device for testing your projects because the iPad simulator is extraordinarily slow for games. If you don’t have a device, please choose the lowest-spec iPad simulator available to you instead, but be prepared... Read more >>

Why many developers still prefer Objective-C to Swift

Article ...tely less shy about adopting it for new features than iOS). I understand why that is the case (ABI stability, etc), but if Apple's not using it for everything I don't see why I need to be beta-testing on their behalf. I lose nothing from waiting until Swift is 'ready', and I gain all the benefits of Objective-C in the meantime. I'm fully of the belief that just because Apple builds somethi... Read more >>

Relationships with SwiftData, SwiftUI, and @Query

Project ...hite) .clipShape(.capsule) } } If you want to see it work with some actual data, you can either create a SwiftUI view to create new Job instances for the selected user, but for testing purposes we can take a little shortcut and add some sample data. First add a property to access the active SwiftData model context: @Environment(\.modelContext) var modelContext And now add a ... Read more >>

5 new Xcode tips and tricks to help you work faster

Article intentionally trying to destroy it / hack it / crash it, then it should be in pretty good shape for the real world. So, I present to you the single most important shortcut you can use while testing your apps in the iOS Simulator: Shift+Cmd+M. This triggers a memory warning: it simulates your app using enough RAM that it caused memory pressure, which forces the system to take emergency ac... Read more >>

Setting up

Project ...?t have a physical iPad to hand, use the lowest-spec iPad simulator rather than something like the 12.9-inch iPad Pro – you'll get much slightly frame rates, making it much more suitable for testing. Read more >>

Penguin, show thyself: SKAction moveBy(x:y:duration:)

Project ...: the penguin moves back down the screen into its hole, then its isVisible property is set to false. We want to trigger this method automatically after a period of time, and, through extensive testing (that is, sitting around playing) I have determined the optimal hide time to be 3.5x popupTime. So, put this code at end of show(): DispatchQueue.main.asyncAfter(deadline: .now() + (hideTime *... Read more >>

Whack to win: SKAction sequences

Project ... you do. If you're using the iOS simulator, bear in mind that it's much hard to move a mouse pointer than it is to use your fingers on a real iPad, so don't adjust the difficulty unless you're testing on a real device! Read more >>

How to disable taps for a view using allowsHitTesting()

Example Code SwiftUI lets us stop a view from receiving any kind of taps using the allowsHitTesting() modifier. If hit testing is disallowed for a view, any taps automatically continue through the view on to whatever is behind it. To demonstrate this, here’s a ZStack containing a transluce... Read more >>

Add sleep(for:) to Clock

Article ...clock.sleep(for: .seconds(1)) print("Saving…") } } Because that uses any Clock, it’s now possible to use something like ContinuousClock in production but your own DummyClock in testing, where you ignore all sleep() commands to keep your tests running quickly. In older versions of Swift the equivalent code would in theory have been try await clock.sleep(until: Read more >>

How to use the coordinator pattern in iOS apps

Article Any view controller can trigger your purchase flow without knowing how it’s done or repeating code. You can add centralized code to handle iPads and other layout variations, or to do A/B testing. But most importantly, you get true view controller isolation: each view controller is responsible only for itself. I have a second article that goes into more detail on common problems peopl... Read more >>

Fixing the keyboard: NotificationCenter

Project ...including showing and hiding, but also orientation, QuickType and more. It might sound like we don't need keyboardWillHideNotification if we have keyboardWillChangeFrameNotification, but in my testing just using keyboardWillChangeFrameNotification isn't enough to catch a hardware keyboard being connected. Now, that's an extremely rare case, but we might as well be sure! To register ourselve... Read more >>

Controlling extension points in protocols

Article ... // check user // check product // perform transaction // update UI } } You might have notice that excludes the // save receipt comment, which means someone testing this code might find that the product is bought and the UI is updated, but silently the receipt is missing – this will cause problems later on. The two-stage process of protocol extensions a... Read more >>

How do you create multi-dimensional arrays?

Example Code ...ray holds strings. It also demonstrates the value type situation that might catch you out: // this is our array of arrays var groups = [[String]]() // we create three simple string arrays for testing var groupA = ["England", "Ireland", "Scotland", "Wales"] var groupB = ["Canada", "Mexico", "United States"] var groupC = ["China", "Japan", "South Korea"] // then add them all to the "groups"... Read more >>

How to find and fix memory leaks using Instruments

Article ...struments to find several display performance issues and monitor memory allocations to detect leaks, which is definitely an improvement. Once again, I hope you’re getting into the flow of re-testing your changes with Instruments regularly. Each time we made a change, we ran it back through Instruments to see whether the results matched what we expected – this is smart practice, and wor... Read more >>

Ready... aim... fire: Timer and follow()

Project ...) createFirework(xMovement: -movementAmount, x: rightEdge, y: bottomEdge) default: break } } You'll notice I made movementAmount into a constant. This is because I was testing various values to find one that worked best, so having it in a constant made it easy to adjust with trial and error. As you can see in the code, each firework is fired from different positions... Read more >>

Making things go bang: SKEmitterNode

Project ...ks() } That's it, your game is done. Obviously you can't shake your laptop to make the iOS Simulator respond, but you can use the keyboard shortcut Ctrl+Cmd+Z to get the same result. If you're testing on your iPad, make sure you give it a good shake in order to trigger the explosions! Read more >>

What is trailing closure syntax?

Example Code ... self.view.backgroundColor = } That's shorter, and avoids the double closing }) code. This functionality is available wherever a closure is the final parameter to a function. For testing purposes, we could write a simple one like this: func greetThenRunClosure(name: String, closure: () -> ()) { print("Hello, \(name)!") closure() } That prints a message, then runs a clo... Read more >>

Setting up

Project ...'s OK because most people don't. Instead, I recommend you install the app "Locate Beacon" on your iPad or iPhone, because that comes with an iBeacon transmitter built in, making it perfect for testing. You also need an iOS device that's compatible with iBeacons, which means iPhone 5 or later, 3rd generation iPad or later, iPad Mini or later, or 5th generation iPod Touch or later. I'm afraid... Read more >>

Enemy or bomb: AVAudioPlayer

Project ...s a reminder, we're going to force the Z position of bombs to be 1, which is higher than the default value of 0. This is so that bombs always appear in front of penguins, because hours of play testing has made it clear to me that it's awful if you don't realize there's a bomb lurking behind something when you swipe it! Creating a bomb also needs to play a fuse sound, but that has its own co... Read more >>

How to use compiler directives to detect the iOS Simulator

Example Code 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. If you want certain code to be run only in the iOS simulator, you should use this: #if targetEnvironment(simulator) // your code #endif Any code between the #if an... Read more >>

Swift 4.2 improves Hashable with a new Hasher struct

Article ...relied on sets and dictionaries having the same order between runs, but if you did then now is the time to update your code. That being said, you can force Swift to use predictable hashing for testing purposes only: set the environment variable SWIFT_DETERMINISTIC_HASHING to 1, and Swift will replace its random hashing seed with a constant value. This will not work in production, but it cou... Read more >>

Tilt to move: CMMotionManager

Project We're going to control this game using the accelerometer that comes as standard on all iPads, but it has a problem: it doesn't come as standard on any Macs, which means we either resign ourselves to testing only on devices or we put in a little hack. This course isn't calling Giving Up with Swift, so we're going to add a hack – in the simulator you'll be able to use touch, and on devices you'll... Read more >>

The ultimate guide to Timer

Article ...eduledTimer(timeInterval: 1.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true) You’ll need an fireTimer() method for it to call, so here’s a simple one just for testing: @objc func fireTimer() { print("Timer fired!") } Note: That needs to use @objc because Timer uses the target/action approach to method calls. Although we’ve requested the timer be trigg... Read more >>

Conference report: WWDC18

Article ...-year opportunity is a regular source of frustration for me. However, I think I did a pretty good job of making the most of it: I spoke to folks from Xcode, Core ML, Natural Language, SiriKit, testing, accessibility, and more. I even (albeit jokingly, I think!) got invited to help out in the Swift lab – tempting! This year Apple made the labs all standing only, much like an Apple Store e... Read more >>

What’s new in Swift 5.0

Article ...rlotte": 5, "William": nil ] let knownAges = people.compactMapValues { $0 } Withdrawn: Counting matching items in a sequence Watch the video This Swift 5.0 feature was withdrawn in beta testing because it was causing performance issues for the type checker. Hopefully it will come back in time for Swift 5.1, perhaps with a new name to avoid problems. SE-0220 introduces a new count(whe... Read more >>

How to write performance tests using measure()

Example Code ...e project, then open your tests file. In my test I’m going to try generating images using a fictional ImageGenerator struct that has a generateImages() method. I’m specifically going to be testing the generateImages() method, which means I’ll create a test instance of ImageGenerator outside the measure() method, like this: func testPerformanceExample() { let generator = ImageGener... Read more >>

Why does Swift have labeled statements?

Article ...?re trying to figure out the correct combination of movements to unlock a safe. We might start by defining an array of all possible movements: let options = ["up", "down", "left", "right"] For testing purposes, here’s the secret combination we’re trying to guess: let secretCombination = ["up", "up", "right"] To find that combination, we need to make arrays containing all possible three-... Read more >>

Sherlock turbocharges your iOS simulator

Article, the amount of time we were wasting. We both work on pretty large apps with a lot of nested screens, and a fairly involved process to onboard a new device, so we were burning a lot of time testing out design tweaks, rebuilding every time and then having to switch between simulators to confirm that the layout worked on all device types. Similarly, we’d often find ourselves working on u... Read more >>

How to test asynchronous functions using expectation()

Example Code ...e second is expectedFulfillmentCount: if you set this to 5 for example, it means fulfill() must be called five times before the time out is reached, which allows you to implement more advanced testing logic. Read more >>

How to do one-time setup for your tests

Example Code ...alled after the invocation of each test method in the class. super.tearDown() } Those are called before and after every test inside your XCTestCase subclass, which allows you to reset your testing environment fully. However, sometimes you prefer to do some setup once and keep that state during all your tests, for example if you need to generate some test data that gets shared in all you... Read more >>

How to render UIViews in 3D using CATransformLayer

Article ...hough! First, here’s a basic viewDidAppear() that sets up the image view: override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) imageView.image = UIImage(named: "TestingSwift") imageView.contentMode = .scaleAspectFit // more code to come } Note: You’ll need to provide your own image, so you should import something into your asset catalog. The next s... Read more >>

Advent of Swiftmas 2018

Article ... Process How to perform regression analysis using Create ML How to update your code to modern Swift How to create a random terrain tile map using SKTileMapNode and GKPerlinNoiseSource Xcode UI Testing Cheat Sheet The complete guide to routing with Vapor 3 How to create a custom gauge control using UIKit How to create a snow scene with Core Animation How to test iOS networking code the easy ... Read more >>

Build a Simon game for watchOS

Article ...ate one of the watchOS simulators, but if you go back to the Product menu and choose Destination you can select whichever one you prefer – personally I prefer using the largest option while testing and the smallest while designing. All being well you should see one color flash when the game begins. If you’d like to double check everything worked, try changing the addToSequence() method... Read more >>

How to measure code coverage in Xcode

Article ...we’re going to look at how it works – specifically why it’s less than perfect as a metric! – then look at how to use it in your own projects. A warning before we start Running code and testing code aren’t the same thing, which makes code coverage an easy metric to game if you’re so inclined. For example, here’s a User struct that can be created with a username and password, an... Read more >>

How to localize your iOS app

Example Code ...lding down the Alt key, then choosing “Run...” Look under the Options tab and you’ll see Application Language is set to System Language by default, but you can change to others there for testing purposes. Localizing text you create in storyboards First, go ahead and give all your UI elements whatever natural text makes sense in your base localization. For example, this might mean givi... Read more >>

The Complete Guide to iOS and Swift Job Interviews

Article ...ether someone would work well in a team environment. Those types of assessments are often optimized for folks who have happened to cram and study the most algorithmic questions, or are good in testing environments. I've never had a situation at work where my manager gave me a project and told me I had 60 minutes to do it or else! I think take home assignments or onsite problem solving work ... Read more >>

How to refactor massive view controllers

Article ...ponsible for our application flow, and mean that none of our view controllers know about the existence of any other view controller. It also makes it easier to make variations, such as for A/B testing or to cater for iPhone/iPad differences. Implementing coordinators in an iOS app takes a little bootstrapping. I’ve already explained how to do it step by step in my article “How to use th... Read more >>

Recording from the microphone with AVAudioRecorder

Project ...ty. We'll be using Apple's AAC format because it gets the most quality for the lowest bitrate. For bitrate we'll use 12,000Hz, which, when combined with the High AAC quality, sounds good in my testing. We'll specify 1 for the number of channels, because we don’t need stereo for these simple recordings. If you set your view controller as the delegate of a recording, you'll be told when rec... Read more >>

Year in review: 2018

Article ...m the Countdown were in the knowledge base. So, to the best of my knowledge I wrote 486 new articles about Swift in 2018. I also wrote three books: Swift Design Patterns, Practical iOS 12, and Testing Swift. Combined, those have 160,000 words, although they aren’t free so I appreciate most folks aren’t able to read them. However, this year I did release the complete text to Hacking with... Read more >>

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.