[swift-evolution] Customized Inline Init Closure
Jo Albright
me at jo2.co
Mon Jan 4 11:51:42 CST 2016
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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160104/5204d231/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: ClosureInit.playground.zip
Type: application/zip
Size: 11767 bytes
Desc: not available
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160104/5204d231/attachment.zip>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160104/5204d231/attachment-0001.html>
More information about the swift-evolution
mailing list