Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

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

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

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Swift has the is operator to test the type of a value:

var onlyUILabels = myArray.filter { $0 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:

var onlyUILabels = myArray.flatMap { $0 as? UILabel }

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

var onlyUILabels = myArray.filter { $0 is UILabel } as! Array<UILabel>

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

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 { $0 as? UILabel }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...