iOS开发(Swift/Objective-C高效生成随机字符串)

原文连接
Objective-C版

// 随机生成字符串(由大小写字母、数字组成) + (NSString *)random: (int)len {char ch[len]; for (int index=0; index57 && num<65) { num = num%57+48; } else if (num>90 && num<97) { num = num%90+65; } ch[index] = num; }return [[NSString alloc] initWithBytes:ch length:len encoding:NSUTF8StringEncoding]; }// 随机生成字符串(由大小写字母组成) + (NSString *)randomNoNumber: (int)len {char ch[len]; for (int index=0; index90 && num<97) { num = num%90+65; } ch[index] = num; }return [[NSString alloc] initWithBytes:ch length:len encoding:NSUTF8StringEncoding]; }

Swift版
extension String {/// 生成随机字符串 /// /// - Parameters: ///- count: 生成字符串长度 ///- isLetter: false=大小写字母和数字组成,true=大小写字母组成,默认为false /// - Returns: String static func random(_ count: Int, _ isLetter: Bool = false) -> String {var ch: [CChar] = Array(repeating: 0, count: count) for index in 0..57 && num<65 && isLetter==false { num = num%57+48 } else if num>90 && num<97 { num = num%90+65 }ch[index] = CChar(num) }return String(cString: ch) } }

【iOS开发(Swift/Objective-C高效生成随机字符串)】使用
/// 大小写字母和数字组成 let string1 = String.random(100)/// 大小写字母组成 let string2 = String.random(100, true)

    推荐阅读