Kacper Cz
Kacper Cz

Reputation: 586

Custom class in Swift conversion

I have created a custom class called PhoneTranslator (based on Xamarin's "Hello, iOS" guide). It looks like this:

class PhoneTranslator {
    func ToNumber(raw:String) -> String {
      var newNumber = raw.isEmpty ? "" : raw.uppercaseString
      //newNumber operations...
      return newNumber
    }
}

Then I have a ViewController standard class. I want to do this:

var translatedNumber : String?

    if let inputText = PhoneNumberTextField.text //getting text from UITextField
    {
        translatedNumber = PhoneTranslator.ToNumber(inputText) //error
    }

Then in line with ToNumber method I get an error Cannot convert value of type 'String' to expected argument type 'PhoneTranslator'.

What am I doing wrong? All input and output types seems to match.

Upvotes: 0

Views: 238

Answers (2)

Rajan Maheshwari
Rajan Maheshwari

Reputation: 14571

Alternatively no need to make a class function. You can have a shared Instance which will be a singleton object for the entire application. With this singleton object you can call the PhoneTranslator methods

class PhoneTranslator {

    static let sharedInstance = PhoneTranslator()

    func ToNumber(raw:String) -> String {
          var newNumber = raw.isEmpty ? "" : raw.uppercaseString
          //newNumber operations...
          return newNumber
          }
    }

And you can call it this way

translatedNumber  = PhoneTranslator.sharedInstance.ToNumber(inputText)

Upvotes: 0

luk2302
luk2302

Reputation: 57124

Change your code to

class PhoneTranslator {
    class func ToNumber(raw:String) -> String {
        var newNumber = raw.isEmpty ? "" : raw.uppercaseString
        return newNumber
    }
}

Your function was not a class function. Therefore you need an instance first. Above code defines the ToNumber function as class func.

Alternatively create an instance of the PhoneTranslator first:

translatedNumber = PhoneTranslator().ToNumber(inputText)

Note the () after PhoneTranslator.

Upvotes: 1

Related Questions