Giter Site home page Giter Site logo

then's Introduction

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("[email protected]", 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.

then's People

Contributors

armored-dragon avatar capnslipp avatar ddddxxx avatar dentelezhkin avatar devxoul avatar jacobh0 avatar jk0369 avatar jverdi avatar muescha avatar murselturk avatar noobish1 avatar phimage avatar ruiaaperes avatar sunshinejr avatar tbaranes avatar wanbok avatar zhipingyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

then's Issues

Is Then dead? (abandon-ware?)

Has Then been abandoned?  It doesn't appear @devxoul has responded to any issues or PRs, or made any code changes since Sept 2019.  And basically every comment he made before than was highly resistant to making any changes or accommodations for the devs who rely on Then.

Is it time for someone else to take over the project?  Is there someone else who is already maintaining an updated fork who's willing to take up the mantle of maintaining the community, and who welcomes us all switching over to his/her fork?

Side-note: I grew tired of some of the issues with Then a while back and wrote my own stab from scratch at solving this problem— I chose to go with a free function approach that's closer to the with keyword in Python, JavaScript, Visual Basic, Object Pascal, Delphi and using in C#, and which seems to be more idiomatic Swift.  I also care about making sure my libraries work in every build toolchain and environment (SPM, CocoaPods, Carthage, Xcode project embedding, etc.); can solve any reasonable user-requested problem (@discardableResult, arbitrary return value, @inlinable, etc.); and can be used freely by everyone (completely copyright-free public domain, no restrictions or attribution needed).  My recently-uploaded library is called With.

How to use 'do' block?

First think I want to say: Thank you! It's awesome.

My trouble is can't use 'do' block. The compile show error "Expected member name following.". Example:

NSUserDefaults.standardUserDefaults().do({
// Do anything with UserDefaults
})

Add extension for basic type?

Maybe, we could add many extensions, eg:

extension Bool: Then {}
extension Int: Then {}
extension Optional: Then {}

Is it right?

Installation with Carthage is broken

Because the repository doesn't contain a .xcodeproj, Carthage is unable to build the framework, failing silently.

Output when running carthage update --platform iOS --no-use-binaries with a clean workspace:

*** Cloning Then
*** Checking out Then at "2.2.0"
*** xcodebuild output can be found in /var/folders/s0/tjb6sjmd3914dzy5mncptr700000gn/T/carthage-xcodebuild.3bko6H.log

The building step is missing from the log. After the last line, there should be another one with the following:

*** Building scheme "Then" in Then.xcodeproj

I've reproduced this with Carthage 0.25 and 0.24.

lazy code

lazy var tableView: UITableView = {
let tabView =UITableView.init(frame: .zero, style: .plain)
tabView.backgroundColor = UIColor.white
tabView.dataSource = self
tabView.delegate = self
return tabView
}()
I often use lazy loading, and,how to write by Then。Can you give me a test code。

Swift 4.2 support?

Thanks for good work. Another swift version has published, please support as soon as possible?

How to set delegate or add target in closure?

lazy var recordButton = UIButton().then {
        $0.setTitle("Start", forState: .Normal)
        $0.setTitle("Stop", forState: .Selected)
        $0.addTarget(self, action: #selector(someAction), forControlEvents: .TouchUpInside)
    }

The "self" cannot be used.

cocoapods with 'Then' issues

when I use it with cocoapods ,I will get the issues "Command /bin/sh failed with exit code 1", but not
appear other what like "then".it is my pods file:

platform :ios, '9.0'
use_frameworks!

target 'MapInSwift' do
pod 'Alamofire'
pod 'SwiftyJSON'
pod 'Then', '~> 2.1'
end

if i remove the line with "pod 'Then', '~> 2.1'", i will get no issue

I fand the solution on the google but no way is fit me.If i need particular setting with Xcode(xcode 8.0; swift 3.0)

[proposal] Mutating a value type

Motivation

To mutate some deeply nested value types, we have to write the whole key path at least twice:

some.very[deep].structure.someProperty = someValue
some.very[deep].structure.anotherProperty = anotherValue

// or with Then:

some.very[deep].structure = some.very[deep].structure.with {
    $0.someProperty = someValue
    $0.anotherProperty = anotherValue
}

Solution

Let's extend Then with mutate function (alternatives: update, access, write):

extension Then {
    public mutating func mutate(_ block: (inout Self) throws -> Void) rethrows {
        try block(&self)
    }
}

Usage:

some.very[deep].structure.mutate {
    $0.someProperty = someValue
    $0.anotherProperty = anotherValue
}

It would be great to have this in Then library. Thank you!

Accessing instance variables in then block

I can't seem to access class variables in my then block:

For example

class GradientView {
   let colors = ...
   lazy var gradientLayer = CAGradientLayer().then {
       $0.colors = self.colors // also tried colors
   }
}

doesn't work, but

class GradientView {
   let colors = ...
   lazy var gradientLayer: CAGradientLayer = {
       let layer = CAGradientLayer()
       layer.colors = self.colors
       return layer
   }()
}

does.

Can I repeat my old pattern of accessing instance variables in a lazy init using Then?

add @discardableResult

_ = UIView().then {
$0.tag = 1
}


UIView().then {
$0.tag = 1
}

如果是下面的,有很多警告

Support for Swift Package Manager

The project I am currently developing could use this library very much, but my project uses Swift Package Manager. It would be nice if we could add support for SwiftPM into this package.

@noescape

Hi, I just make my Configurable and realize you're 1 step before me 😄

I see that this pattern is now widely adopted in many projects, like Dip, ... for the compensation of Builder pattern. Like Dip, I have Initable which works on init as well, good for basic usage

One thing you can improve is to leverage @noescape http://nshint.io/blog/2015/10/23/noescape-attribute/

error: The following binaries use incompatible versions of Swift:

XCode9.3 (Swift4.1) 사용중입니다.
carthage를 이용해 github "devxoul/Then"를 설치했는데 아래와 같은 오류가 뜹니다.

error: The following binaries use incompatible versions of Swift:
/Users/gns/Library/Developer/Xcode/DerivedData/CopyPodcasts-edkbnveraiflpmhipjhtkxsbijgx/Build/Products/Debug-iphoneos/CopyPodcasts.app/CopyPodcasts
/Users/gns/Library/Developer/Xcode/DerivedData/CopyPodcasts-edkbnveraiflpmhipjhtkxsbijgx/Build/Products/Debug-iphoneos/CopyPodcasts.app/Frameworks/Then.framework/Then

해결방법이 있을까요?

ERROR when upload to AppStore

ERROR ITMS-90056: "This bundle Payload/X.app/Frameworks/Then.framework is invalid. The Info.plist file is missing the required key: CFBundleVersion."

How to use this syntax for IBOutlet views?

Instead of creating a new instance for a view, is there a possibility to fetch the existing instance and set attributes to it? I want to update attributes initially for IBOutlets views.

Propose for inclusion in swift-lang

I think this library and pattern is 'swifty' enough to be part of Swift-lang itself!

Perhaps the syntax would change to be like an auto closure.
I speculate the compiler could do something with value-types being treated as immutable after being returned in some cases.

UICollectionView doesn't show cells

image

If I create a UICollectionView with upside code, it works good.
However, I create UICollectionView with downside code, it doesn`t show cells.
Others code all same.

What's the problem??

Strange issue after updating to version 1.0.0

I got compiling error Cannot convert value of type '_ -> ()' to expected argument type 'inout WKWebView -> Void' with this code

webView.then {
    $0.navigationDelegate = self
}

However, the error's gone when there are two assignments in the block

webView.then {
    $0.navigationDelegate = self
    $0.tag = 1
}

[proposal] Implementation of another method without inout

Problem

The code below works in Then 1.0.1 but doesn't work in 1.0.2.

func tempt(label: UILabel) {
    label.text = "I💞Then"
}

let label1 = UILabel()
tempt(label1) // Works fine definitely
UILabel().then(tempt) // Error: Cannot convert value of type '(UILabel) -> ()' to expected argument type 'inout UILabel -> Void'

Adding inout keyword to the func resolves the error, but it brings another problem.

func temptInOut(inout label: UILabel) {
    label.text = "I💞Then"
}

UILabel().then(temptInOut) // Works fine

let label2 = UILabel()
temptInOut(label2) // Error: Cannot convert value of type 'UILabel' to expected argument type 'inout UILabel'
temptInOut(&label2) // Another Error: Cannot pass immutable value as inout argument: 'label2' is a 'let' constant

To resolve all errors, I should write code as below.

var label3 = UILabel()
temptInOut(&label3) // Works fine but seems ugly.

I don't use neither var nor &...

Proposal

#18 is nice-to-have modification, but old-style method(without inout keyword) is also nice in some situations.

So why don't you implement another old-type method as (@noescape block: Self -> Void) -> Self ?

carthage build

$carthage update --platform macOS
results in:

*** Skipped building Then due to the error:
Dependency "Then" has no shared framework schemes for any of the platforms: Mac

If you believe this to be an error, please file an issue with the maintainers at https://github.com/devxoul/Then/issues/new

Using carthage 0.34, Swift 5, xcode 10.2

Cannot used with `struct`

Seems like I cannot use Then on struct type:

struct SomeStruct {
    var name: String = ""
}

extension SomeStruct : Then {}

var aStruct = SomeStruct().then {
    $0.name = "123"
}

$0.name = "123" line throw an error: ...swift:43:10: Cannot assign to property: '$0' is a 'let' constant

Unreliable Autocomplete at class level

Just wondering if anyone else is having problems with autocompletion inside then closure..
It seems to work every time when using with local variables inside functions, but with class/struct level variables it simply does not autocomplete.

I'm using the Swift 2.3 version with Xcode 8 but the problem persists...

(I know this is probably a SourceKit thing, but just wondering if is happening to anyone else)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.