
Explore the Swift 4 cookbook's organized sections and learn iOS fixes—from particle emitters in a sprite kid game to loading data with the quotable protocol, and using accelerometer and sound.
Create a multi-dimensional array by turning a string array into an array of arrays in Swift, and understand how value types keep nested copies independent.
Discover how NSCountedSet efficiently counts objects, storing unique items like a set while tracking how many times each item is added or removed.
Learn how to enumerate items in an array using the enumerated method, iterating each item with its position and printing results like found apples at position zero.
Learn how to locate an element in an array with the index of method, handle its optional result safely using if let, and avoid crashes when the element is absent.
Join an array of strings into a single string using Swift's join method with a comma separator, and view the result in the Xcode log.
Use fast enumeration to loop through an array in Swift, printing each item to the Xcode console, while reading items into a constant named item that should not be modified.
Learn how to loop through an array in reverse using the reversed method, compare reverse.enumerated versus enumerated.reversed, and see the reversed output printed to the console.
Explore how to shuffle an array on iOS 8 and below using a shuffle extension and the fisher gates shuffle algorithm, with example code and practical tips for game play.
Shuffle arrays in Swift using GameplayKit with a simple one-liner. Create an array of lottery balls and pick six random numbers with the built-in random number generator for guaranteed randomness.
Learn how to sort arrays in Swift using sort for in-place sorting and sorted to return a new array, including trailing closures for sorting by a property in custom structs.
Learn how to check whether an array contains a value using the contains method, which returns true or false; the example shows apples printed to the console.
Learn to add a border to a UIView via its underlying layer, using a ten-point black border with the color’s cgColor, and optionally rounding the corners.
Learn to create keyframe animations with CAKeyFrameAnimation, exploring key path, values, key times, and additive properties to produce down-and-back and left-and-right shake effects.
Create smooth red to black gradients with a four-line CAGradientLayer by supplying a colors array and a locations array using CGColor values, and adjust startPoint and endPoint to change direction.
Explore how CAShapeLayer enables hardware-accelerated drawing of 2-D shapes, with fill and stroke colors, line caps, and patterns, using a UIBezierPath rounded rectangle colored red.
Learn to emit particles in iOS apps with CAEmitterLayer by configuring a middle layer object, emitter cells, textures, and birth rate to create colorful, spinning confetti effects.
round the corners of view subclasses by setting the corner radius on the underlying layer, and enable clipped bounds to create corners when the radius equals half the view's size.
Implement two functions to compute the distance and the distance squared between two cgpoints using the pythagoras theorem; use the squared version for fast radius checks, such as tapping within ten points.
Compute the Manhattan distance between two CGPoints on a grid with a dedicated function. Run the code to reveal the distance between the blue and red points.
Use the equalTo method to compare two CGRects by their x, y, width, and height values, which takes two rects and returns true if they are the same.
Core graphics draws circles and ellipses with minimal setup; the example shows a red-filled circle with a green border, drawn half inside and half outside the path.
Draw a square or rectangle with core graphics addRect by setting up a context and colors, producing a red square with a green border.
Learn to draw a text string using core graphics with Swift's built-in draw with attributes at a position and size, via a complete reusable code snippet.
Draw lines in core graphics with move(to:) and addLine(to:), setting up a context and color to render a triangle. Rotate the context to create dynamic effects on iPhone image view.
Learn how to extract the scale component from a CGAffineTransform, even after rotation or translation, with practical Swift code from the iOS quick fixes cookbook.
Extract the rotation value from a CGAffineTransform that combines scale, translation, and rotation, using the code shown to identify the rotation value.
Discover how to extract the translation from a CGAffineTransform with a simple function that takes a transform and returns the translation point.
Render a pdf to an image using iOS built‑in drawing APIs, handling document size, background color, and orientation, via a pre-made method that returns a rendered image or nil.
Leverage core graphics blend modes to draw UIImage differently by blending two images—normal and luminosity—creating a dog and owl composite, with options like multiply and rainbow effect using six stripes.
Apply rectangular physics to a red SKSpriteNode to make it fall, bounce, and rotate in the scene. Create circular physics with a circle radius to simulate a dropping ball.
Enable pixel-perfect physics for an SKSpriteNode with a single line of code using alpha values to define collisions, but note this is slower than rectangle or circle collisions.
Learn how to change between scenes with presentScene, applying move in from the right or doorway transitions with configurable durations to create smooth scene switches.
Learn to recolor SKSpriteNode sprites dynamically with colorBlendFactor, enabling multiple colored sprites with zero performance impact and flashes like turning white when hit, then back to red in three seconds.
Explore creating 3d audio with SKAudioNode by enabling the positional property and applying left-right panning, with a sample that moves the audio node back and forth.
Create a SpriteKit texture atlas in Xcode by using an asset atlas folder (.atlas) to store multiple images in one file, enabling faster loading and handling placement and orientation.
Use SKShapeNode to draw arbitrary shapes, including circles and rounded rectangles, with fill, stroke, and glow options; see a rounded rectangle example with red fill and blue border.
Learn to emit particles with SKEmitterNode using Xcode's built-in visual editor to create realistic smoke, fire, and snow, then customize templates, names, positions, and designs.
Identify touch location with a single line of code using the location(in:) method, then trigger touches began to compute and print x and y coordinates relative to any node.
Import game play kit and generate random numbers with GKRandomSource, producing values from roughly -2 billion to 2 billion, and use the upper-bound inclusive variant for 0 to 10.
Explore how to use GameplayKit's GKRandomDistribution to generate random numbers for virtual dice, including six- and twenty-sided dice, by importing GameplayKit and using a range constructor.
Run multiple sprite kit actions simultaneously with action groups, forming action for sequences waiting for group actions to finish; shrink a spaceship to 10% while fading out in four seconds.
Learn to run SKActions in parallel with groups, then place the group in a sequence to ensure completion; a ship shrinks to 10% while fading over four seconds.
Learn to stop an SKPhysicsBody from responding to physics by toggling its dynamic property, preventing movement while preserving collision behavior in a pixel-perfect enemy mine example.
Use the label node to draw text in Spryte kid games, create a score label with text 'score 0', and update it via score property observer when the score changes.
Explain why ceil, floor, and round produce type-matching results in Swift, and show how to cast their return value to an integer when an int is required.
Identify the property without an initial value and provide a default or create a custom init; override the view controller initializer in storyboards and initialize all properties before super.init.
Use the guard keyword in Swift to enforce early returns, ensure the name property is set, bail out on nil, and safely unwrap before proceeding.
Learn how Swift 2.2's pound if build configuration lets you compile code only if a specific Swift version is detected, aiding libraries that support multiple versions.
Learn to compare two tuples in Swift 2.2 using the comparison operator for up to six elements, and beware that tuple labels are not evaluated during comparison.
Compare the float and CGFloat types, understanding how their precision differs across devices, and convert a Swift float to a CGFloat using the Core Graphics constructor.
Convert a float to an int using the integer constructor. This operation rounds downward, as the example shows 10 rather than 11.
Learn how to convert between strings and doubles using string counterparts, since Swift strings lack a built-in double conversion.
Learn how to convert a string to a float in Swift by using a string as an intermediate, taking advantage of built-in helpers.
Convert an integer hidden in a string by using the integers constructor, and apply the same approach to convert from string to other data types like float and double.
Explore converting a Swift string to NSString with a simple typecast, and highlight the ongoing interoperability between Swift strings and NSString.
Learn how to convert integers to floats in Swift without extra work, using the float datatype, in the Swift 4 cookbook.
Master Swift string interpellation to convert data types, including integers, to a string in one line. Use the string constructor as the more common alternative.
Swift 4 introduces a simple way to convert any NSRange into a Swift string range with a single line of code.
Drag in Objective-C code to your Swift project and configure an Objective-C bridging header to enable Swift to work with Objective-C code, adding the necessary import lines.
Learn how to create multiline string literals in swift using triple quotes, so strings can span multiple lines with embedded variables and line breaks for clearer code.
Discover how the defer keyword schedules code to run when exiting the current scope, ensuring cleanup like closing files happens reliably even with returns or errors.
Use the max function twice: first on the first two numbers, then on the third number and the result of the first call.
Find the maximum of two numbers using the max function for integers, and apply it to floats when both inputs are floats to avoid datatype mixing.
Find the minimum of three numbers by applying the min function twice. The function accepts integers or floating point numbers, but it cannot mix types.
Learn how to find the minimum of two numbers in Swift 4, ensuring both integers or both floating point types, not mixed, with example code and using the main function.
Understand how Swift 4 updates objective-c interoperability and fix selector errors by using @objc on individual methods or @objc members on a class, including IB action and protocol methods.
Learn to force a crash with assert() for debugging, using a condition and a message, with release builds ignoring checks to avoid performance impact.
Install and switch between multiple swift toolchain snapshots to run swift beta releases inside Xcode, enabling swift 4.0 with Xcode 9 and betas on macOS or Linux.
Write text to the echo debug console in Swift using the print function, demonstrating how to pass multiple parameters so they print together.
Learn how to safely unwrap optionals in Swift using if let syntax, ensuring code only runs when the optional has a value.
Explore how Codable enables loading and saving custom data types by conforming to the Codable protocol, encoding to JSON automatically, and decoding back with type inference.
Learn to use compiler directives to run code only in the simulator and provide device-specific alternatives with #if and #else, ensuring zero performance impact during testing.
Discover how Swift's try-catch handles errors with do, try, and catch, and compare force try and optional try patterns using a file-loading example.
Master using #available to guard code for specific iOS versions and mark functions or classes with availability attributes for those releases.
Switch from Android to Swift by following tutorials like hacking with Swift, mastering iOS simulator versus device testing, and learning Auto Layout and size classes for iPhone and iPad apps.
Use stride to loop a numeric range with a custom increment and inclusive or exclusive upper bounds. See examples counting from 0 to 10 and 0.1 to 0.5.
Learn how lazy variables in Swift enable calculation of work, demonstrated with a person struct featuring an age property and a Fibonacci age property that computes only when requested.
Discover how property observers in Swift attach code to value changes, such as updating a score label or printing a message when a variable changes.
Explore swift 1.2 changes that simplify optional handling with if let, remove the pyramid of doom, add optional and forced downcasting, new annotations, a set type, and incremental builds.
Explore swift 2.0 changes, including try-catch, guard for input and optionals, strings measured by characters, and the defer keyword. It adds mutability warnings and built-in api availability checks.
Swift 2.2 introduces major language changes, including tuple comparisons up to six, compile-time version checking, and keywords as argument labels, with deprecations for C-style for loops and tuple splat syntax.
Swift 3.0 introduces major changes, including function parameters with labels, lower camel case, and method syntax updates; closures become non-escaping by default, and many foundation types convert to structures.
Understand how exclamation marks signal optionals and explicitly unwrapped optionals in swift, know when a value is guaranteed and may be nil, and why overusing them is frowned upon.
Use the override keyword to replace a parent class method, especially in UI controllers, to ensure safety; X code will refuse to build if the override is missing or incorrect.
Explore the difference between unowned and weak references in Swift closures, referencing self without owning it and avoiding nil, while noting you don't need to unwrap optionals.
Explore how Swift properties default to strong references, and learn how weak references prevent reference cycles by avoiding ownership, ensuring objects can be deallocated when appropriate.
Know that a cgfloat adapts to 32- or 64-bit platforms and appears in core graphics, UIKit, and SpriteKit; learn how to convert a float or double to a cgfloat.
Explore closures as anonymous functions stored in a variable to be called later. They remember the program state and are used in UI view animations and completion blocks.
Delegate objects receive notifications when something interesting happens in iOS. Conform to a protocol, like the table view delegate, and implement optional or required methods to respond to events.
Dictionaries store values at named keys, with each key mapping to one value; you look up values by key, and keys can be non-string like dates, while dictionaries are ordered.
Explore the Swift double datatype, its high precision for decimals like 3.1 and pi, and why choosing double over float guards accuracy in numeric values.
Explore the float datatype, which stores low precision decimal numbers such as 3.1 and 3.14159. Understand why Swift often defaults to double and when libraries use a C float instead.
Explore nib and xib files, describe user interfaces with Interface Builder, and understand how storyboards have largely replaced nibs and xibs in modern iOS development.
Learn how protocols define a set of actions, how table view data source uses this pattern, and how Swift enforces conformance with required and optional methods.
Discover how selectors name methods on objects or structs to run code at runtime, revived in Swift for target-action patterns with timers and bar button items.
Explore how storyboards organize iOS interfaces by using layout guides for alignment, linking multiple view controllers with segues, and choosing between visual navigation and programmatic creation.
Explore Swift structs vs classes, highlighting value semantics, independent copies, and no inheritance for structs, with memberwise initializers and a to-do list example.
Discover swift tuples as lightweight data holders that resemble anonymous structs, return multiple values from functions, and are accessed by named elements or position, with a name-splitting example.
Master Swift optionals and the question mark that signals a value or no value. Learn safe unwrapping to avoid crashes when an element is missing.
AnyObject lets you pass any object type, enabling untyped flexibility and bridging to Objective-C for properties, parameters, and return values.
Explore copy on write and how it boosts performance by delaying copies of arrays and dictionaries until modification, with shared memory addresses and automatic full copies on write.
Learn the difference between let and var in Swift, why constants are preferred for values that never change, and how using let enhances safety and enables compiler optimizations.
Leverage the nil coalescing operator in Swift to unwrap optionals or provide a default value, ensuring a non-optional string and safer code.
Explore trailing closure syntax, a syntactic sugar that makes code with a final closure parameter easier to read and write, shortening calls and enabling function calls that run a closure.
Enable whole module optimization as a compiler pass to boost release build performance for the App Store by combining all source files and evaluating the entire program for extra optimizations.
Explore how Swift distinguishes variables and constants using let and var. Learn why constants are preferred for safety and how knowing a value won't change enables compiler optimizations.
Learn to implement a cover flow effect on iOS using a free carousel library in a Swift project, including bridging header setup and delegate conformance.
Learn to make empty table views and collection views more attractive and user friendly by using the free DZNEmptyDataSet library to display a title, description, image, or button.
Parse JSON safely with Swiftie Jaison to extract arrays and values with defaults, navigate nested dictionaries, and print first names from a sample people array.
Learn how to add a button to an MKMapView annotation by using the annotation view's right callout accessory, implement the calloutAccessoryControlTapped method, and present an alert with annotation info.
Drag a map view into your storyboard, enable maps capability in project settings to load the map framework, then run to see the MKMapView in the simulator.
Learn how to detect iBeacons with Core Location by requesting either always or when-in-use authorization, scanning beacon regions, and acting on proximity.
Learn to plot driving directions with MKMapView and MKDirectionsRequest for car, foot, or mass transit, enable maps entitlement, and render alternate routes as overlays from New York to San Francisco.
Broadcast an iBeacon from an iPhone using location. Conform to CBPeripheralManagerDelegate, and provide three methods to create, start, stop broadcasting, and mediate with the iOS Bluetooth stack.
Request the user’s location once using requestLocation, which returns immediately while your code continues to run. Handle success with didUpdateLocations and errors with didFailWithError after importing Core Location.
Explore Core Image’s face detectors with CIDetectorTypeFace to detect faces and features like eyes, mouth, smiles, and blinking in images, returning face feature details and positions.
Learn to implement an image picker using UIImagePickerController to select photos from the camera roll, request photo library permission, and handle selection, cancel actions, and privacy messages.
Learn to convert text to speech using the AVSpeechSynthesizer and AVSpeechUtterance by importing AVFoundation, then speak phrases with adjustable rate and language accents such as British, American, Irish, and Australian.
Generate a barcode in iOS using Core Image by converting input strings to ASCII-encoded data, wrap it in a scalable function, and render the barcode in an image.
Learn to generate a PDF417 barcode image from a string by returning the barcode image and loading it into a view to display the result.
Wrap a simple function around the built-in qr code generator exposed as a core image filter, scale the code, and display it in an image view on view load.
Explore Core Image and CIFilter for hardware accelerated image manipulation, applying sepia tone and adjusting intensity (e.g., 0.5 to 0.7) with many available filters.
learn to highlight words as they are spoken with iOS text-to-speech using AVSpeechSynthesizer, AVFoundation, and the delegate protocol, including setting up a label outlet and triggering playback.
Learn to create resizable images by setting cap insets, fixing corners while stretching the center, and optionally tiling the center area for versatile button graphics.
Learn to play sounds on iOS using AVAudioPlayer by storing the player as a property, locating the sound resource, creating the audio player, then playing or stopping safely with checks.
Learn to play sounds with AVAudioPlayer in Swift 4 by importing Foundation, retaining the player as a property, and using play and stop for short effects and looping music.
Learn to record audio in iOS by implementing AVAudioRecorder with AVFoundation, requesting recording permission, configuring a recording button, and saving files to the documents directory.
Learn to use ReplayKit to record the screen in any app, with a complete example and start/stop controls, plus post-recording preview and sharing options.
Render any view into a UIImage with four lines of code, automatically drawing subviews and displaying the result in an image view.
Save a rendered image to a file by converting it to png or jpeg data with UIImagePNGRepresentation or UIImageJPEGRepresentation. Save to the documents directory and verify in Finder.
Learn to add a complete barcode scanning control to a Swift project using the av capture method data protocol, with capture session and preview layer, and handling the view lifecycle.
Discover implementing QR code scanning in iOS with AVFoundation using a capture session, preview layer, and metadata output, wrapped in a reusable view controller with portrait orientation.
Import AVFoundation and use AVCaptureDevice to lock and unlock configuration, ensuring only one app controls the torch, then call the toggle torch method to turn the flashlight on.
Learn how to save an image to the iOS photo library using UIImageWriteToSavedPhotosAlbum, including the four parameters, the required callback method, and setting the photo library usage description for permission.
If you're tired of scrolling through Stack Overflow trying to resuscitate ancient Swift 2.0 code, this is the perfect course for you: over 300 of the most common questions for Swift, iOS, and Xcode get answered right here, with all code fully updated for iOS 11 and Swift 4.
This is real, hands-on stuff that gets right to the point:
All those and more are covered right here, right before your eyes.
Organized for your convenience
With such a huge library of videos to learn from, you might be wondering how fast it can really be to find solutions inside this cookbook collection. Well, let me tell you: it's fast. The whole course is organized by segments such as CALayer, SpriteKit, and UIKit, so in one click you narrow your search down to what interests you most.
And from there you can either jump straight to the solution you care about – "how can I rotate my view?" – or just browse the category to stumble upon all-new things you haven't even tried before.
Tried and tested solutions
Anyone could put together some Swift code examples and call it a cookbook, but this collection is different.
First, this is the largest collection of its type in the world – with over 300 categorized solutions, this is a simply unbeatable problem-solving resource.
Second, this course comes with complete, downloadable source code for all solutions, so you can try them out easily.
Third, these solutions are proven: 10,000 students have already learned Swift from me, so I know the problems they hit time and time again. This course was crafted specifically to solve all the most common problems developers hit with UIKit, SpriteKit, Swift, and more.
But most importantly…
You're guaranteed incredible quality. No more scrabbling around Stack Overflow trying to find fixes, no more reading through ten pages of Google search results to find what you need.
Instead, the Swift 4 Cookbook gives you all the fixes you need to take your apps to the next level, all fully revised and updated for Swift 4 and iOS 11.