Skip to content

Instantly share code, notes, and snippets.

View LeeKahSeng's full-sized avatar

Lee Kah Seng LeeKahSeng

View GitHub Profile
let animalArray: [Animal] = [myTiger, myCow]
let foodArray: [Any] = [Meat(), Grass()]
for (animal, food) in zip(animalArray, foodArray) {
// Feed the animal with their favorite food
animal.eat(food: food)
}
enum AnyAnimal: Animal {
case cow(Cow)
case tiger(Tiger)
var name: String {
switch self {
case let .cow(animal):
return animal.name
case let .tiger(animal):
// Create concrete type Animal
let myTiger = Tiger(withName: "My Tiger")
let myCow = Cow(withName: "My Cow")
// Instantiate AnyAnimal with concrete type Animal
let anyTiger = AnyAnimal.tiger(myTiger)
let anyCow = AnyAnimal.cow(myCow)
let animalArray: [AnyAnimal] = [anyTiger, anyCow]
let foodArray: [Any] = [Meat(), Grass()]
protocol Animal {
var name: String { get }
func walk()
associatedtype FoodType
func eat(food: FoodType)
}
class Cow: Animal {
struct AnyAnimal: Animal {
let name: String
private let walker: () -> Void
private let eater: (Any) -> Void
init<T: Animal>(_ animal: T) {
name = animal.name
walker = {
import Foundation
import CoreData
import UIKit
@objc(TestEntity)
public class TestEntity: NSManagedObject {
var image: UIImage {
set {
base64 = base64(from: image)
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 {
@NSManaged private var base64: String
var image: UIImage {
set {
class Bird {
var name: String
init(name: String) {
self.name = name
}
}
class Chicken: Bird {
let canFly = false
}
// 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