问题
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