我如何在Swift中生成一个随机的字母数字字符串?
当前回答
为Swift 4更新。在类扩展上使用惰性存储变量。这只计算一次。
extension String {
static var chars: [Character] = {
return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".map({$0})
}()
static func random(length: Int) -> String {
var partial: [Character] = []
for _ in 0..<length {
let rand = Int(arc4random_uniform(UInt32(chars.count)))
partial.append(chars[rand])
}
return String(partial)
}
}
String.random(length: 10) //STQp9JQxoq
其他回答
针对Swift 3.0
func randomString(_ length: Int) -> String {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
如果您只需要一个唯一标识符UUID()。uuidString可以满足您的需求。
一种避免输入整套字符的方法:
func randomAlphanumericString(length: Int) -> String {
enum Statics {
static let scalars = [UnicodeScalar("a").value...UnicodeScalar("z").value,
UnicodeScalar("A").value...UnicodeScalar("Z").value,
UnicodeScalar("0").value...UnicodeScalar("9").value].joined()
static let characters = scalars.map { Character(UnicodeScalar($0)!) }
}
let result = (0..<length).map { _ in Statics.characters.randomElement()! }
return String(result)
}
如果你的随机字符串应该是安全随机的,使用这个:
import Foundation
import Security
// ...
private static func createAlphaNumericRandomString(length: Int) -> String? {
// create random numbers from 0 to 63
// use random numbers as index for accessing characters from the symbols string
// this limit is chosen because it is close to the number of possible symbols A-Z, a-z, 0-9
// so the error rate for invalid indices is low
let randomNumberModulo: UInt8 = 64
// indices greater than the length of the symbols string are invalid
// invalid indices are skipped
let symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
var alphaNumericRandomString = ""
let maximumIndex = symbols.count - 1
while alphaNumericRandomString.count != length {
let bytesCount = 1
var randomByte: UInt8 = 0
guard errSecSuccess == SecRandomCopyBytes(kSecRandomDefault, bytesCount, &randomByte) else {
return nil
}
let randomIndex = randomByte % randomNumberModulo
// check if index exceeds symbols string length, then skip
guard randomIndex <= maximumIndex else { continue }
let symbolIndex = symbols.index(symbols.startIndex, offsetBy: Int(randomIndex))
alphaNumericRandomString.append(symbols[symbolIndex])
}
return alphaNumericRandomString
}
简单快捷——UUID().uuidString
//返回由UUID创建的字符串,例如"E621E1F8-C36C-495A-93FC-0C247A3E6E5F" uuidString:字符串{get} https://developer.apple.com/documentation/foundation/uuid
斯威夫特3.0
let randomString = UUID().uuidString //0548CD07-7E2B-412B-AD69-5B2364644433
print(randomString.replacingOccurrences(of: "-", with: ""))
//0548CD077E2B412BAD695B2364644433
EDIT
请不要与UIDevice.current.identifierForVendor混淆。uuidString它不会给出随机值。
推荐文章
- 以编程方式更改导航标题
- 我如何得到一个plist作为一个字典在Swift?
- 将string (or char*)转换为wstring (or wchar_t*)
- Java的assertEquals方法可靠吗?
- 字符串作为SQL数据库的主键
- 如何在Swift中删除视图的所有子视图?
- 属性getter和setter
- 从列中的字符串中删除不需要的部分
- 在c#中转换字符串为类型
- 替换c#字符串中的多个字符
- Java中字符串的字节数
- .join()方法到底做什么?
- 为什么我需要在swift的下划线?
- 我如何得到一个Swift枚举的计数?
- 是否有一个原因,Swift数组赋值是不一致的(既不是引用也不是深度复制)?