快速派生类的便捷初始化器

时间:2019-07-30 20:21:42

标签: swift initialization derived-class

我想使用扩展初始化程序对传入参数进行转换。

我在swift 5.0中找不到正确的语法来做到这一点。这可能吗?

我想避免扩展B转换所有传入的参数(在这种情况下从Strings转换为Ints),但是某种程度上依赖于扩展A init。

import Foundation

class A
{
    var x : Int

    init (_ x_: Int)
    {
        x = x_;
    }
}

class B : A
{
    var y : Int

    init (_ x_: Int, _ y_: Int)
    {
        y = y_
        super.init(x_);
    }    
}    

extension A
{
    convenience init(_ x_: String) {
        self.init(Int(x_)!);
    }
}

extension B
{
    convenience init(_ x_: String, _ y_: String) {
        super.init(x_);
        self.y = Int(y_)!;
    }
}

let a = A(0)
let b = B(1,2)
let ae = A("3")
let be = B("4","5")

print(a)
print(b)
print(ae)
print(be)

1 个答案:

答案 0 :(得分:0)

好吧,这是我所得到的最接近的-我想摆脱那些.0,.1东西,但是..等等。

func F1(_ a: Int, _ b: Int)
{
    print(a)
    print(b)
}

let F1P = (1,2)

// this doesn't work, what is the syntax for this?
// can't find how to apply a tuple to a function in swift,
// everywhere says it should "just work"
//F1(F1P)

F1(F1P.0, F1P.1) // lame


class A
{
    var x : Int

    init (_ x_: Int)
    {
        x = x_;
    }

}

class B : A
{
    var y : Int

    init (_ x_: Int, _ y_: Int)
    {
        y = y_
        super.init(x_);
    }
}

extension A
{
    convenience init(sx: String) {
        self.init(A.transform(sx))
    }

    public class func transform(_ x_: String) -> Int
    {
        return (Int(x_)!)
    }
}

extension B
{
    convenience init(sx: String, sy: String) {
        // I want to do this, but it doesn't work
        // self.init(B.transform(sx, sy));

        let p = B.transform(sx, sy)
        self.init(p.0, p.1); // lame
    }

    public class func transform(_ x_: String, _ y_: String) -> (Int, Int)
    {
        return (A.transform(x_), Int(y_)!)
    }
}

let a = A(0)
let b = B(1,2)
let ae = A(sx:"3")
let be = B(sx:"4", sy:"5")

print(a)
print(b)
print(ae)
print(be)