[swift-evolution] Customized Inline Init Closure
Thorsten Seitz
tseitz42 at icloud.com
Tue Jan 5 08:52:09 CST 2016
Very nice!
I also think that using $0 is fine as it avoids all the problems with shadowing the outer self and thereby avoids erros and increases readability.
-Thorsten
> Am 04.01.2016 um 18:51 schrieb Jo Albright via swift-evolution <swift-evolution at swift.org>:
>
> Here is another option. Attached is a playground I was messing around with. There are some weird bugs I was noticing, but don’t quite know if they are important enough to submit (comment out line 54 to see).
>
> I actually like using the $0 so as to allow access to self if using within another type (ex: view controller code below).
>
> Please respond with any potential issues with the code I have written.
>
> - Jo
>
>
>
> protocol ClosureInit { init() }
>
> extension ClosureInit {
>
> init(@noescape b: inout Self -> Void) { self.init(); b(&self) }
>
> }
>
> struct Person: ClosureInit {
>
> enum GenderType: String { case Male, Female }
>
> var age: Int = 0
> var gender: GenderType?
> var name: String?
>
> }
>
> let me = Person {
>
> $0.name = "Jo"
> $0.age = 32
> $0.gender = .Male
>
> }
>
> me.age // 32
>
> extension Array: ClosureInit { }
>
> let randomIntArray = [Int] {
>
> for _ in 0...10 {
>
> $0.append(Int(arc4random_uniform(100)))
>
> }
>
> }
>
> randomIntArray
>
> let personArray = [Person] {
>
> for _ in 0...8 {
>
> $0.append(Person {
>
> $0.age = Int(arc4random_uniform(100))
> $0.gender = Int(arc4random_uniform(100)) % 2 == 0 ? .Male : .Female // comment this line out to see error
>
>
> })
>
> }
>
> }
>
> personArray
>
> extension UIView: ClosureInit { }
>
> class ViewController: UIViewController {
>
> override func viewDidLoad() {
> super.viewDidLoad()
>
> UILabel {
>
> $0.text = "This is Awesome!"
> $0.textColor = UIColor.cyanColor()
> $0.frame = CGRect(x: 20, y: 20, width: view.frame.width - 40, height: 40)
> view.addSubview($0)
>
> }
>
> view.addSubview(UIButton {
>
> $0.setTitle("Submit", forState: .Normal)
> $0.frame = CGRect(x: 20, y: 60, width: view.frame.width - 40, height: 40)
>
> })
>
>
> }
>
> }
>
> let vc = ViewController()
>
> vc.loadViewIfNeeded()
>
> vc.view.subviews
>
>
> <ClosureInit.playground.zip>
>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160105/c7735c40/attachment.html>
More information about the swift-evolution
mailing list