Created
          November 14, 2023 07:43 
        
      - 
      
 - 
        
Save KaitoMuraoka/acab223002a55375a48f5f71b723a675 to your computer and use it in GitHub Desktop.  
    Managing UserDefault with property wrappers
  
        
  
    
      This file contains hidden or 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
    
  
  
    
  | // 使用例 | |
| struct Settings { | |
| @UserDefault(key: "userName", defaultValue: "Unknown") | |
| static var userName: String | |
| } | |
| // 値の保存 | |
| Settings.userName = "Alice" | |
| // 値の取得 | |
| print(Settings.userName) // Alice | 
  
    
      This file contains hidden or 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 Foundation | |
| @propertyWrapper | |
| struct UserDefault<T> { | |
| let key: String | |
| let defaultValue: T | |
| init(key: String, defaultValue: T) { | |
| self.key = key | |
| self.defaultValue = defaultValue | |
| } | |
| var wrappedValue: T { | |
| get { | |
| return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue | |
| } | |
| set { | |
| UserDefaults.standard.set(newValue, forKey: key) | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment