What is the fastestEncoding property of a string in Swift?

Overview

The fastestEncoding property returns the fastest encoding to which the string may be converted without loss of information.

Syntax

string.fastestEncoding

Return value

This property returns an encoding which is the fastest encoding to which the string may be converted without loss of information.

Code example

// import Foundation
import Foundation
// creates some string values
let str1 = "Welcome"
let str2 = "to"
let str3 = "Edpresso!"
// get all encodings present
print(String.availableStringEncodings)
// get fastest encoding
print(str1.fastestEncoding)
print(str2.fastestEncoding)
print(str3.fastestEncoding)

Explanation

  • Line 2: The Foundation framework was imported.
  • Lines 5 to 7: String values were created.
  • Line 10: Using the availableStringEncodings property of the String class, we printed all available string encodings.
  • Lines 13 to 15: The fastestEncoding property of the strings were gotten and printed to the console. Remember that this property returns the fastest encoding to which a string can be converted to without loss of information.

The UTF-16 differs from other encodings because it uses a minimum of 2 bytes to represent a character in memory.

Free Resources