What is string.hash in Swift?

Overview

The hash property of a string returns an unsigned integer that can be used as a hash address.

Syntax

string.hash

Return value

This value returns an unsigned integer value.

Example

Let’s look at the code below:

// import Foundation
import Foundation
// create string values
let name = "Edpresso"
let role = "Learning Platform"
let author = "Theodore"
let badge = "Gold"
// get hash and print results
print(name.hash)
print(role.hash)
print(author.hash)
print(badge.hash)

Explanation

  • Line 2: We import the Foundation framework. It allows us to access a String instance’s hash property and lots more.
  • Lines 5 to 8: We create some string values.
  • Lines 11 to 14: We get the hash of each string using the hash property and the results are printed to the console.

Free Resources