BS
BleepingSwift
Published on
3 min read

> Generating a Random Emoji in Swift

Share:

Sometimes you need a random emoji for placeholder avatars, visual variety in UI elements, or just to add some personality to your app. Swift's Unicode support makes this straightforward once you know which code point ranges contain emoji.

Basic Random Emoji

Emoji live in specific Unicode ranges. The "Miscellaneous Symbols and Pictographs" block from U+1F300 to U+1F3F0 contains many common emoji like weather symbols, animals, and objects:

Swift
extension String {
    static func randomEmoji() -> String? {
        guard let codePoint = (0x1F300...0x1F3F0).randomElement(),
              let scalar = UnicodeScalar(codePoint) else {
            return nil
        }
        return String(scalar)
    }
}

Call it whenever you need a random emoji:

Swift
let emoji = String.randomEmoji() // "🌸", "🎪", "🏠", etc.

Expanding the Range

The basic range covers only a subset of emoji. To include faces, gestures, and more recent additions, combine multiple ranges:

Swift
extension String {
    static func randomEmoji() -> String {
        let ranges: [ClosedRange<Int>] = [
            0x1F600...0x1F64F, // Emoticons (faces)
            0x1F300...0x1F5FF, // Misc symbols and pictographs
            0x1F680...0x1F6FF, // Transport and maps
            0x1F900...0x1F9FF, // Supplemental symbols
            0x2600...0x26FF,   // Misc symbols (sun, stars, etc.)
        ]

        let allCodePoints = ranges.flatMap { Array($0) }

        guard let codePoint = allCodePoints.randomElement(),
              let scalar = UnicodeScalar(codePoint) else {
            return "😀" // Fallback
        }

        return String(scalar)
    }
}

Note that not all code points in these ranges map to valid emoji. Some are reserved or represent non-emoji symbols. For most use cases this doesn't matter since invalid scalars simply won't render as anything meaningful, but if you need guaranteed emoji output, you'd want to filter to a known list.

Using a Curated List

For predictable results, maintain an explicit list of emoji you want to use:

Swift
extension String {
    private static let emoji = [
        "😀", "😃", "😄", "😁", "😆", "🥹", "😅", "😂",
        "🙂", "😊", "😇", "🥰", "😍", "🤩", "😘", "😋",
        "🐶", "🐱", "🐭", "🐹", "🐰", "🦊", "🐻", "🐼",
        "🍎", "🍐", "🍊", "🍋", "🍌", "🍉", "🍇", "🍓",
        "⭐️", "🌟", "✨", "💫", "🎉", "🎊", "🎁", "🎈"
    ]

    static func randomEmoji() -> String {
        emoji.randomElement() ?? "⭐️"
    }
}

This approach guarantees every result is a recognizable emoji and lets you control the aesthetic. Perhaps you only want happy faces, or animals, or food items for your specific context.

Generating Multiple Unique Emoji

If you need several different emoji without repeats:

Swift
extension String {
    static func randomEmoji(count: Int) -> [String] {
        let allEmoji = [
            "😀", "😃", "😄", "😁", "🐶", "🐱", "🐭",
            "🍎", "🍐", "🍊", "⭐️", "🌟", "✨", "💫"
            // ... more emoji
        ]

        return Array(allEmoji.shuffled().prefix(count))
    }
}

// Usage
let avatarEmoji = String.randomEmoji(count: 5)
// ["🐱", "😄", "🍎", "✨", "😁"]

Checking if a Character is an Emoji

Sometimes you receive user input and want to verify it contains emoji:

Swift
extension Character {
    var isEmoji: Bool {
        guard let scalar = unicodeScalars.first else { return false }
        return scalar.properties.isEmoji && scalar.value > 0x238C
    }
}

extension String {
    var containsEmoji: Bool {
        contains { $0.isEmoji }
    }

    var onlyEmoji: Bool {
        !isEmpty && allSatisfy { $0.isEmoji }
    }
}

The isEmoji property on UnicodeScalar.Properties tells you if a scalar is classified as emoji in the Unicode standard. The additional value check excludes some technical symbols that are technically emoji but don't render as colorful pictographs.

Random emoji add a lightweight touch of visual interest to apps, and Swift's Unicode handling makes working with them clean and type-safe.

subscribe.sh

// Stay Updated

Get notified when I publish new tutorials on Swift, SwiftUI, and iOS development. No spam, unsubscribe anytime.

>

By subscribing, you agree to our Privacy Policy.