-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathContents.swift
94 lines (72 loc) · 2.49 KB
/
Contents.swift
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import UIKit
let name = "Taylor"
for letter in name {
print("Give me a \(letter)!")
}
let letter = name[name.index(name.startIndex, offsetBy: 3)]
extension String {
subscript(i: Int) -> String {
return String(self[index(startIndex, offsetBy: i)])
}
}
let letter2 = name[3]
// --
let password = "12345"
password.hasPrefix("123")
password.hasSuffix("456")
extension String {
// remove a prefix if it exists
func deletingPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else { return self }
return String(self.dropFirst(prefix.count))
}
// remove a suffix if it exists
func deletingSuffix(_ suffix: String) -> String {
guard self.hasSuffix(suffix) else { return self }
return String(self.dropLast(suffix.count))
}
}
// --
let weather = "it's going to rain"
print(weather.capitalized)
extension String {
var capitalizedFirst: String {
guard let firstLetter = self.first else { return "" }
return firstLetter.uppercased() + self.dropFirst()
}
}
// --
let input = "Swift is like Objective-C without the C"
input.contains("Swift")
let languages = ["Python", "Ruby", "Swift"]
languages.contains("Swift")
// we could do this
extension String {
func containsAny(of array: [String]) -> Bool {
for item in array {
if self.contains(item) {
return true
}
}
return false
}
}
input.containsAny(of: languages)
// but this is better
languages.contains(where: input.contains)
//--
let string = "This is a test string"
let attributes: [NSAttributedString.Key: Any] = [
.foregroundColor: UIColor.white,
.backgroundColor: UIColor.red,
.font: UIFont.boldSystemFont(ofSize: 36)
]
let attributedString = NSAttributedString(string: string, attributes: attributes)
// --
let string2 = "This is a test string"
let attributedString2 = NSMutableAttributedString(string: string2)
attributedString2.addAttribute(.font, value: UIFont.systemFont(ofSize: 8), range: NSRange(location: 0, length: 4))
attributedString2.addAttribute(.font, value: UIFont.systemFont(ofSize: 16), range: NSRange(location: 5, length: 2))
attributedString2.addAttribute(.font, value: UIFont.systemFont(ofSize: 24), range: NSRange(location: 8, length: 1))
attributedString2.addAttribute(.font, value: UIFont.systemFont(ofSize: 32), range: NSRange(location: 10, length: 4))
attributedString2.addAttribute(.font, value: UIFont.systemFont(ofSize: 40), range: NSRange(location: 15, length: 6))