I previously wrote a post talking about the basics and how to create a subscript for your own classes, structs...
I didn't want to extend that post too much, and I just wanted to keep it simple, with that basic example.
Now for this, let's see what else we can do using subscripts.
Subscript parameters
As you could see, the subscript signature looks just like a function, on the parameters I wrote
subscript(key: String) -> String? { ... }
And I just used my subscript like this...
jill["costume"]
But following the function rules, I should be used it like this...
jill[key: "costume"]
because I didn't add an underscore before my parameter, and functions use the parameter as parameter name when we skip it.
Well guess what? - This are subscripts not functions, this rule doesn't apply, but...
WE CAN ADD PARAMETER NAMES
and for that the rule is the same, as simple as just add the parameter name before the parameter.
subscript(key key: String) -> String? {
// ...
}
Although we could use whatever name we want, c'mon, help other developers giving good names to them.
This is not a key, it is a property of our
struct, usingpropertyas the name sounds much better don't you think?
subscript(parameter key: String) -> String? {
// ...
}
Now, our subscript will be called like this.
jill[parameter: "costume"]
But there is much more with this, Xcode is so intelligent that will be able to detect all this issues.
In case you try to access to your subscript without your parameter name, Xcode will complain
Also if you start writing inside your brackets or simply using the shortcut CTRL + Space you will see autocompletion.
Static Subscripts
Now! another thing such as functions these can be static as well.
Let's see what we care about... example!
class Service {
static subscript(key: String) -> String {
switch key {
case "production":
return "https://a-production-url.com"
case "stage":
return "https://a-stage-url.com"
case "development":
return "https://a-development-url.com"
default:
return "No URL!"
}
}
}
And we don't need an instance to use our subscript, just call it directly...
Service["production"] // "https://a-production-url.com"
Service["stage"] // "https://a-stage-url.com"
Service["development"] // "https://a-development-url.com"
Service["custom"] // "No URL!"
Nice right?
There is one more topic related I would like to cover about subscripts.
I'll try it later on and HAPPY CODING!


Top comments (0)