Frontmost window of the current application that passes a predicate check
There is a way of improving the code as desired in that it is possible to constrain the type T to T: NSWindow. Upon introducing this change, however, the function will indeed return the first NSWindow in the current ordering, whether or not it is of subtype T (too check this you must construct a test that can actually fail, i.e. by having an NSWindow of a another type above the window you are looking for - e.g. by adding a status item to your app). There is a workaround, however, as described in Optional binding succeeds if it shouldn't. Apart from the solution I stumbled upon in the question (of not constraining T), there is a much preferable option discovered by @vacawama in the answer to the linked question. The workaround is to generalise the variable to Any before type checking, e.g. as follows:

public func frontmost &lt;T: NSWindow&gt; (windowOfType: T.Type) -&gt; T? {
    return frontmostWindow { $0 as Any is T } as? T
}


This improves the api considerably.