Last active
May 21, 2020 08:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the example, John!
This is a neat way to use
#function
for string literals.