Home > Enterprise >  Swift generics: How to represent 'no type'?
Swift generics: How to represent 'no type'?

Time:10-05

I am using Google's promises library, and I would like to create promise without any type (because I don't need any).

However, I am being forced to pick some type:

let promise = Promise<SomeType>.pending()

Is there a type I could pass in place of SomeType that would essentialy mean 'no type', when I need promises just for async flow and exception catching, but I don't want to return a specific value from a function? For example, some type whose only valid value is nil?

I have encountered this problem in multiple places, the only workaround I found so far is to always provide a non-generic alternative, but it gets really tedious and leads to duplicate code.

CodePudding user response:

Types are sets of values, like Int is the set of all integer numbers, String is the set of all sequences of characters and so on.

If you consider the number of items in the set, there are some special types with 0 items and 1 items exactly, and are useful in special cases like this.

Never is the type with no values in it. No instance of a Never type can be constructed because there are no values that it can be (just like an enum with no cases). That is useful to mark situations, code flow etc as 'can't happen', for example the compiler can know that a function that returns Never, can never return. Or that a function that takes Never can never be called. A function that returns Result<Int, Never> will never fail, but is in the world of functions returning Result types. But because never can't be constructed it isn't what you want here. It would mean a Promise that can't be fulfilled.

Void is the type with exactly 1 value. It's normally spelled () on the left and Void on the right, of a function definition. The value of a void is not interesting. It's useful to make a function that returns Void because those are like what other languages call subroutines or procedures. In this case it means a Promise that can be fulfilled but not with any value. It can only be useful for its side effects, therefore.

CodePudding user response:

Is it a correct solution or a workaround if we create an empty class

class Default_Class : Codable {

}

and use this as Promise<Default_Class>.pending

  • Related