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

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

问题描述

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

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
}

这与,

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?

推荐答案

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

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)

如果您使用 AnyObject,编译器不知道该对象是否可以被视为字符串或整数.它可以让你为所欲为(这很糟糕).

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).

例如如果您尝试传递一个字符串 when 它是您以前使用的整数,则应用程序将崩溃.(发生这种情况是因为 Swift 使用动态输入,并且只会给你一个运行时崩溃)

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)

泛型基本上告诉编译器:

我稍后会给你一个类型,我希望你强制执行那个在我指定的任何地方输入."

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

AnyObject 基本上告诉编译器:

不要担心这个变量这里不需要强制任何类型让我做我想做的任何事情."

"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天全站免登陆