A SwiftUI example application demonstrating the usage of TiktokenSwift - Swift bindings for OpenAI's tiktoken library.
- Open
TiktokenSwiftExample.xcodeprojin Xcode - Go to File → Add Package Dependencies...
- Enter the package URL:
https://github.com/narner/TiktokenSwift.git - Choose the version rule (e.g., "Up to Next Major" from 0.1.0)
- Click "Add Package"
- Open
TiktokenSwiftExample.xcodeprojin Xcode - Drag the parent
TiktokenSwiftfolder into the Xcode project navigator - When prompted, choose "Create folder references"
- The local package will be automatically linked
The example app demonstrates:
- Text Encoding: Convert text into token arrays
- Token Visualization: Display tokens with indices in a scrollable view
- Token Decoding: Convert tokens back to text
- Encoder Information: Display vocabulary size and special tokens count
- Error Handling: User-friendly error messages
- Loading States: Visual feedback during operations
The app follows MVVM architecture:
- TiktokenViewModel: Manages state and business logic
- ContentView: Main coordinator view
- Component Views: Modular UI components in the Components folder
- InputSection: Text input and encode button
- TokensSection: Token display and decode/clear buttons
- TokenView: Individual token visualization
- DecodedTextSection: Decoded text display
- InfoSection: Encoder information display
- Enter text in the input field
- Click "Encode Text" to convert to tokens
- View the generated tokens with their indices
- Click "Decode Tokens" to convert back to text
- Use "Clear" to reset tokens and decoded text
The app demonstrates basic TiktokenSwift usage:
import TiktokenSwift
// Initialize the encoder
let encoder = try await CoreBpe.cl100kBase()
// Encode text to tokens
let text = "Hello, world!"
let tokens = encoder.encodeText(text)
// Decode tokens back to text
if let decoded = encoder.decodeTokens(tokens) {
print("Decoded: \(decoded)")
}- iOS 13.0+ / macOS 10.15+
- Xcode 14.0+
- Swift 5.9+
