无法从Swift的子类中转换值

时间:2018-08-14 20:59:53

标签: swift class casting

我做了很多研究,但没有找到问题的答案。其他人则谈论Swift类的基本问题。我自己的课仍然有问题。我也阅读了有关课程的课程,但对我没有帮助。

我有两节课;其中一个继承自另一个。

这是我的课程代码:

public partial class LabelWithFontScaling : Label
{
    public LabelWithFontScaling()
    {
        InitializeComponent();
    }
    private void InitializeComponent()
    {
        this.SuspendLayout();
        this.Name = "label1";
        this.Size = new System.Drawing.Size(250, 100);
        this.ResumeLayout(false);
    }
    float mRatio = 1.0F;
    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        float ratio = e.ClipRectangle.Height / 100.0F;
        if ((ratio > 0.1) && (ratio != mRatio))
        {
            mRatio = ratio;
            base.Font = new Font(Font.FontFamily, 48.0F * ratio, Font.Style);
        }
    }

然后我尝试像这样将class GlobalUser { var uid: String! var publicName: String! var pushID: String! var firstName: String! var lastName: String! var example1: [String:String]! var fullName: String! { get { return firstName + " " + lastName } } init(document: DocumentSnapshot) { guard let data = document.data() else { print("Missing user information during initialization.") return } self.uid = document.documentID self.publicName = (data["publicName"] as? String)! self.pushID = (data["pushID"] as? String)! self.example1 = (data["example1"] as? [String : String])! let name = data["name"] as? [String:String] self.firstName = (name!["firstName"])! self.lastName = (name!["lastName"])! } } class InterestingUser: GlobalUser { var code: Int? var example: [String:String]? var number: Int! { get { return example.count } } override init(document: DocumentSnapshot) { super.init(document: document) } } 投射到GlobalUser

InterestingUser

但是这个转换总是失败的...

有什么主意吗?预先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您遇到的错误是由于以下问题引起的:“ 然后我尝试将GlobalUser强制转换为类似这样的InterestingUser ... ”,并且是由于继承。

您的GlobalUser类是超类。您的InterestingUserGlobalUser的子类。

因此,您的InterestingUser类“了解” GlobalUser,因为它是父类,因此您可以强制转换InterestingUser as? GlobalUser,反之亦然。

示例:

if let interstingUser = InterestingUser() as? GlobalUser {
    // this will succeed because InterestingUser inherits from GlobalUser
}

if let globalUser = GlobalUser() as? InterestingUser {
    // this will fail because GlobalUser is not a subclass of InterestingUser
}

以下是一些游乐场代码供您测试:

class GlobalUser {

}

class InterestingUser: GlobalUser {

}

class Demo {
    func comparison() {
        let interesting = InterestingUser()
        let global = GlobalUser()

        if let intere = interesting as? GlobalUser {
            print("Interesting is global as well")
        }
        if let global = global as? InterestingUser {
            print("Global is interesting")
        }
    }
}

let demo = Demo()
demo.comparison()
// prints 'Interesting is global as well'