✨ Super sweet syntactic sugar for Swift initializers.
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
}()
-
You can use
then()
to all ofNSObject
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() }
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) } }
-
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), ] )
Then is under MIT license. See the LICENSE file for more info.
then's People
Forkers
colemancda 0ber yippeeapp augmify ruiaaperes carabina rakutou osijan oenius imjerrybao avalanched vzheng56 phimage jiritrecak zheref runningjoey albincr gabrielpeart mvictor27 charlesjenkins soberman alloyapple dalu93 sanghavan antscript lerist jverdi towenxie kyaing wangweicheng7 tuyenbq-0446 istareternal jeeliu pflnh soulcorw edenchow qinwenshi jpachecou-zz yaole kevinzk swiftisgod rayman-v johndpope sangwook-han tremollo muescha carlchou00 codebear98 uniquexj kaisayoung thousandsnight swiftylearning skyefreeman doster-hello hamilyjing mengxiangyue wdxgtsh headevenil zmjios hardweight daokunbai icoderro hlebowicz khala-wan barkinet lst-ios devesh-swift magi82 sky-and-hammer ymoyao dander521 blucehn cultivr jayhuo rdxer zh20102618 zuccoi 5nn luyeloveyou justlee-me manlan2 kubatruhlar jiu0929 dharmakshetri mitchellporter zn-yuan 0zine ntkhoi kemchenj wanbok zikex zer0err jashion reversescale gaygang alanjn wxlpp domingguss evilino magiciandlthen's Issues
where is the Then.xcproj ??? can not build
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.
`Tap` might be a better name than `Then`.
Then
sounds like it will just return aPromise
.Tap
is what ruby is using now: http://ruby-doc.org/core-2.3.0/Object.html#method-i-tapXcode 14 code prompt error
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
해결방법이 있을까요?
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: MacIf 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
Question: Why use `then` instead of `with`?
What am I missing? Why can't I use
with
for everything? I have not run into a situation wherewith
is not working... Why have boththen
andwith
?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.
Update Package.swift
thx!
Add extension for basic type?
Maybe, we could add many extensions, eg:
extension Bool: Then {} extension Int: Then {} extension Optional: Then {}
Is it right?
@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 oninit
as well, good for basic usageOne thing you can improve is to leverage
@noescape
http://nshint.io/blog/2015/10/23/noescape-attribute/doesn't support watchOS 3 or 4
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
})[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
withmutate
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!
xcode不能自动补全提示
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."
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 }
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.
No code prompt in Xcode 10.2
iOS 14 Deployment Target Warning
In the new Xcode (12) there is a SwiftPM import warning.
In order to fix I think all you have todo is bump the version to iOS 9 in the
Package.swift
file.
If you are wanting to maintain backwards support I think you can make a new[email protected]
KeychainAccess did something similar.
cannot install through carthage
*** Skipped building Then due to the error:
Dependency "Then" has no shared framework schemesPlease follow this guide to fix -> https://github.com/Carthage/Carthage#share-your-xcode-schemes
Apple privacy manifest support
Hi,
Apple is enforcing every app and SDK provider to provide privacy manifest in their SDK, would you please let me know is there any plan for the support?
https://developer.apple.com/support/third-party-SDK-requirements/
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
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 andusing
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.can not code hinting while use Then
add @discardableResult
_ = UIView().then {
$0.tag = 1
}
UIView().then {
$0.tag = 1
}如果是下面的,有很多警告
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'
endif 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)
UICollectionView doesn't show cells
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。[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
?Suggestion: Then? Why not With?
Nice idea!
I personally suggest a different keyword:
.with { ... }
UILabel().with { $0.textColor = .blackColor() }
Makes a bit more sense.
The keword/idea reminds me a bit of the old VB's
With...End With
statement: https://msdn.microsoft.com/en-us/library/wc500chb.aspxAccessing 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?
Value of type 'UILabel' has no member 'then'
xcode 11
when run, failed"Value of type 'UILabel' has no member 'then'"
Don't push a new branch
Hi everyone!
I'd like to contribute to this repo and today I've not been able to push my branch, I got this message:
remote: Permission to goktugyil/EZSwiftExtensions.git denied to vilapuigvila.
fatal: unable to access 'https://github.com/goktugyil/EZSwiftExtensions.git/': The requested URL returned error: 403
Thanks in advance.why not code hinting while use Then
why not code hinting by xcode while use Then
How to import Then global
I want use then in global
xcode Cannot complete automatically
Can you add @discardableResult on function
Doesn't work with UIView subclasses after Xcode 7.3.1 update
...but works fine with CALayer, NSAttributesString subclasses
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.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.
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)Swift 4.2 support?
Thanks for good work. Another swift version has published, please support as soon as possible?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.