Last active
July 25, 2021 09:09
-
-
Save fx-studio/57f615591c881ca159aeea7826640425 to your computer and use it in GitHub Desktop.
Basic Guide to Property Wrapper with Swift. Read more at https://fxstudio.dev/property-wrapper-trong-10-phut/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
@propertyWrapper | |
struct Capitalized { | |
// MARK: - Properties | |
private var value: String | |
// MARK: - | |
var projectedValue = false | |
var wrappedValue: String { | |
get { | |
value | |
} | |
set { | |
value = newValue.capitalized | |
projectedValue = (newValue.count >= 2 && newValue.count <= 32) ? true : false | |
} | |
} | |
// MARK: - Initialization | |
init(wrappedValue: String) { | |
value = wrappedValue.capitalized | |
} | |
} | |
@propertyWrapper | |
struct Capitalized2 { | |
var wrappedValue: String { | |
didSet { | |
wrappedValue = wrappedValue.capitalized | |
} | |
} | |
} | |
@propertyWrapper | |
struct Uppercased { | |
var wrappedValue: String { | |
didSet { | |
wrappedValue = wrappedValue.uppercased() | |
} | |
} | |
} | |
@propertyWrapper | |
struct MyDouble<T:Numeric> { | |
private var value: T | |
var wrappedValue: T { | |
get { | |
value * 2 | |
} | |
set { | |
value = newValue | |
} | |
} | |
init(wrappedValue: T) { | |
self.value = wrappedValue | |
} | |
} | |
// MARK: - Use In | |
// ------- | |
struct Book { | |
@Capitalized var author: String | |
@Capitalized2 var title: String | |
@Uppercased var des: String = "a. cád f dsf sd à dsaf" | |
} | |
var book = Book(author: "fx studio", title: "a great book") | |
print(book.author) | |
book.title.append("!") | |
print(book.title) | |
// ------- | |
class SomeClass { | |
@MyDouble var count: Float | |
@MyDouble var total: Int = 10 | |
init(count: Float) { | |
self.count = count | |
} | |
} | |
var obj = SomeClass(count: 1) | |
print(obj.count) | |
print(obj.total) | |
obj.count = 19 | |
print(obj.count) | |
// ------- | |
class NewBook { | |
@Capitalized var author: String | |
@Capitalized var title: String | |
init(author: String, title: String) { | |
self.author = author | |
self.title = title | |
} | |
} | |
var newbook = NewBook(author: "f", title: "a great book2") | |
print(newbook.author) | |
print(newbook.$author) | |
newbook.author.append("x studio") | |
print(newbook.author) | |
print(newbook.$author) | |
newbook.$author = true | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment