Files
purchases-ios/Sources/FoundationExtensions/String+Extensions.swift
T

101 lines
2.5 KiB
Swift
Raw Normal View History

2021-08-03 20:42:12 +02:00
//
2021-08-06 14:28:11 -07:00
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
2021-08-03 20:42:12 +02:00
// String+Extensions.swift
//
// Created by Juanpe Catalán on 9/7/21.
//
import Foundation
extension String {
2021-08-06 14:28:11 -07:00
2021-08-03 20:42:12 +02:00
func rot13() -> String {
ROT13.string(self)
}
2021-08-06 14:28:11 -07:00
2023-07-05 15:41:51 -07:00
var trimmedAndEscaped: String {
return self
.trimmingWhitespacesAndNewLines
.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) ?? ""
}
/// Returns `nil` if `self` is an empty string.
var notEmpty: String? {
return self.isEmpty
? nil
: self
}
/// Returns `nil` if `self` is an empty string or it only contains whitespaces.
var notEmptyOrWhitespaces: String? {
return self.trimmingWhitespacesAndNewLines.isEmpty
? nil
: self
}
2023-07-05 15:41:51 -07:00
/// Returns `true` if it contains anything other than whitespaces.
var isNotEmpty: Bool {
return self.notEmptyOrWhitespaces != nil
}
var trimmingWhitespacesAndNewLines: String {
return self.trimmingCharacters(in: .whitespacesAndNewlines)
}
var asData: Data {
return Data(self.utf8)
}
func countOccurences(of character: Character) -> Int {
return self.reduce(0) {
return $1 == character ? $0 + 1 : $0
}
}
}
// MARK: -
internal extension Optional where Wrapped == String {
/// Returns `nil` if `self` is an empty string.
var notEmpty: String? {
return self.flatMap { $0.notEmpty }
}
}
private enum ROT13 {
2021-08-06 14:28:11 -07:00
2022-06-10 11:31:04 -07:00
private static let key: [Character: Character] = {
let size = Self.lowercase.count
let halfSize: Int = size / 2
var result: [Character: Character] = .init(minimumCapacity: size)
for number in 0 ..< size {
let index = (number + halfSize) % size
result[Self.uppercase[number]] = Self.uppercase[index]
result[Self.lowercase[number]] = Self.lowercase[index]
2022-06-10 11:31:04 -07:00
}
return result
}()
private static let lowercase: [Character] = Array("abcdefghijklmnopqrstuvwxyz")
// swiftlint:disable:next force_unwrapping
private static let uppercase: [Character] = Self.lowercase.map { $0.uppercased().first! }
2021-08-03 20:42:12 +02:00
fileprivate static func string(_ string: String) -> String {
2022-06-10 11:31:04 -07:00
let transformed = string.map { Self.key[$0] ?? $0 }
2021-08-03 20:42:12 +02:00
return String(transformed)
}
2021-08-06 14:28:11 -07:00
2021-08-03 20:42:12 +02:00
}