Use optional types in Swift to perfectly solve placeholder Problems

Source: Internet
Author: User

Use optional types in Swift to perfectly solve placeholder Problems

This article mainly introduces the use of the optional types in Swift to perfectly solve the placeholder problem. This article describes how to add the objectsForKeys function for Dictionary, the simpler method in Swift, and embedded optional types, for more information, see

The optional types are newly introduced in Swift and are very powerful. In this blog post, we will discuss how to ensure the security of strong types through optional types in Swift. As an example, we create a Swift version of Objective-c api, but in fact Swift itself does not need such an API.

Added the objectsForKeys function to Dictionary.

In Objective-C, NSDictionary has a method-objectsForKeys: NoFoundMarker:. This method requires an NSArray array as the key value parameter and returns an array containing the relevant values. The document writes: "The Nth value in the returned array corresponds to the nth value in the input array". What if a key value does not exist in the dictionary? As a result, notFoundMarker is returned. For example, if the third key value is not found, the third value in the returned array is the notFoundMarker instead of the third value in the dictionary, however, this value is only used to remind the original dictionary that the corresponding value is not found, but this element exists in the returned array and notFoundMarker is used as the placeholder, because this object cannot be used directly, therefore, there is a dedicated class in the Foundation framework to handle this situation: NSNull.

In Swift, the Dictionary class does not have a function similar to objectsForKeys. To illustrate the problem, we add a function and make it a common method to operate the Dictionary value. We can use extension to implement:

The Code is as follows:

Extension Dictionary {

Func valuesForKeys (keys: [K], notFoundMarker: V)-> [V] {

// The specific implementation code will be written later

}

}

The above is our Swift version, which is very different from Objective-C. In Swift, due to its strong type, the returned result array can only contain a single type of elements, so we cannot put NSNull in the string array, but Swift has a better choice, we can return an optional type of data. All our values are packed in the optional type, instead of NSNull. We only need nil.

The Code is as follows:

Extension Dictionary {

Func valuesForKeys (keys: [Key])-> [Value?] {

Var result = [Value?] ()

Result. reserveCapacity (keys. count)

For key in keys {

Result. append (self [key])

}

Return result

}

}

A simpler method in Swift

My friends may ask why Swift does not need to implement such an API? In fact, it has a simpler implementation, as shown in the following code:

The Code is as follows:

Extension Dictionary {

Func valuesForKeys (keys: [Key])-> [Value?] {

Return keys. map {self [$0]}

}

}

The functions implemented in the preceding method are the same as those implemented in the initial method. Although the core function encapsulates the call of map, this example also shows why Swift does not provide lightweight API interfaces, this is because you can simply call map.

Next, let's experiment with several examples:

The Code is as follows:

Var dic: Dictionary = ["1": 2, "3": 3, "4": 5]

Var t = dic. valuesForKeys (["1", "4"])

// Result: [Optional (2), Optional (5)]

Var t = dict. valuesForKeys (["3", "9"])

// Result: [Optional (3), nil]

T = dic. valuesForKeys ([])

// Result: []

Embedded optional types

Now, if we call the last method for each result, what is the result?

The Code is as follows:

Var dic: Dictionary = ["1": 2, "3": 3, "4": 5]

Var t = dic. valuesForKeys (["1", "4"]). last // The result is: Optional (5 ))

// Optional ("Ching "))

Var t = dict. valuesForKeys (["3", "9"]). last

// Result: Optional (nil)

Var t = dict. valuesForKeys ([]). last

// Result: nil

My friends are confused immediately. Why are there two optional types included in the two layers ?, Especially for the Optional (nil) in the second case, what is the pace?

Let's look back at the definition of the last attribute:

The Code is as follows:

Var last: T? {Get}

Obviously, the type of the last attribute is an optional type of the array element type. In this case, because the element type is (String ?), Then, combined with the returned type, the result is String ?? This is the so-called nested optional type. But what does nested optional types actually mean?

If the above method is re-called in Objective-C, we will use NSNull as the placeholder. The call Syntax of Objective-C is as follows:

The Code is as follows:

[Dict valuesForKeys: @ [@ "1", @ "4"] notFoundMarker: [NSNull null]. lastObject

// 5

[Dict valuesForKeys: @ [@ "1", @ "3"] notFoundMarker: [NSNull null]. lastObject

// NSNull

[Dict valuesForKeys: @ [] notFoundMarker: [NSNull null]. lastObject

// Nil

Whether Swift or Objective-C, the returned value of nil indicates that the array is empty, so it does not have the last element. However, if Optional (nil) or NSNull in Objective-C is returned, the last element in the array exists, but the content of the element is null. In Objective-C, NSNull can only be used as a placeholder for this purpose, but Swift can be implemented from the perspective of language system types.

Provide a default value

Further encapsulation: If one or some elements in my dictionary do not exist, what should we do if we want to provide a default value? The implementation method is simple:

The Code is as follows:

Extension Dictionary {

Func valuesForKeys (keys: [Key], notFoundMarker: Value)-> [Value] {

Return self. valueForKeys (kes). map {$0 ?? NotFoundMarker}

}

}

Dict. valuesForKeys (["1", "5"], notFoundMarker: "Anonymous ")

Compared with Objective-C, it requires placeholders for placeholder purpose, but Swift already supports this usage at the language type system level and provides rich syntax functions. This is the strength of the optional Swift type. Note that the null Union operator? is used in the preceding example ??.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.