NEW: Master Swift design patterns with my latest book! >>

Expanding the Swift Knowledge Base

Paul Hudson    February 12th 2018    @twostraws

I've just added 270 articles to my Swift Knowledge Base, taking it up to 576 tips, techniques, and answers for Swift developers – all updated for the latest version of Xcode and Swift. Click here to browse the knowledge base by category or search for something specific.

Many people have never heard of my work on this knowledge base, mostly because I'm terrible at marketing. If you find something useful here, please help pass on the word by telling others!

I've included a full list of all 270 new articles below, but here are my top twelve you should check out:

  1. How to send notifications asynchronously using NotificationQueue
  2. How to use an image for your background color with UIColor(patternImage:)
  3. How to add a custom initializer to a struct without losing its memberwise initializer
  4. How to lock Interface Builder controls to stop accidental changes
  5. How to generate shaped random numbers using GKGaussianDistribution
  6. How to find an aspect fit image’s size inside an image view
  7. How to group arrays using dictionaries
  8. How to read the battery level of an iPhone or iPad
  9. How to check whether a date is inside a date range
  10. How to display different strings based on available space using variantFittingPresentationWidth()
  11. How to preview files using Quick Look and QLPreviewController
  12. How to do conditional test tear down using addTeardownBlock()

If you were curious, the one that took the most time to write was "What is a monad?" – I wrote that in just a few minutes, then rewrote it, rewrote it again, then again, then again and again, until my brain was starting to switch off. It's one thing to understand something, but quite another to be able to explain it in terms that everyone can understand.

The full list of new articles…

  1. How to send notifications asynchronously using NotificationQueue
  2. How to make optional protocol methods
  3. What’s the difference between frame and bounds?
  4. What’s the difference between init?() and init()?
  5. What’s the difference between == and ===?
  6. How to use an image for your background color with UIColor(patternImage:)
  7. What is a segue?
  8. How to stop your UISearchController bar hiding when you scroll
  9. How to add a custom initializer to a struct without losing its memberwise initializer
  10. How to restrict a protocol to classes
  11. How to compare dates
  12. How to check whether a date is inside a date range
  13. How to check whether users have enabled the reduced motion setting
  14. What is the @objc attribute?
  15. What is the @objcMembers attribute?
  16. What is a singleton?
  17. How to use view controller containment
  18. How to convert speech to text using SFSpeechRecognizer
  19. How to lock Interface Builder controls to stop accidental changes
  20. How to search your app’s Spotlight index
  21. How to animate a blur effect using UIVisualEffectView
  22. How to convert a String to Data
  23. How to convert Data to a String
  24. How to count element frequencies in an array
  25. What’s the difference between a static variable and a class variable?
  26. How to use local variable observers
  27. What is MVC?
  28. How to use reflection to inspect type data
  29. How to detect when the user takes a screenshot
  30. How to force a UIView to redraw: setNeedsDisplay()
  31. How to throw errors using strings
  32. How to make a background image run under the safe area
  33. How to read names in a string using NSLinguisticTagger
  34. How to control a UIProgressView’s animation
  35. How to position a view using Auto Layout anchors
  36. How to resize a custom font using UIFontMetrics
  37. What are breakpoints?
  38. How to render an NSAttributedString to a PDF
  39. How to make a UIView fade out
  40. How to change a view’s anchor point without moving it
  41. How to scan NFC tags using Core NFC
  42. What are watchpoints?
  43. How to add drag and drop to your app
  44. How to display PDFs using PDFView
  45. How to find the first matching element in an array
  46. How to sum an array of numbers using reduce()
  47. How to check whether a string contains any words from an array
  48. How to extract text from a PDF using PDFKit
  49. What is MVVM?
  50. How to watermark PDFs inside a PDFView
  51. What is a protocol associated type?
  52. How to use map() to transform an array
  53. How to use flatMap() to transform an array
  54. How to remove items from an array using filter()
  55. How to use reduce() to condense an array into a single value
  56. How to use map() with an optional value
  57. How to use flatMap() with an optional value
  58. What are sets?
  59. When to use a set rather than an array
  60. How to force a crash using fatalError()
  61. How to append one array to another array
  62. How to calculate the ROT13 of a string
  63. How to loop over non-nil items in an array
  64. How to find the path to a file in your bundle
  65. How to make a sprite follow a path
  66. How to generate fair random numbers using GKShuffledDistribution
  67. How to generate shaped random numbers using GKGaussianDistribution
  68. What are generics?
  69. What is a nested class or nested struct?
  70. How to reverse sort an array
  71. What is function composition?
  72. How to create a custom debug description
  73. How to remove the first or last item from an array
  74. How to use the forEach method to loop over an array
  75. How to make a custom sequence
  76. How to find the highest value in an array
  77. How to swap two items in an array using swapAt()
  78. How to use the rethrows keyword
  79. What is a throwing function?
  80. How to filter a loop using a where clause
  81. What is a lazy sequence?
  82. What is destructuring?
  83. How to break out of multiple loop levels using labeled statements
  84. How to add Markdown comments to your code
  85. How to create an array by repeating an item
  86. How to add associated values to enums
  87. How to add raw values to enums
  88. How to transform a dictionary using mapValues()
  89. How to read a single character from a string
  90. What is the Never return type?
  91. How to read the interface orientation: portrait or landscape?
  92. How to check whether an iPhone or iPad is upside down or face up
  93. How to use vector images in your asset catalog
  94. When is it safe to force unwrap optionals?
  95. Measuring execution speed using CFAbsoluteTimeGetCurrent()
  96. How to group arrays using dictionaries
  97. How to specify default values for dictionary keys
  98. How to use typealias to make it easier to use complex types
  99. What does the open keyword do?
  100. How to detect when the system is under pressure and you should reduce your work
  101. Why is immutability important?
  102. How to make a variadic function
  103. How to use operator overloading
  104. What are protocol extensions?
  105. What is the autoclosure attribute?
  106. What are static methods and variables?
  107. How to count matching items in an array
  108. Remove all instances of an object from an array
  109. What are designated initializers?
  110. What are convenience initializers?
  111. How to run code when an object is destroyed
  112. Check whether all items in an array match a condition
  113. Showing dictionary definitions using UIReferenceLibraryViewController
  114. How to make custom types from strings using ExpressibleByStringLiteral
  115. How to get the lines in a string as an array
  116. How to remove a prefix from a string
  117. What’s the difference between Any and AnyObject?
  118. How to read the red, green, blue, and alpha color components from a UIColor
  119. How to control which screen edges trigger system gestures using preferredScreenEdgesDeferringSystemGestures
  120. How to read your app’s version from your Info.plist file
  121. How to make the device vibrate
  122. How to identify your Auto Layout constraints
  123. How to detect when your size class changes
  124. What are class and subtype existentials?
  125. How to conform to the Equatable protocol
  126. How to find the view controller responsible for a view
  127. How to find an aspect fit image’s size inside an image view
  128. How to add conditions to a breakpoint
  129. What is key-value observing?
  130. How to find the index of the first matching array element
  131. How to find the longest initial sequence in an array
  132. How to check your program state using precondition()
  133. How to add markers to the jump bar
  134. How to use one-sided ranges
  135. How to make UIViewPropertyAnimator scrub with a custom curve: scrubsLinearly
  136. How to multiply an int and a double
  137. How to convert a string to a safe format for URL slugs and filenames
  138. How to simulate gravity in a SpriteKit scene
  139. How to debug physics in a SpriteKit scene using showsPhysics
  140. How to made an SKSpriteNode render faster using blendMode
  141. How to convert radians to degrees
  142. How to convert degrees to radians
  143. How to pass the Fizz Buzz test
  144. How to create a custom OptionSet
  145. What are keypaths?
  146. How to add a button to a navigation bar using storyboards
  147. How to add peek and pop to a UITableView
  148. How to use the zip() function to join two arrays
  149. How to use ISO-8601 dates with JSONDecoder and Codable
  150. How to format JSON using Codable and pretty printing
  151. How to sort the keys of your JSON using Codable
  152. How to advance time in an SKEmitterNode using advanceSimulationTime()
  153. How to make Xcode play sounds while debugging
  154. How to read the battery level of an iPhone or iPad
  155. What are Swift error breakpoints?
  156. How to specify your own date format with Codable and JSONEncoder
  157. How to loop audio using AVAudioPlayer and numberOfLoops
  158. How to hide your navigation bar when the keyboard shows: hidesBarsWhenKeyboardAppears
  159. How to add a number over your app icon using applicationIconBadgeNumber
  160. How to add a badge to your UITabBarItem
  161. How to run a case-insensitive search for one string inside another
  162. How to create keyframe animations using animateKeyframes()
  163. How to add a toolbar above the keyboard using inputAccessoryView
  164. What is the UIAppearance proxy?
  165. How to create a marching ants effect using lineDashPhase
  166. How to make a shape draw itself using strokeEnd
  167. How to detect long presses using UILongPressGestureRecognizer
  168. How to move to the next UITextField when the user presses return
  169. How to read the user’s location while your app is in the background
  170. How to download files with URLSession and downloadTask()
  171. How to change a sprite’s texture using SKTexture
  172. How to warp a sprite using SKWarpGeometryGrid
  173. How to crop a sprite using SKCropNode
  174. How to make a number positive using abs()
  175. How to create a project using Swift Package Manager
  176. What are implicitly unwrapped optionals?
  177. Optional vs implicitly unwrapped optional: what’s the difference?
  178. Self vs self – what’s the difference?
  179. How to make a UIView fill the screen using Auto Layout anchors
  180. How to mask one UIView using another UIView
  181. How to make your user interface in code
  182. How to subclass UIApplication using UIApplicationMain
  183. How to fix the error “protocol can only be used as a generic constraint because it has Self or associated type requirements”
  184. What is class inheritance?
  185. How to fix Auto Layout problems
  186. How to make one sprite draw in front of another using zPosition
  187. How to conform to the Comparable protocol
  188. How to conform to the Hashable protocol
  189. How to use UIPickerView
  190. How to write a closure that returns a value
  191. How to make your app open with a custom URL scheme
  192. How to show PDF thumbnails using PDFThumbnailView
  193. How to perform a segue programmatically using performSegue()
  194. How to make a UIView glow using shadowColor
  195. How to make gesture recognizers work together using require(toFail:)
  196. How to store NSCoding data using Codable
  197. What is a functor?
  198. What is a monad?
  199. What is a view’s intrinsic content size?
  200. How to fix the error “Expression was too complex to be solved in reasonable time”
  201. How to convert JSON into Swift objects using Codable
  202. How to take a photo using the camera and UIImagePickerController
  203. What is an enum?
  204. What is CloudKit?
  205. How to convert a Substring to a String
  206. How to remove duplicate items from an array
  207. How to use UIActivityIndicatorView to show a spinner when work is happening
  208. How to read the average color of a UIImage using CIAreaAverage
  209. What’s the difference between a function and a method?
  210. What is protocol-oriented programming?
  211. What is the safe area layout guide?
  212. How to use UISearchController to let users enter search words
  213. How to add scopes to a UISearchController
  214. How to pixellate a UIImage
  215. What’s the difference between a function and a closure?
  216. Private vs fileprivate: what’s the difference?
  217. How to add annotations to MKMapView using MKPointAnnotation and MKPinAnnotationView
  218. How to play videos using AVPlayerViewController
  219. How to calculate division remainder using modulo
  220. What is CALayer?
  221. How to control the sites a WKWebView can visit using WKNavigationDelegate
  222. How to control the user interface of a WKWebView using WKUIDelegate
  223. How to render PDFs using UIGraphicsPDFRenderer
  224. Adding places to MKMapView using MKPlacemark
  225. How to use UIStepper to let users change number values
  226. How to use multithreaded operations with OperationQueue
  227. How to support right-to-left languages
  228. How to capitalize the first letter of a string
  229. What is an IndexPath?
  230. What’s the difference between a protocol and a class?
  231. What is Automatic Reference Counting (ARC)?
  232. How to split an integer into an array of its digits
  233. What is a computed property?
  234. How to load HTTP content in WKWebView and UIWebView
  235. How to desaturate an image to make it black and white
  236. What is the first responder?
  237. How to load and save a struct in UserDefaults using Codable
  238. How to add multiple UIBarButtonItem to a navigation bar using rightBarButtonItems
  239. What is an escaping closure?
  240. How to customize a view controller’s back button on a navigation bar: backBarButtonItem
  241. How to round only specific corners using maskedCorners
  242. How to constrain a protocol associated type
  243. How to check whether your other apps are installed
  244. How to convert HTML to an NSAttributedString
  245. How to display different strings based on available space using variantFittingPresentationWidth()
  246. What is NSNumber?
  247. How to fix the error “View controller is unreachable because it has no entry points and no identifier for runtime access”
  248. What does the AppDelegate class do?
  249. How to concatenate strings to make one joined string
  250. What is typecasting?
  251. How to draw shapes using UIBezierPath
  252. How to center a view in its container
  253. What is the ternary operator?
  254. How to fix the error “Failed to instantiate the default view controller for UIMainStoryboardFile”
  255. What is optional chaining?
  256. How to check whether an integer lies inside a range
  257. How to split an array into chunks
  258. How to find the difference between two arrays
  259. What is an IBOutlet?
  260. How to preview files using Quick Look and QLPreviewController
  261. How to add a fragment shader to an SKSpriteNode using SKShader
  262. What is a UIViewController
  263. How to load a remote image URL into UIImageView
  264. How to hide the tab bar when a view controller is shown
  265. How to write performance tests using measure()
  266. How to set baselines for your performance tests
  267. How to test throwing functions
  268. How to test asynchronous functions using expectation()
  269. How to do one-time setup for your tests
  270. How to do conditional test tear down using addTeardownBlock()


About the author

Paul Hudson is the creator of Hacking with Swift, the most comprehensive series of Swift books in the world. He's also the editor of Swift Developer News, the maintainer of the Swift Knowledge Base, and Mario Kart world champion. OK, so that last part isn't true. If you're curious you can learn more here.

Click here to visit the Hacking with Swift store >>