There are a variety of potential efficiency points right here:
- Debug builds are unoptimized. Thus loops are a lot slower than launch builds, that are optimized. Select “Edit Scheme…” and test your scheme’s “Run” settings:
- You’re looping inside a loop, which is inefficient. Construct a dictionary and you’ll get pleasure from O(1) efficiency for every character substitution.
- Constructing a string by appending characters one by one is inefficient, ensuing within the string buffer being resized a number of instances. We might typically
reserveCapacity
, to cut back this impact. With small strings, this impact is immaterial, however with longer strings, it may need an observable impression on efficiency.
E.g., my easy strategy:
class Cypher {
non-public let encodeKey: [Character: Character]
non-public let decodeKey: [Character: Character]
init(cyph1: [Character], cyph2: [Character]) {
encodeKey = Dictionary(uniqueKeysWithValues: zip(cyph1, cyph2))
decodeKey = Dictionary(uniqueKeysWithValues: zip(cyph2, cyph1))
}
func encode(_ enter: String) -> String {
String(enter.compactMap { encodeKey[$0] })
}
func decode(_ enter: String) -> String {
String(enter.compactMap { decodeKey[$0] })
}
}
Or, should you actually wished to make use of a for
loop:
class Cypher {
non-public let encodeKey: [Character: Character]
non-public let decodeKey: [Character: Character]
init(cyph1: [Character], cyph2: [Character]) {
encodeKey = Dictionary(uniqueKeysWithValues: zip(cyph1, cyph2))
decodeKey = Dictionary(uniqueKeysWithValues: zip(cyph2, cyph1))
}
func encode(_ enter: String) -> String {
var output = ""
output.reserveCapacity(enter.rely)
for character in enter {
if let encodedCharacter = encodeKey[character] {
output.append(encodedCharacter)
}
}
return output
}
func decode(_ enter: String) -> String {
var output = ""
output.reserveCapacity(enter.rely)
for character in enter {
if let decodedCharacter = decodeKey[character] {
output.append(decodedCharacter)
}
}
return output
}
}
Simply to clarify the constructing of those [Character: Character]
dictionaries: The uniqueKeysWithValues
initializer of Dictionary
expects an array of tuples of keys and values. And the zip
will construct these arrays of tuples by marrying the weather into tuples from the 2 respective sequences, cyph1
and cyph2
.