9

GitHub - SvenTiigi/ValidatedPropertyKit: Easily validate your Properties with Pr...

 4 years ago
source link: https://github.com/SvenTiigi/ValidatedPropertyKit
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

README.md

ValidatedPropertyKit Logo

Swift 5.1 CI Status Version Platform
Carthage Compatible SPM Documentation Twitter


ValidatedPropertyKit enables you to easily validate your properties
with the power of Property Wrappers.


struct User {
    
    @Validated(.nonEmpty)
    var username: String?
    
    @Validated(.isEmail)
    var email: String?
    
    @Validated(.range(8...))
    var password: String?
    
    @Validated(.greaterOrEqual(1))
    var friends: Int?
    
    @Validated(.isURL && .hasPrefix("https"))
    var avatarURL: String?
    
}

Features

  • Easily validate your properties 👮
  • Predefined validations 🚦
  • Logical Operators to combine validations 🔗
  • Customization and configuration to your needs 💪

Installation

CocoaPods

ValidatedPropertyKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'ValidatedPropertyKit'

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

To integrate ValidatedPropertyKit into your Xcode project using Carthage, specify it in your Cartfile:

github "SvenTiigi/ValidatedPropertyKit"

Run carthage update to build the framework and drag the built ValidatedPropertyKit.framework into your Xcode project.

On your application targets’ “Build Phases” settings tab, click the “+” icon and choose “New Run Script Phase” and add the Framework path as mentioned in Carthage Getting started Step 4, 5 and 6

Swift Package Manager

To integrate using Apple's Swift Package Manager, add the following as a dependency to your Package.swift:

dependencies: [
    .package(url: "https://github.com/SvenTiigi/ValidatedPropertyKit.git", from: "0.0.3")
]

Or navigate to your Xcode project then select Swift Packages, click the “+” icon and search for ValidatedPropertyKit.

Xcode SPM

Manually

If you prefer not to use any of the aforementioned dependency managers, you can integrate ValidatedPropertyKit into your project manually. Simply drag the Sources Folder into your Xcode project.

Usage

Validated 👮‍♂️

The @Validated attribute allows you to specify a validation along to the declaration of your property.

It is important to say that the @Validated attribute can only be applied to mutable Optional types as a validation can either succeed or fail.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print(username) // "Mr.Robot"

username = ""
print(username) // nil

Validation 🚦

Every @Validated attribute must be initialized with a Validation which will be initialized with a closure.

@Validated(.init { value in
   value.isEmpty ? .failure("String is empty") : .success(())
})
var username: String?

☝️ Check out the Predefined Validations section to get an overview of the many predefined validations.

Additionally, you can extend the Validation struct via conditional conformance to easily declare your own Validations.

extension Validation where Value == Int {

    /// Will validate if the Integer is the meaning of life
    static var isMeaningOfLife: Validation {
        return .init { value in
            value == 42 ? .success(()) : .failure("\(value) isn't the meaning of life")
        }
    }

}

And apply them to your validated property.

@Validated(.isMeaningOfLife)
var number: Int?

Error Handling 🕵️‍♂️

Each property that is declared with the @Validated attribute can make use of advanced functions and properties from the Validated Property Wrapper itself via the _ notation prefix.

Beside doing a simple nil check on your @Validated property to ensure if the value is valid or not you can access the validatedValue or validationError property to retrieve the ValidationError or the valid value.

@Validated(.nonEmpty)
var username: String?

// Switch on `validatedValue`
switch _username.validatedValue {
case .success(let value):
    // Value is valid ✅
    break
case .failure(let validationError):
    // Value is invalid ⛔️
    break
}

// Or unwrap the `validationError`
if let validationError = _username.validationError {
    // Value is invalid ⛔️
} else {
    // Value is valid ✅
}

Restore ↩️

Additionally, you can restore your @Validated property to the last successful validated value.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print(username) // "Mr.Robot"

username = ""
print(username) // nil

// Restore to last successful validated value
_username.restore()
print(username) // "Mr.Robot"

isValid ✅

As the aforementioned restore() function you can also access the isValid Bool value property to check if the current value is valid.

@Validated(.nonEmpty)
var username: String?

username = "Mr.Robot"
print(_username.isValid) // true

username = ""
print(_username.isValid) // false

Validation Operators 🔗

Validation Operators allowing you to combine multiple Validations like you would do with Bool values.

// Logical AND
@Validated(.isURL && .hasPrefix("https"))
var avatarURL: String?

// Logical OR
@Validated(.hasPrefix("Mr.") || .hasPrefix("Mrs."))
var name: String?

// Logical NOT
@Validated(!.contains("Android", options: .caseInsensitive))
var favoriteOperatingSystem: String?

Predefined Validations

The ValidatedPropertyKit comes with many predefined common validations which you can make use of in order to specify a Validation for your validated property.

KeyPath

The keyPath validation will allow you to specify a validation for a given KeyPath of the attributed property.

@Validated(.keyPath(\.isEnabled, .equals(true)))
var button: UIButton?

Strings

A String property can be validated in many ways like contains, hasPrefix and even RegularExpressions.

@Validated(.contains("Mr.Robot"))
var string: String?

@Validated(.hasPrefix("Mr."))
var string: String?

@Validated(.hasSuffix("OS"))
var string: String?

@Validated(.regularExpression("[0-9]+$"))
var string: String?

@Validated(.isLowercased)
var string: String?

@Validated(.isUppercased)
var string: String?

@Validated(.isEmail)
var string: String?

@Validated(.isURL)
var string: String?

@Validated(.isNumeric)
var string: String?

Equatable

A Equatable type can be validated against a specified value.

@Validated(.equals(42))
var number: Int?

Sequence

A property of type Sequence can be validated via the contains or startsWith validation.

@Validated(.contains("Mr.Robot", "Elliot"))
var sequence: [String]?

@Validated(.startsWith("First Entry"))
var sequence: [String]?

Collection

Every Collection type offers the nonEmpty validation and the range validation where you can easily declare the valid capacity.

@Validated(.nonEmpty)
var collection: [String]?

@Validated(.range(1...10))
var collection: [String]?

Comparable

A Comparable type can be validated with all common comparable operators.

@Validated(.less(50))
var comparable: Int?

@Validated(.lessOrEqual(50))
var comparable: Int?

@Validated(.greater(50))
var comparable: Int?

@Validated(.greaterOrEqual(50))
var comparable: Int?

Featured on

Contributing

Contributions are very welcome 🙌

License

ValidatedPropertyKit
Copyright (c) 2020 Sven Tiigi [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK