Guess about the mechanism underlying the type inference

I tried this code in xCode: let bigNum = Int8.max + Int("1")!The compiler passes a bigNum type variable Int8and gives me an overflow error.

For Int8.max + Int("1")!: the left side "+" has a type Int8, the right side has a type Int. Why did the compiler not output bigNum as a type Int?

'S Guess : Swift-compiler always displays tye into smaller / limited types of values, as Int8is a small and narrow compared with Int, so adding Int8and Intlead to the withdrawal of type Int8.

Question : Am I right? or mostly correct, but not accurate. If yes, please correct me.

thank

+4
source share
1 answer

The type inference engine does not know the Ints bit width. He does not even know that Ints are numbers. The engine knows nothing about the "limitation" or "narrowness" of how types are implemented. He just knows how types relate to each other as supertypes and subtypes ("ISA" relationships), and tries to solve the constraint problems by figuring out what he can connect to the type variables you provided.

, +. + Int . :

public func +(lhs: Int8, rhs: Int8) -> Int8

Int8 . , , :

public func +<T : Strideable>(lhs: T, rhs: T.Stride) -> T

? An Int8 SignedInteger. SignedInteger Strideable :

public protocol Strideable : Comparable {
    associatedtype Stride : SignedNumber
    public func distance(to other: Self) -> Self.Stride
    public func advanced(by n: Self.Stride) -> Self
}

extension SignedInteger {
    public func distance(to other: Self) -> Int
    public func advanced(by n: Int) -> Self
}

- , Stride Int. , :

public func +(lhs: Int8, rhs: Int) -> Int8

, , .

BTW, , Swift , - - +. , .

+7

Source: https://habr.com/ru/post/1650409/


All Articles