Xavier Noria
Xavier Noria

Reputation: 2324

How is == in Character defined?

I see that "é" ("\u{E9}", 1 code point), and "e" + acute ("\u{65}\u{301}", 2 code points) are equal, which is great.

The documentation of == for Character is inherited from Equatable and does not explain its rules. On the other hand, I have looked around Annex #29 without luck. Does Swift implement its own logic?

In either case, how is character equality determined in Swift?

Upvotes: 0

Views: 83

Answers (1)

David Pasztor
David Pasztor

Reputation: 54726

Since Swift is an open-source language, you can check the implementation of built-in methods on GitHub.

You can find the equality operator of Character here.

extension Character: Equatable {
  @inlinable @inline(__always)
  @_effects(readonly)
  public static func == (lhs: Character, rhs: Character) -> Bool {
    return lhs._str == rhs._str
  }
}

As you can see, internally, Character can be initialised from a String and the == operator for Character uses that internal String property to compare two Characters.

@frozen
public struct Character {
  @usableFromInline
  internal var _str: String

  @inlinable @inline(__always)
  internal init(unchecked str: String) {
    self._str = str
    _invariantCheck()
  }
}

You can find the implementation of == for String in StringComparable.swift

Upvotes: 2

Related Questions