Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

ios - Strange generic function appear in view controller after converting to swift 3

In my project, after converting to swift 3, a new function appeared before my ViewController class:

fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
   switch (lhs, rhs) {
  case let (l?, r?):
    return l < r
  case (nil, _?):
    return true
  default:
    return false
  }
}

What does this function do? Why do I need it?

question from:https://stackoverflow.com/questions/39251005/strange-generic-function-appear-in-view-controller-after-converting-to-swift-3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That is interesting. Before the latest Swift 3, you could compare optional values, for example

let a: Int? = nil
let b: Int? = 4

print(a < b) // true

and nil was considered less than all non-optional values.

This feature has been removed (SE-0121 – Remove Optional Comparison Operators) and the above code would fail to compile in Xcode 8 beta 6 with

error: value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?

Apparently, the Swift migrator solves that problem for you by providing a custom < operator which takes two optional operands and therefore "restores" the old behavior.

If you remove that definition then you should see where the comparison is done in your code. Then try to update your code and remove the optional comparisons.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...