Reynaldo Aguilar
Reynaldo Aguilar

Reputation: 1936

Strange behavior with swift compiler

I have the following function in swift:

func f() -> Int
{
    let a = String("a")
    let b = a.unicodeScalars
    println(b[b.startIndex].value)

   //return b[b.startIndex].value
   return 1
}

If I uncomment the first return statement and comment the second one, then I get the compiler error:

Could not find the member 'value'

Why this happens even when I have access to this member in the println function call?

EDIT:

In order to make the question more clear, consider the following code:

struct point {
    var x: UInt32
    var y: UInt32

    init (x: UInt32, y: UInt32) {
        self.x = x
        self.y = y
    }
}

func f () -> Int {
    var arr = [point(x: 0, y: 0)]
    return arr[0].x
}

In this case, the compiler error is:

UInt32 is not convertible to Int

My question is: Why the compiler errors are different even when the problem is the same in both cases?

Upvotes: 3

Views: 388

Answers (2)

Daniel Storm
Daniel Storm

Reputation: 18908

value returns a UInt32. Cast it to an Int.

return Int(b[b.startIndex].value)

Alternatively, you could have the function return a UInt32 as @GoodbyeStackOverflow mentions.

func f() -> UInt32

Upvotes: 2

Andrei Papancea
Andrei Papancea

Reputation: 2224

Return this instead:

return Int(b[b.startIndex].value)

The issue is that b[...].value returns a UInt32, which starting Swift 1.2 no longer converts to Int.

Upvotes: 0

Related Questions