summaryrefslogtreecommitdiffhomepage
path: root/ios/MullvadVPN/Extensions/String+Helpers.swift
blob: 5b41e20a78a70b223e43c6c66e47eb8fa665be67 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//
//  String+Helpers.swift
//  MullvadVPN
//
//  Created by pronebird on 27/03/2020.
//  Copyright © 2025 Mullvad VPN AB. All rights reserved.
//

import UIKit

extension String {
    /// Returns the array of the longest possible subsequences of the given length.
    func split(every length: Int) -> [Substring] {
        guard length > 0 else { return [prefix(upTo: endIndex)] }

        let resultCount = Int((Float(count) / Float(length)).rounded(.up))

        return (0..<resultCount)
            .map { dropFirst($0 * length).prefix(length) }
    }

    func width(using font: UIFont) -> CGFloat {
        let fontAttributes = [NSAttributedString.Key.font: font]
        return self.size(withAttributes: fontAttributes).width
    }
}

extension Array where Element == String {
    func joinedParagraphs(lineBreaks: Int = 2) -> String {
        let separator = String(repeating: "\n", count: lineBreaks)
        return self.joined(separator: separator)
    }
}