I am recently learning the source code of the Bool type in Swift. I have defined a Coin structure (shows below) imitating the source code. Similar to Bool, there are two values of true and false. I want to assign two values to Coin, on and off. It is hoped that the following effects can be achieved during initialization:
let coin = on
However, it is obviously not possible now, what can I do to achieve a direct initialization method like
let display = false?
At the same time, I also want to know where the two reserved keywords, false and true, are defined. I didn't find any relevant content in the Bool.swift file. I hope you can guide me.
The Coin structure is defined below:
public protocol ExpressibleByCoinLiteral {
associatedtype CoinLiteralType: _ExpressibleByIntCoinLiteral
init(coinLiteral value: CoinLiteralType)
}
public protocol _ExpressibleByIntCoinLiteral {
init(_intCoinLiteral value: Int)
}
public struct Coin {
public var _value: Int
public init() {
self._value = 0
}
@_transparent
public init(_ value: Int) {
self._value = value
}
@inlinable
public init(_ value: Coin) {
self = value
}
}
extension Coin: _ExpressibleByIntCoinLiteral, ExpressibleByCoinLiteral {
public init(_intCoinLiteral value: Int) {
self._value = value
}
@_transparent
public init(coinLiteral value: Coin) {
self = value
}
}
extension Coin: LosslessStringConvertible {
public init?(_ description: String) {
if description == "on" {
self = on
} else if description == "off" {
self = off
} else {
return nil
}
}
}
ibex10
2
They are the tokens for Boolean literals, defined in Token.h (C++):
#ifndef SWIFT_TOKEN_H
#define SWIFT_TOKEN_H
#include "swift/Basic/SourceLoc.h"
#include "swift/Basic/LLVM.h"
#include "swift/Parse/Token.h"
#include "swift/Config.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
namespace swift {
enum class tok : uint8_t {
#define TOKEN(X) X,
#include "swift/AST/TokenKinds.def"
NUM_TOKENS
};
...
Note that Token.h defines the TOKEN macro and then includes the file TokenKinds.def, which defines a bunch of macros for different kinds of token.
1 Like
Possibly you're just playing around in order to learn the stdlib implementation, in which case disregard this. But if you are actually trying to implement this in your (non-stdlib) code, then the canonical way to do this is:
enum State {
case on
case off
}
let coin = State.on
// Or equivalently:
let coin: State = .on
You could create global constants if you really want to mimic boolean more closely, although that'd be a bit non-ideomatic:
enum State {
case on
case off
}
let on = State.on
let off = State.off
let coin = on
…though I don't think that'll work as you want with optionality.
3 Likes