Convert Figma logo to code with AI

devxoul logoThen

✨ Super sweet syntactic sugar for Swift initializers

4,187
291
4,187
13

Top Related Projects

24,320

Reactive Programming in Swift

Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.

A collection of Rx operators & tools not found in the core RxSwift distribution

4,233

A Swift binding framework

15,085

Network abstraction layer written in Swift.

A handy collection of more than 500 native Swift extensions to boost your productivity.

Quick Overview

Then is a Swift library that provides a concise and elegant way to initialize objects. It allows for a more readable and expressive syntax when setting up complex objects, especially useful for UI components in iOS development.

Pros

  • Improves code readability and reduces boilerplate
  • Supports method chaining for a more fluent API
  • Compatible with both UIKit and SwiftUI
  • Lightweight and easy to integrate

Cons

  • May not be necessary for simple object initializations
  • Requires learning a new syntax pattern
  • Could potentially make debugging more challenging in some cases
  • Might lead to overuse, resulting in less idiomatic Swift code

Code Examples

Setting up a UILabel:

let label = UILabel().then {
    $0.textAlignment = .center
    $0.textColor = .black
    $0.text = "Hello, World!"
    $0.font = UIFont.systemFont(ofSize: 16)
}

Configuring a UIButton:

let button = UIButton(type: .system).then {
    $0.setTitle("Tap me", for: .normal)
    $0.setTitleColor(.blue, for: .normal)
    $0.layer.cornerRadius = 5
    $0.layer.borderWidth = 1
    $0.layer.borderColor = UIColor.blue.cgColor
}

Creating a custom view:

class CustomView: UIView {
    let titleLabel = UILabel().then {
        $0.font = .boldSystemFont(ofSize: 18)
        $0.textColor = .darkGray
    }
    
    let descriptionLabel = UILabel().then {
        $0.font = .systemFont(ofSize: 14)
        $0.textColor = .gray
        $0.numberOfLines = 0
    }
}

Getting Started

  1. Add Then to your project using Swift Package Manager:

    dependencies: [
        .package(url: "https://github.com/devxoul/Then.git", from: "3.0.0")
    ]
    
  2. Import Then in your Swift file:

    import Then
    
  3. Start using Then to initialize and configure objects:

    let view = UIView().then {
        $0.backgroundColor = .white
        $0.layer.cornerRadius = 10
    }
    

Competitor Comparisons

24,320

Reactive Programming in Swift

Pros of RxSwift

  • Comprehensive reactive programming framework for complex asynchronous operations
  • Large ecosystem with extensions for UIKit, Cocoa, and other iOS/macOS libraries
  • Powerful operators for transforming and combining data streams

Cons of RxSwift

  • Steeper learning curve due to its extensive API and reactive programming concepts
  • Potential for memory leaks if not used carefully (e.g., retain cycles in closures)
  • Overkill for simple tasks or projects with minimal asynchronous operations

Code Comparison

Then:

let label = UILabel().then {
    $0.textAlignment = .center
    $0.textColor = .black
    $0.text = "Hello, World!"
}

RxSwift:

Observable.just("Hello, World!")
    .map { $0.uppercased() }
    .subscribe(onNext: { text in
        self.label.text = text
    })
    .disposed(by: disposeBag)

Summary

Then is a lightweight library for simplifying object initialization, while RxSwift is a comprehensive reactive programming framework. Then excels in readability and simplicity for basic tasks, whereas RxSwift shines in complex asynchronous scenarios but requires more setup and understanding of reactive concepts.

Cocoa framework and Obj-C dynamism bindings for ReactiveSwift.

Pros of ReactiveCocoa

  • Comprehensive reactive programming framework for iOS and macOS
  • Supports functional reactive programming paradigms
  • Extensive ecosystem and community support

Cons of ReactiveCocoa

  • Steeper learning curve for developers new to reactive programming
  • Can introduce complexity in simpler use cases
  • Larger codebase and potential performance overhead

Code Comparison

ReactiveCocoa:

let searchResults = searchString
    .throttle(0.3, on: QueueScheduler.main)
    .flatMap(.latest) { (query: String) -> SignalProducer<[SearchResult], NoError> in
        return API.search(query)
    }

Then:

let user = User().then {
    $0.name = "John"
    $0.age = 25
}

Key Differences

  • ReactiveCocoa is a full-fledged reactive programming framework, while Then is a lightweight syntactic sugar library
  • ReactiveCocoa focuses on handling asynchronous events and data streams, whereas Then simplifies object initialization and configuration
  • ReactiveCocoa requires a deeper understanding of reactive concepts, while Then is more intuitive for Swift developers

Use Cases

  • ReactiveCocoa: Complex UI interactions, network requests, and data binding
  • Then: Quick and clean object setup, especially for UI components and model objects

A collection of Rx operators & tools not found in the core RxSwift distribution

Pros of RxSwiftExt

  • Provides a wide range of operators and utilities specifically for RxSwift
  • Regularly maintained and updated by the RxSwift community
  • Offers more complex and specialized functionalities for reactive programming

Cons of RxSwiftExt

  • Steeper learning curve due to its focus on reactive programming concepts
  • Requires RxSwift as a dependency, which may increase project complexity
  • May be overkill for simpler projects that don't heavily rely on reactive programming

Code Comparison

Then:

let label = UILabel().then {
    $0.textAlignment = .center
    $0.textColor = .black
    $0.text = "Hello, World!"
}

RxSwiftExt:

Observable.from([1, 2, 3, 4, 5])
    .partition { $0 % 2 == 0 }
    .subscribe(onNext: { evens, odds in
        print("Evens: \(evens), Odds: \(odds)")
    })

Summary

Then is a lightweight library for simplifying object initialization, while RxSwiftExt is a comprehensive extension for RxSwift, offering advanced reactive programming capabilities. Then is more suitable for projects focusing on clean, concise object setup, whereas RxSwiftExt is ideal for complex reactive programming scenarios in iOS development.

4,233

A Swift binding framework

Pros of Bond

  • More comprehensive reactive programming framework
  • Supports data binding and KVO observation
  • Offers a wider range of reactive types and operators

Cons of Bond

  • Steeper learning curve due to more complex API
  • Heavier dependency with more code and functionality
  • May be overkill for simpler use cases

Code Comparison

Bond:

let name = Observable<String?>("")
let greeting = name.map { "Hello, \($0 ?? "")!" }
greeting.bind(to: label.reactive.text)

Then:

let label = UILabel().then {
    $0.text = "Hello, World!"
    $0.textColor = .black
}

Summary

Bond is a more powerful reactive programming framework with data binding capabilities, while Then is a simpler utility for concise object initialization. Bond offers more functionality but comes with increased complexity, whereas Then focuses on providing a clean syntax for object setup. Choose Bond for reactive programming needs and Then for streamlined object creation.

15,085

Network abstraction layer written in Swift.

Pros of Moya

  • Provides a network abstraction layer, simplifying API interactions
  • Supports stubbing for easy testing and development
  • Offers built-in request/response logging for debugging

Cons of Moya

  • Steeper learning curve due to its comprehensive feature set
  • Requires more setup and configuration compared to Then
  • May be overkill for simple projects or basic networking needs

Code Comparison

Moya example:

let provider = MoyaProvider<MyAPI>()
provider.request(.userProfile) { result in
    switch result {
    case let .success(response):
        let data = response.data
        // Handle the response
    case let .failure(error):
        // Handle the error
    }
}

Then example:

let user = User().then {
    $0.name = "John"
    $0.age = 30
    $0.email = "john@example.com"
}

Key Differences

  • Moya focuses on networking and API interactions, while Then is a utility for Swift object initialization
  • Moya provides a more robust solution for complex networking needs, whereas Then offers a simpler syntax for object configuration
  • Then is more lightweight and easier to integrate for its specific use case, while Moya requires more setup but offers more comprehensive networking features

A handy collection of more than 500 native Swift extensions to boost your productivity.

Pros of SwifterSwift

  • Comprehensive collection of extensions for Swift types and UIKit
  • Regularly updated with new features and improvements
  • Well-documented with examples for each extension

Cons of SwifterSwift

  • Large codebase may increase app size and compilation time
  • Some extensions might conflict with custom implementations
  • Learning curve to familiarize with all available extensions

Code Comparison

Then:

let label = UILabel().then {
    $0.textAlignment = .center
    $0.textColor = .black
    $0.text = "Hello, World!"
}

SwifterSwift:

let label = UILabel()
label.textAlignment = .center
label.textColor = .black
label.text = "Hello, World!"

Summary

Then focuses on providing a concise syntax for initializing and configuring objects, while SwifterSwift offers a wide range of extensions for various Swift types and UIKit components. Then is lightweight and easy to adopt, whereas SwifterSwift provides a more comprehensive set of utilities but may require more time to learn and integrate effectively.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Then

Swift CocoaPods Build Status

✨ Super sweet syntactic sugar for Swift initializers.

At a Glance

Initialize UILabel then set its properties.

let label = UILabel().then {
  $0.textAlignment = .center
  $0.textColor = .black
  $0.text = "Hello, World!"
}

This is equivalent to:

let label: UILabel = {
  let label = UILabel()
  label.textAlignment = .center
  label.textColor = .black
  label.text = "Hello, World!"
  return label
}()

Tips and Tricks

  • You can use then() to all of NSObject subclasses.

    let queue = OperationQueue().then {
      $0.maxConcurrentOperationCount = 1
    }
    
  • Want to use with your own types? Just make extensions.

    extension MyType: Then {}
    
    let instance = MyType().then {
      $0.really = "awesome!"
    }
    
  • Use with() when copying the value types.

    let newFrame = oldFrame.with {
      $0.size.width = 200
      $0.size.height = 100
    }
    newFrame.width // 200
    newFrame.height // 100
    
  • Use do() to do something with less typing.

    UserDefaults.standard.do {
      $0.set("devxoul", forKey: "username")
      $0.set("devxoul@gmail.com", forKey: "email")
      $0.synchronize()
    }
    

Real World Example

Here's an example usage in an UIViewController subclass.

final class MyViewController: UIViewController {

  let titleLabel = UILabel().then {
    $0.textColor = .black
    $0.textAlignment = .center
  }

  let tableView = UITableView().then {
    $0.backgroundColor = .clear
    $0.separatorStyle = .none
    $0.register(MyCell.self, forCellReuseIdentifier: "myCell")
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    self.view.addSubview(self.titleLabel)
    self.view.addSubview(self.tableView)
  }

}

Installation

  • Using CocoaPods:

    pod 'Then'
    
  • Using Swift Package Manager:

    import PackageDescription
    
    let package = Package(
      name: "MyAwesomeApp",
      dependencies: [
        .Package(url: "https://github.com/devxoul/Then", majorVersion: 2),
      ]
    )
    

License

Then is under MIT license. See the LICENSE file for more info.