简体   繁体   中英

Why CustomStringConvertible protocol not working for Int?

public func +<T: CustomStringConvertible>(lhs: T, rhs: T)->String{
    return lhs.description+rhs.description
}

let a:String = "A"

let i:Int = 0

print(a+i)

I am overloading '+' operator for CustomStringConvertible types. String and Int both confirms CustomStringConvertible protocol but it gives an error: "binary operator '+' cannot be applied to operands of type 'String' and 'Int' print(a+i)". It working fine when I apply it to 'String'+'NSNumber'. don't know what is going behind the scene. why it is not working?

The problem is firstly (believe it or not) String doesn't conform to CustomStringConvertible . You'll therefore want to conform it yourself in order for it to return self for description (probably easier than writing another overload to deal with strings independently).

extension String:CustomStringConvertible {
    public var description: String {
        return self
    }
}

Secondly, you need two generic parameters for your + overload, in order to allow it to accept different types for both parameters, while ensuring that both parameters conform to CustomStringConvertible :

public func +<T: CustomStringConvertible, U:CustomStringConvertible>(lhs: T, rhs: U)->String{
    return lhs.description+rhs.description
}

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