accessing struct from one class to another

旧街凉风 提交于 2019-12-02 04:01:42

问题


Is it possible to access a struct from another class?

ex:

class A{
    struct structOfClassA {
        func returnLetterA () -> String{
            return "a"
        }
    }
}

class B{
    let classA = A()

    init(){
        classA.structOfClassA.returnLetterA // this is what I want to achieve
    }
}

how can I access the the struct from Class A() in Class B()?

is there a workaround with this?

Thank you!


回答1:


The structure in class A defines a type (that can be used within the scope of class A), but you need an instance of it to be able to call the member functions of the structure. E.g.:

class A {
    struct StructOfClassA {
        func returnLetterA() -> String{
            return "a"
        }
    }

    var structOfClassA = StructOfClassA() 
        /* Instance of 'StructOfClassA' structure type */
}

class B {
    let classA = A()

    init() {
        let myLetter = classA.structOfClassA.returnLetterA()
        print(myLetter)
    }
}

var myB = B() // prints "a"

Alternatively, you can let B be a subclass of A, which gives you access to the type StructOfClassA from the superclass, in which case you could create an instance of StructOfClassA and access its method returnLetterA():

class A {
    class StructOfClassA {
        func returnLetterA() -> String{
            return "a"
        }
    }
}

class B : A {
    let classA = A()

    override init() {
        let myLetter = StructOfClassA().returnLetterA()
        print(myLetter)
    }
}

var myB = B() // prints "a"



回答2:


You have just declared the struct A in class A but you also have to create an instance from struct A.

class A{
    struct SomeStruct {
        func returnLetterA () -> String{
            return "a"
        }
    }
    let A = SomeStruct()
}

class B{
    let classA = A()

    init(){
        let letter = classA.A.returnLetterA() // this is what I want to achive
    }
}


来源:https://stackoverflow.com/questions/34932917/accessing-struct-from-one-class-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!