Enforce function parameter must be optional - swift

I have a custom operator ?= that is used to simply assign optional values to non-optionals.
var a: String
let b: String?
a = b ?? a
// is simplified to
a ?= b
This works well, but I don't want people to be able to use this operator when b is not optional. It's not going to cause any problems but it looks bad and I don't like it.
My function signature is currently:
func ?=<T> (originalValue: inout T, optionalNewValue: T?)
How could I make this cause a compiler warning or error when optionalNewValue is not actually an optional?

As other have said in the comments, the ?= operator might not be the best solution to your problems. Now if you're keen to that operator, or adds value to your code base, then there is a workaround that would allow you to reject non optional values on the right hand side of the operator.
You can use an OptionalCompatible protocol for the right hand side of the operator:
protocol OptionalCompatible {
associatedtype Wrapped
var optionalValue: Wrapped? { get }
}
extension Optional: OptionalCompatible {
var optionalValue: Wrapped? { return self }
}
func ?=<T, U> (originalValue: inout T, optionalNewValue: U) where U: OptionalCompatible, U.Wrapped == T {
originalValue = optionalNewValue.optionalValue ?? originalValue
}
Using a custom protocol will disable the auto-promotion of non-optionals to optionals, allowing only optionals to be used.
There is a caveat, though: in theory the conformance OptionalCompatible can be added to any type.

How could I make this cause a compiler warning or error when optionalNewValue is not actually an optional?
You cannot. It is a built-in fact of Swift that a nonOptional of type T can always be assigned or passed where an Optional<T> is expected.

Related

Swift Protocol Optional conformance via Non-Optional

I have a protocol with an optional property.
Most of the types that conform to this protocol will have a matching optional property. However, one has a non-optional property of the same type and name.
protocol SomeProtocol {
var foo: Int? { get }
}
struct StructA: SomeProtocol {
let foo: Int?
}
struct StructB: SomeProtocol {
let foo: Int // Type 'StructB' does not conform to protocol 'SomeProtocol'
}
Pressing Xcode's "Fix - Do you want to add protocol stubs?" button adds the optional version of the property, but the structure now has invalid duplicated variable names:
struct StructB: SomeProtocol {
let foo: Int
var foo: Int? { return foo } // Invalid redeclaration of 'foo'
}
In the { get }-only case, I had assumed that this would "just work" due to the non-optional always satisfying the constraints of the optional, similar to how you can return a non-optional in a function with an optional return type. But apparently that is not the case.
This works the same for functions as well; a protocol's func bar() -> Int? is not satisfied by a conforming type declaring func bar() -> Int.
Is there any way around this issue? I would prefer not to rename the variables or add intermediate getters.
Has this situation been considered for Swift? What is the rational for not allowing a non-optional to satisfy an optional protocol variable?
If the protocol provides a default implementation that returns an optional:
protocol SomeProtocol {
var foo: Int? { get }
}
extension SomeProtocol {
var foo: Int? { return nil }
}
protocol-conforming types can then provide an overriding non-optional version of the variable/function:
struct StructB: SomeProtocol {
let foo: Int
}
I found this discussed on the Swift Evolution forum:
At the first glance I thought there is a rule that allows us to satisfy protocol requirements with non-optional types, but this resulted in an error. Only after further investigation I noticed that a default implementation must exist in order to 'kind of override' the requirement with a non-optional version.
https://forums.swift.org/t/how-does-this-rule-work-in-regard-of-ambiguity/19448
This Swift team also discusses allowing non-optional types to satisfy optional-value protocols:
Would it make any sense to allow protocol requirement satisfaction with non-optional types, like with failable init's? (Probably with some implicit optional promotion.)
Yep, totally! Except for the part where this changes the behavior of existing code, so we'd have to be very careful about it. This is considered part of [SR-522] Protocol funcs cannot have covariant returns
which is tracked on Stack Overflow here:
Why can't a get-only property requirement in a protocol be satisfied by a property which conforms?
The extension-with-default-implementation solution offered by pkamb is helpful in terms of getting the compiler to recognize conformance, but you need to be aware of the strange behavior this can produce.
An object of the newly conforming type will return a different value depending on what type you cast it to (this also includes passing as to a parameter whose type is the protocol):
let bar = StructB(foo: 7)
let baz: SomeProtocol = bar
bar.foo // evaluates to 7
baz.foo // evaluates to nil (surprise!)
As someone recently commented on a related Swift bug ticket: "This can be quite surprising and perhaps could be considered a bug of its own?"
It definitely tripped me up.

About variable type in Swift

I understand the difference between String! type and String? type. But what about String type? How does it differs from String! and String? in swift? Does String! type identical to String type?
Say, I have a class like this:
class Person {
private var _name: String!
var name: String {
return _name
}
init(name: String) {
_name = name
}
}
There is no compiler error, looks like String type is identical to String! type. But I am not sure...
String and String! are not identical. There is just happens to be enough sugar in the language to convert between them. Similarly there is sugar in the language to convert between String and String? (but not in reverse).
Start with the basics. There is String. Unless there is some strong reason, you should use String when you mean a string of characters. Everything else is "more stuff" and you shouldn't add it unless you need it.
There is Optional<String>. This is just an enum with two cases, one with a value, and one without a value:
public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
case None
case Some(Wrapped)
// ...
}
There is a postfix operator ! for Optional which will return Wrapped if it's available, and crash if it is not. So far, no magic. This is stuff you could build yourself.
There are are few pieces of magic around Optional. First, the type Wrapped? is magically converted to Optional<Wrapped> by the compiler (for any Wrapped). This is just syntactic sugar. The two notations are identical. Second, there is optional-chaining with the ?. "operator" (it's not really an operator; it's part of the language and you couldn't build it yourself). And then there's optional promotion. Any type Wrapped can be automatically and implicitly converted to Wrapped? if needed. There are are few other pieces of magic around Optional like if-let syntax, and there's nil which is a synonym for Optional.None (I believe they're actually identical). But Optional really is just a generic type, implemented as an enum. It's just a type the compiler knows special things about.
Then there is ImplicitlyUnwrappedOptional<Wrapped>. This is also just an enum (in Swift 2.2; this will change in Swift 3).
public enum ImplicitlyUnwrappedOptional<Wrapped> : _Reflectable, NilLiteralConvertible {
case None
case Some(Wrapped)
// ...
}
This is not the same as Optional and it is not the same as Wrapped. It's a completely different type. But it also has some magic associated with it. First, the type Wrapped! is syntactic sugar for ImplicitlyUnwrappedOptional<Wrapped>. Again, it's just sugar. The two are the same (in Swift 2.2, not in Swift 3). Next, if IUO<Wrapped> is found in a place that Wrapped is expected, it will automatically be converted to Wrapped or crash if there is no value. If it is found in a place that Wrapped? is expected, it will automatically be converted to Wrapped?. Those are magical, and it's why sometimes String and String! seem to be the same type. That's just the compiler magically "making it work" for you by adding an invisible conversion step. It doesn't mean they're really the same type.
IUO is mostly useful in bridging to certain Objective-C patterns, especially involving Storyboards, and should be avoided outside of those situations. Even in those situations, IUO is just there for convenience. You could do all the same things using regular Optionals, you'd just have to check them with if-let more often. Using Optionals is much safer than using IUO. It's easy to think "I know for certain this value will always be set before it is used." And just this week I chased down a crasher due to being wrong about that. There's a difference between "it should be" and "it must be." But, being totally safe with Optionals in Storyboards could be very inconvenient and might mask some bugs (by doing nothing rather than crashing), so that's the most common place for IUO.
IUO properties used to be valuable for dealing with failable init methods. That's no longer a problem in Swift 2.2, so that use has gone away. The last "pure Swift" use that I run into is when you must pass self to the initializer of something you store as a property (you can't pass self at that point because all your properties have been initialized). That's an unfortunate use-case and very messy, and I hope we come up with a fix for it. Outside of these kinds of cases, you should avoid Implicitly Unwrapped Optionals.
String and String! are same and different at the same time. If you declare let or var as String, you will have to set some value at init method. If you declare it as String! you can set value when you want but you must do it before reading this value.
So, if your _name will be nil, your app will crash.
If you declare it as String, compiler guarantees that _name != nil before the first reading. If you declare it as String!, you should guarantee it.
This things have same type because of this:
var test1: String = "test"
var test2: String! = "test"
if test1 is String { // True
print("test1 is String")
}
if test2 is String { // True
print("test2 is String")
}
This types are equal but this things are different
Note the difference between these two functions:
func f() {
let x: String? = nil
guard let y: String = x else {
print("failed")
return
}
}
func g() {
let x: String? = nil
guard let y: String! = x else {
print("failed")
return
}
print(y.dynamicType, y)
}
f() # failed
g() # Optional<String> nil
You are better to read swift documentation than any answer here. Properly undestandig swift's type system is very important, so do it first.
both String! and String? are optional types.
Using String? requires you to test whether the value is nil (.None) or a value (.Some). For example using guard statements or if-let clauses.
String! is an optional that is assumed to be non-nil and is unwrapped automatically. This allows you to write cleaner-looking code and avoid unwrapping wherever the value is used. BUT: if your value is nil a fatal error will occur.

How to use Equatable protocol on two objects of an unknown type?

Say I have two variables, and I don't know what type they are (and it's not possible to know what type they are until runtime):
var a: Any
var b: Any
How can I test if they are equal, using the Equatable protocol? I can't just do a == b because that requires that both of the items are the same, Equatable type, and the compiler can't prove that because they could be different types (and one or both might not even be Equatable).
So, is it possible to tell the compiler to check if they both have the same type, and if that type conforms to Equatable, then to use the == operator on them and return the result, otherwise returning false?
If there is no way to do this, is there a good reason Swift prevents this, or is it a current limitation of Swift that could be fixed in the future?
Under the assumption that if a and b differ in type then they are never equal, you can use a generic function with constraint to achieve the goal.
func isEqual<T : Equatable>(a: T, b: T) -> Bool {
return a == b;
}
You cannot have a and b differ in type, as the Equatable protocol assumes that the LHS and RHS of the comparison are of the same type. This seems a reasonable constraint, but one can certainly write a notion of equality that doesn't require this. In these cases, you'll need your own equality protocol.
You use generics and function overload:
func isEqual<T: Equatable>(a: T, b: T) -> Bool {
return a == b
}
func isEqual<T, U>(a: T, b: U) -> Bool {
return false
}
If both variables have the same type, as that type conforms to Equatable, then the compiler will choose the first function, otherwise will go the second one.
This will work for Objective-C objects too, providing you cast to NSObject before calling the function: isEqual(var1 as? NSObject, var2 as? NSObject)

Why doesn't swift infer the appropriate overload function with a generic return argument without a type constraint?

Note
Swift is changing rapidly, this question was asked regarding:
Xcode 7, Swift 2.0
Explanation
I'm looking to implement a generic return argument. Quite often, I find it necessary to implement an optional version overload so I can access the underlying type and handle it appropriately. Here's some manufactured functions. The assignment of String is just there as a placeholder for replication:
func ambiguous<T>() -> T {
let thing = "asdf"
return thing as! T
}
func ambiguous<T>() -> T? {
return nil
}
Now, if we look at the implementation:
// Fine
let a: String = ambiguous()
// Ambiguous
let b: String? = ambiguous()
This might seem obvious because you could assign type T to a variable of type T?. So it makes sense that it would have trouble inferring. The problem is, that with a type constraint, it suddenly works. (This can be anything, I'm using Equatable for easy replication.
func nonAmbiguous<T : Equatable>() -> T {
let thing: AnyObject = "asdf"
return thing as! T
}
func nonAmbiguous<T : Equatable>() -> T? {
return nil
}
And now, it functions as expected:
// Fine
let c: String = nonAmbiguous()
// Fine
let d: String? = nonAmbiguous()
Note, this also works with other type:
func nonAmbiguous<T>() -> [T] {
let thing: AnyObject = ["asdf"]
return thing as! [T]
}
func nonAmbiguous<T>() -> [T]? {
return nil
}
// Fine
let e: [String] = nonAmbiguous()
// Fine
let d: [String]? = nonAmbiguous()
Question:
Is there a way to have a return generic argument infer the appropriate overload through optionality?
if no
Is this a language feature, or a bug somewhere. If it's a language feature, please explain the underlying issue preventing the possibility of this behavior.
The first example is ambiguous because T can be inferred as both String
and String?.
The second example is not ambiguous because String is Equatable but String? is not, so T : Equatable cannot be inferred as String?.
The third case is not ambiguous because [T] is not
inferred as [String]?.
Remark: Generally, Optional<Wrapped> does not conform to Equatable
even if Wrapped does, in the same way as Array<Element>
does not conform to Equatable even if Element does.
This is a restriction of the current type system in Swift which
might be improved in a future version, compare
[swift-dev] RFC: Adding Optional variants of == for collections to the std lib.
from the Swift development mailing list.

Incrementing an implicitly unwrapped optional

I declare an implicitly unwrapped optional as:
var numberOfRows: Int!
and initialize it in init:
numberOfRows = 25
Later I need to decrement it by one so I write:
numberOfRows--
but this doesn't compile. The error message says the decrement operator can't be applied to an implicitly unwrapped optional. With a little experimentation I find that the following compiles without error:
numberOfRows!--
I would like to understand this. What is the explanation for what seems like the extra '!'?
Implicitly unwrapped optional is a type on its own, and is different from the type it that wraps. Some operators on optionals and implicitly unwrapped optionals are pre-defined for you out of the box by the language, but for the rest you have to define them yourself.
In this particular case an operator postfix func --(inout value: Int!) -> Int! is just not defined. If you want to use postfix -- operator on Int! just the same way you use it on Int then you will have to define one.
E.g. something like:
postfix func --<T: SignedIntegerType>(inout value: T!) -> T! {
guard let _value = value else { return nil }
value = _value - 1
return _value
}
If we look at what the optional type is, we will see that this is enum like:
enum Optional<T> {
case Some(T)
case None
}
And it can be Some Type like Int for example or None and in this case it's have nil value.
When you make this:
var numberOfRows: Int!
you directly is indicated by the ! that this is not Int type but this is the enum Optional<Int> type. At moment of creation it's will be Some<Int> if equal it value but with this ! you have that it is enum Optional<Int> and in some next moment it will be the None. That's why you have to use ! second time when make this:
numberOfRows!--
Your nomberOfRows value is Optional<Int> type and it may be Int or nil and you have to directly indicate that this is Int type to make -- action.