Skip to content

Instantly share code, notes, and snippets.

@yeldarby
Created June 20, 2019 16:30
Show Gist options
  • Save yeldarby/d65f2cace9a9af32f50b82ef874c8724 to your computer and use it in GitHub Desktop.
Save yeldarby/d65f2cace9a9af32f50b82ef874c8724 to your computer and use it in GitHub Desktop.
SwiftUI Challenge
/**********
YOUR CHALLENGE, SHOULD YOU CHOOSE TO ACCEPT IT:
Modify the code below to work with a list
of arbitrary size *without* preallocating a
fixed-length array.
REPLY @braddwyer ON TWITTER WITH YOUR SOLUTION HERE:
https://twitter.com/braddwyer/status/1141744658399334401
(Original challenge via @JadenGeller, https://twitter.com/JadenGeller/status/1141300214654881792 )
**********/
//
// ContentView.swift
// SwiftUI Challenge Accepted
//
// Created by Brad Dwyer on 6/19/19.
// Copyright © 2019 Brad Dwyer. All rights reserved.
//
import SwiftUI
import Combine
struct ContentView: View {
var nums:[Int] = []
// HACK: set `count` to the maximum number of list items you want to support!
@State var counts:[Int] = [Int].init(repeating: 0, count: 100)
init() {
self.init(data:[1,2,3,4,5])
}
init(data:[Int]) {
self.nums = data
}
var count:Int {
get {
var ret = 0
for v in counts {
ret = ret + v
}
return ret
}
}
var views:[ToggleView] = []
var body: some View {
return VStack {
NavigationView {
List {
ForEach(nums.indices) { i in
ToggleView(i: i, nums: self.nums, counts: self.$counts)
}
}
.navigationBarTitle(Text("My favorite numbers!"))
}
Text("The sum of my favorite numbers is \(count).").padding()
}
}
}
struct ToggleView : View {
var i:Int
@State var nums:[Int]
@State var on:Bool = false
@Binding var counts:[Int]
var isOn:String {
get {
if(self.on) {
self.counts[self.i] = self.nums[self.i]
} else {
self.counts[self.i] = 0
}
return self.on ? "on" : "off"
}
}
var body: some View {
return Toggle(isOn: $on) {
Text("I like the number \(nums[i]) \(isOn)")
}
}
}
#if DEBUG
struct ContentView_Previews : PreviewProvider {
static var previews: some View {
ContentView(data: [1,2,3,4,5,6,7,8,9,10])
}
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment