Skip to content

Instantly share code, notes, and snippets.

@JohnSundell
Last active May 21, 2020 08:19
Show Gist options
  • Save JohnSundell/bc8bc138529978fc2fb8c90d96b7d801 to your computer and use it in GitHub Desktop.
Save JohnSundell/bc8bc138529978fc2fb8c90d96b7d801 to your computer and use it in GitHub Desktop.
An example of using #function for user defaults properties, and a test that guards against property name changes
import UIKit
class OnboardingManager {
private let userDefaults: UserDefaults
init(userDefaults: UserDefaults = .standard) {
self.userDefaults = userDefaults
}
func presentOnboardingControllerIfNeeded(in viewController: UIViewController) {
guard !userDefaults.onboardingCompleted else {
return
}
// Present view controller
userDefaults.onboardingCompleted = true
}
}
private extension UserDefaults {
var onboardingCompleted: Bool {
get { return bool(forKey: #function) }
set { set(newValue, forKey: #function) }
}
}
import XCTest
class OnboardingManagerTests: XCTestCase {
private var manager: OnboardingManager!
private var userDefaults: UserDefaults!
override func setUp() {
super.setUp()
userDefaults = UserDefaults(suiteName: "test")
userDefaults.removePersistentDomain(forName: "test")
manager = OnboardingManager(userDefaults: userDefaults)
}
func testPresentingOnboardingViewController() {
let viewController = UIViewController()
manager.presentOnboardingControllerIfNeeded(in: viewController)
XCTAssertNotNil(viewController.presentedViewController)
}
func testNoOnboardingViewControllerPresentedIfOnboardingCompleted() {
// Here we use a string literal (the property isn't even accessible), which guards against name changes
userDefaults.set(true, forKey: "onboardingCompleted")
let viewController = UIViewController()
manager.presentOnboardingControllerIfNeeded(in: viewController)
XCTAssertNil(viewController.presentedViewController)
}
}
@PaulSolt
Copy link

Thanks for the example, John!

This is a neat way to use #function for string literals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment