1

I have a generic class which contains a variable of generic data type. I need to convert this variable to String.

Example Code -

class test<T> {
var value:T!
var name: String!

  init(text: String, val: T)
  {
    name = text
    value = val
  }

  func toString() -> String {
    let temp = value as! String
    //let temp = String(value)
    return name + ": " + temp 
  }
}

I tried down-casting it by doing let temp = value as! String but it leads to crash during run time

Doing let temp = String(value) throws Cannot invoke initializer for type 'String' with an argument list of type '(T?)' build error

2
  • the crash won't happen if you specify T as String , can you show creation of test ? Commented Jan 16, 2019 at 21:45
  • T is going to be Int or Float in my case Commented Jan 17, 2019 at 3:45

1 Answer 1

3

You can use String interpolation to include value in a String.

class Test<T> {
    var value:T
    var name: String

    init(text: String, val: T) {
        name = text
        value = val
    }

    func toString() -> String {
        return "\(name): \(value)"
    }
}

Unrelated to your issue, but don't declare any of your variables as implicitly unwrapped Optionals (! after their type), especially not when you are setting them in the initializer. You should also conform to the Swift naming convention, which is UpperCamelCase for types (Test).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.