swift - Comparing optional arrays -
swift - Comparing optional arrays -
running next code snippet in playground gives error:
let a: [int]? = [1,2] allow b: [int]? = [1,2] == b // value of optional type '[int]?' not unwrapped; did mean utilize '!' or '?'?
while doing similar 'simpler' optional type works:
var x: int? = 10 var y: int? x == y // false
what reasoning behind first case, of optional arrays, not beingness allowed? why can't swift first see if either side if nil
(.none
) , if not, actual array comparison.
the reason works simpler types because there version of ==
defined optionals contain types equatable
:
func ==<t : equatable>(lhs: t?, rhs: t?) -> bool
but while int
equatable
, array
not (because might contain not equatable - in case how be). equatable
things have ==
operator, not things ==
operator equatable
.
you write special-case version of ==
optional arrays containing equatable types:
func ==<t: equatable>(lhs: [t]?, rhs: [t]?) -> bool { switch (lhs,rhs) { case (.some(let lhs), .some(let rhs)): homecoming lhs == rhs case (.none, .none): homecoming true default: homecoming false } }
you generalize cover collection containing equatable elements:
func ==<c: collectiontype c.generator.element: equatable> (lhs: c?, rhs: c?) -> bool { switch (lhs,rhs) { case (.some(let lhs), .some(let rhs)): homecoming lhs == rhs case (.none, .none): homecoming true default: homecoming false } }
swift
Comments
Post a Comment