Skip to content

Instantly share code, notes, and snippets.

View LeeKahSeng's full-sized avatar

Lee Kah Seng LeeKahSeng

View GitHub Profile
struct User: Codable {
var firstName: String
var lastName: String
var lastLogin: Date?
}
@propertyWrapper
struct Storage<T: Codable> {
private let key: String
private let defaultValue: T
struct AppData {
@Storage(key: "enable_auto_login_key", defaultValue: false)
static var enableAutoLogin: Bool
@Storage(key: "username_key", defaultValue: "")
static var username: String
}
struct AppData {
private static let enableAutoLoginKey = "enable_auto_login_key"
private static let usernameKey = "username_key"
static var enableAutoLogin: Bool {
get {
// Read from UserDefaults
return UserDefaults.standard.bool(forKey:enableAutoLoginKey)
}
class Boy {
// Failable initialisation
init?(age: Int) {
// Age cannot be less than 0
if age < 0 {
return nil
}
}
}
let str: String? = "test"
// Optional binding using 'if'
if let value = str {
print(value)
}
// Optional binding using guard
guard let value = str else {
// Create another bird array that accept nil value
let otherBirds: [Bird?] = [chicken, nil]
let chicken4 = otherBirds[0] as? Chicken? // Cast successful: chicken4 type is Chicken??
let chicken5 = otherBirds[0] as! Chicken? // Cast successful: chicken5 type is Chicken?
let chicken6 = otherBirds[1] as? Chicken? // Cast failed: Trigger runtime error
let chicken7 = otherBirds[1] as! Chicken? // Cast failed: Trigger runtime error
let chicken8 = otherBirds[0] as? Chicken! // chicken8 type is Chicken?? | Warning: Using '!' here is deprecated and will be removed in a future release
let chicken9 = otherBirds[0] as! Chicken! // chicken9 type is Chicken? | Warning: Using '!' here is deprecated and will be removed in a future release
class Bird {
var name: String
init(name: String) {
self.name = name
}
}
class Chicken: Bird {
let canFly = false
}
import Foundation
import CoreData
import UIKit
@objc(TestEntity)
public class TestEntity: NSManagedObject {
@NSManaged private var base64: String
var image: UIImage {
set {
import Foundation
import CoreData
extension TestEntity {
@nonobjc public class func fetchRequest() -> NSFetchRequest<TestEntity> {
return NSFetchRequest<TestEntity>(entityName: "TestEntity")
}
}
import Foundation
import CoreData
import UIKit
@objc(TestEntity)
public class TestEntity: NSManagedObject {
var image: UIImage {
set {
base64 = base64(from: image)