泛型和Swift中的AnyObject之间的区别 [英] Difference between Generics and AnyObject in Swift

查看:194
本文介绍了泛型和Swift中的AnyObject之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个 myFilter 函数,它接受一个泛型参数并根据谓词过滤数组。这与Swift提供的 filter()函数相同。

  FUNC myFilter< T>(来源:[T],​​谓词:(T) - >布尔) - > (T){
var result = [T]()
for source {
if predicate(i){
result.append(i)
}
}
返回结果
}



  func myFilter(source:[AnyObject],predicate:(AnyObject) - > Bool) - > {
如果谓词(i){
result.append(i)
} {
var result = [AnyObject]()

}
返回结果
}

我们没有达到甚至在后面的例子中泛型的点?

解决方案

泛型是类型安全的,这意味着如果您将字符串作为泛型传递并尝试作为整数使用,编译器会抱怨你将无法编译你的(这是很好的)。 (发生这种情况是因为Swift使用静态类型,并且能够为您提供编译器错误

如果使用AnyObject,编译器不知道该对象是否可以被当作字符串或整数。它会让你做任何你想做的事情(这是坏的)。



例如。如果您尝试在 时传递字符串,那么您以前使用的Integer会导致应用程序崩溃。 (发生这种情况是因为Swift使用动态类型,并且将 给你一个运行时崩溃



泛型基本上告诉编译器:


我要去稍后再给你一个类型,我希望你在我指定的任何地方执行那个
类型




不要担心这个变量否需要在这里执行任何类型让我做任何我想做的事。



Consider this myFilter function that takes in a generic argument and filters the array based on the predicate. This is same as the filter() function provided by Swift.

func myFilter<T>(source: [T], predicate:(T) -> Bool) -> [T] {
  var result = [T]()
  for i in source {
    if predicate(i) {
      result.append(i)
    }
  }
  return result
}

How is this different from,

func myFilter(source: [AnyObject], predicate:(AnyObject) -> Bool) -> [AnyObject] {
  var result = [AnyObject]()
  for i in source {
    if predicate(i) {
      result.append(i)
    }
  }
  return result
}

Aren't we achieving the point of generics even in the latter example?

解决方案

Generics are type safe, meaning if you pass a string as a generic and try to use as a integer the compiler will complain and you will not be able to compile your (which is good). (This happens because Swift is using Static typing, and is able to give you a compiler error)

If you use AnyObject the compiler has no idea if the object can be treated as a String or as an Integer. It will allow you to do whatever you want with it (which is bad).

e.g. if you try to pass a String when it the your previously used Integer the application will crash. (This happens because Swift is using Dynamic typing and will only give you a runtime crash)

Generics basically tells the compiler:

"I am going to give you a type later and I want you to enforce that type everywhere I specify."

AnyObject basically tells the compiler:

"Don't worry about this variable no need to enforce any type here let me do whatever I want to."

这篇关于泛型和Swift中的AnyObject之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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