Skip to content

Instantly share code, notes, and snippets.

@lorentey

lorentey/shadow.swift

Last active Jul 8, 2018
Embed
What would you like to do?
The most annoying thing about Swift 3's naming conventions is that some renamed members now shadow frequently used global functions:
extension Array where Element: Comparable {
func clamp(from lowerBound: Element, to upperBound: Element) -> Array {
return self.map { min(upperBound, max(lowerBound, $0)) }
}
}
let clamped = [0, 1, 2, 3, 4, 5, 6].clamp(from: 2, to: 4))
@lorentey

This comment has been minimized.

Copy link
Owner Author

@lorentey lorentey commented Jun 2, 2016

Swift 2.2:

[2, 2, 2, 3, 4, 4, 4]

Swift 3:

shadow.swift:3:27: error: argument passed to call that takes no arguments
    return self.map { min(upperBound, max(lowerBound, $0)) }
                         ~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@lorentey

This comment has been minimized.

Copy link
Owner Author

@lorentey lorentey commented Jun 2, 2016

The problem is that Sequence has min and max methods (renamed from minElement and maxElement) that hide the global min and max functions. The straightforward workaround is to prefix the global names with their module name, i.e., to use Swift.max and Swift.min.

@erica

This comment has been minimized.

Copy link

@erica erica commented Jun 2, 2016

Again, this is more a bug report territory than "the language has changed, how do I do things the new way". :(

@resuna

This comment has been minimized.

Copy link

@resuna resuna commented Jun 30, 2016

Just got bit by this one.

Renaming “minElement” and “maxElement” to “min” and “max” was well-intentioned, but having to write Swift.min(Int, Int) is not an improvement.

@accountidentifier

This comment has been minimized.

Copy link

@accountidentifier accountidentifier commented Jul 8, 2018

extension Collection {
@inline(_always) public func max( x: T, _ y: T) -> T where T : Comparable { return Swift.max(x,y) }
@inline(_always) public func min( x: T, _ y: T) -> T where T : Comparable { return Swift.min(x,y) }
}

Seems to compile, but yuck.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment