简体   繁体   中英

Int is not convertible to T

I have the following protocol

public protocol NumericType {
    static func +(lhs: Self, rhs: Self) -> Self
    static func addWithOverflow(_ lhs: Self, _ rhs: Self) -> (Self, overflow: Bool)
}

Also I am extending Int to conforms to it as follows

extension Int : NumericType { }

Then I have a struct with the following definition

struct State<T:NumericType>  {

    let current : T

    init(current : T) {

        self.current = current
    }

    static func initial() -> State<T> {

        return State(current: 0) // Int is not convertible to T
    }
}

NumericType does not promise that it is ExpressibleByIntegerLiteral , so there's no way to convert 0 (which is assumed to be an Int here) to T . Your protocol needs to provide some .zero that it knows it can initialize with (or it needs to conform to ExpressibleByIntegerLiteral ).

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