Skip to content

Instantly share code, notes, and snippets.

View Otbivnoe's full-sized avatar

Nikita Ermolenko Otbivnoe

View GitHub Profile
@_functionBuilder
struct SubviewsBuilder {
static func buildBlock(_ views: UIView...) -> [UIView] {
return views
}
}
extension UIView {
func addSubviews(@SubviewsBuilder _ subviews: () -> [UIView]) -> UIView {
subviews().forEach { addSubview($0) }
@dynamicMemberLookup
struct Person {
subscript(dynamicMember member: String) -> String {
let properties = ["name": "Nikita", "age": "24"]
return properties[member, default: ""]
}
}
print(Person().name) // Nikita
protocol ProtocolWithAssociatedType {
associatedtype T
}
struct Test<T>: ProtocolWithAssociatedType {} // no compile error
struct Test: ProtocolWithAssociatedType {} // error: Type 'Test' does not conform to protocol 'ProtocolWithAssociatedType'
func printData(from keyPaths: KeyPath<[String: Any], Any?>...) {
keyPaths.forEach { keyPath in
print(dict[keyPath: keyPath])
}
}
printData(from: \.name, \.age)
// Optional("Nikita")
// Optional(24)
@dynamicMemberLookup
protocol DictionaryDynamicLookup {
associatedtype Key
associatedtype Value
subscript(key: Key) -> Value? { get }
}
extension DictionaryDynamicLookup where Key == String {
subscript(dynamicMember member: String) -> Value? {
return self[member]
extension UserDefaults {
subscript<T: RawRepresentable>(key: String) -> T? {
get {
if let rawValue = value(forKey: key) as? T.RawValue {
return T(rawValue: rawValue)
}
return nil
}
set {
enum AppTheme: Int {
case light
case dark
}
class SettingsService {
var appTheme: AppTheme {
get {
if let rawValue: AppTheme.RawValue = UserDefaults.standard[#function], let theme = AppTheme(rawValue: rawValue) {
extension UserDefaults {
subscript<T>(key: String) -> T? {
get {
return value(forKey: key) as? T
}
set {
set(newValue, forKey: key)
}
}
class SettingsService {
var isNotificationsEnabled: Bool {
get {
let isEnabled = UserDefaults.standard.value(forKey: #function) as? Bool
return isEnabled ?? true
}
set {
UserDefaults.standard.setValue(newValue, forKey: #function)
}
class SettingsService {
private enum Keys {
static let isNotificationsEnabled = "isNotificationsEnabled"
}
var isNotificationsEnabled: Bool {
get {
let isEnabled = UserDefaults.standard.value(forKey: Keys.isNotificationsEnabled) as? Bool
return isEnabled ?? true