Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Last active March 30, 2018 15:29
Show Gist options
  • Save jayrhynas/806a461a92bf2589ea02f6c72048bffc to your computer and use it in GitHub Desktop.
Save jayrhynas/806a461a92bf2589ea02f6c72048bffc to your computer and use it in GitHub Desktop.
struct InoutIUO {
static func f<T>(_: inout T) {
print("f<T>(T)")
}
static func f<T>(_: inout T?) {
print("f<T>(T?)")
}
static func f<T>(_: inout Array<T>?) {
print("f<T>(Array<T>?)")
}
// warning: invalid redeclaration of 'f' which differs only by the kind of optional passed as an inout argument ('Array<T>!' vs. 'Array<T>?')
// note: overloading by kind of optional is deprecated and will be removed in a future release
static func f<T>(_: inout Array<T>!) {
print("f<T>(Array<T>!)")
}
}
struct InoutOpt {
static func f<T>(_: inout T) {
print("f<T>(T)")
}
static func f<T>(_: inout T?) {
print("f<T>(T?)")
}
static func f<T>(_: inout Array<T>?) {
print("f<T>(Array<T>?)")
}
}
struct Normal {
static func f<T>(_: T) {
print("f<T>(T)")
}
static func f<T>(_: T?) {
print("f<T>(T?)")
}
static func f<T>(_: Array<T>?) {
print("f<T>(Array<T>?)")
}
}
var a: [Int]! = [1]
InoutIUO.f(&a) // calls f<T>(Array<T>!)
InoutOpt.f(&a) // calls f<T>(T)
Normal.f(a) // calls f<T>(Array<T>?)
var i: Int! = 1
InoutIUO.f(&i) // calls f<T>(T)
InoutOpt.f(&i) // calls f<T>(T)
Normal.f(i) // calls f<T>(T?)
@jayrhynas
Copy link
Author

With the release of Xcode 9.3/Swift 4.1, you no longer need to provide two overloads of a function to handle different types of optionals.

Passing different kinds of optionals (? or !) to a function as inout no longer requires overriding that function. (36913150)

That, combined with SR-6685, means that old code that had both overloads now prints a warning message:

warning: invalid redeclaration of 'f' which differs only by the kind of optional passed as an inout argument ('Array<T>!' vs. 'Array<T>?')
note: overloading by kind of optional is deprecated and will be removed in a future release

However, in this case where there is a specific overload for arrays, removing the IUO overload of the function changes which function gets called. When passed an optional array, the normal function calls the array-specific overload, but the inout function calls the generic T overload.

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