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

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

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

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

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

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

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

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

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

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

Shipping a visionOS app for launch

Article ...nsure your text is clear on the glass backgrounds. I just finished a day-long workshop specifically on visionOS – if you're a Hacking with Swift+ subscriber you can rewatch it all for free. Testing on a real device at Apple's Vision Pro Labs I wanted to build an app that would only be possible on visionOS, which brought a rather significant drawback: I actually needed to test the thing o... 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 ...es 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 >>

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

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

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

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

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

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

How to create a random terrain tile map using SKTileMapNode and GKPerlinNoiseSource

Example Code ...e a nice, seamless map, and if we place both the layers inside a single SKNode we can move the map easily. Tip: You can add the following code to your current game project if you want, but for testing purposes you should probably create a new SpriteKit project as a sandbox. First please add this property to your game scene: let map = SKNode() That will contain both the sand tiles and the gr... Read more >>

How to use raw strings in Swift 5

Article ... code review and validation. Is already escaped. Escaped material should not be pre-interpreted by the compiler. Requires easy transport between source and code in both directions, whether for testing or just updating source. The first two are the ones that are most likely to affect you: adding escaping to strings that already have escaping usually makes code much harder to read. As an exa... Read more >>

How to add advanced text styling using AttributedString

Example Code ...k. There are a handful attributes we can customize, including underline pattern and color: struct ContentView: View { var message: AttributedString { var result = AttributedString("Testing 1 2 3!") result.font = .largeTitle result.foregroundColor = .white result.backgroundColor = .blue result.underlineStyle = Text.LineStyle(pattern: .solid, color:... Read more >>

Working with CloudKit records: CKRecord.Reference, fetch(withRecordID:), and save()

Project ...une from Star Wars," you might be tempted to think "ah, that means our whistle should have an array of strings attached to its record." If you try that, it'll work, and it'll work great – in testing. But when it comes to shipping apps, this approach hits a core problem: conflicts. A conflict occurs when CloudKit receives two sets of different information, and it's something that record ar... Read more >>

Advanced coordinators in iOS

Article ...thing else. Using protocols is really useful when working in large apps where you want much more flexibility, because you can add extra protocols freely, swap in different coordinators for A/B testing, and more. Another option is to remove the concrete coordinator type and remove protocols and use a closure instead. This works well when you have only one or two actions being triggered by a ... Read more >>

Xcode tips and tricks – part four

Article This is part four of a series on Xcode tips and tricks, this time covering testing, debugging, colors, and more! Xcode tips and tricks – part one Xcode tips and tricks – part two Xcode tips and tricks – part three Xcode tips and tricks – part four If you have some... Read more >>

Xcode 12 wish list: SwiftUI, iPadOS, and more

Article ...utorial platform seems to herald a shift in their focus that must surely reflect experience from Everyone Can Code. This new approach is focused on structured teaching, real-world results, and testing – the way each step ends with a short quiz is simple and smart, and opens up a huge range of gamification options in coming years. My Unwrap app for learning Swift lets you earn badges for ... Read more >>

Setting up

Project ...ift project. The GitHub API is simple, fast, and outputs JSON, but most importantly it's public. Be warned, though: you get to make only 60 requests an hour without an API key, so while you're testing your app make sure you don't refresh too often! If you weren't sure, a "Git commit" is a set of changes a developer made to source code that is stored in a source control repository. For examp... 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 >>

Dynamically filtering @FetchRequest with SwiftUI

Project ...w that will host our information. Like I said, this is also going to have two buttons that lets us change the way the view is filtered, and we’re going to have an extra button to insert some testing data so you can see how it works. First, add two properties to your ContentView struct so that we have a managed object context we can save objects to, and some state we can use as a filter: @... 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 >>

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

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

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

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

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 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: clock.now.advan... 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 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 >>

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

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

Flashzilla: Wrap up

Project This was another big project, but also another one where we covered some really great techniques like gestures, hit testing, timers, and more. When these features work together we can do remarkable things in our apps, providing an experience to users that is seamless and delightful. You also saw once again the impo... 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 >>

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

5 new Xcode tips and tricks to help you work faster

Article ...is 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 >>

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: clock.now.advan... Read more >>

Sharing an image using ShareLink

Project ...t means changing the method to this: @MainActor func setFilter(_ filter: CIFilter) { Now Swift will ensure that code always runs on the main actor, and the compile error will go away. Tip: For testing purposes, you should perhaps change the review condition from 20 down to 5 or so, just to make sure your code works the way you expect! That final step completes our app, so go ahead and run i... Read more >>

How to use the coordinator pattern in iOS apps

Article ...it. 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 >>

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

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 = UIColor.red } 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 >>

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

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.