swift - Automatic Type Conversion with extension: What is happening here? -
i'm going through first chapter of the swift programming language
book , i'm @ part it's describing extension
keyword.
i had go @ "experiment":
“write extension double type adds absolutevalue property.”
i got working this:
extension double { var absolutevalue: double { if(self < 0) { return self * -1 } return self } } (-10.5).absolutevalue // 10.5
but seems work integers:
(-4).absolutevalue // 4.0
what happening here? compiler changing type int
double
because sees there absolutevalue
extension on double
not int
?
this appears case because if add extension
of same name on int
so:
extension int { var absolutevalue: int { return 42 } }
that overrides extension
on double
. , (-4).absolutevalue
returns 42
is there way add extension
only works on double
s not int
s?
edit: looks it's doing conversion @ compile-time , since didn't define type literal converted it. following produces error
var i:int = -4; i.absolutevalue
"playground execution failed: error: :12:1: error: 'int' not have member named 'absolutevalue' i.absolutevalue ^ ~~~~~~~~~~~~~"
edit 2: appears apply literals; following produces error:
var = -4; i.absolutevalue
yes, extension wrote double
s, not int
s. take @ example:
extension double { var absolutevalue: double { if (self < 0) { return self * -1 } return self } } var double: int = 10 double.absolutevalue // int not have member named absolutevalue
but, in code compiler implicitly converting int
double
.
Comments
Post a Comment