0

I'm just reading through the Swift book from Apple and am a little confused about implicit conversion. In one example there is this:

let mynum: Float = 4

and then immediately after it says: "Values are never implicitly converted to another type."

Whats going on here? They just implicitly converted an Int literal into a Float and then they are saying that values are never implicitly converted? Can anyone explain what the rule/exception is here?

dgund
  • 3,459
  • 4
  • 39
  • 64
Jemar Jones
  • 1,491
  • 2
  • 21
  • 27
  • possible duplicate of ["CGFloat is not convertible to Int" when trying to calculate an expression](http://stackoverflow.com/questions/27461801/cgfloat-is-not-convertible-to-int-when-trying-to-calculate-an-expression) – matt Dec 17 '14 at 05:03
  • @matt different question – Jemar Jones Dec 17 '14 at 05:05
  • Not at all, and see my answer there: http://stackoverflow.com/a/27461821/341994 If you think that doesn't answer your question, think some more. – matt Dec 17 '14 at 05:07
  • @matt Ah, it does seem to answer my question. Yet the question asked is not clearly the same IMO. – Jemar Jones Dec 17 '14 at 05:12
  • But if you'd consulted it, you'd have gotten your answer. That's what `duplicate` is about. It means "don't ask a question you don't have to ask". :) – matt Dec 17 '14 at 05:15

1 Answers1

3

4 is not a "value". It is a literal. So it can be interpreted however Swift likes. There is nothing to "convert"; it is used to create the value, but the created value will be a Float, because that is what you asked for.

But now try this:

let i : Int = 4
let mynum: Float = i

Ooooops.

To put it another way:

let mynum: Float = 4

is interpreted as

let mynum = Float(4) // we are _creating_ the value

But if we start with i, you have to create the value:

let i : Int = 4
let mynum: Float = Float(i)

Swift won't do that for you.

BONUS LESSON Hold my beer and watch this:

struct Dog : IntegerLiteralConvertible {
    var number : Int?
    init(integerLiteral: Int) {
        self.number = integerLiteral
    }
}
let dog : Dog = 42

Float works like that, sort of.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    So only variables/constants are considered to be "value"'s? What are the rules for literals (is it documented somewhere)? – Jemar Jones Dec 17 '14 at 05:08
  • Mmmmmm, well, it's all about the `IntegerLiteralConvertible` protocol. I don't think you really want to go there.... – matt Dec 17 '14 at 05:11
  • If you get really curious, see the Swift header, where Float is extended to adopt `IntegerLiteralConvertible`. That means you can supply an Integer literal where a Float is expected, and a special corresponding `init` will be called. – matt Dec 17 '14 at 05:14
  • 1
    Ahah it would bug me if i didn't have some understanding of what is going on, i shall look it up. Thanks – Jemar Jones Dec 17 '14 at 05:16