简体   繁体   中英

How to check a generic type can be converted to String in swift

How to check the Generic type can be converted to String ? Like below,

class Stack<T> {
    var values = [T]()

    func debugPrint() {
        values.map {
          String($0) // How to check if $0 can be converted to String?
        }
    }
}

If you want your class to handle only types that can be casted to a String then change the generics definition so that T conforms to LosslessStringConvertible

class Stack<T:LosslessStringConvertible> 

If on the other hand you are only interested in getting a string for printing then you can use String(describing:)

 values.map {
    String(describing:$0)
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM