转换为swift 3后,奇怪的通用函数出现在视图控制器中 [英] Strange generic function appear in view controller after converting to swift 3

查看:170
本文介绍了转换为swift 3后,奇怪的通用函数出现在视图控制器中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,转换为swift 3后,在我的 ViewController 类之前出现了一个新函数:

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?

推荐答案

这很有趣。在最新的Swift 3之前,您可以
比较可选值,例如

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

nil 被认为低于所有非可选值。

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

此功能已被删除(SE-0121 - 删除可选的比较运算符)和上面的代码将无法在Xcode 8 beta 6中编译

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 '?'?

显然,Swift迁移器通过
解决了这个问题,提供了自定义< 运算符,它带有两个可选的操作数
,因此恢复旧的行为。

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.

这篇关于转换为swift 3后,奇怪的通用函数出现在视图控制器中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆