Last active
February 16, 2020 14:33
-
-
Save wildthink/d42f45da70ef48f212a3ea2a72e21697 to your computer and use it in GitHub Desktop.
Quick clone of NSObjects using NSArchiver
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
// https://medium.cobeisfresh.com/accessing-types-from-extensions-in-swift-32ca87ec5190 | |
public protocol Clonable { | |
func clone() throws -> Self? | |
} | |
public protocol Clonable { | |
func clone() throws -> Self | |
} | |
public struct CloneError: Error, CustomStringConvertible { | |
let file: String | |
let line: Int | |
let summary: String | |
public var description: String { "CloneError (\(file):\(line)) \(summary)" } | |
init (_ msg: String, file: String = #file, line: Int = #line) { | |
summary = msg | |
self.file = file | |
self.line = line | |
} | |
} | |
public func clone<S: AnyObject>(_ nob: S, fin: ((inout S) -> Void)? = nil) throws -> S { | |
throw CloneError("Unable to clone Class '\(type(of: nob))'") | |
} | |
public func clone<S: NSCopying>(_ nob: S, fin: ((inout S) -> Void)? = nil) throws -> S { | |
var clone = nob.copy() as! S | |
fin?(&clone) | |
return clone | |
} | |
public func clone<S: Clonable>(_ nob: S, fin: ((inout S) -> Void)? = nil) throws -> S { | |
var clone = try nob.clone() | |
fin?(&clone) | |
return clone | |
} | |
public func clone<S: Codable>(_ nob: S, fin: ((inout S) -> Void)? = nil) throws -> S { | |
let encoder = JSONEncoder() | |
let decoder = JSONDecoder() | |
let data = try encoder.encode(nob) | |
var clone = try decoder.decode(S.self, from: data) | |
fin?(&clone) | |
return clone | |
} | |
@objc class Bob: NSObject { | |
var name = "George" | |
} | |
var str = "Hello, playground" | |
let cs = try? clone(str) | |
let bob = Bob() | |
bob is Clonable | |
let bc = clone(bob) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment