Create new concrete object from variable - swift

I want to create an extension method for any type which returns a new object with the concrete type of the variable, e.g.:
class A
{
required public init() {}
}
class B : A {}
let myProp = B()
doSomethingWith(myProp)
func doSomethingWith(_ prop:A)
{
// Should create a new object of type B:
let foo = prop.createNew()
}
So far my extension looks like this:
extension NSObject
{
public func createNew() -> T
{
let t = type(of: self)
let new = t.init()
}
}
However it needs to return a generic type and I'm stuck with that. How would I have to implement createNew() properly?

It's just Self, right?
extension NSObject {
public func createNew() -> Self {
return type(of: self).init()
}
}

Related

Problem with swift polymorphism and dynamic type

I just encountered a strange behavior in swift's inheritance handling, when it comes to polymorphism and dynamic types. The following code shows the problem I encounter, which basically is: The dynamic type is recognized correctly (printed by print("type(of: self) = \(classType)")), but the generic function testGeneric uses the wrong type.
class Global {
static func testGeneric<T: TestSuperClass>(of type: T.Type) {
print("T.Type = \(T.self)")
}
}
class TestSuperClass {
func run() {
let classType = type(of: self)
print("type(of: self) = \(classType)")
Global.testGeneric(of: classType)
}
}
class TestClass: TestSuperClass {
}
class TestClass2: TestSuperClass {
override func run() {
let classType = type(of: self)
print("type(of: self) = \(classType)")
Global.testGeneric(of: classType)
}
}
let testClass = TestClass()
let testClass2 = TestClass2()
testClass.run()
testClass2.run()
the printed output is
type(of: self) = TestClass
T.Type = TestSuperClass
type(of: self) = TestClass2
T.Type = TestClass2
So basically when calling testClass.run(), type(of: self) yields TestClass, which I would expect. The problem then is that the generic function testGeneric, which is called immediately afterwards, somehow does not work with type TestClass, but uses TestSuperClass instead.
What I personally would expect is
type(of: self) = TestClass
T.Type = TestClass
type(of: self) = TestClass2
T.Type = TestClass2
i.e., the generic function testGeneric using the type TestClass instead of TestSuperClass when called via testClass.run().
Questions:
- Do you have an explanation for that?
- How can I obtain the behavior I had in mind?
In Swift, the compiler want's to know at compile time which generic type to "infer". Therefore, the type system will bind to the static type. There is no such thing as dynamic type inference.
Therefore the compiler generates the following (see comments):
class TestSuperClass {
func run() {
let classType = type(of: self) // static MetaType TestSuperClass.Type
print("type(of: self) = \(classType)") // dynamic type: TestClass
Global.testGeneric(of: classType) // infer to static type, i.e. testGeneric<TestSuperClass>
}
}
As a result, T.self is TestSuperClass in your case, because that's what the compiler is able to see:
static func testGeneric<T: TestSuperClass>(of type: T.Type) {
print("T.Type = \(T.self)")
}
What you maybe want is the following:
static func testGeneric<T: TestSuperClass>(of type: T.Type) {
print("T.Type = \(type)")
}
Here, you do not print the type of T, but the (dynamic) value of the parameter type, which in your case is TestClass
To answer the second question: You will not be able to change the dynamic type of the retured array; it will always be [TestSuperClass] - although it will contain TestClass objects:
class Global {
static func testGeneric<T: TestSuperClass>(of type: T.Type) {
print("T.Type = \(T.self)")
}
static func returnObjects<T: TestSuperClass>(of theType: T.Type) -> [T] {
let newObj = theType.init()
let newObjType = type(of:newObj)
print("type(of: newObj) = \(newObjType)")
return [newObj]
}
}
class TestSuperClass {
required init() {
print ("TestSuperClass.init")
}
func run() {
let classType = type(of: self)
print("type(of: self) = \(classType)")
Global.testGeneric(of: classType)
let array = Global.returnObjects(of: classType)
let arrayType = type(of:array)
print("type(of: self) = \(arrayType)")
print (array)
}
}
class TestClass: TestSuperClass {
required init() {
super.init()
print("TestClass.init")
}
}
let testClass = TestClass()
testClass.run()
TestSuperClass.init
TestClass.init
type(of: self) = TestClass
T.Type = TestSuperClass
TestSuperClass.init
TestClass.init
type(of: newObj) = TestClass
type(of: self) = Array < TestSuperClass >
[__lldb_expr_21.TestClass]

Is there a way to initialize a class in swift by using a variable which contains the name of the class?

Suppose I have a simple factory which returns various subclasses of a custom ModelObject class like:
class func testModelObject(className: String) -> ModelObject
{
let obj = // instance of the subclass of ModelObject specified by className
return obj
}
Is there a way to do this? Will Swift freak out when I try to call any methods of that object? Should I have something else for my return type?
For best type safety, you should let testModalObject to accept a meta-type like:
class ModelObject {
required init() {}
}
class Subclass: ModelObject {
required init() { super.init() }
}
func testModalObject(_ type: ModelObject.Type) -> ModelObject {
return type.init()
}
testModalObject(Subclass.self)
If you really need a string input, you will need to rely on the Objective-C runtime and do some casting (see how to create instance of a class from a string in swift 3):
#objc
class ModelObject: NSObject { // <---
required override init() {}
}
#objc(MOSubclass) // <-- tell ObjC the name is "MOSubclass" instead of "????.Subclass".
class Subclass: ModelObject {
required init() { super.init() }
}
func testModalObject(_ typeName: String) -> ModelObject? {
let cls = NSClassFromString("MO\(typeName)") as? ModelObject.Type
return cls?.init()
}
testModalObject("Subclass")!

Pass class as param into function which returns an object of this type in swift?

I need to write something like this:
func createInstanceOfClass(someClass: Class) -> UIViewController {
var vc = someClass()
//some initialization
...
//
return
}
I found some similar questions but some of them are not appropriate for this task, some about param T which seems to be extra.
Here is an example of how you might do this. Use T.Type to reference the metatype of T, and T.self to reference the type T.
protocol DefaultConstructible {
init()
}
class A: DefaultConstructible {
required init() {}
}
struct B: DefaultConstructible {
init() {}
}
func makeAnInstance<T: DefaultConstructible>(of c: T.Type) -> T {
return c.init()
}
let a = makeAnInstance(of: A.self)
let b = makeAnInstance(of: B.self)

Swift: Instantiate class (AnyClass) conforming to protocol

I want to implement something like "registerClassForAction".
For that purpose, I have defined a protocol:
#objc protocol TestProt {
func testMe() -> String
}
Let's do a class declaration:
class TestClass: NSObject, TestProt {
func testMe() -> String {
return "test"
}
}
I define the function to register the object in another class:
func registerClassForAction(aClass: AnyClass) { ... }
Switching to the REPL, I'd simulate the register method:
let aClass: AnyClass = TestClass.classForCoder() //or .self
let tClass = aClass as NSObject.Type
let tInst = tClass() as TestProt
tInst.testMe()
This currently works but is there another way to instantiate tClass, other than with
let tClass = aClass as NSObject.Type
Reason for asking, I'd like to explore the chance of getting rid of the NSObject so my TestClass does not to inherit from NSObject. Delegation was considered, but I'd like to control the lifetime of tInst and be able to dealloc it at a specific point in time.
thanks for helping
Ron
This is possible in Swift 2.0 without requiring #objc or subclassing NSObject:
protocol TestProt {
func testMe() -> String
}
class TestClass: TestProt {
// This init is required in order
// to construct an instance with
// a metatype value (class.init())
required init() {
}
func testMe() -> String {
return "Hello from TestClass"
}
}
let theClass = TestClass.self
let tInst: TestProt = theClass.init()
tInst.testMe()

Implementing copy() in Swift

I want to be able to copy a custom class in Swift. So far, so good. In Objective-C I just had to implement the NSCopying protocol, which means implementing copyWithZone.
As an example, I have a basic class called Value which stores a NSDecimalNumber.
func copyWithZone(zone: NSZone) -> AnyObject! {
return Value(value: value.copy() as NSDecimalNumber)
}
In Objective-C I, could easily just call copy to copy my object. In Swift, there seems to be no way to call copy. Do I really need to call copyWithZone even if no zone is needed? And which zone do I need to pass as a parameter?
The copy method is defined in NSObject. If your custom class does not inherit from NSObject, copy won't be available.
You can define copy for any object in the following way:
class MyRootClass {
//create a copy if the object implements NSCopying, crash otherwise
func copy() -> Any {
guard let asCopying = ((self as AnyObject) as? NSCopying) else {
fatalError("This class doesn't implement NSCopying")
}
return asCopying.copy(with: nil)
}
}
class A : MyRootClass {
}
class B : MyRootClass, NSCopying {
func copy(with zone: NSZone? = nil) -> Any {
return B()
}
}
var b = B()
var a = A()
b.copy() //will create a copy
a.copy() //will fail
I guess that copy isn't really a pure Swift way of copying objects. In Swift it is probably a more common way to create a copy constructor (an initializer that takes an object of the same type).
Well, there is a really easy solution for this and you do not have to create root class.
protocol Copyable {
init(instance: Self)
}
extension Copyable {
func copy() -> Self {
return Self.init(instance: self)
}
}
Now, if you want to make your custom class be able to copy, you have to conform it to Copyable protocol and provide init(instance: Self) implementation.
class A: Copyable {
var field = 0
init() {
}
required init(instance: A) {
self.field = instance.field
}
}
Finally, you can use func copy() -> Self on any instance of A class to create a copy of it.
let a = A()
a.field = 1
let b = a.copy()
You can just write your own copy method
class MyRootClass {
var someVariable:Int
init() {
someVariable = 2
}
init(otherObject:MyRootClass) {
someVariable = otherObject.someVariable
}
func copy() -> MyRootClass {
return MyRootClass(self)
}
}
The benefit of this is when you are using subclasses around your project, you can call the 'copy' command and it will copy the subclass. If you just init a new one to copy, you will also have to rewrite that class for each object...
var object:Object
....
//This code will only work for specific class
var objectCopy = Object()
//vs
//This code will work regardless of whether you are using subClass or superClass
var objectCopy = object.copy()
In my case the object chain was large and nested so was looking for simpler solutions.
The core concept being simple enough... duplicate the data by new initialization, I used Encode and Decode to deep-copy the entire object since my objects were already conforming to Codable,
Simple Example:
class MyCodableObject: Codable, CustomStringConvertible {
var name: String
var description: String { name }
init(name: String) {
self.name = name
}
}
let originalArr = [MyCodableObject(name: "a"),
MyCodableObject(name: "b")]
do {
let data = try JSONEncoder().encode(originalArr)
let copyArr = try JSONDecoder().decode([MyCodableObject].self, from: data)
//modify if required
copyArr.forEach { obj in
obj.name = "\(obj.name) modified"
}
print(originalArr, copyArr) //-> [a, b] [a modified, b modified]
} catch {
fatalError(error.localizedDescription)
}
Refactor (Generic Solution):
To simplify future cases we can create a protocol that will provide a copy function.
For Non-Codable objects, you will have to implement your own copy function.
For Codable objects, we can provide a default implementation so it's ready-to-use. Like so:
protocol Copyable {
func copy() -> Self
}
extension Copyable where Self: Codable {
func copy() -> Self {
do {
let encoded = try JSONEncoder().encode(self)
let decoded = try JSONDecoder().decode(Self.self, from: encoded)
return decoded
} catch {
fatalError(error.localizedDescription)
}
}
}
We can now conform a Codable object to our Copyable protocol and start using it immediately.
extension MyCodableObject: Copyable {}
Example:
let a = MyCodableObject(name: "A")
let b = a.copy()
b.name = "B"
print(a.name, b.name) //-> "A B"
We can also conform an Array of Codable objects to Copyable and access the copy function instantly:
extension Array: Copyable where Element: Codable {}
Example:
let originalArr = [MyCodableObject(name: "a"),
MyCodableObject(name: "b")]
let copyArr = originalArr.copy()
copyArr.forEach { (obj) in
obj.name = "\(obj.name) modified"
}
print(originalArr, copyArr) //-> [a, b] [a modified, b modified]
IMO, the simplest way to achieve this is :
protocol Copyable
{
init(other: Self)
}
extension Copyable
{
func copy() -> Self
{
return Self.init(other: self)
}
}
Implemented in a struct as :
struct Struct : Copyable
{
var value: String
init(value: String)
{
self.value = value
}
init(other: Struct)
{
value = other.value
}
}
And, in a class, as :
class Shape : Copyable
{
var color: NSColor
init(color: NSColor)
{
self.color = color
}
required init(other: Shape)
{
color = other.color
}
}
And in subclasses of such a base class as :
class Circle : Shape
{
var radius: Double = 0.0
init(color: NSColor, radius: Double)
{
super.init(color: color)
self.radius = radius
}
required init(other: Shape)
{
super.init(other: other)
if let other = other as? Circle
{
radius = other.radius
}
}
}
class Square : Shape
{
var side: Double = 0.0
init(color: NSColor, side: Double)
{
super.init(color: color)
self.side = side
}
required init(other: Shape)
{
super.init(other: other)
if let other = other as? Square
{
side = other.side
}
}
}
If you want to be able to copy an array of Copyable types :
extension Array where Element : Copyable
{
func copy() -> Array<Element>
{
return self.map { $0.copy() }
}
}
Which then allows you to do simple code like :
{
let shapes = [Circle(color: .red, radius: 5.0), Square(color: .blue, side: 5.0)]
let copies = shapes.copy()
}
In my opinion, more Swifty way is to use associated type in Copyable protocol which allows define return type for method copy. Other ways don't allow to copy an object tree like this:
protocol Copyable {
associatedtype V
func copy() -> V
func setup(v: V) -> V
}
class One: Copyable {
typealias T = One
var name: String?
func copy() -> V {
let instance = One()
return setup(instance)
}
func setup(v: V) -> V {
v.name = self.name
return v
}
}
class Two: One {
var id: Int?
override func copy() -> Two {
let instance = Two()
return setup(instance)
}
func setup(v: Two) -> Two {
super.setup(v)
v.id = self.id
return v
}
}
extension Array where Element: Copyable {
func clone() -> [Element.V] {
var copiedArray: [Element.V] = []
for element in self {
copiedArray.append(element.copy())
}
return copiedArray
}
}
let array = [One(), Two()]
let copied = array.clone()
print("\(array)")
print("\(copied)")
Copyable instances in swift
NOTE:
The great thing about this approach to copying Class instances is that it doesn't rely on NSObject or objc code, and most importantly it doesn't clutter up the "Data-Style-Class". Instead it extends the protocol that extends the "Data-Style-Class". This way you can compartmentalize better by having the copy code in another place than the data it self. The inheritance between classes is also taken care of as long as you model the protocols after the classes. Here is an example of this approach:
protocol IA{var text:String {get set}}
class A:IA{
var text:String
init(_ text:String){
self.text = text
}
}
extension IA{
func copy() -> IA {
return A(text)
}
}
protocol IB:IA{var number:Int {get set}}
class B:A,IB{
var number:Int
init(_ text:String, _ number:Int){
self.number = number
super.init(text)
}
}
extension IB{
func copy() -> IB {
return B(text,number)
}
}
let original = B("hello",42)
var uniqueCopy = original.copy()
uniqueCopy.number = 15
Swift.print("uniqueCopy.number: " + "\(uniqueCopy.number)")//15
Swift.print("original.number: " + "\(original.number)")//42
NOTE:
To see an implementation of this approach in real code: Then check out this Graphic Framework for OSX: (PERMALINK) https://github.com/eonist/Element/wiki/Progress2#graphic-framework-for-osx
The different shapes uses the same style but each style uses a style.copy() call to create an unique instance. Then a new gradient is set on this copy rather than on the original reference like this:
The code for the above example goes like this:
/*Gradients*/
let gradient = Gradient(Gradients.red(),[],GradientType.Linear,π/2)
let lineGradient = Gradient(Gradients.teal(0.5),[],GradientType.Linear,π/2)
/*Styles*/
let fill:GradientFillStyle = GradientFillStyle(gradient);
let lineStyle = LineStyle(20,NSColorParser.nsColor(Colors.green()).alpha(0.5),CGLineCap.Round)
let line = GradientLineStyle(lineGradient,lineStyle)
/*Rect*/
let rect = RectGraphic(40,40,200,200,fill,line)
addSubview(rect.graphic)
rect.draw()
/*Ellipse*/
let ellipse = EllipseGraphic(300,40,200,200,fill.mix(Gradients.teal()),line.mix(Gradients.blue(0.5)))
addSubview(ellipse.graphic)
ellipse.draw()
/*RoundRect*/
let roundRect = RoundRectGraphic(40,300,200,200,Fillet(50),fill.mix(Gradients.orange()),line.mix(Gradients.yellow(0.5)))
addSubview(roundRect.graphic)
roundRect.draw()
/*Line*/
let lineGraphic = LineGraphic(CGPoint(300,300),CGPoint(500,500),line.mix(Gradients.deepPurple()))
addSubview(lineGraphic.graphic)
lineGraphic.draw()
NOTE:
The copy call is actually done in the mix() method. This is done so that code can be more compact and an instance is conveniently returned right away.
PERMALINK for all the supporting classes for this example: https://github.com/eonist/swift-utils
Only if you are using ObjectMapper library :
do like this
let groupOriginal = Group(name:"Abc",type:"Public")
let groupCopy = Mapper<Group>().mapAny(group.toJSON())! //where Group is Mapable
Swift making copies of passed class instances
If you use the code in the accepted answer(the OP answered their own question) here, so long as your class is a subclass of NSObject and uses the Copying protocol in that post it will work as expected by calling the copyOfValues() function.
With this, no tedious setup or copy functions where you need to assign all the instance variables to the new instance.
I should know, I wrote that code and just tested it XD