Implicit casting in Swift

Playing with sample code from the Swift Language Guide: Extensions I have an extedned struct Double, like this

extension Double {
    func someFunc() {
        print("someFunc")
    }
}

I was surprised that this statement

2.someFunc()

did not generate a compile-time error like: A value of type 'Int' does not have a member someFunc. I was expecting the value 2 to be implicitly entered in Int, but Swift would return it in Double. Why is this? How does Swift determine that the value 2 in this case is of type Double?

Then I tried calling someFunc () like this

let x = 2
x.someFunc()

Here I get the expected compile time error

This is a controversial statement in Swift. Programming Language 3.0.1: Language Guide: Basics: Type Security and Type Output ?

, , , .

, , , Double ExpressibleByIntegerLiteral. Float . , . , Double . ? ?

struct someStruct: ExpressibleByIntegerLiteral{
    var i:Int = 0

    init(integerLiteral value: Int64){
        i = Int(value)
    }    
}

extension someStruct {
    func someFunc() {print("Somestruct someFunc") }
}

extension Double {
    func someFunc() { print("Double someFunc") }
}

4.someFunc()

//prints: Double someFunc
+4
2

, ExpressibleByIntegerLiteral. 2 leteral, , , , someFunc(), Double , .

+3

Double ExpressibleByIntegerLiteral. , , ExpressibleByIntegerLiteral, Double someFunc(), , Double 2.

, . .

+2

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


All Articles