0

I have a function I use to generate random strings for email addresses or passwords (for example). It was originally set like this:

static func random(length: Int) -> String {
    let characters = "abcdefghijklmnopqrstuvwxyz"
    return String((0..<length).map { _ in characters.randomElement()! })
}

So I changed it to this:

static func random(length: Int) -> String {
    let characters = CharacterSet.lowercaseLetters
    return String((0..<length).map { _ in characters.randomElement()! })
}

But I get an error saying "Value of type 'CharacterSet' has no member 'randomElement'.

I'm very new to Swift and I've done a lot of searching and so far I haven't found a good solution. I want to keep this function short and sweet. And I've been at this for a while now. Any help would be greatly appreciated! Please let me know if any more context is needed.


Edit: My question got closed because it was seen as a duplicate but, I looked at the solution page and tried to apply it to my issue and still no resolution. I'm not sure if that's because the previous answers are from 2015 and older or they were for obj-c

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Indigo
  • 167
  • 1
  • 2
  • 13

1 Answers1

0

As I said in my comment of the possible duplicated post you can use that extension from the accepted answer to get all characters from a CharacterSet and get a randomElement from the resulting collection. Also as stated in the accepted answer some characters may not be present in the font used to display the result:

extension CharacterSet {
    var array: [Character] {
        var result: [Character] = []
        for plane: UInt8 in 0...16 where hasMember(inPlane: plane) {
            for unicode in UInt32(plane) << 16 ..< UInt32(plane + 1) << 16 {
                if let uniChar = UnicodeScalar(unicode), contains(uniChar) {
                    result.append(Character(uniChar))
                }
            }
        }
        return result
    }
}

let lowercaseLettersArray = CharacterSet.lowercaseLetters.array
let randomCharacter = lowercaseLettersArray.randomElement()!  // "ᵳ"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571