‘some’ and ‘any’ in Swift

Updated 12 August 2022

Save

We will be learning how we can use ‘some’ and ‘any’ in Swift.

‘some’ keyword was introduced in 5.1 however, the ‘any’ keyword was introduced in Swift 5.6

In Swift 5.7 we can use these two keywords in the function’s parameter position.

So let’s discuss in detail regarding these keywords.

Initial steps

Here is an example code snippet of how we can use the ‘some’ and ‘any’ keywords with functions.

Above all, let’s define a protocol as mentioned in the above code snippet.

Now we will define the struct that uses the AnyProtocolName protocol as below.

Please be noted that the data types of the anyStructOne and anyStructTwo are different, which are anyStructThree & anyStructFour

Using ‘some’ and ‘any’ in Swift

‘some’ keyword

We can use the ‘some’ keyword in the function’s parameter position which is the same as making the function generic. However, it is used together with a protocol to create an opaque type that represents something that is conformed to a specific protocol.

In addition, ‘some’ keyword can be used with variables as described below.

Here, we are telling the compiler that we are working on a specific concrete type.

So it will throw a compile time error when we change the type.

‘any’ keyword

In Swift 5.6, the ‘any’ keyword is not mandatory when creating an existential type, but in Swift 5.7, you will get a compile error.

Here is an example of how we can use the ‘any’ keyword.

Unlike the ‘some’ keyword we can use ‘any’ keyword for protocols with associated types.

References

If you want to learn more please visit here

Please visit my other blogs here.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home