comparison Non-Optional and Optional without unwrap

This code work:

let one: Int ? = 5
let two = 5
let result = one == two

print ( result )

//print true
Why we can access to Optional value without unwrap within comparison operations?

···

--
Седых Александр

1 Like

The 'one' value isn't being unwrapped; the 'two' value is being wrapped in an optional, and then compared. In effect, it's doing:

let result = one == Optional(two)

This allows you to pass in non-optional values to functions that take optional arguments, e.g.

func printme(_ i:Int?) { print("\(i)") }

printme(one)
printme(two)

Alex

···

On 18 Oct 2016, at 09:58, Седых Александр via swift-users <swift-users@swift.org> wrote:

This code work:

let one: Int? = 5
let two = 5
let result = one == two

print(result)

//print true

Why we can access to Optional value without unwrap within comparison operations?

1 Like

Because the comparison function “==“ has the signature:

func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool

An optional parameter accepts non-optionals. In a sense non-optionals are “promoted” to optionals when used for an optional parameter.

Rien.

···

On 18 Oct 2016, at 10:58, Седых Александр via swift-users <swift-users@swift.org> wrote:

This code work:

let one: Int? = 5
let two = 5
let result = one == two

print(result)

//print true

Why we can access to Optional value without unwrap within comparison operations?

--
Седых Александр
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

1 Like