-
-
Save alemar11/b62e8c6642f787384f5988e029690d43 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