ios 如何在 Swift 中测试变量的类?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24097825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 00:38:46  来源:igfitidea点击:

How to test for the class of a variable in Swift?

iosswift

提问by ielyamani

I want to check if the elements of an Array are a subclass of UILabel in Swift:

我想检查 Array 的元素是否是 Swift 中 UILabel 的子类:

import UIKit

var u1 = UILabel()
u1.text="hello"
var u2 = UIView(frame: CGRectMake(0, 0, 200, 20))
var u3 = UITableView(frame: CGRectMake(0, 20, 200, 80))

var myArray = [u1, u2, u3]

var onlyUILabels = myArray.filter({"what to put here?"})

Without bridging to objective-c.

没有桥接到objective-c。

回答by Jesse Rusak

Swift has the isoperator to test the type of a value:

Swift 有一个is操作符来测试一个值的类型:

var onlyUILabels = myArray.filter { 
var onlyUILabels = myArray.flatMap { 
var onlyUILabels = myArray.filter { 
extension Array {
    func mapOptional<U>(f: (T -> U?)) -> Array<U> {
        var result = Array<U>()
        for original in self {
            let transformed: U? = f(original)
            if let transformed = transformed {
                result.append(transformed)
            }
        }
        return result
    }
}
var onlyUILabels = myArray.mapOptional { 
var (a,b,c,d) = ("String", 42, 10.0, "secondString")
let myArray: Array<Any> = [a,b,c,d]
var onlyStrings = myArray.filter({ return 
let objectClass: AnyClass = object_getClass(object) as AnyClass
let objectClassName =  NSStringFromClass(objectClass)
println("Class = \(objectClassName)")
is String }) onlyStrings // ["String", "secondString"]
as? UILabel }
is UILabel } as! Array<UILabel>
as? UILabel }
is UILabel }

As a side note, this will still produce an Array<UIView>, not Array<UILabel>. As of the Swift 2 beta series, you can use flatMap for this:

作为旁注,这仍然会产生一个Array<UIView>,而不是Array<UILabel>。从 Swift 2 beta 系列开始,您可以为此使用 flatMap:

UILabel // UILabel    
Swift._NSSwiftArrayImpl //Swift Array
MyProject.Customer_Customer_   //for a CoreData class named Customer

Previously (Swift 1), you could cast, which works but feels a bit ugly.

以前(Swift 1),您可以投射,这有效但感觉有点难看。

 return object.dynamicType == otherObject.dynamicType

Or else you need some way to build a list of just the labels. I don't see anything standard, though. Maybe something like:

否则,您需要某种方法来构建仅包含标签的列表。不过,我看不出任何标准。也许是这样的:

##代码##

回答by wottpal

In Swift you should do the iskeyword if you are wondering about the according class. In the filter-closure you can use $0to specify the first parameter.

在 Swift 中,is如果您想知道相应的类,您应该使用关键字。在filter-closure 中,您可以$0用来指定第一个参数。

Sample

样本

##代码##

回答by eharo2

Without getting to the object.class( ) nirvana, in Swift, we can still use the Objective-C Runtime to get some useful information about the object′s class as follows (and not exactly bridging to Objective-C):

没有进入 object.class() 的必杀技,在 Swift 中,我们仍然可以使用 Objective-C 运行时来获取有关对象类的一些有用信息,如下所示(并不完全桥接到 Objective-C):

##代码##

Note that we get the "MyProject." or (sometimes) the "Swift." prefix, depending if you refer to your own classes or Swift classes:

请注意,我们得到了“MyProject”。或(有时)“斯威夫特”。前缀,取决于您是指自己的类还是 Swift 类:

##代码##

回答by TheCodingArt

You may compare classes using the following in swift:

您可以在 swift 中使用以下内容比较类:

##代码##

dynamicType will return an instance of Class which you may compare

dynamicType 将返回一个您可以比较的 Class 实例