HOW TO CALL A FUNCTION WITHIN A STRUCTURE AND A CLASS?

Total Post:128

Points:898
 1039  View(s)
Ratings:
Rate this:
I have two files: ClassA.swift and ClassB.swift
class ClassA: NSObject {
        struct StructA {
            func talk(string: String) {
                println("I say: \(string)")
            }
        }
    }
 
 
    class ClassB: NSObject {
        func makeItTalk(string: String) {
            ClassA.StructA.talk("Hello") <--------------
        }
    }

I get the following error message

Type 'ClassA.StructA' does not conform to protocol 'StringLiteralConvertible'

Any idea why? Is it actually something than can be achieved?

  1. Post:194

    Points:1396
    Re: How to call a function within a structure and a class?

    You are accessing StructA in a static context, whereas you need an instance of it:


    class ClassB: NSObject {

            func makeItTalk(string: String) {

                var myStruct = ClassA.StructA()

                myStruct.talk("Hello")

            }

        }

    Alternatively, if your goal is to access that method statically, just declare it as a static struct method:

    static func talk(string: String) {

            println("I say: \(string)")

        }

  1. Post:36

    Points:260
    Re: How to call a function within a structure and a class?

    You are using talk as static method, but it is declared as instance method. Change to:

    class ClassA: NSObject {
            struct StructA {
                static func talk(string: String) {
                    println("I say: \(string)")
                }
            }
        }

      Modified On Apr-05-2018 11:59:49 PM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!