Skip to content

Instantly share code, notes, and snippets.

View yoxisem544's full-sized avatar
🥑

David Lin yoxisem544

🥑
View GitHub Profile
import Foundation
class Child: NSObject {
let name: String
// KVO-enabled properties must be @objc dynamic
@objc dynamic var age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
protocol Constructable {
init()
}
extension Int {
func of<T: Constructable>(_ this: T.Type) -> [T] {
guard self > 0 else { return [] }
return (1...self).map({ _ in T() })
}
let jsonData = """
{ "title": "Blah",
"frontCover": {},
"backCover": { "image": "", "text": "It's good, read it" }
}
"""
struct BookCover: Decodable {
var text: String
var image: String?
public protocol JSONEmptyRepresentable {
// 如果建立物件時會遇到 空 json {},則需要提供自身的 coding keys
associatedtype CodingKeyType: CodingKey
}
extension KeyedDecodingContainer {
public func decodeIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? where T : Decodable & JSONEmptyRepresentable {
// 先檢查有沒有我們要找的 frontCover key
if contains(key) {
// 有的話建立出 nested container
extension BookCover: JSONEmptyRepresentable {
typealias CodingKeyType = BookCover.CodingKeys
}
public protocol JSONBlankRepresentable: RawRepresentable {}
extension KeyedDecodingContainer {
public func decodeIfPresent<T>(_ type: T.Type, forKey key: K) throws -> T? where T : Decodable & JSONBlankRepresentable, T.RawValue == String {
if contains(key) {
if let stringValue = try decodeIfPresent(String.self, forKey: key), stringValue.isEmpty == false {
return T.init(rawValue: stringValue)
}
}
return nil
enum Gender {
case male, female
}
struct User {
let name: String
let gender: String // Not good enough
let gender: Gender // Good
}
public enum ContentKind : Codable {
case app(String)
case movie(Int)
}
extension ContentKind {
// decode 錯誤拿來丟的錯誤
enum CodingError: Error { case decoding(String) }
// 拿來解析的 keys
enum CodableKeys: String, CodingKey { case app, movie }
enum SpaceshipKind : String, Codable {
case transport
case freighter
case fighter
enum CodableKeys: String, CodingKey {
case spaceship = "grand_spaceship"
}
enum CodingError: Error { case decodig(String) }
require 'rest-client'
require 'nokogiri'
require 'open-uri'
class KAIYOUImageGetter
def initialize
@counter = 0
@URL = "http://kai-you.net/article/43334/images/84"
response = RestClient.get @URL