ref – http://chineseruleof8.com/code/index.php/2017/02/01/swift-3-0-constants-and-variables/
Non-optional parameters
1) You cannot force unwrap a non-optionals. There’s nothing to unwrap because it is not an optional.
1 2 3 4 |
// parameter constant String type private func test(myParam: String) -> String{ return myParam! // error } |
2) You cannot use optional chaining on non-optionals variables because optional chaining can only be done on optional variables
1 2 3 4 |
// parameter constant String type private func test(myParam: String) -> String{ return myParam? // error } |
3) You CAN use the non-optional variable as is:
1 2 3 4 5 6 7 |
// parameter constant String type private func test(myParam: String) -> String{ return myParam // correct } let res = test(myParam: "ricky") print(res) |
result:
ricky
Optional parameters
1) You CAN use force unwrap, as it means you are sure that the optional is non-nil, and you are using a short-hand to unwrap it.
In other words, Optional is an enum where its two attributes are None, and Wrapped(your value). By using ‘!’, you are unwrapping the value object.
1 2 3 4 |
// parameter optional String type private func test2(myParam: String?) -> String { return myParam! //correct } |
2) You CAN use ‘?’ on the parameter to indicate that you want to use optional chaining. Optional Chaining is simply a way for you to chain access of the Wrapped object and call a property or method on it.
In other words, Optional is an enum where its two attributes are None, and Wrapped(your value). By using ‘?’, you are accessing Wrapped(your value), and thus be able to get to the Wrapped(..)
However, you still need to access the object/value inside that Wrapped, and that’s why you have to use ‘!’ on the outside.
1 2 3 |
private func test2(myParam: String?) -> String { return (myParam?.appending("haha"))! //correct } |
3) You cannot simply use the parameter like this. Optional parameters need to be unwrapped before you can access its value object.
1 2 3 |
private func test2(myParam: String?) -> String { return myParam } |
Implicity Unwrapped Optional parameters
You CAN use the parameter name as is because implicit unwrapped optional means you are sure it is not nil.
1 2 3 |
private func test3(myParam: String!) -> String { return myParam } |