repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
manhpro/website
iOSQuiz-master/iOSQuiz-master/LeoiOSQuiz/Classes/ViewControllers/MainViewController/MainViewController.swift
1
8626
// // MainViewController.swift // LeoiOSQuiz // // Created by NeoLap on 4/15/17. // Copyright © 2017 Leo LE. All rights reserved. // import UIKit import PromiseKit import GoogleMaps import Alamofire //37.786882 //-122.399972 class MainViewController: UIViewController { var locationManager: CLLocationManager! var mapView: GMSMapView! var userMarker: GMSMarker? var userLocation: CLLocation? var restaurants: [Restaurant]? { didSet { updateMarkersOnMap(restaurants: restaurants) } } let services = AuthenticationServices() let restaurantServices = RestaurantServices() var restaurantMarkers: [GMSMarker]? var shouldUpdateRestaurants = true override func viewDidLoad() { super.viewDidLoad() congigureMapView() configureUserLocation() handleToCallAPIGetNearbyRestaurants() } } //MARK: - Data extension MainViewController { func handleToCallAPIGetNearbyRestaurants() { if shouldUpdateRestaurants { callAPIGetNearbyRestaurants() } } func callAPIGetNearbyRestaurants() { cancelRequests() showInternetIndicator() firstly { () -> Promise<GetRestaurantsOutput> in let input = inputGetRestaurants() return restaurantServices.getResaturants(input) }.then { [weak self] (output) -> Void in self?.restaurants = output.restaurants self?.shouldUpdateRestaurants = false self?.hideInternetIndicator() }.catch { [weak self] (error) in self?.showErrorAlert(message: error.localizedDescription) self?.shouldUpdateRestaurants = false self?.hideInternetIndicator() } } fileprivate func inputGetRestaurants() -> GetRestaurantsInput { let centerCoordinate = self.centerCoodinate() let input = GetRestaurantsInput(latitude: centerCoordinate.latitude, longitude: centerCoordinate.longitude) return input } fileprivate func centerCoodinate() -> CLLocationCoordinate2D { let center = self.mapView.center return self.mapView.projection.coordinate(for: center) } fileprivate func cancelRequests() { let sessionManager = Alamofire.SessionManager.default sessionManager.session.getTasksWithCompletionHandler { dataTasks, uploadTasks, downloadTasks in dataTasks.forEach { $0.cancel() } } } fileprivate func restaurantAtMarker(_ marker: GMSMarker) -> Restaurant { var restaurant = Restaurant() guard let restaurantMarkers = restaurantMarkers else { return restaurant } guard let restaurants = restaurants else { return restaurant } for i in 0..<restaurantMarkers.count { if marker == restaurantMarkers[i], i < restaurants.count { restaurant = restaurants[i] break } } return restaurant } } //MARK: - Map view extension MainViewController { fileprivate func congigureMapView() { mapView = GMSMapView() mapView.frame = self.view.frame self.view.addSubview(mapView) mapView.delegate = self mapView.isMyLocationEnabled = true mapView.settings.myLocationButton = true mapView.addObserver(self, forKeyPath: "myLocation", options: .new, context: nil) } override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let change = change else { return } if change[NSKeyValueChangeKey.oldKey] == nil { let location = change[NSKeyValueChangeKey.newKey] as! CLLocation userLocation = location updateCurrentUserMarkerWith(location: location) } } } //MARK: - User location extension MainViewController { fileprivate func configureUserLocation() { locationManager = CLLocationManager() locationManager.distanceFilter = 50.0 locationManager.requestWhenInUseAuthorization() locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.startUpdatingLocation() if mapView != nil, let location = locationManager.location { mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: kDefaultMapZoom, bearing: 0, viewingAngle: 0) } } } //MARK: - Location Manager Delegate extension MainViewController: CLLocationManagerDelegate { } //MARK: - Map view delegate extension MainViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, willMove gesture: Bool) { shouldUpdateRestaurants = gesture } func mapView(_ mapView: GMSMapView, idleAt position: GMSCameraPosition) { handleToCallAPIGetNearbyRestaurants() } func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { if isUserMarker(marker) { return nil } let inforView = InforWindowView.initFromNib() inforView.frame = CGRect(x: 0, y: 0, width: (self.view.frame.width - 30), height: 70) inforView.restaurant = restaurantAtMarker(marker) return inforView } func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) { goToDetailRestaurantAtMarker(marker) } func didTapMyLocationButton(for mapView: GMSMapView) -> Bool { if let location = locationManager.location { mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: kDefaultMapZoom, bearing: 0, viewingAngle: 0) } return true } } //MARK: - Location manager extension MainViewController { } //MARK: - Add a marker extension MainViewController { fileprivate func updateMarkersOnMap(restaurants: [Restaurant]?) { removeAllMarkers() guard let restaurants = restaurants else { return } restaurantMarkers = [GMSMarker]() for restaurant in restaurants { restaurantMarkers?.append(addAMarkerWithRestaurantInfor(restaurant: restaurant)) } } fileprivate func removeAllMarkers() { clearMapView() if let userLocation = userLocation { updateCurrentUserMarkerWith(location: userLocation) } } fileprivate func clearMapView() { restaurantMarkers?.removeAll() self.mapView.clear() self.userMarker = nil } fileprivate func updateCurrentUserMarkerWith(location: CLLocation) { if self.userMarker == nil { let marker = newUserMarker() self.userMarker = marker } self.userMarker?.position = location.coordinate } fileprivate func newUserMarker() -> GMSMarker { let marker = GMSMarker() marker.title = kStringUserLocationTitle marker.icon = UIImage(named: "icon_user_marker")?.scaledToSize(size: CGSize(width: kMarkerIconWidth, height: kMarkerIconWidth)) marker.map = self.mapView marker.isFlat = true marker.tracksInfoWindowChanges = true return marker } fileprivate func addAMarkerWithRestaurantInfor(restaurant: Restaurant) -> GMSMarker { let marker = GMSMarker() marker.title = restaurant.name marker.icon = UIImage(named: "icon_restaurant.pdf")?.scaledToSize(size: CGSize(width: kMarkerIconWidth, height: kMarkerIconWidth)) marker.map = self.mapView marker.isFlat = true marker.tracksInfoWindowChanges = true let coordinate = CLLocationCoordinate2D(latitude: restaurant.coordinates.latitude, longitude: restaurant.coordinates.longtitude) marker.position = coordinate return marker } fileprivate func isUserMarker(_ marker: GMSMarker) -> Bool { return marker == self.userMarker } } //MARK: - Go to restaurant details extension MainViewController { fileprivate func goToDetailRestaurantAtMarker(_ marker: GMSMarker) { let restaurant = restaurantAtMarker(marker) let storyBoard = UIStoryboard(name: "Main", bundle: nil) let detailVC = storyBoard.instantiateViewController(withIdentifier: RestaurantDetailsViewController.className) as! RestaurantDetailsViewController detailVC.restaurant = restaurant let navi = UINavigationController(rootViewController: detailVC) present(navi, animated: true, completion: nil) } }
cc0-1.0
66b17d0f6d4c1412f05425ec8fad24cf
32.560311
154
0.663072
5.343866
false
false
false
false
rabbitinspace/Tosoka
Tests/TosokaTests/Base64/Base64URLSafeDecodingTests.swift
1
4091
import Foundation import XCTest @testable import Tosoka class Base64URLSafeDecodingTests: XCTestCase { // MARK: - Tests func testDecodingWithoutPadding() { XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3Vy"), "any carnal pleasur" ) } func testDecodingWithOnePadding() { XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3VyZS4="), "any carnal pleasure." ) XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3U="), "any carnal pleasu" ) } func testDecodingWithTwoPadding() { XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3VyZQ=="), "any carnal pleasure" ) XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhcw=="), "any carnal pleas" ) } func testDecodingWithOneDisabledPadding() { XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3VyZS4"), "any carnal pleasure." ) XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3U"), "any carnal pleasu" ) } func testDecodingWithTwoDisabledPadding() { XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhc3VyZQ"), "any carnal pleasure" ) XCTAssertEqual( decode("YW55IGNhcm5hbCBwbGVhcw"), "any carnal pleas" ) } // MARK: - rfc4648 test vectors func testStandardTestVectorsWithPadding() { XCTAssertEqual( decode(""), "" ) XCTAssertEqual( decode("Zg=="), "f" ) XCTAssertEqual( decode("Zm8="), "fo" ) XCTAssertEqual( decode("Zm9v"), "foo" ) XCTAssertEqual( decode("Zm9vYg=="), "foob" ) XCTAssertEqual( decode("Zm9vYmE="), "fooba" ) XCTAssertEqual( decode("Zm9vYmFy"), "foobar" ) } func testStandardTestVectorsWithoutPadding() { XCTAssertEqual( decode(""), "" ) XCTAssertEqual( decode("Zg"), "f" ) XCTAssertEqual( decode("Zm8"), "fo" ) XCTAssertEqual( decode("Zm9v"), "foo" ) XCTAssertEqual( decode("Zm9vYg"), "foob" ) XCTAssertEqual( decode("Zm9vYmE"), "fooba" ) XCTAssertEqual( decode("Zm9vYmFy"), "foobar" ) } // MARK: - Private private func decode(_ string: String) -> String? { guard let data = string.data(using: .utf8) else { XCTFail() return nil } let coder = Base64(coder: URLSafeCodingAlphabet.self) guard let result = try? coder.decode(data) else { XCTFail() return nil } return String(data: result, encoding: .utf8) } // MARK: - All tests static var allTests : [(String, (Base64URLSafeDecodingTests) -> () throws -> Void)] { return [ ("testDecodingWithoutPadding", testDecodingWithoutPadding), ("testDecodingWithOnePadding", testDecodingWithOnePadding), ("testDecodingWithTwoPadding", testDecodingWithTwoPadding), ("testDecodingWithOneDisabledPadding", testDecodingWithOneDisabledPadding), ("testDecodingWithTwoDisabledPadding", testDecodingWithTwoDisabledPadding), ("testStandardTestVectorsWithPadding", testStandardTestVectorsWithPadding), ("testStandardTestVectorsWithoutPadding", testStandardTestVectorsWithoutPadding), ] } }
mit
de88a130d316c918e9170ad7cfb548b6
22.784884
93
0.495478
5.491275
false
true
false
false
HabitRPG/habitrpg-ios
Habitica Database/Habitica Database/Models/User/RealmSubscriptionConsecutive.swift
1
911
// // RealmSubscriptionConsecutive.swift // Habitica Database // // Created by Phillip Thelen on 23.04.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import RealmSwift class RealmSubscriptionConsecutive: Object, SubscriptionConsecutiveProtocol { @objc dynamic var hourglasses: Int = 0 @objc dynamic var gemCapExtra: Int = 0 @objc dynamic var count: Int = 0 @objc dynamic var offset: Int = 0 @objc dynamic var id: String? override static func primaryKey() -> String { return "id" } convenience init(userID: String?, protocolObject: SubscriptionConsecutiveProtocol) { self.init() self.id = userID hourglasses = protocolObject.hourglasses gemCapExtra = protocolObject.gemCapExtra count = protocolObject.count offset = protocolObject.offset } }
gpl-3.0
6ed45f9188c9228ad8dad2cb228b00ab
26.575758
88
0.686813
4.55
false
false
false
false
kstaring/swift
test/SILGen/errors.swift
1
44294
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s import Swift class Cat {} enum HomeworkError : Error { case TooHard case TooMuch case CatAteIt(Cat) } func someValidPointer<T>() -> UnsafePointer<T> { fatalError() } func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() } // CHECK: sil hidden @_TF6errors10make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: return [[T2]] : $Cat func make_a_cat() throws -> Cat { return Cat() } // CHECK: sil hidden @_TF6errors15dont_make_a_cat{{.*}} : $@convention(thin) () -> (@owned Cat, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[BOX]] func dont_make_a_cat() throws -> Cat { throw HomeworkError.TooHard } // CHECK: sil hidden @_TF6errors11dont_return{{.*}} : $@convention(thin) <T> (@in T) -> (@out T, @error Error) { // CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError // CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error // CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type // CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt // CHECK-NEXT: store [[T1]] to [init] [[ADDR]] // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: destroy_addr %1 : $*T // CHECK-NEXT: throw [[BOX]] func dont_return<T>(_ argument: T) throws -> T { throw HomeworkError.TooMuch } // CHECK: sil hidden @_TF6errors16all_together_nowFSbCS_3Cat : $@convention(thin) (Bool) -> @owned Cat { // CHECK: bb0(%0 : $Bool): // CHECK: [[DR_FN:%.*]] = function_ref @_TF6errors11dont_returnur{{.*}} : // Branch on the flag. // CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]] // In the true case, call make_a_cat(). // CHECK: [[FLAG_TRUE]]: // CHECK: [[MAC_FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]] // CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat) // In the false case, call dont_make_a_cat(). // CHECK: [[FLAG_FALSE]]: // CHECK: [[DMAC_FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]] // CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat): // CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat) // Merge point for the ternary operator. Call dont_return with the result. // CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat): // CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]] // CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat // CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]] // CHECK: [[DR_NORMAL]]({{%.*}} : $()): // CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat // CHECK-NEXT: dealloc_stack [[RET_TEMP]] // CHECK-NEXT: dealloc_stack [[ARG_TEMP]] // CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat) // Return block. // CHECK: [[RETURN]]([[T0:%.*]] : $Cat): // CHECK-NEXT: return [[T0]] : $Cat // Catch dispatch block. // CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error // CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]] // CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError // CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]] // Catch HomeworkError. // CHECK: [[IS_HWE]]: // CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError // CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]] // Catch HomeworkError.CatAteIt. // CHECK: [[MATCH]]([[T0:%.*]] : $Cat): // CHECK-NEXT: debug_value // CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: destroy_addr [[SRC_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat) // Catch other HomeworkErrors. // CHECK: [[NO_MATCH]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch other types. // CHECK: [[NOT_HWE]]: // CHECK-NEXT: dealloc_stack [[DEST_TEMP]] // CHECK-NEXT: dealloc_stack [[SRC_TEMP]] // CHECK-NEXT: br [[CATCHALL:bb[0-9]+]] // Catch all. // CHECK: [[CATCHALL]]: // CHECK: [[T0:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]]) // CHECK-NEXT: destroy_value [[ERROR]] : $Error // CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat) // Landing pad. // CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) // CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error): // CHECK-NEXT: dealloc_stack // CHECK-NEXT: dealloc_stack // CHECK-NEXT: br [[CATCH]]([[T0]] : $Error) func all_together_now(_ flag: Bool) -> Cat { do { return try dont_return(flag ? make_a_cat() : dont_make_a_cat()) } catch HomeworkError.CatAteIt(let cat) { return cat } catch _ { return Cat() } } // Catch in non-throwing context. // CHECK-LABEL: sil hidden @_TF6errors11catch_a_catFT_CS_3Cat : $@convention(thin) () -> @owned Cat // CHECK-NEXT: bb0: // CHECK: [[F:%.*]] = function_ref @_TFC6errors3CatC{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat // CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type // CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]]) // CHECK-NEXT: return [[V]] : $Cat func catch_a_cat() -> Cat { do { return Cat() } catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}} } // Initializers. class HasThrowingInit { var field: Int init(value: Int) throws { field = value } } // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) { // CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $HasThrowingInit // CHECK-NEXT: assign %0 to [[T1]] : $*Int // CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]] // CHECK-NEXT: destroy_value [[T0]] // CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit // CHECK-LABEL: sil hidden @_TFC6errors15HasThrowingInitC{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error) // CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit // CHECK: [[T0:%.*]] = function_ref @_TFC6errors15HasThrowingInitc{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2 // CHECK: bb1([[SELF:%.*]] : $HasThrowingInit): // CHECK-NEXT: return [[SELF]] // CHECK: bb2([[ERROR:%.*]] : $Error): // CHECK-NEXT: builtin "willThrow" // CHECK-NEXT: throw [[ERROR]] enum ColorError : Error { case Red, Green, Blue } //CHECK-LABEL: sil hidden @_TF6errors6IThrowFzT_Vs5Int32 //CHECK: builtin "willThrow" //CHECK-NEXT: throw func IThrow() throws -> Int32 { throw ColorError.Red return 0 // expected-warning {{will never be executed}} } // Make sure that we are not emitting calls to 'willThrow' on rethrow sites. //CHECK-LABEL: sil hidden @_TF6errors12DoesNotThrowFzT_Vs5Int32 //CHECK-NOT: builtin "willThrow" //CHECK: return func DoesNotThrow() throws -> Int32 { _ = try IThrow() return 2 } // rdar://20782111 protocol Doomed { func check() throws } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors12DoomedStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors12DoomedStruct5check{{.*}} : $@convention(method) (DoomedStruct) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error struct DoomedStruct : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors11DoomedClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error { // CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> () , $@convention(method) (@guaranteed DoomedClass) -> @error Error // CHECK-NEXT: try_apply [[T0]]([[SELF]]) // CHECK: bb1([[T0:%.*]] : $()): // CHECK: [[T0:%.*]] = tuple () // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T0]] : $() // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: destroy_value [[SELF]] : $DoomedClass // CHECK: dealloc_stack [[TEMP]] // CHECK: throw [[T0]] : $Error class DoomedClass : Doomed { func check() throws {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV6errors11HappyStructS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct // CHECK: [[T0:%.*]] = function_ref @_TFV6errors11HappyStruct5check{{.*}} : $@convention(method) (HappyStruct) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() struct HappyStruct : Doomed { func check() {} } // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC6errors10HappyClassS_6DoomedS_FS1_5check{{.*}} : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error // CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass // CHECK: copy_addr %0 to [initialization] [[TEMP]] // CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass // CHECK: [[T0:%.*]] = class_method [[SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> () , $@convention(method) (@guaranteed HappyClass) -> () // CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]]) // CHECK: [[T1:%.*]] = tuple () // CHECK: destroy_value [[SELF]] : $HappyClass // CHECK: dealloc_stack [[TEMP]] // CHECK: return [[T1]] : $() class HappyClass : Doomed { func check() {} } func create<T>(_ fn: () throws -> T) throws -> T { return try fn() } func testThunk(_ fn: () throws -> Int) throws -> Int { return try create(fn) } // CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo__dSizoPs5Error__XFo__iSizoPS___ : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error) // CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)): // CHECK: try_apply %1() // CHECK: bb1([[T0:%.*]] : $Int): // CHECK: store [[T0]] to [trivial] %0 : $*Int // CHECK: [[T0:%.*]] = tuple () // CHECK: return [[T0]] // CHECK: bb2([[T0:%.*]] : $Error): // CHECK: builtin "willThrow"([[T0]] : $Error) // CHECK: throw [[T0]] : $Error func createInt(_ fn: () -> Int) throws {} func testForceTry(_ fn: () -> Int) { try! createInt(fn) } // CHECK-LABEL: sil hidden @_TF6errors12testForceTryFFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> () // CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int): // CHECK: [[FUNC:%.*]] = function_ref @_TF6errors9createIntFzFT_SiT_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error // CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK: try_apply [[FUNC]]([[ARG_COPY]]) // CHECK: destroy_value [[ARG]] // CHECK: return // CHECK: builtin "unexpectedError" // CHECK: unreachable func testForceTryMultiple() { _ = try! (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors20testForceTryMultipleFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error) // CHECK-NEXT: unreachable // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors20testForceTryMultipleFT_T_' // Make sure we balance scopes correctly inside a switch. // <rdar://problem/20923654> enum CatFood { case Canned case Dry } // Something we can switch on that throws. func preferredFood() throws -> CatFood { return CatFood.Canned } func feedCat() throws -> Int { switch try preferredFood() { case .Canned: return 0 case .Dry: return 1 } } // CHECK-LABEL: sil hidden @_TF6errors7feedCatFzT_Si : $@convention(thin) () -> (Int, @error Error) // CHECK: debug_value undef : $Error, var, name "$error", argno 1 // CHECK: %1 = function_ref @_TF6errors13preferredFoodFzT_OS_7CatFood : $@convention(thin) () -> (CatFood, @error Error) // CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5 // CHECK: bb1([[VAL:%.*]] : $CatFood): // CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3 // CHECK: bb5([[ERROR:%.*]] : $Error) // CHECK: throw [[ERROR]] : $Error // Throwing statements inside cases. func getHungryCat(_ food: CatFood) throws -> Cat { switch food { case .Canned: return try make_a_cat() case .Dry: return try dont_make_a_cat() } } // errors.getHungryCat throws (errors.CatFood) -> errors.Cat // CHECK-LABEL: sil hidden @_TF6errors12getHungryCatFzOS_7CatFoodCS_3Cat : $@convention(thin) (CatFood) -> (@owned Cat, @error Error) // CHECK: bb0(%0 : $CatFood): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3 // CHECK: bb1: // CHECK: [[FN:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6 // CHECK: bb3: // CHECK: [[FN:%.*]] = function_ref @_TF6errors15dont_make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7 // CHECK: bb6([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR:%.*]] : $Error) // CHECK: bb7([[ERROR:%.*]] : $Error): // CHECK: br bb8([[ERROR]] : $Error) // CHECK: bb8([[ERROR:%.*]] : $Error): // CHECK: throw [[ERROR]] : $Error func take_many_cats(_ cats: Cat...) throws {} func test_variadic(_ cat: Cat) throws { try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors13test_variadicFzCS_3CatT_ : $@convention(thin) (@owned Cat) -> @error Error { // CHECK: bb0([[ARG:%.*]] : $Cat): // CHECK: debug_value undef : $Error, var, name "$error", argno 2 // CHECK: [[TAKE_FN:%.*]] = function_ref @_TF6errors14take_many_catsFztGSaCS_3Cat__T_ : $@convention(thin) (@owned Array<Cat>) -> @error Error // CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4 // CHECK: [[T0:%.*]] = function_ref @_TFs27_allocateUninitializedArray // CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]]) // CHECK: [[ARRAY:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 0 // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : $(Array<Cat>, Builtin.RawPointer), 1 // CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat // Element 0. // CHECK: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]] // CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat): // CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]] // Element 1. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1 // CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[ARG]] // CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]] // Element 2. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2 // CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]] // CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat): // CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]] // Element 3. // CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3 // CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat : $@convention(thin) () -> (@owned Cat, @error Error) // CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]] // CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat): // CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]] // Complete the call and return. // CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]] // CHECK: [[NORM_CALL]]([[T0:%.*]] : $()): // CHECK-NEXT: destroy_value %0 : $Cat // CHECK-NEXT: [[T0:%.*]] = tuple () // CHECK-NEXT: return // Failure from element 0. // CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error) // Failure from element 2. // CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from element 3. // CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_addr [[ELT2]] // CHECK-NEXT: destroy_addr [[ELT1]] // CHECK-NEXT: destroy_addr [[ELT0]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[T0:%.*]] = function_ref @_TFs29_deallocateUninitializedArray // CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]]) // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Failure from call. // CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error) // Rethrow. // CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value %0 : $Cat // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors13test_variadicFzCS_3CatT_' // rdar://20861374 // Clear out the self box before delegating. class BaseThrowingInit : HasThrowingInit { var subField: Int init(value: Int, subField: Int) throws { self.subField = subField try super.init(value: value) } } // CHECK: sil hidden @_TFC6errors16BaseThrowingInitc{{.*}} : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error) // CHECK: [[BOX:%.*]] = alloc_box $@box BaseThrowingInit // CHECK: [[PB:%.*]] = project_box [[BOX]] // CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]] // Initialize subField. // CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]] // CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField // CHECK-NEXT: assign %1 to [[T1]] // Super delegation. // CHECK-NEXT: [[T0:%.*]] = load_borrow [[MARKED_BOX]] // CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit // CHECK: [[T3:%[0-9]+]] = function_ref @_TFC6errors15HasThrowingInitcfzT5valueSi_S0_ : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) // CHECK-NEXT: apply [[T3]](%0, [[T2]]) // Cleanups for writebacks. protocol Supportable { mutating func support() throws } protocol Buildable { associatedtype Structure : Supportable var firstStructure: Structure { get set } subscript(name: String) -> Structure { get set } } func supportFirstStructure<B: Buildable>(_ b: inout B) throws { try b.firstStructure.support() } // CHECK-LABEL: sil hidden @_TF6errors21supportFirstStructure{{.*}} : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error { // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: throw [[ERROR]] func supportStructure<B: Buildable>(_ b: inout B, name: String) throws { try b[name].support() } // CHECK-LABEL: sil hidden @_TF6errors16supportStructure // CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 : // CHECK: [[INDEX_COPY:%.*]] = copy_value [[INDEX:%1]] : $String // CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer // CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure // CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer // CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 : // CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]]) // CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0 // CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1 // CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure // CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B // CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK: switch_enum [[CALLBACK]] // CHECK: apply // CHECK: dealloc_stack [[BUFFER]] // CHECK: dealloc_stack [[MATBUFFER]] // CHECK: destroy_value [[INDEX]] : $String // CHECK: throw [[ERROR]] struct Pylon { var name: String mutating func support() throws {} } struct Bridge { var mainPylon : Pylon subscript(name: String) -> Pylon { get { return mainPylon } set {} } } func supportStructure(_ b: inout Bridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_ : $@convention(thin) (@inout Bridge, @owned String) -> @error Error { // CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String // CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon // CHECK-NEXT: [[BASE:%.*]] = load [copy] [[ARG1]] : $*Bridge // CHECK-NEXT: // function_ref // CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFV6errors6Bridgeg9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]]) // CHECK-NEXT: destroy_value [[BASE]] // CHECK-NEXT: store [[T0]] to [init] [[TEMP]] // CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[ARG1]]) // CHECK-NEXT: dealloc_stack [[TEMP]] // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // We end up with ugly redundancy here because we don't want to // consume things during cleanup emission. It's questionable. // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]] // CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]] // CHECK-NEXT: // function_ref // CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFV6errors6Bridges9subscriptFSSVS_5Pylon : // CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[ARG1]]) // CHECK-NEXT: destroy_addr [[TEMP]] // CHECK-NEXT: dealloc_stack [[TEMP]] // ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY // CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String // CHECK-NEXT: destroy_value [[INDEX]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_6Bridge4nameSS_T_' struct OwnedBridge { var owner : Builtin.UnknownObject subscript(name: String) -> Pylon { addressWithOwner { return (someValidPointer(), owner) } mutableAddressWithOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout OwnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_ : // CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors11OwnedBridgeaO9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_11OwnedBridge4nameSS_T_' struct PinnedBridge { var owner : Builtin.NativeObject subscript(name: String) -> Pylon { addressWithPinnedNativeOwner { return (someValidPointer(), owner) } mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) } } } func supportStructure(_ b: inout PinnedBridge, name: String) throws { try b[name].support() } // CHECK: sil hidden @_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_ : // CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String): // CHECK: [[SUPPORT:%.*]] = function_ref @_TFV6errors5Pylon7support // CHECK: [[ARG2_COPY:%.*]] = copy_value [[ARG2]] : $String // CHECK-NEXT: // function_ref // CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_TFV6errors12PinnedBridgeap9subscriptFSSVS_5Pylon : // CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]]) // CHECK-NEXT: [[T1:%.*]] = tuple_extract [[T0]] : {{.*}}, 0 // CHECK-NEXT: [[OWNER:%.*]] = tuple_extract [[T0]] : {{.*}}, 1 // CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]] // CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]] // CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]] // CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]] // CHECK: [[BB_NORMAL]] // CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: tuple () // CHECK-NEXT: return // CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]] // CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject> // CHECK-NEXT: destroy_value [[OWNER]] // CHECK-NEXT: destroy_value [[ARG2]] : $String // CHECK-NEXT: throw [[ERROR]] // CHECK: } // end sil function '_TF6errors16supportStructureFzTRVS_12PinnedBridge4nameSS_T_' // ! peepholes its argument with getSemanticsProvidingExpr(). // Test that that doesn't look through try!. // rdar://21515402 func testForcePeephole(_ f: () throws -> Int?) -> Int { let x = (try! f())! return x } // CHECK-LABEL: sil hidden @_TF6errors15testOptionalTryFT_T_ // CHECK-NEXT: bb0: // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>) // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors15testOptionalTryFT_T_' func testOptionalTry() { _ = try? make_a_cat() } // CHECK-LABEL: sil hidden @_TF6errors18testOptionalTryVarFT_T_ // CHECK-NEXT: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $@box Optional<Cat> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat) // CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1 // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : $@box Optional<Cat> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors18testOptionalTryVarFT_T_' func testOptionalTryVar() { var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors26testOptionalTryAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors26testOptionalTryAddressOnlyurFxT_' func testOptionalTryAddressOnly<T>(_ obj: T) { _ = try? dont_return(obj) } // CHECK-LABEL: sil hidden @_TF6errors29testOptionalTryAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $@box Optional<T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK: [[FN:%.+]] = function_ref @_TF6errors11dont_return // CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T // CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T // CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]], // CHECK: [[SUCCESS]]({{%.+}} : $()): // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[DONE:[^ ]+]], // CHECK: [[DONE]]: // CHECK-NEXT: destroy_value [[BOX]] : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]] // CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors29testOptionalTryAddressOnlyVarurFxT_' func testOptionalTryAddressOnlyVar<T>(_ obj: T) { var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors23testOptionalTryMultipleFT_T_ // CHECK: bb0: // CHECK: [[FN_1:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]], // CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat) // CHECK: [[FN_2:%.+]] = function_ref @_TF6errors10make_a_catFzT_CS_3Cat // CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]], // CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat) // CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat) // CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]] // CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>) // CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>): // CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error): // CHECK-NEXT: destroy_value [[ERROR]] // CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt // CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>) // CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error): // CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat // CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error) // CHECK: } // end sil function '_TF6errors23testOptionalTryMultipleFT_T_' func testOptionalTryMultiple() { _ = try? (make_a_cat(), make_a_cat()) } // CHECK-LABEL: sil hidden @_TF6errors25testOptionalTryNeverFailsFT_T_ // CHECK: bb0: // CHECK-NEXT: [[VALUE:%.+]] = tuple () // CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]] // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_TF6errors25testOptionalTryNeverFailsFT_T_' func testOptionalTryNeverFails() { _ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors28testOptionalTryNeverFailsVarFT_T_ // CHECK: bb0: // CHECK-NEXT: [[BOX:%.+]] = alloc_box $@box Optional<()> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : $@box Optional<()> // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_TF6errors28testOptionalTryNeverFailsVarFT_T_' func testOptionalTryNeverFailsVar() { var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}} } // CHECK-LABEL: sil hidden @_TF6errors36testOptionalTryNeverFailsAddressOnly // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_stack $Optional<T> // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T> // CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK-NEXT: } // end sil function '_TF6errors36testOptionalTryNeverFailsAddressOnlyurFxT_' func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) { _ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} } // CHECK-LABEL: sil hidden @_TF6errors39testOptionalTryNeverFailsAddressOnlyVar // CHECK: bb0(%0 : $*T): // CHECK: [[BOX:%.+]] = alloc_box $@box Optional<T> // CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]] // CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T // CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1 // CHECK-NEXT: destroy_value [[BOX]] : $@box Optional<T> // CHECK-NEXT: destroy_addr %0 : $*T // CHECK-NEXT: [[VOID:%.+]] = tuple () // CHECK-NEXT: return [[VOID]] : $() // CHECK: } // end sil function '_TFC6errors13OtherErrorSubCfT_S0_' func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) { var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}} } class SomeErrorClass : Error { } // CHECK-LABEL: sil_vtable SomeErrorClass // CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _TFC6errors14SomeErrorClassD // CHECK-NEXT: #SomeErrorClass.init!initializer.1: _TFC6errors14SomeErrorClasscfT_S0_ // CHECK-NEXT: } class OtherErrorSub : OtherError { } // CHECK-LABEL: sil_vtable OtherErrorSub { // CHECK-NEXT: #OtherError.init!initializer.1: _TFC6errors13OtherErrorSubcfT_S0_ // OtherErrorSub.init() -> OtherErrorSub // CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _TFC6errors13OtherErrorSubD // OtherErrorSub.__deallocating_deinit // CHECK-NEXT:}
apache-2.0
24c7af4577253332c0b6e9d98ae60f3b
47.879691
234
0.603229
3.195858
false
false
false
false
badoo/Chatto
Chatto/sources/ChatController/ChatMessages/New/ChatCollectionViewLayoutModelFactory.swift
1
3861
/* The MIT License (MIT) Copyright (c) 2015-present Badoo Trading Limited. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import UIKit public protocol ChatCollectionViewLayoutModelFactoryProtocol: AnyObject { func createLayoutModel(items: ChatItemCompanionCollection, collectionViewWidth: CGFloat) -> ChatCollectionViewLayoutModel } final class ChatCollectionViewLayoutModelFactory: ChatCollectionViewLayoutModelFactoryProtocol { // MARK: - Type declarations private struct HeightValue { var value: CGFloat = 0 private let heightProvider: () -> CGFloat init(_ heightProvider: @escaping () -> CGFloat) { self.heightProvider = heightProvider } mutating func calculate() { self.value = self.heightProvider() } } // MARK: - Instantiation init() {} // MARK: - ChatCollectionViewLayoutUpdater public func createLayoutModel(items: ChatItemCompanionCollection, collectionViewWidth width: CGFloat) -> ChatCollectionViewLayoutModel { var heights = items.map { companion in HeightValue { companion.height(forMaxWidth: width) } } enum ExecutionContext { case this, main } let isMainThread = Thread.isMainThread let contexts: Indices<ExecutionContext> = Indices(of: items) { isMainThread || $0.presenter.canCalculateHeightInBackground ? .this : .main } for index in contexts[.this] { heights[index].calculate() } if !contexts[.main].isEmpty { DispatchQueue.main.sync { for index in contexts[.main] { heights[index].calculate() } } } let heightValues = heights.map { $0.value } let bottomMargins = items.map(\.bottomMargin) let layoutData = Array(zip(heightValues, bottomMargins)) return ChatCollectionViewLayoutModel.createModel(width, itemsLayoutData: layoutData) } } private extension ChatItemCompanion { func height(forMaxWidth maxWidth: CGFloat) -> CGFloat { self.presenter.heightForCell(maximumWidth: maxWidth, decorationAttributes: self.decorationAttributes) } var bottomMargin: CGFloat { self.decorationAttributes?.bottomMargin ?? 0 } } private struct Indices<Key: Hashable> { private let indicesByKey: [Key: Set<Int>] init<C: Collection>(of collection: C, decide: (C.Element) -> Key) where C.Index == Int { var indicesByKey: [Key: Set<Int>] = [:] for (index, element) in collection.enumerated() { indicesByKey[decide(element), default: []].insert(index) } self.indicesByKey = indicesByKey } subscript(_ key: Key) -> Set<Int> { self.indicesByKey[key] ?? [] } }
mit
98ba6e9ca3d8293c914718e457e18d93
32
96
0.677545
5.047059
false
false
false
false
vulgur/WeeklyFoodPlan
WeeklyFoodPlan/WeeklyFoodPlan/Models/DailyPlan.swift
1
768
// // DailyPlan.swift // WeeklyFoodPlan // // Created by vulgur on 2017/3/3. // Copyright © 2017年 MAD. All rights reserved. // import Foundation import RealmSwift class DailyPlan: Object { dynamic var id = UUID().uuidString dynamic var date = Date() dynamic var isExpired = false var meals = List<Meal>() override static func primaryKey() -> String? { return "id" } convenience init(plan: DailyPlan) { self.init() self.date = plan.date self.meals.append(contentsOf: plan.meals) } func reduceIngredients() { for meal in self.meals { for mealFood in meal.mealFoods { mealFood.food?.reduceNeedIngredientCount() } } } }
mit
2bf999b35fa41ac7344cc291b59a3c22
20.857143
58
0.589542
4.203297
false
false
false
false
ruter/Strap-in-Swift
Instafilter/Instafilter/ViewController.swift
1
5117
// // ViewController.swift // Instafilter // // Created by Ruter on 16/4/24. // Copyright © 2016年 Ruter. All rights reserved. // import UIKit class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var intensity: UISlider! var currentImage: UIImage! var context: CIContext! var currentFilter: CIFilter! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. title = "Instafilter" navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(importPicture)) context = CIContext(options: nil) currentFilter = CIFilter(name: "CISepiaTone") intensity.value = 0 intensity.enabled = false } func importPicture() { let picker = UIImagePickerController() picker.allowsEditing = true picker.delegate = self presentViewController(picker, animated: true, completion: nil) } @IBAction func changeFilter(sender: UIButton) { let ac = UIAlertController(title: "Choose filter", message: nil, preferredStyle: .ActionSheet) ac.addAction(UIAlertAction(title: "CIBumpDistortion", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIGaussianBlur", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIPixellate", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CISepiaTone", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CITwirlDistortion", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIUnsharpMask", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "CIVignette", style: .Default, handler: setFilter)) ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)) presentViewController(ac, animated: true, completion: nil) } @IBAction func save(sender: UIButton) { UIImageWriteToSavedPhotosAlbum(imageView.image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil) } @IBAction func intensityChanged(sender: UISlider) { applyProcessing() } func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafePointer<Void>) { if error == nil { let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } else { let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) } } func applyProcessing() { let inputKeys = currentFilter.inputKeys if inputKeys.contains(kCIInputIntensityKey) { currentFilter.setValue(intensity.value, forKey: kCIInputIntensityKey) } if inputKeys.contains(kCIInputRadiusKey) { currentFilter.setValue(intensity.value * 200, forKey: kCIInputRadiusKey) } if inputKeys.contains(kCIInputScaleKey) { currentFilter.setValue(intensity.value * 10, forKey: kCIInputScaleKey) } if inputKeys.contains(kCIInputCenterKey) { currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey) } let cgimg = context.createCGImage(currentFilter.outputImage!, fromRect: currentFilter.outputImage!.extent) let processedImage = UIImage(CGImage: cgimg) imageView.image = processedImage } func setFilter(action: UIAlertAction) { currentFilter = CIFilter(name: action.title!) let beginImage = CIImage(image: currentImage) currentFilter.setValue(beginImage, forKey: kCIInputImageKey) applyProcessing() } // MARK: - imagePicker delegate func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { var newImage: UIImage if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage { newImage = possibleImage } else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage { newImage = possibleImage } else { return } dismissViewControllerAnimated(true, completion: nil) currentImage = newImage let beginImage = CIImage(image: currentImage) currentFilter.setValue(beginImage, forKey: kCIInputImageKey) applyProcessing() intensity.enabled = true } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
0b41839169f53413cd5435792d2beb7e
36.057971
135
0.7237
4.810913
false
false
false
false
bvic23/VinceRP
VinceRPTests/Common/Threading/AtomicReferenceSpec.swift
1
1456
//// //// Created by Viktor Belenyesi on 22/04/15. //// Copyright (c) 2015 Viktor Belenyesi. All rights reserved. //// // //@testable import VinceRP // //import Quick //import Nimble // //class Foo: Equatable { // let i: Int // init(_ i: Int) { // self.i = i // } //} // //func ==(lhs: Foo, rhs: Foo) -> Bool { // return lhs.i == rhs.i //} // //class AtomicReferenceSpec: QuickSpec { // // override func spec() { // // describe("default") { // // it("should have all the normal operations") { // // given // let thing1 = Foo(5) // let thing1bis = Foo(5) // equals(), but not the same reference // let thing2 = Foo(10) // // // when // let atomic = AtomicReference(thing1) // // // then // expect(atomic.value) == thing1 // atomic.value = thing2 // // expect(atomic.value) == thing2 // expect(atomic.compareAndSet(thing1, thing1)) == false // // expect(atomic.value) == thing2 // expect(atomic.compareAndSet(thing2, thing1)) == true // // expect(atomic.value) == thing1 // expect(atomic.compareAndSet(thing1bis, thing2)) == false // // expect(atomic.getAndSet(thing2)) == thing1 // expect(atomic.value) == thing2 // } // // } // // } // //}
mit
a586a2cfac3109296001bacde803cd36
24.103448
80
0.480082
3.559902
false
false
false
false
rahulsend89/MemoryGame
MemoryGame/BlockCVC.swift
1
1779
// // BlockCVC.swift // MemoryGame // // Created by Rahul Malik on 7/15/17. // Copyright © 2017 aceenvisage. All rights reserved. // import UIKit.UICollectionViewCell class BlockCVC: UICollectionViewCell { // MARK: - Properties @IBOutlet weak var frontImageView: UIImageView! @IBOutlet weak var backImageView: UIImageView! var block: Block? { didSet { guard let block = block else { return } frontImageView.image = block.image } } fileprivate(set) var shown: Bool = false // MARK: - Methods func showBlock(_ show: Bool, animted: Bool) { frontImageView.isHidden = false backImageView.isHidden = false shown = show if animted { if show { UIView.transition(from: backImageView, to: frontImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } else { UIView.transition(from: frontImageView, to: backImageView, duration: 0.5, options: [.transitionFlipFromRight, .showHideTransitionViews], completion: { (_: Bool) -> Void in }) } } else { if show { bringSubview(toFront: frontImageView) backImageView.isHidden = true } else { bringSubview(toFront: backImageView) frontImageView.isHidden = true } } } }
mit
5432e0866c13cedbc0880d3d671bc52d
28.633333
96
0.490439
5.680511
false
false
false
false
rb-de0/Fluxer
Sources/Flux/Dispatcher.swift
1
3050
// // Dispatcher.swift // Fluxer // // Created by rb_de0 on 2017/03/21. // Copyright © 2017年 rb_de0. All rights reserved. // import Foundation public final class Dispatcher { public typealias AsyncActionCallback = (Action) -> () public typealias AsyncActionCreator = (@escaping AsyncActionCallback) -> () private let lock = NSLock() private var actionHandlers = [ActionHandler]() private var isDispatching = false public init() {} public func dispatch(_ action: Action) { lock.lock() defer { lock.unlock() } startDispatch() actionHandlers.forEach { handler in invokeActionHandler(handler: handler, action: action) } stopDispatching() } public func dispatch(_ asyncActionCreator: AsyncActionCreator) { asyncActionCreator {[weak self] action in guard let strongSelf = self else { return } strongSelf.dispatch(action) } } public func dispatch(_ asyncAction: AsyncAction) { dispatch(asyncAction.exec) } public func waitFor(_ registrationTokens: [String], action: Action) { guard isDispatching else { fatalError("waitFor must be invoked while dispatching") } for registrationToken in registrationTokens { guard let handler = actionHandlers.filter ({ $0.registrationToken == registrationToken }).first else { continue } if handler.status == .pending { fatalError("circular dependency detected while") } if handler.status == .waiting { invokeActionHandler(handler: handler, action: action) } } } public func register(_ handler: @escaping (Action) -> ()) -> String { let registrationToken = generateRegistrationToken() actionHandlers.append(ActionHandler(registrationToken, handler, .waiting)) return registrationToken } public func unregister(registrationToken: String) { actionHandlers = actionHandlers.filter { $0.registrationToken != registrationToken } } // MARK: - Private private func startDispatch() { actionHandlers.forEach { $0.status = .waiting } isDispatching = true } private func stopDispatching() { isDispatching = false } private func invokeActionHandler(handler: ActionHandler, action: Action) { guard handler.status == .waiting else { return } handler.status = .pending handler.handleFunc(action) handler.status = .handled } private func generateRegistrationToken() -> String { return UUID().uuidString } }
mit
cafff6028d4c6c1a2f4ca40d6e289f9f
24.605042
114
0.558254
5.826004
false
false
false
false
MagicLab-team/BannerView
BannerView/BannerCollectionView.swift
1
1222
// // BannerCollectionView.swift // BannerView // // Created by Roman Sorochak on 7/6/17. // Copyright © 2017 MagicLab. All rights reserved. // import UIKit public class BannerCollectionView: UICollectionView { var isTouching: Bool = false public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) isTouching = true print("touchesBegan: \(isTouching)") } override public func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) isTouching = true print("touchesMoved: \(isTouching)") } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesEnded(touches, with: event) isTouching = false print("touchesEnded: \(isTouching)") } override public func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesCancelled(touches, with: event) isTouching = false print("touchesCancelled: \(isTouching)") } }
mit
9014427ba19bcd0a3bd55cc1ec2cd197
24.4375
90
0.608518
5.06639
false
false
false
false
tlax/GaussSquad
GaussSquad/View/CalculatorOptions/VCalculatorOptionsHeader.swift
1
3240
import UIKit class VCalculatorOptionsHeader:UICollectionReusableView { private weak var controller:CCalculatorOptions? private weak var layoutNoneTop:NSLayoutConstraint! private let kLabelLeft:CGFloat = 10 private let kLabelWidth:CGFloat = 200 private let kButtonRight:CGFloat = -10 private let kButtonWidth:CGFloat = 120 private let kButtonHeight:CGFloat = 34 override init(frame:CGRect) { super.init(frame:frame) clipsToBounds = true backgroundColor = UIColor.white let labelTitle:UILabel = UILabel() labelTitle.translatesAutoresizingMaskIntoConstraints = false labelTitle.backgroundColor = UIColor.clear labelTitle.isUserInteractionEnabled = false labelTitle.font = UIFont.bold(size:17) labelTitle.textColor = UIColor.black labelTitle.text = NSLocalizedString("VCalculatorOptionsHeader_title", comment:"") let buttonNone:UIButton = UIButton() buttonNone.translatesAutoresizingMaskIntoConstraints = false buttonNone.clipsToBounds = true buttonNone.backgroundColor = UIColor.squadRed buttonNone.layer.cornerRadius = kButtonHeight / 2.0 buttonNone.setTitle( NSLocalizedString("VCalculatorOptionsHeader_buttonNone", comment:""), for:UIControlState.normal) buttonNone.setTitleColor( UIColor.white, for:UIControlState.normal) buttonNone.setTitleColor( UIColor(white:1, alpha:0.2), for:UIControlState.highlighted) buttonNone.titleLabel?.font = UIFont.bold(size:14) buttonNone.addTarget( self, action:#selector(actionNone(sender:)), for:UIControlEvents.touchUpInside) addSubview(labelTitle) addSubview(buttonNone) NSLayoutConstraint.equalsVertical( view:labelTitle, toView:self) NSLayoutConstraint.leftToLeft( view:labelTitle, toView:self, constant:kLabelLeft) NSLayoutConstraint.width( view:labelTitle, constant:kLabelWidth) layoutNoneTop = NSLayoutConstraint.topToTop( view:buttonNone, toView:self) NSLayoutConstraint.height( view:buttonNone, constant:kButtonHeight) NSLayoutConstraint.width( view:buttonNone, constant:kButtonWidth) NSLayoutConstraint.rightToRight( view:buttonNone, toView:self, constant:kButtonRight) } required init?(coder:NSCoder) { return nil } override func layoutSubviews() { let height:CGFloat = bounds.maxY let remain:CGFloat = height - kButtonHeight let marginTop:CGFloat = remain / 2.0 layoutNoneTop.constant = marginTop super.layoutSubviews() } //MARK: actions func actionNone(sender button:UIButton) { controller?.selectOption(item:nil) } //MARK: public func config(controller:CCalculatorOptions) { self.controller = controller } }
mit
d2deb07cfcd9e965388df50ed503fa28
30.153846
89
0.630247
5.615251
false
false
false
false
tinypass/piano-sdk-for-ios
Sources/Composer/Composer/Models/PageViewMeterEventParams.swift
1
834
import Foundation @objcMembers public class PageViewMeterEventParams: NSObject { public let meterName: String fileprivate(set) public var views: Int = 0 fileprivate(set) public var viewsLeft: Int = 0 fileprivate(set) public var maxViews: Int = 0 fileprivate(set) public var totalViews: Int = 0 fileprivate(set) public var incremented: Bool = false init?(dict: [String: Any]?) { if dict == nil { return nil } meterName = dict!["meterName"] as? String ?? "" views = dict!["views"] as? Int ?? 0 viewsLeft = dict!["viewsLeft"] as? Int ?? 0 maxViews = dict!["maxViews"] as? Int ?? 0 totalViews = dict!["totalViews"] as? Int ?? 0 incremented = dict!["incremented"] as? Bool ?? false } }
apache-2.0
f9dcb50c10bc7c71fa4cf664f8c98391
26.8
63
0.579137
4.321244
false
false
false
false
TheTekton/Malibu
Sources/Response/WaveValidation.swift
1
1073
import Foundation import When // MARK: - Validations public extension Promise where T: Wave { public func validate(_ validator: Validating) -> Promise<Wave> { return then({ result -> Wave in try validator.validate(result) return result }) } public func validate<T: Sequence>(statusCodes: T) -> Promise<Wave> where T.Iterator.Element == Int { return validate(StatusCodeValidator(statusCodes: statusCodes)) } public func validate<T : Sequence>(contentTypes: T) -> Promise<Wave> where T.Iterator.Element == String { return validate(ContentTypeValidator(contentTypes: contentTypes)) } public func validate() -> Promise<Wave> { return validate(statusCodes: 200..<300).then({ result -> Wave in let contentTypes: [String] if let accept = result.request.value(forHTTPHeaderField: "Accept") { contentTypes = accept.components(separatedBy: ",") } else { contentTypes = ["*/*"] } try ContentTypeValidator(contentTypes: contentTypes).validate(result) return result }) } }
mit
76dc4c118e48ffe5077cc107c5a9d7db
27.236842
107
0.674744
4.565957
false
false
false
false
Johnykutty/JSONModeller
JSONModeller/Extensions/String+Extension.swift
1
2024
// // String+Extension.swift // JSONModeller // // Created by Johnykutty Mathew on 03/06/15. // Copyright (c) 2015 Johnykutty Mathew. All rights reserved. // import Foundation extension String { func startsWithDigit() -> Bool { let regex = try! NSRegularExpression(pattern: "^[0-9].*", options: []) if nil != regex.firstMatch(in: self, options: [], range: self.range()) { return true } return false } func range() -> NSRange { return NSMakeRange(0, self.characters.count) } func substring(_ range: NSRange) -> String { if self.isEmpty { return "" } let from = range.location let end = range.location + range.length return self[from..<end] } subscript (r: Range<Int>) -> String { get { if self.isEmpty { return "" } let subStart = self.characters.index(self.startIndex, offsetBy: r.lowerBound, limitedBy: self.endIndex) let subEnd = self.index (subStart!, offsetBy: r.upperBound - r.lowerBound, limitedBy: self.endIndex) return self.substring(with: subStart!..<subEnd!) } } func substring(from: Int) -> String { if self.isEmpty { return "" } let end = self.characters.count return self[from..<end] } func substring(to: Int) -> String { if self.isEmpty { return "" } let from = 0 return self[from..<to] } func substring(_ from: Int, length: Int) -> String { if self.isEmpty { return "" } let end = from + length return self[from..<end] } func firstLetterLoweredString() -> String { if self.isEmpty { return "" } let lowercase = self.substring(to: 1).lowercased() let value = lowercase + self.substring(from: 1) return value } }
mit
4e4e922a48b3e42ed43b8e0339aab6e9
25.285714
115
0.529644
4.315565
false
false
false
false
FrganiLY/Calculock
Calculock/AppDelegate.swift
1
4602
// // AppDelegate.swift // Calculock // // Created by F. Mansur on 01/03/2017. // Copyright © 2017 FrganiLY - F. Mansur. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Calculock") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } }
mit
38ceea8556e72f0cc7c6ba99c3342830
49.01087
285
0.685503
5.765664
false
false
false
false
jigneshsheth/Datastructures
DataStructure/DataStructure/Stack/Stack.swift
1
909
// // Stack.swift // DataStructure // // Created by Jigs Sheth on 11/13/21. // Copyright © 2021 jigneshsheth.com. All rights reserved. // import Foundation struct Stack<Element:Equatable>:Equatable { //Storage private var storage:[Element] = [] var isEmpty:Bool { return peek() == nil } var first:Element? { return storage.first } init(){} init(_ elemenets:[Element]) { storage = elemenets } //Push mutating func push(_ element:Element) { storage.append(element) } @discardableResult mutating func pop() -> Element? { return storage.popLast() } func peek() -> Element? { return storage.last } } extension Stack:CustomStringConvertible{ var description: String { return storage.map{"\($0)"}.joined(separator: " ") } } extension Stack: ExpressibleByArrayLiteral { init(arrayLiteral elements: Element...) { storage = elements } }
mit
5e30b73aada10c59737085071266c06c
13.885246
60
0.656388
3.350554
false
false
false
false
soheilbm/Swift-for-Caveman
MyPlaygroundTest.playground/Contents.swift
1
7986
//: Playground - noun: a place where people can play import UIKit // ############ Variables ############## \\ // let is for constants and you can't change it // var is for dynamic let NAME = "Daniel" var newName = "David" newName = "Alex" // single line declaration var x = 0.0, y = 0.0, z = 0.0 // type of annotations var welcomeMessage: String welcomeMessage = "Hello" // same type in single line declaration var red, green, yello, blue: Double println(welcomeMessage + " " + newName) println(welcomeMessage + " \(newName)") // ############ Numbers ############## \\ let minValueUint8 = UInt8.min let maxValueUint8 = UInt8.max // let maxValueUint8 = UINT8_MAX let minValueInt8 = INT8_MIN // UInt without number indicate the unsigned integer of the // running device let myDeviceInt:UInt = UInt.max // Numeric Literals let paddedDouble = 000123.456 let oneMillion = 1_000_000 // converting numbers let doubleToInteger = Int(paddedDouble) // ############ Semicolons ############## \\ // Let you to write more statement in single line let cat = "😸"; let helloKitty = "Hi"; println(helloKitty + " \(cat)"); // ############ Type Aliases ############## \\ // let you define alternate name for existing type // Remember typealiases is for system type typealias AudioSample = UInt16 let maxAudioSampleFound: AudioSample = 0 typealias myImage = UIImage let avatar:myImage // ############ Bool ############## \\ var awesomeBool: Bool = false // ############ Tuples ############# \\ // tuples group multiple values into a single compund value. let helloTuple = (123, "what's up", "awesome",["yes"],404) let http404Error = (404, "not Found") println(http404Error.0) let (statusCode, statusMessage) = http404Error // if you only need some of the tuple value with ignoring others let (_,justGiveMeStatus,_,_,_) = helloTuple // You can name the individual element in tuple let http202Error = (statusCode: 200, description: "Ok") println(http202Error.0) println(http202Error.statusCode) // ############ Optional ############# \\ let convertetNumber = "123".toInt() var serverResponseCode: Int? = 404 serverResponseCode = nil // ############ Optional Binding ############# \\ // you can use optional binding to find out whether an optional contains a value, and if so, to make that value available if let awesomeNumber = "1234".toInt(){ // converted value println(awesomeNumber) }else{ // failed to convert } // multiple optional binding if let awesomeNum1 = "123".toInt(), awesomeNum2 = "43".toInt(){ // converted value println(awesomeNum1+awesomeNum2) }else{ // failed to convert } // ####### Implicitly Unwrapped Optional ########## \\ // As described above, optional allowed to have nil value. // But sometimes its clear for programmer that its really // have a value. // so you write an implicitly unwrapped optional using `!` let possibleString: String? = "An Optional String" let forcedString: String = possibleString! // ############ Assertions ############# \\ // assertion is a runtime check that a logical condition is true // when xcode running your app in debug mode and checks for assert let age = -3 // assert(age >= 0 , "A person's age cannot be less than zero") // this cause assertion to be trigerred // ############ Operations ############# \\ var a = 11 var b = 7 var c: Int = a & b // AND c = a | b // OR c = a ^ b // XOR c = a++ println(a) println(c) // nil coalescing operator // a ?? b // unwrap an optional a if it contains a value, or return a default value b var awesomeNumbers = a ?? 3 var randomName: String? let colorName = randomName ?? "Blue" randomName = "green" let colorName2 = randomName ?? "Blue" // Range Operator for index in 1...3 { println("hi \(index)") } // ############ Arrays ############# \\ let names = ["Anna","alex","Jack","David"] for i in 0..<names.count { println("hi \(names[i])") } for i in "hello" { println(i) } for i in indices("hello") { println(i) } let exclamationMark: Character = "!" var someInts = [Int]() var someAnotherInts: [Int] = Array() var anotherInts: [Int] = [] var threeDoubles = [Double](count: 3, repeatedValue: 3.0) threeDoubles[0...1] = [2.0,2.0] println(threeDoubles) for (index,value) in enumerate(names) { println("\n index \(index) and value of \(value)") } for _ in 1...names.count { println("no i") } // ############ Sets ############# \\ // set stores distinct values of the same type in a collection with no // defined ordering. You can use set alternate to array when the order // of the items is not important, or when you need to ensure that an item // ONLY appear once. var letters = Set<Character>() letters = ["c","b","b","b","b","b"] letters.count if letters.contains("c"){ letters.insert("a") } // sorted does not have ordering // thus you can use global sorted function for char in sorted(letters){ println(char) } // ############ Dictionary ############# \\ var nameOfIntegers = [Int: String]() nameOfIntegers[16] = "Sixteen" nameOfIntegers = [:] // make dictionary empty // ############ Switch ############# \\ let someChar: Character = "e" switch someChar { case "a","b","d": println("this one a b d") case "c","f","e": println("this one c f e") default: println("the rest") } let somePoint = (1,1) switch somePoint{ case (0,0): println("this is 0 0") case(_,0): println("the y is 0") case(0,_): println("the x is 0") case(-2...2,-2...2): println("its between -2 ... 2") default: println("ok") } switch somePoint{ case (let x,0): println("this is \(x)") case let(x,y): println("the y is \(y) and x \(x)") default: println("ok") } // using where statement var desc = "" switch somePoint{ case let(x,y) where x == y: desc += "the x < y " fallthrough default: desc += "ok, this also reads default" } println(desc) // Control transfer Statements // - continue: tell the loop stop & start again from begining // - break: end executation of an entire control flow // - fallthrough: only for switch statements // - return // ############ Functions ############# \\ func sayHello(personName: String) -> String { return "hello \(personName)" } println(sayHello("David")) // in order to show parameter name you can use another name before the local name func sayGoodbye(userName name: String) { println("hi") } sayGoodbye(userName: "David") // short version we could use '#' func sayGoodbyeAgain(#name: String){ // } sayGoodbyeAgain(name: "david") // default parameter func awesomeDefault(name :String = "Daniel"){ // this has default name } // function param are constant by default // if you want to change them add 'var' before it func varParams(var name: String){ name = "I changed" } // in-out function func swapMyValues(inout a: Int,inout b:Int){ let tempA = a a = b b = tempA } var someInt1 = 13, someInt2 = 20 swapMyValues(&someInt1, &someInt2) println("value 1:\(someInt1) and 2:\(someInt2) has changed") // ############ Closures ############# \\
mit
ac963a1ad9367f6802150aa0f859dc26
21.873926
121
0.560817
4.212665
false
false
false
false
kickstarter/ios-ksapi
KsApi/models/lenses/UserLenses.swift
1
7312
import Prelude extension User { public enum lens { public static let avatar = Lens<User, User.Avatar>( view: { $0.avatar }, set: { User(avatar: $0, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let facebookConnected = Lens<User, Bool?>( view: { $0.facebookConnected }, set: { User(avatar: $1.avatar, facebookConnected: $0, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let id = Lens<User, Int>( view: { $0.id }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $0, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let isFriend = Lens<User, Bool?>( view: { $0.isFriend }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $0, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let liveAuthToken = Lens<User, String?>( view: { $0.liveAuthToken }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $0, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let location = Lens<User, Location?>( view: { $0.location }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $0, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let name = Lens<User, String>( view: { $0.name }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $0, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let newsletters = Lens<User, User.NewsletterSubscriptions>( view: { $0.newsletters }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $0, notifications: $1.notifications, social: $1.social, stats: $1.stats) } ) public static let notifications = Lens<User, User.Notifications>( view: { $0.notifications }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $0, social: $1.social, stats: $1.stats) } ) public static let social = Lens<User, Bool?>( view: { $0.social }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $0, stats: $1.stats) } ) public static let stats = Lens<User, User.Stats>( view: { $0.stats }, set: { User(avatar: $1.avatar, facebookConnected: $1.facebookConnected, id: $1.id, isFriend: $1.isFriend, liveAuthToken: $1.liveAuthToken, location: $1.location, name: $1.name, newsletters: $1.newsletters, notifications: $1.notifications, social: $1.social, stats: $0) } ) } } extension Lens where Whole == User, Part == User.Avatar { public var large: Lens<User, String?> { return User.lens.avatar..User.Avatar.lens.large } public var medium: Lens<User, String> { return User.lens.avatar..User.Avatar.lens.medium } public var small: Lens<User, String> { return User.lens.avatar..User.Avatar.lens.small } } extension Lens where Whole == User, Part == User.NewsletterSubscriptions { public var games: Lens<User, Bool?> { return User.lens.newsletters..User.NewsletterSubscriptions.lens.games } public var happening: Lens<User, Bool?> { return User.lens.newsletters..User.NewsletterSubscriptions.lens.happening } public var promo: Lens<User, Bool?> { return User.lens.newsletters..User.NewsletterSubscriptions.lens.promo } public var weekly: Lens<User, Bool?> { return User.lens.newsletters..User.NewsletterSubscriptions.lens.weekly } } extension Lens where Whole == User, Part == User.Notifications { public var backings: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.backings } public var comments: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.comments } public var follower: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.follower } public var friendActivity: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.friendActivity } public var postLikes: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.postLikes } public var updates: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.updates } public var mobileBackings: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobileBackings } public var mobileComments: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobileComments } public var mobileFollower: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobileFollower } public var mobileFriendActivity: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobileFriendActivity } public var mobilePostLikes: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobilePostLikes } public var mobileUpdates: Lens<User, Bool?> { return User.lens.notifications..User.Notifications.lens.mobileUpdates } } extension Lens where Whole == User, Part == User.Stats { public var backedProjectsCount: Lens<User, Int?> { return User.lens.stats..User.Stats.lens.backedProjectsCount } public var createdProjectsCount: Lens<User, Int?> { return User.lens.stats..User.Stats.lens.createdProjectsCount } public var memberProjectsCount: Lens<User, Int?> { return User.lens.stats..User.Stats.lens.memberProjectsCount } public var starredProjectsCount: Lens<User, Int?> { return User.lens.stats..User.Stats.lens.starredProjectsCount } }
apache-2.0
b50cf078b81ca11c38ad8e22422abc2d
39.175824
108
0.685312
3.719227
false
false
false
false
sharath-cliqz/browser-ios
Client/Cliqz/Frontend/Browser/CliqzURLBarView.swift
2
8125
// // CliqzURLBarView.swift // Client // // Created by Sahakyan on 8/25/16. // Copyright © 2016 Mozilla. All rights reserved. // import UIKit import SnapKit import Shared import QuartzCore enum Whitelisted { case yes case no case undefined } protocol CliqzURLBarViewProtocol: class{ func isPrivate() -> Bool } class CliqzURLBarView: URLBarView { static let antitrackingGreenBackgroundColor = UIConstants.CliqzThemeColor static let antitrackingOrangeBackgroundColor = UIConstants.GhosteryGray static let antitrackingButtonSize = CGSize(width: 42, height: CGFloat(URLBarViewUX.LocationHeight)) private var trackersCount = 0 fileprivate lazy var antitrackingButton: UIButton = { let button = UIButton(type: .custom) button.setTitle("0", for: .normal) button.titleLabel?.font = UIFont.systemFont(ofSize: 12) button.backgroundColor = UIColor.clear button.accessibilityLabel = "AntiTrackingButton" let buttonImage = self.imageForAntiTrackingButton(Whitelisted.undefined) button.setImage(buttonImage, for: .normal) button.titleEdgeInsets = UIEdgeInsets(top: 5, left: 2, bottom: 5, right: 0) button.imageEdgeInsets = UIEdgeInsets(top: 4, left: 2, bottom: 4, right: 20) button.addTarget(self, action: #selector(antitrackingButtonPressed), for: .touchUpInside) button.isHidden = true return button }() fileprivate lazy var newTabButton: UIButton = { let button = UIButton(type: .custom) button.setImage(UIImage.templateImageNamed("bottomNav-NewTab"), for: .normal) button.accessibilityLabel = NSLocalizedString("New tab", comment: "Accessibility label for the New tab button in the tab toolbar.") button.addTarget(self, action: #selector(CliqzURLBarView.SELdidClickNewTab), for: UIControlEvents.touchUpInside) return button }() static let antitrackingActiveNormal = UIImage(named: "antitrackingActiveNormal") static let antitrackingInactiveNormal = UIImage(named: "antitrackingInactiveNormal") static let antitrackingActiveForget = UIImage(named: "antitrackingActiveForget") static let antitrackingInactiveForget = UIImage(named: "antitrackingInactiveForget") override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } deinit{ NotificationCenter.default.removeObserver(self) } override func prepareOverlayAnimation() { super.prepareOverlayAnimation() self.newTabButton.isHidden = !self.toolbarIsShowing } override func transitionToOverlay(_ didCancel: Bool = false) { super.transitionToOverlay(didCancel) self.newTabButton.alpha = inOverlayMode ? 0 : 1 } override func updateViewsForOverlayModeAndToolbarChanges() { super.updateViewsForOverlayModeAndToolbarChanges() self.newTabButton.isHidden = !self.toolbarIsShowing || inOverlayMode } func updateTrackersCount(_ count: Int) { trackersCount = count self.antitrackingButton.setTitle("\(count)", for: UIControlState()) self.setNeedsDisplay() } func showAntitrackingButton(_ hidden: Bool) { self.antitrackingButton.isHidden = !hidden self.bringSubview(toFront: self.antitrackingButton) self.setNeedsUpdateConstraints() } func isAntiTrackingButtonHidden() -> Bool { return antitrackingButton.isHidden } func enableAntitrackingButton(_ enable: Bool) { self.antitrackingButton.isEnabled = enable } func refreshAntiTrackingButton(_ notification: Notification){ if let userInfo = notification.userInfo{ var whitelisted : Whitelisted = .undefined if let onWhiteList = userInfo["whitelisted"] as? Bool{ whitelisted = onWhiteList ? Whitelisted.yes : Whitelisted.no } var newURL : URL? = nil if let url = userInfo["newURL"] as? URL{ newURL = url } let antitrackingImag = self.imageForAntiTrackingButton(whitelisted, newURL: newURL) self.antitrackingButton.setImage(antitrackingImag, for: .normal) } else { let antitrackingImag = self.imageForAntiTrackingButton(Whitelisted.undefined) self.antitrackingButton.setImage(antitrackingImag, for: .normal) } } func imageForAntiTrackingButton(_ whitelisted: Whitelisted, newURL: URL? = nil) -> UIImage? { var theURL : URL if let url = newURL { theURL = url } else if let url = self.currentURL { theURL = url } else { return (delegate?.isPrivate() ?? false) ? CliqzURLBarView.antitrackingActiveForget : CliqzURLBarView.antitrackingActiveNormal } guard let domain = theURL.host else {return (delegate?.isPrivate() ?? false) ? CliqzURLBarView.antitrackingActiveForget : CliqzURLBarView.antitrackingActiveNormal} var isAntiTrackingEnabled = false //Doc: If the observer checks if the website is whitelisted, it might get the wrong value, since the correct value may not be set yet. //To avoid that whitelisted is sent as an argument, and takes precedence over isDomainWhiteListed. if whitelisted != .undefined{ isAntiTrackingEnabled = whitelisted == .yes ? false : true }else{ isAntiTrackingEnabled = !AntiTrackingModule.sharedInstance.isDomainWhiteListed(domain) } let isWebsiteOnPhisingList = AntiPhishingDetector.isDetectedPhishingURL(theURL) if isAntiTrackingEnabled && !isWebsiteOnPhisingList { return (delegate?.isPrivate() ?? false) ? CliqzURLBarView.antitrackingActiveForget : CliqzURLBarView.antitrackingActiveNormal } return (delegate?.isPrivate() ?? false) ? CliqzURLBarView.antitrackingInactiveForget : CliqzURLBarView.antitrackingInactiveNormal } fileprivate func commonInit() { NotificationCenter.default.addObserver(self, selector:#selector(refreshAntiTrackingButton) , name: NSNotification.Name(rawValue: NotificationRefreshAntiTrackingButton), object: nil) addSubview(self.antitrackingButton) antitrackingButton.snp.makeConstraints { make in make.centerY.equalTo(self.locationContainer) make.leading.equalTo(self.locationContainer.snp.trailing).offset(-1 * URLBarViewUX.ButtonWidth) make.size.equalTo(CliqzURLBarView.antitrackingButtonSize) } addSubview(newTabButton) // Cliqz: Changed new tab position, now it should be befores tabs button newTabButton.snp.makeConstraints { make in make.right.equalTo(self.tabsButton.snp.left).offset(-URLBarViewUX.URLBarButtonOffset) make.centerY.equalTo(self) make.size.equalTo(backButton) } // Cliqz: Changed share position, now it should be before new tab button shareButton.snp.remakeConstraints { (make) in make.right.equalTo(self.newTabButton.snp.left).offset(-URLBarViewUX.URLBarButtonOffset) make.centerY.equalTo(self) make.size.equalTo(backButton) } self.actionButtons.append(newTabButton) } @objc private func antitrackingButtonPressed(sender: UIButton) { let status = CliqzURLBarView.antitrackingGreenBackgroundColor == sender.backgroundColor ? "green" : "Orange" self.delegate?.urlBarDidClickAntitracking(self, trackersCount: trackersCount, status: status) } // Cliqz: Add actions for new tab button func SELdidClickNewTab() { delegate?.urlBarDidPressNewTab(self, button: newTabButton) } override func applyTheme(_ themeName: String) { super.applyTheme(themeName) if let theme = URLBarViewUX.Themes[themeName] { self.antitrackingButton.setTitleColor(theme.textColor, for: .normal) } } }
mpl-2.0
9b0b477a20efa7e790a2a5bf3e85464b
36.611111
189
0.6887
4.99631
false
false
false
false
TeamYYZ/DineApp
Dine/YYZTextField.swift
1
5978
// // YYZTextField.swift // Dine // // Created by YiHuang on 3/15/16. // Copyright © 2016 YYZ. All rights reserved. // import UIKit enum CustomTextFieldType { case Email, Password, Name, Mobile, Vericode } class YYZTextField: UITextField, UITextFieldDelegate { lazy var validatedImageView = UIImageView(image: UIImage(named: "validated")) var vericode: String? var textChangedCB: ((Bool)->())? var bottomBorder: UIView? var fieldType: CustomTextFieldType? { didSet { self.addTarget(self, action: #selector(YYZTextField.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged) } } /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { // Drawing code } */ func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { guard let t = textField.text else {return true} if string != "" { if textField.text?.characters.count == 3 && textField.text?[t.startIndex] != "(" { textField.text = "(" + textField.text! + ") " } else if textField.text?.characters.count == 9 { textField.text = textField.text! + "-" } } else { if let end = textField.text?.endIndex { if textField.text?.characters.count < 2 {return true} if textField.text?[end.predecessor().predecessor()] == "-" { textField.text?.removeAtIndex(end.predecessor().predecessor()) } else if textField.text?[end.predecessor().predecessor()] == " " { let _range = end.predecessor().predecessor().predecessor()..<end.predecessor() textField.text?.removeRange(_range) if t[t.startIndex] == "(" { textField.text?.removeAtIndex(t.startIndex) } } } } return true } func isValidEmail() -> Bool { if let _ = self.text?.rangeOfString("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}", options: .RegularExpressionSearch, range: nil, locale: nil) { textChangedCB?(true) return true } else { textChangedCB?(false) return false } } func isValidPassword() -> Bool { if self.text?.characters.count >= 6 { textChangedCB?(true) return true } else { textChangedCB?(false) return false } } func isValidName() -> Bool { if self.text?.characters.count >= 1 { textChangedCB?(true) return true } else { textChangedCB?(false) return false } } func isCorrectVericode() -> Bool { print(self.text) print(self.vericode) if self.text != nil && self.vericode != nil && self.text == self.vericode { textChangedCB?(true) print("correct vericode") return true } else { textChangedCB?(false) return false } } func isMobile() -> Bool { if let _ = self.text?.rangeOfString("\\(?\\d{3}\\)?\\s\\d{3}-\\d{4}", options: .RegularExpressionSearch, range: nil, locale: nil) { textChangedCB?(true) return true } else { textChangedCB?(false) return false } } override func rightViewRectForBounds(bounds: CGRect) -> CGRect { return CGRect(x: self.frame.size.width - 20, y: 10, width: 20.0, height: 20.0) } func textFieldDidChange(textField: UITextField) { if let fieldType = self.fieldType { switch fieldType { case .Email: if isValidEmail() { self.rightViewMode = .Always } else { self.rightViewMode = .Never } case .Name: if isValidName() { self.rightViewMode = .Always } else { self.rightViewMode = .Never } case .Password: if isValidPassword() { self.rightViewMode = .Always } else { self.rightViewMode = .Never } case .Mobile: if isMobile() { self.rightViewMode = .Always } else { self.rightViewMode = .Never } case .Vericode: if isCorrectVericode() { self.rightViewMode = .Always } else { self.rightViewMode = .Never } } } } override func awakeFromNib() { self.borderStyle = .None self.bottomBorder = self.setBottomBorder(color: ColorTheme.sharedInstance.loginTextColor) self.tintColor = ColorTheme.sharedInstance.loginTextColor self.textColor = ColorTheme.sharedInstance.loginTextColor if let placeholder = self.placeholder { self.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName : ColorTheme.sharedInstance.loginTextColor]) } self.autocapitalizationType = .None self.autocorrectionType = .No self.rightViewMode = .Never self.rightView = validatedImageView } override func layoutSubviews() { super.layoutSubviews() self.bottomBorder?.frame = CGRectMake(0.0, self.frame.size.height - 1, self.frame.size.width, 1.0) } }
gpl-3.0
b7cd7c83d06c398362d900b3eb7f744b
31.840659
169
0.527689
5.104184
false
false
false
false
wjk930726/weibo
weiBo/weiBo/iPhone/Modules/View/OAuthViewController/WBRegisterViewController.swift
1
1626
// // WBRegisterViewController.swift // weiBo // // Created by 王靖凯 on 2017/11/21. // Copyright © 2017年 王靖凯. All rights reserved. // import UIKit class WBRegisterViewController: UIViewController { /// 注册新浪微博用户接口,该接口为受限接口(只对受邀请的合作伙伴开放)。 lazy var leftBarButtonItem: UIBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(cancel)) lazy var webView: UIWebView = { let webView = UIWebView(frame: self.view.bounds) webView.scrollView.bounces = false webView.scrollView.backgroundColor = UIColor.colorWithHex(hex: 0xEBEDEF) return webView }() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { NotificationCenter.default.removeObserver(self) } } extension WBRegisterViewController { func setupUI() { navigationItem.leftBarButtonItem = leftBarButtonItem view.addSubview(webView) let urlStr = "https://m.weibo.cn/reg/index?vt=4&res=wel&wm=3349&backURL=http%3A%2F%2Fm.weibo.cn%2F%3F%26jumpfrom%3Dweibocom" if let url = URL(string: urlStr) { webView.loadRequest(URLRequest(url: url)) } } } extension WBRegisterViewController { @objc fileprivate func cancel() { dismiss(animated: true, completion: nil) } }
mit
984c3bb8e5f18404863756eb0f2b94ed
28.037736
134
0.670565
4.082228
false
false
false
false
malaonline/iOS
mala-ios/View/Profile/AboutTitleView.swift
1
2106
// // AboutTitleView.swift // mala-ios // // Created by 王新宇 on 3/15/16. // Copyright © 2016 Mala Online. All rights reserved. // import UIKit class AboutTitleView: UIView { // MARK: - Property /// 标题文字 var title: String = "" { didSet { titleLabel.text = title titleLabel.sizeToFit() } } // MARK: - Components /// 标题 private var titleLabel: UILabel = { let titleLabel = UILabel( fontSize: 14, textColor: UIColor(named: .ArticleSubTitle) ) return titleLabel }() /// 左侧装饰线 private var leftLine: UIImageView = { let leftLine = UIImageView(imageName: "titleLeftLine") return leftLine }() /// 右侧装饰线 private var rightLine: UIImageView = { let rightLine = UIImageView(imageName: "titleRightLine") return rightLine }() // MARK: - Constructed override init(frame: CGRect) { super.init(frame: frame) setupUserInterface() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Private private func setupUserInterface() { // SubViews addSubview(titleLabel) addSubview(leftLine) addSubview(rightLine) // Autolayout titleLabel.snp.makeConstraints { (maker) -> Void in maker.top.equalTo(self) maker.centerX.equalTo(self) maker.height.equalTo(14) maker.bottom.equalTo(self) } leftLine.snp.makeConstraints { (maker) -> Void in maker.centerY.equalTo(titleLabel) maker.left.equalTo(self).offset(10) maker.right.equalTo(titleLabel.snp.left).offset(-5) } rightLine.snp.makeConstraints { (maker) -> Void in maker.centerY.equalTo(titleLabel) maker.left.equalTo(titleLabel.snp.right).offset(5) maker.right.equalTo(self).offset(-10) } } }
mit
2577d85c73a34180f1bd736b5623cd8d
24.518519
64
0.563619
4.583149
false
false
false
false
tadeuzagallo/GithubPulse
widget/GithubPulse/Controllers/ContentViewController.swift
2
5012
// // ContentViewController.swift // GithubPulse // // Created by Tadeu Zagallo on 12/28/14. // Copyright (c) 2014 Tadeu Zagallo. All rights reserved. // import Cocoa import WebKit class ContentViewController: NSViewController, NSXMLParserDelegate, WebPolicyDelegate { @IBOutlet weak var webView:WebView? @IBOutlet weak var lastUpdate:NSTextField? var regex = try? NSRegularExpression(pattern: "^osx:(\\w+)\\((.*)\\)$", options: NSRegularExpressionOptions.CaseInsensitive) var calls: [String: [String] -> Void] func loadCalls() { self.calls = [:] self.calls["contributions"] = { (args) in Contributions.fetch(args[0]) { (success, commits, streak, today) in if success { if args.count < 2 || args[1] == "true" { NSNotificationCenter.defaultCenter().postNotificationName("check_icon", object: nil, userInfo: ["today": today]) } } let _ = self.webView?.stringByEvaluatingJavaScriptFromString("contributions(\"\(args[0])\", \(success), \(today),\(streak),\(commits))") } } self.calls["set"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.setValue(args[1], forKey: args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["get"] = { (args) in var value = NSUserDefaults.standardUserDefaults().valueForKey(args[0]) as? String if value == nil { value = "" } let key = args[0].stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) let v = value!.stringByReplacingOccurrencesOfString("'", withString: "\\'", options: [], range: nil) self.webView?.stringByEvaluatingJavaScriptFromString("get('\(key)', '\(v)', \(args[1]))"); } self.calls["remove"] = { (args) in let userDefaults = NSUserDefaults.standardUserDefaults() userDefaults.removeObjectForKey(args[0]) userDefaults.synchronize() if args[0] == "username" { NSNotificationCenter.defaultCenter().postNotificationName("check_username", object: self, userInfo: nil) } } self.calls["check_login"] = { (args) in let active = NSBundle.mainBundle().isLoginItem() self.webView?.stringByEvaluatingJavaScriptFromString("raw('check_login', \(active))") } self.calls["toggle_login"] = { (args) in if NSBundle.mainBundle().isLoginItem() { NSBundle.mainBundle().removeFromLoginItems() } else { NSBundle.mainBundle().addToLoginItems() } } self.calls["quit"] = { (args) in NSApplication.sharedApplication().terminate(self) } self.calls["update"] = { (args) in GithubUpdate.check(true) } self.calls["open_url"] = { (args) in if let checkURL = NSURL(string: args[0]) { NSWorkspace.sharedWorkspace().openURL(checkURL) } } } required init?(coder: NSCoder) { self.calls = [:] super.init(coder: coder) self.loadCalls() } override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { self.calls = [:] super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) self.loadCalls() } override func viewDidLoad() { #if DEBUG let url = NSURL(string: "http://0.0.0.0:8080")! #else let indexPath = NSBundle.mainBundle().pathForResource("index", ofType: "html", inDirectory: "front") let url = NSURL(fileURLWithPath: indexPath!) #endif let request = NSURLRequest(URL: url) self.webView?.policyDelegate = self self.webView?.drawsBackground = false self.webView?.wantsLayer = true self.webView?.layer?.cornerRadius = 5 self.webView?.layer?.masksToBounds = true self.webView?.mainFrame.loadRequest(request) super.viewDidLoad() } @IBAction func refresh(sender: AnyObject?) { self.webView?.reload(sender) } func webView(webView: WebView!, decidePolicyForNavigationAction actionInformation: [NSObject : AnyObject]!, request: NSURLRequest!, frame: WebFrame!, decisionListener listener: WebPolicyDecisionListener!) { let url:String = request.URL!.absoluteString.stringByRemovingPercentEncoding! if url.hasPrefix("osx:") { let matches = self.regex?.matchesInString(url, options: [], range: NSMakeRange(0, url.characters.count)) if let match = matches?[0] { let fn = (url as NSString).substringWithRange(match.rangeAtIndex(1)) let args = (url as NSString).substringWithRange(match.rangeAtIndex(2)).componentsSeparatedByString("%%") #if DEBUG print(fn, args) #endif let closure = self.calls[fn] closure?(args) } } else if (url.hasPrefix("log:")) { #if DEBUG print(url) #endif } else { listener.use() } } }
mit
30fe2d676d5adb7cccbff6d55fe064c0
31.551948
208
0.635674
4.439327
false
false
false
false
hanhailong/practice-swift
Calendar/Adding Recurring Events to Calendars/Adding Recurring Events to Calendars/AppDelegate.swift
2
9180
// // AppDelegate.swift // Adding Recurring Events to Calendars // // Created by Domenico on 25/05/15. // License MIT // import UIKit import EventKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { self.requestAuthorization() return true } // Requesting Calendar access func requestAuthorization(){ let eventStore = EKEventStore() switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent){ case .Authorized: createRecurringEventInStore(eventStore) case .Denied: displayAccessDenied() case .NotDetermined: eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {[weak self] (granted: Bool, error: NSError!) -> Void in if granted{ self!.createRecurringEventInStore(eventStore) } else { self!.displayAccessDenied() } }) case .Restricted: displayAccessRestricted() } } // Find a source in the EventStore func sourceInEventStore( eventStore: EKEventStore, type: EKSourceType, title: String) -> EKSource?{ for source in eventStore.sources() as! [EKSource]{ if source.sourceType.value == type.value && source.title.caseInsensitiveCompare(title) == NSComparisonResult.OrderedSame{ return source } } return nil } // Find a calendar by Title func calendarWithTitle( title: String, type: EKCalendarType, source: EKSource, eventType: EKEntityType) -> EKCalendar?{ for calendar in source.calendarsForEntityType(eventType) as! Set<EKCalendar>{ if calendar.title.caseInsensitiveCompare(title) == NSComparisonResult.OrderedSame && calendar.type.value == type.value{ return calendar } } return nil } // Create a new event func createEventWithTitle( title: String, startDate: NSDate, endDate: NSDate, inCalendar: EKCalendar, inEventStore: EKEventStore, notes: String) -> Bool{ /* If a calendar does not allow modification of its contents then we cannot insert an event into it */ if inCalendar.allowsContentModifications == false{ println("The selected calendar does not allow modifications.") return false } /* Create an event */ var event = EKEvent(eventStore: inEventStore) event.calendar = inCalendar /* Set the properties of the event such as its title, start date/time, end date/time, etc. */ event.title = title event.notes = notes event.startDate = startDate event.endDate = endDate /* Finally, save the event into the calendar */ var error:NSError? let result = inEventStore.saveEvent(event, span: EKSpanThisEvent, error: &error) if result == false{ if let theError = error{ println("An error occurred \(theError)") } } return result } // Remove an event∂∂ func removeEventWithTitle( title: String, startDate: NSDate, endDate: NSDate, store: EKEventStore, calendar: EKCalendar, notes: String) -> Bool{ var result = false /* If a calendar does not allow modification of its contents then we cannot insert an event into it */ if calendar.allowsContentModifications == false{ println("The selected calendar does not allow modifications.") return false } let predicate = store.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: [calendar]) /* Get all the events that match the parameters */ let events = store.eventsMatchingPredicate(predicate) as! [EKEvent] if events.count > 0{ /* Delete them all */ for event in events{ var error:NSError? if store.removeEvent(event, span: EKSpanThisEvent, commit: false, error: &error) == false{ if let theError = error{ println("Failed to remove \(event) with error = \(theError)") } } } var error:NSError? if store.commit(&error){ println("Successfully committed") result = true } else if let theError = error{ println("Failed to commit the event store with error = \(theError)") } } else { println("No events matched your input.") } return result } //- MARK: Helper Methods func displayAccessDenied(){ println("Access to the event store is denied.") } func displayAccessRestricted(){ println("Access to the event store is restricted.") } /* This method finds the calendar as well */ func createRecurringEventInStore(store: EKEventStore){ let icloudSource = sourceInEventStore(store, type: EKSourceTypeCalDAV, title: "iCloud") if icloudSource == nil{ println("You have not configured iCloud for your device.") return } let calendar = calendarWithTitle("Calendar", type: EKCalendarTypeCalDAV, source: icloudSource!, eventType: EKEntityTypeEvent) if calendar == nil{ println("Could not find the calendar we were looking for.") return } createRecurringEventInStore(store, calendar: calendar!) } func createRecurringEventInStore(store: EKEventStore, calendar: EKCalendar) -> Bool{ let event = EKEvent(eventStore: store) /* Create an event that happens today and happens every month for a year from now */ let startDate = NSDate() /* The event's end date is one hour from the moment it is created */ let oneHour:NSTimeInterval = 1 * 60 * 60 let endDate = startDate.dateByAddingTimeInterval(oneHour) /* Assign the required properties, especially the target calendar */ event.calendar = calendar event.title = "My Event" event.startDate = startDate event.endDate = endDate /* The end date of the recurring rule is one year from now */ let oneYear:NSTimeInterval = 365 * 24 * 60 * 60; let oneYearFromNow = startDate.dateByAddingTimeInterval(oneYear) /* Create an Event Kit date from this date */ let recurringEnd = EKRecurrenceEnd.recurrenceEndWithEndDate( oneYearFromNow) as! EKRecurrenceEnd /* And the recurring rule. This event happens every month (EKRecurrenceFrequencyMonthly), once a month (interval:1) and the recurring rule ends a year from now (end:RecurringEnd) */ let recurringRule = EKRecurrenceRule( recurrenceWithFrequency: EKRecurrenceFrequencyMonthly, interval: 1, end: recurringEnd) /* Set the recurring rule for the event */ event.recurrenceRules = [recurringRule] var error:NSError? if store.saveEvent(event, span: EKSpanFutureEvents, error: &error){ println("Successfully created the recurring event.") return true } else if let theError = error{ println("Failed to create the recurring " + "event with error = \(theError)") } return false } }
mit
12c632a48825d819a2cc3ae7f2056d10
32.246377
127
0.515911
6.109188
false
false
false
false
thombles/Flyweight
Flyweight/Server/DTO.swift
1
9445
// Flyweight - iOS client for GNU social // Copyright 2017 Thomas Karpiniec // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation import ObjectMapper class NoticeDTO: Mappable { var text: String? var truncated: Bool? var createdAt: Date? var inReplyToStatusId: String? var uri: String? var source: String? var id: Int64? var inReplyToUserId: Int64? var inReplyToScreenName: String? // geo? var user: UserDTO? var statusnetHtml: String? var statusnetConversationId: Int64? var statusnetInGroups: Bool? var externalUrl: String? var inReplyToProfileUrl: String? var inReplyToOstatusUri: String? // attentions? var faveNum: Int64? var repeatNum: Int64? var isPostVerb: Bool? var isLocal: Bool? var favorited: Bool? var repeated: Bool? required init?(map: Map) { } func mapping(map: Map) { let createdAtDateFormatter = DateFormatter() createdAtDateFormatter.locale = Locale(identifier: "en_US_POSIX") createdAtDateFormatter.dateFormat = "E MMM dd HH:mm:ss xxxx yyyy" createdAtDateFormatter.timeZone = TimeZone(secondsFromGMT: 0) text <- map["text"] truncated <- map["truncated"] createdAt <- (map["created_at"], DateFormatterTransform(dateFormatter: createdAtDateFormatter)) inReplyToStatusId <- map["in_reply_to_status_id"] uri <- map["uri"] source <- map["source"] id <- map["id"] inReplyToUserId <- map["in_reply_to_user_id"] inReplyToScreenName <- map["in_reply_to_screen_name"] // geo? user <- map["user"] statusnetHtml <- map["statusnet_html"] statusnetConversationId <- map["statusnet_conversation_id"] statusnetInGroups <- map["statusnet_in_groups"] externalUrl <- map["external_url"] inReplyToProfileUrl <- map["in_reply_to_profileurl"] inReplyToOstatusUri <- map["in_reply_to_ostatus_uri"] // attentions? faveNum <- map["fave_num"] repeatNum <- map["repeat_num"] isPostVerb <- map["is_post_verb"] isLocal <- map["is_local"] favorited <- map["favorited"] repeated <- map["repeated"] } } class UserDTO: Mappable { var id: Int64? var name: String? var screenName: String? var location: String? var description: String? var profileImageUrl: String? var profileImageUrlHttps: String? var profileImageUrlProfileSize: String? var profileImageUrlOriginal: String? var groupsCount: Int? var linkColor: Bool? var backgroundColor: Bool? var url: String? var protected: Bool? var followersCount: Int? var friendsCount: Int? var createdAt: Date? var utcOffset: String? var timeZone: String? var statusesCount: Int? var following: Bool? var statusnetBlocking: Bool? var notifications: Bool? var statusnetProfileUrl: String? var coverPhoto: Bool? var backgroundImage: Bool? var profileLinkColor: Bool? var profileBackgroundColor: Bool? var profileBannerUrl: Bool? var isLocal: Bool? var isSilenced: Bool? var rights: RightsDTO? var isSandboxed: Bool? var ostatusUri: String? var favoritesCount: Int? required init?(map: Map) { } func mapping(map: Map) { let createdAtDateFormatter = DateFormatter() createdAtDateFormatter.locale = Locale(identifier: "en_US_POSIX") createdAtDateFormatter.dateFormat = "E MMM dd HH:mm:ss xxxx yyyy" createdAtDateFormatter.timeZone = TimeZone(secondsFromGMT: 0) id <- map["id"] name <- map["name"] screenName <- map["screen_name"] location <- map["location"] description <- map["description"] profileImageUrl <- map["profile_image_url"] profileImageUrlHttps <- map["profile_image_url_https"] profileImageUrlProfileSize <- map["profile_image_url_profile_size"] profileImageUrlOriginal <- map["profile_image_url_original"] groupsCount <- map["groups_count"] linkColor <- map["linkcolor"] backgroundColor <- map["backgroundcolor"] url <- map["url"] protected <- map["protected"] followersCount <- map["followers_count"] friendsCount <- map["friends_count"] createdAt <- (map["created_at"], DateFormatterTransform(dateFormatter: createdAtDateFormatter)) utcOffset <- map["utc_offset"] timeZone <- map["time_zone"] statusesCount <- map["statuses_count"] following <- map["following"] statusnetBlocking <- map["statusnet_blocking"] notifications <- map["notifications"] statusnetProfileUrl <- map["statusnet_profile_url"] coverPhoto <- map["cover_photo"] backgroundImage <- map["background_image"] profileLinkColor <- map["profile_link_color"] profileBackgroundColor <- map["profile_background_color"] profileBannerUrl <- map["profile_banner_url"] isLocal <- map["is_local"] isSilenced <- map["is_silenced"] rights <- map["rights"] isSandboxed <- map["is_sandboxed"] ostatusUri <- map["ostatus_uri"] favoritesCount <- map["favourites_count"] } } class RightsDTO: Mappable { var deleteUser: Bool? var deleteOthersNotice: Bool? var silence: Bool? var sandbox: Bool? required init?(map: Map) { } func mapping(map: Map) { deleteUser <- map["delete_user"] deleteOthersNotice <- map["delete_others_notice"] silence <- map["silence"] sandbox <- map["sandbox"] } } // Collection of objects in /api/gnusocial/config.json // A few of them anyway. Don't necessarily care about all the data there. class SiteConfigDTO: Mappable { var name: String? var server: String? var theme: String? var path: String? var logo: String? var fancy: String? var language: String? var email: String? var broughtBy: String? var broughtByUrl: String? var timezone: String? var closed: String? var inviteOnly: String? var private_: String? var textLimit: String? var ssl: String? var sslServer: String? required init?(map: Map) { } func mapping(map: Map) { name <- map["name"] server <- map["server"] theme <- map["theme"] path <- map["path"] logo <- map["logo"] fancy <- map["fancy"] language <- map["language"] email <- map["email"] broughtBy <- map["broughtby"] broughtByUrl <- map["broughtbyurl"] timezone <- map["timezone"] closed <- map["closed"] inviteOnly <- map["inviteonly"] private_ <- map["private"] textLimit <- map["textlimit"] ssl <- map["ssl"] sslServer <- map["sslserver"] } } class ProfileConfigDTO: Mappable { var bioLimit: String? required init?(map: Map) { } func mapping(map: Map) { bioLimit <- map["biolimit"] } } class GroupConfigDTO: Mappable { var descLimit: String? required init?(map: Map) { } func mapping(map: Map) { descLimit <- map["desclimit"] } } class NoticeConfigDTO: Mappable { var contentLimit: String? required init?(map: Map) { } func mapping(map: Map) { contentLimit <- map["contentlimit"] } } class AttachmentsConfigDTO: Mappable { var uploads: Bool? var fileQuota: Int? required init?(map: Map) { } func mapping(map: Map) { uploads <- map["uploads"] fileQuota <- map["file_quota"] } } class GnusocialConfigDTO: Mappable { var site: SiteConfigDTO? var profile: ProfileConfigDTO? var group: GroupConfigDTO? var notice: NoticeConfigDTO? var attachments: AttachmentsConfigDTO? required init?(map: Map) { } func mapping(map: Map) { site <- map["site"] profile <- map["profile"] group <- map["group"] notice <- map["notice"] attachments <- map["attachments"] } } /// We could extract more information out of here if we wanted but I'd rather get it through the atom feed class VerifyCredentialsDTO: Mappable { var id: Int64? var statusNetProfileUrl: String? var name: String? var screenName: String? required init?(map: Map) { } func mapping(map: Map) { id <- map["id"] statusNetProfileUrl <- map["statusnet_profile_url"] name <- map["name"] screenName <- map["screen_name"] } } /// Transmitted to server when creating a new notice class StatusesUpdateDTO { var status: String? var source: String? var inReplyToStatusId: Int64? var latitude: String? var longitude: String? var mediaIds: String? }
apache-2.0
1e04e434ebe23ad5350aea2f579bc99f
28.60815
106
0.624034
4.301002
false
false
false
false
tinysun212/swift-windows
stdlib/public/core/Policy.swift
1
26227
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Swift Standard Prolog Library. //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Standardized uninhabited type //===----------------------------------------------------------------------===// /// The return type of functions that do not return normally; a type with no /// values. /// /// Use `Never` as the return type when declaring a closure, function, or /// method that unconditionally throws an error, traps, or otherwise does /// not terminate. /// /// func crashAndBurn() -> Never { /// fatalError("Something very, very bad happened") /// } @_fixed_layout public enum Never {} //===----------------------------------------------------------------------===// // Standardized aliases //===----------------------------------------------------------------------===// /// The return type of functions that don't explicitly specify a return type; /// an empty tuple (i.e., `()`). /// /// When declaring a function or method, you don't need to specify a return /// type if no value will be returned. However, the type of a function, /// method, or closure always includes a return type, which is `Void` if /// otherwise unspecified. /// /// Use `Void` or an empty tuple as the return type when declaring a /// closure, function, or method that doesn't return a value. /// /// // No return type declared: /// func logMessage(_ s: String) { /// print("Message: \(s)") /// } /// /// let logger: (String) -> Void = logMessage /// logger("This is a void function") /// // Prints "Message: This is a void function" public typealias Void = () //===----------------------------------------------------------------------===// // Aliases for floating point types //===----------------------------------------------------------------------===// // FIXME: it should be the other way round, Float = Float32, Double = Float64, // but the type checker loses sugar currently, and ends up displaying 'FloatXX' // in diagnostics. /// A 32-bit floating point type. public typealias Float32 = Float /// A 64-bit floating point type. public typealias Float64 = Double //===----------------------------------------------------------------------===// // Default types for unconstrained literals //===----------------------------------------------------------------------===// /// The default type for an otherwise-unconstrained integer literal. public typealias IntegerLiteralType = Int /// The default type for an otherwise-unconstrained floating point literal. public typealias FloatLiteralType = Double /// The default type for an otherwise-unconstrained Boolean literal. /// /// When you create a constant or variable using one of the Boolean literals /// `true` or `false`, the resulting type is determined by the /// `BooleanLiteralType` alias. For example: /// /// let isBool = true /// print("isBool is a '\(type(of: isBool))'") /// // Prints "isBool is a 'Bool'" /// /// The type aliased by `BooleanLiteralType` must conform to the /// `ExpressibleByBooleanLiteral` protocol. public typealias BooleanLiteralType = Bool /// The default type for an otherwise-unconstrained unicode scalar literal. public typealias UnicodeScalarType = String /// The default type for an otherwise-unconstrained Unicode extended /// grapheme cluster literal. public typealias ExtendedGraphemeClusterType = String /// The default type for an otherwise-unconstrained string literal. public typealias StringLiteralType = String //===----------------------------------------------------------------------===// // Default types for unconstrained number literals //===----------------------------------------------------------------------===// // Integer literals are limited to 2048 bits. // The intent is to have arbitrary-precision literals, but implementing that // requires more work. // // Rationale: 1024 bits are enough to represent the absolute value of min/max // IEEE Binary64, and we need 1 bit to represent the sign. Instead of using // 1025, we use the next round number -- 2048. public typealias _MaxBuiltinIntegerType = Builtin.Int2048 #if os(Cygwin) && (arch(i386) || arch(x86_64)) public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80 #else public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64 #endif //===----------------------------------------------------------------------===// // Standard protocols //===----------------------------------------------------------------------===// #if _runtime(_ObjC) /// The protocol to which all classes implicitly conform. /// /// You use `AnyObject` when you need the flexibility of an untyped object or /// when you use bridged Objective-C methods and properties that return an /// untyped result. `AnyObject` can be used as the concrete type for an /// instance of any class, class type, or class-only protocol. For example: /// /// class FloatRef { /// let value: Float /// init(_ value: Float) { /// self.value = value /// } /// } /// /// let x = FloatRef(2.3) /// let y: AnyObject = x /// let z: AnyObject = FloatRef.self /// /// `AnyObject` can also be used as the concrete type for an instance of a type /// that bridges to an Objective-C class. Many value types in Swift bridge to /// Objective-C counterparts, like `String` and `Int`. /// /// let s: AnyObject = "This is a bridged string." as NSString /// print(s is NSString) /// // Prints "true" /// /// let v: AnyObject = 100 as NSNumber /// print(type(of: v)) /// // Prints "__NSCFNumber" /// /// The flexible behavior of the `AnyObject` protocol is similar to /// Objective-C's `id` type. For this reason, imported Objective-C types /// frequently use `AnyObject` as the type for properties, method parameters, /// and return values. /// /// Casting AnyObject Instances to a Known Type /// =========================================== /// /// Objects with a concrete type of `AnyObject` maintain a specific dynamic /// type and can be cast to that type using one of the type-cast operators /// (`as`, `as?`, or `as!`). /// /// This example uses the conditional downcast operator (`as?`) to /// conditionally cast the `s` constant declared above to an instance of /// Swift's `String` type. /// /// if let message = s as? String { /// print("Successful cast to String: \(message)") /// } /// // Prints "Successful cast to String: This is a bridged string." /// /// If you have prior knowledge that an `AnyObject` instance has a particular /// type, you can use the unconditional downcast operator (`as!`). Performing /// an invalid cast triggers a runtime error. /// /// let message = s as! String /// print("Successful cast to String: \(message)") /// // Prints "Successful cast to String: This is a bridged string." /// /// let badCase = v as! String /// // Runtime error /// /// Casting is always safe in the context of a `switch` statement. /// /// let mixedArray: [AnyObject] = [s, v] /// for object in mixedArray { /// switch object { /// case let x as String: /// print("'\(x)' is a String") /// default: /// print("'\(object)' is not a String") /// } /// } /// // Prints "'This is a bridged string.' is a String" /// // Prints "'100' is not a String" /// /// Accessing Objective-C Methods and Properties /// ============================================ /// /// When you use `AnyObject` as a concrete type, you have at your disposal /// every `@objc` method and property---that is, methods and properties /// imported from Objective-C or marked with the `@objc` attribute. Because /// Swift can't guarantee at compile time that these methods and properties /// are actually available on an `AnyObject` instance's underlying type, these /// `@objc` symbols are available as implicitly unwrapped optional methods and /// properties, respectively. /// /// This example defines an `IntegerRef` type with an `@objc` method named /// `getIntegerValue()`. /// /// class IntegerRef { /// let value: Int /// init(_ value: Int) { /// self.value = value /// } /// /// @objc func getIntegerValue() -> Int { /// return value /// } /// } /// /// func getObject() -> AnyObject { /// return IntegerRef(100) /// } /// /// let obj: AnyObject = getObject() /// /// In the example, `obj` has a static type of `AnyObject` and a dynamic type /// of `IntegerRef`. You can use optional chaining to call the `@objc` method /// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of /// `obj`, you can call `getIntegerValue()` directly. /// /// let possibleValue = obj.getIntegerValue?() /// print(possibleValue) /// // Prints "Optional(100)" /// /// let certainValue = obj.getIntegerValue() /// print(certainValue) /// // Prints "100" /// /// If the dynamic type of `obj` doesn't implement a `getIntegerValue()` /// method, the system returns a runtime error when you initialize /// `certainValue`. /// /// Alternatively, if you need to test whether `obj.getIntegerValue()` exists, /// use optional binding before calling the method. /// /// if let f = obj.getIntegerValue { /// print("The value of 'obj' is \(f())") /// } else { /// print("'obj' does not have a 'getIntegerValue()' method") /// } /// // Prints "The value of 'obj' is 100" /// /// - SeeAlso: `AnyClass` @objc public protocol AnyObject : class {} #else /// The protocol to which all classes implicitly conform. /// /// - SeeAlso: `AnyClass` public protocol AnyObject : class {} #endif // Implementation note: the `AnyObject` protocol *must* not have any method or // property requirements. // FIXME: AnyObject should have an alternate version for non-objc without // the @objc attribute, but AnyObject needs to be not be an address-only // type to be able to be the target of castToNativeObject and an empty // non-objc protocol appears not to be. There needs to be another way to make // this the right kind of object. /// The protocol to which all class types implicitly conform. /// /// You can use the `AnyClass` protocol as the concrete type for an instance of /// any class. When you do, all known `@objc` class methods and properties are /// available as implicitly unwrapped optional methods and properties, /// respectively. For example: /// /// class IntegerRef { /// @objc class func getDefaultValue() -> Int { /// return 42 /// } /// } /// /// func getDefaultValue(_ c: AnyClass) -> Int? { /// return c.getDefaultValue?() /// } /// /// The `getDefaultValue(_:)` function uses optional chaining to safely call /// the implicitly unwrapped class method on `c`. Calling the function with /// different class types shows how the `getDefaultValue()` class method is /// only conditionally available. /// /// print(getDefaultValue(IntegerRef.self)) /// // Prints "Optional(42)" /// /// print(getDefaultValue(NSString.self)) /// // Prints "nil" /// /// - SeeAlso: `AnyObject` public typealias AnyClass = AnyObject.Type /// A type that supports standard bitwise arithmetic operators. /// /// Types that conform to the `BitwiseOperations` protocol implement operators /// for bitwise arithmetic. The integer types in the standard library all /// conform to `BitwiseOperations` by default. When you use bitwise operators /// with an integer, you perform operations on the raw data bits that store /// the integer's value. /// /// In the following examples, the binary representation of any values are /// shown in a comment to the right, like this: /// /// let x: UInt8 = 5 // 0b00000101 /// /// Here are the required operators for the `BitwiseOperations` protocol: /// /// - The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. This /// is equivalent to the union of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR operation with a value and `allZeros` always /// returns the same value. /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - The bitwise NOT operator (`~`) is a prefix operator that returns a value /// where all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// The `OptionSet` protocol uses a raw value that conforms to /// `BitwiseOperations` to provide mathematical set operations like /// `union(_:)`, `intersection(_:)` and `contains(_:)` with O(1) performance. /// /// Conforming to the BitwiseOperations Protocol /// ============================================ /// /// To make your custom type conform to `BitwiseOperations`, add a static /// `allZeros` property and declare the four required operator functions. Any /// type that conforms to `BitwiseOperations`, where `x` is an instance of the /// conforming type, must satisfy the following conditions: /// /// - `x | Self.allZeros == x` /// - `x ^ Self.allZeros == x` /// - `x & Self.allZeros == .allZeros` /// - `x & ~Self.allZeros == x` /// - `~x == x ^ ~Self.allZeros` /// /// - SeeAlso: `OptionSet` public protocol BitwiseOperations { /// Returns the intersection of bits set in the two arguments. /// /// The bitwise AND operator (`&`) returns a value that has each bit set to /// `1` where *both* of its arguments had that bit set to `1`. This is /// equivalent to the intersection of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x & y // 0b00000100 /// /// Performing a bitwise AND operation with a value and `allZeros` always /// returns `allZeros`. /// /// print(x & .allZeros) // 0b00000000 /// // Prints "0" /// /// - Complexity: O(1). static func & (lhs: Self, rhs: Self) -> Self /// Returns the union of bits set in the two arguments. /// /// The bitwise OR operator (`|`) returns a value that has each bit set to /// `1` where *one or both* of its arguments had that bit set to `1`. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x | y // 0b00001111 /// /// Performing a bitwise OR operation with a value and `allZeros` always /// returns the same value. /// /// print(x | .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func | (lhs: Self, rhs: Self) -> Self /// Returns the bits that are set in exactly one of the two arguments. /// /// The bitwise XOR operator (`^`), or exclusive OR operator, returns a value /// that has each bit set to `1` where *one or the other but not both* of /// its operators has that bit set to `1`. This is equivalent to the /// symmetric difference of two sets. For example: /// /// let x: UInt8 = 5 // 0b00000101 /// let y: UInt8 = 14 // 0b00001110 /// let z = x ^ y // 0b00001011 /// /// Performing a bitwise XOR with a value and `allZeros` always returns the /// same value: /// /// print(x ^ .allZeros) // 0b00000101 /// // Prints "5" /// /// - Complexity: O(1). static func ^ (lhs: Self, rhs: Self) -> Self /// Returns the inverse of the bits set in the argument. /// /// The bitwise NOT operator (`~`) is a prefix operator that returns a value /// in which all the bits of its argument are flipped: Bits that are `1` in the /// argument are `0` in the result, and bits that are `0` in the argument /// are `1` in the result. This is equivalent to the inverse of a set. For /// example: /// /// let x: UInt8 = 5 // 0b00000101 /// let notX = ~x // 0b11111010 /// /// Performing a bitwise NOT operation on `allZeros` returns a value with /// every bit set to `1`. /// /// let allOnes = ~UInt8.allZeros // 0b11111111 /// /// - Complexity: O(1). static prefix func ~ (x: Self) -> Self /// The empty bitset. /// /// The `allZeros` static property is the [identity element][] for bitwise OR /// and XOR operations and the [fixed point][] for bitwise AND operations. /// For example: /// /// let x: UInt8 = 5 // 0b00000101 /// /// // Identity /// x | .allZeros // 0b00000101 /// x ^ .allZeros // 0b00000101 /// /// // Fixed point /// x & .allZeros // 0b00000000 /// /// [identity element]:http://en.wikipedia.org/wiki/Identity_element /// [fixed point]:http://en.wikipedia.org/wiki/Fixed_point_(mathematics) static var allZeros: Self { get } } /// Calculates the union of bits sets in the two arguments and stores the result /// in the first argument. /// /// - Parameters: /// - lhs: A value to update with the union of bits set in the two arguments. /// - rhs: Another value. public func |= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs | rhs } /// Calculates the intersections of bits sets in the two arguments and stores /// the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the intersections of bits set in the two /// arguments. /// - rhs: Another value. public func &= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs & rhs } /// Calculates the bits that are set in exactly one of the two arguments and /// stores the result in the first argument. /// /// - Parameters: /// - lhs: A value to update with the bits that are set in exactly one of the /// two arguments. /// - rhs: Another value. public func ^= <T : BitwiseOperations>(lhs: inout T, rhs: T) { lhs = lhs ^ rhs } //===----------------------------------------------------------------------===// // Standard pattern matching forms //===----------------------------------------------------------------------===// /// Returns a Boolean value indicating whether two arguments match by value /// equality. /// /// The pattern-matching operator (`~=`) is used internally in `case` /// statements for pattern matching. When you match against an `Equatable` /// value in a `case` statement, this operator is called behind the scenes. /// /// let weekday = 3 /// let lunch: String /// switch weekday { /// case 3: /// lunch = "Taco Tuesday!" /// default: /// lunch = "Pizza again." /// } /// // lunch == "Taco Tuesday!" /// /// In this example, the `case 3` expression uses this pattern-matching /// operator to test whether `weekday` is equal to the value `3`. /// /// - Note: In most cases, you should use the equal-to operator (`==`) to test /// whether two instances are equal. The pattern-matching operator is /// primarily intended to enable `case` statement pattern matching. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. @_transparent public func ~= <T : Equatable>(a: T, b: T) -> Bool { return a == b } //===----------------------------------------------------------------------===// // Standard precedence groups //===----------------------------------------------------------------------===// precedencegroup AssignmentPrecedence { assignment: true associativity: right } precedencegroup FunctionArrowPrecedence { associativity: right higherThan: AssignmentPrecedence } precedencegroup TernaryPrecedence { associativity: right higherThan: FunctionArrowPrecedence } precedencegroup DefaultPrecedence { higherThan: TernaryPrecedence } precedencegroup LogicalDisjunctionPrecedence { associativity: left higherThan: TernaryPrecedence } precedencegroup LogicalConjunctionPrecedence { associativity: left higherThan: LogicalDisjunctionPrecedence } precedencegroup ComparisonPrecedence { higherThan: LogicalConjunctionPrecedence } precedencegroup NilCoalescingPrecedence { associativity: right higherThan: ComparisonPrecedence } precedencegroup CastingPrecedence { higherThan: NilCoalescingPrecedence } precedencegroup RangeFormationPrecedence { higherThan: CastingPrecedence } precedencegroup AdditionPrecedence { associativity: left higherThan: RangeFormationPrecedence } precedencegroup MultiplicationPrecedence { associativity: left higherThan: AdditionPrecedence } precedencegroup BitwiseShiftPrecedence { higherThan: MultiplicationPrecedence } //===----------------------------------------------------------------------===// // Standard operators //===----------------------------------------------------------------------===// // Standard postfix operators. postfix operator ++ postfix operator -- // Optional<T> unwrapping operator is built into the compiler as a part of // postfix expression grammar. // // postfix operator ! // Standard prefix operators. prefix operator ++ prefix operator -- prefix operator ! prefix operator ~ prefix operator + prefix operator - // Standard infix operators. // "Exponentiative" infix operator << : BitwiseShiftPrecedence infix operator >> : BitwiseShiftPrecedence // "Multiplicative" infix operator * : MultiplicationPrecedence infix operator &* : MultiplicationPrecedence infix operator / : MultiplicationPrecedence infix operator % : MultiplicationPrecedence infix operator & : MultiplicationPrecedence // "Additive" infix operator + : AdditionPrecedence infix operator &+ : AdditionPrecedence infix operator - : AdditionPrecedence infix operator &- : AdditionPrecedence infix operator | : AdditionPrecedence infix operator ^ : AdditionPrecedence // FIXME: is this the right precedence level for "..." ? infix operator ... : RangeFormationPrecedence infix operator ..< : RangeFormationPrecedence // The cast operators 'as' and 'is' are hardcoded as if they had the // following attributes: // infix operator as : CastingPrecedence // "Coalescing" infix operator ?? : NilCoalescingPrecedence // "Comparative" infix operator < : ComparisonPrecedence infix operator <= : ComparisonPrecedence infix operator > : ComparisonPrecedence infix operator >= : ComparisonPrecedence infix operator == : ComparisonPrecedence infix operator != : ComparisonPrecedence infix operator === : ComparisonPrecedence infix operator !== : ComparisonPrecedence // FIXME: ~= will be built into the compiler. infix operator ~= : ComparisonPrecedence // "Conjunctive" infix operator && : LogicalConjunctionPrecedence // "Disjunctive" infix operator || : LogicalDisjunctionPrecedence // User-defined ternary operators are not supported. The ? : operator is // hardcoded as if it had the following attributes: // operator ternary ? : : TernaryPrecedence // User-defined assignment operators are not supported. The = operator is // hardcoded as if it had the following attributes: // infix operator = : AssignmentPrecedence // Compound infix operator *= : AssignmentPrecedence infix operator /= : AssignmentPrecedence infix operator %= : AssignmentPrecedence infix operator += : AssignmentPrecedence infix operator -= : AssignmentPrecedence infix operator <<= : AssignmentPrecedence infix operator >>= : AssignmentPrecedence infix operator &= : AssignmentPrecedence infix operator ^= : AssignmentPrecedence infix operator |= : AssignmentPrecedence // Workaround for <rdar://problem/14011860> SubTLF: Default // implementations in protocols. Library authors should ensure // that this operator never needs to be seen by end-users. See // test/Prototypes/GenericDispatch.swift for a fully documented // example of how this operator is used, and how its use can be hidden // from users. infix operator ~> @available(*, unavailable, renamed: "BitwiseOperations") public typealias BitwiseOperationsType = BitwiseOperations
apache-2.0
9a3422c4da621150192ca33bf68b13fe
35.426389
81
0.617188
4.518002
false
false
false
false
gokselkoksal/Core
Core/Sources/Helpers/SubscriptionManager.swift
1
1654
// // SubscriptionManager.swift // Core // // Created by Goksel Koksal on 30/06/2017. // Copyright © 2017 GK. All rights reserved. // import Foundation internal final class SubscriptionManager<StateType: State> { private var subscriptionSyncQueue = DispatchQueue(label: "component.subscription.sync") private var _subscriptions: [Subscription] = [] private var subscriptions: [Subscription] { get { return subscriptionSyncQueue.sync { return self._subscriptions } } set { subscriptionSyncQueue.sync { self._subscriptions = newValue } } } internal func subscribe<S: Subscriber>(_ subscriber: S, on queue: DispatchQueue = .main) where S.StateType == StateType { guard !self.subscriptions.contains(where: { $0.subscriber === subscriber }) else { return } let subscription = Subscription(subscriber: subscriber, queue: queue) self.subscriptions.append(subscription) } internal func unsubscribe<S: Subscriber>(_ subscriber: S) where S.StateType == StateType { if let subscriptionIndex = subscriptions.firstIndex(where: { $0.subscriber === subscriber }) { subscriptions.remove(at: subscriptionIndex) } } internal func publish(_ newState: StateType) { forEachSubscription { $0.notify(with: newState) } } internal func publish(_ navigation: Navigation) { forEachSubscription { $0.notify(with: navigation) } } private func forEachSubscription(_ block: (Subscription) -> Void) { subscriptions = subscriptions.filter { $0.subscriber != nil } for subscription in subscriptions { block(subscription) } } }
mit
3dbb9c13266f29b16a84989f25c74ada
29.611111
123
0.687235
4.516393
false
false
false
false
enzosterro/cryproapp
CryptoApp/Controller/StatusMenuController.swift
1
7219
// // StatusMenuController.swift // CryptoApp // // Created by Enzo Sterro on 02/10/2017. // Copyright © 2017 Enzo Sterro. All rights reserved. // import Cocoa final class StatusMenuController: NSObject { // MARK: Outlets @IBOutlet private weak var statusMenu: NSMenu! @IBOutlet private weak var statusChangeMenuButton: NSMenuItem! @IBOutlet private weak var lastUpdateMenuButton: NSMenuItem! @IBOutlet private weak var currenciesMenuAsset: NSMenuItem! @IBOutlet private weak var statisticMenuItem: NSMenuItem! @IBOutlet private weak var statisticMenuView: StatisticMenuView! // MARK: State Enumerations private enum TimerState { case updating case stopped } enum AppState<Coin> { case showing(Coin) case updating(String?) case error } // MARK: Constants and Variables private struct TimerInterval { static let basic: TimeInterval = 60 static let short: TimeInterval = 5 } private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) private var timer: Timer? private var timerState: TimerState = .updating private var currentAppState: AppState<Coin> = .updating(nil) private var coins: [Coin]? private var currentCoinID: String? { didSet { guard let currentCoinID = currentCoinID else { switchAppState(to: .error) return } update() UserDefaults.currentCurrency = currentCoinID } } private var isConnectionLost = false // MARK: View Lifecycle override func awakeFromNib() { // Initializing status menu statusItem.menu = statusMenu // Constructing Current Menu from results that has been retrieved from remote server constructCurrencyMenu() // Starting from showing "Updating" status switchAppState(to: .updating(nil)) currentCoinID = UserDefaults.currentCurrency // Init statistic menu item statisticMenuItem.view = statisticMenuView // Scheduling updates scheduleUpdates(timeInterval: TimerInterval.basic) } // MARK: Update Methods private func scheduleUpdates(timeInterval: TimeInterval) { timer = Timer.scheduledTimer(timeInterval: timeInterval, target: self, selector: #selector(update), userInfo: nil, repeats: true) } @objc private func update() { guard let currentCoinID = currentCoinID else { switchAppState(to: .error) return } CryptoAPI.fetchRates(currency: currentCoinID) { [weak self] result in guard let self = self else { return } switch result { case .success(let coin): guard let coin = coin else { self.switchAppState(to: .error) return } DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.switchAppState(to: .showing(coin)) } case .error(let error): NSLog(error.localizedDescription) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { self.switchAppState(to: .error) } case .customError(let customError): NSLog(customError) } } } // MARK: State Switchers private func switchMenuItemUpdate(to state: TimerState) { timerState = state switch timerState { case .updating: statusChangeMenuButton.title = NSLocalizedString("Pause Updates", comment: "A pause button in status menu.") case .stopped: statusChangeMenuButton.title = NSLocalizedString("Resume", comment: "A resume button in status menu.") invalidateTimer() } } private func switchAppState(to state: AppState<Coin>) { currentAppState = state switch currentAppState { case .showing(let coin): statusItem.title = coin.priceUSD.format(with: .currency) lastUpdateMenuButton.title = coin.lastUpdated.formattedAsStringDate statusItem.image = NSImage(named: coin.id) ?? NSImage(named: "default") statisticMenuView.render(coin) if isConnectionLost { constructCurrencyMenu() setTimerUpdateWith(timerInterval: TimerInterval.basic) isConnectionLost = false } case .updating(let coin): let coin = coin ?? "default" statusItem.image = NSImage(named: coin) statusItem.title = NSLocalizedString("Updating…", comment: "Title next to the rate, that indicates an update process.") case .error: if isConnectionLost == false { statusItem.image = NSImage(named: "connectionLost") setTimerUpdateWith(timerInterval: TimerInterval.short) isConnectionLost = true } } } // MARK: Timer private func invalidateTimer() { timer?.invalidate() timer = nil } private func setTimerUpdateWith(timerInterval: TimeInterval) { invalidateTimer() scheduleUpdates(timeInterval: timerInterval) } // MARK: Currencies Menu Construction private func constructCurrencyMenu() { currenciesMenuAsset.submenu?.removeAllItems() CryptoAPI.fetchTopCurrencies { result in switch result { case .success(let coins): self.coins = coins DispatchQueue.main.async { coins.forEach { coin in let menuItem = NSMenuItem(title: coin.name, action: #selector(self.selectItem), keyEquivalent: "") menuItem.target = self menuItem.isEnabled = true if self.currentCoinID == coin.id { menuItem.state = .on } self.currenciesMenuAsset.submenu?.addItem(menuItem) } } case .error(let error): self.currenciesMenuAsset.submenu?.addItem(withTitle: "Cannot load currencies", action: nil, keyEquivalent: "") NSLog(error.localizedDescription) case .customError(let customError): NSLog(customError) } } } @objc func selectItem(_ item: NSMenuItem) { guard let id = coins?.first(where: { $0.name == item.title })?.id else { return } switchAppState(to: .updating(id)) currentCoinID = id setMenuItemStateOn(for: item) } /// Finds the first previously selected element and turns it off. Selects the current element. private func setMenuItemStateOn(for item: NSMenuItem) { currenciesMenuAsset.submenu?.items.first { $0.state == .on }?.state = .off item.state = .on } // MARK: Status Menu Actions @IBAction func refreshClicked(_ sender: NSMenuItem) { update() } @IBAction func statusChangeClicked(_ sender: NSMenuItem) { switchMenuItemUpdate(to: timerState == .updating ? .stopped : .updating) } @IBAction func quitClicked(_ sender: NSMenuItem) { NSApplication.shared.terminate(self) } }
apache-2.0
2fe3a401dd2b3c45783bbbe3e1042d25
30.649123
137
0.619041
4.976552
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Assets/SFAssets.swift
1
45935
// // SFAssets.swift // SwifterUI // // Created by Brandon Maldonado Alonso on 8/30/18. // Copyright © 2018 (null). All rights reserved. // // Generated by PaintCode // http://www.paintcodeapp.com // import UIKit public class SFAssets: NSObject { //// Cache private struct Cache { static var imageOfArrowRight: UIImage? static var arrowRightTargets: [AnyObject]? static var imageOfArrowDown: UIImage? static var arrowDownTargets: [AnyObject]? static var imageOfPlus: UIImage? static var plusTargets: [AnyObject]? static var imageOfClose: UIImage? static var closeTargets: [AnyObject]? static var imageOfCancelIcon: UIImage? static var cancelIconTargets: [AnyObject]? static var imageOfBigPlus: UIImage? static var bigPlusTargets: [AnyObject]? static var imageOfComposeIcon: UIImage? static var composeIconTargets: [AnyObject]? static var imageOfProfileIcon: UIImage? static var profileIconTargets: [AnyObject]? static var imageOfShareIcon: UIImage? static var shareIconTargets: [AnyObject]? static var imageOfSendIcon: UIImage? static var sendIconTargets: [AnyObject]? static var imageOfExtraIcon: UIImage? static var extraIconTargets: [AnyObject]? } //// Drawing Methods @objc dynamic public class func drawArrowRight(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 11, height: 20), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 11, height: 20), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 11, y: resizedFrame.height / 20) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 0.29, y: 18.29)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 19.71), controlPoint1: CGPoint(x: -0.1, y: 18.68), controlPoint2: CGPoint(x: -0.1, y: 19.32)) bezierPath.addCurve(to: CGPoint(x: 1.71, y: 19.71), controlPoint1: CGPoint(x: 0.68, y: 20.1), controlPoint2: CGPoint(x: 1.32, y: 20.1)) bezierPath.addLine(to: CGPoint(x: 10.71, y: 10.71)) bezierPath.addCurve(to: CGPoint(x: 10.71, y: 9.29), controlPoint1: CGPoint(x: 11.1, y: 10.32), controlPoint2: CGPoint(x: 11.1, y: 9.68)) bezierPath.addLine(to: CGPoint(x: 1.71, y: 0.29)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 0.29), controlPoint1: CGPoint(x: 1.32, y: -0.1), controlPoint2: CGPoint(x: 0.68, y: -0.1)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 1.71), controlPoint1: CGPoint(x: -0.1, y: 0.68), controlPoint2: CGPoint(x: -0.1, y: 1.32)) bezierPath.addLine(to: CGPoint(x: 8.59, y: 10)) bezierPath.addLine(to: CGPoint(x: 0.29, y: 18.29)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawArrowDown(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 20, height: 11), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 20, height: 11), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 20, y: resizedFrame.height / 11) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 10, y: 8.59)) bezierPath.addLine(to: CGPoint(x: 1.71, y: 0.29)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 0.29), controlPoint1: CGPoint(x: 1.32, y: -0.1), controlPoint2: CGPoint(x: 0.68, y: -0.1)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 1.71), controlPoint1: CGPoint(x: -0.1, y: 0.68), controlPoint2: CGPoint(x: -0.1, y: 1.32)) bezierPath.addLine(to: CGPoint(x: 9.29, y: 10.71)) bezierPath.addCurve(to: CGPoint(x: 10.71, y: 10.71), controlPoint1: CGPoint(x: 9.68, y: 11.1), controlPoint2: CGPoint(x: 10.32, y: 11.1)) bezierPath.addLine(to: CGPoint(x: 19.71, y: 1.71)) bezierPath.addCurve(to: CGPoint(x: 19.71, y: 0.29), controlPoint1: CGPoint(x: 20.1, y: 1.32), controlPoint2: CGPoint(x: 20.1, y: 0.68)) bezierPath.addCurve(to: CGPoint(x: 18.29, y: 0.29), controlPoint1: CGPoint(x: 19.32, y: -0.1), controlPoint2: CGPoint(x: 18.68, y: -0.1)) bezierPath.addLine(to: CGPoint(x: 10, y: 8.59)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawPlus(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 20, height: 20), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 20, height: 20), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 20, y: resizedFrame.height / 20) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 11, y: 9)) bezierPath.addLine(to: CGPoint(x: 11, y: 1)) bezierPath.addCurve(to: CGPoint(x: 10, y: 0), controlPoint1: CGPoint(x: 11, y: 0.45), controlPoint2: CGPoint(x: 10.55, y: 0)) bezierPath.addCurve(to: CGPoint(x: 9, y: 1), controlPoint1: CGPoint(x: 9.45, y: 0), controlPoint2: CGPoint(x: 9, y: 0.45)) bezierPath.addLine(to: CGPoint(x: 9, y: 9)) bezierPath.addLine(to: CGPoint(x: 1, y: 9)) bezierPath.addCurve(to: CGPoint(x: 0, y: 10), controlPoint1: CGPoint(x: 0.45, y: 9), controlPoint2: CGPoint(x: 0, y: 9.45)) bezierPath.addCurve(to: CGPoint(x: 1, y: 11), controlPoint1: CGPoint(x: 0, y: 10.55), controlPoint2: CGPoint(x: 0.45, y: 11)) bezierPath.addLine(to: CGPoint(x: 9, y: 11)) bezierPath.addLine(to: CGPoint(x: 9, y: 19)) bezierPath.addCurve(to: CGPoint(x: 10, y: 20), controlPoint1: CGPoint(x: 9, y: 19.55), controlPoint2: CGPoint(x: 9.45, y: 20)) bezierPath.addCurve(to: CGPoint(x: 11, y: 19), controlPoint1: CGPoint(x: 10.55, y: 20), controlPoint2: CGPoint(x: 11, y: 19.55)) bezierPath.addLine(to: CGPoint(x: 11, y: 11)) bezierPath.addLine(to: CGPoint(x: 19, y: 11)) bezierPath.addCurve(to: CGPoint(x: 20, y: 10), controlPoint1: CGPoint(x: 19.55, y: 11), controlPoint2: CGPoint(x: 20, y: 10.55)) bezierPath.addCurve(to: CGPoint(x: 19, y: 9), controlPoint1: CGPoint(x: 20, y: 9.45), controlPoint2: CGPoint(x: 19.55, y: 9)) bezierPath.addLine(to: CGPoint(x: 11, y: 9)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawClose(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 12, height: 12), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 12, height: 12), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 12, y: resizedFrame.height / 12) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 7.15, y: 6)) bezierPath.addLine(to: CGPoint(x: 11.76, y: 10.61)) bezierPath.addCurve(to: CGPoint(x: 11.76, y: 11.76), controlPoint1: CGPoint(x: 12.08, y: 10.93), controlPoint2: CGPoint(x: 12.08, y: 11.44)) bezierPath.addCurve(to: CGPoint(x: 10.61, y: 11.76), controlPoint1: CGPoint(x: 11.44, y: 12.08), controlPoint2: CGPoint(x: 10.93, y: 12.08)) bezierPath.addLine(to: CGPoint(x: 6, y: 7.15)) bezierPath.addLine(to: CGPoint(x: 1.39, y: 11.76)) bezierPath.addCurve(to: CGPoint(x: 0.24, y: 11.76), controlPoint1: CGPoint(x: 1.07, y: 12.08), controlPoint2: CGPoint(x: 0.56, y: 12.08)) bezierPath.addCurve(to: CGPoint(x: 0.24, y: 10.61), controlPoint1: CGPoint(x: -0.08, y: 11.44), controlPoint2: CGPoint(x: -0.08, y: 10.93)) bezierPath.addLine(to: CGPoint(x: 4.85, y: 6)) bezierPath.addLine(to: CGPoint(x: 0.24, y: 1.39)) bezierPath.addCurve(to: CGPoint(x: 0.24, y: 0.24), controlPoint1: CGPoint(x: -0.08, y: 1.07), controlPoint2: CGPoint(x: -0.08, y: 0.56)) bezierPath.addCurve(to: CGPoint(x: 1.39, y: 0.24), controlPoint1: CGPoint(x: 0.56, y: -0.08), controlPoint2: CGPoint(x: 1.07, y: -0.08)) bezierPath.addLine(to: CGPoint(x: 6, y: 4.85)) bezierPath.addLine(to: CGPoint(x: 10.61, y: 0.24)) bezierPath.addCurve(to: CGPoint(x: 11.76, y: 0.24), controlPoint1: CGPoint(x: 10.93, y: -0.08), controlPoint2: CGPoint(x: 11.44, y: -0.08)) bezierPath.addCurve(to: CGPoint(x: 11.76, y: 1.39), controlPoint1: CGPoint(x: 12.08, y: 0.56), controlPoint2: CGPoint(x: 12.08, y: 1.07)) bezierPath.addLine(to: CGPoint(x: 7.15, y: 6)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawCancelIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 16, height: 16), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 16, height: 16), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 16, y: resizedFrame.height / 16) //// Color Declarations let fillColor2 = UIColor(red: 1.000, green: 0.251, blue: 0.251, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 8, y: 6.59)) bezierPath.addLine(to: CGPoint(x: 1.71, y: 0.29)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 0.29), controlPoint1: CGPoint(x: 1.32, y: -0.1), controlPoint2: CGPoint(x: 0.68, y: -0.1)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 1.71), controlPoint1: CGPoint(x: -0.1, y: 0.68), controlPoint2: CGPoint(x: -0.1, y: 1.32)) bezierPath.addLine(to: CGPoint(x: 6.59, y: 8)) bezierPath.addLine(to: CGPoint(x: 0.29, y: 14.29)) bezierPath.addCurve(to: CGPoint(x: 0.29, y: 15.71), controlPoint1: CGPoint(x: -0.1, y: 14.68), controlPoint2: CGPoint(x: -0.1, y: 15.32)) bezierPath.addCurve(to: CGPoint(x: 1.71, y: 15.71), controlPoint1: CGPoint(x: 0.68, y: 16.1), controlPoint2: CGPoint(x: 1.32, y: 16.1)) bezierPath.addLine(to: CGPoint(x: 8, y: 9.41)) bezierPath.addLine(to: CGPoint(x: 14.29, y: 15.71)) bezierPath.addCurve(to: CGPoint(x: 15.71, y: 15.71), controlPoint1: CGPoint(x: 14.68, y: 16.1), controlPoint2: CGPoint(x: 15.32, y: 16.1)) bezierPath.addCurve(to: CGPoint(x: 15.71, y: 14.29), controlPoint1: CGPoint(x: 16.1, y: 15.32), controlPoint2: CGPoint(x: 16.1, y: 14.68)) bezierPath.addLine(to: CGPoint(x: 9.41, y: 8)) bezierPath.addLine(to: CGPoint(x: 15.71, y: 1.71)) bezierPath.addCurve(to: CGPoint(x: 15.71, y: 0.29), controlPoint1: CGPoint(x: 16.1, y: 1.32), controlPoint2: CGPoint(x: 16.1, y: 0.68)) bezierPath.addCurve(to: CGPoint(x: 14.29, y: 0.29), controlPoint1: CGPoint(x: 15.32, y: -0.1), controlPoint2: CGPoint(x: 14.68, y: -0.1)) bezierPath.addLine(to: CGPoint(x: 8, y: 6.59)) bezierPath.close() fillColor2.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawBigPlus(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 32, height: 32), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 32, height: 32), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 32, y: resizedFrame.height / 32) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 17.6, y: 14.4)) bezierPath.addLine(to: CGPoint(x: 30.4, y: 14.4)) bezierPath.addCurve(to: CGPoint(x: 32, y: 16), controlPoint1: CGPoint(x: 31.28, y: 14.4), controlPoint2: CGPoint(x: 32, y: 15.12)) bezierPath.addCurve(to: CGPoint(x: 30.4, y: 17.6), controlPoint1: CGPoint(x: 32, y: 16.88), controlPoint2: CGPoint(x: 31.28, y: 17.6)) bezierPath.addLine(to: CGPoint(x: 17.6, y: 17.6)) bezierPath.addLine(to: CGPoint(x: 17.6, y: 30.4)) bezierPath.addCurve(to: CGPoint(x: 16, y: 32), controlPoint1: CGPoint(x: 17.6, y: 31.28), controlPoint2: CGPoint(x: 16.88, y: 32)) bezierPath.addCurve(to: CGPoint(x: 14.4, y: 30.4), controlPoint1: CGPoint(x: 15.12, y: 32), controlPoint2: CGPoint(x: 14.4, y: 31.28)) bezierPath.addLine(to: CGPoint(x: 14.4, y: 17.6)) bezierPath.addLine(to: CGPoint(x: 1.6, y: 17.6)) bezierPath.addCurve(to: CGPoint(x: 0, y: 16), controlPoint1: CGPoint(x: 0.72, y: 17.6), controlPoint2: CGPoint(x: 0, y: 16.88)) bezierPath.addCurve(to: CGPoint(x: 1.6, y: 14.4), controlPoint1: CGPoint(x: 0, y: 15.12), controlPoint2: CGPoint(x: 0.72, y: 14.4)) bezierPath.addLine(to: CGPoint(x: 14.4, y: 14.4)) bezierPath.addLine(to: CGPoint(x: 14.4, y: 1.6)) bezierPath.addCurve(to: CGPoint(x: 16, y: 0), controlPoint1: CGPoint(x: 14.4, y: 0.72), controlPoint2: CGPoint(x: 15.12, y: 0)) bezierPath.addCurve(to: CGPoint(x: 17.6, y: 1.6), controlPoint1: CGPoint(x: 16.88, y: 0), controlPoint2: CGPoint(x: 17.6, y: 0.72)) bezierPath.addLine(to: CGPoint(x: 17.6, y: 14.4)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawComposeIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 21, height: 21), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 21, height: 21), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 21, y: resizedFrame.height / 21) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 8.35, y: 10.4)) bezierPath.addLine(to: CGPoint(x: 18.58, y: 0.18)) bezierPath.addCurve(to: CGPoint(x: 19.42, y: 0.18), controlPoint1: CGPoint(x: 18.81, y: -0.06), controlPoint2: CGPoint(x: 19.19, y: -0.06)) bezierPath.addLine(to: CGPoint(x: 20.58, y: 1.33)) bezierPath.addCurve(to: CGPoint(x: 20.58, y: 2.18), controlPoint1: CGPoint(x: 20.81, y: 1.56), controlPoint2: CGPoint(x: 20.81, y: 1.94)) bezierPath.addLine(to: CGPoint(x: 10.35, y: 12.4)) bezierPath.addLine(to: CGPoint(x: 8.35, y: 10.4)) bezierPath.close() bezierPath.move(to: CGPoint(x: 8.1, y: 14.05)) bezierPath.addLine(to: CGPoint(x: 6.57, y: 14.56)) bezierPath.addCurve(to: CGPoint(x: 6.19, y: 14.37), controlPoint1: CGPoint(x: 6.41, y: 14.61), controlPoint2: CGPoint(x: 6.24, y: 14.53)) bezierPath.addCurve(to: CGPoint(x: 6.19, y: 14.18), controlPoint1: CGPoint(x: 6.17, y: 14.31), controlPoint2: CGPoint(x: 6.17, y: 14.24)) bezierPath.addLine(to: CGPoint(x: 6.7, y: 12.65)) bezierPath.addCurve(to: CGPoint(x: 7.65, y: 11.11), controlPoint1: CGPoint(x: 6.89, y: 12.07), controlPoint2: CGPoint(x: 7.22, y: 11.54)) bezierPath.addLine(to: CGPoint(x: 9.65, y: 13.1)) bezierPath.addCurve(to: CGPoint(x: 8.1, y: 14.05), controlPoint1: CGPoint(x: 9.21, y: 13.53), controlPoint2: CGPoint(x: 8.68, y: 13.86)) bezierPath.close() bezierPath.move(to: CGPoint(x: 14.32, y: 1.61)) bezierPath.addLine(to: CGPoint(x: 13.46, y: 2.46)) bezierPath.addCurve(to: CGPoint(x: 12.76, y: 2.75), controlPoint1: CGPoint(x: 13.28, y: 2.65), controlPoint2: CGPoint(x: 13.02, y: 2.75)) bezierPath.addLine(to: CGPoint(x: 3.85, y: 2.75)) bezierPath.addCurve(to: CGPoint(x: 2.48, y: 2.92), controlPoint1: CGPoint(x: 2.93, y: 2.75), controlPoint2: CGPoint(x: 2.7, y: 2.79)) bezierPath.addCurve(to: CGPoint(x: 2.16, y: 3.23), controlPoint1: CGPoint(x: 2.34, y: 2.99), controlPoint2: CGPoint(x: 2.24, y: 3.09)) bezierPath.addCurve(to: CGPoint(x: 2, y: 4.6), controlPoint1: CGPoint(x: 2.04, y: 3.46), controlPoint2: CGPoint(x: 2, y: 3.68)) bezierPath.addLine(to: CGPoint(x: 2, y: 16.91)) bezierPath.addCurve(to: CGPoint(x: 2.16, y: 18.27), controlPoint1: CGPoint(x: 2, y: 17.82), controlPoint2: CGPoint(x: 2.04, y: 18.05)) bezierPath.addCurve(to: CGPoint(x: 2.48, y: 18.59), controlPoint1: CGPoint(x: 2.24, y: 18.41), controlPoint2: CGPoint(x: 2.34, y: 18.51)) bezierPath.addCurve(to: CGPoint(x: 3.85, y: 18.75), controlPoint1: CGPoint(x: 2.7, y: 18.71), controlPoint2: CGPoint(x: 2.93, y: 18.75)) bezierPath.addLine(to: CGPoint(x: 16.15, y: 18.75)) bezierPath.addCurve(to: CGPoint(x: 17.52, y: 18.59), controlPoint1: CGPoint(x: 17.07, y: 18.75), controlPoint2: CGPoint(x: 17.3, y: 18.71)) bezierPath.addCurve(to: CGPoint(x: 17.84, y: 18.27), controlPoint1: CGPoint(x: 17.66, y: 18.51), controlPoint2: CGPoint(x: 17.76, y: 18.41)) bezierPath.addCurve(to: CGPoint(x: 18, y: 16.91), controlPoint1: CGPoint(x: 17.96, y: 18.05), controlPoint2: CGPoint(x: 18, y: 17.82)) bezierPath.addLine(to: CGPoint(x: 18, y: 7.99)) bezierPath.addCurve(to: CGPoint(x: 18.29, y: 7.29), controlPoint1: CGPoint(x: 18, y: 7.73), controlPoint2: CGPoint(x: 18.11, y: 7.47)) bezierPath.addLine(to: CGPoint(x: 19.15, y: 6.43)) bezierPath.addCurve(to: CGPoint(x: 19.85, y: 6.43), controlPoint1: CGPoint(x: 19.34, y: 6.24), controlPoint2: CGPoint(x: 19.66, y: 6.24)) bezierPath.addCurve(to: CGPoint(x: 20, y: 6.79), controlPoint1: CGPoint(x: 19.95, y: 6.53), controlPoint2: CGPoint(x: 20, y: 6.65)) bezierPath.addLine(to: CGPoint(x: 20, y: 16.91)) bezierPath.addCurve(to: CGPoint(x: 19.6, y: 19.22), controlPoint1: CGPoint(x: 20, y: 18.24), controlPoint2: CGPoint(x: 19.86, y: 18.73)) bezierPath.addCurve(to: CGPoint(x: 18.47, y: 20.35), controlPoint1: CGPoint(x: 19.34, y: 19.71), controlPoint2: CGPoint(x: 18.95, y: 20.09)) bezierPath.addCurve(to: CGPoint(x: 16.15, y: 20.75), controlPoint1: CGPoint(x: 17.98, y: 20.61), controlPoint2: CGPoint(x: 17.49, y: 20.75)) bezierPath.addLine(to: CGPoint(x: 3.85, y: 20.75)) bezierPath.addCurve(to: CGPoint(x: 1.53, y: 20.35), controlPoint1: CGPoint(x: 2.51, y: 20.75), controlPoint2: CGPoint(x: 2.02, y: 20.61)) bezierPath.addCurve(to: CGPoint(x: 0.4, y: 19.22), controlPoint1: CGPoint(x: 1.05, y: 20.09), controlPoint2: CGPoint(x: 0.66, y: 19.71)) bezierPath.addCurve(to: CGPoint(x: 0, y: 16.91), controlPoint1: CGPoint(x: 0.14, y: 18.73), controlPoint2: CGPoint(x: 0, y: 18.24)) bezierPath.addLine(to: CGPoint(x: 0, y: 4.6)) bezierPath.addCurve(to: CGPoint(x: 0.4, y: 2.29), controlPoint1: CGPoint(x: 0, y: 3.26), controlPoint2: CGPoint(x: 0.14, y: 2.78)) bezierPath.addCurve(to: CGPoint(x: 1.53, y: 1.15), controlPoint1: CGPoint(x: 0.66, y: 1.8), controlPoint2: CGPoint(x: 1.05, y: 1.41)) bezierPath.addCurve(to: CGPoint(x: 3.85, y: 0.75), controlPoint1: CGPoint(x: 2.02, y: 0.89), controlPoint2: CGPoint(x: 2.51, y: 0.75)) bezierPath.addLine(to: CGPoint(x: 13.96, y: 0.75)) bezierPath.addCurve(to: CGPoint(x: 14.46, y: 1.25), controlPoint1: CGPoint(x: 14.24, y: 0.75), controlPoint2: CGPoint(x: 14.46, y: 0.98)) bezierPath.addCurve(to: CGPoint(x: 14.32, y: 1.61), controlPoint1: CGPoint(x: 14.46, y: 1.38), controlPoint2: CGPoint(x: 14.41, y: 1.51)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawProfileIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 21, height: 21), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 21, height: 21), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 21, y: resizedFrame.height / 21) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 10.5, y: 11.44)) bezierPath.addCurve(to: CGPoint(x: 5.25, y: 5.72), controlPoint1: CGPoint(x: 7.6, y: 11.44), controlPoint2: CGPoint(x: 5.25, y: 8.88)) bezierPath.addCurve(to: CGPoint(x: 10.5, y: -0), controlPoint1: CGPoint(x: 5.25, y: 2.56), controlPoint2: CGPoint(x: 7.6, y: -0)) bezierPath.addCurve(to: CGPoint(x: 15.75, y: 5.72), controlPoint1: CGPoint(x: 13.4, y: -0), controlPoint2: CGPoint(x: 15.75, y: 2.56)) bezierPath.addCurve(to: CGPoint(x: 10.5, y: 11.44), controlPoint1: CGPoint(x: 15.75, y: 8.88), controlPoint2: CGPoint(x: 13.4, y: 11.44)) bezierPath.close() bezierPath.move(to: CGPoint(x: 21, y: 18.5)) bezierPath.addCurve(to: CGPoint(x: 0, y: 18.5), controlPoint1: CGPoint(x: 21, y: 21.83), controlPoint2: CGPoint(x: 0, y: 21.83)) bezierPath.addCurve(to: CGPoint(x: 10.5, y: 12.48), controlPoint1: CGPoint(x: 0, y: 15.18), controlPoint2: CGPoint(x: 5.97, y: 12.48)) bezierPath.addCurve(to: CGPoint(x: 21, y: 18.5), controlPoint1: CGPoint(x: 15.03, y: 12.48), controlPoint2: CGPoint(x: 21, y: 15.18)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawShareIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 17, height: 22), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 17, height: 22), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 17, y: resizedFrame.height / 22) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 12.28, y: 9.17)) bezierPath.addCurve(to: CGPoint(x: 11.33, y: 8.25), controlPoint1: CGPoint(x: 11.76, y: 9.17), controlPoint2: CGPoint(x: 11.33, y: 8.76)) bezierPath.addCurve(to: CGPoint(x: 12.28, y: 7.33), controlPoint1: CGPoint(x: 11.33, y: 7.74), controlPoint2: CGPoint(x: 11.76, y: 7.33)) bezierPath.addLine(to: CGPoint(x: 13.63, y: 7.33)) bezierPath.addCurve(to: CGPoint(x: 15.53, y: 7.69), controlPoint1: CGPoint(x: 14.54, y: 7.33), controlPoint2: CGPoint(x: 15.03, y: 7.42)) bezierPath.addCurve(to: CGPoint(x: 16.64, y: 8.76), controlPoint1: CGPoint(x: 16.01, y: 7.93), controlPoint2: CGPoint(x: 16.38, y: 8.3)) bezierPath.addCurve(to: CGPoint(x: 17, y: 10.6), controlPoint1: CGPoint(x: 16.91, y: 9.25), controlPoint2: CGPoint(x: 17, y: 9.72)) bezierPath.addLine(to: CGPoint(x: 17, y: 18.73)) bezierPath.addCurve(to: CGPoint(x: 16.64, y: 20.58), controlPoint1: CGPoint(x: 17, y: 19.62), controlPoint2: CGPoint(x: 16.91, y: 20.09)) bezierPath.addCurve(to: CGPoint(x: 15.53, y: 21.65), controlPoint1: CGPoint(x: 16.38, y: 21.04), controlPoint2: CGPoint(x: 16.01, y: 21.4)) bezierPath.addCurve(to: CGPoint(x: 13.63, y: 22), controlPoint1: CGPoint(x: 15.03, y: 21.91), controlPoint2: CGPoint(x: 14.54, y: 22)) bezierPath.addLine(to: CGPoint(x: 3.37, y: 22)) bezierPath.addCurve(to: CGPoint(x: 1.47, y: 21.65), controlPoint1: CGPoint(x: 2.46, y: 22), controlPoint2: CGPoint(x: 1.97, y: 21.91)) bezierPath.addCurve(to: CGPoint(x: 0.36, y: 20.58), controlPoint1: CGPoint(x: 0.99, y: 21.4), controlPoint2: CGPoint(x: 0.62, y: 21.04)) bezierPath.addCurve(to: CGPoint(x: 0, y: 18.73), controlPoint1: CGPoint(x: 0.09, y: 20.09), controlPoint2: CGPoint(x: 0, y: 19.62)) bezierPath.addLine(to: CGPoint(x: 0, y: 10.6)) bezierPath.addCurve(to: CGPoint(x: 0.36, y: 8.76), controlPoint1: CGPoint(x: 0, y: 9.72), controlPoint2: CGPoint(x: 0.09, y: 9.25)) bezierPath.addCurve(to: CGPoint(x: 1.47, y: 7.69), controlPoint1: CGPoint(x: 0.62, y: 8.3), controlPoint2: CGPoint(x: 0.99, y: 7.93)) bezierPath.addCurve(to: CGPoint(x: 3.37, y: 7.33), controlPoint1: CGPoint(x: 1.97, y: 7.42), controlPoint2: CGPoint(x: 2.46, y: 7.33)) bezierPath.addLine(to: CGPoint(x: 4.72, y: 7.33)) bezierPath.addCurve(to: CGPoint(x: 5.67, y: 8.25), controlPoint1: CGPoint(x: 5.24, y: 7.33), controlPoint2: CGPoint(x: 5.67, y: 7.74)) bezierPath.addCurve(to: CGPoint(x: 4.72, y: 9.17), controlPoint1: CGPoint(x: 5.67, y: 8.76), controlPoint2: CGPoint(x: 5.24, y: 9.17)) bezierPath.addLine(to: CGPoint(x: 3.37, y: 9.17)) bezierPath.addCurve(to: CGPoint(x: 2.36, y: 9.3), controlPoint1: CGPoint(x: 2.74, y: 9.17), controlPoint2: CGPoint(x: 2.55, y: 9.2)) bezierPath.addCurve(to: CGPoint(x: 2.03, y: 9.62), controlPoint1: CGPoint(x: 2.21, y: 9.38), controlPoint2: CGPoint(x: 2.11, y: 9.48)) bezierPath.addCurve(to: CGPoint(x: 1.89, y: 10.6), controlPoint1: CGPoint(x: 1.93, y: 9.81), controlPoint2: CGPoint(x: 1.89, y: 9.99)) bezierPath.addLine(to: CGPoint(x: 1.89, y: 18.73)) bezierPath.addCurve(to: CGPoint(x: 2.03, y: 19.71), controlPoint1: CGPoint(x: 1.89, y: 19.34), controlPoint2: CGPoint(x: 1.93, y: 19.52)) bezierPath.addCurve(to: CGPoint(x: 2.36, y: 20.03), controlPoint1: CGPoint(x: 2.11, y: 19.85), controlPoint2: CGPoint(x: 2.21, y: 19.96)) bezierPath.addCurve(to: CGPoint(x: 3.37, y: 20.17), controlPoint1: CGPoint(x: 2.55, y: 20.13), controlPoint2: CGPoint(x: 2.74, y: 20.17)) bezierPath.addLine(to: CGPoint(x: 13.63, y: 20.17)) bezierPath.addCurve(to: CGPoint(x: 14.64, y: 20.03), controlPoint1: CGPoint(x: 14.26, y: 20.17), controlPoint2: CGPoint(x: 14.45, y: 20.13)) bezierPath.addCurve(to: CGPoint(x: 14.97, y: 19.71), controlPoint1: CGPoint(x: 14.79, y: 19.96), controlPoint2: CGPoint(x: 14.89, y: 19.85)) bezierPath.addCurve(to: CGPoint(x: 15.11, y: 18.73), controlPoint1: CGPoint(x: 15.07, y: 19.52), controlPoint2: CGPoint(x: 15.11, y: 19.34)) bezierPath.addLine(to: CGPoint(x: 15.11, y: 10.6)) bezierPath.addCurve(to: CGPoint(x: 14.97, y: 9.62), controlPoint1: CGPoint(x: 15.11, y: 9.99), controlPoint2: CGPoint(x: 15.07, y: 9.81)) bezierPath.addCurve(to: CGPoint(x: 14.64, y: 9.3), controlPoint1: CGPoint(x: 14.89, y: 9.48), controlPoint2: CGPoint(x: 14.79, y: 9.38)) bezierPath.addCurve(to: CGPoint(x: 13.63, y: 9.17), controlPoint1: CGPoint(x: 14.45, y: 9.2), controlPoint2: CGPoint(x: 14.26, y: 9.17)) bezierPath.addLine(to: CGPoint(x: 12.28, y: 9.17)) bezierPath.close() bezierPath.move(to: CGPoint(x: 4.05, y: 3.94)) bezierPath.addLine(to: CGPoint(x: 7.65, y: 0.44)) bezierPath.addCurve(to: CGPoint(x: 7.83, y: 0.27), controlPoint1: CGPoint(x: 7.73, y: 0.37), controlPoint2: CGPoint(x: 7.79, y: 0.31)) bezierPath.addCurve(to: CGPoint(x: 8.77, y: 0.04), controlPoint1: CGPoint(x: 8.1, y: 0.01), controlPoint2: CGPoint(x: 8.46, y: -0.05)) bezierPath.addCurve(to: CGPoint(x: 8.97, y: 0.12), controlPoint1: CGPoint(x: 8.84, y: 0.06), controlPoint2: CGPoint(x: 8.9, y: 0.09)) bezierPath.addCurve(to: CGPoint(x: 9.21, y: 0.32), controlPoint1: CGPoint(x: 9.06, y: 0.17), controlPoint2: CGPoint(x: 9.14, y: 0.24)) bezierPath.addLine(to: CGPoint(x: 12.95, y: 3.94)) bezierPath.addCurve(to: CGPoint(x: 12.95, y: 5.23), controlPoint1: CGPoint(x: 13.31, y: 4.29), controlPoint2: CGPoint(x: 13.31, y: 4.88)) bezierPath.addCurve(to: CGPoint(x: 11.61, y: 5.23), controlPoint1: CGPoint(x: 12.58, y: 5.59), controlPoint2: CGPoint(x: 11.98, y: 5.59)) bezierPath.addLine(to: CGPoint(x: 9.44, y: 3.13)) bezierPath.addLine(to: CGPoint(x: 9.44, y: 14.67)) bezierPath.addCurve(to: CGPoint(x: 8.5, y: 15.59), controlPoint1: CGPoint(x: 9.44, y: 15.17), controlPoint2: CGPoint(x: 9.02, y: 15.59)) bezierPath.addCurve(to: CGPoint(x: 7.56, y: 14.67), controlPoint1: CGPoint(x: 7.98, y: 15.59), controlPoint2: CGPoint(x: 7.56, y: 15.17)) bezierPath.addLine(to: CGPoint(x: 7.56, y: 3.13)) bezierPath.addLine(to: CGPoint(x: 5.39, y: 5.23)) bezierPath.addCurve(to: CGPoint(x: 4.05, y: 5.23), controlPoint1: CGPoint(x: 5.02, y: 5.59), controlPoint2: CGPoint(x: 4.42, y: 5.59)) bezierPath.addCurve(to: CGPoint(x: 4.05, y: 3.94), controlPoint1: CGPoint(x: 3.69, y: 4.88), controlPoint2: CGPoint(x: 3.69, y: 4.29)) bezierPath.close() fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawSendIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 12, height: 12), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 12, height: 12), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 12, y: resizedFrame.height / 12) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 10.14, y: 6)) bezierPath.addLine(to: CGPoint(x: 4.14, y: 0)) bezierPath.addLine(to: CGPoint(x: 3, y: 1.14)) bezierPath.addLine(to: CGPoint(x: 7.86, y: 6)) bezierPath.addLine(to: CGPoint(x: 3, y: 10.86)) bezierPath.addLine(to: CGPoint(x: 4.14, y: 12)) bezierPath.addLine(to: CGPoint(x: 10.14, y: 6)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() context.restoreGState() } @objc dynamic public class func drawExtraIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 12, height: 12), resizing: ResizingBehavior = .aspectFit) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Resize to Target Frame context.saveGState() let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 12, height: 12), target: targetFrame) context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY) context.scaleBy(x: resizedFrame.width / 12, y: resizedFrame.height / 12) //// Color Declarations let fillColor = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000) //// Bezier Drawing let bezierPath = UIBezierPath() bezierPath.move(to: CGPoint(x: 5, y: 1)) bezierPath.addLine(to: CGPoint(x: 5, y: 11)) bezierPath.addCurve(to: CGPoint(x: 6, y: 12), controlPoint1: CGPoint(x: 5, y: 11.55), controlPoint2: CGPoint(x: 5.45, y: 12)) bezierPath.addCurve(to: CGPoint(x: 7, y: 11), controlPoint1: CGPoint(x: 6.55, y: 12), controlPoint2: CGPoint(x: 7, y: 11.55)) bezierPath.addLine(to: CGPoint(x: 7, y: 1)) bezierPath.addCurve(to: CGPoint(x: 6, y: 0), controlPoint1: CGPoint(x: 7, y: 0.45), controlPoint2: CGPoint(x: 6.55, y: 0)) bezierPath.addCurve(to: CGPoint(x: 5, y: 1), controlPoint1: CGPoint(x: 5.45, y: 0), controlPoint2: CGPoint(x: 5, y: 0.45)) bezierPath.close() bezierPath.usesEvenOddFillRule = true fillColor.setFill() bezierPath.fill() //// Bezier 2 Drawing let bezier2Path = UIBezierPath() bezier2Path.move(to: CGPoint(x: 11, y: 5)) bezier2Path.addLine(to: CGPoint(x: 1, y: 5)) bezier2Path.addCurve(to: CGPoint(x: 0, y: 6), controlPoint1: CGPoint(x: 0.45, y: 5), controlPoint2: CGPoint(x: 0, y: 5.45)) bezier2Path.addCurve(to: CGPoint(x: 1, y: 7), controlPoint1: CGPoint(x: 0, y: 6.55), controlPoint2: CGPoint(x: 0.45, y: 7)) bezier2Path.addLine(to: CGPoint(x: 11, y: 7)) bezier2Path.addCurve(to: CGPoint(x: 12, y: 6), controlPoint1: CGPoint(x: 11.55, y: 7), controlPoint2: CGPoint(x: 12, y: 6.55)) bezier2Path.addCurve(to: CGPoint(x: 11, y: 5), controlPoint1: CGPoint(x: 12, y: 5.45), controlPoint2: CGPoint(x: 11.55, y: 5)) bezier2Path.close() bezier2Path.usesEvenOddFillRule = true fillColor.setFill() bezier2Path.fill() context.restoreGState() } //// Generated Images @objc dynamic public class var imageOfArrowRight: UIImage { if Cache.imageOfArrowRight != nil { return Cache.imageOfArrowRight! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 11, height: 20), false, 0) SFAssets.drawArrowRight() Cache.imageOfArrowRight = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfArrowRight! } @objc dynamic public class var imageOfArrowDown: UIImage { if Cache.imageOfArrowDown != nil { return Cache.imageOfArrowDown! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 11), false, 0) SFAssets.drawArrowDown() Cache.imageOfArrowDown = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfArrowDown! } @objc dynamic public class var imageOfPlus: UIImage { if Cache.imageOfPlus != nil { return Cache.imageOfPlus! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0) SFAssets.drawPlus() Cache.imageOfPlus = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfPlus! } @objc dynamic public class var imageOfClose: UIImage { if Cache.imageOfClose != nil { return Cache.imageOfClose! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 12, height: 12), false, 0) SFAssets.drawClose() Cache.imageOfClose = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfClose! } @objc dynamic public class var imageOfCancelIcon: UIImage { if Cache.imageOfCancelIcon != nil { return Cache.imageOfCancelIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 16, height: 16), false, 0) SFAssets.drawCancelIcon() Cache.imageOfCancelIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfCancelIcon! } @objc dynamic public class var imageOfBigPlus: UIImage { if Cache.imageOfBigPlus != nil { return Cache.imageOfBigPlus! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 32, height: 32), false, 0) SFAssets.drawBigPlus() Cache.imageOfBigPlus = UIGraphicsGetImageFromCurrentImageContext()!.withRenderingMode(.alwaysTemplate) UIGraphicsEndImageContext() return Cache.imageOfBigPlus! } @objc dynamic public class var imageOfComposeIcon: UIImage { if Cache.imageOfComposeIcon != nil { return Cache.imageOfComposeIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 21, height: 21), false, 0) SFAssets.drawComposeIcon() Cache.imageOfComposeIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfComposeIcon! } @objc dynamic public class var imageOfProfileIcon: UIImage { if Cache.imageOfProfileIcon != nil { return Cache.imageOfProfileIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 21, height: 21), false, 0) SFAssets.drawProfileIcon() Cache.imageOfProfileIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfProfileIcon! } @objc dynamic public class var imageOfShareIcon: UIImage { if Cache.imageOfShareIcon != nil { return Cache.imageOfShareIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 17, height: 22), false, 0) SFAssets.drawShareIcon() Cache.imageOfShareIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfShareIcon! } @objc dynamic public class var imageOfSendIcon: UIImage { if Cache.imageOfSendIcon != nil { return Cache.imageOfSendIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 12, height: 12), false, 0) SFAssets.drawSendIcon() Cache.imageOfSendIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfSendIcon! } @objc dynamic public class var imageOfExtraIcon: UIImage { if Cache.imageOfExtraIcon != nil { return Cache.imageOfExtraIcon! } UIGraphicsBeginImageContextWithOptions(CGSize(width: 12, height: 12), false, 0) SFAssets.drawExtraIcon() Cache.imageOfExtraIcon = UIGraphicsGetImageFromCurrentImageContext()! UIGraphicsEndImageContext() return Cache.imageOfExtraIcon! } //// Customization Infrastructure @objc @IBOutlet dynamic var arrowRightTargets: [AnyObject]! { get { return Cache.arrowRightTargets } set { Cache.arrowRightTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfArrowRight) } } } @objc @IBOutlet dynamic var arrowDownTargets: [AnyObject]! { get { return Cache.arrowDownTargets } set { Cache.arrowDownTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfArrowDown) } } } @objc @IBOutlet dynamic var plusTargets: [AnyObject]! { get { return Cache.plusTargets } set { Cache.plusTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfPlus) } } } @objc @IBOutlet dynamic var closeTargets: [AnyObject]! { get { return Cache.closeTargets } set { Cache.closeTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfClose) } } } @objc @IBOutlet dynamic var cancelIconTargets: [AnyObject]! { get { return Cache.cancelIconTargets } set { Cache.cancelIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfCancelIcon) } } } @objc @IBOutlet dynamic var bigPlusTargets: [AnyObject]! { get { return Cache.bigPlusTargets } set { Cache.bigPlusTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfBigPlus) } } } @objc @IBOutlet dynamic var composeIconTargets: [AnyObject]! { get { return Cache.composeIconTargets } set { Cache.composeIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfComposeIcon) } } } @objc @IBOutlet dynamic var profileIconTargets: [AnyObject]! { get { return Cache.profileIconTargets } set { Cache.profileIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfProfileIcon) } } } @objc @IBOutlet dynamic var shareIconTargets: [AnyObject]! { get { return Cache.shareIconTargets } set { Cache.shareIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfShareIcon) } } } @objc @IBOutlet dynamic var sendIconTargets: [AnyObject]! { get { return Cache.sendIconTargets } set { Cache.sendIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfSendIcon) } } } @objc @IBOutlet dynamic var extraIconTargets: [AnyObject]! { get { return Cache.extraIconTargets } set { Cache.extraIconTargets = newValue for target: AnyObject in newValue { let _ = target.perform(NSSelectorFromString("setImage:"), with: SFAssets.imageOfExtraIcon) } } } @objc(SFAssetsResizingBehavior) public enum ResizingBehavior: Int { case aspectFit /// The content is proportionally resized to fit into the target rectangle. case aspectFill /// The content is proportionally resized to completely fill the target rectangle. case stretch /// The content is stretched to match the entire target rectangle. case center /// The content is centered in the target rectangle, but it is NOT resized. public func apply(rect: CGRect, target: CGRect) -> CGRect { if rect == target || target == CGRect.zero { return rect } var scales = CGSize.zero scales.width = abs(target.width / rect.width) scales.height = abs(target.height / rect.height) switch self { case .aspectFit: scales.width = min(scales.width, scales.height) scales.height = scales.width case .aspectFill: scales.width = max(scales.width, scales.height) scales.height = scales.width case .stretch: break case .center: scales.width = 1 scales.height = 1 } var result = rect.standardized result.size.width *= scales.width result.size.height *= scales.height result.origin.x = target.minX + (target.width - result.width) / 2 result.origin.y = target.minY + (target.height - result.height) / 2 return result } } }
mit
a939fd2ce2b4716a8f7f35519bfa200c
53.359763
165
0.626704
3.506145
false
false
false
false
danwilliams64/AsyncOperation
AsyncOperation/AsyncOperation.swift
1
2404
// // AsyncOperation.swift // AsyncOperation // // Copyright (c) 2015, Dan Williams // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation public class AsyncOperation: NSOperation { // MARK: - Properties public override var executing: Bool { return internalExecuting } public override var finished: Bool { return internalFinshed } public override var asynchronous: Bool { return true } internal var internalExecuting = false { willSet { willChangeValueForKey("isExecuting") } didSet { didChangeValueForKey("isExecuting") } } internal var internalFinshed = false { willSet { willChangeValueForKey("isFinished") } didSet { didChangeValueForKey("isFinished") } } // MARK: - NSOperation public override func start() { internalExecuting = true execute() } // MARK: - Public /** Override `execute` with the operation's main logic. */ public func execute() { fatalError("`execute` method not overridden by superclass.") } /** Called from within the `execute` function when the operation has completed. */ internal func finish() { internalExecuting = false internalFinshed = true } }
mit
dda0e0c0135bf2296447bedbc277712e
31.945205
90
0.670965
4.987552
false
false
false
false
patrick-gleeson/thinginess_swift
ThinginessSwift/Classes/BaseThing.swift
1
1245
// // BaseThing.swift // Pods // // Created by Patrick Gleeson on 16/09/2016. // // public class BaseThing { // Constructors public init(attributes: [String: String]) { self.attributes = attributes ?? [String:String]() ThingRegistry.sharedInstance.register(self, with_types: thingTypes()) } public convenience init() { self.init(attributes: [:]) } // Public methods public func attribute(attribute_name: String) -> String? { return attributes[attribute_name] } public func update(newAttributes: [String: String]) { newAttributes.forEach { (name : String, value: String) -> () in attributes[name] = value } } // Private methods private func thingTypes() -> Array<String> { return thingTypesFromMirror(Mirror(reflecting: self)) } private func thingTypesFromMirror(mirror: Mirror) -> Array<String> { let typeString = String(mirror.subjectType) if typeString == "BaseThing" { return [typeString] } else { return [typeString] + thingTypesFromMirror(mirror.superclassMirror()!) } } // Instance variables private var attributes : [String: String] }
mit
074d65463ca14daf71822d355b707dc3
24.9375
82
0.616064
4.430605
false
false
false
false
BrandonMA/SwifterUI
SwifterUI/SwifterUI/UILibrary/Extensions/UIView.swift
1
696
// // UIView.swift // SwifterUI // // Created by brandon maldonado alonso on 06/02/18. // Copyright © 2018 Brandon Maldonado Alonso. All rights reserved. // import UIKit public extension UIView { // MARK: - Instance Properties final var useCompactInterface: Bool { return self.traitCollection.horizontalSizeClass == .compact || self.traitCollection.verticalSizeClass == .compact } // MARK: - Instance Methods final func addShadow(color: UIColor, offSet: CGSize, radius: CGFloat, opacity: Float) { layer.shadowColor = color.cgColor layer.shadowOffset = offSet layer.shadowRadius = radius layer.shadowOpacity = opacity } }
mit
ba38e91e92dcef56a56dacc3dcb54f78
24.740741
121
0.683453
4.633333
false
false
false
false
Swiftodon/Leviathan
Leviathan/Sources/Views/AccountManagement/LogonView.swift
1
3870
// // LogonView.swift // Leviathan // // Created by Thomas Bonk on 11.11.22. // Copyright 2022 The Swiftodon Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import MastodonSwift import SwiftUI import WebView struct LogonView: View { var body: some View { ScrollView { VStack { Text("Please enter the server name of the Mastodon instance, that you wish to logon to.") .lineLimit(5) .multilineTextAlignment(.center) .padding(.bottom, 10) Form { TextField("Server Name:", text: $serverName, prompt: Text("Server Name")) .fixedSize() .onChange(of: serverName, perform: loadInstanceInformation(server:)) } .padding(.bottom, 10) instanceInformation() WebView(webView: webViewStore.webView) .frame(width: 400, height: 300) .padding(.vertical, 10) .cornerRadius(10) Spacer() } } .onAppear { webViewStore.webView.load(URLRequest(url: URL(string: "https://www.youtube.com/embed/IPSbNdBmWKE")!)) } .padding(.all, 20) } var completed: (() -> ())? = nil // MARK: - Private Properties @StateObject private var webViewStore = WebViewStore() @EnvironmentObject private var sessionModel: SessionModel @State private var serverName: String = "" @State private var instance: Instance? = nil // MARK: - Private Methods @ViewBuilder private func instanceInformation() -> some View { if let instance { VStack { AsyncImage( url: URL(string: instance.thumbnail!)!, content:{ $0.resizable() }, placeholder: { Text("🐘").font(.system(size: 72)) }) .frame(width: 240, height: 120) .cornerRadius(10) Text(instance.description!.attributedString!) .lineLimit(50) .multilineTextAlignment(.center) Button { logon() } label: { Text("Logon") .font(.system(size: 18)) .padding() .background(RoundedRectangle(cornerRadius: 8).fill(Color.blue)) .frame(width: 250, height: 50) } .buttonStyle(PlainButtonStyle()) Spacer() } } else { EmptyView() } } private func logon() { sessionModel.logon(instanceURL: URL(string: "https://\(serverName)")!) completed?() } private func loadInstanceInformation(server: String) { if let url = URL(string: "https://\(server)") { let client = MastodonClient(baseURL: url) Task { let instance = try? await client.readInstanceInformation() update { self.instance = instance } } } } } struct LogonView_Previews: PreviewProvider { static var previews: some View { LogonView() } }
apache-2.0
992c14fa1a61b508f40a9bc1e16cc3f6
28.519084
113
0.528575
4.90736
false
false
false
false
BalestraPatrick/Tweetometer
Carthage/Checkouts/Swifter/Sources/SwifterMessages.swift
2
4454
// // SwifterMessages.swift // Swifter // // Copyright (c) 2014 Matt Donnelly. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Swifter { /** GET direct_messages/events/show Returns a single Direct Message event by the given id. */ public func getDirectMessage(for messageId: String, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "direct_messages/events/show.json" let parameters = ["id": messageId] self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** GET direct_messages/events/list Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order. */ public func getDirectMessages(count: Int? = nil, cursor: String? = nil, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "direct_messages/events/list.json" var parameters: [String: Any] = [:] parameters["count"] ??= count parameters["cursor"] ??= cursor self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** DELETE direct_messages/events/destroy Returns all Direct Message events (both sent and received) within the last 30 days. Sorted in reverse-chronological order. */ public func destroyDirectMessage(for messageId: String, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "direct_messages/events/destroy.json" let parameters = ["id": messageId] self.deleteJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } /** POST direct_messages/events/new Publishes a new message_create event resulting in a Direct Message sent to a specified user from the authenticating user. Returns an event if successful. Supports publishing Direct Messages with optional Quick Reply and media attachment. Replaces behavior currently provided by POST direct_messages/new. Requires a JSON POST body and Content-Type header to be set to application/json. Setting Content-Length may also be required if it is not automatically. # Direct Message Rate Limiting When a message is received from a user you may send up to 5 messages in response within a 24 hour window. Each message received resets the 24 hour window and the 5 allotted messages. Sending a 6th message within a 24 hour window or sending a message outside of a 24 hour window will count towards rate-limiting. This behavior only applies when using the POST direct_messages/events/new endpoint. */ public func postDirectMessage(to recipientUserId: String, message: String, success: SuccessHandler? = nil, failure: FailureHandler? = nil) { let path = "direct_messages/events/new.json" var parameters: [String: Any] = [:] parameters[Swifter.DataParameters.jsonDataKey] = "json-body" parameters["json-body"] = [ "event": [ "type": "message_create", "message_create": [ "target": [ "recipient_id": recipientUserId ], "message_data": ["text": message ] ] ] ] self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure) } }
mit
1efbb77777b8d407afbdfa71d7999d8e
38.767857
396
0.714863
4.012613
false
false
false
false
WebberLai/WLComics
WLComics/View Controllers/Left View Controllers/EpisodeDetailViewController.swift
1
5450
// // EpisodeDetailViewController.swift // WLComics // // Created by Webber Lai on 2017/7/28. // Copyright © 2017年 webberlai. All rights reserved. // import UIKit import Swift8ComicSDK import Kingfisher import QuickLook class EpisodeDetailViewController: UIViewController { var currentEpisode : Episode! var allEpisodes = Array<Any>() as! [Episode] var detailViewController: DetailViewController? = nil var pages = Array<String>() var episodeIndex : Int = 0 @IBOutlet weak var tableView : UITableView! override func viewDidLoad() { super.viewDidLoad() if let split = splitViewController { let controllers = split.viewControllers detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController detailViewController?.imgSlider.currentIndex = 0 detailViewController?.delegate = self } WLComics.sharedInstance().loadEpisodeDetail(self.currentEpisode, onLoadDetail: { (episode) in episode.setUpPages() self.pages = episode.getImageUrlList() self.detailViewController?.setEpisodeUrl(episode.getUrl()) self.detailViewController?.updateImages(imgs: self.pages) DispatchQueue.main.async { self.tableView.reloadData() } }) self.tableView.tableHeaderView = nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension EpisodeDetailViewController : UITableViewDataSource , UITableViewDelegate,DetailViewControllerDelegate{ func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return pages.count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat{ return 116.0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "Cell"); cell.textLabel?.text = String("P" + "\(indexPath.row + 1)") let url = URL(string:pages[indexPath.row]) cell.imageView!.kf.setImage(with: url, placeholder: Image.init(named:"comic_place_holder"), options: [.transition(ImageTransition.fade(1)),.requestModifier(WLComics.sharedInstance().buildDownloadEpisodeHeader(currentEpisode.getUrl()))], progressBlock: { receivedSize, totalSize in }, completionHandler: { image, error, cacheType, imageURL in self.detailViewController?.imgSlider.imageViewArray[indexPath.row].image = image }) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { detailViewController?.imgSlider.adjustContentOffsetFor(index: indexPath.row, offsetIndex: indexPath.row, animated: true) } func sliderImageTapped(index: Int) { tableView.selectRow(at: IndexPath.init(row: index, section: 0), animated: true, scrollPosition: .none) } func showNextEpisode() { if episodeIndex < allEpisodes.count-1 { episodeIndex += 1 self.currentEpisode = self.allEpisodes[episodeIndex] detailViewController?.imgSlider.currentIndex = 0 WLComics.sharedInstance().loadEpisodeDetail(self.currentEpisode, onLoadDetail: { (episode) in episode.setUpPages() self.pages = episode.getImageUrlList() DispatchQueue.main.async { self.tableView.reloadData() self.title = self.currentEpisode.getName() self.detailViewController?.setEpisodeUrl(episode.getUrl()) self.detailViewController?.updateImages(imgs: self.pages) } }) } } func showPreviousEpisode() { if episodeIndex > 0{ episodeIndex -= 1 self.currentEpisode = self.allEpisodes[episodeIndex] detailViewController?.imgSlider.currentIndex = 0 WLComics.sharedInstance().loadEpisodeDetail(self.currentEpisode, onLoadDetail: { (episode) in episode.setUpPages() self.pages = episode.getImageUrlList() DispatchQueue.main.async { self.tableView.reloadData() self.title = self.currentEpisode.getName() self.detailViewController?.setEpisodeUrl(episode.getUrl()) self.detailViewController?.updateImages(imgs: self.pages) } }) } } }
mit
271cebba9b571424fc8bfdab7b05cf58
37.907143
180
0.626583
5.518744
false
false
false
false
codepgq/WeiBoDemo
PQWeiboDemo/PQWeiboDemo/classes/CenterAdd 添加/controller/PQComposeTextViewController.swift
1
6468
// // PQComposeTextViewController.swift // PQWeiboDemo // // Created by Mac on 16/10/18. // Copyright © 2016年 ios. All rights reserved. // import UIKit import SVProgressHUD class PQComposeTextViewController: UIViewController { //toolBar 高度约束 var toolBarHeightCons : NSLayoutConstraint? //表情键盘 lazy var emoticon : EmojiController = EmojiController { (emoticon : Emoticon) -> () in self.textView.insertEmoticon(emoticon : emoticon) } //表情键盘显示标志位 var isShowEmoticon : Bool = false override func viewDidLoad() { super.viewDidLoad() setNav() setupUI() //监听键盘弹出frame发生改变通知 NotificationCenter.default.addObserver(self, selector: #selector(PQComposeTextViewController.keyboardSizeValueChanged(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) textView.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) textView.resignFirstResponder() } //键盘通知 @objc private func keyboardSizeValueChanged(noti : Notification){ // print(noti.userInfo!) let keyPoint : CGPoint = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect).origin toolBarHeightCons?.constant = -(UIScreen.main.bounds.height - keyPoint.y) // print("-------------\(toolBarHeightCons)") view.layoutIfNeeded() // 3.更新界面 let duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber /* 工具条回弹是因为执行了两次动画, 而系统自带的键盘的动画节奏(曲线) 7 7在apple API中并没有提供给我们, 但是我们可以使用 7这种节奏有一个特点: 如果连续执行两次动画, 不管上一次有没有执行完毕, 都会立刻执行下一次 也就是说上一次可能会被忽略 如果将动画节奏设置为7, 那么动画的时长无论如何都会自动修改为0.5 UIView动画的本质是核心动画, 所以可以给核心动画设置动画节奏 */ // 1.取出键盘的动画节奏 let curve = noti.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber UIView.animate(withDuration: duration.doubleValue) { () -> Void in // 2.设置动画节奏 UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve.intValue)!) self.view.layoutIfNeeded() } // let anim = toolbar.layer.animation(forKey: "position") // print("duration = \(anim?.duration)") } private func setupUI(){ view.addSubview(textView) view.addSubview(toolbar) toolbar.toolDelegate = self textView.pq_fill(referView: view) placeholderLabel.pq_AlignInner(type: .TopLeft, referView: textView, size: nil ,offset: CGPoint(x: 5, y: 8)) let cons = toolbar.pq_AlignInner(type: pq_AlignType.BottomLeft, referView: view, size: CGSize(width: UIScreen.main.bounds.width, height: 49)) //获取到高度约束 toolBarHeightCons = toolbar.pq_ConstraintBottom(constraintsList: cons) navigationItem.rightBarButtonItem?.isEnabled = false } private func setNav(){ navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.plain, target: self, action: #selector(closeVC)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: .plain, target: self, action: #selector(sendStatus)) navigationItem.titleView = composeTitleView } //取消 @objc private func closeVC(){ gotoHomeVC() } private func gotoHomeVC(){ dismiss(animated: true, completion: nil) } //发送 @objc private func sendStatus(){ let url = "2/statuses/update.json" let text = textView.getRequestStr() let params = ["access_token":PQOauthInfo.loadAccoutInfo()?.access_token,"status":text] PQNetWorkManager.shareNetWorkManager().post(url, parameters: params, progress: nil, success: { (_, JSON) in SVProgressHUD.showSuccess(withStatus: "发送成功") self.gotoHomeVC() }) { (_, error) in print("微博发送失败\n\(error)") SVProgressHUD.showError(withStatus: "发送失败") } } //method // mark - 懒加载 //标题 private lazy var composeTitleView : PQComposeTitleView = PQComposeTitleView() //工具条 private lazy var toolbar : PQComposeToolView = PQComposeToolView(frame: CGRect.zero) //textView lazy var textView : UITextView = { let text = UITextView(frame: CGRect.zero) text.delegate = self text.alwaysBounceVertical = true text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.onDrag text.addSubview(self.placeholderLabel) return text }() //placeholder lazy var placeholderLabel : UILabel = { let label = UILabel.createLabelWithFontSize(fontSize: 13, textColor: UIColor.lightGray) label.text = "分享新鲜事…" return label }() } extension PQComposeTextViewController : UITextViewDelegate,PQComposeToolViewDelegate{ func textViewDidChange(_ textView: UITextView){ placeholderLabel.isHidden = textView.hasText navigationItem.rightBarButtonItem?.isEnabled = textView.hasText } //选择图片 func toolDidSelectedShiosePic(){ } //@ func toolDidSelectedAtSomeOne(){ } //关于话题 func toolDidSelectedAboutTalk(){ } //表情键盘 func toolDidSelectedChangeToEmoticon(){ // 0 取反标志位 isShowEmoticon = !isShowEmoticon // 1、关闭键盘 textView.resignFirstResponder() // 2、设置键盘的inputView textView.inputView = isShowEmoticon ? emoticon.view : nil // 3、显示键盘 textView.becomeFirstResponder() } //加号 func toolDidSelectedAddOhter(){ } }
mit
5726d1b141a4292af8c900848b79ccd8
30.875676
200
0.632186
4.680159
false
false
false
false
Paladinfeng/Weibo-Swift
Weibo/Weibo/Classes/ViewModel/PFStatusListViewModel.swift
1
2010
// // PFStatusListViewModel.swift // Weibo // // Created by Paladinfeng on 15/12/11. // Copyright © 2015年 Paladinfeng. All rights reserved. // //建立这个ViewModel是为了处理HomeView的数据逻辑 import UIKit class PFStatusListViewModel: NSObject { var statusList: [PFStatusViewModel]? } extension PFStatusListViewModel { func loadData(isPullUp isPullUp: Bool, complete:(count: Int,isSuccess: Bool)->()) { var maxid = isPullUp == true ? (statusList?.last?.status?.id ?? 0) : 0 if maxid > 0 { maxid -= 1 } let sinceid = isPullUp == true ? 0 : statusList?.first?.status?.id ?? 0 HMNetworkTools.shareTools.loadHomeData(maxid: maxid, sinceid: sinceid) { (response, error) -> () in if error != nil { print(error) complete(count: 0, isSuccess: false) return } if let result = response as? [String: AnyObject] { if let statusDict = result["statuses"] as? [[String: AnyObject]] { var tempArray = [PFStatusViewModel]() for value in statusDict { let status = PFStatus(dict: value) tempArray.append(PFStatusViewModel(status: status)) } print("本次加载\(tempArray.count)条数据") if self.statusList == nil{ self.statusList = [PFStatusViewModel]() } if isPullUp { self.statusList = self.statusList! + tempArray }else { self.statusList = tempArray + self.statusList! } complete(count:tempArray.count ,isSuccess: true) } } } } }
mit
1b04161140b31d813ac40477f494dfc5
29.71875
107
0.476845
5.198413
false
false
false
false
haskellswift/swift-package-manager
Sources/Basic/TemporaryFile.swift
1
8444
/* This source file is part of the Swift.org open source project Copyright 2016 Apple Inc. and the Swift project authors Licensed under Apache License v2.0 with Runtime Library Exception See http://swift.org/LICENSE.txt for license information See http://swift.org/CONTRIBUTORS.txt for Swift project authors */ import libc import func POSIX.getenv import class Foundation.FileHandle import class Foundation.FileManager public enum TempFileError: Swift.Error { /// Could not create a unique temporary filename. case couldNotCreateUniqueName /// Some error thrown defined by posix's open(). // FIXME: This should be factored out into a open error enum. case other(Int32) } private extension TempFileError { init(errno: Int32) { switch errno { case libc.EEXIST: self = .couldNotCreateUniqueName default: self = .other(errno) } } } /// Determines the directory in which the temporary file should be created. Also makes /// sure the returning path has a trailing forward slash. /// /// - Parameters: /// - dir: If present this will be the temporary directory. /// /// - Returns: Path to directory in which temporary file should be created. private func determineTempDirectory(_ dir: AbsolutePath? = nil) -> AbsolutePath { // FIXME: Add other platform specific locations. let tmpDir = dir ?? cachedTempDirectory // FIXME: This is a runtime condition, so it should throw and not crash. precondition(localFileSystem.isDirectory(tmpDir)) return tmpDir } /// Returns temporary directory location by searching relevant env variables. /// Evaluates once per execution. private var cachedTempDirectory: AbsolutePath = { return AbsolutePath(getenv("TMPDIR") ?? getenv("TEMP") ?? getenv("TMP") ?? "/tmp/") }() /// This class is basically a wrapper over posix's mkstemps() function to creates disposable files. /// The file is deleted as soon as the object of this class is deallocated. public final class TemporaryFile { /// If specified during init, the temporary file name begins with this prefix. let prefix: String /// If specified during init, the temporary file name ends with this suffix. let suffix: String /// The directory in which the temporary file is created. public let dir: AbsolutePath /// The full path of the temporary file. For safety file operations should be done via the fileHandle instead of using this path. public let path: AbsolutePath /// The file descriptor of the temporary file. It is used to create NSFileHandle which is exposed to clients. private let fd: Int32 /// FileHandle of the temporary file, can be used to read/write data. public let fileHandle: FileHandle /// Creates an instance of Temporary file. The temporary file will live on disk until the instance /// goes out of scope. /// /// - Parameters: /// - dir: If specified the temporary file will be created in this directory otherwise environment variables /// TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env variables are /// set, dir will be set to `/tmp/`. /// - prefix: The prefix to the temporary file name. /// - suffix: The suffix to the temporary file name. /// /// - Throws: TempFileError public init(dir: AbsolutePath? = nil, prefix: String = "TemporaryFile", suffix: String = "") throws { self.suffix = suffix self.prefix = prefix // Determine in which directory to create the temporary file. self.dir = determineTempDirectory(dir) // Construct path to the temporary file. let path = self.dir.appending(RelativePath(prefix + ".XXXXXX" + suffix)) // Convert path to a C style string terminating with null char to be an valid input // to mkstemps method. The XXXXXX in this string will be replaced by a random string // which will be the actual path to the temporary file. var template = [UInt8](path.asString.utf8).map{ Int8($0) } + [Int8(0)] fd = libc.mkstemps(&template, Int32(suffix.utf8.count)) // If mkstemps failed then throw error. if fd == -1 { throw TempFileError(errno: errno) } self.path = AbsolutePath(String(cString: template)) fileHandle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) } /// Remove the temporary file before deallocating. deinit { unlink(path.asString) } } extension TemporaryFile: CustomStringConvertible { public var description: String { return "<TemporaryFile: \(path)>" } } /// Contains the error which can be thrown while creating a directory using POSIX's mkdir. // // FIXME: This isn't right place to declare this, probably POSIX or merge with FileSystemError? public enum MakeDirectoryError: Swift.Error { /// The given path already exists as a directory, file or symbolic link. case pathExists /// The path provided was too long. case pathTooLong /// Process does not have permissions to create directory. /// Note: Includes read-only filesystems or if file system does not support directory creation. case permissionDenied /// The path provided is unresolvable because it has too many symbolic links or a path component is invalid. case unresolvablePathComponent /// Exceeded user quota or kernel is out of memory. case outOfMemory /// All other system errors with their value. case other(Int32) } private extension MakeDirectoryError { init(errno: Int32) { switch errno { case libc.EEXIST: self = .pathExists case libc.ENAMETOOLONG: self = .pathTooLong case libc.EACCES, libc.EFAULT, libc.EPERM, libc.EROFS: self = .permissionDenied case libc.ELOOP, libc.ENOENT, libc.ENOTDIR: self = .unresolvablePathComponent case libc.ENOMEM, libc.EDQUOT: self = .outOfMemory default: self = .other(errno) } } } /// A class to create disposable directories using POSIX's mkdtemp() method. public final class TemporaryDirectory { /// If specified during init, the temporary directory name begins with this prefix. let prefix: String /// The full path of the temporary directory. public let path: AbsolutePath /// If true, try to remove the whole directory tree before deallocating. let removeTreeOnDeinit: Bool /// Creates a temporary directory which is automatically removed when the object of this class goes out of scope. /// /// - Parameters: /// - dir: If specified the temporary directory will be created in this directory otherwise environment variables /// TMPDIR, TEMP and TMP will be checked for a value (in that order). If none of the env variables are /// set, dir will be set to `/tmp/`. /// - prefix: The prefix to the temporary file name. /// - removeTreeOnDeinit: If enabled try to delete the whole directory tree otherwise remove only if its empty. /// /// - Throws: MakeDirectoryError public init(dir: AbsolutePath? = nil, prefix: String = "TemporaryDirectory", removeTreeOnDeinit: Bool = false) throws { self.removeTreeOnDeinit = removeTreeOnDeinit self.prefix = prefix // Construct path to the temporary directory. let path = determineTempDirectory(dir).appending(RelativePath(prefix + ".XXXXXX")) // Convert path to a C style string terminating with null char to be an valid input // to mkdtemp method. The XXXXXX in this string will be replaced by a random string // which will be the actual path to the temporary directory. var template = [UInt8](path.asString.utf8).map{ Int8($0) } + [Int8(0)] if libc.mkdtemp(&template) == nil { throw MakeDirectoryError(errno: errno) } self.path = AbsolutePath(String(cString: template)) } /// Remove the temporary file before deallocating. deinit { if removeTreeOnDeinit { let _ = try? FileManager.default.removeItem(atPath: path.asString) } else { rmdir(path.asString) } } } extension TemporaryDirectory: CustomStringConvertible { public var description: String { return "<TemporaryDirectory: \(path)>" } }
apache-2.0
dc9a0743f4d680ab5cc73cf90e9b9903
38.830189
133
0.67918
4.733184
false
false
false
false
MyHammer/MHAppIndexing
Pod/Classes/MHUserActivityManager.swift
1
5858
// // MHUserActivityManager.swift // Pods // // Created by Andre Hess on 17.02.16. // // import UIKit import CoreSpotlight import MobileCoreServices let userActivityActivationDelay = 2.0 /// Manager for indexing objects that confirm to protocol **MHUserActivityObject** @available(iOS 9.0, *) public class MHUserActivityManager: NSObject, NSUserActivityDelegate { /// Factory method returning a shared instance of MHUserActivityManager public static let sharedInstance = MHUserActivityManager() var activities: NSMutableArray var didStartMakingActivitiesCurrent = false override init() { self.activities = [] super.init() } /** Adding an object to search index - parameter searchObject: Object that confirms to protocol MHUserActivityObject */ public func addObjectToSearchIndex(searchObject: MHUserActivityObject) { let activityType = searchObject.mhDomainIdentifier + ":" + searchObject.mhUniqueIdentifier let userActivity = self.createUserActivity(activityType) userActivity.title = searchObject.mhTitle userActivity.userInfo = searchObject.mhUserInfo userActivity.eligibleForSearch = searchObject.mhEligibleForSearch userActivity.eligibleForPublicIndexing = searchObject.mhEligibleForPublicIndexing userActivity.eligibleForHandoff = searchObject.mhEligibleForHandoff userActivity.webpageURL = searchObject.mhWebpageURL if let expDate = searchObject.mhExpirationDate { userActivity.expirationDate = expDate } else { let dateNow: NSDate = NSDate() let timeInterval: NSTimeInterval = NSTimeInterval(60 * 60 * 24 * searchItemDaysTillExpiration) userActivity.expirationDate = dateNow.dateByAddingTimeInterval(timeInterval) } userActivity.delegate = self self.contentAttributeSetFromSearchObject(searchObject, completion: { (attributeSet:CSSearchableItemAttributeSet) in userActivity.contentAttributeSet = attributeSet self.makeActivityCurrent(userActivity) }) } func createUserActivity(activityType:String) -> NSUserActivity { return NSUserActivity(activityType: activityType) } func contentAttributeSetFromSearchObject(searchObject: MHUserActivityObject, completion: ((attributeSet:CSSearchableItemAttributeSet)->Void)?) { var attributes = searchObject.mhAttributeSet if attributes == nil { attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeImage as String) } attributes!.relatedUniqueIdentifier = searchObject.mhUniqueIdentifier attributes!.title = searchObject.mhTitle attributes!.contentDescription = searchObject.mhContentDescription attributes!.keywords = searchObject.mhKeywords self.loadImageFromImageInfo(searchObject.mhImageInfo, attributes: attributes!, completion: completion) } func loadImageFromImageInfo(imageInfo:MHImageInfo?, attributes:CSSearchableItemAttributeSet, completion:((attributeSet:CSSearchableItemAttributeSet)->Void)?) { if let info:MHImageInfo = imageInfo { if let assetFilename = info.assetImageName { if let image = UIImage(named: assetFilename) { let imageData = UIImagePNGRepresentation(image) attributes.thumbnailData = imageData } completion?(attributeSet: attributes) } else if let imageFileName = NSBundle.mainBundle().pathForResource(info.bundleImageName, ofType: info.bundleImageType) { attributes.thumbnailURL = NSURL.fileURLWithPath(imageFileName) completion?(attributeSet: attributes) } else if let imageURL = info.imageURL { UIImage.loadImageAsyncFromURL(imageURL, completion: { (result:UIImage?) in if let image = result { attributes.thumbnailData = UIImagePNGRepresentation(image) } completion?(attributeSet: attributes) }) } else { completion?(attributeSet: attributes) } } else { completion?(attributeSet: attributes) } } func makeActivityCurrent(activity: NSUserActivity) { self.activities.addObject(activity) if (!self.didStartMakingActivitiesCurrent) { self.didStartMakingActivitiesCurrent = true dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(userActivityActivationDelay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.makeFirstActivityCurrent() } } } func makeFirstActivityCurrent() { let firstActivity = self.activities.firstObject firstActivity?.becomeCurrent() if let activityTitle = firstActivity?.mhTitle { NSLog("UserActivity will become current with title: " + activityTitle) } else { NSLog("UserActivity will become current") } } // MARK: - NSUserActivityDelegate methods /** Make next activity to current activity to add it to search index - parameter userActivity: Already indexed activity */ public func userActivityWillSave(userActivity: NSUserActivity) { if let activityTitle = userActivity.title { NSLog("UserActivity will save with title: " + activityTitle) } else { NSLog("UserActivity will save") } if self.activities.count > 0 { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(userActivityActivationDelay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in self.activities.removeObject(userActivity) if self.activities.count > 0 { self.makeFirstActivityCurrent() } else { self.didStartMakingActivitiesCurrent = false } } } else { self.didStartMakingActivitiesCurrent = false } } }
apache-2.0
9e95a42114bdf8c6430b76cff8336400
38.053333
163
0.701093
5.207111
false
false
false
false
broomburgo/SignalArchitecture
SignalArchitectureTests/Emitter+SignalTests.swift
1
6192
import XCTest @testable import SignalArchitecture class Emitter_SignalTests: XCTestCase { var intEmitter = Emitter<Int>(executionQueue: Queue.main) var voidEmitter = Emitter<Void>(executionQueue: Queue.main) override func setUp() { intEmitter = Emitter<Int>(executionQueue: Queue.main) voidEmitter = Emitter<Void>(executionQueue: Queue.main) } func testObserveAndEmit() { let expectedValue = 4 let willObserveSignal = expectationWithDescription("willObserveSignal") intEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue) willObserveSignal.fulfill() return .Continue } intEmitter.emit(expectedValue) waitForExpectationsWithTimeout(1, handler: nil) } func testEmitAndObserveTwice() { let expectedValue = 4 var hasObservedOnce = false let willObserveSignal1 = expectationWithDescription("willObserveSignal1") let willObserveSignal2 = expectationWithDescription("willObserveSignal2") intEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue) if hasObservedOnce { willObserveSignal2.fulfill() } else { willObserveSignal1.fulfill() hasObservedOnce = true } return .Continue } intEmitter.emit(expectedValue) intEmitter.emit(expectedValue) waitForExpectationsWithTimeout(1, handler: nil) } func testEmitTwiceAndObserveOnce() { let expectedValue = 4 var hasObservedOnce = false let willObserveSignal = expectationWithDescription("willObserveSignal") intEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue) XCTAssertFalse(hasObservedOnce) willObserveSignal.fulfill() hasObservedOnce = true return .Stop } intEmitter.emit(expectedValue) intEmitter.emit(expectedValue) waitForExpectationsWithTimeout(1, handler: nil) } func testObserveIsAsyncOnMain() { var shouldBe5andThen4 = 5 let willObserve = expectationWithDescription("willObserve") voidEmitter.signal.observe { shouldBe5andThen4 = 4 willObserve.fulfill() return .Continue } XCTAssertEqual(shouldBe5andThen4, 5) voidEmitter.emit() XCTAssertEqual(shouldBe5andThen4, 5) let willExecuteAsync = expectationWithDescription("willExecuteAsync") Queue.main.after(1) { XCTAssertEqual(shouldBe5andThen4, 4) willExecuteAsync.fulfill() } waitForExpectationsWithTimeout(2, handler: nil) } func testMultipleSignalsAllContinue() { let expectedValue1 = 9 let expectedValue2 = 13 var hasObservedOnce1 = false let willObserve1_1 = expectationWithDescription("willObserve1_1") let willObserve1_2 = expectationWithDescription("willObserve1_2") intEmitter.signal.observe { value in if hasObservedOnce1 { XCTAssertEqual(value, expectedValue2) willObserve1_2.fulfill() } else { hasObservedOnce1 = true XCTAssertEqual(value, expectedValue1) willObserve1_1.fulfill() } return .Continue } var hasObservedOnce2 = false let willObserve2_1 = expectationWithDescription("willObserve2_1") let willObserve2_2 = expectationWithDescription("willObserve2_2") intEmitter.signal.observe { value in if hasObservedOnce2 { XCTAssertEqual(value, expectedValue2) willObserve2_2.fulfill() } else { hasObservedOnce2 = true XCTAssertEqual(value, expectedValue1) willObserve2_1.fulfill() } return .Continue } intEmitter.emit(expectedValue1) intEmitter.emit(expectedValue2) waitForExpectationsWithTimeout(1, handler: nil) } func testMultipleSignalsSomeContinueSomeStop() { let expectedValue1 = 9 let expectedValue2 = 13 let willObserve1_1 = expectationWithDescription("willObserve1_1") intEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue1) willObserve1_1.fulfill() return .Stop } var hasObservedOnce2 = false let willObserve2_1 = expectationWithDescription("willObserve2_1") let willObserve2_2 = expectationWithDescription("willObserve2_2") intEmitter.signal.observe { value in if hasObservedOnce2 { XCTAssertEqual(value, expectedValue2) willObserve2_2.fulfill() } else { hasObservedOnce2 = true XCTAssertEqual(value, expectedValue1) willObserve2_1.fulfill() } return .Continue } intEmitter.emit(expectedValue1) intEmitter.emit(expectedValue2) waitForExpectationsWithTimeout(1, handler: nil) } func testObserveAndEmitBackground() { let backgroundEmitter = Emitter<Int>(executionQueue: Queue.background) let expectedValue = 4 let willObserveSignal = expectationWithDescription("willObserveSignal") backgroundEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue) willObserveSignal.fulfill() return .Continue } backgroundEmitter.emit(expectedValue) waitForExpectationsWithTimeout(1, handler: nil) } func testMultipleSignalsSomeContinueSomeStopBackground() { let backgroundIntEmitter = Emitter<Int>(executionQueue: Queue.background) let expectedValue1 = 9 let expectedValue2 = 13 let willObserve1_1 = expectationWithDescription("willObserve1_1") backgroundIntEmitter.signal.observe { value in XCTAssertEqual(value, expectedValue1) willObserve1_1.fulfill() return .Stop } var hasObservedOnce2 = false let willObserve2_1 = expectationWithDescription("willObserve2_1") let willObserve2_2 = expectationWithDescription("willObserve2_2") backgroundIntEmitter.signal.observe { value in if hasObservedOnce2 { XCTAssertEqual(value, expectedValue2) willObserve2_2.fulfill() } else { hasObservedOnce2 = true XCTAssertEqual(value, expectedValue1) willObserve2_1.fulfill() } return .Continue } backgroundIntEmitter.emit(expectedValue1) backgroundIntEmitter.emit(expectedValue2) waitForExpectationsWithTimeout(1, handler: nil) } }
mit
9ad51c78f63ee37864bc8ddf4d96baac
27.273973
77
0.708818
5.108911
false
true
false
false
xiwang126/BeeHive-swift
BeeHive-swift/Classes/BeeHive.swift
1
2020
// // Created by UgCode on 2017/3/13. // import Foundation public class BeeHive { public static let shared = BeeHive() //save application global context private let _onceToken = NSUUID().uuidString public var context: BHContext { didSet { DispatchQueue.once(token: _onceToken) { loadStaticModules() loadStaticServices() } } } public var isEnableException: Bool = false /// 必须在给context赋值之前注册要动态注册的module public static func registerDynamicModule(_ moduleClass: AnyClass) { BHModuleManager.shared.registerDynamicModule(moduleClass) } public static func triggerCustomEvent(_ eventType: Int) { if eventType > 1000 { return } BHModuleManager.shared.triggerEvent(BHModuleEventType(rawValue: eventType)!) } init() { self.context = BHContext.shared } public func createService(_ proto: ServiceName) throws -> AnyObject { return try BHServiceManager.shared.create(service: proto) } //Registration is recommended to use a static way public func registerService(_ proto: ServiceName, service serviceClass: AnyClass) { BHServiceManager.shared.register(service: proto, implClass: serviceClass) } private func loadStaticModules() { BHModuleManager.shared.loadLocalModules() BHModuleManager.shared.registedAllModules() } private func loadStaticServices() { BHServiceManager.shared.isEnableException = isEnableException BHServiceManager.shared.registerLocalServices() } } extension DispatchQueue { private static var _onceTracker = [String]() class func once(token: String, block: (Void)->Void) { objc_sync_enter(self); defer { objc_sync_exit(self) } if _onceTracker.contains(token) { return } _onceTracker.append(token) block() } }
mit
dd4cd116cf0891eb0b820897ab1cac6f
25.864865
87
0.642857
4.7109
false
false
false
false
adrfer/swift
test/SILGen/enum_derived.swift
12
1835
// RUN: rm -rf %t // RUN: mkdir %t // RUN: %target-swift-frontend -emit-module -module-name def_enum -o %t %S/Inputs/def_enum.swift // RUN: %target-swift-frontend -I %t -O -primary-file %s -emit-ir | FileCheck -check-prefix=CHECK -check-prefix=CHECK-NORMAL %s // RUN: %target-swift-frontend -I %t -O -primary-file %s -enable-testing -emit-ir | FileCheck -check-prefix=CHECK -check-prefix=CHECK-TESTABLE %s import def_enum // Check if the hashValue and == for an enum (without payload) are generated and // check if that functions are compiled in an optimal way. enum E { case E0 case E1 case E2 case E3 } // Check if the hashValue getter can be compiled to a simple zext instruction. // CHECK-NORMAL-LABEL:define hidden i{{.*}} @_TFO12enum_derived1Eg9hashValueSi(i2) // CHECK-TESTABLE-LABEL:define i{{.*}} @_TFO12enum_derived1Eg9hashValueSi(i2) // CHECK: %1 = zext i2 %0 to i{{.*}} // CHECK: ret i{{.*}} %1 // Check if the == comparison can be compiled to a simple icmp instruction. // CHECK-NORMAL-LABEL:define hidden i1 @_TZF12enum_derivedoi2eeFTOS_1ES0__Sb(i2, i2) // CHECK-TESTABLE-LABEL:define i1 @_TZF12enum_derivedoi2eeFTOS_1ES0__Sb(i2, i2) // CHECK: %2 = icmp eq i2 %0, %1 // CHECK: ret i1 %2 // Derived conformances from extensions // The actual enums are in Inputs/def_enum.swift extension def_enum.TrafficLight : ErrorType {} // CHECK-LABEL: define i{{32|64}} @_TFE12enum_derivedO8def_enum12TrafficLightg5_codeSi(i2) extension def_enum.Term : ErrorType {} // CHECK-NORMAL-LABEL: define hidden i64 @_TFO12enum_derived7Phantomg8rawValueVs5Int64(i1, %swift.type* nocapture readnone %T) #1 // CHECK-TESTABLE-LABEL: define i64 @_TFO12enum_derived7Phantomg8rawValueVs5Int64(i1, %swift.type* nocapture readnone %T) #1 enum Phantom<T> : Int64 { case Up case Down } extension Phantom : RawRepresentable {}
apache-2.0
f05249c3494dbc7b670d6b68d3e1080c
34.980392
145
0.719346
3.018092
false
true
false
false
artsy/eigen
ios/Artsy/View_Controllers/Live_Auctions/LiveAuctionSaleLotsDataSource.swift
1
1824
import UIKit protocol LiveAuctionSaleLotsDataSourceScrollableDelgate: AnyObject { func registerForScrollingState(_ viewController: LiveAuctionLotViewController) } class LiveAuctionSaleLotsDataSource: NSObject, UIPageViewControllerDataSource { var salesPerson: LiveAuctionsSalesPersonType! weak var scrollingDelegate: LiveAuctionSaleLotsDataSourceScrollableDelgate? func liveAuctionPreviewViewControllerForIndex(_ index: Int) -> LiveAuctionLotViewController? { guard 0..<salesPerson.lotCount ~= index else { return nil } let lotViewModel = salesPerson.lotViewModelForIndex(index) let auctionVC = LiveAuctionLotViewController( index: index, lotViewModel: lotViewModel, salesPerson: salesPerson ) scrollingDelegate?.registerForScrollingState(auctionVC) return auctionVC } func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { if salesPerson.lotCount == 1 { return nil } guard let viewController = viewController as? LiveAuctionLotViewController else { return nil } var newIndex = viewController.index - 1 if newIndex < 0 { newIndex = salesPerson.lotCount - 1 } return liveAuctionPreviewViewControllerForIndex(newIndex) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { if salesPerson.lotCount == 1 { return nil } guard let viewController = viewController as? LiveAuctionLotViewController else { return nil } let newIndex = (viewController.index + 1) % salesPerson.lotCount return liveAuctionPreviewViewControllerForIndex(newIndex) } }
mit
93ded8c60d1b8a52d6531f2871679139
42.428571
149
0.747259
6.100334
false
false
false
false
coderZsq/coderZsq.target.swift
StudyNotes/Swift Note/ObjC.io/Swift4/Functional/CoreGraphics.swift
1
8200
// // CoreGraphics.swift // Functional // // Created by 朱双泉 on 2018/5/18. // Copyright © 2018 Castie!. All rights reserved. // import CoreGraphics import UIKit class DrawView: UIView { override func draw(_ rect: CGRect) { // CoreGraphics.renderer.draw(in: rect) // UIGraphicsGetCurrentContext()?.draw(CoreGraphics.example1, in: rect) // UIGraphicsGetCurrentContext()?.draw(CoreGraphics.example2, in: rect) UIGraphicsGetCurrentContext()?.draw(barGraph( [("Moscow", 700), ("Shanghai", 1000), ("Istanbul", 900), ("Berlin", 200), ("New York", 500)] ), in: rect) } } class CoreGraphics { static var renderer: UIImage { let bounds = CGRect(origin: .zero, size: CGSize(width: 300, height: 200)) let renderer = UIGraphicsImageRenderer(bounds: bounds) return renderer.image { context in UIColor.blue.setFill() context.fill(CGRect(x: 0.0, y: 37.5, width: 75.0, height: 75.0)) UIColor.red.setFill() context.fill(CGRect(x: 75.0, y: 0.0, width: 150.0, height: 150.0)) UIColor.green.setFill() context.cgContext.fillEllipse(in: CGRect(x: 225.0, y: 37.5, width: 75.0, height: 75.0)) } } } enum Primitive { case ellipase case rectangle case text(String) } indirect enum Diagram { case primitive(CGSize, Primitive) case beside(Diagram, Diagram) case below(Diagram, Diagram) case attributed(Attribute, Diagram) case align(CGPoint, Diagram) } enum Attribute { case fillColor(UIColor) } extension Diagram { var size: CGSize { switch self { case .primitive(let size, _): return size case .attributed(_, let x): return x.size case let .beside(l, r): let sizeL = l.size let sizeR = r.size return CGSize(width: sizeL.width + sizeR.width, height: max(sizeL.height, sizeR.height)) case let .below(l, r): return CGSize(width: max(l.size.width, r.size.width), height: l.size.height + r.size.height) case .align(_, let r): return r.size } } } func *(l: CGFloat, r: CGSize) -> CGSize { return CGSize(width: l * r.width, height: l * r.height) } func *(l: CGSize, r: CGSize) -> CGSize { return CGSize(width: l.width * r.width, height: l.height * r.height) } func -(l: CGSize, r: CGSize) -> CGSize { return CGSize(width: l.width - r.width, height: l.height - r.height) } func +(l: CGPoint, r: CGPoint) -> CGPoint { return CGPoint(x: l.x + r.x, y: l.y + r.y) } extension CGSize { var point: CGPoint { return CGPoint(x: self.width, y: self.height) } } extension CGPoint { var size: CGSize { return CGSize(width: x, height: y) } } extension CGSize { func fit(into rect: CGRect, alignment: CGPoint) -> CGRect { let scale = min(rect.width / width, rect.height / height) let targetSize = scale * self let spacerSize = alignment.size * (rect.size - targetSize) return CGRect(origin: rect.origin + spacerSize.point, size: targetSize) } } extension CoreGraphics { static func run() { let center = CGPoint(x: 0.5, y: 0.5) let target = CGRect(x: 0, y: 0, width: 200, height: 100) print(CGSize(width: 1,height: 1).fit(into: target, alignment: center)) let topLeft = CGPoint(x: 0, y: 0) print(CGSize(width: 1, height: 1).fit(into: target, alignment: topLeft)) } } extension CGContext { func draw(_ primitive: Primitive, in frame: CGRect) { switch primitive { case .rectangle: fill(frame) case .ellipase: fillEllipse(in: frame) case .text(let text): let font = UIFont.systemFont(ofSize: 12) let attributes = [NSAttributedStringKey.font : font] let attributedText = NSAttributedString(string: text, attributes: attributes) attributedText.draw(in: frame) } } } extension CGPoint { static let bottom = CGPoint(x: 0.5, y: 1) static let top = CGPoint(x: 0.5, y: 1) static let center = CGPoint(x: 0.5, y: 0.5) } extension CGRect { func split(ratio: CGFloat, edge: CGRectEdge) -> (CGRect, CGRect) { let length = edge.isHorizontal ? width : height return divided(atDistance: length * ratio, from: edge) } } extension CGRectEdge { var isHorizontal: Bool { return self == .maxXEdge || self == .minXEdge; } } extension CGContext { func draw(_ diagram: Diagram, in bounds: CGRect) { switch diagram { case let .primitive(size, primitive): let bounds = size.fit(into: bounds, alignment: .center) draw(primitive, in: bounds) case .align(let alignment, let diagram): let bounds = diagram.size.fit(into: bounds, alignment: alignment) draw(diagram, in: bounds) case let .beside(left, right): let (lBounds, rBounds) = bounds.split( ratio: left.size.width / diagram.size.width, edge: .minXEdge) draw(left, in: lBounds) draw(right, in: rBounds) case .below(let top, let bottom): let (tBounds, bBounds) = bounds.split(ratio: top.size.height / diagram.size.height, edge: .minYEdge) draw(top, in: tBounds) draw(bottom, in: bBounds) case let .attributed(.fillColor(color), diagram): saveGState() color.set() draw(diagram, in: bounds) restoreGState() } } } func rect(width: CGFloat, height: CGFloat) -> Diagram { return .primitive(CGSize(width: width, height: height), .rectangle) } func circle(diameter: CGFloat) -> Diagram { return .primitive(CGSize(width: diameter, height: diameter), .ellipase) } func text(_ theText: String, width: CGFloat, height: CGFloat) -> Diagram { return .primitive(CGSize(width: width, height: height), .text(theText)) } func square(side: CGFloat) -> Diagram { return rect(width: side, height: side) } precedencegroup VerticalCombination { associativity: left } infix operator ---: VerticalCombination func ---(l: Diagram, r: Diagram) -> Diagram { return .below(l, r) } precedencegroup HorizontalCombination { higherThan: VerticalCombination associativity: left } infix operator |||: HorizontalCombination func |||(l: Diagram, r: Diagram) -> Diagram { return .beside(l, r) } extension Diagram { func filled(_ color: UIColor) -> Diagram { return .attributed(.fillColor(color), self) } func aligned(to position: CGPoint) -> Diagram { return .align(position, self) } } extension Diagram { init() { self = rect(width: 0, height: 0) } } extension Sequence where Iterator.Element == Diagram { var hcat: Diagram { return reduce(Diagram(), |||) } } extension Sequence where Iterator.Element == CGFloat { var normalized: [CGFloat] { let maxVal = reduce(0, Swift.max) return map { $0 / maxVal } } } func barGraph(_ input: [(String, Double)]) -> Diagram { let values: [CGFloat] = input.map { CGFloat($0.1) } let bars = values.normalized.map { x in return rect(width: 1, height: 3 * x).filled(.black).aligned(to: .bottom) }.hcat let labels = input.map { label, _ in return text(label, width: 1, height: 0.3).aligned(to: .top) }.hcat return bars --- labels } extension CoreGraphics { static var example1: Diagram { let blueSquare = square(side: 1).filled(.blue) let redSquare = square(side: 2).filled(.red) let greenCircle = circle(diameter: 1).filled(.green) return blueSquare ||| redSquare ||| greenCircle } static var example2: Diagram { let blueSquare = square(side: 1).filled(.blue) let redSquare = square(side: 2).filled(.red) let greenCircle = circle(diameter: 1).filled(.green) let cyanCircle = circle(diameter: 1).filled(.cyan) return blueSquare ||| cyanCircle ||| redSquare ||| greenCircle } }
mit
71c791b171c7712d6e42bf3649bc311f
28.792727
112
0.605883
3.775576
false
false
false
false
KoCMoHaBTa/MHAppKit
MHAppKit/Extensions/UIKit/UIView/UIView+Inspectable.swift
1
991
// // UIView+Inspectable.swift // MHAppKit // // Created by Milen Halachev on 27.09.17. // Copyright © 2017 Milen Halachev. All rights reserved. // #if canImport(UIKit) && !os(watchOS) import Foundation import UIKit extension UIView { @IBInspectable open var cornerRadius: CGFloat { get { return self.layer.cornerRadius } set { self.layer.cornerRadius = newValue } } @IBInspectable open var maskToBounds: Bool { get { return self.layer.masksToBounds } set { self.layer.masksToBounds = newValue } } @IBInspectable open var borderWidth: CGFloat { get { return self.layer.borderWidth } set { self.layer.borderWidth = newValue } } @IBInspectable open var borderColor: UIColor? { get { return self.layer.borderColor == nil ? nil : UIColor(cgColor: self.layer.borderColor!) } set { self.layer.borderColor = newValue?.cgColor } } } #endif
mit
e12673894e3d0817b3c9bb63259ade57
24.384615
102
0.625253
4.439462
false
false
false
false
khizkhiz/swift
test/SILGen/witness_same_type.swift
8
1097
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s protocol Fooable { associatedtype Bar func foo<T: Fooable where T.Bar == Self.Bar>(x x: T) -> Self.Bar } struct X {} // Ensure that the protocol witness for requirements with same-type constraints // is set correctly. <rdar://problem/16369105> // CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17witness_same_type3FooS_7FooableS_FS1_3foo{{.*}} : $@convention(witness_method) <T where T : Fooable, T.Bar == X> (@in T, @in_guaranteed Foo) -> @out X struct Foo: Fooable { typealias Bar = X func foo<T: Fooable where T.Bar == X>(x x: T) -> X { return X() } } // rdar://problem/19049566 // CHECK-LABEL: sil [transparent] [thunk] @_TTWu0_Rxs8Sequence_zWx8Iterator7Element_rGV17witness_same_type14LazySequenceOfxq__S_S2_FS_12makeIterator public struct LazySequenceOf<SS : Sequence, A where SS.Iterator.Element == A> : Sequence { public func makeIterator() -> AnyIterator<A> { var opt: AnyIterator<A>? return opt! } public subscript(i : Int) -> A { get { var opt: A? return opt! } } }
apache-2.0
2cc6dcb6e25a7a32fef6cda123ad880c
32.242424
207
0.672744
3.235988
false
false
false
false
GMSLabs/Hyber-SDK-iOS
Example/Hyber/SettingsViewController.swift
1
1288
// // SettingsViewController.swift // Hyber // // Created by Taras Markevych on 5/25/17. // Copyright © 2017 Incuube. All rights reserved. // import UIKit class SettingsViewController: UIViewController { let def = UserDefaults.standard var newKey = "" @IBAction func saveAction(_ sender: Any) { newKey = apiKeyTextField.text! def.set(newKey, forKey: "apikey") def.synchronize() self.dismiss(animated: true) } @IBAction func cancelAction(_ sender: Any) { self.dismiss(animated: true) } @IBAction func resetAction(_ sender: Any) { def.removeObject(forKey: "apikey") def.synchronize() self.viewDidLoad() } @IBOutlet weak var apiKeyTextField: UITextField! @IBOutlet weak var fcmTokenLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() DispatchQueue.main.async { self.apiKeyTextField.text = gedApiKeyProd() if let defauls = self.def.object(forKey: "fcmToken") { self.fcmTokenLabel.text = defauls as? String } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
apache-2.0
79d16c9a0fb51ea156439588d3bd0379
25.8125
66
0.620824
4.453287
false
false
false
false
michael-lehew/swift-corelibs-foundation
Foundation/NSXMLParser.swift
1
40156
// This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // // It is necessary to explicitly cast strlen to UInt to match the type // of prefixLen because currently, strlen (and other functions that // rely on swift_ssize_t) use the machine word size (int on 32 bit and // long in on 64 bit). I've filed a bug at bugs.swift.org: // https://bugs.swift.org/browse/SR-314 #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif import CoreFoundation extension XMLParser { public enum ExternalEntityResolvingPolicy : UInt { case resolveExternalEntitiesNever // default case resolveExternalEntitiesNoNetwork case resolveExternalEntitiesSameOriginOnly //only applies to NSXMLParser instances initialized with -initWithContentsOfURL: case resolveExternalEntitiesAlways } } extension _CFXMLInterface { var parser: XMLParser { return unsafeBitCast(self, to: XMLParser.self) } } extension XMLParser { internal var interface: _CFXMLInterface { return unsafeBitCast(self, to: _CFXMLInterface.self) } } private func UTF8STRING(_ bytes: UnsafePointer<UInt8>) -> String? { // strlen operates on the wrong type, char*. We can't rebind the memory to a different type without knowing it's length, // but since we know strlen is in libc, its safe to directly bitcast the pointer without worrying about multiple accesses // of different types visible to the compiler. let len = strlen(unsafeBitCast(bytes, to: UnsafePointer<Int8>.self)) let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: bytes, count: Int(len))) return str } internal func _NSXMLParserCurrentParser() -> _CFXMLInterface? { if let parser = XMLParser.currentParser() { return parser.interface } else { return nil } } internal func _NSXMLParserExternalEntityWithURL(_ interface: _CFXMLInterface, urlStr: UnsafePointer<Int8>, identifier: UnsafePointer<Int8>, context: _CFXMLInterfaceParserContext, originalLoaderFunction: _CFXMLInterfaceExternalEntityLoader) -> _CFXMLInterfaceParserInput? { let parser = interface.parser let policy = parser.externalEntityResolvingPolicy var a: URL? if let allowedEntityURLs = parser.allowedExternalEntityURLs { if let url = URL(string: String(describing: urlStr)) { a = url if let scheme = url.scheme { if scheme == "file" { a = URL(fileURLWithPath: url.path) } } } if let url = a { let allowed = allowedEntityURLs.contains(url) if allowed || policy != .resolveExternalEntitiesSameOriginOnly { if allowed { return originalLoaderFunction(urlStr, identifier, context) } } } } switch policy { case .resolveExternalEntitiesSameOriginOnly: guard let url = parser._url else { break } if a == nil { a = URL(string: String(describing: urlStr)) } guard let aUrl = a else { break } var matches: Bool if let aHost = aUrl.host, let host = url.host { matches = host == aHost } else { return nil } if matches { if let aPort = aUrl.port, let port = url.port { matches = port == aPort } else { return nil } } if matches { if let aScheme = aUrl.scheme, let scheme = url.scheme { matches = scheme == aScheme } else { return nil } } if !matches { return nil } break case .resolveExternalEntitiesAlways: break case .resolveExternalEntitiesNever: return nil case .resolveExternalEntitiesNoNetwork: return _CFXMLInterfaceNoNetExternalEntityLoader(urlStr, identifier, context) } return originalLoaderFunction(urlStr, identifier, context) } internal func _NSXMLParserGetContext(_ ctx: _CFXMLInterface) -> _CFXMLInterfaceParserContext { return ctx.parser._parserContext! } internal func _NSXMLParserInternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2InternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _NSXMLParserIsStandalone(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceIsStandalone(ctx.parser._parserContext) } internal func _NSXMLParserHasInternalSubset(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasInternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserHasExternalSubset(_ ctx: _CFXMLInterface) -> Int32 { return _CFXMLInterfaceHasExternalSubset(ctx.parser._parserContext) } internal func _NSXMLParserGetEntity(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>) -> _CFXMLInterfaceEntity? { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) var entity = _CFXMLInterfaceGetPredefinedEntity(name) if entity == nil { entity = _CFXMLInterfaceSAX2GetEntity(context, name) } if entity == nil { if let delegate = parser.delegate { let entityName = UTF8STRING(name)! // if the systemID was valid, we would already have the correct entity (since we're loading external dtds) so this callback is a bit of a misnomer let result = delegate.parser(parser, resolveExternalEntityName: entityName, systemID: nil) if _CFXMLInterfaceHasDocument(context) != 0 { if let data = result { // unfortunately we can't add the entity to the doc to avoid further lookup since the delegate can change under us data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Void in _NSXMLParserCharacters(ctx, ch: bytes, len: Int32(data.count)) } } } } } return entity } internal func _NSXMLParserNotationDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let notationName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) delegate.parser(parser, foundNotationDeclarationWithName: notationName, publicID: publicIDString, systemID: systemIDString) } } internal func _NSXMLParserAttributeDecl(_ ctx: _CFXMLInterface, elem: UnsafePointer<UInt8>, fullname: UnsafePointer<UInt8>, type: Int32, def: Int32, defaultValue: UnsafePointer<UInt8>, tree: _CFXMLInterfaceEnumeration) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let elementString = UTF8STRING(elem)! let nameString = UTF8STRING(fullname)! let typeString = "" // FIXME! let defaultValueString = UTF8STRING(defaultValue) delegate.parser(parser, foundAttributeDeclarationWithName: nameString, forElement: elementString, type: typeString, defaultValue: defaultValueString) } // in a regular sax implementation tree is added to an attribute, which takes ownership of it; in our case we need to make sure to release it _CFXMLInterfaceFreeEnumeration(tree) } internal func _NSXMLParserElementDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, type: Int32, content: _CFXMLInterfaceElementContent) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let nameString = UTF8STRING(name)! let modelString = "" // FIXME! delegate.parser(parser, foundElementDeclarationWithName: nameString, model: modelString) } } internal func _NSXMLParserUnparsedEntityDecl(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, publicId: UnsafePointer<UInt8>, systemId: UnsafePointer<UInt8>, notationName: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let context = _NSXMLParserGetContext(ctx) // Add entities to the libxml2 doc so they'll resolve properly _CFXMLInterfaceSAX2UnparsedEntityDecl(context, name, publicId, systemId, notationName) if let delegate = parser.delegate { let declName = UTF8STRING(name)! let publicIDString = UTF8STRING(publicId) let systemIDString = UTF8STRING(systemId) let notationNameString = UTF8STRING(notationName) delegate.parser(parser, foundUnparsedEntityDeclarationWithName: declName, publicID: publicIDString, systemID: systemIDString, notationName: notationNameString) } } internal func _NSXMLParserStartDocument(_ ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidStartDocument(parser) } } internal func _NSXMLParserEndDocument(_ ctx: _CFXMLInterface) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parserDidEndDocument(parser) } } internal func _colonSeparatedStringFromPrefixAndSuffix(_ prefix: UnsafePointer<UInt8>, _ prefixlen: UInt, _ suffix: UnsafePointer<UInt8>, _ suffixLen: UInt) -> String { let prefixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: prefix, count: Int(prefixlen))) let suffixString = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: suffix, count: Int(suffixLen))) return "\(prefixString!):\(suffixString!)" } internal func _NSXMLParserStartElementNs(_ ctx: _CFXMLInterface, localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>, nb_namespaces: Int32, namespaces: UnsafeMutablePointer<UnsafePointer<UInt8>?>, nb_attributes: Int32, nb_defaulted: Int32, attributes: UnsafeMutablePointer<UnsafePointer<UInt8>?>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let reportNamespaces = parser.shouldReportNamespacePrefixes // Since strlen is in libc, it's safe to bitcast the UInt8 pointer argument to an Int8 (char *) pointer. let prefixLen = prefix != nil ? UInt(strlen(unsafeBitCast(prefix!, to: UnsafePointer<Int8>.self))) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let qualifiedNameString = prefixLen != 0 ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(unsafeBitCast(localname, to: UnsafePointer<Int8>.self)))) : localnameString let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nil var nsDict = [String:String]() var attrDict = [String:String]() if nb_attributes + nb_namespaces > 0 { for idx in stride(from: 0, to: Int(nb_namespaces) * 2, by: 2) { var namespaceNameString: String? var asAttrNamespaceNameString: String? if let ns = namespaces[idx] { if reportNamespaces { namespaceNameString = UTF8STRING(ns) } asAttrNamespaceNameString = _colonSeparatedStringFromPrefixAndSuffix("xmlns", 5, ns, UInt(strlen(unsafeBitCast(ns, to: UnsafePointer<Int8>.self)))) } else { namespaceNameString = "" asAttrNamespaceNameString = "xmlns" } let namespaceValueString = namespaces[idx + 1] != nil ? UTF8STRING(namespaces[idx + 1]!) : "" if reportNamespaces { if let k = namespaceNameString, let v = namespaceValueString { nsDict[k] = v } } if !reportQNameURI { if let k = asAttrNamespaceNameString, let v = namespaceValueString { attrDict[k] = v } } } } if reportNamespaces { parser._pushNamespaces(nsDict) } for idx in stride(from: 0, to: Int(nb_attributes) * 5, by: 5) { if attributes[idx] == nil { continue } var attributeQName: String let attrLocalName = attributes[idx]! let attrPrefix = attributes[idx + 1] // Since strlen is in libc, it's safe to bitcast the UInt8 pointer argument to an Int8 (char *) pointer. let attrPrefixLen = attrPrefix != nil ? strlen(unsafeBitCast(attrPrefix!, to: UnsafePointer<Int8>.self)) : 0 if attrPrefixLen != 0 { attributeQName = _colonSeparatedStringFromPrefixAndSuffix(attrPrefix!, UInt(attrPrefixLen), attrLocalName, UInt(strlen((unsafeBitCast(attrLocalName, to: UnsafePointer<Int8>.self))))) } else { attributeQName = UTF8STRING(attrLocalName)! } // idx+2 = URI, which we throw away // idx+3 = value, i+4 = endvalue // By using XML_PARSE_NOENT the attribute value string will already have entities resolved var attributeValue = "" if attributes[idx + 3] != nil && attributes[idx + 4] != nil { let numBytesWithoutTerminator = attributes[idx + 4]! - attributes[idx + 3]! let numBytesWithTerminator = numBytesWithoutTerminator + 1 if numBytesWithoutTerminator != 0 { var chars = [UInt8](repeating: 0, count: numBytesWithTerminator) attributeValue = chars.withUnsafeMutableBufferPointer({ (buffer: inout UnsafeMutableBufferPointer<UInt8>) -> String in // In Swift code, buffer is alwaus accessed as UInt8. // Since strncpy is in libc, it's safe to bitcast the UInt8 pointer arguments to an Int8 (char *) pointer. strncpy(unsafeBitCast(buffer.baseAddress!, to: UnsafeMutablePointer<Int8>.self), unsafeBitCast(attributes[idx + 3]!, to: UnsafePointer<Int8>.self), numBytesWithoutTerminator) //not strlcpy because attributes[i+3] is not Nul terminated return UTF8STRING(buffer.baseAddress!)! }) } attrDict[attributeQName] = attributeValue } } if let delegate = parser.delegate { if reportQNameURI { delegate.parser(parser, didStartElement: localnameString!, namespaceURI: (namespaceURIString != nil ? namespaceURIString : ""), qualifiedName: (qualifiedNameString != nil ? qualifiedNameString : ""), attributes: attrDict) } else { delegate.parser(parser, didStartElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil, attributes: attrDict) } } } internal func _NSXMLParserEndElementNs(_ ctx: _CFXMLInterface , localname: UnsafePointer<UInt8>, prefix: UnsafePointer<UInt8>?, URI: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser let reportQNameURI = parser.shouldProcessNamespaces let prefixLen = prefix != nil ? strlen(unsafeBitCast(prefix!, to: UnsafePointer<Int8>.self)) : 0 let localnameString = (prefixLen == 0 || reportQNameURI) ? UTF8STRING(localname) : nil let nilStr: String? = nil let qualifiedNameString = (prefixLen != 0) ? _colonSeparatedStringFromPrefixAndSuffix(prefix!, UInt(prefixLen), localname, UInt(strlen(unsafeBitCast(localname, to: UnsafePointer<Int8>.self)))) : nilStr let namespaceURIString = reportQNameURI ? UTF8STRING(URI) : nilStr if let delegate = parser.delegate { if reportQNameURI { // When reporting namespace info, the delegate parameters are not passed in nil delegate.parser(parser, didEndElement: localnameString!, namespaceURI: namespaceURIString == nil ? "" : namespaceURIString, qualifiedName: qualifiedNameString == nil ? "" : qualifiedNameString) } else { delegate.parser(parser, didEndElement: qualifiedNameString!, namespaceURI: nil, qualifiedName: nil) } } // Pop the last namespaces that were pushed (safe since XML is balanced) parser._popNamespaces() } internal func _NSXMLParserCharacters(_ ctx: _CFXMLInterface, ch: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser let context = parser._parserContext! if _CFXMLInterfaceInRecursiveState(context) != 0 { _CFXMLInterfaceResetRecursiveState(context) } else { if let delegate = parser.delegate { let str = String._fromCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: ch, count: Int(len))) delegate.parser(parser, foundCharacters: str!) } } } internal func _NSXMLParserProcessingInstruction(_ ctx: _CFXMLInterface, target: UnsafePointer<UInt8>, data: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let targetString = UTF8STRING(target)! let dataString = UTF8STRING(data) delegate.parser(parser, foundProcessingInstructionWithTarget: targetString, data: dataString) } } internal func _NSXMLParserCdataBlock(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>, len: Int32) -> Void { let parser = ctx.parser if let delegate = parser.delegate { delegate.parser(parser, foundCDATA: Data(bytes: value, count: Int(len))) } } internal func _NSXMLParserComment(_ ctx: _CFXMLInterface, value: UnsafePointer<UInt8>) -> Void { let parser = ctx.parser if let delegate = parser.delegate { let comment = UTF8STRING(value)! delegate.parser(parser, foundComment: comment) } } internal func _NSXMLParserExternalSubset(_ ctx: _CFXMLInterface, name: UnsafePointer<UInt8>, ExternalID: UnsafePointer<UInt8>, SystemID: UnsafePointer<UInt8>) -> Void { _CFXMLInterfaceSAX2ExternalSubset(ctx.parser._parserContext, name, ExternalID, SystemID) } internal func _structuredErrorFunc(_ interface: _CFXMLInterface, error: _CFXMLInterfaceError) { let err = _CFErrorCreateFromXMLInterface(error)._nsObject let parser = interface.parser parser._parserError = err if let delegate = parser.delegate { delegate.parser(parser, parseErrorOccurred: err) } } open class XMLParser : NSObject { private var _handler: _CFXMLInterfaceSAXHandler internal var _stream: InputStream? internal var _data: Data? internal var _chunkSize = Int(4096 * 32) // a suitably large number for a decent chunk size internal var _haveDetectedEncoding = false internal var _bomChunk: Data? fileprivate var _parserContext: _CFXMLInterfaceParserContext? internal var _delegateAborted = false internal var _url: URL? internal var _namespaces = [[String:String]]() // initializes the parser with the specified URL. public convenience init?(contentsOf url: URL) { if url.isFileURL { if let stream = InputStream(url: url) { self.init(stream: stream) _url = url } else { return nil } } else { do { let data = try Data(contentsOf: url) self.init(data: data) self._url = url } catch { return nil } } } // create the parser from data public init(data: Data) { _CFSetupXMLInterface() _data = data _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } deinit { _CFXMLInterfaceDestroySAXHandler(_handler) _CFXMLInterfaceDestroyContext(_parserContext) } //create a parser that incrementally pulls data from the specified stream and parses it. public init(stream: InputStream) { _CFSetupXMLInterface() _stream = stream _handler = _CFXMLInterfaceCreateSAXHandler() _parserContext = nil } open weak var delegate: XMLParserDelegate? open var shouldProcessNamespaces: Bool = false open var shouldReportNamespacePrefixes: Bool = false //defaults to NSXMLNodeLoadExternalEntitiesNever open var externalEntityResolvingPolicy: ExternalEntityResolvingPolicy = .resolveExternalEntitiesNever open var allowedExternalEntityURLs: Set<URL>? internal static func currentParser() -> XMLParser? { if let current = Thread.current.threadDictionary["__CurrentNSXMLParser"] { return current as? XMLParser } else { return nil } } internal static func setCurrentParser(_ parser: XMLParser?) { if let p = parser { Thread.current.threadDictionary["__CurrentNSXMLParser"] = p } else { Thread.current.threadDictionary.removeValue(forKey: "__CurrentNSXMLParser") } } internal func _handleParseResult(_ parseResult: Int32) -> Bool { return true /* var result = true if parseResult != 0 { if parseResult != -1 { // TODO: determine if this result is a fatal error from libxml via the CF implementations } } return result */ } internal func parseData(_ data: Data) -> Bool { _CFXMLInterfaceSetStructuredErrorFunc(interface, _structuredErrorFunc) var result = true /* The vast majority of this method just deals with ensuring we do a single parse on the first 4 received bytes before continuing on to the actual incremental section */ if _haveDetectedEncoding { var totalLength = data.count if let chunk = _bomChunk { totalLength += chunk.count } if (totalLength < 4) { if let chunk = _bomChunk { var newData = Data() newData.append(chunk) newData.append(data) _bomChunk = newData } else { _bomChunk = data } } else { var allExistingData: Data if let chunk = _bomChunk { var newData = Data() newData.append(chunk) newData.append(data) allExistingData = newData } else { allExistingData = data } var handler: _CFXMLInterfaceSAXHandler? = nil if delegate != nil { handler = _handler } _parserContext = allExistingData.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> _CFXMLInterfaceParserContext in return _CFXMLInterfaceCreatePushParserCtxt(handler, interface, bytes, 4, nil) } var options = _kCFXMLInterfaceRecover | _kCFXMLInterfaceNoEnt // substitute entities, recover on errors if shouldResolveExternalEntities { options |= _kCFXMLInterfaceDTDLoad } if handler == nil { options |= (_kCFXMLInterfaceNoError | _kCFXMLInterfaceNoWarning) } _CFXMLInterfaceCtxtUseOptions(_parserContext, options) _haveDetectedEncoding = true _bomChunk = nil if (totalLength > 4) { let remainingData = allExistingData.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer<UInt8>) -> Data in let ptr = bytes.advanced(by: 4) return Data(bytesNoCopy: ptr, count: totalLength - 4, deallocator: .none) } let _ = parseData(remainingData) } } } else { let parseResult = data.withUnsafeBytes { (bytes: UnsafePointer<Int8>) -> Int32 in return _CFXMLInterfaceParseChunk(_parserContext, bytes, Int32(data.count), 0) } result = _handleParseResult(parseResult) } _CFXMLInterfaceSetStructuredErrorFunc(interface, nil) return result } internal func parseFromStream() -> Bool { var result = true XMLParser.setCurrentParser(self) if let stream = _stream { stream.open() let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize) var len = stream.read(buffer, maxLength: _chunkSize) if len != -1 { while len > 0 { let data = Data(bytesNoCopy: buffer, count: len, deallocator: .none) result = parseData(data) len = stream.read(buffer, maxLength: _chunkSize) } } else { result = false } free(buffer) stream.close() } else if let data = _data { let buffer = malloc(_chunkSize)!.bindMemory(to: UInt8.self, capacity: _chunkSize) var range = NSMakeRange(0, min(_chunkSize, data.count)) while result { let chunk = data.withUnsafeBytes { (buffer: UnsafePointer<UInt8>) -> Data in let ptr = buffer.advanced(by: range.location) return Data(bytesNoCopy: UnsafeMutablePointer(mutating: ptr), count: range.length, deallocator: .none) } result = parseData(chunk) if range.location + range.length >= data.count { break } range = NSMakeRange(range.location + range.length, min(_chunkSize, data.count - (range.location + range.length))) } free(buffer) } else { result = false } XMLParser.setCurrentParser(nil) return result } // called to start the event-driven parse. Returns YES in the event of a successful parse, and NO in case of error. open func parse() -> Bool { return parseFromStream() } // called by the delegate to stop the parse. The delegate will get an error message sent to it. open func abortParsing() { if let context = _parserContext { _CFXMLInterfaceStopParser(context) _delegateAborted = true } } internal var _parserError: Error? // can be called after a parse is over to determine parser state. open var parserError: Error? { return _parserError } //Toggles between disabling external entities entirely, and the current setting of the 'externalEntityResolvingPolicy'. //The 'externalEntityResolvingPolicy' property should be used instead of this, unless targeting 10.9/7.0 or earlier open var shouldResolveExternalEntities: Bool = false // Once a parse has begun, the delegate may be interested in certain parser state. These methods will only return meaningful information during parsing, or after an error has occurred. open var publicID: String? { return nil } open var systemID: String? { return nil } open var lineNumber: Int { return Int(_CFXMLInterfaceSAX2GetLineNumber(_parserContext)) } open var columnNumber: Int { return Int(_CFXMLInterfaceSAX2GetColumnNumber(_parserContext)) } internal func _pushNamespaces(_ ns: [String:String]) { _namespaces.append(ns) if let del = self.delegate { ns.forEach { del.parser(self, didStartMappingPrefix: $0.0, toURI: $0.1) } } } internal func _popNamespaces() { let ns = _namespaces.removeLast() if let del = self.delegate { ns.forEach { del.parser(self, didEndMappingPrefix: $0.0) } } } } /* For the discussion of event methods, assume the following XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type='text/css' href='cvslog.css'?> <!DOCTYPE cvslog SYSTEM "cvslog.dtd"> <cvslog xmlns="http://xml.apple.com/cvslog"> <radar:radar xmlns:radar="http://xml.apple.com/radar"> <radar:bugID>2920186</radar:bugID> <radar:title>API/NSXMLParser: there ought to be an NSXMLParser</radar:title> </radar:radar> </cvslog> */ // The parser's delegate is informed of events through the methods in the NSXMLParserDelegateEventAdditions category. public protocol XMLParserDelegate: class { // Document handling methods func parserDidStartDocument(_ parser: XMLParser) // sent when the parser begins parsing of the document. func parserDidEndDocument(_ parser: XMLParser) // sent when the parser has completed parsing. If this is encountered, the parse was successful. // DTD handling methods for various declarations. func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String) func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) // sent when the parser finds an element start tag. // In the case of the cvslog tag, the following is what the delegate receives: // elementName == cvslog, namespaceURI == http://xml.apple.com/cvslog, qualifiedName == cvslog // In the case of the radar tag, the following is what's passed in: // elementName == radar, namespaceURI == http://xml.apple.com/radar, qualifiedName == radar:radar // If namespace processing >isn't< on, the xmlns:radar="http://xml.apple.com/radar" is returned as an attribute pair, the elementName is 'radar:radar' and there is no qualifiedName. func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) // sent when an end tag is encountered. The various parameters are supplied as above. func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) // sent when the parser first sees a namespace attribute. // In the case of the cvslog tag, before the didStartElement:, you'd get one of these with prefix == @"" and namespaceURI == @"http://xml.apple.com/cvslog" (i.e. the default namespace) // In the case of the radar:radar tag, before the didStartElement: you'd get one of these with prefix == @"radar" and namespaceURI == @"http://xml.apple.com/radar" func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) // sent when the namespace prefix in question goes out of scope. func parser(_ parser: XMLParser, foundCharacters string: String) // This returns the string of the characters encountered thus far. You may not necessarily get the longest character run. The parser reserves the right to hand these to the delegate as potentially many calls in a row to -parser:foundCharacters: func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String) // The parser reports ignorable whitespace in the same way as characters it's found. func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?) // The parser reports a processing instruction to you using this method. In the case above, target == @"xml-stylesheet" and data == @"type='text/css' href='cvslog.css'" func parser(_ parser: XMLParser, foundComment comment: String) // A comment (Text in a <!-- --> block) is reported to the delegate as a single string func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) // this reports a CDATA block to the delegate as an NSData. func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? // this gives the delegate an opportunity to resolve an external entity itself and reply with the resulting data. func parser(_ parser: XMLParser, parseErrorOccurred parseError: NSError) // ...and this reports a fatal error to the delegate. The parser will stop parsing. func parser(_ parser: XMLParser, validationErrorOccurred validationError: NSError) } extension XMLParserDelegate { func parserDidStartDocument(_ parser: XMLParser) { } func parserDidEndDocument(_ parser: XMLParser) { } func parser(_ parser: XMLParser, foundNotationDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: XMLParser, foundUnparsedEntityDeclarationWithName name: String, publicID: String?, systemID: String?, notationName: String?) { } func parser(_ parser: XMLParser, foundAttributeDeclarationWithName attributeName: String, forElement elementName: String, type: String?, defaultValue: String?) { } func parser(_ parser: XMLParser, foundElementDeclarationWithName elementName: String, model: String) { } func parser(_ parser: XMLParser, foundInternalEntityDeclarationWithName name: String, value: String?) { } func parser(_ parser: XMLParser, foundExternalEntityDeclarationWithName name: String, publicID: String?, systemID: String?) { } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) { } func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) { } func parser(_ parser: XMLParser, didStartMappingPrefix prefix: String, toURI namespaceURI: String) { } func parser(_ parser: XMLParser, didEndMappingPrefix prefix: String) { } func parser(_ parser: XMLParser, foundCharacters string: String) { } func parser(_ parser: XMLParser, foundIgnorableWhitespace whitespaceString: String) { } func parser(_ parser: XMLParser, foundProcessingInstructionWithTarget target: String, data: String?) { } func parser(_ parser: XMLParser, foundComment comment: String) { } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { } func parser(_ parser: XMLParser, resolveExternalEntityName name: String, systemID: String?) -> Data? { return nil } func parser(_ parser: XMLParser, parseErrorOccurred parseError: NSError) { } func parser(_ parser: XMLParser, validationErrorOccurred validationError: NSError) { } } extension XMLParser { // If validation is on, this will report a fatal validation error to the delegate. The parser will stop parsing. public static let ErrorDomain: String = "NSXMLParserErrorDomain" // for use with NSError. // Error reporting public enum ErrorCode : Int { case internalError case outOfMemoryError case documentStartError case emptyDocumentError case prematureDocumentEndError case invalidHexCharacterRefError case invalidDecimalCharacterRefError case invalidCharacterRefError case invalidCharacterError case characterRefAtEOFError case characterRefInPrologError case characterRefInEpilogError case characterRefInDTDError case entityRefAtEOFError case entityRefInPrologError case entityRefInEpilogError case entityRefInDTDError case parsedEntityRefAtEOFError case parsedEntityRefInPrologError case parsedEntityRefInEpilogError case parsedEntityRefInInternalSubsetError case entityReferenceWithoutNameError case entityReferenceMissingSemiError case parsedEntityRefNoNameError case parsedEntityRefMissingSemiError case undeclaredEntityError case unparsedEntityError case entityIsExternalError case entityIsParameterError case unknownEncodingError case encodingNotSupportedError case stringNotStartedError case stringNotClosedError case namespaceDeclarationError case entityNotStartedError case entityNotFinishedError case lessThanSymbolInAttributeError case attributeNotStartedError case attributeNotFinishedError case attributeHasNoValueError case attributeRedefinedError case literalNotStartedError case literalNotFinishedError case commentNotFinishedError case processingInstructionNotStartedError case processingInstructionNotFinishedError case notationNotStartedError case notationNotFinishedError case attributeListNotStartedError case attributeListNotFinishedError case mixedContentDeclNotStartedError case mixedContentDeclNotFinishedError case elementContentDeclNotStartedError case elementContentDeclNotFinishedError case xmlDeclNotStartedError case xmlDeclNotFinishedError case conditionalSectionNotStartedError case conditionalSectionNotFinishedError case externalSubsetNotFinishedError case doctypeDeclNotFinishedError case misplacedCDATAEndStringError case cdataNotFinishedError case misplacedXMLDeclarationError case spaceRequiredError case separatorRequiredError case nmtokenRequiredError case nameRequiredError case pcdataRequiredError case uriRequiredError case publicIdentifierRequiredError case ltRequiredError case gtRequiredError case ltSlashRequiredError case equalExpectedError case tagNameMismatchError case unfinishedTagError case standaloneValueError case invalidEncodingNameError case commentContainsDoubleHyphenError case invalidEncodingError case externalStandaloneEntityError case invalidConditionalSectionError case entityValueRequiredError case notWellBalancedError case extraContentError case invalidCharacterInEntityError case parsedEntityRefInInternalError case entityRefLoopError case entityBoundaryError case invalidURIError case uriFragmentError case nodtdError case delegateAbortedParseError } }
apache-2.0
784a3eb3d1d3baa4b23863cc614e91d3
39.561616
344
0.646553
5.190125
false
false
false
false
swift-mtl/WTM-Montreal
Pods/Eureka/Source/Rows.swift
1
51121
// Rows.swift // Eureka ( https://github.com/xmartlabs/Eureka ) // // Copyright (c) 2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit import Foundation protocol FieldRowConformance : FormatterConformance { var textFieldPercentage : CGFloat? { get set } var placeholder : String? { get set } var placeholderColor : UIColor? { get set } } protocol TextAreaConformance : FormatterConformance { var placeholder : String? { get set } } public protocol PostalAddressRowConformance: PostalAddressFormatterConformance { var postalAddressPercentage : CGFloat? { get set } var placeholderColor : UIColor? { get set } var streetPlaceholder : String? { get set } var statePlaceholder : String? { get set } var postalCodePlaceholder : String? { get set } var cityPlaceholder : String? { get set } var countryPlaceholder : String? { get set } } public protocol FormatterConformance: class { var formatter: NSFormatter? { get set } var useFormatterDuringInput: Bool { get set } } public protocol PostalAddressFormatterConformance: class { var streetUseFormatterDuringInput: Bool { get set } var streetFormatter: NSFormatter? { get set } var stateUseFormatterDuringInput: Bool { get set } var stateFormatter: NSFormatter? { get set } var postalCodeUseFormatterDuringInput: Bool { get set } var postalCodeFormatter: NSFormatter? { get set } var cityUseFormatterDuringInput: Bool { get set } var cityFormatter: NSFormatter? { get set } var countryUseFormatterDuringInput: Bool { get set } var countryFormatter: NSFormatter? { get set } } public class FieldRow<T: Any, Cell: CellType where Cell: BaseCell, Cell: TextFieldCell, Cell.Value == T>: Row<T, Cell>, FieldRowConformance, KeyboardReturnHandler { /// Configuration for the keyboardReturnType of this row public var keyboardReturnType : KeyboardReturnTypeConfiguration? /// The percentage of the cell that should be occupied by the textField public var textFieldPercentage : CGFloat? /// The placeholder for the textField public var placeholder : String? /// The textColor for the textField's placeholder public var placeholderColor : UIColor? /// A formatter to be used to format the user's input public var formatter: NSFormatter? /// If the formatter should be used while the user is editing the text. public var useFormatterDuringInput: Bool public required init(tag: String?) { useFormatterDuringInput = false super.init(tag: tag) self.displayValueFor = { [unowned self] value in guard let v = value else { return nil } if let formatter = self.formatter { if self.cell.textField.isFirstResponder() { if self.useFormatterDuringInput { return formatter.editingStringForObjectValue(v as! AnyObject) } else { return String(v) } } return formatter.stringForObjectValue(v as! AnyObject) } else{ return String(v) } } } } public class _PostalAddressRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell: PostalAddressCell, Cell.Value == T>: Row<T, Cell>, PostalAddressRowConformance, KeyboardReturnHandler { /// Configuration for the keyboardReturnType of this row public var keyboardReturnType : KeyboardReturnTypeConfiguration? /// The percentage of the cell that should be occupied by the postal address public var postalAddressPercentage: CGFloat? /// The textColor for the textField's placeholder public var placeholderColor : UIColor? /// The placeholder for the street textField public var streetPlaceholder : String? /// The placeholder for the state textField public var statePlaceholder : String? /// The placeholder for the zip textField public var postalCodePlaceholder : String? /// The placeholder for the city textField public var cityPlaceholder : String? /// The placeholder for the country textField public var countryPlaceholder : String? /// A formatter to be used to format the user's input for street public var streetFormatter: NSFormatter? /// A formatter to be used to format the user's input for state public var stateFormatter: NSFormatter? /// A formatter to be used to format the user's input for zip public var postalCodeFormatter: NSFormatter? /// A formatter to be used to format the user's input for city public var cityFormatter: NSFormatter? /// A formatter to be used to format the user's input for country public var countryFormatter: NSFormatter? /// If the formatter should be used while the user is editing the street. public var streetUseFormatterDuringInput: Bool /// If the formatter should be used while the user is editing the state. public var stateUseFormatterDuringInput: Bool /// If the formatter should be used while the user is editing the zip. public var postalCodeUseFormatterDuringInput: Bool /// If the formatter should be used while the user is editing the city. public var cityUseFormatterDuringInput: Bool /// If the formatter should be used while the user is editing the country. public var countryUseFormatterDuringInput: Bool public required init(tag: String?) { streetUseFormatterDuringInput = false stateUseFormatterDuringInput = false postalCodeUseFormatterDuringInput = false cityUseFormatterDuringInput = false countryUseFormatterDuringInput = false super.init(tag: tag) } } public protocol _DatePickerRowProtocol { var minimumDate : NSDate? { get set } var maximumDate : NSDate? { get set } var minuteInterval : Int? { get set } } public class _DateFieldRow: Row<NSDate, DateCell>, _DatePickerRowProtocol { /// The minimum value for this row's UIDatePicker public var minimumDate : NSDate? /// The maximum value for this row's UIDatePicker public var maximumDate : NSDate? /// The interval between options for this row's UIDatePicker public var minuteInterval : Int? /// The formatter for the date picked by the user public var dateFormatter: NSDateFormatter? required public init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let val = value, let formatter = self.dateFormatter else { return nil } return formatter.stringFromDate(val) } } } public class _DateInlineFieldRow: Row<NSDate, DateInlineCell>, _DatePickerRowProtocol { /// The minimum value for this row's UIDatePicker public var minimumDate : NSDate? /// The maximum value for this row's UIDatePicker public var maximumDate : NSDate? /// The interval between options for this row's UIDatePicker public var minuteInterval : Int? /// The formatter for the date picked by the user public var dateFormatter: NSDateFormatter? required public init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let val = value, let formatter = self.dateFormatter else { return nil } return formatter.stringFromDate(val) } } } public class _DateInlineRow: _DateInlineFieldRow { public typealias InlineRow = DatePickerRow public required init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .NoStyle dateFormatter?.dateStyle = .MediumStyle dateFormatter?.locale = .currentLocale() } public func setupInlineRow(inlineRow: DatePickerRow) { inlineRow.minimumDate = minimumDate inlineRow.maximumDate = maximumDate inlineRow.minuteInterval = minuteInterval } } public class _DateTimeInlineRow: _DateInlineFieldRow { public typealias InlineRow = DateTimePickerRow public required init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .ShortStyle dateFormatter?.dateStyle = .ShortStyle dateFormatter?.locale = .currentLocale() } public func setupInlineRow(inlineRow: DateTimePickerRow) { inlineRow.minimumDate = minimumDate inlineRow.maximumDate = maximumDate inlineRow.minuteInterval = minuteInterval } } public class _TimeInlineRow: _DateInlineFieldRow { public typealias InlineRow = TimePickerRow public required init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .ShortStyle dateFormatter?.dateStyle = .NoStyle dateFormatter?.locale = .currentLocale() } public func setupInlineRow(inlineRow: TimePickerRow) { inlineRow.minimumDate = minimumDate inlineRow.maximumDate = maximumDate inlineRow.minuteInterval = minuteInterval } } public class _CountDownInlineRow: _DateInlineFieldRow { public typealias InlineRow = CountDownPickerRow public required init(tag: String?) { super.init(tag: tag) displayValueFor = { guard let date = $0 else { return nil } let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: date) let min = NSCalendar.currentCalendar().component(.Minute, fromDate: date) if hour == 1{ return "\(hour) hour \(min) min" } return "\(hour) hours \(min) min" } } public func setupInlineRow(inlineRow: CountDownPickerRow) { inlineRow.minimumDate = minimumDate inlineRow.maximumDate = maximumDate inlineRow.minuteInterval = minuteInterval } } public class _TextRow: FieldRow<String, TextCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _IntRow: FieldRow<Int, IntCell> { public required init(tag: String?) { super.init(tag: tag) let numberFormatter = NSNumberFormatter() numberFormatter.locale = .currentLocale() numberFormatter.numberStyle = .DecimalStyle numberFormatter.minimumFractionDigits = 0 formatter = numberFormatter } } public class _PhoneRow: FieldRow<String, PhoneCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _NameRow: FieldRow<String, NameCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _EmailRow: FieldRow<String, EmailCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _PasswordRow: FieldRow<String, PasswordCell> { public required init(tag: String?) { super.init(tag: tag) } } public class DecimalFormatter : NSNumberFormatter, FormatterProtocol { public override init() { super.init() locale = .currentLocale() numberStyle = .DecimalStyle minimumFractionDigits = 2 maximumFractionDigits = 2 } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool { guard obj != nil else { return false } let str = string.componentsSeparatedByCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).joinWithSeparator("") obj.memory = NSNumber(double: (Double(str) ?? 0.0)/Double(pow(10.0, Double(minimumFractionDigits)))) return true } public func getNewPosition(forPosition position: UITextPosition, inTextInput textInput: UITextInput, oldValue: String?, newValue: String?) -> UITextPosition { return textInput.positionFromPosition(position, offset:((newValue?.characters.count ?? 0) - (oldValue?.characters.count ?? 0))) ?? position } } public class _DecimalRow: FieldRow<Double, DecimalCell> { public required init(tag: String?) { super.init(tag: tag) let numberFormatter = NSNumberFormatter() numberFormatter.locale = .currentLocale() numberFormatter.numberStyle = .DecimalStyle numberFormatter.minimumFractionDigits = 2 formatter = numberFormatter } } public class _URLRow: FieldRow<NSURL, URLCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _TwitterRow: FieldRow<String, TwitterCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _AccountRow: FieldRow<String, AccountCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _ZipCodeRow: FieldRow<String, ZipCodeCell> { public required init(tag: String?) { super.init(tag: tag) } } public class _TimeRow: _DateFieldRow { required public init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .ShortStyle dateFormatter?.dateStyle = .NoStyle dateFormatter?.locale = NSLocale.currentLocale() } } public class _DateRow: _DateFieldRow { required public init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .NoStyle dateFormatter?.dateStyle = .MediumStyle dateFormatter?.locale = NSLocale.currentLocale() } } public class _DateTimeRow: _DateFieldRow { required public init(tag: String?) { super.init(tag: tag) dateFormatter = NSDateFormatter() dateFormatter?.timeStyle = .ShortStyle dateFormatter?.dateStyle = .ShortStyle dateFormatter?.locale = NSLocale.currentLocale() } } public class _CountDownRow: _DateFieldRow { required public init(tag: String?) { super.init(tag: tag) displayValueFor = { [unowned self] value in guard let val = value else { return nil } if let formatter = self.dateFormatter { return formatter.stringFromDate(val) } let components = NSCalendar.currentCalendar().components(NSCalendarUnit.Minute.union(NSCalendarUnit.Hour), fromDate: val) var hourString = "hour" if components.hour != 1{ hourString += "s" } return "\(components.hour) \(hourString) \(components.minute) min" } } } public class _DatePickerRow : Row<NSDate, DatePickerCell>, _DatePickerRowProtocol { public var minimumDate : NSDate? public var maximumDate : NSDate? public var minuteInterval : Int? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } public class _PickerRow<T where T: Equatable> : Row<T, PickerCell<T>>{ public var options = [T]() required public init(tag: String?) { super.init(tag: tag) } } public class _PickerInlineRow<T where T: Equatable> : Row<T, LabelCellOf<T>>{ public typealias InlineRow = PickerRow<T> public var options = [T]() required public init(tag: String?) { super.init(tag: tag) } } public class _TextAreaRow: AreaRow<String, TextAreaCell> { required public init(tag: String?) { super.init(tag: tag) } } public class _LabelRow: Row<String, LabelCell> { required public init(tag: String?) { super.init(tag: tag) } } public class _CheckRow: Row<Bool, CheckCell> { required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } public final class ListCheckRow<T: Equatable>: Row<T, ListCheckCell<T>>, SelectableRowType, RowType { public var selectableValue: T? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } public class _SwitchRow: Row<Bool, SwitchCell> { required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil } } public class _PushRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell.Value == T> : SelectorRow<T, SelectorViewController<T>, Cell> { public required init(tag: String?) { super.init(tag: tag) presentationMode = .Show(controllerProvider: ControllerProvider.Callback { return SelectorViewController<T>(){ _ in } }, completionCallback: { vc in vc.navigationController?.popViewControllerAnimated(true) }) } } public class _PopoverSelectorRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell.Value == T> : SelectorRow<T, SelectorViewController<T>, Cell> { public required init(tag: String?) { super.init(tag: tag) onPresentCallback = { [weak self] (_, viewController) -> Void in guard let porpoverController = viewController.popoverPresentationController, tableView = self?.baseCell.formViewController()?.tableView, cell = self?.cell else { fatalError() } porpoverController.sourceView = tableView porpoverController.sourceRect = tableView.convertRect(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, fromView: cell) } presentationMode = .Popover(controllerProvider: ControllerProvider.Callback { return SelectorViewController<T>(){ _ in } }, completionCallback: { [weak self] in $0.dismissViewControllerAnimated(true, completion: nil) self?.reload() }) } public override func didSelect() { deselect() super.didSelect() } } public class AreaRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell: AreaCell, Cell.Value == T>: Row<T, Cell>, TextAreaConformance { public var placeholder : String? public var formatter: NSFormatter? public var useFormatterDuringInput: Bool public required init(tag: String?) { useFormatterDuringInput = false super.init(tag: tag) self.displayValueFor = { [unowned self] value in guard let v = value else { return nil } if let formatter = self.formatter { if self.cell.textView.isFirstResponder() { if self.useFormatterDuringInput { return formatter.editingStringForObjectValue(v as! AnyObject) } else { return String(v) } } return formatter.stringForObjectValue(v as! AnyObject) } else{ return String(v) } } } } public class OptionsRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell.Value == T> : Row<T, Cell> { public var options: [T] { get { return dataProvider?.arrayData ?? [] } set { dataProvider = DataProvider(arrayData: newValue) } } public var selectorTitle: String? required public init(tag: String?) { super.init(tag: tag) } } public class _ActionSheetRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell.Value == T>: OptionsRow<T, Cell>, PresenterRowType { public var onPresentCallback : ((FormViewController, SelectorAlertController<T>)->())? lazy public var presentationMode: PresentationMode<SelectorAlertController<T>>? = { return .PresentModally(controllerProvider: ControllerProvider.Callback { [weak self] in let vc = SelectorAlertController<T>(title: self?.selectorTitle, message: nil, preferredStyle: .ActionSheet) if let popView = vc.popoverPresentationController { guard let cell = self?.cell, tableView = cell.formViewController()?.tableView else { fatalError() } popView.sourceView = tableView popView.sourceRect = tableView.convertRect(cell.detailTextLabel?.frame ?? cell.textLabel?.frame ?? cell.contentView.frame, fromView: cell) } vc.row = self return vc }, completionCallback: { [weak self] in $0.dismissViewControllerAnimated(true, completion: nil) self?.cell?.formViewController()?.tableView?.reloadData() }) }() public required init(tag: String?) { super.init(tag: tag) } public override func customDidSelect() { super.customDidSelect() if let presentationMode = presentationMode where !isDisabled { if let controller = presentationMode.createController(){ controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!) } } } } public class _AlertRow<T: Equatable, Cell: CellType where Cell: BaseCell, Cell.Value == T>: OptionsRow<T, Cell>, PresenterRowType { public var onPresentCallback : ((FormViewController, SelectorAlertController<T>)->())? lazy public var presentationMode: PresentationMode<SelectorAlertController<T>>? = { return .PresentModally(controllerProvider: ControllerProvider.Callback { [weak self] in let vc = SelectorAlertController<T>(title: self?.selectorTitle, message: nil, preferredStyle: .Alert) vc.row = self return vc }, completionCallback: { [weak self] in $0.dismissViewControllerAnimated(true, completion: nil) self?.cell?.formViewController()?.tableView?.reloadData() } ) }() public required init(tag: String?) { super.init(tag: tag) } public override func customDidSelect() { super.customDidSelect() if let presentationMode = presentationMode where !isDisabled { if let controller = presentationMode.createController(){ controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!) } } } } public struct ImageRowSourceTypes : OptionSetType { public let rawValue: Int public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 } public init(rawValue: Int) { self.rawValue = rawValue } private init(_ sourceType: UIImagePickerControllerSourceType) { self.init(rawValue: 1 << sourceType.rawValue) } public static let PhotoLibrary = ImageRowSourceTypes(.PhotoLibrary) public static let Camera = ImageRowSourceTypes(.Camera) public static let SavedPhotosAlbum = ImageRowSourceTypes(.SavedPhotosAlbum) public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum] } public enum ImageClearAction { case No case Yes(style: UIAlertActionStyle) } public class _ImageRow<Cell: CellType where Cell: BaseCell, Cell.Value == UIImage> : SelectorRow<UIImage, ImagePickerController, Cell> { public var sourceTypes: ImageRowSourceTypes public internal(set) var imageURL: NSURL? public var clearAction = ImageClearAction.Yes(style: .Destructive) private var _sourceType: UIImagePickerControllerSourceType = .Camera public required init(tag: String?) { sourceTypes = .All super.init(tag: tag) presentationMode = .PresentModally(controllerProvider: ControllerProvider.Callback { return ImagePickerController() }, completionCallback: { [weak self] vc in self?.select() vc.dismissViewControllerAnimated(true, completion: nil) }) self.displayValueFor = nil } // copy over the existing logic from the SelectorRow private func displayImagePickerController(sourceType: UIImagePickerControllerSourceType) { if let presentationMode = presentationMode where !isDisabled { if let controller = presentationMode.createController(){ controller.row = self controller.sourceType = sourceType onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: cell.formViewController()!) } else{ _sourceType = sourceType presentationMode.presentViewController(nil, row: self, presentingViewController: cell.formViewController()!) } } } public override func customDidSelect() { guard !isDisabled else { super.customDidSelect() return } deselect() var availableSources: ImageRowSourceTypes = [] if UIImagePickerController.isSourceTypeAvailable(.PhotoLibrary) { availableSources.insert(.PhotoLibrary) } if UIImagePickerController.isSourceTypeAvailable(.Camera) { availableSources.insert(.Camera) } if UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) { availableSources.insert(.SavedPhotosAlbum) } sourceTypes.intersectInPlace(availableSources) if sourceTypes.isEmpty { super.customDidSelect() return } // now that we know the number of actions aren't empty let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .ActionSheet) guard let tableView = cell.formViewController()?.tableView else { fatalError() } if let popView = sourceActionSheet.popoverPresentationController { popView.sourceView = tableView popView.sourceRect = tableView.convertRect(cell.accessoryView?.frame ?? cell.contentView.frame, fromView: cell) } if sourceTypes.contains(.Camera) { let cameraOption = UIAlertAction(title: NSLocalizedString("Take Photo", comment: ""), style: .Default, handler: { [weak self] _ in self?.displayImagePickerController(.Camera) }) sourceActionSheet.addAction(cameraOption) } if sourceTypes.contains(.PhotoLibrary) { let photoLibraryOption = UIAlertAction(title: NSLocalizedString("Photo Library", comment: ""), style: .Default, handler: { [weak self] _ in self?.displayImagePickerController(.PhotoLibrary) }) sourceActionSheet.addAction(photoLibraryOption) } if sourceTypes.contains(.SavedPhotosAlbum) { let savedPhotosOption = UIAlertAction(title: NSLocalizedString("Saved Photos", comment: ""), style: .Default, handler: { [weak self] _ in self?.displayImagePickerController(.SavedPhotosAlbum) }) sourceActionSheet.addAction(savedPhotosOption) } switch clearAction { case .Yes(let style): if let _ = value { let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in self?.value = nil self?.updateCell() }) sourceActionSheet.addAction(clearPhotoOption) } case .No: break } // check if we have only one source type given if sourceActionSheet.actions.count == 1 { if let imagePickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) { displayImagePickerController(imagePickerSourceType) } } else { let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler:nil) sourceActionSheet.addAction(cancelOption) if let presentingViewController = cell.formViewController() { presentingViewController.presentViewController(sourceActionSheet, animated: true, completion:nil) } } } public override func prepareForSegue(segue: UIStoryboardSegue) { super.prepareForSegue(segue) guard let rowVC = segue.destinationViewController as? ImagePickerController else { return } rowVC.sourceType = _sourceType } public override func customUpdateCell() { super.customUpdateCell() cell.accessoryType = .None if let image = self.value { let imageView = UIImageView(frame: CGRectMake(0, 0, 44, 44)) imageView.contentMode = .ScaleAspectFill imageView.image = image imageView.clipsToBounds = true cell.accessoryView = imageView } else{ cell.accessoryView = nil } } } public class _MultipleSelectorRow<T: Hashable, Cell: CellType where Cell: BaseCell, Cell.Value == Set<T>> : GenericMultipleSelectorRow<T, MultipleSelectorViewController<T>, Cell> { public required init(tag: String?) { super.init(tag: tag) self.displayValueFor = { if let t = $0 { return t.map({ String($0) }).joinWithSeparator(", ") } return nil } } } public class _ButtonRowOf<T: Equatable> : Row<T, ButtonCellOf<T>> { public var presentationMode: PresentationMode<UIViewController>? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellStyle = .Default } public override func customDidSelect() { super.customDidSelect() if !isDisabled { if let presentationMode = presentationMode { if let controller = presentationMode.createController(){ presentationMode.presentViewController(controller, row: self, presentingViewController: self.cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: self.cell.formViewController()!) } } } } public override func customUpdateCell() { super.customUpdateCell() let leftAligmnment = presentationMode != nil cell.textLabel?.textAlignment = leftAligmnment ? .Left : .Center cell.accessoryType = !leftAligmnment || isDisabled ? .None : .DisclosureIndicator cell.editingAccessoryType = cell.accessoryType if (!leftAligmnment){ var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0) } else{ cell.textLabel?.textColor = nil } } public override func prepareForSegue(segue: UIStoryboardSegue) { super.prepareForSegue(segue) let rowVC = segue.destinationViewController as? RowControllerType rowVC?.completionCallback = self.presentationMode?.completionHandler } } public class _ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType where VCType: UIViewController, VCType.RowValue == T>: Row<T, ButtonCellOf<T>>, PresenterRowType { public var presentationMode: PresentationMode<VCType>? public var onPresentCallback : ((FormViewController, VCType)->())? required public init(tag: String?) { super.init(tag: tag) displayValueFor = nil cellStyle = .Default } public override func customUpdateCell() { super.customUpdateCell() let leftAligmnment = presentationMode != nil cell.textLabel?.textAlignment = leftAligmnment ? .Left : .Center cell.accessoryType = !leftAligmnment || isDisabled ? .None : .DisclosureIndicator cell.editingAccessoryType = cell.accessoryType if (!leftAligmnment){ var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 cell.tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) cell.textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha:isDisabled ? 0.3 : 1.0) } else{ cell.textLabel?.textColor = nil } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { if let presentationMode = presentationMode { if let controller = presentationMode.createController(){ controller.row = self onPresentCallback?(cell.formViewController()!, controller) presentationMode.presentViewController(controller, row: self, presentingViewController: self.cell.formViewController()!) } else{ presentationMode.presentViewController(nil, row: self, presentingViewController: self.cell.formViewController()!) } } } } public override func prepareForSegue(segue: UIStoryboardSegue) { super.prepareForSegue(segue) guard let rowVC = segue.destinationViewController as? VCType else { return } if let callback = self.presentationMode?.completionHandler{ rowVC.completionCallback = callback } onPresentCallback?(cell.formViewController()!, rowVC) rowVC.row = self } } //MARK: Rows /// Boolean row that has a checkmark as accessoryType public final class CheckRow: _CheckRow, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// Boolean row that has a UISwitch as accessoryType public final class SwitchRow: _SwitchRow, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// Simple row that can show title and value but is not editable by user. public final class LabelRow: _LabelRow, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// A row with an NSDate as value where the user can select a date from a picker view. public final class DateRow: _DateRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.detailTextLabel?.textColor row.onCellUnHighlight { cell, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } } /// A row with an NSDate as value where the user can select a time from a picker view. public final class TimeRow: _TimeRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.detailTextLabel?.textColor row.onCellUnHighlight { cell, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } } /// A row with an NSDate as value where the user can select date and time from a picker view. public final class DateTimeRow: _DateTimeRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.detailTextLabel?.textColor row.onCellUnHighlight { cell, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } } /// A row with an NSDate as value where the user can select hour and minute as a countdown timer in a picker view. public final class CountDownRow: _CountDownRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.detailTextLabel?.textColor row.onCellUnHighlight { cell, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } } /// A row with an NSDate as value where the user can select a date from an inline picker view. public final class DateInlineRow: _DateInlineRow, RowType, InlineRowType { required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } } /// A row with an NSDate as value where the user can select a time from an inline picker view. public final class TimeInlineRow: _TimeInlineRow, RowType, InlineRowType { required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } } /// A row with an NSDate as value where the user can select date and time from an inline picker view. public final class DateTimeInlineRow: _DateTimeInlineRow, RowType, InlineRowType { required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } } /// A row with an NSDate as value where the user can select hour and minute as a countdown timer in an inline picker view. public final class CountDownInlineRow: _CountDownInlineRow, RowType, InlineRowType { required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } } /// A row with an NSDate as value where the user can select a date directly. public final class DatePickerRow : _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an NSDate as value where the user can select a time directly. public final class TimePickerRow : _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an NSDate as value where the user can select date and time directly. public final class DateTimePickerRow : _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with an NSDate as value where the user can select hour and minute as a countdown timer. public final class CountDownPickerRow : _DatePickerRow, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A String valued row where the user can enter arbitrary text. public final class TextRow: _TextRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter names. Biggest difference to TextRow is that it autocapitalization is set to Words. public final class NameRow: _NameRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter secure text. public final class PasswordRow: _PasswordRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter an email address. public final class EmailRow: _EmailRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter a twitter username. public final class TwitterRow: _TwitterRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter a simple account username. public final class AccountRow: _AccountRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter a zip code. public final class ZipCodeRow: _ZipCodeRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A row where the user can enter an integer number. public final class IntRow: _IntRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A row where the user can enter a decimal number. public final class DecimalRow: _DecimalRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A row where the user can enter an URL. The value of this row will be a NSURL. public final class URLRow: _URLRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A String valued row where the user can enter a phone number. public final class PhoneRow: _PhoneRow, RowType { required public init(tag: String?) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } } /// A row with a UITextView where the user can enter large text. public final class TextAreaRow: _TextAreaRow, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// An options row where the user can select an option from an UISegmentedControl public final class SegmentedRow<T: Equatable>: OptionsRow<T, SegmentedCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// An options row where the user can select an option from an ActionSheet public final class ActionSheetRow<T: Equatable>: _ActionSheetRow<T, AlertSelectorCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// An options row where the user can select an option from a modal Alert public final class AlertRow<T: Equatable>: _AlertRow<T, AlertSelectorCell<T>>, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// A selector row where the user can pick an image public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A selector row where the user can pick an option from a pushed view controller public final class PushRow<T: Equatable> : _PushRow<T, PushSelectorCell<T>>, RowType { public required init(tag: String?) { super.init(tag: tag) } } public final class PopoverSelectorRow<T: Equatable> : _PopoverSelectorRow<T, PushSelectorCell<T>>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A selector row where the user can pick several options from a pushed view controller public final class MultipleSelectorRow<T: Hashable> : _MultipleSelectorRow<T, PushSelectorCell<Set<T>>>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A generic row with a button. The action of this button can be anything but normally will push a new view controller public final class ButtonRowOf<T: Equatable> : _ButtonRowOf<T>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A row with a button and String value. The action of this button can be anything but normally will push a new view controller public typealias ButtonRow = ButtonRowOf<String> /// A generic row with a button that presents a view controller when tapped public final class ButtonRowWithPresent<T: Equatable, VCType: TypedRowControllerType where VCType: UIViewController, VCType.RowValue == T> : _ButtonRowWithPresent<T, VCType>, RowType { public required init(tag: String?) { super.init(tag: tag) } } /// A generic inline row where the user can pick an option from a picker view public final class PickerInlineRow<T where T: Equatable> : _PickerInlineRow<T>, RowType, InlineRowType{ required public init(tag: String?) { super.init(tag: tag) onExpandInlineRow { cell, row, _ in let color = cell.detailTextLabel?.textColor row.onCollapseInlineRow { cell, _, _ in cell.detailTextLabel?.textColor = color } cell.detailTextLabel?.textColor = cell.tintColor } } public override func customDidSelect() { super.customDidSelect() if !isDisabled { toggleInlineRow() } } public func setupInlineRow(inlineRow: InlineRow) { inlineRow.options = self.options inlineRow.displayValueFor = self.displayValueFor } } /// A generic row where the user can pick an option from a picker view public final class PickerRow<T where T: Equatable>: _PickerRow<T>, RowType { required public init(tag: String?) { super.init(tag: tag) } } /// A PostalAddress valued row where the user can enter a postal address. public final class PostalAddressRow: _PostalAddressRow<PostalAddress, DefaultPostalAddressCell<PostalAddress>>, RowType { public required init(tag: String? = nil) { super.init(tag: tag) onCellHighlight { cell, row in let color = cell.textLabel?.textColor row.onCellUnHighlight { cell, _ in cell.textLabel?.textColor = color } cell.textLabel?.textColor = cell.tintColor } } }
mit
9910c19c8100c0755b19b1cacdf6603f
34.900281
216
0.647405
4.984011
false
false
false
false
naokits/my-programming-marathon
iPhoneSensorDemo/Pods/RxCocoa/RxCocoa/iOS/Proxies/RxCollectionViewDataSourceProxy.swift
52
3975
// // RxCollectionViewDataSourceProxy.swift // RxCocoa // // Created by Krunoslav Zaher on 6/29/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if os(iOS) || os(tvOS) import Foundation import UIKit #if !RX_NO_MODULE import RxSwift #endif let collectionViewDataSourceNotSet = CollectionViewDataSourceNotSet() class CollectionViewDataSourceNotSet : NSObject , UICollectionViewDataSource { func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { rxAbstractMethodWithMessage(dataSourceNotSet) } // The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath: func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { rxAbstractMethodWithMessage(dataSourceNotSet) } } /** For more information take a look at `DelegateProxyType`. */ public class RxCollectionViewDataSourceProxy : DelegateProxy , UICollectionViewDataSource , DelegateProxyType { /** Typed parent object. */ public weak private(set) var collectionView: UICollectionView? private weak var _requiredMethodsDataSource: UICollectionViewDataSource? = collectionViewDataSourceNotSet /** Initializes `RxCollectionViewDataSourceProxy` - parameter parentObject: Parent object for delegate proxy. */ public required init(parentObject: AnyObject) { self.collectionView = (parentObject as! UICollectionView) super.init(parentObject: parentObject) } // MARK: delegate /** Required delegate method implementation. */ public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, numberOfItemsInSection: section) ?? 0 } /** Required delegate method implementation. */ public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { return (_requiredMethodsDataSource ?? collectionViewDataSourceNotSet).collectionView(collectionView, cellForItemAtIndexPath: indexPath) } // MARK: proxy /** For more information take a look at `DelegateProxyType`. */ public override class func createProxyForObject(object: AnyObject) -> AnyObject { let collectionView = (object as! UICollectionView) return castOrFatalError(collectionView.rx_createDataSourceProxy()) } /** For more information take a look at `DelegateProxyType`. */ public override class func delegateAssociatedObjectTag() -> UnsafePointer<Void> { return _pointer(&dataSourceAssociatedTag) } /** For more information take a look at `DelegateProxyType`. */ public class func setCurrentDelegate(delegate: AnyObject?, toObject object: AnyObject) { let collectionView: UICollectionView = castOrFatalError(object) collectionView.dataSource = castOptionalOrFatalError(delegate) } /** For more information take a look at `DelegateProxyType`. */ public class func currentDelegateFor(object: AnyObject) -> AnyObject? { let collectionView: UICollectionView = castOrFatalError(object) return collectionView.dataSource } /** For more information take a look at `DelegateProxyType`. */ public override func setForwardToDelegate(forwardToDelegate: AnyObject?, retainDelegate: Bool) { let requiredMethodsDataSource: UICollectionViewDataSource? = castOptionalOrFatalError(forwardToDelegate) _requiredMethodsDataSource = requiredMethodsDataSource ?? collectionViewDataSourceNotSet super.setForwardToDelegate(forwardToDelegate, retainDelegate: retainDelegate) } } #endif
mit
a2f26c73b4a1346da0bd20555ec54530
32.677966
146
0.73226
6.104455
false
false
false
false
robertoseidenberg/MixerBox
MixerBox/HSB.swift
1
776
import simd public struct HSB { public var hue: Float // Range: 0...1 public var saturation: Float // Range: 0...1 public var brightness: Float // Range: 0...1 public init(hue: Float, saturation: Float, brightness: Float) { self.hue = hue .clamp(min: 0, max: 1) self.saturation = saturation.clamp(min: 0, max: 1) self.brightness = brightness.clamp(min: 0, max: 1) } public init(hue: CGFloat, saturation: CGFloat, brightness: CGFloat) { self.hue = Float(hue) .clamp(min: 0, max: 1) self.saturation = Float(saturation).clamp(min: 0, max: 1) self.brightness = Float(brightness).clamp(min: 0, max: 1) } } extension HSB { public func rgb() -> RGB { return UIColor(hsb: self).rgb() } }
mit
6db7135a8697ab1106dc45e8f0954fef
26.714286
71
0.609536
3.433628
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Post/Scheduling/SchedulingDatePickerViewController.swift
1
8248
import Foundation import Gridicons import UIKit protocol DateCoordinatorHandler: AnyObject { var coordinator: DateCoordinator? { get set } } class DateCoordinator { var date: Date? let timeZone: TimeZone let dateFormatter: DateFormatter let dateTimeFormatter: DateFormatter let updated: (Date?) -> Void init(date: Date?, timeZone: TimeZone, dateFormatter: DateFormatter, dateTimeFormatter: DateFormatter, updated: @escaping (Date?) -> Void) { self.date = date self.timeZone = timeZone self.dateFormatter = dateFormatter self.dateTimeFormatter = dateTimeFormatter self.updated = updated } } // MARK: - Date Picker @available(iOS, introduced: 14.0) class SchedulingDatePickerViewController: UIViewController, DatePickerSheet, DateCoordinatorHandler, SchedulingViewControllerProtocol { var coordinator: DateCoordinator? = nil let chosenValueRow = ChosenValueRow(frame: .zero) lazy var datePickerView: UIDatePicker = { let datePicker = UIDatePicker() datePicker.preferredDatePickerStyle = .inline datePicker.calendar = Calendar.current if let timeZone = coordinator?.timeZone { datePicker.timeZone = timeZone } datePicker.date = coordinator?.date ?? Date() datePicker.translatesAutoresizingMaskIntoConstraints = false datePicker.addTarget(self, action: #selector(datePickerValueChanged(sender:)), for: .valueChanged) return datePicker }() @objc private func datePickerValueChanged(sender: UIDatePicker) { let date = sender.date coordinator?.date = date chosenValueRow.detailLabel.text = coordinator?.dateFormatter.string(from: date) } private lazy var closeButton: UIBarButtonItem = { let item = UIBarButtonItem(image: .gridicon(.cross), style: .plain, target: self, action: #selector(closeButtonPressed)) item.accessibilityLabel = NSLocalizedString("Close", comment: "Accessibility label for the date picker's close button.") return item }() private lazy var publishButton = UIBarButtonItem(title: NSLocalizedString("Publish immediately", comment: "Immediately publish button title"), style: .plain, target: self, action: #selector(SchedulingDatePickerViewController.publishImmediately)) override func viewDidLoad() { super.viewDidLoad() chosenValueRow.titleLabel.text = NSLocalizedString("Choose a date", comment: "Label for Publish date picker") let doneButton = UIBarButtonItem(title: NSLocalizedString("Done", comment: "Label for Done button"), style: .done, target: self, action: #selector(done)) navigationItem.setRightBarButton(doneButton, animated: false) setup(topView: chosenValueRow, pickerView: datePickerView) view.tintColor = .editorPrimary setupForAccessibility() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() preferredContentSize = calculatePreferredSize() } private func calculatePreferredSize() -> CGSize { let targetSize = CGSize(width: view.bounds.width, height: UIView.layoutFittingCompressedSize.height) return view.systemLayoutSizeFitting(targetSize) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { (segue.destination as? DateCoordinatorHandler)?.coordinator = coordinator } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) resetNavigationButtons() } @objc func closeButtonPressed() { dismiss(animated: true, completion: nil) } override func accessibilityPerformEscape() -> Bool { dismiss(animated: true, completion: nil) return true } @objc func publishImmediately() { coordinator?.updated(nil) navigationController?.dismiss(animated: true, completion: nil) } @objc func done() { coordinator?.updated(coordinator?.date) navigationController?.dismiss(animated: true, completion: nil) } @objc private func resetNavigationButtons() { let includeCloseButton = traitCollection.verticalSizeClass == .compact || (isVoiceOverOrSwitchControlRunning && navigationController?.modalPresentationStyle != .popover) if includeCloseButton { navigationItem.leftBarButtonItems = [closeButton, publishButton] } else { navigationItem.leftBarButtonItems = [publishButton] } } } @available(iOS 14.0, *) extension SchedulingDatePickerViewController { @objc func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { let presentationController = PartScreenPresentationController(presentedViewController: presented, presenting: presenting) presentationController.delegate = self return presentationController } @objc func adaptivePresentationStyle(for: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle { return traitCollection.verticalSizeClass == .compact ? .overFullScreen : .none } } // MARK: Accessibility @available(iOS 14.0, *) private extension SchedulingDatePickerViewController { func setupForAccessibility() { let notificationNames = [ UIAccessibility.voiceOverStatusDidChangeNotification, UIAccessibility.switchControlStatusDidChangeNotification ] NotificationCenter.default.addObserver(self, selector: #selector(resetNavigationButtons), names: notificationNames, object: nil) } var isVoiceOverOrSwitchControlRunning: Bool { UIAccessibility.isVoiceOverRunning || UIAccessibility.isSwitchControlRunning } } // MARK: DatePickerSheet Protocol protocol DatePickerSheet { func configureStackView(topView: UIView, pickerView: UIView) -> UIView } extension DatePickerSheet { /// Constructs a view with `topView` on top and `pickerView` on bottom /// - Parameter topView: A view to be shown above `pickerView` /// - Parameter pickerView: A view to be shown on the bottom func configureStackView(topView: UIView, pickerView: UIView) -> UIView { pickerView.translatesAutoresizingMaskIntoConstraints = false let pickerWrapperView = UIView() pickerWrapperView.addSubview(pickerView) let sideConstraints: [NSLayoutConstraint] = [ pickerView.leftAnchor.constraint(equalTo: pickerWrapperView.leftAnchor), pickerView.rightAnchor.constraint(equalTo: pickerWrapperView.rightAnchor) ] NSLayoutConstraint.activate([ pickerView.centerXAnchor.constraint(equalTo: pickerWrapperView.safeCenterXAnchor), pickerView.topAnchor.constraint(equalTo: pickerWrapperView.topAnchor), pickerView.bottomAnchor.constraint(equalTo: pickerWrapperView.bottomAnchor) ]) NSLayoutConstraint.activate(sideConstraints) let stackView = UIStackView(arrangedSubviews: [ topView, pickerWrapperView ]) stackView.axis = .vertical stackView.translatesAutoresizingMaskIntoConstraints = false return stackView } } extension DatePickerSheet where Self: UIViewController { /// Adds `topView` and `pickerView` to view hierarchy + standard styling for the view controller's view /// - Parameter topView: A view to show above `pickerView` (see `ChosenValueRow`) /// - Parameter pickerView: A view to show below the top view func setup(topView: UIView, pickerView: UIView) { WPStyleGuide.configureColors(view: view, tableView: nil) let stackView = configureStackView(topView: topView, pickerView: pickerView) view.addSubview(stackView) view.pinSubviewToSafeArea(stackView) } }
gpl-2.0
924199b783dbfa3686ce21ec4fafafc4
37.185185
249
0.693986
5.812544
false
false
false
false
dvor/Antidote
Antidote/AppCoordinator.swift
1
6454
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. import UIKit class AppCoordinator { fileprivate let window: UIWindow fileprivate var activeCoordinator: TopCoordinatorProtocol! fileprivate var theme: Theme init(window: UIWindow) { self.window = window let filepath = Bundle.main.path(forResource: "default-theme", ofType: "yaml")! let yamlString = try! NSString(contentsOfFile:filepath, encoding:String.Encoding.utf8.rawValue) as String theme = try! Theme(yamlString: yamlString) applyTheme(theme) } } // MARK: CoordinatorProtocol extension AppCoordinator: TopCoordinatorProtocol { func startWithOptions(_ options: CoordinatorOptions?) { let storyboard = UIStoryboard(name: "LaunchPlaceholderBoard", bundle: Bundle.main) window.rootViewController = storyboard.instantiateViewController(withIdentifier: "LaunchPlaceholderController") recreateActiveCoordinator(options: options) } func handleLocalNotification(_ notification: UILocalNotification) { activeCoordinator.handleLocalNotification(notification) } func handleInboxURL(_ url: URL) { activeCoordinator.handleInboxURL(url) } } extension AppCoordinator: RunningCoordinatorDelegate { func runningCoordinatorDidLogout(_ coordinator: RunningCoordinator, importToxProfileFromURL: URL?) { KeychainManager().deleteActiveAccountData() recreateActiveCoordinator() if let url = importToxProfileFromURL, let coordinator = activeCoordinator as? LoginCoordinator { coordinator.handleInboxURL(url) } } func runningCoordinatorDeleteProfile(_ coordinator: RunningCoordinator) { let userDefaults = UserDefaultsManager() let profileManager = ProfileManager() let name = userDefaults.lastActiveProfile! do { try profileManager.deleteProfileWithName(name) KeychainManager().deleteActiveAccountData() userDefaults.lastActiveProfile = nil recreateActiveCoordinator() } catch let error as NSError { handleErrorWithType(.deleteProfile, error: error) } } func runningCoordinatorRecreateCoordinatorsStack(_ coordinator: RunningCoordinator, options: CoordinatorOptions) { recreateActiveCoordinator(options: options, skipAuthorizationChallenge: true) } } extension AppCoordinator: LoginCoordinatorDelegate { func loginCoordinatorDidLogin(_ coordinator: LoginCoordinator, manager: OCTManager, password: String) { KeychainManager().toxPasswordForActiveAccount = password recreateActiveCoordinator(manager: manager, skipAuthorizationChallenge: true) } } // MARK: Private private extension AppCoordinator { func applyTheme(_ theme: Theme) { let linkTextColor = theme.colorForType(.LinkText) UIButton.appearance().tintColor = linkTextColor UISwitch.appearance().onTintColor = linkTextColor UINavigationBar.appearance().tintColor = linkTextColor } func recreateActiveCoordinator(options: CoordinatorOptions? = nil, manager: OCTManager? = nil, skipAuthorizationChallenge: Bool = false) { if let password = KeychainManager().toxPasswordForActiveAccount { let successBlock: (OCTManager) -> Void = { [unowned self] manager -> Void in self.activeCoordinator = self.createRunningCoordinatorWithManager(manager, options: options, skipAuthorizationChallenge: skipAuthorizationChallenge) } if let manager = manager { successBlock(manager) } else { let deleteActiveAccountAndRetry: (Void) -> Void = { [unowned self] in KeychainManager().deleteActiveAccountData() self.recreateActiveCoordinator(options: options, manager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) } guard let profileName = UserDefaultsManager().lastActiveProfile else { deleteActiveAccountAndRetry() return } let path = ProfileManager().pathForProfileWithName(profileName) guard let configuration = OCTManagerConfiguration.configurationWithBaseDirectory(path) else { deleteActiveAccountAndRetry() return } ToxFactory.createToxWithConfiguration(configuration, encryptPassword: password, successBlock: successBlock, failureBlock: { _ in log("Cannot create tox with configuration \(configuration)") deleteActiveAccountAndRetry() }) } } else { activeCoordinator = createLoginCoordinator(options) } } func createRunningCoordinatorWithManager(_ manager: OCTManager, options: CoordinatorOptions?, skipAuthorizationChallenge: Bool) -> RunningCoordinator { let coordinator = RunningCoordinator(theme: theme, window: window, toxManager: manager, skipAuthorizationChallenge: skipAuthorizationChallenge) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } func createLoginCoordinator(_ options: CoordinatorOptions?) -> LoginCoordinator { let coordinator = LoginCoordinator(theme: theme, window: window) coordinator.delegate = self coordinator.startWithOptions(options) return coordinator } }
mit
1f15e3af5da6cad20f81521158bfa150
38.595092
137
0.609544
6.572301
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
EclipseSoundscapes/Features/EclipseCenter/Cells/InfoCell.swift
1
4201
// // InfoCell.swift // EclipseSoundscapes // // Created by Arlindo Goncalves on 7/25/17. // // Copyright © 2017 Arlindo Goncalves. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see [http://www.gnu.org/licenses/]. // // For Contact email: [email protected] import Eureka final class InfoCell: Cell<EclipseEvent>, CellType { @IBOutlet weak var stackView: UIStackView! let eventLabel : UILabel = { let label = UILabel() label.font = UIFont.getDefautlFont(.condensedMedium, size: 15) label.textColor = .white label.textAlignment = .center label.numberOfLines = 0 return label }() let localTimeLabel : UILabel = { let label = UILabel() label.font = UIFont.getDefautlFont(.condensedMedium, size: 15) label.textColor = .white label.textAlignment = .center return label }() let timeLabel : UILabel = { let label = UILabel() label.font = UIFont.getDefautlFont(.condensedMedium, size: 15) label.textColor = .white label.textAlignment = .center return label }() required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func setup() { super.setup() selectionStyle = .none stackView.alignment = .center stackView.distribution = .fillEqually stackView.axis = .horizontal stackView.spacing = 5 stackView.addArrangedSubview(eventLabel) stackView.addArrangedSubview(localTimeLabel) stackView.addArrangedSubview(timeLabel) } func set(_ event: EclipseEvent?, atUserLocation: Bool = true) { guard let event = event else { return } let eventKey = atUserLocation ? "EclipsCenterEventName" : "EclipsCenterEventNameClosest" eventLabel.text = "\(event.name):" eventLabel.accessibilityLabel = localizedString(key: eventKey, arguments: event.name) let localTime = Date.convertUtcToLocalTime(dateString: event.time, dateFormat: .HH_mm_ss_S, outputFormat: .h_mm_ss_a) ?? "N/A" localTimeLabel.text = localTime localTimeLabel.accessibilityLabel = localizedString(key: "EclipsCenterLocalTime", arguments: localTime) timeLabel.text = event.time timeLabel.accessibilityLabel = localizedString(key: "EclipsCenterUniversalTime", arguments: event.time) } func toggleAccessibility(_ onOff: Bool, atUserLocation: Bool = true) { if !onOff { let titleKey = atUserLocation ? "EclipsCenterEventTitle" : "EclipsCenterEventClosestTitle" let hintKey = atUserLocation ? "EclipsCenterEventTitleHint" : "EclipsCenterEventClosestTitleHint" accessibilityLabel = localizedString(key: titleKey) accessibilityHint = localizedString(key: hintKey) } else { accessibilityLabel = nil accessibilityHint = nil } isAccessibilityElement = onOff eventLabel.isAccessibilityElement = onOff localTimeLabel.isAccessibilityElement = onOff timeLabel.isAccessibilityElement = onOff } } final class InfoRow: Row<InfoCell>, RowType { required init(tag: String?) { super.init(tag: tag) cellProvider = CellProvider<InfoCell>(nibName: "InfoCell") } }
gpl-3.0
9b856865bd6091a3e1db44e929f36a1e
35.842105
111
0.652619
4.833142
false
false
false
false
rickerbh/Moya
Moya/RxSwift/Moya+RxSwift.swift
1
2704
import Foundation import RxSwift import Alamofire /// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures. public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> { /// Current requests that have not completed or errored yet. /// Note: Do not access this directly. It is public only for unit-testing purposes (sigh). public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>() /// Initializes a reactive provider. override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, manager: Manager = Alamofire.Manager.sharedInstance) { super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure, manager: manager) } /// Designated request-making method. public func request(token: T) -> Observable<MoyaResponse> { let endpoint = self.endpoint(token) return deferred { [weak self] () -> Observable<MoyaResponse> in if let existingObservable = self!.inflightRequests[endpoint] { return existingObservable } let observable: Observable<MoyaResponse> = AnonymousObservable { observer in let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in if let error = error { observer.on(.Error(error as NSError)) } else { if let data = data { observer.on(.Next(MoyaResponse(statusCode: statusCode!, data: data, response: response))) } observer.on(.Completed) } } return AnonymousDisposable { if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = nil cancellableToken?.cancel() objc_sync_exit(weakSelf) } } } if let weakSelf = self { objc_sync_enter(weakSelf) weakSelf.inflightRequests[endpoint] = observable objc_sync_exit(weakSelf) } return observable } } }
mit
186f51f8352d88185eb6e82b78834092
47.285714
368
0.607618
5.955947
false
false
false
false
RedMadRobot/input-mask-ios
Source/InputMask/InputMask/Classes/Mask.swift
1
14069
// // Project «InputMask» // Created by Jeorge Taflanidi // import Foundation /** ### Mask Iterates over user input. Creates formatted strings from it. Extracts value specified by mask format. Provided mask format string is translated by the ```Compiler``` class into a set of states, which define the formatting and value extraction. - seealso: ```Compiler```, ```State``` and ```CaretString``` classes. */ public class Mask: CustomDebugStringConvertible, CustomStringConvertible { /** ### Result The end result of mask application to the user input string. */ public struct Result: CustomDebugStringConvertible, CustomStringConvertible { /** Formatted text with updated caret position. */ public let formattedText: CaretString /** Value, extracted from formatted text according to mask format. */ public let extractedValue: String /** Calculated absolute affinity value between the mask format and input text. */ public let affinity: Int /** User input is complete. */ public let complete: Bool public var debugDescription: String { return "FORMATTED TEXT: \(self.formattedText)\nEXTRACTED VALUE: \(self.extractedValue)\nAFFINITY: \(self.affinity)\nCOMPLETE: \(self.complete)" } public var description: String { return self.debugDescription } /** Produce a reversed ```Result``` with reversed formatted text (```CaretString```) and reversed extracted value. */ func reversed() -> Result { return Result( formattedText: self.formattedText.reversed(), extractedValue: self.extractedValue.reversed, affinity: affinity, complete: complete ) } } private let initialState: State private static var cache: [String: Mask] = [:] /** Constructor. - parameter format: mask format. - parameter customNotations: a list of custom rules to compile square bracket ```[]``` groups of format symbols. - returns: Initialized ```Mask``` instance. - throws: ```CompilerError``` if format string is incorrect. */ public required init(format: String, customNotations: [Notation] = []) throws { self.initialState = try Compiler(customNotations: customNotations).compile(formatString: format) } /** Constructor. Operates over own ```Mask``` cache where initialized ```Mask``` objects are stored under corresponding format key: ```[format : mask]``` - returns: Previously cached ```Mask``` object for requested format string. If such it doesn't exist in cache, the object is constructed, cached and returned. */ public class func getOrCreate(withFormat format: String, customNotations: [Notation] = []) throws -> Mask { if let cachedMask: Mask = cache[format] { return cachedMask } else { let mask: Mask = try Mask(format: format, customNotations: customNotations) cache[format] = mask return mask } } /** Check your mask format is valid. - parameter format: mask format. - parameter customNotations: a list of custom rules to compile square bracket ```[]``` groups of format symbols. - returns: ```true``` if this format coupled with custom notations will compile into a working ```Mask``` object. Otherwise ```false```. */ public class func isValid(format: String, customNotations: [Notation] = []) -> Bool { return nil != (try? self.init(format: format, customNotations: customNotations)) } /** Apply mask to the user input string. - parameter toText: user input string with current cursor position - parameter autocomplete: enable text autocompletion; `false` by default - returns: Formatted text with extracted value an adjusted cursor position. */ public func apply(toText text: CaretString) -> Result { let iterator: CaretStringIterator = self.makeIterator(forText: text) var affinity: Int = 0 var extractedValue: String = "" var modifiedString: String = "" var modifiedCaretPosition: Int = text.string.distanceFromStartIndex(to: text.caretPosition) var state: State = self.initialState var autocompletionStack = AutocompletionStack() var insertionAffectsCaret: Bool = iterator.insertionAffectsCaret() var deletionAffectsCaret: Bool = iterator.deletionAffectsCaret() var character: Character? = iterator.next() while let char: Character = character { if let next: Next = state.accept(character: char) { if deletionAffectsCaret { autocompletionStack.pushBack(next: state.autocomplete()) } state = next.state modifiedString += nil != next.insert ? String(next.insert!) : "" extractedValue += nil != next.value ? String(next.value!) : "" if next.pass { insertionAffectsCaret = iterator.insertionAffectsCaret() deletionAffectsCaret = iterator.deletionAffectsCaret() character = iterator.next() affinity += 1 } else { if insertionAffectsCaret && nil != next.insert { modifiedCaretPosition += 1 } affinity -= 1 } } else { if deletionAffectsCaret { modifiedCaretPosition -= 1 } insertionAffectsCaret = iterator.insertionAffectsCaret() deletionAffectsCaret = iterator.deletionAffectsCaret() character = iterator.next() affinity -= 1 } } while text.caretGravity.autocomplete && insertionAffectsCaret, let next: Next = state.autocomplete() { state = next.state modifiedString += nil != next.insert ? String(next.insert!) : "" extractedValue += nil != next.value ? String(next.value!) : "" if nil != next.insert { modifiedCaretPosition += 1 } } while text.caretGravity.autoskip && !autocompletionStack.isEmpty { let skip: Next = autocompletionStack.pop() if modifiedString.count == modifiedCaretPosition { if nil != skip.insert && skip.insert == modifiedString.last { modifiedString.removeLast() modifiedCaretPosition -= 1 } if nil != skip.value && skip.value == extractedValue.last { extractedValue.removeLast() } } else { if nil != skip.insert { modifiedCaretPosition -= 1 } } } return Result( formattedText: CaretString( string: modifiedString, caretPosition: modifiedString.startIndex(offsetBy: modifiedCaretPosition), caretGravity: text.caretGravity ), extractedValue: extractedValue, affinity: affinity, complete: self.noMandatoryCharactersLeftAfterState(state) ) } /** Generate placeholder. - returns: Placeholder string. */ public var placeholder: String { return self.appendPlaceholder(withState: self.initialState, placeholder: "") } /** Minimal length of the text inside the field to fill all mandatory characters in the mask. - returns: Minimal satisfying count of characters inside the text field. */ public var acceptableTextLength: Int { return self.countStates(ofTypes: [FixedState.self, FreeState.self, ValueState.self]) } /** Maximal length of the text inside the field. - returns: Total available count of mandatory and optional characters inside the text field. */ public var totalTextLength: Int { return self.countStates(ofTypes: [FixedState.self, FreeState.self, ValueState.self, OptionalValueState.self]) } /** Minimal length of the extracted value with all mandatory characters filled. - returns: Minimal satisfying count of characters in extracted value. */ public var acceptableValueLength: Int { var state: State? = self.initialState var length: Int = 0 while let s: State = state, !(state is EOLState) { if s is FixedState || s is ValueState { length += 1 } state = s.child } return length } /** Maximal length of the extracted value. - returns: Total available count of mandatory and optional characters for extracted value. */ public var totalValueLength: Int { var state: State? = self.initialState var length: Int = 0 while let s: State = state, !(state is EOLState) { if s is FixedState || s is ValueState || s is OptionalValueState { length += 1 } state = s.child } return length } public var debugDescription: String { return self.initialState.debugDescription } public var description: String { return self.debugDescription } func makeIterator(forText text: CaretString) -> CaretStringIterator { return CaretStringIterator(caretString: text) } /** While scanning through the input string in the `.apply(…)` method, the mask builds a graph of autocompletion steps. This graph accumulates the results of `.autocomplete()` calls for each consecutive `State`, acting as a `stack` of `Next` object instances. Each time the `State` returns `null` for its `.autocomplete()`, the graph resets empty. */ private struct AutocompletionStack { private var stack = [Next]() var isEmpty: Bool { stack.isEmpty } mutating func pushBack(next: Next?) { if let next: Next = next { stack.append(next) } else { stack.removeAll() } } mutating func pop() -> Next { return stack.removeLast() } mutating func removeAll() { stack.removeAll() } } } private extension Mask { func appendPlaceholder(withState state: State?, placeholder: String) -> String { guard let state: State = state else { return placeholder } if state is EOLState { return placeholder } if let state = state as? FixedState { return self.appendPlaceholder(withState: state.child, placeholder: placeholder + String(state.ownCharacter)) } if let state = state as? FreeState { return self.appendPlaceholder(withState: state.child, placeholder: placeholder + String(state.ownCharacter)) } if let state = state as? OptionalValueState { switch state.type { case .alphaNumeric: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "-") case .literal: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "a") case .numeric: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "0") case .custom(let char, _): return self.appendPlaceholder(withState: state.child, placeholder: placeholder + String(char)) } } if let state = state as? ValueState { switch state.type { case .alphaNumeric: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "-") case .literal: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "a") case .numeric: return self.appendPlaceholder(withState: state.child, placeholder: placeholder + "0") case .ellipsis: return placeholder case .custom(let char, _): return self.appendPlaceholder(withState: state.child, placeholder: placeholder + String(char)) } } return placeholder } func noMandatoryCharactersLeftAfterState(_ state: State) -> Bool { if (state is EOLState) { return true } else if let valueState = state as? ValueState { return valueState.isElliptical } else if (state is FixedState) { return false } else { return self.noMandatoryCharactersLeftAfterState(state.nextState()) } } func countStates(ofTypes stateTypes: [State.Type]) -> Int { var state: State? = self.initialState var length: Int = 0 while let s: State = state, !(state is EOLState) { for stateType in stateTypes { if type(of: s) == stateType { length += 1 } } state = s.child } return length } }
mit
7eb8da36875f06f60c47f805ec71d8aa
34.517677
155
0.56637
5.54395
false
false
false
false
joalbright/Gameboard
Gameboards.playground/Sources/Boards/Chess.swift
1
4900
import UIKit public struct Chess { public enum PieceType: String { case none = " " case rook1 = "♜" case knight1 = "♞" case bishop1 = "♝" case queen1 = "♛" case king1 = "♚" case pawn1 = "♟" case rook2 = "♖" case knight2 = "♘" case bishop2 = "♗" case queen2 = "♕" case king2 = "♔" case pawn2 = "♙" } public static var board: Grid { return Grid([ "♜♞♝♛♚♝♞♜".array(), 8 ✕ "♟", 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ "♙", "♖♘♗♕♔♗♘♖".array() ]) } public static let playerPieces = ["♜♞♝♛♚♝♞♜♟","♖♘♗♕♔♗♘♖♙"] public static func validateEmptyPath(_ s1: Square, _ s2: Square, _ grid: Grid) throws { let mRow = s2.0 - s1.0 let mCol = s2.1 - s1.1 let d1 = mRow == 0 ? 0 : mRow > 0 ? 1 : -1 let d2 = mCol == 0 ? 0 : mCol > 0 ? 1 : -1 var p1 = s1.0 + d1, p2 = s1.1 + d2 while p1 != s2.0 || p2 != s2.1 { guard grid[p1,p2] == EmptyPiece else { throw MoveError.blockedmove } p1 += d1 p2 += d2 } } public static func validateMove(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) throws -> Piece? { let mRow = s2.0 - s1.0 let mCol = s2.1 - s1.1 // let dR = mRow == 0 ? 0 : mRow > 0 ? 1 : -1 // let dC = mCol == 0 ? 0 : mCol > 0 ? 1 : -1 switch PieceType(rawValue: p1) ?? .none { case .bishop1, .bishop2: guard abs(mRow) == abs(mCol) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .king1, .king2: guard abs(mRow) < 2 && abs(mCol) < 2 else { throw MoveError.invalidmove } case .knight1, .knight2: guard (abs(mRow) == 2 && abs(mCol) == 1) || (abs(mRow) == 1 && abs(mCol) == 2) else { throw MoveError.invalidmove } case .pawn1: guard (abs(mCol) == 0 && p2 == EmptyPiece) || (abs(mCol) == 1 && mRow == 1 && p2 != EmptyPiece) else { throw MoveError.invalidmove } guard (mRow < 2 && mRow > 0) || (s1.0 == 1 && mRow == 2) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .pawn2: guard (abs(mCol) == 0 && p2 == EmptyPiece) || (abs(mCol) == 1 && mRow == -1 && p2 != EmptyPiece) else { throw MoveError.invalidmove } guard (mRow > -2 && mRow < 0) || (s1.0 == 6 && mRow == -2) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .queen1, .queen2: guard mRow == 0 || mCol == 0 || abs(mRow) == abs(mCol) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .rook1, .rook2: guard mRow == 0 || mCol == 0 else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .none: throw MoveError.incorrectpiece } guard !hint else { return nil } let piece = grid[s2.0,s2.1] grid[s2.0,s2.1] = p1 // place my piece in target square grid[s1.0,s1.1] = EmptyPiece // remove my piece from original square return piece } } // Coordinates public let A8 = ("a",8), A7 = ("a",7), A6 = ("a",6), A5 = ("a",5), A4 = ("a",4), A3 = ("a",3), A2 = ("a",2), A1 = ("a",1) public let B8 = ("b",8), B7 = ("b",7), B6 = ("b",6), B5 = ("b",5), B4 = ("b",4), B3 = ("b",3), B2 = ("b",2), B1 = ("b",1) public let C8 = ("c",8), C7 = ("c",7), C6 = ("c",6), C5 = ("c",5), C4 = ("c",4), C3 = ("c",3), C2 = ("c",2), C1 = ("c",1) public let D8 = ("d",8), D7 = ("d",7), D6 = ("d",6), D5 = ("d",5), D4 = ("d",4), D3 = ("d",3), D2 = ("d",2), D1 = ("d",1) public let E8 = ("e",8), E7 = ("e",7), E6 = ("e",6), E5 = ("e",5), E4 = ("e",4), E3 = ("e",3), E2 = ("e",2), E1 = ("e",1) public let F8 = ("f",8), F7 = ("f",7), F6 = ("f",6), F5 = ("f",5), F4 = ("f",4), F3 = ("f",3), F2 = ("f",2), F1 = ("f",1) public let G8 = ("g",8), G7 = ("g",7), G6 = ("g",6), G5 = ("g",5), G4 = ("g",4), G3 = ("g",3), G2 = ("g",2), G1 = ("g",1) public let H8 = ("h",8), H7 = ("h",7), H6 = ("h",6), H5 = ("h",5), H4 = ("h",4), H3 = ("h",3), H2 = ("h",2), H1 = ("h",1)
apache-2.0
f46d960168fb230444ceacc1d5be947d
33.978102
145
0.412563
3.04254
false
false
false
false
omondigeno/ActionablePushMessages
Pods/MK/Sources/MaterialPulseView.swift
1
6054
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of MaterialKit nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit public class MaterialPulseView : MaterialView { /// A CAShapeLayer used in the pulse animation. public private(set) lazy var pulseLayer: CAShapeLayer = CAShapeLayer() /// Sets whether the scaling animation should be used. public lazy var pulseScale: Bool = true /// Enables and disables the spotlight effect. public var spotlight: Bool = false { didSet { if spotlight { pulseFill = false } } } /** Determines if the pulse animation should fill the entire view. */ public var pulseFill: Bool = false { didSet { if pulseFill { spotlight = false } } } /// The opcaity value for the pulse animation. public var pulseColorOpacity: CGFloat = 0.25 { didSet { updatePulseLayer() } } /// The color of the pulse effect. public var pulseColor: UIColor? { didSet { updatePulseLayer() } } /** A delegation method that is executed when the view has began a touch event. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event) let point: CGPoint = layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer) if true == layer.containsPoint(point) { let r: CGFloat = (width < height ? height : width) / 2 let f: CGFloat = 3 let v: CGFloat = r / f let d: CGFloat = 2 * f let s: CGFloat = 1.05 let t: CFTimeInterval = 0.25 if nil != pulseColor && 0 < pulseColorOpacity { MaterialAnimation.animationDisabled { self.pulseLayer.bounds = CGRectMake(0, 0, v, v) self.pulseLayer.position = point self.pulseLayer.cornerRadius = r / d self.pulseLayer.hidden = false } pulseLayer.addAnimation(MaterialAnimation.scale(pulseFill ? 3 * d : d, duration: t), forKey: nil) } if pulseScale { layer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } } } /** A delegation method that is executed when the view touch event is moving. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesMoved(touches, withEvent: event) if spotlight { let point: CGPoint = layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer) if layer.containsPoint(point) { MaterialAnimation.animationDisabled { self.pulseLayer.position = point } } } } /** A delegation method that is executed when the view touch event has ended. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesEnded(touches, withEvent: event) shrinkAnimation() } /** A delegation method that is executed when the view touch event has been cancelled. - Parameter touches: A set of UITouch objects. - Parameter event: A UIEvent object. */ public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { super.touchesCancelled(touches, withEvent: event) shrinkAnimation() } /** Prepares the view instance when intialized. When subclassing, it is recommended to override the prepareView method to initialize property values and other setup operations. The super.prepareView method should always be called immediately when subclassing. */ public override func prepareView() { super.prepareView() pulseColor = MaterialColor.white preparePulseLayer() } /// Prepares the pulseLayer property. internal func preparePulseLayer() { pulseLayer.hidden = true pulseLayer.zPosition = 1 visualLayer.addSublayer(pulseLayer) } /// Updates the pulseLayer when settings have changed. internal func updatePulseLayer() { pulseLayer.backgroundColor = pulseColor?.colorWithAlphaComponent(pulseColorOpacity).CGColor } /// Executes the shrink animation for the pulse effect. internal func shrinkAnimation() { let t: CFTimeInterval = 0.25 let s: CGFloat = 1 if nil != pulseColor && 0 < pulseColorOpacity { MaterialAnimation.animateWithDuration(t, animations: { self.pulseLayer.hidden = true }) pulseLayer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } if pulseScale { layer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil) } } }
apache-2.0
5a6fa7ad0c0d9e7af563f873eecc52fe
31.037037
101
0.731913
3.998679
false
false
false
false
googlemaps/maps-sdk-for-ios-samples
GoogleMaps-Swift/GoogleMapsSwiftDemos/Swift/Samples/MarkerEventsViewController.swift
1
2193
// Copyright 2020 Google LLC. All rights reserved. // // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under // the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF // ANY KIND, either express or implied. See the License for the specific language governing // permissions and limitations under the License. import GoogleMaps import UIKit final class MarkerEventsViewController: UIViewController { private lazy var mapView: GMSMapView = { let camera = GMSCameraPosition(latitude: -37.81969, longitude: 144.966085, zoom: 4) return GMSMapView(frame: .zero, camera: camera) }() private var melbourneMarker = GMSMarker( position: CLLocationCoordinate2D(latitude: -37.81969, longitude: 144.966085)) override func loadView() { let sydneyMarker = GMSMarker( position: CLLocationCoordinate2D(latitude: -33.8683, longitude: 151.2086)) sydneyMarker.map = mapView melbourneMarker.map = mapView mapView.delegate = self view = mapView } } extension MarkerEventsViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, markerInfoWindow marker: GMSMarker) -> UIView? { if marker == melbourneMarker { return UIImageView(image: UIImage(named: "Icon")) } return nil } func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker) -> Bool { // Animate to the marker CATransaction.begin() CATransaction.setAnimationDuration(3) let camera = GMSCameraPosition(target: marker.position, zoom: 8, bearing: 50, viewingAngle: 60) mapView.animate(to: camera) CATransaction.commit() // Melbourne marker has a InfoWindow so return false to allow markerInfoWindow to // fire. Also check that the marker isn't already selected so that the InfoWindow // doesn't close. if marker == melbourneMarker && mapView.selectedMarker != melbourneMarker { return false } return true } }
apache-2.0
4eeb22143af123b648c682b543ec2fef
34.95082
99
0.725946
4.421371
false
false
false
false
castial/HYAlertController
HYAlertControllerDemo/HYAlertControllerDemo/HYAlertController/HYAlertView.swift
2
2781
// // HYAlertView.swift // Quick-Start-iOS // // Created by work on 2016/11/4. // Copyright © 2016年 hyyy. All rights reserved. // import UIKit class HYAlertView: HYPickerView, DataPresenter { var actions: [HYAlertAction] = [] fileprivate var isShowCancelCell: Bool { return cancelAction != nil } override init(frame: CGRect) { super.init(frame: frame) if tableView.responds(to: #selector(setter: UITableViewCell.separatorInset)) { tableView.separatorInset = .zero } if tableView.responds(to: #selector(setter: UIView.layoutMargins)) { tableView.layoutMargins = .zero } tableView.delegate = self tableView.dataSource = self addSubview(tableView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - UITableViewDataSource extension HYAlertView: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return isShowCancelCell ? 2 : 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? actions.count : 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = HYAlertCell(style: .value1, reuseIdentifier: HYAlertCell.ID) if indexPath.section == 0 { cell.action = actions[indexPath.row] } else { cell.cancelAction = cancelAction } return cell } } // MARK: - UITableViewDelegate extension HYAlertView: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return section == 1 ? 10 : 0.1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return HYAlertCell.cellHeight } func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)) { cell.separatorInset = .zero } if cell.responds(to: #selector(setter: UIView.layoutMargins)) { cell.layoutMargins = .zero } } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { let action = actions[indexPath.row] action.myHandler(action) } else { if let cancelAction = cancelAction { cancelAction.myHandler(cancelAction) } } delegate?.clickItemHandler() } }
mit
995d754d7aaf0420a539d3096df23a15
29.195652
112
0.639669
4.814558
false
false
false
false
bkmunar/firefox-ios
Client/Frontend/Reader/ReaderModeUtils.swift
1
4351
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation struct ReaderModeUtils { static let DomainPrefixesToSimplify = ["www.", "mobile.", "m.", "blog."] static func simplifyDomain(domain: String) -> String { for prefix in DomainPrefixesToSimplify { if domain.hasPrefix(prefix) { return domain.substringFromIndex(advance(domain.startIndex, count(prefix))) } } return domain } static func generateReaderContent(readabilityResult: ReadabilityResult, initialStyle: ReaderModeStyle) -> String? { if let stylePath = NSBundle.mainBundle().pathForResource("Reader", ofType: "css") { if let css = NSString(contentsOfFile: stylePath, encoding: NSUTF8StringEncoding, error: nil) { if let tmplPath = NSBundle.mainBundle().pathForResource("Reader", ofType: "html") { if let tmpl = NSMutableString(contentsOfFile: tmplPath, encoding: NSUTF8StringEncoding, error: nil) { tmpl.replaceOccurrencesOfString("%READER-CSS%", withString: css as String, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-STYLE%", withString: initialStyle.encode(), options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-DOMAIN%", withString: simplifyDomain(readabilityResult.domain), options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-URL%", withString: readabilityResult.url, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-TITLE%", withString: readabilityResult.title, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-CREDITS%", withString: readabilityResult.credits, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%READER-CONTENT%", withString: readabilityResult.content, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) tmpl.replaceOccurrencesOfString("%WEBSERVER-BASE%", withString: WebServer.sharedInstance.base, options: NSStringCompareOptions.allZeros, range: NSMakeRange(0, tmpl.length)) return tmpl as String } } } } return nil } static func isReaderModeURL(url: NSURL) -> Bool { if let scheme = url.scheme, host = url.host, path = url.path { return scheme == "http" && host == "localhost" && path == "/reader-mode/page" } return false } static func decodeURL(url: NSURL) -> NSURL? { if ReaderModeUtils.isReaderModeURL(url) { if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false), queryItems = components.queryItems where queryItems.count == 1 { if let queryItem = queryItems.first as? NSURLQueryItem, value = queryItem.value { return NSURL(string: value) } } } return nil } static func encodeURL(url: NSURL?) -> NSURL? { let baseReaderModeURL: String = WebServer.sharedInstance.URLForResource("page", module: "reader-mode") if let absoluteString = url?.absoluteString { if let encodedURL = absoluteString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) { if let aboutReaderURL = NSURL(string: "\(baseReaderModeURL)?url=\(encodedURL)") { return aboutReaderURL } } } return nil } }
mpl-2.0
8810d14f869126033cdd8bc7f1bfd41c
49.604651
155
0.617789
5.70249
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/Views/TextField/TextFieldViewModel.swift
1
15255
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization import RxCocoa import RxRelay import RxSwift import ToolKit /// A view model for text field public class TextFieldViewModel { // MARK: - Type /// The trailing accessory view. /// Can potentially support, images, labels and even custom views public enum AccessoryContentType: Equatable { /// Image accessory view case badgeImageView(BadgeImageViewModel) /// Label accessory view case badgeLabel(BadgeViewModel) /// Empty accessory view case empty } public enum Focus: Equatable { public enum OffSource: Equatable { case returnTapped case endEditing case setup } case on case off(OffSource) var isOn: Bool { switch self { case .on: return true case .off: return false } } } struct Mode: Equatable { /// The title text let title: String /// The title text let subtitle: String /// The title color let titleColor: Color /// The border color let borderColor: Color /// The cursor color let cursorColor: Color init( isFocused: Bool, shouldShowHint: Bool, caution: Bool, hint: String, title: String, subtitle: String ) { self.subtitle = subtitle if shouldShowHint, !hint.isEmpty { self.title = hint borderColor = caution ? .warning : .destructive titleColor = caution ? .warning : .destructive cursorColor = caution ? .warning : .destructive } else { self.title = title titleColor = .descriptionText if isFocused { borderColor = .primaryButton cursorColor = .primaryButton } else { borderColor = .mediumBorder cursorColor = .mediumBorder } } } } private typealias LocalizedString = LocalizationConstants.TextField // MARK: Properties /// The state of the text field public var state: Observable<State> { stateRelay.asObservable() } /// Should text field gain / drop focus public let focusRelay = BehaviorRelay<Focus>(value: .off(.setup)) public var focus: Driver<Focus> { focusRelay .asDriver() .distinctUntilChanged() } /// The content type of the `UITextField` var contentType: Driver<UITextContentType?> { contentTypeRelay .asDriver() .distinctUntilChanged() } /// The keyboard type of the `UITextField` var keyboardType: Driver<UIKeyboardType> { keyboardTypeRelay .asDriver() .distinctUntilChanged() } /// The isSecureTextEntry of the `UITextField` var isSecure: Driver<Bool> { isSecureRelay .asDriver() .distinctUntilChanged() } /// The color of the content (.mutedText, .textFieldText) var textColor: Driver<UIColor> { textColorRelay.asDriver() } /// A text to display below the text field in case of an error var mode: Driver<Mode> { Driver .combineLatest( focus, showHintIfNeededRelay.asDriver(), hintRelay.asDriver(), cautionRelay.asDriver(), titleRelay.asDriver(), subtitleRelay.asDriver() ) .map { focus, shouldShowHint, hint, caution, title, subtitle in Mode( isFocused: focus.isOn, shouldShowHint: shouldShowHint, caution: caution, hint: hint, title: title, subtitle: subtitle ) } .distinctUntilChanged() } public let isEnabledRelay = BehaviorRelay<Bool>(value: true) var isEnabled: Observable<Bool> { isEnabledRelay.asObservable() } /// The placeholder of the text-field public let placeholderRelay: BehaviorRelay<NSAttributedString> var placeholder: Driver<NSAttributedString> { placeholderRelay.asDriver() } var autocapitalizationType: Observable<UITextAutocapitalizationType> { autocapitalizationTypeRelay.asObservable() } /// A relay for accessory content type let accessoryContentTypeRelay = BehaviorRelay<AccessoryContentType>(value: .empty) var accessoryContentType: Observable<AccessoryContentType> { accessoryContentTypeRelay .distinctUntilChanged() } /// The original (initial) content of the text field public let originalTextRelay = BehaviorRelay<String?>(value: nil) var originalText: Observable<String?> { originalTextRelay .map { $0?.trimmingCharacters(in: .whitespaces) } .distinctUntilChanged() } /// Streams events when the accessory is being tapped public var tap: Signal<Void> { tapRelay.asSignal() } /// Streams events when the accessory is being tapped public let tapRelay = PublishRelay<Void>() /// The content of the text field public let textRelay = BehaviorRelay<String>(value: "") public var text: Observable<String> { textRelay .map { $0.trimmingCharacters(in: .whitespaces) } .distinctUntilChanged() } /// The content of the title field public let titleRelay: BehaviorRelay<String> public let subtitleRelay: BehaviorRelay<String> let titleFont = UIFont.main(.medium, 14) let subtitleFont = UIFont.main(.medium, 12) let textFont = UIFont.main(.medium, 16) let showHintIfNeededRelay = BehaviorRelay(value: false) /// Used for equality private var internalText: String? private let autocapitalizationTypeRelay: BehaviorRelay<UITextAutocapitalizationType> private let keyboardTypeRelay: BehaviorRelay<UIKeyboardType> private let contentTypeRelay: BehaviorRelay<UITextContentType?> private let isSecureRelay = BehaviorRelay(value: false) private let textColorRelay = BehaviorRelay<UIColor>(value: .textFieldText) private let hintRelay = BehaviorRelay<String>(value: "") private let cautionRelay = BehaviorRelay<Bool>(value: false) private let stateRelay = BehaviorRelay<State>(value: .empty) private let disposeBag = DisposeBag() // MARK: - Injected let returnKeyType: UIReturnKeyType let validator: TextValidating let formatter: TextFormatting let textMatcher: TextMatchValidatorAPI? let type: TextFieldType let accessibility: Accessibility let messageRecorder: MessageRecording // MARK: - Setup public init( with type: TextFieldType, accessibilitySuffix: String? = nil, returnKeyType: UIReturnKeyType = .done, validator: TextValidating, formatter: TextFormatting = TextFormatterFactory.alwaysCorrect, textMatcher: TextMatchValidatorAPI? = nil, messageRecorder: MessageRecording ) { self.messageRecorder = messageRecorder self.formatter = formatter self.validator = validator self.textMatcher = textMatcher self.type = type let placeholder = NSAttributedString( string: type.placeholder, attributes: [ .foregroundColor: UIColor.textFieldPlaceholder, .font: textFont ] ) autocapitalizationTypeRelay = BehaviorRelay(value: type.autocapitalizationType) placeholderRelay = BehaviorRelay(value: placeholder) titleRelay = BehaviorRelay(value: type.title) subtitleRelay = BehaviorRelay(value: "") contentTypeRelay = BehaviorRelay(value: type.contentType) keyboardTypeRelay = BehaviorRelay(value: type.keyboardType) isSecureRelay.accept(type.isSecure) if let suffix = accessibilitySuffix { accessibility = type.accessibility.with(idSuffix: ".\(suffix)") } else { accessibility = type.accessibility } self.returnKeyType = returnKeyType originalText .compactMap { $0 } .bindAndCatch(to: textRelay) .disposed(by: disposeBag) text .bindAndCatch(to: validator.valueRelay) .disposed(by: disposeBag) text .subscribe(onNext: { [weak self] text in // we update the changes of the text to our internalText property // for equality purposes self?.internalText = text }) .disposed(by: disposeBag) let matchState: Observable<TextValidationState> if let textMatcher = textMatcher { matchState = textMatcher.validationState } else { matchState = .just(.valid) } Observable .combineLatest( matchState, validator.validationState, text.asObservable() ) .map { matchState, validationState, text in State( matchState: matchState, validationState: validationState, text: text ) } .bindAndCatch(to: stateRelay) .disposed(by: disposeBag) state .map { $0.hint ?? "" } .bindAndCatch(to: hintRelay) .disposed(by: disposeBag) state .map(\.isCautioning) .bindAndCatch(to: cautionRelay) .disposed(by: disposeBag) } public func set(next: TextFieldViewModel) { focusRelay .filter { $0 == .off(.returnTapped) } .map { _ in .on } .bindAndCatch(to: next.focusRelay) .disposed(by: disposeBag) } func textFieldDidEndEditing() { ensureIsOnMainQueue() DispatchQueue.main.async { self.focusRelay.accept(.off(.endEditing)) self.showHintIfNeededRelay.accept(true) } } func textFieldShouldReturn() -> Bool { ensureIsOnMainQueue() DispatchQueue.main.async { self.focusRelay.accept(.off(.returnTapped)) } return true } func textFieldShouldBeginEditing() -> Bool { ensureIsOnMainQueue() DispatchQueue.main.async { self.focusRelay.accept(.on) } return true } /// Should be called upon editing the text field func textFieldEdited(with value: String) { messageRecorder.record("Text field \(type.debugDescription) edited") textRelay.accept(value) showHintIfNeededRelay.accept(type.showsHintWhileTyping) } func editIfNecessary(_ text: String, operation: TextInputOperation) -> TextFormattingSource { let processResult = formatter.format(text, operation: operation) switch processResult { case .formatted(to: let processedText), .original(text: let processedText): textFieldEdited(with: processedText) } return processResult } } // MARK: - State extension TextFieldViewModel { /// A state of a single text field public enum State { /// Valid state - validation is passing case valid(value: String) /// Valid state - validation is passing, user may /// need to be informed of more information case caution(value: String, reason: String?) /// Empty field case empty /// Mismatch error case mismatch(reason: String?) /// Invalid state - validation is not passing. case invalid(reason: String?) var hint: String? { switch self { case .invalid(reason: let reason), .mismatch(reason: let reason), .caution(value: _, reason: let reason): return reason default: return nil } } public var isCautioning: Bool { switch self { case .caution: return true default: return false } } public var isEmpty: Bool { switch self { case .empty: return true default: return false } } var isInvalid: Bool { switch self { case .invalid: return true default: return false } } var isMismatch: Bool { switch self { case .mismatch: return true default: return false } } /// Returns the text value if there is a valid value public var value: String? { switch self { case .valid(value: let value), .caution(value: let value, reason: _): return value default: return nil } } /// Returns whether or not the currenty entry is valid public var isValid: Bool { switch self { case .valid: return true default: return false } } /// Reducer for possible validation states init(matchState: TextValidationState, validationState: TextValidationState, text: String) { guard !text.isEmpty else { self = .empty return } switch (matchState, validationState, text) { case (.valid, .valid, let text): self = .valid(value: text) case (.invalid(reason: let reason), _, text): self = .mismatch(reason: reason) case (_, .invalid(reason: let reason), _), (_, .blocked(reason: let reason), _): self = .invalid(reason: reason) case (_, .conceivable(reason: let reason), let text): self = .caution(value: text, reason: reason) default: self = .invalid(reason: nil) } } } } extension TextFieldViewModel: Equatable { public static func == (lhs: TextFieldViewModel, rhs: TextFieldViewModel) -> Bool { lhs.internalText == rhs.internalText } } // MARK: - Equatable (Lossy - only the state, without associated values) extension TextFieldViewModel.State: Equatable { public static func == ( lhs: TextFieldViewModel.State, rhs: TextFieldViewModel.State ) -> Bool { switch (lhs, rhs) { case (.valid, .valid), (.mismatch, .mismatch), (.invalid, .invalid), (.empty, .empty): return true default: return false } } }
lgpl-3.0
97b9ede2afdc5d978381ef47e8cb7eaf
28.619417
99
0.567654
5.469344
false
false
false
false
huonw/swift
test/SILGen/super_init_refcounting.swift
1
4151
// RUN: %target-swift-emit-silgen %s | %FileCheck %s class Foo { init() {} init(_ x: Foo) {} init(_ x: Int) {} } class Bar: Foo { // CHECK-LABEL: sil hidden @$S22super_init_refcounting3BarC{{[_0-9a-zA-Z]*}}fc // CHECK: bb0([[INPUT_SELF:%.*]] : $Bar): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Bar } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store [[INPUT_SELF]] to [init] [[PB_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[ORIG_SELF_UP:%.*]] = upcast [[ORIG_SELF]] // CHECK-NOT: copy_value [[ORIG_SELF_UP]] // CHECK: [[SUPER_INIT:%[0-9]+]] = function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF_UP]]) // CHECK: [[NEW_SELF_DOWN:%.*]] = unchecked_ref_cast [[NEW_SELF]] // CHECK: store [[NEW_SELF_DOWN]] to [init] [[PB_SELF_BOX]] override init() { super.init() } } extension Foo { // CHECK-LABEL: sil hidden @$S22super_init_refcounting3FooC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Foo } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: [[ORIG_SELF:%.*]] = load [take] [[PB_SELF_BOX]] // CHECK-NOT: copy_value [[ORIG_SELF]] // CHECK: [[SUPER_INIT:%.*]] = class_method // CHECK: [[NEW_SELF:%.*]] = apply [[SUPER_INIT]]([[ORIG_SELF]]) // CHECK: store [[NEW_SELF]] to [init] [[PB_SELF_BOX]] convenience init(x: Int) { self.init() } } class Zim: Foo { var foo = Foo() // CHECK-LABEL: sil hidden @$S22super_init_refcounting3ZimC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Zang: Foo { var foo: Foo override init() { foo = Foo() super.init() } // CHECK-LABEL: sil hidden @$S22super_init_refcounting4ZangC{{[_0-9a-zA-Z]*}}fc // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: function_ref @$S22super_init_refcounting3FooCACycfc : $@convention(method) (@owned Foo) -> @owned Foo } class Bad: Foo { // Invalid code, but it's not diagnosed till DI. We at least shouldn't // crash on it. override init() { super.init(self) } } class Good: Foo { let x: Int // CHECK-LABEL: sil hidden @$S22super_init_refcounting4GoodC{{[_0-9a-zA-Z]*}}fc // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var Good } // CHECK: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK: [[PB_SELF_BOX:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK: store %0 to [init] [[PB_SELF_BOX]] // CHECK: [[SELF_OBJ:%.*]] = load_borrow [[PB_SELF_BOX]] // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[SELF_OBJ]] : $Good, #Good.x // CHECK: assign {{.*}} to [[X_ADDR]] : $*Int // CHECK: [[SELF_OBJ:%.*]] = load [take] [[PB_SELF_BOX]] : $*Good // CHECK: [[SUPER_OBJ:%.*]] = upcast [[SELF_OBJ]] : $Good to $Foo // CHECK: [[BORROWED_SUPER:%.*]] = begin_borrow [[SUPER_OBJ]] // CHECK: [[DOWNCAST_BORROWED_SUPER:%.*]] = unchecked_ref_cast [[BORROWED_SUPER]] : $Foo to $Good // CHECK: [[X_ADDR:%.*]] = ref_element_addr [[DOWNCAST_BORROWED_SUPER]] : $Good, #Good.x // CHECK: [[X:%.*]] = load [trivial] [[X_ADDR]] : $*Int // CHECK: end_borrow [[BORROWED_SUPER]] from [[SUPER_OBJ]] // CHECK: [[SUPER_INIT:%.*]] = function_ref @$S22super_init_refcounting3FooCyACSicfc : $@convention(method) (Int, @owned Foo) -> @owned Foo // CHECK: apply [[SUPER_INIT]]([[X]], [[SUPER_OBJ]]) override init() { x = 10 super.init(x) } }
apache-2.0
b7d831781fd119925ec9c0ee9106616c
41.793814
149
0.543002
3.210363
false
false
false
false
kysonyangs/ysbilibili
ysbilibili/Classes/HomePage/View/ZHNhomePageArchiveCollectionViewCell.swift
1
3030
// // ZHNhomePageArchiveCollectionViewCell.swift // zhnbilibili // // Created by 张辉男 on 17/1/13. // Copyright © 2017年 zhn. All rights reserved. // import UIKit class ZHNhomePageArchiveCollectionViewCell: YSNormalBaseCell { override var statusModel: YSItemDetailModel? { didSet { intialStatus() if let play = statusModel?.play { playLabel.text = play.returnShowString() } if let danmuku = statusModel?.danmaku { danmukuLabel.text = danmuku.returnShowString() } } } // MARK - 懒加载控件 lazy var playIconImageView: UIImageView = { let playIconImageView = UIImageView() playIconImageView.contentMode = .center playIconImageView.image = UIImage(named: "misc_playCount_new")?.ysTintColor( UIColor.lightGray) return playIconImageView }() lazy var playLabel: UILabel = { let playLabel = UILabel() playLabel.font = UIFont.systemFont(ofSize: 11) playLabel.textColor = UIColor.lightGray return playLabel }() lazy var danmukuIconImageView: UIImageView = { let danmukuIconImageView = UIImageView() danmukuIconImageView.contentMode = .center danmukuIconImageView.image = UIImage(named: "misc_danmakuCount_new")?.ysTintColor( UIColor.lightGray) return danmukuIconImageView }() lazy var danmukuLabel: UILabel = { let danmukuLabel = UILabel() danmukuLabel.font = UIFont.systemFont(ofSize: 11) danmukuLabel.textColor = UIColor.lightGray return danmukuLabel }() // MARK - life cycle override init(frame: CGRect) { super.init(frame: frame) titleLabel.backgroundColor = UIColor.clear self.addSubview(playIconImageView) self.addSubview(playLabel) self.addSubview(danmukuIconImageView) self.addSubview(danmukuLabel) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() playIconImageView.snp.makeConstraints { (make) in make.left.equalTo(contentImageView.snp.left) make.top.equalTo(titleLabel.snp.bottom) make.size.equalTo(CGSize(width: 20, height: 20)) } playLabel.snp.makeConstraints { (make) in make.left.equalTo(playIconImageView.snp.right).offset(5) make.centerY.equalTo(playIconImageView) } danmukuIconImageView.snp.makeConstraints { (make) in make.left.equalTo(contentImageView.snp.centerX) make.centerY.equalTo(playIconImageView) make.size.equalTo(playIconImageView.snp.size) } danmukuLabel.snp.makeConstraints { (make) in make.centerY.equalTo(playIconImageView) make.left.equalTo(danmukuIconImageView.snp.right).offset(5) } } }
mit
27150f0b07d42ff2b205dc225bdec865
32.831461
109
0.637662
4.97686
false
false
false
false
wuzer/douyuTV
douyuTV/douyuTV/View/RecommendGameView.swift
1
2415
// // RecommendGameView.swift // douyuTV // // Created by Jefferson on 2016/10/25. // Copyright © 2016年 Jefferson. All rights reserved. // import UIKit private let KItemEdgeInset: CGFloat = 10 private let KGameCellIdentify = "KGameCellIdentify" class RecommendGameView: UIView { var anchorGroups: [BaseModel]? { didSet { collectionView.reloadData() } } fileprivate lazy var collectionView: UICollectionView = { let flowLayout = UICollectionViewFlowLayout() flowLayout.itemSize = CGSize(width: 80, height: 90) flowLayout.minimumLineSpacing = 0 flowLayout.minimumInteritemSpacing = 0 flowLayout.scrollDirection = .horizontal let collectionView: UICollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flowLayout) collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.register(GameViewCell.self, forCellWithReuseIdentifier: KGameCellIdentify) collectionView.backgroundColor = UIColor.white collectionView.contentInset = UIEdgeInsets(top: 0, left: KItemEdgeInset, bottom: 0, right: KItemEdgeInset) return collectionView }() override init(frame: CGRect) { super.init(frame: frame) setupSubViews() self.backgroundColor = UIColor.orange } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: set UI extension RecommendGameView { fileprivate func setupSubViews() { addSubview(collectionView) } } // MARK: UICollectionViewDataSource extension RecommendGameView : UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return anchorGroups?.count ?? 0 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: KGameCellIdentify, for: indexPath) as! GameViewCell // cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.orange : UIColor.red let anchor = anchorGroups?[indexPath.item] cell.anchor = anchor return cell } }
mit
b59812f2f4352c9d9b32e208ed3ec5c4
30.736842
126
0.681177
5.519451
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/Utils/Array+SectionModel.swift
1
1281
// // Array+SectionModel.swift // Drrrible // // Created by Suyeol Jeon on 09/05/2017. // Copyright © 2017 StyleShare Inc. All rights reserved. // import RxDataSources extension Array where Element: SectionModelType { subscript(indexPath: IndexPath) -> Element.Item { get { return self[indexPath.section].items[indexPath.item] } mutating set { self.update(section: indexPath.section) { items in items[indexPath.item] = newValue } } } mutating func insert(newElement: Element.Item, at indexPath: IndexPath) { self.update(section: indexPath.section) { items in items.insert(newElement, at: indexPath.item) } } @discardableResult mutating func remove(at indexPath: IndexPath) -> Element.Item { return self.update(section: indexPath.section) { items in return items.remove(at: indexPath.item) } } mutating func replace(section: Int, items: [Element.Item]) { self[section] = Element.init(original: self[section], items: items) } private mutating func update<T>(section: Int, mutate: (inout [Element.Item]) -> T) -> T { var items = self[section].items let value = mutate(&items) self[section] = Element.init(original: self[section], items: items) return value } }
mit
0695a5764957ccfdc9be8d050fab2d80
26.826087
91
0.675781
3.867069
false
false
false
false
someoneAnyone/Nightscouter
Common/Extensions/Double-Extension.swift
1
3904
// // ApplicationExtensions.swift // Nightscout // // Created by Peter Ina on 5/18/15. // Copyright (c) 2015 Peter Ina. All rights reserved. // import Foundation public extension Range { var randomInt: Int { get { var offset = 0 if (lowerBound as! Int) < 0 // allow negative ranges { offset = abs(lowerBound as! Int) } let mini = UInt32(lowerBound as! Int + offset) let maxi = UInt32(upperBound as! Int + offset) return Int(mini + arc4random_uniform(maxi - mini)) - offset } } } public extension MgdlValue { var toMmol: Double { get{ return (self / 18) } } var toMgdl: Double { get{ return floor(self * 18) } } internal var mgdlFormatter: NumberFormatter { let numberFormat = NumberFormatter() numberFormat.numberStyle = .none return numberFormat } var formattedForMgdl: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mgdlFormatter.string(from: NSNumber(value: self))! } internal var mmolFormatter: NumberFormatter { let numberFormat = NumberFormatter() numberFormat.numberStyle = .decimal numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 return numberFormat } var formattedForMmol: String { if let reserved = ReservedValues(mgdl: self) { return reserved.description } return self.mmolFormatter.string(from: NSNumber(value: self.toMmol))! } } public extension MgdlValue { internal var bgDeltaFormatter: NumberFormatter { let numberFormat = NumberFormatter() numberFormat.numberStyle = .decimal numberFormat.positivePrefix = numberFormat.plusSign numberFormat.negativePrefix = numberFormat.minusSign return numberFormat } func formattedBGDelta(forUnits units: GlucoseUnit, appendString: String? = nil) -> String { var formattedNumber: String = "" switch units { case .mmol: let numberFormat = bgDeltaFormatter numberFormat.minimumFractionDigits = 1 numberFormat.maximumFractionDigits = 1 numberFormat.secondaryGroupingSize = 1 formattedNumber = numberFormat.string(from: NSNumber(value: self)) ?? "?" case .mgdl: formattedNumber = self.bgDeltaFormatter.string(from: NSNumber(value: self)) ?? "?" } var unitMarker: String = units.rawValue if let appendString = appendString { unitMarker = appendString } return formattedNumber + " " + unitMarker } var formattedForBGDelta: String { return self.bgDeltaFormatter.string(from: NSNumber(value: self))! } } public extension Double { var isInteger: Bool { return rint(self) == self } } public extension Double { mutating func millisecondsToSecondsTimeInterval() -> TimeInterval { let milliseconds = self/1000 let rounded = milliseconds.rounded(.toNearestOrAwayFromZero) return rounded } var inThePast: TimeInterval { return -self } mutating func toDateUsingMilliseconds() -> Date { let date = Date(timeIntervalSince1970:millisecondsToSecondsTimeInterval()) return date } } public extension TimeInterval { var millisecond: Double { return self*1000 } } extension Int { var msToSeconds: Double { return Double(self) / 1000 } }
mit
a173eae338a2c8325d4502262486f566
25.026667
95
0.594006
5.089961
false
false
false
false
silence0201/Swift-Study
GuidedTour/08Enumerations.playground/Contents.swift
1
3090
//: Playground - noun: a place where people can play enum CompassPoint{ case north case south case east case west } enum Planet{ case mercury,venus,earth,mars,jupiter,saturn,uranus,neptune } var directionToHead = CompassPoint.west directionToHead = .east // Swich switch directionToHead{ case .north: print("Lots of planets have a north") case .south: print("Watch out for penguins") case .east: print("Where the sun rises") case .west: print("Where the skies are blue") } let somePlanet = Planet.earth switch somePlanet { case .earth: print("Mostly Harmless") default: print("Not a safe place for humans") } // 关联值 enum Barcode{ case upc(Int,Int,Int,Int) case qrCode(String) } var profuctBarcode = Barcode.upc(8, 85909, 51226, 3) profuctBarcode = .qrCode("ABVCXSSDF") switch profuctBarcode { case .upc(let numberSystem,let manufactu,let profuct,let check): print("UPC:\(numberSystem) \(manufactu) \(profuct) \(check)") case .qrCode(let produceCode): print("QR Code:\(produceCode)") } profuctBarcode = Barcode.upc(8, 85909, 51226, 3) switch profuctBarcode { case let .upc(numberSystem, manufacturer, product, check): print("UPC : \(numberSystem), \(manufacturer), \(product), \(check).") case let .qrCode(productCode): print("QR code: \(productCode).") } // Raw Value enum ASCLLControlCharacter: Character{ case tab = "\t" case lineFeed = "\n" case carriageReturn = "\r" } // Implicitly Assigned Raw Values enum PlanetRaw: Int{ case mercury = 1,venus, earth, mars, jupiter, saturn, uranus, neptune } let earthsOrdewr = PlanetRaw.earth.rawValue print(earthsOrdewr) enum CompassPointRaw: String{ case north, south, east, west } let sunsetDirection = CompassPointRaw.west.rawValue print(sunsetDirection) // init With Raw Value let possiblePlanet = PlanetRaw(rawValue: 7) let positionToFind = PlanetRaw(rawValue: 11) if let somePlanet = positionToFind{ switch somePlanet { case .earth: print("Mostly harmless") default: print("Not a safe place for humans") } }else{ print("Error") } // 递归枚举 enum ArithmeticExpression{ case number(Int) indirect case addition(ArithmeticExpression,ArithmeticExpression) indirect case multiplication(ArithmeticExpression,ArithmeticExpression) } indirect enum ArithmeticExpression2 { case number(Int) case addition(ArithmeticExpression2, ArithmeticExpression2) case multiplication(ArithmeticExpression2, ArithmeticExpression2) } let five = ArithmeticExpression.number(5) let four = ArithmeticExpression.number(4) let sum = ArithmeticExpression.addition(five, four) let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2)) func evaluate(_ expression: ArithmeticExpression) -> Int { switch expression { case .number(let value): return value case let .addition(lhs, rhs): return evaluate(lhs) + evaluate(rhs) case let .multiplication(lhs, rhs): return evaluate(lhs) * evaluate(rhs) } } print(evaluate(product))
mit
ab4c4df7df8df6a09621c5ea008e0f21
23.220472
86
0.717165
3.859473
false
false
false
false
cliffpanos/True-Pass-iOS
iOSApp/CheckIn/Primary Controllers/PassesViewController.swift
1
11067
// // PassesViewController.swift // True Pass // // Created by Cliff Panos on 4/1/17. // Copyright © 2017 Clifford Panos. All rights reserved. // import UIKit import CoreData class PassesNavigationController: UINavigationController { } class PassesViewController: ManagedViewController, UISearchBarDelegate, UISearchResultsUpdating { @IBOutlet weak var tableView: UITableView! var searchDisplay = UISearchController(searchResultsController: nil) var searchBar: UISearchBar! var filtered = [TPPass]() var selectedIndexPath: IndexPath? override func viewDidLoad() { super.viewDidLoad() searchBar = searchDisplay.searchBar searchBar.placeholder = "Search by name" searchBar.autocapitalizationType = .words searchBar.searchBarStyle = .minimal searchBar.delegate = self searchDisplay.obscuresBackgroundDuringPresentation = false self.searchDisplay.searchResultsUpdater = self if #available(iOS 11, *) { navigationController?.navigationBar.prefersLargeTitles = true self.navigationItem.searchController = searchDisplay self.navigationItem.hidesSearchBarWhenScrolling = true navigationItem.largeTitleDisplayMode = .automatic } else { tableView.tableHeaderView = searchDisplay.searchBar } //Hide the search bar on initial launch //let offset = CGPoint(x: 0, y: (self.navigationController?.navigationBar.frame.height)!) //tableView.setContentOffset(offset, animated: true) //Make the tableView editable from the Navigation Bar navigationItem.leftBarButtonItem = self.editButtonItem //3D Touch Peek & Pop if self.traitCollection.forceTouchCapability == .available { registerForPreviewing(with: self, sourceView: self.view) } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if C.passes.count == 0 { switchToGuestGettingStarted() } //self.navigationItem.leftBarButtonItem?.isEnabled = tableView.visibleCells.count != 0 tableView.reloadData() //TODO FIX THIS if !(SplitViewController.instance?.isCollapsed ?? true) && selectedIndexPath == nil { print("Autoselecting row 0") let indexZero = IndexPath(row: 0, section: 0) self.selectedIndexPath = indexZero tableView.selectRow(at: indexZero, animated: true, scrollPosition: .none) self.performSegue(withIdentifier: "toPassDetail", sender: tableView.cellForRow(at: indexZero)) } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) guard let indexPath = selectedIndexPath else { return } if SplitViewController.isShowingDetail { tableView.selectRow(at: indexPath, animated: true, scrollPosition: .middle) } } override func setEditing(_ editing: Bool, animated: Bool) { super.setEditing(editing, animated: animated) self.tableView.setEditing(editing, animated: animated) } //MARK: - Navigation-related items func dismissKeyboard() { self.view.endEditing(true) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.text = "" dismissKeyboard() } //MARK: - Handle search bar and search controller fileprivate func isSearching() -> Bool { return searchDisplay.isActive && !(searchDisplay.searchBar.text ?? "").isEmpty } func updateSearchResults(for searchController: UISearchController) { let text = searchBar.text?.lowercased() ?? "" filtered = C.passes.filter { ($0.name).lowercased().contains(text) } tableView.reloadData() } } //MARK: - TableView Delegation and Prototype Cell Implementation ----------------------------- extension PassesViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "passCell", for: indexPath) as! PassCell let pass = isSearching() ? filtered[indexPath.row] : C.passes[indexPath.row] cell.decorate(for: pass) return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return isSearching() ? filtered.count : C.passes.count } func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool { return false } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return !isSearching() } func tableView(_ tableView: UITableView, willBeginEditingRowAt indexPath: IndexPath) { self.navigationController?.setEditing(true, animated: true) } func tableView(_ tableView: UITableView, didEndEditingRowAt indexPath: IndexPath?) { self.navigationController?.setEditing(false, animated: true) } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { let revokeAction = UITableViewRowAction(style: .destructive, title: "Revoke") { _, indexPath in self.tableView(self.tableView, commit: .delete, forRowAt: indexPath) } return [revokeAction] } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { switch editingStyle { case .delete: showDestructiveAlert("Confirm Revocation", message: "Permanently revoke this pass?", destructiveTitle: "Revoke", popoverSetup: nil, withStyle: .alert, forDestruction: { _ in let row = indexPath.row; let section = indexPath.section let relevantPasses = self.isSearching() ? self.filtered : C.passes let pass = relevantPasses[row] let sameCellSelectedAsPresented = indexPath == self.selectedIndexPath if PassManager.delete(pass: pass) { if let index = C.passes.index(of: pass) { C.passes.remove(at: index) self.tableView.deleteRows(at: [indexPath], with: .fade) } else { tableView.reloadData() } } else { return } guard (row - 1 < relevantPasses.count - 1 && row - 1 >= 0) || (row < relevantPasses.count - 1 && row >= 0) else { self.switchToGuestGettingStarted() return } guard sameCellSelectedAsPresented else { print(1); return } guard SplitViewController.isShowingDetail else { print(2); return } let newIndexPath = IndexPath(row: (row - 1 < relevantPasses.count - 1 && row - 1 >= 0) ? row - 1 : row, section: section) tableView.selectRow(at: newIndexPath, animated: true, scrollPosition: .middle) let cell = tableView.cellForRow(at: newIndexPath) self.performSegue(withIdentifier: "toPassDetail", sender: cell) }) default: return } } func switchToGuestGettingStarted() { (self.navigationController!.tabBarController! as! RootViewController).switchToGuestRootController(withIdentifier: "passInfoViewController") } //Segue preparation for when a UITableViewCell is pressed override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let cell = sender as? PassCell{ let embedder = (segue.destination as! UINavigationController).viewControllers.first! as! PassDetailEmbedderController let indexPath = tableView.indexPathForRow(at: cell.center)! self.selectedIndexPath = indexPath embedder.pass = isSearching() ? filtered[indexPath.row] : C.passes[indexPath.row] } searchDisplay.dismiss(animated: true, completion: nil) } } class PassCell: UITableViewCell { var pass: TPPass! var contactTextView = ContactView() @IBOutlet weak var nameTitle: UILabel! @IBOutlet weak var startTime: UILabel! @IBOutlet weak var fullContactView: ContactView! func decorate(for pass: TPPass) { self.pass = pass self.nameTitle.text = pass.name guard let start = pass.startDate else { self.startTime.text = "No Start Date & Time" return } let text = C.format(date: start as Date) let components = text.components(separatedBy: ",") if components.count >= 3 { self.startTime.text = "\(components[0]) at\(components[2])" } else { self.startTime.text = C.format(date: start as Date) } fullContactView.setupContactView(forData: pass.imageData as Data?, andName: pass.name) } override func setSelected(_ selected: Bool, animated: Bool) { self.backgroundColor = selected ? UIColor.groupTableViewBackground : UIColor.white } override func setHighlighted(_ highlighted: Bool, animated: Bool) { self.backgroundColor = highlighted ? UIColor.groupTableViewBackground : UIColor.white } } //MARK: - 3D Touch Peek & Pop Implementation extension PassesViewController: UIViewControllerPreviewingDelegate { func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? { let cellPosition = tableView.convert(location, from: self.view) guard let indexPath = tableView.indexPathForRow(at: cellPosition) else { return nil } let rect = self.view.convert(tableView.cellForRow(at: indexPath)!.frame, from: self.tableView) previewingContext.sourceRect = rect let pdvc = C.storyboard.instantiateViewController(withIdentifier: "passDetailNavigationController") as! PassDetailNavigationController (pdvc.viewControllers.first! as! PassDetailEmbedderController).pass = isSearching() ? filtered[indexPath.row] : C.passes[indexPath.row] return pdvc } func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) { //searchDisplay.dismiss(animated: true) SplitViewController.instance?.showDetailViewController(viewControllerToCommit, sender: nil) //self.navigationController?.pushViewController(viewControllerToCommit, animated: true) } }
apache-2.0
8530685781147c4027ff19d5e1955b5f
35.76412
185
0.638804
5.451232
false
false
false
false
bitboylabs/selluv-ios
selluv-ios/Pods/XCGLogger/Sources/XCGLogger/Destinations/FileDestination.swift
12
7480
// // FileDestination.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2014-06-06. // Copyright © 2014 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // // MARK: - FileDestination /// A standard destination that outputs log details to a file open class FileDestination: BaseDestination { // MARK: - Properties /// Logger that owns the destination object open override var owner: XCGLogger? { didSet { if owner != nil { openFile() } else { closeFile() } } } /// The dispatch queue to process the log on open var logQueue: DispatchQueue? = nil /// FileURL of the file to log to open var writeToFileURL: URL? = nil { didSet { openFile() } } /// File handle for the log file internal var logFileHandle: FileHandle? = nil /// Option: whether or not to append to the log file if it already exists internal var shouldAppend: Bool /// Option: if appending to the log file, the string to output at the start to mark where the append took place internal var appendMarker: String? // MARK: - Life Cycle public init(owner: XCGLogger? = nil, writeToFile: Any, identifier: String = "", shouldAppend: Bool = false, appendMarker: String? = "-- ** ** ** --") { self.shouldAppend = shouldAppend self.appendMarker = appendMarker if writeToFile is NSString { writeToFileURL = URL(fileURLWithPath: writeToFile as! String) } else if writeToFile is URL { writeToFileURL = writeToFile as? URL } else { writeToFileURL = nil } super.init(owner: owner, identifier: identifier) if owner != nil { openFile() } } deinit { // close file stream if open closeFile() } // MARK: - File Handling Methods /// Open the log file for writing. /// /// - Parameters: None /// /// - Returns: Nothing /// private func openFile() { guard let owner = owner else { return } if logFileHandle != nil { closeFile() } if let writeToFileURL = writeToFileURL { let fileManager: FileManager = FileManager.default let fileExists: Bool = fileManager.fileExists(atPath: writeToFileURL.path) if !shouldAppend || !fileExists { fileManager.createFile(atPath: writeToFileURL.path, contents: nil, attributes: nil) } do { logFileHandle = try FileHandle(forWritingTo: writeToFileURL) if fileExists && shouldAppend { logFileHandle?.seekToEndOfFile() if let appendMarker = appendMarker, let encodedData = "\(appendMarker)\n".data(using: String.Encoding.utf8) { _try({ self.logFileHandle?.write(encodedData) }, catch: { (exception: NSException) in owner._logln("Objective-C Exception occurred: \(exception)", level: .error) }) } } } catch let error as NSError { owner._logln("Attempt to open log file for \(fileExists && shouldAppend ? "appending" : "writing") failed: \(error.localizedDescription)", level: .error) logFileHandle = nil return } owner.logAppDetails(selectedDestination: self) let logDetails = LogDetails(level: .info, date: Date(), message: "XCGLogger " + (fileExists && shouldAppend ? "appending" : "writing") + " log to: " + writeToFileURL.absoluteString, functionName: "", fileName: "", lineNumber: 0, userInfo: XCGLogger.Constants.internalUserInfo) owner._logln(logDetails.message, level: logDetails.level) if owner.destination(withIdentifier: identifier) == nil { processInternal(logDetails: logDetails) } } } /// Close the log file. /// /// - Parameters: None /// /// - Returns: Nothing /// private func closeFile() { logFileHandle?.closeFile() logFileHandle = nil } /// Rotate the log file, storing the existing log file in the specified location. /// /// - Parameters: /// - archiveToFile: FileURL or path (as String) to where the existing log file should be rotated to. /// /// - Returns: /// - true: Log file rotated successfully. /// - false: Error rotating the log file. /// @discardableResult open func rotateFile(to archiveToFile: Any) -> Bool { var archiveToFileURL: URL? = nil if archiveToFile is NSString { archiveToFileURL = URL(fileURLWithPath: archiveToFile as! String) } else if archiveToFile is URL { archiveToFileURL = archiveToFile as? URL } else { return false } if let archiveToFileURL = archiveToFileURL, let writeToFileURL = writeToFileURL { let fileManager: FileManager = FileManager.default guard !fileManager.fileExists(atPath: archiveToFileURL.path) else { return false } closeFile() haveLoggedAppDetails = false do { try fileManager.moveItem(atPath: writeToFileURL.path, toPath: archiveToFileURL.path) } catch let error as NSError { openFile() owner?._logln("Unable to rotate file \(writeToFileURL.path) to \(archiveToFileURL.path): \(error.localizedDescription)", level: .error) return false } owner?._logln("Rotated file \(writeToFileURL.path) to \(archiveToFileURL.path)", level: .info) openFile() return true } return false } // MARK: - Overridden Methods /// Write the log to the log file. /// /// - Parameters: /// - logDetails: The log details. /// - message: Formatted/processed message ready for output. /// /// - Returns: Nothing /// open override func output(logDetails: LogDetails, message: String) { let outputClosure = { var logDetails = logDetails var message = message // Apply filters, if any indicate we should drop the message, we abort before doing the actual logging if self.shouldExclude(logDetails: &logDetails, message: &message) { return } self.applyFormatters(logDetails: &logDetails, message: &message) if let encodedData = "\(message)\n".data(using: String.Encoding.utf8) { _try({ self.logFileHandle?.write(encodedData) }, catch: { (exception: NSException) in self.owner?._logln("Objective-C Exception occurred: \(exception)", level: .error) }) } } if let logQueue = logQueue { logQueue.async(execute: outputClosure) } else { outputClosure() } } }
mit
e2ac190ebe717ad512125bc72a9f8eee
32.24
288
0.559433
5.28178
false
false
false
false
stripe/stripe-ios
StripeUICore/StripeUICore/Source/Elements/Form/FormElement.swift
1
2098
// // FormElement.swift // StripeUICore // // Created by Yuki Tokuhiro on 6/7/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import Foundation import UIKit /** The top-most, parent Element Element container. Displays its views in a vertical stack. Coordinates focus between its child Elements. */ @_spi(STP) public class FormElement: ContainerElement { weak public var delegate: ElementDelegate? lazy var formView: FormView = { return FormView(viewModel: viewModel) }() public let elements: [Element] public let style: Style public let theme: ElementsUITheme // MARK: - Style public enum Style { /// Default element styling in stack view case plain /// Form draws borders around each Element case bordered } // MARK: - ViewModel public struct ViewModel { let elements: [UIView] let bordered: Bool let theme: ElementsUITheme public init(elements: [UIView], bordered: Bool, theme: ElementsUITheme = .default) { self.elements = elements self.bordered = bordered self.theme = theme } } var viewModel: ViewModel { return ViewModel(elements: elements.map({ $0.view }), bordered: style == .bordered, theme: theme) } // MARK: - Initializer public convenience init(elements: [Element?], theme: ElementsUITheme = .default) { self.init(elements: elements, style: .plain, theme: theme) } public init(elements: [Element?], style: Style, theme: ElementsUITheme = .default) { self.elements = elements.compactMap { $0 } self.style = style self.theme = theme defer { self.elements.forEach { $0.delegate = self } } } public func setElements(_ elements: [Element], hidden: Bool, animated: Bool) { formView.setViews(elements.map({ $0.view }), hidden: hidden, animated: animated) } } // MARK: - Element extension FormElement: Element { public var view: UIView { return formView } }
mit
3605daed7c5f7a8196e27f29f29dcdcc
26.233766
105
0.626609
4.471215
false
false
false
false
spacedrabbit/vapor-todolist
vapor-todolist/Sources/App/main_old.swift
1
8612
// // main_old.swift // vapor-todolist // // Created by Louis Tur on 5/16/17. // // import Vapor import VaporSQLite import HTTP /* Note: This file is meant to be used to follow along with the older lessons. It is a standalone version and should not be considered (directly) as part of this project */ class Customer: NodeRepresentable { var customerId: Int! var firstName: String! var lastName: String! init(first: String, last: String, id: Int = -1) { self.firstName = first self.lastName = last self.customerId = id } // todo: look up the documentation changes for NodeRepresentable // why has this "context" parameter been added // note: this can be compared to the JSONable protocol we defined a long time ago func makeNode() throws -> Node { return try Node(node: ["first_name": self.firstName, "last_name": self.lastName]) } func makeNode(context: Context) throws -> Node { return try Node(node: self.makeNode(), in: context) } } // throwing this into a closure to remove errors about top-level declarations // renames 'drop' -> 'prop' for further clarity let closure: ()->() = { let prop = Droplet() // MARK: Adding in SQlite support and querying for version # try prop.addProvider(VaporSQLite.Provider.self) prop.get("version") { request in let result = try prop.database?.driver.raw("SELECT sqlite_version()") return try JSON(node: result) } // MARK: Basic Routing prop.get("hello") { request in return try JSON(node: [ "message" : "hello world!"]) } prop.get("names") { request in return try JSON(node: ["names" : ["Alex", "Mary", "John"]]) } // MARK: Returning Custom JSON // a GET endpoint without an identifier is treated as the root prop.get("customer") { request in let customer = Customer(first: "Louis", last: "Tur") return try JSON(node: customer) } // MARK: URL Paths // evaluates to /foo/bar prop.get("foo", "bar") { request in return "foo bar" } // MARK: Errors prop.get("error") { request in throw Abort.custom(status: .other(statusCode: 1001, reasonPhrase: "how'd you even get here?"), message: "Go back, it's a trap!") } prop.get("vapor") { request in return Response(redirect: "error") } // MARK: URL Parameters prop.get("users", ":id") { (request: Request) in guard let userId: Int = request.parameters["id"]?.int else { throw Abort.notFound } return "User Id: \(userId)" } // parameters can also be strongly typed and added to the closure? prop.get("customer", Int.self) { request, userId in return "User Id: \(userId)" } // we can even switch up these types // AND (bonus) it will allow for overloading a route with different typed parameters prop.get("customer", String.self) { request, userId in return "User Id: \(userId)" } // MARK: Groups // Groups logically group routes under a specific parent-level URL path prop.group("_tasks") { groups in // note: this assumes that the URL will be prefixed with /tasks // so having a redirect as "vapor" evaluates as "/tasks/vapor" // to use a route outside of this path, you need to give a relative // path like "/vapor" groups.get("all") { request in return Response(redirect: "/vapor") } groups.get("due_soon") { request in return Response(redirect: "/names") } } // MARK: POST Requests // You can inspect the request object for query params, header info, body info etc.. // the way this is tested is via postman, just be sure to set breakpoints ahead of time before you build/run prop.post("users") { request in guard let firstName = request.json?["first_name"]?.string, let lastName = request.json?["last_name"]?.string else { throw Abort.badRequest } let newUser = Customer(first: firstName, last: lastName) return try JSON(node: newUser) } // MARK: Inserting into SQLite // create an endpoint /customers/create for POST requests prop.post("customers", "create") { request in // look for our keys guard let first = request.json?["first_name"]?.string, let last = request.json?["last_name"]?.string else { throw Abort.badRequest } // raw sends in raw SQL queries... god I hope there is another option let result = try prop.database?.driver.raw("INSERT INTO Customer(firstName, lastName) VALUES(?,?)", [first, last]) // something must be returned. in this case it ends up being an empty array if all goes well. // otherwise we'll receive some useful error info to help debug return try JSON(node: result) } // MARK: Retrieving from SQLite prop.get("customers", "all") { request in var customers: [Customer] = [] // this is likely to return a number of results, but even if only 1 it will still get // returned as an array let result = try prop.database?.driver.raw("SELECT customerId,firstName,lastName FROM Customer;") guard let nodeArray = result?.nodeArray else { return try JSON(node: customers) } for node in nodeArray { let customer: Customer = Customer(first: node["firstName"]!.string!, last: node["lastName"]!.string!, id: node["customerId"]!.int!) customers.append(customer) } return try JSON(node: customers) } prop.get("customers") { request in guard let query = request.query?["name"]?.string else { throw Abort.badRequest } let result = try prop.database?.driver.raw("SELECT * from Customer WHERE firstName IS \"\(query)\"") return try JSON(node: result) } // MARK: - Validators - // MARK: Email // you get free email validators built into vapor prop.post("register") { request in guard let email: Valid<Email> = try request.data["email"]?.validated() else { throw Abort.custom(status: .notAcceptable, message: "Your email could not be validated") } return "Validated: \(email)" } // MARK: Unique Items prop.post("unique") { request in guard let inputCommaSeperated = request.data["input"]?.string else { throw Abort.badRequest } // This is saying the return object will be a unique array of string, generically // The input expected is a comma-seperated list of values let unique: Valid<Unique<[String]>> = try inputCommaSeperated.components(separatedBy: ",").validated() return "Validated Unique: \(unique)" } // MARK: Matching Keys prop.post("keys") { request in // "keyCode" here is the key looked for in the json body guard let keyCode = request.data["keyCode"]?.string else { throw Abort.badRequest } // we're validation on the value of keyCode against "Secret!!!" let key: Valid<Matches<String>> = try keyCode.validated(by: Matches("Secret!!!")) return "Validated \(key)" } // MARK: - Custom Validators prop.post("register") { request in guard let inputPassword = request.data["password"]?.string else { throw Abort.badRequest } // between 5-12 and not just alpha numeric (so, with special characters) // let password = try inputPassword.validated(by: !OnlyAlphanumeric.self && // Count.containedIn(low: 5, high: 12)) // let password: Valid<PasswordValidator> = try inputPassword.validated(by: PasswordValidator.self) // TODO: how does this work by simply calling .validated and saying the Valid object will be of type PasswordValidator let password: Valid<PasswordValidator> = try inputPassword.validated() // these two will return bools let passwordIsValid = inputPassword.passes(PasswordValidator.self) let isValid = try inputPassword.tested(by: PasswordValidator.self) return "Validated password: \(password)" } // MARK: - RandomUser prop.get("random_user") { request in let response = try prop.client.get("https://randomuser.me/api") guard let responseData = response.data["results"]?.array?[0] as? JSON else { throw Abort.badRequest } return responseData } // MARK: - Controllers - // "registering" this router // because this singleton obj can check its routes, this "registering" is really just // defering the prop.get code to another location. let controller = DemoTasksViewController() controller.addRoutes(drop: prop) // MARK: RESTful Controller //prop.resource("task", controller) prop.run() } as! () -> ()
mit
29927f23d1fa98fbceaa44b0e96dd406
30.778598
137
0.653855
4.198927
false
false
false
false
usiu/noticeboard
ios/NoticeBoard/Views/BoardTableAdapter.swift
1
6235
// // BoardTableAdapter.swift // NoticeBoard // // Created by Salama AB on 3/29/15. // Copyright (c) 2015 Salama AB. All rights reserved. // import UIKit import QuartzCore import Refresher class BoardTableAdapter: NSObject, UITableViewDelegate, UITableViewDataSource { class var TAG: String { get { return "BoardTableAdapter"} } let dataMngr = DataManager.sharedInstance; let tableView: UITableView; var currentFeed: Int { didSet { if currentFeed != oldValue { self.refresh(); } } } init(table: UITableView, feed: Int) { self.tableView = table; self.currentFeed = feed; super.init(); self.tableView.delegate = self; self.tableView.dataSource = self; } func addRefresher(callback: Bool -> Void) { self.tableView.addPullToRefreshWithAction({ self.refresh(fromServer: true) {(ok) in callback(ok); self.tableView.stopPullToRefresh(); }; }, withAnimator: BeatAnimator()); } func pullToRefresh() { self.tableView.startPullToRefresh(); } func refresh(fromServer: Bool = false, callback:(Bool->Void)? = nil) { if fromServer { dataMngr.fetchItems(self.currentFeed){ (status) in if let feed = self.dataMngr.getFeed(self.currentFeed) { var items = self.dataMngr.getItems(feed.id); Log.i(BoardTableAdapter.TAG, msg: "Feed '\(feed.title)' has loaded \(items.count) item(s)") } if status { self.tableView.reloadData(); } callback?(status); } } else { tableView.reloadData(); callback?(true); } } private func _getBoardItem(tableRow: Int) -> BoardItem? { let items = dataMngr.getItems(currentFeed); return items[tableRow / 2]; } func getSelectedItem() -> BoardItem? { if let idx = tableView.indexPathForSelectedRow() { return self._getBoardItem(idx.row); } return nil; } func clearSelection() { if let idx = tableView.indexPathForSelectedRow() { tableView.deselectRowAtIndexPath(idx, animated: true); } } func getFeedTitle() -> String? { if let feed = dataMngr.getFeed(currentFeed) { return feed.title; } return nil; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // even rows will be invisible if (indexPath.row % 2 == 1) { var separatorCell = tableView.dequeueReusableCellWithIdentifier("CardSeparator") as UITableViewCell; return separatorCell; } else { var cell = tableView.dequeueReusableCellWithIdentifier("CardCell") as CardCell return cell; } } func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { if indexPath.row % 2 != 1 { let card = cell as CardCell; if let item = self._getBoardItem(indexPath.row) { card.title.text = item.title; card.summary.text = item.summary; card.source.text = "\u{f09e} " + item.source!; if let timeAgo = item.date?.timeAgo(false) { card.date.text = "\u{f017} " + timeAgo; } if item.imageUrl != nil { card.photo.load(item.imageUrl!); } } } } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if indexPath.row % 2 != 1 { return 237; } else { return 15; } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { let items = dataMngr.getItems(currentFeed).count; let rows = (items * 2) - 1; // Invisiable items return rows; } } class BeatAnimator: PullToRefreshViewAnimator { private var layerLoader: CAShapeLayer = CAShapeLayer() init() { layerLoader.lineWidth = 4 layerLoader.strokeColor = UIColor.usiuBlue().CGColor; layerLoader.strokeEnd = 0 } func startAnimation() { var pathAnimationEnd = CABasicAnimation(keyPath: "strokeEnd") pathAnimationEnd.duration = 0.5 pathAnimationEnd.repeatCount = 100 pathAnimationEnd.autoreverses = true pathAnimationEnd.fromValue = 1 pathAnimationEnd.toValue = 0.8 self.layerLoader.addAnimation(pathAnimationEnd, forKey: "strokeEndAnimation") var pathAnimationStart = CABasicAnimation(keyPath: "strokeStart") pathAnimationStart.duration = 0.5 pathAnimationStart.repeatCount = 100 pathAnimationStart.autoreverses = true pathAnimationStart.fromValue = 0 pathAnimationStart.toValue = 0.2 self.layerLoader.addAnimation(pathAnimationStart, forKey: "strokeStartAnimation") } func stopAnimation() { self.layerLoader.removeAllAnimations() } func layoutLayers(superview: UIView) { if layerLoader.superlayer == nil { superview.layer.addSublayer(layerLoader) } var bezierPathLoader = UIBezierPath() bezierPathLoader.moveToPoint(CGPointMake(0, superview.frame.height - 3)) bezierPathLoader.addLineToPoint(CGPoint(x: superview.frame.width, y: superview.frame.height - 3)) layerLoader.path = bezierPathLoader.CGPath } func changeProgress(progress: CGFloat) { self.layerLoader.strokeEnd = progress } }
mit
653c8e398d201ac2b55e91af1f70f283
28.690476
125
0.559904
5.270499
false
false
false
false
dche/FlatColor
Sources/Hsb.swift
1
3926
// // FlatColor - Hsb.swift // // HSB color model. // // Copyright (c) 2017 The FlatColor authors. // Licensed under MIT License. // For `floor(:Float)`. #if os(Linux) import Glibc #else import simd #endif import FlatUtil import GLMath /// Color value in HSB color model. public struct Hsb: Color { public typealias InexactNumber = Float fileprivate var _hsba = vec4.zero public var hue: Float { get { return _hsba.x } set { _hsba.x = clamp(newValue, 0, Float.tau) } } public var saturation: Float { get { return _hsba.y } set { _hsba.y = clamp(newValue, 0, 1) } } public var brightness: Float { get { return _hsba.z } set { _hsba.z = clamp(newValue, 0, 1) } } public var alpha: Float { get { return _hsba.w } set { _hsba.w = clamp(newValue, 0, 1) } } fileprivate init (_ hsba: vec4) { self._hsba = clamp(hsba, vec4(0), vec4(Float.tau, 1, 1, 1)) } /// Constructs a HSB color. /// /// - note: Parameter `h` is expected in the range of `[0, 2π]`. public init (hue: Float, saturation: Float, brightness: Float, alpha: Float = 1) { self.init(vec4(hue, saturation, brightness, alpha)) } } // MARK: Color extension Hsb { public init (rgb: Rgb) { let h = rgb.hue let s = rgb.saturation let b = rgb.brightness _hsba = vec4(h, s, b, rgb.alpha) } public var rgbColor: Rgb { let h = self.hue let s = self.saturation let v = self.brightness if s.isZero { return Rgb(red: v, green: v, blue: v) } else { let hv = degrees(h) / 60 let hi = mod(floor(hv), 6) let f = hv - hi let p = v * (1 - s) let q = v * (1 - f * s) let t = v * (1 - (1 - f) * s) switch hi { case 0: return Rgb(red: v, green: t, blue: p) case 1: return Rgb(red: q, green: v, blue: p) case 2: return Rgb(red: p, green: v, blue: t) case 3: return Rgb(red: p, green: q, blue: v) case 4: return Rgb(red: t, green: p, blue: v) case 5: return Rgb(red: v, green: p, blue: q) default: fatalError("Unreachable!") } } } public var vector: vec4 { return self._hsba } } extension Hsb: Random { public init(withRng rng: inout Rng) { let h = rng.nextFloat() * Float.tau let s = rng.nextFloat() // TODO: Should be nextFloatClosed(). let b = rng.nextFloat() self.init(vec4(h, s, b, 1)) } } extension Hsb: CustomStringConvertible { public var description: String { return "Hsb(hue: \(self.hue), saturation: \(self.saturation), brightness: \(self.brightness), alpha: \(self.alpha))" } } extension Rgb { /// The hue of of a RGB color. public var hue: Float { let r = self.red let g = self.green let b = self.blue let mx = max(r, max(g, b)) let mn = min(r, min(g, b)) if mx ~== mn { return 0 } else { let c = (mx - mn).recip let deg: Float switch mx { case _ where mx == r: deg = mod(((g - b) * c), 6) case _ where mx == g: deg = ((b - r) * c) + 2 default: deg = ((r - g) * c) + 4 } return radians(mod((deg * 60 + 360), 360)) } } /// The saturation of a RGB color. public var saturation: Float { let r = self.red let g = self.green let b = self.blue let mx = max(r, max(g, b)) let mn = min(r, min(g, b)) if mx ~== mn { // gray. return 0 } else { return 1 - mn / mx } } /// The brightness of a RGB color. public var brightness: Float { return self.vector.rgb.max } }
mit
80262846183bac05994262a3ef0c9102
23.378882
124
0.503949
3.48579
false
false
false
false
laszlokorte/reform-swift
ReformApplication/ReformApplication/ForLoopInstructionDetailController.swift
1
2081
// // ForLoopInstructionDetailController.swift // Reform // // Created by Laszlo Korte on 06.10.15. // Copyright © 2015 Laszlo Korte. All rights reserved. // import Cocoa import ReformCore import ReformExpression class ForLoopInstructionDetailController : NSViewController, InstructionDetailController { @IBOutlet var errorLabel : NSTextField? @IBOutlet var countField : NSTextField? var stringifier : Stringifier? var parser : ((String) -> Result<ReformExpression.Expression, ShuntingYardError>)? var intend : (() -> ())? var error : String? { didSet { updateError() } } override var representedObject : Any? { didSet { updateLabel() } } override func viewDidLoad() { updateLabel() updateError() } func updateError() { if let error = error { errorLabel?.stringValue = error if let errorLabel = errorLabel { self.view.addSubview(errorLabel) } } else { errorLabel?.removeFromSuperview() } } func updateLabel() { guard let node = representedObject as? InstructionNode else { return } guard let instruction = node.instruction as? ForLoopInstruction else { return } guard let stringifier = stringifier else { return } countField?.stringValue = stringifier.stringFor(instruction.expression) ?? "" } @IBAction func onChange(_ sender: Any?) { guard let parser = parser, let string = countField?.stringValue, let intend = intend else { return } guard let node = representedObject as? InstructionNode else { return } switch parser(string) { case .success(let expr): node.replaceWith(ForLoopInstruction(expression: expr)) intend() case .fail(let err): print(err) } } }
mit
eef2276a9e676fce3f3b6b0bb28abbf0
22.370787
90
0.567788
5.213033
false
false
false
false
ccrama/Slide-iOS
Slide for Reddit/RealmDataWrappers.swift
1
39268
// // RealmDataWrappers.swift // Slide for Reddit // // Created by Carlos Crane on 1/26/17. // Copyright © 2017 Haptic Apps. All rights reserved. // import Foundation import RealmSwift import reddift class RealmDataWrapper { //Takes a Link from reddift and turns it into a Realm model static func linkToRSubmission(submission: Link) -> RSubmission { let flair = submission.linkFlairText.isEmpty ? submission.linkFlairCssClass : submission.linkFlairText var bodyHtml = submission.selftextHtml.replacingOccurrences(of: "<blockquote>", with: "<cite>").replacingOccurrences(of: "</blockquote>", with: "</cite>") bodyHtml = bodyHtml.replacingOccurrences(of: "<div class=\"md\">", with: "") var json: JSONDictionary? json = submission.baseJson var w: Int = 0 var h: Int = 0 var thumb = false //is thumbnail present var big = false //is big image present var lowq = false //is lq image present var burl: String = "" //banner url var turl: String = "" //thumbnail url var lqUrl: String = "" //lq banner url let previews = ((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["resolutions"] as? [Any]) let preview = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) var videoPreview = (((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["hls_url"] as? String) if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) } if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((json?["preview"] as? [String: Any])?["reddit_video_preview"] as? [String: Any])?["fallback_url"] as? String) } if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["variants"] as? [String: Any])?["mp4"] as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) } if (videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil) && json?["crosspost_parent_list"] != nil { videoPreview = (((((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["preview"] as? [String: Any])?["reddit_video_preview"] as? [String: Any])?["fallback_url"] as? String) } if (videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil) && json?["crosspost_parent_list"] != nil { videoPreview = (((((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) } if preview != nil && !(preview?.isEmpty())! { burl = (preview!.replacingOccurrences(of: "&amp;", with: "&")) w = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["width"] as? Int)! if w < 200 { big = false } else { h = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["height"] as? Int)! big = true } } let thumbnailType = ContentType.getThumbnailType(submission: submission) switch thumbnailType { case .NSFW: thumb = true turl = "nsfw" case .DEFAULT: thumb = true turl = "web" case .SELF, .NONE: thumb = false case .URL: thumb = true turl = submission.thumbnail.removingPercentEncoding ?? submission.thumbnail } let type = ContentType.getContentType(baseUrl: submission.url) if big { //check for low quality image if previews != nil && !(previews?.isEmpty)! { if submission.url != nil && type == .IMGUR { lqUrl = (submission.url?.absoluteString)! lqUrl = lqUrl.substring(0, length: lqUrl.lastIndexOf(".")!) + (SettingValues.lqLow ? "m" : "l") + lqUrl.substring(lqUrl.lastIndexOf(".")!, length: lqUrl.length - lqUrl.lastIndexOf(".")!) } else { let length = previews?.count if SettingValues.lqLow && length! >= 3 { lqUrl = ((previews?[1] as? [String: Any])?["url"] as? String)! } else if length! >= 4 { lqUrl = ((previews?[2] as? [String: Any])?["url"] as? String)! } else if length! >= 5 { lqUrl = ((previews?[length! - 1] as? [String: Any])?["url"] as? String)! } else { lqUrl = preview! } lowq = true } } } let rSubmission = RSubmission() do { try rSubmission.smallPreview = ((previews?.first as? [String: Any])?["url"] as? String)?.convertHtmlSymbols() ?? "" } catch { } rSubmission.subreddit_icon = ((json?["sr_detail"] as? [String: Any])?["icon_img"] as? String ?? ((json?["sr_detail"] as? [String: Any])?["community_icon"] as? String ?? "")) rSubmission.id = submission.getId() rSubmission.author = submission.author rSubmission.created = NSDate(timeIntervalSince1970: TimeInterval(submission.createdUtc)) rSubmission.isEdited = submission.edited > 0 rSubmission.edited = NSDate(timeIntervalSince1970: TimeInterval(submission.edited)) rSubmission.silver = ((json?["gildings"] as? [String: Any])?["gid_1"] as? Int) ?? 0 rSubmission.gold = ((json?["gildings"] as? [String: Any])?["gid_2"] as? Int) ?? 0 rSubmission.platinum = ((json?["gildings"] as? [String: Any])?["gid_3"] as? Int) ?? 0 rSubmission.htmlBody = bodyHtml rSubmission.subreddit = submission.subreddit rSubmission.archived = submission.archived rSubmission.locked = submission.locked do { try rSubmission.urlString = ((submission.url?.absoluteString) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.urlString = (submission.url?.absoluteString) ?? "" } rSubmission.urlString = rSubmission.urlString.removingPercentEncoding ?? rSubmission.urlString rSubmission.title = submission.title rSubmission.commentCount = submission.numComments rSubmission.saved = submission.saved rSubmission.stickied = submission.stickied rSubmission.visited = submission.visited rSubmission.bannerUrl = burl rSubmission.thumbnailUrl = turl rSubmission.thumbnail = thumb rSubmission.nsfw = submission.over18 rSubmission.banner = big rSubmission.lqUrl = String.init(htmlEncodedString: lqUrl) rSubmission.domain = submission.domain rSubmission.lQ = lowq rSubmission.score = submission.score rSubmission.flair = flair rSubmission.voted = submission.likes != .none rSubmission.upvoteRatio = submission.upvoteRatio rSubmission.vote = submission.likes == .up rSubmission.name = submission.id do { try rSubmission.videoPreview = (videoPreview ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoPreview = videoPreview ?? "" } do { try rSubmission.videoMP4 = ((((((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["variants"] as? [String: Any])?["mp4"] as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoMP4 = "" } if rSubmission.videoMP4 == "" { do { try rSubmission.videoMP4 = ((((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoMP4 = "" } } rSubmission.height = h rSubmission.width = w rSubmission.distinguished = submission.distinguished.type rSubmission.canMod = submission.canMod rSubmission.isSelf = submission.isSelf rSubmission.body = submission.selftext rSubmission.permalink = submission.permalink rSubmission.canMod = submission.canMod rSubmission.spoiler = submission.baseJson["spoiler"] as? Bool ?? false rSubmission.oc = submission.baseJson["is_original_content"] as? Bool ?? false rSubmission.removedBy = submission.baseJson["banned_by"] as? String ?? "" rSubmission.removalReason = submission.baseJson["ban_note"] as? String ?? "" rSubmission.removalNote = submission.baseJson["mod_note"] as? String ?? "" rSubmission.removed = !rSubmission.removedBy.isEmpty() rSubmission.cakeday = submission.baseJson["author_cakeday"] as? Bool ?? false rSubmission.hidden = submission.baseJson["hidden"] as? Bool ?? false for item in submission.baseJson["mod_reports"] as? [AnyObject] ?? [] { let array = item as! [Any] rSubmission.reports.append("\(array[0]): \(array[1])") } for item in submission.baseJson["user_reports"] as? [AnyObject] ?? [] { let array = item as! [Any] rSubmission.reports.append("\(array[0]): \(array[1])") } rSubmission.awards.removeAll() for item in submission.baseJson["all_awardings"] as? [AnyObject] ?? [] { if let award = item as? JSONDictionary { if award["icon_url"] != nil && award["count"] != nil { let name = award["name"] as? String ?? "" if name != "Silver" && name != "Gold" && name != "Platinum" { rSubmission.awards.append("\(award["icon_url"]!)*\(award["count"]!)") } } } } rSubmission.gallery.removeAll() for item in (submission.baseJson["gallery_data"] as? JSONDictionary)?["items"] as? [JSONDictionary] ?? [] { if let image = (submission.baseJson["media_metadata"] as? JSONDictionary)?[item["media_id"] as! String] as? JSONDictionary { if image["s"] != nil && (image["s"] as? JSONDictionary)?["u"] != nil { rSubmission.gallery.append((image["s"] as? JSONDictionary)?["u"] as! String) } } } rSubmission.pollOptions.removeAll() for item in (submission.baseJson["poll_data"] as? JSONDictionary)?["options"] as? [AnyObject] ?? [] { if let poll = item as? JSONDictionary { if poll["text"] != nil { let name = poll["text"] as? String ?? "" let amount = poll["vote_count"] as? Int ?? -1 rSubmission.pollOptions.append("\(name);\(amount)") } } } rSubmission.pollTotal = (submission.baseJson["poll_data"] as? JSONDictionary)?["total_vote_count"] as? Int ?? 0 rSubmission.gilded = rSubmission.silver + rSubmission.gold + rSubmission.platinum + rSubmission.awards.count > 0 rSubmission.approvedBy = submission.baseJson["approved_by"] as? String ?? "" rSubmission.approved = !rSubmission.approvedBy.isEmpty() if json?["crosspost_parent_list"] != nil { rSubmission.isCrosspost = true let sub = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["subreddit"] as? String ?? "" let author = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["author"] as? String ?? "" let permalink = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["permalink"] as? String ?? "" rSubmission.crosspostSubreddit = sub rSubmission.crosspostAuthor = author rSubmission.crosspostPermalink = permalink } return rSubmission } //Takes a Link from reddift and turns it into a Realm model static func updateSubmission(_ rSubmission: RSubmission, _ submission: Link) -> RSubmission { let flair = submission.linkFlairText.isEmpty ? submission.linkFlairCssClass : submission.linkFlairText var bodyHtml = submission.selftextHtml.replacingOccurrences(of: "<blockquote>", with: "<cite>").replacingOccurrences(of: "</blockquote>", with: "</cite>") bodyHtml = bodyHtml.replacingOccurrences(of: "<div class=\"md\">", with: "") var json: JSONDictionary? json = submission.baseJson var w: Int = 0 var h: Int = 0 var thumb = false //is thumbnail present var big = false //is big image present var lowq = false //is lq image present var burl: String = "" //banner url var turl: String = "" //thumbnail url var lqUrl: String = "" //lq banner url let previews = ((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["resolutions"] as? [Any]) let preview = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) var videoPreview = (((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["hls_url"] as? String) if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) } if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((json?["preview"] as? [String: Any])?["reddit_video_preview"] as? [String: Any])?["fallback_url"] as? String) } if videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil { videoPreview = (((((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["variants"] as? [String: Any])?["mp4"] as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) } if (videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil) && json?["crosspost_parent_list"] != nil { videoPreview = (((((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["preview"] as? [String: Any])?["reddit_video_preview"] as? [String: Any])?["fallback_url"] as? String) } if (videoPreview != nil && videoPreview!.isEmpty || videoPreview == nil) && json?["crosspost_parent_list"] != nil { videoPreview = (((((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) } if preview != nil && !(preview?.isEmpty())! { burl = (preview!.replacingOccurrences(of: "&amp;", with: "&")) w = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["width"] as? Int)! if w < 200 { big = false } else { h = (((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["source"] as? [String: Any])?["height"] as? Int)! big = true } } let thumbnailType = ContentType.getThumbnailType(submission: submission) switch thumbnailType { case .NSFW: thumb = true turl = "nsfw" case .DEFAULT: thumb = true turl = "web" case .SELF, .NONE: thumb = false case .URL: thumb = true turl = submission.thumbnail.removingPercentEncoding ?? submission.thumbnail } let type = ContentType.getContentType(baseUrl: submission.url) if big { //check for low quality image if previews != nil && !(previews?.isEmpty)! { if submission.url != nil && type == .IMGUR { lqUrl = (submission.url?.absoluteString)! lqUrl = lqUrl.substring(0, length: lqUrl.lastIndexOf(".")!) + (SettingValues.lqLow ? "m" : "l") + lqUrl.substring(lqUrl.lastIndexOf(".")!, length: lqUrl.length - lqUrl.lastIndexOf(".")!) } else { let length = previews?.count if SettingValues.lqLow && length! >= 3 { lqUrl = ((previews?[1] as? [String: Any])?["url"] as? String)! } else if length! >= 4 { lqUrl = ((previews?[2] as? [String: Any])?["url"] as? String)! } else if length! >= 5 { lqUrl = ((previews?[length! - 1] as? [String: Any])?["url"] as? String)! } else { lqUrl = preview! } lowq = true } } } rSubmission.awards.removeAll() for item in submission.baseJson["all_awardings"] as? [AnyObject] ?? [] { if let award = item as? JSONDictionary { if award["icon_url"] != nil && award["count"] != nil { let name = award["name"] as? String ?? "" if name != "Silver" && name != "Gold" && name != "Platinum" { rSubmission.awards.append("\(award["icon_url"]!)*\(award["count"]!)") } } } } rSubmission.gallery.removeAll() for item in (submission.baseJson["gallery_data"] as? JSONDictionary)?["items"] as? [JSONDictionary] ?? [] { if let image = (submission.baseJson["media_metadata"] as? JSONDictionary)?[item["media_id"] as! String] as? JSONDictionary { if image["s"] != nil && (image["s"] as? JSONDictionary)?["u"] != nil { rSubmission.gallery.append((image["s"] as? JSONDictionary)?["u"] as! String) } } } rSubmission.pollOptions.removeAll() for item in (submission.baseJson["poll_data"] as? JSONDictionary)?["options"] as? [AnyObject] ?? [] { if let poll = item as? JSONDictionary { if poll["text"] != nil { let name = poll["text"] as? String ?? "" let amount = poll["vote_count"] as? Int ?? -1 rSubmission.pollOptions.append("\(name);\(amount)") } } } rSubmission.pollTotal = (submission.baseJson["poll_data"] as? JSONDictionary)?["total_vote_count"] as? Int ?? 0 rSubmission.author = submission.author rSubmission.created = NSDate(timeIntervalSince1970: TimeInterval(submission.createdUtc)) rSubmission.isEdited = submission.edited > 0 rSubmission.edited = NSDate(timeIntervalSince1970: TimeInterval(submission.edited)) rSubmission.silver = ((submission.baseJson["gildings"] as? [String: Any])?["gid_1"] as? Int) ?? 0 rSubmission.gold = ((submission.baseJson["gildings"] as? [String: Any])?["gid_2"] as? Int) ?? 0 rSubmission.platinum = ((submission.baseJson["gildings"] as? [String: Any])?["gid_3"] as? Int) ?? 0 rSubmission.gilded = rSubmission.silver + rSubmission.gold + rSubmission.platinum + rSubmission.awards.count > 0 rSubmission.htmlBody = bodyHtml rSubmission.subreddit = submission.subreddit rSubmission.archived = submission.archived rSubmission.locked = submission.locked rSubmission.canMod = submission.canMod do { try rSubmission.urlString = ((submission.url?.absoluteString) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.urlString = (submission.url?.absoluteString) ?? "" } rSubmission.urlString = rSubmission.urlString.removingPercentEncoding ?? rSubmission.urlString rSubmission.title = submission.title rSubmission.commentCount = submission.numComments rSubmission.saved = submission.saved rSubmission.stickied = submission.stickied rSubmission.spoiler = submission.baseJson["spoiler"] as? Bool ?? false rSubmission.oc = submission.baseJson["is_original_content"] as? Bool ?? false rSubmission.visited = submission.visited rSubmission.bannerUrl = burl rSubmission.thumbnailUrl = turl rSubmission.thumbnail = thumb rSubmission.removedBy = submission.baseJson["banned_by"] as? String ?? "" rSubmission.removalReason = submission.baseJson["ban_note"] as? String ?? "" rSubmission.removalNote = submission.baseJson["mod_note"] as? String ?? "" rSubmission.hidden = submission.baseJson["hidden"] as? Bool ?? false rSubmission.removed = !rSubmission.removedBy.isEmpty() rSubmission.nsfw = submission.over18 rSubmission.banner = big rSubmission.lqUrl = String.init(htmlEncodedString: lqUrl) rSubmission.domain = submission.domain rSubmission.lQ = lowq rSubmission.score = submission.score rSubmission.flair = flair rSubmission.voted = submission.likes != .none rSubmission.upvoteRatio = submission.upvoteRatio rSubmission.vote = submission.likes == .up rSubmission.name = submission.id rSubmission.height = h rSubmission.width = w rSubmission.distinguished = submission.distinguished.type rSubmission.isSelf = submission.isSelf rSubmission.body = submission.selftext rSubmission.permalink = submission.permalink do { try rSubmission.videoPreview = (videoPreview ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoPreview = videoPreview ?? "" } do { try rSubmission.videoMP4 = ((((((((json?["preview"] as? [String: Any])?["images"] as? [Any])?.first as? [String: Any])?["variants"] as? [String: Any])?["mp4"] as? [String: Any])?["source"] as? [String: Any])?["url"] as? String) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoMP4 = "" } if rSubmission.videoMP4 == "" { do { try rSubmission.videoMP4 = ((((json?["media"] as? [String: Any])?["reddit_video"] as? [String: Any])?["fallback_url"] as? String) ?? "").convertHtmlSymbols() ?? "" } catch { rSubmission.videoMP4 = "" } } rSubmission.cakeday = submission.baseJson["author_cakeday"] as? Bool ?? false if json?["crosspost_parent_list"] != nil { rSubmission.isCrosspost = true let sub = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["subreddit"] as? String ?? "" let author = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["author"] as? String ?? "" let permalink = ((json?["crosspost_parent_list"] as? [Any])?.first as? [String: Any])?["permalink"] as? String ?? "" rSubmission.crosspostSubreddit = sub rSubmission.crosspostAuthor = author rSubmission.crosspostPermalink = permalink } rSubmission.reports.removeAll() for item in submission.baseJson["mod_reports"] as? [AnyObject] ?? [] { let array = item as! [Any] rSubmission.reports.append("\(array[0]): \(array[1])") } for item in submission.baseJson["user_reports"] as? [AnyObject] ?? [] { let array = item as! [Any] rSubmission.reports.append("\(array[0]): \(array[1])") } rSubmission.approvedBy = submission.baseJson["approved_by"] as? String ?? "" rSubmission.approved = !rSubmission.approvedBy.isEmpty() return rSubmission } static func friendToRealm(user: User) -> Object { let rFriend = RFriend() rFriend.name = user.name rFriend.friendSince = NSDate(timeIntervalSince1970: TimeInterval(user.date)) return rFriend } static func commentToRealm(comment: Thing, depth: Int) -> Object { if comment is Comment { return commentToRComment(comment: comment as! Comment, depth: depth) } else { return moreToRMore(more: comment as! More) } } //Takes a Comment from reddift and turns it into a Realm model static func commentToRComment(comment: Comment, depth: Int) -> RComment { let flair = comment.authorFlairText.isEmpty ? comment.authorFlairCssClass : comment.authorFlairText var bodyHtml = comment.bodyHtml.replacingOccurrences(of: "<blockquote>", with: "<cite>").replacingOccurrences(of: "</blockquote>", with: "</cite>") bodyHtml = bodyHtml.replacingOccurrences(of: "<div class=\"md\">", with: "") let rComment = RComment() let json = comment.baseJson rComment.id = comment.getId() rComment.author = comment.author rComment.created = NSDate(timeIntervalSince1970: TimeInterval(comment.createdUtc)) rComment.isEdited = comment.edited > 0 rComment.edited = NSDate(timeIntervalSince1970: TimeInterval(comment.edited)) rComment.silver = ((json["gildings"] as? [String: Any])?["gid_1"] as? Int) ?? 0 rComment.gold = ((json["gildings"] as? [String: Any])?["gid_2"] as? Int) ?? 0 rComment.platinum = ((json["gildings"] as? [String: Any])?["gid_3"] as? Int) ?? 0 rComment.gilded = rComment.silver + rComment.gold + rComment.platinum > 0 rComment.htmlText = bodyHtml rComment.subreddit = comment.subreddit rComment.submissionTitle = comment.submissionTitle rComment.saved = comment.saved rComment.body = comment.body rComment.removalReason = comment.baseJson["ban_note"] as? String ?? "" rComment.removalNote = comment.baseJson["mod_note"] as? String ?? "" rComment.removedBy = comment.baseJson["banned_by"] as? String ?? "" rComment.removed = !rComment.removedBy.isEmpty() rComment.approvedBy = comment.baseJson["approved_by"] as? String ?? "" rComment.approved = !rComment.approvedBy.isEmpty() rComment.sticky = comment.stickied rComment.flair = flair rComment.cakeday = comment.baseJson["author_cakeday"] as? Bool ?? false let richtextFlairs = (json["author_flair_richtext"] as? [Any]) if richtextFlairs != nil && richtextFlairs!.count > 0 { for flair in richtextFlairs! { if let flairDict = flair as? [String: Any] { if flairDict["e"] != nil && flairDict["e"] as! String == "emoji" { rComment.urlFlair = ((flairDict["u"] as? String) ?? "").decodeHTML().trimmed() } else if flairDict["e"] != nil && flairDict["e"] as! String == "text" { rComment.flair = ((flairDict["t"] as? String) ?? "").decodeHTML().trimmed() } } } } for item in comment.modReports { let array = item as! [Any] rComment.reports.append("\(array[0]): \(array[1])") } for item in comment.userReports { let array = item as! [Any] rComment.reports.append("\(array[0]): \(array[1])") } // TODO: - rComment.pinned = comment.pinned rComment.score = comment.score rComment.depth = depth rComment.canMod = comment.canMod rComment.linkid = comment.linkId rComment.archived = comment.archived rComment.distinguished = comment.distinguished.type rComment.controversiality = comment.controversiality rComment.voted = comment.likes != .none rComment.vote = comment.likes == .up rComment.name = comment.name rComment.parentId = comment.parentId rComment.scoreHidden = comment.scoreHidden rComment.permalink = "https://www.reddit.com" + comment.permalink return rComment } static func messageToRMessage(message: Message) -> RMessage { let title = message.baseJson["link_title"] as? String ?? "" var bodyHtml = message.bodyHtml.replacingOccurrences(of: "<blockquote>", with: "<cite>").replacingOccurrences(of: "</blockquote>", with: "</cite>") bodyHtml = bodyHtml.replacingOccurrences(of: "<div class=\"md\">", with: "") let rMessage = RMessage() rMessage.htmlBody = bodyHtml rMessage.name = message.name rMessage.id = message.getId() rMessage.author = message.author rMessage.subreddit = message.subreddit rMessage.created = NSDate(timeIntervalSince1970: TimeInterval(message.createdUtc)) rMessage.isNew = message.new rMessage.linkTitle = title rMessage.context = message.context rMessage.wasComment = message.wasComment rMessage.subject = message.subject return rMessage } //Takes a More from reddift and turns it into a Realm model static func moreToRMore(more: More) -> RMore { let rMore = RMore() if more.getId().endsWith("_") { rMore.id = "more_\(NSUUID().uuidString)" } else { rMore.id = more.getId() } rMore.name = more.name rMore.parentId = more.parentId rMore.count = more.count for s in more.children { let str = RString() str.value = s rMore.children.append(str) } return rMore } } class RListing: Object { override class func primaryKey() -> String? { return "subreddit" } @objc dynamic var updated = NSDate(timeIntervalSince1970: 1) @objc dynamic var subreddit = "" @objc dynamic var comments = false let links = List<RSubmission>() } class RSubmission: Object { override class func primaryKey() -> String? { return "id" } @objc dynamic var id = "" @objc dynamic var name = "" @objc dynamic var author = "" @objc dynamic var created = NSDate(timeIntervalSince1970: 1) @objc dynamic var edited = NSDate(timeIntervalSince1970: 1) @objc dynamic var gilded = false @objc dynamic var gold = 0 @objc dynamic var silver = 0 @objc dynamic var platinum = 0 @objc dynamic var htmlBody = "" @objc dynamic var body = "" @objc dynamic var title = "" @objc dynamic var subreddit = "" @objc dynamic var archived = false @objc dynamic var locked = false @objc dynamic var hidden = false @objc dynamic var urlString = "" @objc dynamic var distinguished = "" @objc dynamic var videoPreview = "" @objc dynamic var videoMP4 = "" @objc dynamic var isCrosspost = false @objc dynamic var spoiler = false @objc dynamic var oc = false @objc dynamic var canMod = false @objc dynamic var crosspostAuthor = "" @objc dynamic var crosspostSubreddit = "" @objc dynamic var crosspostPermalink = "" @objc dynamic var cakeday = false @objc dynamic var subreddit_icon = "" var type: ContentType.CType { if isSelf { return .SELF } if url != nil { return ContentType.getContentType(baseUrl: url) } else { return .NONE } } var url: URL? { return URL.init(string: self.urlString) } var reports = List<String>() var awards = List<String>() var gallery = List<String>() var pollOptions = List<String>() @objc dynamic var pollTotal = -1 @objc dynamic var removedBy = "" @objc dynamic var removed = false @objc dynamic var approvedBy = "" @objc dynamic var approved = false @objc dynamic var removalReason = "" @objc dynamic var removalNote = "" @objc dynamic var isEdited = false @objc dynamic var commentCount = 0 @objc dynamic var saved = false @objc dynamic var stickied = false @objc dynamic var visited = false @objc dynamic var isSelf = false @objc dynamic var permalink = "" @objc dynamic var bannerUrl = "" @objc dynamic var thumbnailUrl = "" @objc dynamic var smallPreview = "" @objc dynamic var lqUrl = "" @objc dynamic var lQ = false @objc dynamic var thumbnail = false @objc dynamic var banner = false @objc dynamic var nsfw = false @objc dynamic var score = 0 @objc dynamic var upvoteRatio: Double = 0 @objc dynamic var flair = "" @objc dynamic var domain = "" @objc dynamic var voted = false @objc dynamic var height = 0 @objc dynamic var width = 0 @objc dynamic var vote = false let comments = List<RComment>() func getId() -> String { return id } var likes: VoteDirection { if voted { if vote { return .up } else { return .down } } return .none } } class RMessage: Object { override class func primaryKey() -> String? { return "id" } @objc dynamic var id = "" @objc dynamic var name = "" @objc dynamic var author = "" @objc dynamic var created = NSDate(timeIntervalSince1970: 1) @objc dynamic var htmlBody = "" @objc dynamic var isNew = false @objc dynamic var linkTitle = "" @objc dynamic var context = "" @objc dynamic var wasComment = false @objc dynamic var subreddit = "" @objc dynamic var subject = "" func getId() -> String { return id } } class RComment: Object { override class func primaryKey() -> String? { return "id" } func getId() -> String { return id } @objc dynamic var id = "" @objc dynamic var name = "" @objc dynamic var body = "" @objc dynamic var author = "" @objc dynamic var permalink = "" var reports = List<String>() @objc dynamic var removedBy = "" @objc dynamic var removalReason = "" @objc dynamic var removalNote = "" @objc dynamic var approvedBy = "" @objc dynamic var approved = false @objc dynamic var removed = false @objc dynamic var created = NSDate(timeIntervalSince1970: 1) @objc dynamic var edited = NSDate(timeIntervalSince1970: 1) @objc dynamic var depth = 0 @objc dynamic var gilded = false @objc dynamic var gold = 0 @objc dynamic var silver = 0 @objc dynamic var platinum = 0 @objc dynamic var htmlText = "" @objc dynamic var distinguished = "" @objc dynamic var linkid = "" @objc dynamic var canMod = false @objc dynamic var sticky = false @objc dynamic var submissionTitle = "" @objc dynamic var pinned = false @objc dynamic var controversiality = 0 @objc dynamic var isEdited = false @objc dynamic var subreddit = "" @objc dynamic var scoreHidden = false @objc dynamic var parentId = "" @objc dynamic var archived = false @objc dynamic var score = 0 @objc dynamic var flair = "" @objc dynamic var voted = false @objc dynamic var vote = false @objc dynamic var saved = false @objc dynamic var cakeday = false @objc dynamic var urlFlair = "" var likes: VoteDirection { if voted { if vote { return .up } else { return .down } } return .none } } class RString: Object { @objc dynamic var value = "" } class RMore: Object { override class func primaryKey() -> String? { return "id" } func getId() -> String { return id } @objc dynamic var count = 0 @objc dynamic var id = "" @objc dynamic var name = "" @objc dynamic var parentId = "" let children = List<RString>() } class RSubmissionListing: Object { @objc dynamic var name = "" @objc dynamic var accessed = NSDate(timeIntervalSince1970: 1) @objc dynamic var comments = false let submissions = List<RSubmission>() } class RFriend: Object { @objc dynamic var name = "" @objc dynamic var friendSince = NSDate(timeIntervalSince1970: 1) } extension String { func convertHtmlSymbols() throws -> String? { guard let data = data(using: .utf8) else { return nil } return try NSAttributedString(data: data, options: convertToNSAttributedStringDocumentReadingOptionKeyDictionary([convertFromNSAttributedStringDocumentAttributeKey(NSAttributedString.DocumentAttributeKey.documentType): convertFromNSAttributedStringDocumentType(NSAttributedString.DocumentType.html), convertFromNSAttributedStringDocumentAttributeKey(NSAttributedString.DocumentAttributeKey.characterEncoding): String.Encoding.utf8.rawValue]), documentAttributes: nil).string } } extension String { init(htmlEncodedString: String) { self.init() guard let encodedData = htmlEncodedString.data(using: .utf8) else { self = htmlEncodedString return } let attributedOptions: [String: Any] = [ convertFromNSAttributedStringDocumentAttributeKey(NSAttributedString.DocumentAttributeKey.documentType): convertFromNSAttributedStringDocumentType(NSAttributedString.DocumentType.html), convertFromNSAttributedStringDocumentAttributeKey(NSAttributedString.DocumentAttributeKey.characterEncoding): String.Encoding.utf8.rawValue, ] do { let attributedString = try NSAttributedString(data: encodedData, options: convertToNSAttributedStringDocumentReadingOptionKeyDictionary(attributedOptions), documentAttributes: nil) self = attributedString.string } catch { print("Error: \(error)") self = htmlEncodedString } } } // Helper function inserted by Swift 4.2 migrator. private func convertToNSAttributedStringDocumentReadingOptionKeyDictionary(_ input: [String: Any]) -> [NSAttributedString.DocumentReadingOptionKey: Any] { return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.DocumentReadingOptionKey(rawValue: key), value) }) } // Helper function inserted by Swift 4.2 migrator. private func convertFromNSAttributedStringDocumentAttributeKey(_ input: NSAttributedString.DocumentAttributeKey) -> String { return input.rawValue } // Helper function inserted by Swift 4.2 migrator. private func convertFromNSAttributedStringDocumentType(_ input: NSAttributedString.DocumentType) -> String { return input.rawValue }
apache-2.0
9553dfee057b7237063ef3bb2d2fe108
44.342956
482
0.586752
4.65856
false
false
false
false
tlax/looper
looper/View/Camera/Filter/BlenderOverlay/VCameraFilterBlenderOverlayListAdd.swift
1
3118
import UIKit class VCameraFilterBlenderOverlayListAdd:UIButton { weak var layoutLeft:NSLayoutConstraint! private weak var image:UIImageView! private let kAnimationImagesDuration:TimeInterval = 0.15 private let kAnimationDuration:TimeInterval = 0.5 init() { super.init(frame:CGRect.zero) clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false backgroundColor = UIColor.clear let animatingImages:[UIImage] = [ #imageLiteral(resourceName: "assetCameraFilterBlenderAdd1"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd2"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd3"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd4"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd5"), #imageLiteral(resourceName: "assetCameraFilterBlenderAdd0")] let image:UIImageView = UIImageView() image.isUserInteractionEnabled = false image.translatesAutoresizingMaskIntoConstraints = false image.clipsToBounds = true image.contentMode = UIViewContentMode.center image.image = #imageLiteral(resourceName: "assetCameraFilterBlenderAdd0") image.animationImages = animatingImages image.animationDuration = kAnimationImagesDuration self.image = image addSubview(image) NSLayoutConstraint.equals( view:image, toView:self) } required init?(coder:NSCoder) { return nil } deinit { image.stopAnimating() } //MARK: public func animateHide() { guard let width:CGFloat = superview?.bounds.maxX else { return } let halfWidth:CGFloat = width / 2.0 let halfSelfWidth:CGFloat = bounds.midX let totalWidth:CGFloat = width + halfWidth - halfSelfWidth image.startAnimating() layoutLeft.constant = totalWidth UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.superview?.layoutIfNeeded() }) { [weak self] (done:Bool) in self?.image.stopAnimating() } } func animateShow() { guard let width:CGFloat = superview?.bounds.maxX else { return } let selfWidth:CGFloat = bounds.maxX let remainLeft:CGFloat = width - selfWidth let marginLeft:CGFloat = remainLeft / 2.0 image.startAnimating() layoutLeft.constant = marginLeft UIView.animate( withDuration:kAnimationDuration, animations: { [weak self] in self?.superview?.layoutIfNeeded() }) { [weak self] (done:Bool) in self?.image.stopAnimating() } } }
mit
58daec57930f562d35de95d37650b42e
26.350877
81
0.5805
5.927757
false
false
false
false
shahabc/ProjectNexus
Mobile Buy SDK Sample Apps/Advanced App - ObjC/Mobile Buy SDK Advanced Sample/HomeViewController.swift
1
5977
// // HomeViewController.swift // Mobile Buy SDK Advanced Sample // // Created by Shahab Chaouche on 2016-12-14. // Copyright © 2016 Shopify. All rights reserved. // import UIKit import SFFocusViewLayout import Alamofire import AlamofireImage import Buy import CKWaveCollectionViewTransition class HomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet weak var homeCollectionView: UICollectionView! var collections: [BUYCollection] = [] var imageArray:[UIImage] = [] var selectedIndex: Int? let singleton = Singleton.sharedInstance override func viewDidLoad() { super.viewDidLoad() let imageview = UIImageView(image: #imageLiteral(resourceName: "logo33")) self.navigationItem.titleView = imageview // Checks for any data passed from the iMSG extension let userDefaults = UserDefaults(suiteName: "group.com.nexus.Mobile-Buy-SDK-Advanced-Sample") let isExtension = userDefaults?.bool(forKey: "IsExtension") // Fetches all the products in the store UIApplication.shared.isNetworkActivityIndicatorVisible = true singleton.client.getProductsPage(1, inCollection: 402946826, withTags: nil, sortOrder: .collectionDefault, completion: { products, page, reachedEnd, error in UIApplication.shared.isNetworkActivityIndicatorVisible = false if (error == nil && (products != nil)) { self.singleton.products = products! // if isExtension! { // self.tabBarController?.selectedIndex = 2 // } // userDefaults?.set(false, forKey: "IsExtension") // userDefaults?.synchronize() } else { print("Error fetching products: \(error)") } }) // Fetches all the collections in the store UIApplication.shared.isNetworkActivityIndicatorVisible = true singleton.client.getCollectionsPage(1, completion: { collections, page, reachedEnd, error in UIApplication.shared.isNetworkActivityIndicatorVisible = false if (error == nil && (collections != nil)) { self.collections = collections! self.homeCollectionView.reloadData() if isExtension! { self.tabBarController?.selectedIndex = 2 } userDefaults?.set(false, forKey: "IsExtension") userDefaults?.synchronize() } else { print("Error fetching products: \(error)") } }) singleton.cart = BUYCart(modelManager: (singleton.client.modelManager), jsonDictionary:nil) } override func viewDidLayoutSubviews() { guard let layout = homeCollectionView.collectionViewLayout as? UICollectionViewFlowLayout else { fatalError("Expected the collection view to have a UICollectionViewFlowLayout") } layout.itemSize.width = self.view.bounds.size.width layout.itemSize.height = self.view.bounds.size.width / 1.5 } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - UICollectionViewDataSource func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return collections.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? CategoryCollectionViewCell //cell?.backgroundColor = .randomColor() let collection = self.collections[indexPath.row] as BUYCollection cell?.categoryLabel.text = collection.title cell?.categoryLabel.sizeToFit() let imageURL = collection.image.sourceURL cell?.categoryImageView.sd_setImage(with: imageURL, placeholderImage: UIImage(named: "placeholder.png")) //cell?.categoryImageView.image = imageArray[indexPath.row] //cell.backgroundView?.backgroundColor = UIColor.blue return cell! } // MARK: - UICollectionViewDelegate func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { selectedIndex = indexPath.row performSegue(withIdentifier: "ProductViewControllerSegue", sender: self) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. if (segue.identifier == "ProductViewControllerSegue") { let pvc = segue.destination as? ProductCollectionViewController if let selectedIndex = selectedIndex { pvc?.collection = self.collections[selectedIndex] } } } } extension CGFloat { static func random() -> CGFloat { return CGFloat(arc4random()) / CGFloat(UInt32.max) } } extension UIColor { static func randomColor() -> UIColor { // If you wanted a random alpha, just create another // random number for that too. return UIColor(red: .random(), green: .random(), blue: .random(), alpha: 1.0) } }
mit
160d23ff9c1b8780a433fd4cecc1fd66
33.744186
186
0.627343
5.659091
false
false
false
false
Eflet/Charts
ChartsDemo-OSX/ChartsDemo-OSX/Demos/PieDemoViewController.swift
6
2361
// // PieDemoViewController.swift // ChartsDemo-OSX // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts import Foundation import Cocoa import Charts public class PieDemoViewController: NSViewController { @IBOutlet var pieChartView: PieChartView! override public func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. let xs = Array(1..<10).map { return Double($0) } let ys1 = xs.map { i in return abs(sin(Double(i / 2.0 / 3.141 * 1.5)) * 100) } let yse1 = ys1.enumerate().map { idx, i in return ChartDataEntry(value: i, xIndex: idx) } let data = PieChartData(xVals: xs) let ds1 = PieChartDataSet(yVals: yse1, label: "Hello") ds1.colors = ChartColorTemplates.vordiplom() data.addDataSet(ds1) let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle paragraphStyle.lineBreakMode = .ByTruncatingTail paragraphStyle.alignment = .Center let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "iOS Charts\nby Daniel Cohen Gindi") centerText.setAttributes([NSFontAttributeName: NSFont(name: "HelveticaNeue-Light", size: 15.0)!, NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(0, centerText.length)) centerText.addAttributes([NSFontAttributeName: NSFont(name: "HelveticaNeue-Light", size: 13.0)!, NSForegroundColorAttributeName: NSColor.grayColor()], range: NSMakeRange(10, centerText.length - 10)) centerText.addAttributes([NSFontAttributeName: NSFont(name: "HelveticaNeue-LightItalic", size: 13.0)!, NSForegroundColorAttributeName: NSColor(red: 51 / 255.0, green: 181 / 255.0, blue: 229 / 255.0, alpha: 1.0)], range: NSMakeRange(centerText.length - 19, 19)) self.pieChartView.centerAttributedText = centerText self.pieChartView.data = data self.pieChartView.descriptionText = "Piechart Demo" } override public func viewWillAppear() { self.pieChartView.animate(xAxisDuration: 0.0, yAxisDuration: 1.0) } }
apache-2.0
1e9928fffd0f0eb03a2bbf39aa6d8669
41.945455
268
0.685726
4.722
false
false
false
false
quickthyme/PUTcat
Tests/iOS/Environment/EnvironmentPresenterTests.swift
1
9156
import XCTest class EnvironmentPresenterTests: XCTestCase { var subject: EnvironmentPresenterSpy! var scene: EnvironmentSceneMock! override func setUp() { super.setUp() scene = EnvironmentSceneMock() subject = EnvironmentPresenterSpy() } func autoExpect(_ expect: XCTestExpectation, timeout: TimeInterval) { DispatchQueue.main.asyncAfter(deadline: .now()+timeout) { expect.fulfill() } } } // MARK: - Environment Scene Delegate extension EnvironmentPresenterTests { func test_when_get_scene_data__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") subject.getSceneData(scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucFetchEnvironmentListWasCalled) } } func test_when_get_scene_data__it_sets_scene_data_on_scene_and_calls_refresh() { let expect = expectation(description: "it_sets_scene_data_on_scene_and_calls_refresh") subject.getSceneData(scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertGreaterThan(self.scene.sceneData.section.count, 0) XCTAssertTrue(self.scene.refreshSceneWasCalled) } } func test_when_scene_did_select_item_with_segueid__it_tells_scene_to_navigate() { let expect = expectation(description: "it_tells_scene_to_navigate") let item = createEnvironmentSceneDataItem1() subject.scene(self.scene, didSelect: item) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.navigateWasCalled) XCTAssertEqual(self.scene.navigateSegueID, SegueID.Variable) } } func test_when_scene_did_select_item_without_segueid__it_does_not_tell_scene_to_navigate() { let expect = expectation(description: "it_does_not_tell_scene_to_navigate") var item = createEnvironmentSceneDataItem1() item.segue = nil subject.scene(self.scene, didSelect: item) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertFalse(self.scene.navigateWasCalled) XCTAssertNil(self.scene.navigateSegueID) } } func test_when_add_item__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") subject.addItem(scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucAddEnvironmentWasCalled) } } func test_when_add_item__it_calls_refresh() { let expect = expectation(description: "it_calls_refresh") subject.addItem(scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.refreshSceneWasCalled) } } func test_when_update_item__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") let item = createEnvironmentSceneDataItem1() subject.update(item: item, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucUpdateEnvironmentWasCalled) XCTAssertEqual(self.subject.ucUpdateEnvironmentParameter_id, "123") XCTAssertEqual(self.subject.ucUpdateEnvironmentParameter_name, "Title 1") } } func test_when_update_item__it_calls_refresh() { let expect = expectation(description: "it_calls_refresh") let item = createEnvironmentSceneDataItem1() subject.update(item: item, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.refreshSceneWasCalled) } } func test_when_delete_item__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") let item = createEnvironmentSceneDataItem1() subject.delete(item: item, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucDeleteEnvironmentWasCalled) XCTAssertEqual(self.subject.ucDeleteEnvironmentParameter_environmentID, "123") } } func test_when_delete_item__it_calls_refresh() { let expect = expectation(description: "it_calls_refresh") let item = createEnvironmentSceneDataItem1() subject.delete(item: item, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.refreshSceneWasCalled) } } func test_when_update_ordinality__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") let data = createEnvironmentSceneData() subject.updateOrdinality(sceneData: data, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucSortEnvironmentListWasCalled) XCTAssertEqual(self.subject.ucSortEnvironmentListParameter_ordinality!, ["123","456"]) } } func test_when_update_ordinality__it_calls_refresh() { let expect = expectation(description: "it_calls_refresh") let data = createEnvironmentSceneData() subject.updateOrdinality(sceneData: data, scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.refreshSceneWasCalled) } } func test_when_export_environment__it_invokes_proper_use_case_with_correct_parameters() { let expect = expectation(description: "it_invokes_proper_use_case_with_correct_parameters") let scene = EnvironmentSceneMock() subject.exportEnvironment(name: "Environment 1", scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.subject.ucBuildFullyConstructedEnvironmentWasCalled) XCTAssertEqual(self.subject.ucBuildFullyConstructedEnvironmentParameter_name, "Environment 1") } } func test_when_export_environment__it_calls_present_send_email() { let expect = expectation(description: "it_calls_present_send_email") subject.exportEnvironment(name: "Environment 1", scene: scene) autoExpect(expect, timeout: 0.25) waitForExpectations(timeout: 0.5) { _ in XCTAssertTrue(self.scene.presentSendEmailWithAttachmentWasCalled) XCTAssertEqual(self.scene.presentSendEmailSubject, "Export of Environment 1 Environment") XCTAssertGreaterThan(self.scene.presentSendEmailAttachment!.count, 0) XCTAssertEqual(self.scene.presentSendEmailFilename, "Environment 1.putcatEnvironment") XCTAssertEqual(self.scene.presentSendEmailMimeType, "application/putcat") } } // MARK: - Local Mocks fileprivate typealias CellID = EnvironmentSceneDataItem.CellID fileprivate typealias SegueID = EnvironmentSceneDataItem.SegueID fileprivate typealias Icon = EnvironmentSceneDataItem.Icon fileprivate func createEnvironmentSceneData() -> EnvironmentSceneData { return EnvironmentSceneData(section: [ EnvironmentSceneDataSection(title: "Section", item: [createEnvironmentSceneDataItem1(), createEnvironmentSceneDataItem2()]) ] ) } fileprivate func createEnvironmentSceneDataItem1() -> EnvironmentSceneDataItem { return EnvironmentSceneDataItem(refID: "123", cellID: CellID.BasicCell, title: "Title 1", detail: "Description 1", segue: SegueID.Variable, icon: UIImage(named: Icon.Environment)) } fileprivate func createEnvironmentSceneDataItem2() -> EnvironmentSceneDataItem { return EnvironmentSceneDataItem(refID: "456", cellID: CellID.BasicCell, title: "Title 2", detail: "Description 2", segue: SegueID.Variable, icon: UIImage(named: Icon.Environment)) } }
apache-2.0
3bcb6182f6154e18423f96ce368111f5
39.334802
106
0.640891
4.729339
false
true
false
false
QuarkWorks/RealmModelGenerator
RealmModelGenerator/AttributeDetailVC.swift
1
4403
// // AttributeDetailVC.swift // RealmModelGenerator // // Created by Zhaolong Zhong on 3/29/16. // Copyright © 2016 QuarkWorks. All rights reserved. // import Cocoa class AttributeDetailVC: NSViewController, AttributeDetailViewDelegate, Observer { static let TAG = NSStringFromClass(AttributeDetailVC.self) @IBOutlet weak var attributeDetailView: AttributeDetailView! { didSet{ self.attributeDetailView.delegate = self } } weak var attribute:Attribute? { didSet{ if oldValue === self.attribute { return } oldValue?.observable.removeObserver(observer: self) self.attribute?.observable.addObserver(observer: self) self.invalidateViews() } } // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() } func invalidateViews() { if !self.isViewLoaded || attribute == nil { return } guard let attribute = self.attribute else { return } attributeDetailView.name = attribute.name attributeDetailView.isIgnored = attribute.isIgnored attributeDetailView.isIndexed = attribute.isIndexed attributeDetailView.isPrimary = attribute.entity.primaryKey === attribute attributeDetailView.isRequired = attribute.isRequired attributeDetailView.hasDefault = attribute.hasDefault attributeDetailView.defaultValue = attribute.defaultValue attributeDetailView.selectedIndex = AttributeType.values.index(of: attribute.type)! } func onChange(observable: Observable) { self.invalidateViews() } // MARK: - AttributeDetailView delegate func attributeDetailView(attributeDetailView: AttributeDetailView, shouldChangeAttributeTextField newValue: String, control:NSControl) -> Bool { guard let attribute = self.attribute else { return false } if control === self.attributeDetailView.nameTextField { do { try attribute.setName(name: newValue) } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Unable to rename attribute: \(attribute.name) to: \(newValue). There is an attribute with the same name.") return false } } else { attribute.defaultValue = newValue } return true } func attributeDetailView(attributeDetailView: AttributeDetailView, shouldChangeAttributeCheckBoxFor sender: NSButton, state: Bool) -> Bool { guard let attribute = self.attribute else { return false } switch sender { case self.attributeDetailView.ignoredCheckBox: attribute.isIgnored = state break; case self.attributeDetailView.indexedCheckBox: do { try attribute.setIndexed(isIndexed: state) } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Unable to set index for attribute \(attribute.name) with type \(attribute.type.rawValue) ") return false } break; case self.attributeDetailView.primaryCheckBox: if state { do { try attribute.entity.setPrimaryKey(primaryKey: attribute) } catch { Tools.popupAlert(messageText: "Error", buttonTitle: "OK", informativeText: "Unable to set primary key for attribute \(attribute.name) with type \(attribute.type.rawValue) ") return false } } else { if attribute.entity.primaryKey === attribute { try! attribute.entity.setPrimaryKey(primaryKey: nil) } } break; case self.attributeDetailView.requiredCheckBox: attribute.isRequired = state break; case self.attributeDetailView.defaultCheckBox: attribute.hasDefault = state break; default: break } return true } func attributeDetailView(attributeDetailView: AttributeDetailView, selectedTypeDidChange selectedIndex: Int) -> Bool { self.attribute!.type = AttributeType.values[selectedIndex] return true } }
mit
d652a9c013e8920220b882924d1a7db2
36.305085
198
0.620854
5.621967
false
false
false
false
xmartlabs/Bender
Example/Example/Tests/Helpers/UIViewController.swift
1
1736
// // UIViewController.swift // Example // // Created by Mathias Claassen on 5/31/17. // // import MetalBender import Metal import UIKit protocol ExampleViewController { var inputSize: LayerSize { get } var pixelBufferPool: CVPixelBufferPool? { get set } } extension ExampleViewController { mutating func setPixelBufferPool() { let bufferAttributes = [kCVPixelBufferPixelFormatTypeKey as String: NSNumber(value: Int32(kCVPixelFormatType_64RGBAHalf)), kCVPixelBufferWidthKey as String: inputSize.w, kCVPixelBufferHeightKey as String: inputSize.w] as [String: Any] CVPixelBufferPoolCreate(kCFAllocatorDefault, [kCVPixelBufferPoolMinimumBufferCountKey as String: 1] as CFDictionary, bufferAttributes as CFDictionary, &pixelBufferPool) } func getPixelBuffer(from texture: MTLTexture, bufferPool: CVPixelBufferPool) -> CVPixelBuffer? { let channels = texture.arrayLength * 4 var pixelBuffer: CVPixelBuffer? CVPixelBufferPoolCreatePixelBuffer(kCFAllocatorDefault, bufferPool, &pixelBuffer) guard let buffer = pixelBuffer else { return nil } CVPixelBufferLockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0)) if let pointer = CVPixelBufferGetBaseAddress(buffer) { let region = MTLRegionMake2D(0, 0, texture.width, texture.height) texture.getBytes(pointer, bytesPerRow: 2 * channels * texture.width, from: region, mipmapLevel: 0) } CVPixelBufferUnlockBaseAddress(buffer, CVPixelBufferLockFlags(rawValue: 0)) return buffer } }
mit
2014b9ae96baf628ad0ab2279d32fe97
33.72
130
0.669355
5.511111
false
false
false
false
xuech/OMS-WH
OMS-WH/Classes/StockSearch/Controller/StockInWHSearchViewController.swift
1
6657
// // StockInWHSearchViewController.swift // OMS-WH // // Created by ___Gwy on 2017/9/18. // Copyright © 2017年 medlog. All rights reserved. // import UIKit import SVProgressHUD class StockInWHSearchViewController: UIViewController { fileprivate let viewModel = StockInWHSearchViewModel() private let orgCode = UserDefaults.Global.readString(forKey: .orgCode) ?? "" private let whName = UserDefaults.Global.readString(forKey: .orgName) fileprivate var supplyCode = "" fileprivate var brandCode = "" fileprivate var prolnsCode = "" fileprivate var medTypeCode = "" var getData:((_ arr:[StockInWHModel]?, _ supplyName:String?, _ whName:String?)->())? override func viewDidLoad() { super.viewDidLoad() title = "仓配中心库存查询" view.backgroundColor = UIColor.white setUp() } func setUp(){ self.view.addSubview(searchView) //仓库名这栏不能修改 if whName != nil{ searchView.whNameTF.showTextField.text = whName }else{ searchView.whNameTF.showTextField.placeholder = "暂无仓配中心" } searchView.supplyNameTF.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(requstSupply))) searchView.brandTF.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(requstBrand))) searchView.prolnsTF.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(requstProlns))) searchView.medTypeTF.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(requstMedType))) searchView.reSetBtn.addTarget(self, action: #selector(StockInWHSearchViewController.reSet), for: .touchUpInside) searchView.searchBtn.addTarget(self, action: #selector(StockInWHSearchViewController.search), for: .touchUpInside) } lazy var searchView:StockInWHSearchView = { let searchView = StockInWHSearchView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight + kNavBarHeight)) return searchView }() //货控方 @objc func requstSupply(){ viewModel.requstSupply(orgCode) { (data, error) in let picker = PickViewController(frame: self.view.bounds, dataSource: data, title: "请选择供货方", modeBehaviour: ChooseBehaviour.chooseOwner) picker.GetCode = {(indexpath:Int) in self.searchView.supplyNameTF.showTextField.text = data[indexpath]["oIName"] as? String self.supplyCode = data[indexpath]["oIOrgCode"] as! String } self.view.addSubview(picker.view) self.addChildViewController(picker) } } //品牌 @objc func requstBrand(){ guard supplyCode != "" else { return SVProgressHUD.showError("请先选择货控方") } viewModel.requstBrand(supplyCode) { (data, error) in let picker = PickViewController(frame: self.view.bounds, dataSource: data, title: "请选择品牌", modeBehaviour: ChooseBehaviour.chooseBrand) picker.GetCode = {(indexpath:Int) in self.searchView.brandTF.showTextField.text = data[indexpath]["medBrandName"] as? String self.brandCode = data[indexpath]["medBrandCode"] as! String } self.view.addSubview(picker.view) self.addChildViewController(picker) } } //产品线 @objc func requstProlns(){ guard brandCode != "" else { return SVProgressHUD.showError("请先选择品牌") } let param = ["medBrandCode":brandCode,"oIOrgCode":supplyCode] viewModel.requstProlns(param) { (data, error) in let picker = PickViewController(frame: self.view.bounds, dataSource: data, title: "请选择产品线", modeBehaviour: ChooseBehaviour.chooseProlns) picker.GetCode = {(indexpath:Int) in self.searchView.prolnsTF.showTextField.text = data[indexpath]["medProdLnName"] as? String self.prolnsCode = data[indexpath]["medProdLnCode"] as! String } self.view.addSubview(picker.view) self.addChildViewController(picker) } } //物料类型 @objc func requstMedType(){ viewModel.requstDict(["dictTypeCode":"MMICTG"]) { (data, error) in let picker = PickViewController(frame: self.view.bounds, dataSource: data, title: "请选择产品线", modeBehaviour: ChooseBehaviour.chooseDictValue) picker.GetCode = {(indexpath:Int) in self.searchView.medTypeTF.showTextField.text = data[indexpath]["dictValueName"] as? String self.medTypeCode = data[indexpath]["dictValueCode"] as! String } self.view.addSubview(picker.view) self.addChildViewController(picker) } } @objc func reSet(){ searchView.supplyNameTF.showTextField.text = "" searchView.brandTF.showTextField.text = "" searchView.prolnsTF.showTextField.text = "" searchView.medTypeTF.showTextField.text = "" searchView.medCodeTF.showTextField.text = "" searchView.medNameTF.showTextField.text = "" searchView.medSpecificationTF.showTextField.text = "" supplyCode = "" brandCode = "" prolnsCode = "" medTypeCode = "" } @objc func search(){ guard supplyCode != "" else { return SVProgressHUD.showError("请先选择货控方") } let param = ["categoryByPlatform":medTypeCode, "medBrandCode":brandCode, "medMICode":searchView.medCodeTF.showTextField.text!, "medMIName":searchView.medNameTF.showTextField.text!, "medMIWarehouse":orgCode, "medProdLnCode":prolnsCode, "pageNum":"1", "pageSize":"10000000", "sOOIOrgCode":supplyCode, "specification":searchView.medSpecificationTF.showTextField.text!] viewModel.requstStockInWH(param) { (data, error) in if data.count > 0{ self.getData!(data,self.searchView.supplyNameTF.showTextField.text!,self.searchView.whNameTF.showTextField.text!) }else{ SVProgressHUD.showError("该条件下未查到相关数据") } self.navigationController?.popViewController(animated: true) } } }
mit
b4117db9cf0ba9d8e137bb562f33dc5d
39.72956
151
0.625386
4.713246
false
false
false
false
pedrovsn/2reads
reads2/reads2/BibliotecaTableViewController.swift
1
3504
// // BibliotecaTableViewController.swift // reads2 // // Created by Student on 11/29/16. // Copyright © 2016 Student. All rights reserved. // import UIKit class BibliotecaTableViewController: UITableViewController { let livros = Livro.getList() override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return livros.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("libraryCell", forIndexPath: indexPath) as! BibliotecaTableViewCell let livro = livros[indexPath.row] cell.nomeDoLivro.text = livro.titulo cell.autorDoLivro.text = livro.autor cell.capaDoLivro.image = UIImage(named: livro.imagem!) return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
2f7dd7ed3adfc8ae782833b0932b31cc
33.683168
157
0.684271
5.397535
false
false
false
false
exis-io/swiftRiffle
Pod/Classes/Deferred.swift
1
3064
// // Deferred.swift // Pods // // Created by damouse on 12/4/15. // // Homebaked, python Twisted inspired deferreds with A+ inspired syntax // These guys will chain callbacks and errbacks import Foundation import Mantle public class Deferred { // Callback and Errback ids var cb: UInt64 = 0 var eb: UInt64 = 0 var callbackFuntion: ([Any] -> Any?)? = nil var errbackFunction: ([Any] -> Any?)? = nil var next: Deferred? public init() {} init(domain: Domain) { // Automatically creates and sets callback and errback assignments for the given domain cb = CBID() eb = CBID() domain.app.deferreds[eb] = self domain.app.deferreds[cb] = self } // Final, internal implementation of addCallback public func then(fn: () -> ()) -> Deferred { next = Deferred() callbackFuntion = { a in return fn() } return next! } public func error(fn: (String) -> ()) -> Deferred { next = Deferred() errbackFunction = { a in fn(a[0] as! String) } return next! } public func callback(args: [Any]) -> Any? { // Fires off a deferred chain recursively. TODO: work in error logic, recovery, propogation, etc var ret: Any? if let handler = callbackFuntion { // if the next result is a deferred, wait for it to complete before returning (?) ret = handler(args) } // follow the chain, propogate the calback to the next deferred if let n = next { if let arrayReturn = ret as? [Any] { return n.callback(arrayReturn) } return n.callback([ret]) } return nil } public func errback(args: [Any]) -> Any? { if let handler = errbackFunction { // if the next result is a deferred, wait for it to complete before returning (?) handler(args) } // follow the chain, propogate the calback to the next deferred if let n = next { return n.errback(args) } // No chain exists. TODO: Send the error to some well-known place //Riffle.warn("Unhandled error: \(args)") return nil } } // Contains handler "then"s to replace handler functions public class HandlerDeferred: Deferred { public var mantleDomain: UInt64! override init(domain: Domain) { super.init(domain: domain) mantleDomain = domain.mantleDomain } public override func then(fn: () -> ()) -> Deferred { // this override is a special case. It overrides the base then, but cant go in the extension return _then([]) { a in return fn() } } public func _then(types: [Any], _ fn: [Any] -> ()) -> Deferred { next = Deferred() CallExpects(mantleDomain, self.cb, marshall(types)) callbackFuntion = { a in return fn(a) } return next! } }
mit
e63b947a67c5cc8ba825707f0a9151d9
27.110092
104
0.561684
4.309423
false
false
false
false
pepaslabs/LearningRxSwift
lesson3.7_timer/solution/RxSwiftHello/RxSwiftHello/ViewController.swift
1
1154
// // ViewController.swift // RxSwiftHello // // Created by Pepas Personal on 11/24/15. // Copyright © 2015 Pepas Labs. All rights reserved. // import UIKit import RxSwift import RxCocoa class DelayedSingleHelloGenerator { class func generate() -> Observable<String> { let delayedObservable = timer(3, MainScheduler.sharedInstance) let helloObservable = delayedObservable.map({ (_) -> String in return "hello" }) return helloObservable } } class DelayedTickHelloGenerator { class func generate() -> Observable<String> { let tickerObservable = timer(3.0, 1.0, MainScheduler.sharedInstance) let helloObservable = tickerObservable.map { (_) -> String in return "hello" } return helloObservable } } class ViewController: UIViewController { let disposeBag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() DelayedSingleHelloGenerator.generate().subscribeNext { (s) -> Void in debugPrint(s) }.addDisposableTo(disposeBag) } }
mit
fe052d96a42efb178fc60ca728cb7d70
21.173077
77
0.620989
4.804167
false
false
false
false
zitao0322/ShopCar
Shoping_Car/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift
18
3128
// // VirtualTimeConverterType.swift // Rx // // Created by Krunoslav Zaher on 12/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Parametrization for virtual time used by `VirtualTimeScheduler`s. */ public protocol VirtualTimeConverterType { /** Virtual time unit used that represents ticks of virtual clock. */ associatedtype VirtualTimeUnit /** Virtual time unit used to represent differences of virtual times. */ associatedtype VirtualTimeIntervalUnit /** Converts virtual time to real time. - parameter virtualTime: Virtual time to convert to `NSDate`. - returns: `NSDate` corresponding to virtual time. */ func convertFromVirtualTime(virtualTime: VirtualTimeUnit) -> RxTime /** Converts real time to virtual time. - parameter time: `NSDate` to convert to virtual time. - returns: Virtual time corresponding to `NSDate`. */ func convertToVirtualTime(time: RxTime) -> VirtualTimeUnit /** Converts from virtual time interval to `NSTimeInterval`. - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. - returns: `NSTimeInterval` corresponding to virtual time interval. */ func convertFromVirtualTimeInterval(virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval /** Converts from virtual time interval to `NSTimeInterval`. - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. - returns: Virtual time interval corresponding to time interval. */ func convertToVirtualTimeInterval(timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit /** Offsets virtual time by virtual time interval. - parameter time: Virtual time. - parameter offset: Virtual time interval. - returns: Time corresponding to time offsetted by virtual time interval. */ func offsetVirtualTime(time time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit /** This is aditional abstraction because `NSDate` is unfortunately not comparable. Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. */ func compareVirtualTime(lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison } /** Virtual time comparison result. This is aditional abstraction because `NSDate` is unfortunately not comparable. Extending `NSDate` with `Comparable` would be too risky because of possible collisions with other libraries. */ public enum VirtualTimeComparison { /** lhs < rhs. */ case LessThan /** lhs == rhs. */ case Equal /** lhs > rhs. */ case GreaterThan } extension VirtualTimeComparison { /** lhs < rhs. */ var lessThen: Bool { return self == .LessThan } /** lhs > rhs */ var greaterThan: Bool { return self == .GreaterThan } /** lhs == rhs */ var equal: Bool { return self == .Equal } }
mit
1080b6192e836cf5f3e19ed60904dc35
26.191304
113
0.679885
5.134647
false
false
false
false
the-grid/Disc
DiscTests/Models/ProviderSpec.swift
1
2289
import Argo import Disc import Nimble import Ogra import Quick class ProviderSpec: QuickSpec { override func spec() { describe("raw values") { describe("Facebook") { it("should have the correct raw value") { expect(Provider.Facebook.rawValue).to(equal("facebook")) } } describe("GitHub") { it("should have the correct raw value") { expect(Provider.GitHub.rawValue).to(equal("github")) } } describe("GitHub (public)") { it("should have the correct raw value") { expect(Provider.GitHubPublic.rawValue).to(equal("github_public")) } } describe("GitHub (private)") { it("should have the correct raw value") { expect(Provider.GitHubPrivate.rawValue).to(equal("github_private")) } } describe("Google") { it("should have the correct raw value") { expect(Provider.Google.rawValue).to(equal("google")) } } describe("Twitter") { it("should have the correct raw value") { expect(Provider.Twitter.rawValue).to(equal("twitter")) } } } describe("decoding") { it("should produce a Provider") { let rawValue = "github" let json = JSON.String(rawValue) guard let decoded = Provider.decode(json).value else { return XCTFail("Unable to decode JSON: \(json)") } let provider = Provider(rawValue: rawValue) expect(decoded).to(equal(provider)) } } describe("encoding") { it("should produce JSON") { let rawValue = "github" let provider = Provider(rawValue: rawValue) let encoded = provider.encode() let json = JSON.String(rawValue) expect(encoded).to(equal(json)) } } } }
mit
f89992c867f21a4cf01585659c7720d5
32.173913
87
0.459589
5.489209
false
false
false
false
byu-oit/ios-byuSuite
byuSuite/Apps/YTime/controller/YTimePunchesViewController.swift
1
12295
// // YTimePunchesViewController.swift // byuSuite // // Created by Eric Romrell on 5/18/17. // Copyright © 2017 Brigham Young University. All rights reserved. // private let DATE_FORMAT = DateFormatter.defaultDateFormat("h:mm a") private let DELETE_DATE_FORMAT = DateFormatter.defaultDateFormat("yyyy-MM-dd") private let HEIGHT_TO_HIDE_TOOLBAR: CGFloat = -44.0 private let PUNCH_CELL_ID = "PunchCell" private let EXCEPTION_CELL_ID = "ExceptionCell" private let DELETABLE_CELL_ID = "DeletableCell" class YTimePunchesViewController: ByuTableDataViewController, UITextFieldDelegate { //Outlets @IBOutlet private weak var noDataLabel: UILabel! @IBOutlet private weak var toolbarHeightToBottomConstraint: NSLayoutConstraint! @IBOutlet private weak var toolbar: UIToolbar! //Public properties var employeeRecord: Int! var punches: [YTimePunch]! var selectedDate: Date! //Private properties private var currentlyEditing: (UIDatePicker, YTimeExceptionTableViewCell?)? //The date picker and cell that the user is editing private var punchesToSave = [IndexPath: YTimePunch]() { didSet { toolbarHeightToBottomConstraint.constant = punchesToSave.count > 0 ? 0 : HEIGHT_TO_HIDE_TOOLBAR toolbar.isHidden = punchesToSave.count == 0 } } private var totalHours: String? private var exceptionCellCount = 0 override func viewDidLoad() { super.viewDidLoad() super.title = DateFormatter.defaultDateFormat("EEE MMM d, yyyy").string(from: selectedDate) if punches.count == 0 { tableView.isHidden = true noDataLabel.isHidden = false } else { loadTableData() } } //MARK: UITableViewDataSource callbacks func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? { return totalHours } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = tableData.row(forIndexPath: indexPath) if row.cellId == EXCEPTION_CELL_ID, let cell = tableData.dequeueCell(forTableView: tableView, atIndexPath: indexPath) as? YTimeExceptionTableViewCell { //If this is an exception, load up the time proposed to correct the exception into the textfield. cell.textField.text = DATE_FORMAT.string(fromOptional: punches[indexPath.row].punchTime) cell.rightDetailTextLabel.text = row.detailText return cell } else { return super.tableView(tableView, cellForRowAt: indexPath) } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { var actions = [UITableViewRowAction]() if tableData.cellId(forIndexPath: indexPath) == DELETABLE_CELL_ID { actions = [UITableViewRowAction(style: .destructive, title: "Delete", handler: { (_, _) in if let punch: YTimePunch = self.tableData.object(forIndexPath: indexPath) { self.deletePunch(punch, indexPath: indexPath) } })] } return actions } //MARK: UITextFieldDelegate callbacks func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool { //The text field's first super view is the cell's content view, not the cell itself let currentCell = textField.superview?.superview as? YTimeExceptionTableViewCell //Create a time picker and set it as the inputView of the text field let datePicker = UIDatePicker() datePicker.datePickerMode = .time //Set min and max times on the time picker if let currentCell = currentCell, let indexPath = tableView.indexPath(for: currentCell) { let calendar = Calendar.defaultCalendar() //Set minimumDate to startOfToday. Will be overwritten if another punch exists before the exception datePicker.minimumDate = calendar.startOfDay(for: selectedDate) //Set maximumDate to the end of today. Will be overwritten if another punch exists after the exception datePicker.maximumDate = calendar.endOfDay(for: selectedDate) //If there are punches before/after the exception, the min/max should be set to those punch times let indexOfPunch = indexPath.row if indexOfPunch > 0, let punchTime = punches[indexOfPunch - 1].punchTime { datePicker.minimumDate = calendar.combine(date: selectedDate, time: punchTime) } if indexOfPunch < punches.count - 1, let punchTime = punches[indexOfPunch + 1].punchTime { datePicker.maximumDate = calendar.combine(date: selectedDate, time: punchTime) } } textField.inputView = datePicker let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancel(sender:))) let flex = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let submitButton = UIBarButtonItem(title: "OK", style: .done, target: self, action: #selector(save(sender:))) let toolbar = UIToolbar() toolbar.items = [cancelButton, flex, submitButton] toolbar.sizeToFit() toolbar.tintColor = UIColor.byuToolbarTint textField.inputAccessoryView = toolbar currentlyEditing = (datePicker, currentCell) return true } //MARK: Listeners @objc func save(sender: Any) { let cell = currentlyEditing?.1 //Hide the keyboard cell?.textField.resignFirstResponder() guard let exceptionCell = cell, let indexPath = self.tableView.indexPath(for: exceptionCell) else { return } let punchTime = self.getPunchTime() let exceptionPunch = self.punches[indexPath.row] exceptionPunch.punchTime = punchTime exceptionPunch.employeeRecord = self.employeeRecord //Add the selected time to the textField tableView.reloadRows(at: [indexPath], with: .automatic) punchesToSave[indexPath] = exceptionPunch } @objc func cancel(sender: Any) { //Just hide the keyboard currentlyEditing?.1?.textField.resignFirstResponder() } @IBAction func submitAllPunches(_ sender: Any) { var callbackCounter = 0 let decrementCallbackCounter: () -> Void = { callbackCounter -= 1 if callbackCounter == 0 { self.spinner?.stopAnimating() super.displayAlert(title: "Success", message: "The correction\(self.punchesToSave.count == 1 ? " was" : "s were") successfully submitted.", alertHandler: nil) self.punchesToSave.removeAll() } } self.spinner?.startAnimating() for (indexPath, punch) in punchesToSave { callbackCounter += 1 YTimeClient.createPunch(punch, callback: { (status, error) in if status != nil { decrementCallbackCounter() //Manually make the cell look like a regular punch cell to avoid reloading tableData/making new service calls let cell = self.tableView.cellForRow(at: indexPath) as? YTimeExceptionTableViewCell cell?.textField.textColor = UIColor.black cell?.textField.isEnabled = false cell?.rightDetailTextLabel.textColor = .black } else { super.displayAlert(error: error, message: "A server error occurred while processing one or more of the submitted corrections. Please try again later.") } }) } } @IBAction func cancelAllPunches(_ sender: Any) { for (indexPath, _) in punchesToSave { (tableView.cellForRow(at: indexPath) as? YTimeExceptionTableViewCell)?.textField.text = nil } punchesToSave.removeAll() } //MARK: Private functions private func loadTableData() { tableData = TableData(rows: punches.map { (punch) -> Row in let row = Row(detailText: punch.punchType) if let time = punch.punchTime { row.cellId = PUNCH_CELL_ID row.text = DATE_FORMAT.string(from: time) if let deletablePair = punch.deletablePair, deletablePair != 0 { row.cellId = DELETABLE_CELL_ID row.action = { super.displayActionSheet(from: self, title: "Delete duplicate punch?", actions: [UIAlertAction(title: "Delete", style: .default, handler: { (_) in self.deletePunch(punch, indexPath: nil) })]) { (_) in self.tableView.deselectSelectedRow() } } row.object = punch } else { //Regular punch cells should not be enabled. row.enabled = false } } else { row.cellId = EXCEPTION_CELL_ID exceptionCellCount += 1 } return row } ) loadTotalHours() tableView.reloadData() } private func deletePunch(_ punch: YTimePunch, indexPath: IndexPath?) { if let sequenceNumber = punch.sequenceNumber { self.spinner?.startAnimating() YTimeClient.deletePunch(employeeRecord: self.employeeRecord.toString(), punchDate: DELETE_DATE_FORMAT.string(from: self.selectedDate), sequenceNumber: sequenceNumber, callback: { (error) in if let error = error { super.displayAlert(error: error) } else { //Both these values are nullabe. Tapping doesn't pass in indexPath and swiping does not select the row. if let indexPath = indexPath ?? self.tableView.indexPathForSelectedRow { //The following code helps us avoid popping back to make a new call to the service to fetch the new punches self.tableView.beginUpdates() self.tableView.deleteRows(at: [indexPath], with: .fade) self.punches.remove(at: indexPath.row) //Reset the deletablePair of the corresponding punch so that the tableView changes it to a regular punch cell self.punches.first(where: { $0.deletablePair == punch.deletablePair })?.deletablePair = 0 self.loadTableData() self.tableView.endUpdates() } else { //Popping back will reload the punches so that they will be correct if the user comes back to this date self.popBack() } self.spinner?.stopAnimating() } }) } } private func loadTotalHours() { var totalInterval: TimeInterval = 0.0 let calendar = Calendar.defaultCalendar() var inPunch: Date? = calendar.startOfDay(for: selectedDate) //Initialize to startOfDay: if the first punch is an out, we will include time from start of day in our total for punch in punches { //If there are any exceptions, return null so that the footer doesn't load guard var time = punch.punchTime else { return } if punch.clockIn { inPunch = time } else if let start = inPunch { //punchTime only has hours, minutes and seconds so we combine it with the year, month and day from today's date for accurate timeIntervalSince calculations. time = calendar.combine(date: start, time: time) ?? time totalInterval += time.timeIntervalSince(start) //Reset the inPunch (since it's now been totaled in) inPunch = nil } } //If the last punch was "in", add another interval from that punch until now if let start = inPunch { //The start date doesn't have a year, month or date attached to it (so it default to 1/1/2000). Set it to today so that the calculation works properly guard let startDate = calendar.combine(date: selectedDate, time: start) else { return } if selectedDate.isToday { totalInterval += Date().timeIntervalSince(startDate) } else { //Only append time until end of the selectedDate and not until now if let endOfDay = calendar.endOfDay(for: selectedDate) { totalInterval += endOfDay.timeIntervalSince(startDate) } } } //This will turn the total into the format: 0h 00m totalHours = String(format: "Total: %01lih %02lim", lround(floor(totalInterval / 3600)), lround(floor(totalInterval / 60)) % 60) } private func getPunchTime() -> Date { //The day, month, and year come from the selected date. The hours and minute come from the date picker. Fuse the two and return the date let cal = Calendar.current var selectedDateComps = cal.dateComponents([.day, .month, .year, .timeZone], from: selectedDate) let datePickerComps = cal.dateComponents([.hour, .minute], from: currentlyEditing?.0.date ?? Date()) selectedDateComps.hour = datePickerComps.hour selectedDateComps.minute = datePickerComps.minute selectedDateComps.second = 0 return cal.date(from: selectedDateComps) ?? Date() } }
apache-2.0
57200919d21c5c73695c7fee98eb899d
39.843854
192
0.692696
4.373533
false
false
false
false
S2dentik/Taylor
TaylorFramework/Modules/caprices/ProccessingMessage/Options/FileOption.swift
4
632
// // FileOption.swift // Caprices // // Created by Dmitrii Celpan on 9/6/15. // Copyright © 2015 yopeso.dmitriicelpan. All rights reserved. // import Foundation let FileLong = "--file" let FileShort = "-f" struct FileOption: ExecutableOption { var analyzePath = FileManager.default.currentDirectoryPath var optionArgument: Path let name = "FileOption" init(argument: Path = "") { optionArgument = argument } func executeOnDictionary(_ dictionary: inout Options) { dictionary.add([optionArgument.absolutePath(analyzePath)], toKey: ResultDictionaryFileKey) } }
mit
3d2b497ac61093cb8e22a79a048c39cc
21.535714
98
0.676704
3.968553
false
false
false
false
jeremiahyan/ResearchKit
samples/ORKParkinsonStudy/ORKParkinsonStudy/Graphs/BarGraphChartTableViewCell.swift
2
5403
/* Copyright (c) 2018, Apple Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import ResearchKit let padding: CGFloat = 10.0 class BarGraphChartTableViewCell: UITableViewCell { var graphView: ORKBarGraphChartView let titleLabel = UILabel() override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { graphView = ORKBarGraphChartView() super.init(style: style, reuseIdentifier: reuseIdentifier) self.contentView.addSubview(graphView) titleLabel.translatesAutoresizingMaskIntoConstraints = false titleLabel.font = UIFont.systemFont(ofSize: 25.0, weight: .thin) titleLabel.textAlignment = .center self.contentView.addSubview(titleLabel) setupConstraints() } func setupConstraints() { graphView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .top, multiplier: 1.0, constant: padding), NSLayoutConstraint(item: titleLabel, attribute: .left, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .left, multiplier: 1.0, constant: padding), NSLayoutConstraint(item: graphView, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: padding), NSLayoutConstraint(item: graphView, attribute: .left, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .left, multiplier: 1.0, constant: padding), NSLayoutConstraint(item: graphView, attribute: .right, relatedBy: .equal, toItem: self.safeAreaLayoutGuide, attribute: .right, multiplier: 1.0, constant: -padding), NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: graphView.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: padding) ]) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
bsd-3-clause
4584b0c80a93846369f44308706fc63b
45.577586
82
0.54007
6.629448
false
false
false
false
tadasz/MistikA
MistikA/Classes/PuzzleEnum.swift
1
11094
// // PuzzleEnum.swift // MistikA // // Created by Tadas Ziemys on 29/07/14. // Copyright (c) 2014 Tadas Ziemys. All rights reserved. // import Foundation // MARK: - Protocol protocol PuzzleEnum { var fileName: String { get } var answers: [String] { get } func isCorrectAnswer(answer: String) -> Bool } // MARK: - Optical Illusion Puzzle enum OpticalIllusionPuzzle: Int { case Kareivis = 0 case Delfinai case Asilas case Fermeris case Vovere case Geles case Arklys case Moteris case Ponas case Mociute case Seneliai case Meska case Antis case Kiskis static let allValues = [Kareivis, Delfinai, Asilas, Fermeris, Vovere, Geles, Arklys, Moteris, Ponas, Mociute, Seneliai, Meska, Antis, Kiskis] } extension OpticalIllusionPuzzle: PuzzleEnum { var fileName: String { get { return "illiusion\(self.rawValue+1).jpg" } } var answers: [String] { get { switch self { case .Kareivis: return ["kareivis", "veidas", "mociute", "boba", "sikna", "subine", "uzpakalis"] case .Delfinai: return ["porele", "seksas", "delfinai", "delfinas", "pora"] case .Asilas: return ["asilas", "ruonis"] case .Fermeris: return ["fermeris", "moteris", "zmona", "vyras", "wife", "farmer"] case .Vovere: return ["vovere", "antis", "triusis", "gulbe"] case .Geles: return ["moteris", "geles", "gele"] case .Arklys: return ["arklys", "varle"] case .Moteris: return ["moteris", "vaikas", "berniukas"] case .Ponas: return ["ponas", "asilas", "ponai", "slektos"] case .Mociute: return ["mociute", "sene", "mergina", "jaunuole", "mergaite"] case .Seneliai: return ["seneliai", "senukai", "seniai", "daininkai", "girtuokliai", "muzikantai"] case .Meska: return ["meska", "ruonis"] case .Antis: return ["antis", "kiskis", "zuikis", "triusis"] case .Kiskis: return ["kiskis", "zuikis", "anciukas", "antis"] default: return [""] } } } func isCorrectAnswer(answer: String) -> Bool { var correctWords = 0 let array = answer.componentsSeparatedByString(" ") if array.count != 2 { return false } for answerString in array { for string in self.answers { print("string = \(string) answerString = \(answerString)") let compareResult = string.compare(answerString.lowercaseString, options: NSStringCompareOptions.DiacriticInsensitiveSearch, range: nil, locale: nil) if compareResult == NSComparisonResult.OrderedSame { correctWords++ break; } } } if correctWords > 1 { return true } return false } } // MARK: - Stereo Illusion Puzzle enum StereoIllusionPuzzle: Int { case Cow = 0 case Vilkas case Dolphins case Drakonas case Drugelis case Flying_bird case Gorilla case Heart case Infinity case Kaukole case Kirvis case Pianinas case Skateboard case Skull case Sports_car case Tea_pot case Ant case Woman static let allValues = [Cow, Vilkas, Dolphins, Drakonas, Drugelis, Flying_bird, Gorilla, Heart, Infinity, Kaukole, Kirvis, Pianinas, Skateboard, Skull, Sports_car, Tea_pot, Ant, Woman] } extension StereoIllusionPuzzle: PuzzleEnum { var fileName: String { get { switch self { case Ant: return "ant.jpg" case Cow: return "cow.jpg" case Dolphins: return "dolphins.jpg" case Drakonas: return "drakonas.jpg" case Drugelis: return "drugelis.jpg" case Flying_bird: return "flying_bird.jpg" case Gorilla: return "gorilla.jpg" case Heart: return "heart.jpg" case Infinity: return "infinity.jpg" case Kaukole: return "kaukole.jpg" case Kirvis: return "kirvis.jpg" case Pianinas: return "pianinas.jpg" case Skateboard: return "skateboard.jpg" case Skull: return "skull.jpg" case Sports_car: return "sports_car.jpg" case Tea_pot: return "tea_pot.jpg" case Vilkas: return "vilkas.jpg" case Woman: return "woman.jpg" } } } var answers: [String] { get { switch self { case Ant: return ["skruzdė","skruzdėlė","skruzdele"] case Cow: return ["karve", "karvė", "jautis", "bulius"] case Dolphins: return ["delfinas", "delfinai"] case Drakonas: return ["drakonas", "slibinas", "driezas", "driežas"] case Drugelis: return ["drugelis", "drugys"] case Flying_bird: return ["paukstis", "paukštis", "skrenda", "skrendantis", "skrendantis paukstis", "erelis"] case Gorilla: return ["gorila", "gorilos", "bezdžionė", "bezdzione"] case Heart: return ["širdis", "sirdis", "meilė", "meile"] case Infinity: return ["begalybė", "begalybė", "buranka"] case Kaukole: return ["kaukuolė", "kaukuole", "mirtis"] case Kirvis: return ["kirvis", "malkos", "kapoja"] case Pianinas: return ["pianinas", "fortepijonas"] case Skateboard: return ["riedlente", "riedlentė"] case Skull: return ["kaukuolė", "kaukuole", "mirtis"] case Sports_car: return ["mašina", "masina", "sportinė mašina", "sportine masina"] case Tea_pot: return ["arbata", "arbatinukas", "arbatinis"] case Vilkas: return ["vilkas", "suo", "vilksunis", "vilksunis"] case Woman: return ["moteris", "nuogale", "nuoga moteris"] } } } func isCorrectAnswer(answer: String) -> Bool { for string in self.answers { let compareResult = string.compare(answer.lowercaseString, options: NSStringCompareOptions.DiacriticInsensitiveSearch, range: nil, locale: nil) if compareResult == NSComparisonResult.OrderedSame { return true } } return false } } // MARK: - Map Puzzle enum MapPuzzle: Int { case Akademija = 0 case Aleksotas case Alkoholikai case Bendrabutis case Botanikos case Dobuzinskio case Gedimino case Sala case Santaka case Senamiestis case Silainiai case Zoo static let allValues = [Akademija, Aleksotas, Alkoholikai, Bendrabutis, Botanikos, Dobuzinskio, Gedimino, Sala, Santaka, Senamiestis, Silainiai, Zoo] } extension MapPuzzle: PuzzleEnum { var fileName: String { get { switch self { case .Akademija: return "akademija.png" case Aleksotas: return "aleksotas.png" case Alkoholikai: return "alkoholikai.png" case Bendrabutis: return "bendrabutis.png" case Botanikos: return "botanikos.png" case Dobuzinskio: return "dobuzinskio.png" case Gedimino: return "gedimino.png" case Sala: return "sala.png" case Santaka: return "santaka.png" case Senamiestis: return "senamiestis.png" case Silainiai: return "silainiai.png" case Zoo: return "zoo.png" } } } var puzzleCount: Int { get { return MapPuzzle.allValues.count } } var answers: [String] { get { switch self { case .Akademija: return ["akademija","universitetas","veterinarija","veterinarijos akademija","LSMU"] case Aleksotas: return ["tado tevai","tevai","aleksotas"] case Alkoholikai: return ["alkoholikai", "klubas sala", "pirmas musu butas", "alkoholiku butas", "dauksos", "pilis"] case Bendrabutis: return ["bendrabutis", "bendrikas", "sajungos", "sąjungos aikštė", "barakas"] case Botanikos: return ["botanikos", "botanikos sodas", "botanika"] case Dobuzinskio: return ["dobuzinskio", "laisves aleja", "gedimino", "dobužinskio", "udros namai"] case Gedimino: return ["gedimino", "soburas", "laisve"] case Sala: return ["sala", "nemuno sala"] case Santaka: return ["santaka", "santakos parkas", "nemunas ir neris"] case Senamiestis: return ["senamiestis", "musu butas", "biruta", "birutos butas"] case Silainiai: return ["silainiai", "silainiu ziedas", "šilainiai"] case Zoo: return ["zoo", "zoologijos sodas", "zoologijos", "gyvunai"] } } } func isCorrectAnswer(answer: String) -> Bool { for string in self.answers { if string == answer.lowercaseString { return true } } return false } } // MARK: - Final Puzzle enum FinalPuzzle: Int { case Rasa = 0 case Turiu case Tau case Klau case Sima static let allValues = [Rasa, Turiu, Tau, Klau, Sima] } extension FinalPuzzle: PuzzleEnum { var fileName: String { get { switch self { case Rasa: return "rasa.jpg" case Turiu: return "turiu.jpg" case Tau: return "tau.jpg" case Klau: return "klau.jpg" case Sima: return "sima.jpg" } } } var answers: [String] { get { switch self { case Rasa: return ["rasa"] case Turiu: return ["turiu"] case Tau: return ["tau"] case Klau: return ["klau"] case Sima: return ["sima"] } } } func isCorrectAnswer(answer: String) -> Bool { for string in self.answers { let compareResult = string.compare(answer.lowercaseString, options: NSStringCompareOptions.DiacriticInsensitiveSearch, range: nil, locale: nil) if compareResult == NSComparisonResult.OrderedSame { return true } } return false } }
mit
d8702bb50479e0d03a39d5371fa3e40f
27.173028
188
0.529311
3.948288
false
false
false
false
Sephiroth87/C-swifty4
Common/MetalPipeline.swift
1
1974
// // MetalPipeline.swift // C-swifty4 // // Created by Fabio on 20/11/2017. // Copyright © 2017 orange in a day. All rights reserved. // import MetalKit class MetalPipeline { private let texture: MTLTexture private let scaleFilter: ScaleFilter let device: MTLDevice let pipelineState: MTLRenderPipelineState let commandQueue: MTLCommandQueue let processedTexture: MTLTexture init(usesMtlBuffer: Bool = false) { device = MTLCreateSystemDefaultDevice()! let library = device.makeDefaultLibrary()! let pipeline = MTLRenderPipelineDescriptor() pipeline.colorAttachments[0].pixelFormat = .bgra8Unorm pipeline.vertexFunction = library.makeFunction(name: "vertex_main") pipeline.fragmentFunction = library.makeFunction(name: "fragment_main") pipelineState = try! device.makeRenderPipelineState(descriptor: pipeline) commandQueue = device.makeCommandQueue()! let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm, width: 512, height: 512, mipmapped: false) texture = device.makeTexture(descriptor: textureDescriptor)! scaleFilter = ScaleFilter(device: device, library: library, usesMtlBuffer: usesMtlBuffer) processedTexture = scaleFilter.texture if usesMtlBuffer && processedTexture.buffer == nil { fatalError("Processed texture needs to have a backing buffer") } } func process(data: UnsafePointer<UInt32>, size: CGSize, additionalCommands: ((MTLCommandBuffer) -> Void)? = nil) { texture.replace(region: MTLRegionMake2D(0, 0, Int(size.width), Int(size.height)), mipmapLevel: 0, withBytes: data, bytesPerRow: Int(size.width) * 4) let commandBuffer = commandQueue.makeCommandBuffer()! scaleFilter.apply(to: texture, with: commandBuffer) additionalCommands?(commandBuffer) commandBuffer.commit() } }
mit
5d7d17f11a0a94232c423a821e2fbb8a
39.265306
156
0.699949
4.835784
false
false
false
false
Conche/Conche
Conche/Commands/build.swift
2
5049
import Darwin import PathKit func dependencyPath(conchePath:Path, _ spec:Specification) -> Path { let packagesPath = conchePath + "packages" return packagesPath + spec.name } func downloadDependencies(conchePath: Path, specifications: [Specification]) throws { let downloadSources = specifications.filter { !dependencyPath(conchePath, $0).exists } if !downloadSources.isEmpty { print("Downloading Dependencies") for spec in downloadSources { print("-> \(spec.name)") if let source = spec.source { try source.download(dependencyPath(conchePath, spec)) } else { print("git / tag source not found.") exit(1) } } } } func resolve(specification: Specification) throws -> DependencyGraph { let cpSource = GitFilesystemSource(name: "CocoaPods", uri: "https://github.com/CocoaPods/Specs") let localSource = LocalFilesystemSource(path: Path.current) let dependency = try Dependency(name: specification.name, requirements: [Requirement(specification.version.description)]) let dependencyGraph: DependencyGraph do { dependencyGraph = try resolve(dependency, sources: [localSource, cpSource]) } catch { try cpSource.update() dependencyGraph = try resolve(dependency, sources: [localSource, cpSource]) } return dependencyGraph } func buildTask() throws -> Task { let spec = try findPodspec() let conchePath = Path(".conche") if !conchePath.exists { try conchePath.mkdir() } let moddir = conchePath + "modules" if !moddir.exists { try moddir.mkdir() } let libdir = conchePath + "lib" if !libdir.exists { try libdir.mkdir() } let dependencyGraph = try resolve(spec) let task = try dependencyGraph.buildTask() if let cliEntryPoints = spec.entryPoints["cli"] { if !cliEntryPoints.isEmpty { let cliTask = AnonymousTask("Building Entry Points") { let bindir = conchePath + "bin" if !bindir.exists { try bindir.mkdir() } let libraries = dependencyGraph.flatten().map { $0.name } + [spec.name] let flags = libraries.map { "-l\($0)" }.joinWithSeparator(" ") for (name, source) in cliEntryPoints { let destination = bindir + name let libdir = conchePath + "lib" let modulesdir = conchePath + "modules" print("-> \(name) -> \(destination)") try swiftc(["-I", modulesdir.description, "-L", libdir.description, flags, "-o", destination.description, source]) } } cliTask.dependencies.append(task) return cliTask } } return task } public func build() throws { try runTask(try buildTask()) } public func install(destination: String) throws { let destinationPath = Path(destination) let conchePath = Path(".conche") try destinationPath.mkpath() let specification = try findPodspec() guard let cliEntryPoints = specification.entryPoints["cli"] where !cliEntryPoints.isEmpty else { throw Error("\(specification.name) does not have any installable tools.") } let task = AnonymousTask("Installing \(specification.name)") { let destinationBinDir = destinationPath + "bin" let destinationLibDir = destinationPath + "lib" + specification.name try destinationBinDir.mkpath() try destinationLibDir.mkpath() // Copy libraries let dependencyGraph = try resolve(specification) let specifications = dependencyGraph.flatten() let libraries = specifications.map { $0.name } for library in libraries { let source: Path = conchePath + "lib" + "lib\(library).dylib" let destination = destinationLibDir + "lib\(library).dylib" if destination.exists { try destination.delete() } try source.copy(destination) } // Update library search paths func updateSearchPath(dependency: String, binary: Path) throws { try invoke("install_name_tool", [ "-change", ".conche/lib/lib\(dependency).dylib", "@executable_path/../lib/\(specification.name)/lib\(dependency).dylib", binary.description, ]) } func updateLibSearchPath(dependencyGraph: DependencyGraph) throws { let library = destinationLibDir + "lib\(dependencyGraph.root.name).dylib" for dependency in dependencyGraph.dependencies { try updateSearchPath(dependency.root.name, binary: library) } try dependencyGraph.dependencies.forEach(updateLibSearchPath) } try updateLibSearchPath(dependencyGraph) // Copy binary for (entryPoint, _) in cliEntryPoints { let source: Path = conchePath + "bin" + entryPoint let destination = destinationBinDir + entryPoint if destination.exists { try destination.delete() } try source.copy(destination) for specification in dependencyGraph.flatten() { try updateSearchPath(specification.name, binary: destination) } try updateSearchPath(specification.name, binary: destination) } } task.dependencies.append(try buildTask()) try runTask(task) }
bsd-2-clause
50fd6ce5251c0f2441b4a48e07de237c
31.785714
124
0.677164
4.436731
false
false
false
false
jay18001/brickkit-ios
Tests/Bricks/ButtonBrickTests.swift
1
11304
// // ButtonBrickTests.swift // BrickKit // // Created by Ruben Cagnie on 10/6/16. // Copyright © 2016 Wayfair. All rights reserved. // import XCTest @testable import BrickKit class ButtonBrickTests: XCTestCase { fileprivate let ButtonBrickIdentifier = "ButtonBrickIdentifier" var brickCollectionView: BrickCollectionView! var buttonBrick: ButtonBrick! override func setUp() { super.setUp() continueAfterFailure = false brickCollectionView = BrickCollectionView(frame: CGRect(x: 0, y: 0, width: 320, height: 480)) } func setupButtonBrickWithModel(_ model: ButtonBrickCellModel) -> ButtonBrickCell? { return setupSection(ButtonBrick(ButtonBrickIdentifier, dataSource: model)) } func setupButtonBrick(_ title: String, configureButtonBlock: ConfigureButtonBlock? = nil) -> ButtonBrickCell? { return setupSection(ButtonBrick(ButtonBrickIdentifier, title: title, configureButtonBlock: configureButtonBlock)) } func setupSection(_ buttonBrick: ButtonBrick) -> ButtonBrickCell? { brickCollectionView.registerBrickClass(ButtonBrick.self) self.buttonBrick = buttonBrick let section = BrickSection(bricks: [ buttonBrick ]) brickCollectionView.setSection(section) brickCollectionView.layoutSubviews() return buttonCell } var buttonCell: ButtonBrickCell? { let cell = brickCollectionView.cellForItem(at: IndexPath(item: 0, section: 1)) as? ButtonBrickCell cell?.layoutIfNeeded() return cell } func testButtonBrick() { let cell = setupButtonBrick("Hello World") XCTAssertEqual(cell?.button.titleLabel?.text, "Hello World") XCTAssertEqual(cell?.topSpaceConstraint?.constant, 0) XCTAssertEqual(cell?.bottomSpaceConstraint?.constant, 0) XCTAssertEqual(cell?.leftSpaceConstraint?.constant, 0) XCTAssertEqual(cell?.rightSpaceConstraint?.constant, 0) let buttonSize = CGSize(width: 320, height: 30) XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: buttonSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint.zero, size: buttonSize)) } func testButtonBrickMultiLine() { let cell = setupButtonBrick("Hello World\nHello World") XCTAssertEqual(cell?.button.titleLabel?.text, "Hello World\nHello World") let buttonSize = CGSize(width: 320, height: 48) XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: buttonSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint.zero, size: buttonSize)) } func testButtonBrickEdgeInsets() { let cell = setupButtonBrick("Hello World", configureButtonBlock: { cell in cell.edgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 10) }) XCTAssertEqual(cell?.topSpaceConstraint?.constant, 5) XCTAssertEqual(cell?.leftSpaceConstraint?.constant, 5) XCTAssertEqual(cell?.bottomSpaceConstraint?.constant, 10) XCTAssertEqual(cell?.rightSpaceConstraint?.constant, 10) let cellSize = CGSize(width: 320, height: 45) let buttonSize = CGSize(width: 305, height: 30) XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: cellSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint(x: 5, y: 5), size: buttonSize)) } func testButtonBrickEdgeInsetsMultiLine() { let cell = setupButtonBrick("Hello World\nHello World", configureButtonBlock: { cell in cell.edgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 10) }) let cellSize = CGSize(width: 320, height: 63) let buttonSize = CGSize(width: 305, height: 48) XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: cellSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint(x: 5, y: 5), size: buttonSize)) } func testChangeText() { var cell = setupButtonBrick("Hello World") XCTAssertEqual(cell?.button.titleLabel?.text, "Hello World") buttonBrick.title = "World Hello" XCTAssertEqual(buttonBrick.title, "World Hello") brickCollectionView.reloadBricksWithIdentifiers([ButtonBrickIdentifier], shouldReloadCell: false) cell = buttonCell XCTAssertEqual(cell?.button.title(for: UIControlState()), "World Hello") buttonBrick.title = "Hello World" brickCollectionView.reloadBricksWithIdentifiers([ButtonBrickIdentifier], shouldReloadCell: true) brickCollectionView.layoutIfNeeded() cell = buttonCell XCTAssertEqual(cell?.button.titleLabel?.text, "Hello World") } func testSetupButtonBlock() { let expectation = self.expectation(description: "Should call setup button block") let model = ButtonBrickCellModel(title: "Hello World", configureButtonBlock: { (cell) in expectation.fulfill() }) _ = setupButtonBrickWithModel(model) waitForExpectations(timeout: 5, handler: nil) } func testButtonChangeText() { let buttonBrick = ButtonBrick(title: "Hello World") buttonBrick.title = "World Hello" XCTAssertEqual(buttonBrick.title, "World Hello") } func testButtonConfigureCellBlock() { let configureButtonBlock: ConfigureButtonBlock = { cell in } let buttonBrick = ButtonBrick(title: "Hello World") buttonBrick.configureButtonBlock = configureButtonBlock XCTAssertNotNil(buttonBrick.configureButtonBlock) } func testButtonTextShouldBeEmptyStringWhenSettingToNil() { let buttonBrick = ButtonBrick(title: "Hello World") buttonBrick.title = nil XCTAssertEqual(buttonBrick.title, "") } func testCantSetTextOfButtonBrickWithWrongDataSource() { expectFatalError { let buttonBrick = ButtonBrick(dataSource: FixedButtonDataSource()) buttonBrick.title = "Hello World" } } func testCantGetTextOfButtonBrickWithWrongDataSource() { expectFatalError { let buttonBrick = ButtonBrick(dataSource: FixedButtonDataSource()) let _ = buttonBrick.title } } func testCantSetConfigureCellBlockOfButtonBrickWithWrongDataSource() { expectFatalError { let buttonBrick = ButtonBrick(dataSource: FixedButtonDataSource()) buttonBrick.configureButtonBlock = { cell in } } } func testCantGetConfigureCellBlockOfButtonBrickWithWrongDataSource() { expectFatalError { let buttonBrick = ButtonBrick(dataSource: FixedButtonDataSource()) let _ = buttonBrick.configureButtonBlock } } func testButtonBrickChevronEdgeInsets() { brickCollectionView.registerNib(ButtonBrickNibs.Chevron, forBrickWithIdentifier: ButtonBrickIdentifier) let cell = setupButtonBrick("Hello World", configureButtonBlock: { cell in cell.edgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 10) }) XCTAssertEqual(cell?.topSpaceConstraint?.constant, 5) XCTAssertEqual(cell?.leftSpaceConstraint?.constant, 5) XCTAssertEqual(cell?.bottomSpaceConstraint?.constant, 10) XCTAssertEqual(cell?.rightSpaceConstraint?.constant, 10) #if os(iOS) let cellSize = CGSize(width: 320, height: 45) let buttonSize = CGSize(width: 320 - 15 - cell!.rightImage!.frame.width, height: 30) #else let cellSize = CGSize(width: 320, height: 101) let buttonSize = CGSize(width: 320 - 15 - cell!.rightImage!.frame.width, height: 86) #endif XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: cellSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint(x: 5, y: 5), size: buttonSize)) } func testButtonBrickChevronEdgeInsetsMultiLine() { brickCollectionView.registerNib(ButtonBrickNibs.Chevron, forBrickWithIdentifier: ButtonBrickIdentifier) let cell = setupButtonBrick("Hello World\nHello World", configureButtonBlock: { cell in cell.edgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 10, right: 10) }) #if os(iOS) let cellSize = CGSize(width: 320, height: 63) let buttonSize = CGSize(width: 320 - 15 - cell!.rightImage!.frame.width, height: 48) #else let cellSize = CGSize(width: 320, height: 147) let buttonSize = CGSize(width: 320 - 15 - cell!.rightImage!.frame.width, height: 132) #endif XCTAssertEqual(cell?.frame, CGRect(origin: CGPoint.zero, size: cellSize)) XCTAssertEqual(cell?.button.frame, CGRect(origin: CGPoint(x: 5, y: 5), size: buttonSize)) } func testButtonDelegate() { let delegate = FixedButtonDelegate() let cell = setupSection(ButtonBrick(ButtonBrickIdentifier, dataSource: FixedButtonDataSource(), delegate: delegate)) // Ideally cell?.button?.sendActionsForControlEvents(.TouchUpInside) is called, but this doesn't work in XCTests let actions = cell?.button.actions(forTarget: cell, forControlEvent: .touchUpInside) XCTAssertEqual(actions?.count, 1) cell!.perform(Selector(actions!.first!), with: cell!.button) XCTAssertTrue(delegate.buttonTouched) } func testBrickCellTapDelegate() { let tapDelegate = MockBrickCellTapDelegate() let delegate = FixedButtonDelegate() let brick = ButtonBrick(ButtonBrickIdentifier, dataSource: FixedButtonDataSource(), delegate: delegate) brick.brickCellTapDelegate = tapDelegate let cell = setupSection(brick) cell?.didTapCell() XCTAssertTrue(tapDelegate.didTapBrickCellCalled) } func testNilBrickCellTapDelegate() { let tapDelegate = MockBrickCellTapDelegate() let delegate = FixedButtonDelegate() let cell = setupSection(ButtonBrick(ButtonBrickIdentifier, dataSource: FixedButtonDataSource(), delegate: delegate)) XCTAssertNil(cell?.gestureRecognizers) cell?.didTapCell() XCTAssertFalse(tapDelegate.didTapBrickCellCalled) } func testMultipleBrickCellTapDelegate() { let tapDelegate = MockBrickCellTapDelegate() let delegate = FixedButtonDelegate() let brick = ButtonBrick(ButtonBrickIdentifier, dataSource: FixedButtonDataSource(), delegate: delegate) brick.brickCellTapDelegate = tapDelegate let cell = setupSection(brick) for _ in 0..<10 { brickCollectionView.reloadData() } XCTAssertTrue(cell?.gestureRecognizers?.count == 1) } } class FixedButtonDataSource: ButtonBrickCellDataSource { func configureButtonBrick(_ cell: ButtonBrickCell) { } } class FixedButtonDelegate: ButtonBrickCellDelegate { var buttonTouched = false func didTapOnButtonForButtonBrickCell(_ cell: ButtonBrickCell) { buttonTouched = true } } class MockBrickCellTapDelegate: NSObject, BrickCellTapDelegate { var didTapBrickCellCalled = false func didTapBrickCell(_ brickCell: BrickCell) { didTapBrickCellCalled = true } }
apache-2.0
fce939893489c3698b7cb583576004c4
36.92953
124
0.680173
5.223198
false
true
false
false
spothero/SHEmailValidator
Sources/SpotHeroEmailValidator/SHAutocorrectSuggestionView.swift
1
14585
// Copyright © 2021 SpotHero, Inc. All rights reserved. #if canImport(UIKit) import Foundation import UIKit /// Completion block for when the autocorrect suggestion view is shown. public typealias SetupBlock = (SHAutocorrectSuggestionView?) -> Void // Obj-C code is documented above every call or signature for ease of maintenance and identifying any escaped defects. // As we refactor the behavior and logic and feel more confident in the translation to Swift, we'll remove the commented code blocks. public class SHAutocorrectSuggestionView: UIView { private static let cornerRadius: CGFloat = 6 private static let arrowHeight: CGFloat = 12 private static let arrowWidth: CGFloat = 8 private static let maxWidth: CGFloat = 240 private static let dismissButtonWidth: CGFloat = 30 weak var delegate: AutocorrectSuggestionViewDelegate? public var suggestedText: String? public var fillColor: UIColor? public var titleColor: UIColor? public var suggestionColor: UIColor? private var target: UIView? private var titleRect: CGRect? private var suggestionRect: CGRect? private let titleFont: UIFont private let suggestionFont: UIFont private let title: String? public static func show(from target: UIView, inContainerView container: UIView?, title: String?, autocorrectSuggestion suggestion: String?, withSetupBlock block: SetupBlock?) -> SHAutocorrectSuggestionView { let suggestionView = SHAutocorrectSuggestionView(target: target, title: title, autocorrectSuggestion: suggestion, withSetupBlock: block) suggestionView.show(from: target, inContainerView: container) return suggestionView } public static func show(from target: UIView, title: String?, autocorrectSuggestion suggestion: String?, withSetupBlock block: SetupBlock?) -> SHAutocorrectSuggestionView { return SHAutocorrectSuggestionView.show(from: target, inContainerView: target.superview, title: title, autocorrectSuggestion: suggestion, withSetupBlock: block) } public static func defaultFillColor() -> UIColor { return .black } public static func defaultTitleColor() -> UIColor { return .white } public static func defaultSuggestionColor() -> UIColor { return UIColor(red: 0.5, green: 0.5, blue: 1.0, alpha: 1.0) } public init(target: UIView, title: String?, autocorrectSuggestion suggestion: String?, withSetupBlock block: SetupBlock?) { self.title = title self.suggestedText = suggestion self.titleFont = UIFont.boldSystemFont(ofSize: 13) self.suggestionFont = UIFont.boldSystemFont(ofSize: 13) super.init(frame: .zero) let paragraphTitleStyle = NSMutableParagraphStyle() paragraphTitleStyle.lineBreakMode = .byWordWrapping paragraphTitleStyle.alignment = .left let paragraphSuggestedStyle = NSMutableParagraphStyle() paragraphSuggestedStyle.lineBreakMode = .byCharWrapping paragraphSuggestedStyle.alignment = .left let titleSizeRect = title?.boundingRect(with: CGSize(width: Self.maxWidth - Self.dismissButtonWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [ .font: self.titleFont, .paragraphStyle: paragraphTitleStyle, .foregroundColor: UIColor.white, ], context: nil) let suggestionSizeRect = suggestion?.boundingRect(with: CGSize(width: Self.maxWidth - Self.dismissButtonWidth, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: [ .font: self.suggestionFont, .paragraphStyle: paragraphSuggestedStyle, .foregroundColor: Self.defaultSuggestionColor(), ], context: nil) guard let titleSize = titleSizeRect?.size, let suggestionSize = suggestionSizeRect?.size else { return } let width = max(titleSize.width, suggestionSize.width) + Self.dismissButtonWidth + (Self.cornerRadius * 2) let height = titleSize.height + suggestionSize.height + Self.arrowHeight + (Self.cornerRadius * 2) let left = max(10, target.center.x - (width / 2)) let top = target.frame.origin.y - height + 4 self.frame = CGRect(x: left, y: top, width: width, height: height).integral self.isOpaque = false self.titleRect = CGRect(x: (width - Self.dismissButtonWidth - titleSize.width) / 2, y: Self.cornerRadius, width: titleSize.width, height: titleSize.height) self.suggestionRect = CGRect(x: Self.cornerRadius, y: Self.cornerRadius + titleSize.height, width: suggestionSize.width, height: suggestionSize.height) block?(self) self.fillColor = self.fillColor ?? Self.defaultFillColor() self.titleColor = self.titleColor ?? Self.defaultTitleColor() self.suggestionColor = self.suggestionColor ?? Self.defaultSuggestionColor() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func draw(_ rect: CGRect) { let contentSize = CGSize(width: self.bounds.size.width, height: self.bounds.size.height - Self.arrowHeight) let arrowBottom = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height) let path = CGMutablePath() path.move(to: CGPoint(x: arrowBottom.x, y: arrowBottom.y)) path.addLine(to: CGPoint(x: arrowBottom.x - Self.arrowWidth, y: arrowBottom.y - Self.arrowHeight)) path.addArc(tangent1End: CGPoint(x: 0, y: contentSize.height), tangent2End: CGPoint(x: 0, y: contentSize.height - Self.cornerRadius), radius: Self.cornerRadius) path.addArc(tangent1End: CGPoint(x: 0, y: 0), tangent2End: CGPoint(x: Self.cornerRadius, y: 0), radius: Self.cornerRadius) path.addArc(tangent1End: CGPoint(x: contentSize.width, y: 0), tangent2End: CGPoint(x: contentSize.width, y: Self.cornerRadius), radius: Self.cornerRadius) path.addArc(tangent1End: CGPoint(x: contentSize.width, y: contentSize.height), tangent2End: CGPoint(x: contentSize.width - Self.cornerRadius, y: contentSize.height), radius: Self.cornerRadius) path.addLine(to: CGPoint(x: arrowBottom.x + Self.arrowWidth, y: arrowBottom.y - Self.arrowHeight)) path.closeSubpath() guard let context = UIGraphicsGetCurrentContext() else { return } context.saveGState() context.addPath(path) context.clip() let fillColor = self.fillColor ?? Self.defaultFillColor() context.setFillColor(fillColor.cgColor) context.fill(bounds) context.restoreGState() let separatorX = contentSize.width - Self.dismissButtonWidth context.setStrokeColor(UIColor.gray.cgColor) context.setLineWidth(1) context.move(to: CGPoint(x: separatorX, y: 0)) context.addLine(to: CGPoint(x: separatorX, y: contentSize.height)) context.strokePath() let xSize: CGFloat = 12 context.setLineWidth(4) context.move(to: CGPoint(x: separatorX + (Self.dismissButtonWidth - xSize) / 2, y: (contentSize.height - xSize) / 2)) context.addLine(to: CGPoint(x: separatorX + (Self.dismissButtonWidth + xSize) / 2, y: (contentSize.height + xSize) / 2)) context.strokePath() context.move(to: CGPoint(x: separatorX + (Self.dismissButtonWidth - xSize) / 2, y: (contentSize.height + xSize) / 2)) context.addLine(to: CGPoint(x: separatorX + (Self.dismissButtonWidth + xSize) / 2, y: (contentSize.height - xSize) / 2)) context.strokePath() let paragraphTitleStyle = NSMutableParagraphStyle() paragraphTitleStyle.lineBreakMode = .byWordWrapping paragraphTitleStyle.alignment = .center let paragraphSuggestedStyle = NSMutableParagraphStyle() paragraphSuggestedStyle.lineBreakMode = .byCharWrapping paragraphSuggestedStyle.alignment = .left if let title = self.title, let titleRect = self.titleRect { self.titleColor?.set() title.draw(in: titleRect, withAttributes: [ .font: self.titleFont, .paragraphStyle: paragraphTitleStyle, .foregroundColor: UIColor.white, ]) } if let suggestedText = self.suggestedText, let suggestionRect = self.suggestionRect { self.suggestionColor?.set() suggestedText.draw(in: suggestionRect, withAttributes: [ .font: self.suggestionFont, .paragraphStyle: paragraphSuggestedStyle, .foregroundColor: Self.defaultSuggestionColor(), ]) } } override public func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { guard touches.count == 1 else { return } guard let touchPoint = touches.first?.location(in: self) else { return } let viewSize = self.bounds.size guard touchPoint.x >= 0, touchPoint.x < viewSize.width, touchPoint.y >= 0, touchPoint.y < viewSize.height - Self.arrowHeight else { return } let wasDismissedWithAccepted = touchPoint.x <= viewSize.width - Self.dismissButtonWidth && self.suggestedText != nil self.delegate?.suggestionView(self, wasDismissedWithAccepted: wasDismissedWithAccepted) self.dismiss() } public func show(from target: UIView, inContainerView container: UIView?) { self.target = target self.alpha = 0.2 self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) self.frame = target.superview?.convert(self.frame, to: container) ?? .zero container?.addSubview(self) UIView.animate( withDuration: 0.2, animations: { self.alpha = 1 self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) }, completion: { _ in UIView.animate(withDuration: 0.1, animations: { self.transform = .identity }) } ) } public func updatePosition() { guard let target = self.target, let targetSuperview = target.superview else { return } let width = self.bounds.size.width let height = self.bounds.size.height let left = max(10, target.center.x - (width / 2)) let top = target.frame.origin.y - height self.frame = targetSuperview.convert(CGRect(x: left, y: top, width: width, height: height), to: self.superview).integral } public func dismiss() { UIView.animate( withDuration: 0.1, animations: { self.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) }, completion: { _ in UIView.animate( withDuration: 0.2, animations: { self.alpha = 0.2 self.transform = CGAffineTransform(scaleX: 0.6, y: 0.6) }, completion: { _ in self.removeFromSuperview() self.target = nil } ) } ) } } #endif
apache-2.0
d4c1f26579842591270afb3545be6f1c
44.575
143
0.508914
6.053964
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/NotificationPreferencesController.swift
1
23293
// // NotificationPreferencesController.swift // Telegram // // Created by Mikhail Filimonov on 03/06/2019. // Copyright © 2019 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit import Postbox import TelegramCore import InAppSettings private let modernSoundsNamePaths: [String] = [ strings().notificationsSoundNote, strings().notificationsSoundAurora, strings().notificationsSoundBamboo, strings().notificationsSoundChord, strings().notificationsSoundCircles, strings().notificationsSoundComplete, strings().notificationsSoundHello, strings().notificationsSoundInput, strings().notificationsSoundKeys, strings().notificationsSoundPopcorn, strings().notificationsSoundPulse, strings().notificationsSoundSynth ] private let classicSoundNamePaths: [String] = [ strings().notificationsSoundTritone, strings().notificationsSoundTremolo, strings().notificationsSoundAlert, strings().notificationsSoundBell, strings().notificationsSoundCalypso, strings().notificationsSoundChime, strings().notificationsSoundGlass, strings().notificationsSoundTelegraph ] private func soundName(sound: PeerMessageSound) -> String { switch sound { case .none: return strings().notificationsSoundNone case .default: return "" case let .bundledModern(id): if id >= 0 && Int(id) < modernSoundsNamePaths.count { return modernSoundsNamePaths[Int(id)] } return "Sound \(id)" case let .bundledClassic(id): if id >= 0 && Int(id) < classicSoundNamePaths.count { return classicSoundNamePaths[Int(id)] } return "Sound \(id)" case let .cloud(fileId): return "Sound \(fileId)" } } public func localizedPeerNotificationSoundString(sound: PeerMessageSound, default: PeerMessageSound? = nil, list: NotificationSoundList? = nil) -> String { switch sound { case .`default`: if let defaultSound = `default` { let name = soundName(sound: defaultSound) let actualName: String if name.isEmpty { actualName = soundName(sound: .bundledModern(id: 0)) } else { actualName = name } return strings().peerInfoNotificationsDefaultSound(actualName) } else { return strings().peerInfoNotificationsDefault } case let .cloud(fileId): if let list = list, let sound = list.sounds.first(where: { $0.file.fileId.id == fileId }) { if sound.file.fileName == nil || sound.file.fileName!.isEmpty, sound.file.isVoice { return strings().notificationSoundToneVoice } return (sound.file.fileName ?? "#").nsstring.deletingPathExtension } else { return strings().peerInfoNotificationsDefault } default: return soundName(sound: sound) } } func fileNameForNotificationSound(postbox: Postbox, sound: PeerMessageSound, defaultSound: PeerMessageSound?, list: NotificationSoundList? = nil) -> Signal<TelegramMediaResource?, NoError> { switch sound { case .none: return .single(nil) case .`default`: if let defaultSound = defaultSound { if case .default = defaultSound { return .single(SoundEffectPlay.resource(name: "100", type: "m4a")) } else { return fileNameForNotificationSound(postbox: postbox, sound: defaultSound, defaultSound: nil, list: list) } } else { return .single(LocalFileReferenceMediaResource(localFilePath: "default", randomId: arc4random64())) } case let .bundledModern(id): return .single(SoundEffectPlay.resource(name: "\(id + 100)", type: "m4a")) case let .bundledClassic(id): return .single(SoundEffectPlay.resource(name: "\(id + 2)", type: "m4a")) case let .cloud(fileId): if let list = list { if let file = list.sounds.first(where: { $0.file.fileId.id == fileId})?.file { _ = fetchedMediaResource(mediaBox: postbox.mediaBox, reference: .standalone(resource: file.resource), ranges: nil, statsCategory: .audio, reportResultStatus: true).start() return postbox.mediaBox.resourceData(id: file.resource.id) |> filter { $0.complete } |> take(1) |> map { _ in return file.resource } } } return .single(nil) } } enum NotificationsAndSoundsEntryTag: ItemListItemTag { case allAccounts case messagePreviews case includeChannels case unreadCountCategory case joinedNotifications case reset var stableId: InputDataEntryId { switch self { case .allAccounts: return .general(_id_all_accounts) case .messagePreviews: return .general(_id_message_preview) case .includeChannels: return .general(_id_include_channels) case .unreadCountCategory: return .general(_id_count_unred_messages) case .joinedNotifications: return .general(_id_new_contacts) case .reset: return .general(_id_reset) } } func isEqual(to other: ItemListItemTag) -> Bool { if let other = other as? NotificationsAndSoundsEntryTag, self == other { return true } else { return false } } } private final class NotificationArguments { let resetAllNotifications:() -> Void let toggleMessagesPreview:() -> Void let toggleNotifications:() -> Void let notificationTone:() -> Void let toggleIncludeUnreadChats:(Bool) -> Void let toggleCountUnreadMessages:(Bool) -> Void let toggleIncludeGroups:(Bool) -> Void let toggleIncludeChannels:(Bool) -> Void let allAcounts: ()-> Void let snoof: ()-> Void let updateJoinedNotifications: (Bool) -> Void let toggleBadge: (Bool)->Void let toggleRequestUserAttention: ()->Void let toggleInAppSounds:(Bool)->Void init(resetAllNotifications: @escaping() -> Void, toggleMessagesPreview:@escaping() -> Void, toggleNotifications:@escaping() -> Void, notificationTone:@escaping() -> Void, toggleIncludeUnreadChats:@escaping(Bool) -> Void, toggleCountUnreadMessages:@escaping(Bool) -> Void, toggleIncludeGroups:@escaping(Bool) -> Void, toggleIncludeChannels:@escaping(Bool) -> Void, allAcounts: @escaping()-> Void, snoof: @escaping()-> Void, updateJoinedNotifications: @escaping(Bool) -> Void, toggleBadge: @escaping(Bool)->Void, toggleRequestUserAttention: @escaping ()->Void, toggleInAppSounds: @escaping(Bool)->Void) { self.resetAllNotifications = resetAllNotifications self.toggleMessagesPreview = toggleMessagesPreview self.toggleNotifications = toggleNotifications self.notificationTone = notificationTone self.toggleIncludeUnreadChats = toggleIncludeUnreadChats self.toggleCountUnreadMessages = toggleCountUnreadMessages self.toggleIncludeGroups = toggleIncludeGroups self.toggleIncludeChannels = toggleIncludeChannels self.allAcounts = allAcounts self.snoof = snoof self.updateJoinedNotifications = updateJoinedNotifications self.toggleBadge = toggleBadge self.toggleRequestUserAttention = toggleRequestUserAttention self.toggleInAppSounds = toggleInAppSounds } } private let _id_all_accounts = InputDataIdentifier("_id_all_accounts") private let _id_notifications = InputDataIdentifier("_id_notifications") private let _id_message_preview = InputDataIdentifier("_id_message_preview") private let _id_reset = InputDataIdentifier("_id_reset") private let _id_badge_enabled = InputDataIdentifier("_badge_enabled") private let _id_include_muted_chats = InputDataIdentifier("_id_include_muted_chats") private let _id_include_public_group = InputDataIdentifier("_id_include_public_group") private let _id_include_channels = InputDataIdentifier("_id_include_channels") private let _id_count_unred_messages = InputDataIdentifier("_id_count_unred_messages") private let _id_new_contacts = InputDataIdentifier("_id_new_contacts") private let _id_snoof = InputDataIdentifier("_id_snoof") private let _id_tone = InputDataIdentifier("_id_tone") private let _id_bounce = InputDataIdentifier("_id_bounce") private let _id_turnon_notifications = InputDataIdentifier("_id_turnon_notifications") private let _id_turnon_notifications_title = InputDataIdentifier("_id_turnon_notifications_title") private let _id_message_effect = InputDataIdentifier("_id_message_effect") private func notificationEntries(settings:InAppNotificationSettings, soundList: NotificationSoundList?, globalSettings: GlobalNotificationSettingsSet, accounts: [AccountWithInfo], unAuthStatus: UNUserNotifications.AuthorizationStatus, arguments: NotificationArguments) -> [InputDataEntry] { var entries:[InputDataEntry] = [] var sectionId: Int32 = 0 var index: Int32 = 0 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 switch unAuthStatus { case .denied: entries.append(InputDataEntry.custom(sectionId: sectionId, index: index, value: .none, identifier: _id_turnon_notifications_title, equatable: nil, comparable: nil, item: { initialSize, stableId in return TurnOnNotificationsRowItem(initialSize, stableId: stableId, viewType: .firstItem) })) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_turnon_notifications, data: InputDataGeneralData(name: strings().notificationSettingsTurnOn, color: theme.colors.text, type: .none, viewType: .lastItem, action: { openSystemSettings(.notifications) }))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 default: break } if accounts.count > 1 { entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsShowNotificationsFrom), data: InputDataGeneralTextData(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_all_accounts, data: InputDataGeneralData(name: strings().notificationSettingsAllAccounts, color: theme.colors.text, type: .switchable(settings.notifyAllAccounts), viewType: .singleItem, action: { arguments.allAcounts() }))) index += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(settings.notifyAllAccounts ? strings().notificationSettingsShowNotificationsFromOn : strings().notificationSettingsShowNotificationsFromOff), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 } entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsToggleNotificationsHeader), data: InputDataGeneralTextData(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_notifications, data: InputDataGeneralData(name: strings().notificationSettingsToggleNotifications, color: theme.colors.text, type: .switchable(settings.enabled), viewType: .firstItem, action: { arguments.toggleNotifications() }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_message_preview, data: InputDataGeneralData(name: strings().notificationSettingsMessagesPreview, color: theme.colors.text, type: .switchable(settings.displayPreviews), viewType: .innerItem, action: { arguments.toggleMessagesPreview() }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_tone, data: InputDataGeneralData(name: strings().notificationSettingsNotificationTone, color: theme.colors.text, type: .nextContext(localizedPeerNotificationSoundString(sound: settings.tone, list: soundList)), viewType: .innerItem, action: arguments.notificationTone))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_bounce, data: InputDataGeneralData(name: strings().notificationSettingsBounceDockIcon, color: theme.colors.text, type: .switchable(settings.requestUserAttention), viewType: .innerItem, action: { arguments.toggleRequestUserAttention() }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_reset, data: InputDataGeneralData(name: strings().notificationSettingsResetNotifications, color: theme.colors.text, type: .none, viewType: .lastItem, action: { arguments.resetAllNotifications() }))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsSoundEffects), data: InputDataGeneralTextData(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_message_effect, data: InputDataGeneralData(name: strings().notificationSettingsSendMessageEffect, color: theme.colors.text, type: .switchable(FastSettings.inAppSounds), viewType: .singleItem, action: { arguments.toggleInAppSounds(!FastSettings.inAppSounds) }))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsBadgeHeader), data: InputDataGeneralTextData(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_badge_enabled, data: InputDataGeneralData(name: strings().notificationSettingsBadgeEnabled, color: theme.colors.text, type: .switchable(settings.badgeEnabled), viewType: .firstItem, action: { arguments.toggleBadge(!settings.badgeEnabled) }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_include_public_group, data: InputDataGeneralData(name: strings().notificationSettingsIncludeGroups, color: theme.colors.text, type: .switchable(settings.totalUnreadCountIncludeTags.contains(.group)), viewType: .innerItem, enabled: settings.badgeEnabled, action: { arguments.toggleIncludeGroups(!settings.totalUnreadCountIncludeTags.contains(.group)) }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_include_channels, data: InputDataGeneralData(name: strings().notificationSettingsIncludeChannels, color: theme.colors.text, type: .switchable(settings.totalUnreadCountIncludeTags.contains(.channel)), viewType: .innerItem, enabled: settings.badgeEnabled, action: { arguments.toggleIncludeChannels(!settings.totalUnreadCountIncludeTags.contains(.channel)) }))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_count_unred_messages, data: InputDataGeneralData(name: strings().notificationSettingsCountUnreadMessages, color: theme.colors.text, type: .switchable(settings.totalUnreadCountDisplayCategory == .messages), viewType: .lastItem, enabled: settings.badgeEnabled, action: { arguments.toggleCountUnreadMessages(settings.totalUnreadCountDisplayCategory != .messages) }))) index += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsBadgeDesc), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_new_contacts, data: InputDataGeneralData(name: strings().notificationSettingsContactJoined, color: theme.colors.text, type: .switchable(globalSettings.contactsJoined), viewType: .singleItem, action: { arguments.updateJoinedNotifications(!globalSettings.contactsJoined) }))) index += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsContactJoinedInfo), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(strings().notificationSettingsSnoofHeader), data: InputDataGeneralTextData(viewType: .textTopItem))) index += 1 entries.append(InputDataEntry.general(sectionId: sectionId, index: index, value: .none, error: nil, identifier: _id_snoof, data: InputDataGeneralData(name: strings().notificationSettingsSnoof, color: theme.colors.text, type: .switchable(!settings.showNotificationsOutOfFocus), viewType: .singleItem, action: { arguments.snoof() }))) index += 1 entries.append(InputDataEntry.desc(sectionId: sectionId, index: index, text: .plain(!settings.showNotificationsOutOfFocus ? strings().notificationSettingsSnoofOn : strings().notificationSettingsSnoofOff), data: InputDataGeneralTextData(viewType: .textBottomItem))) index += 1 entries.append(.sectionId(sectionId, type: .normal)) sectionId += 1 return entries } func NotificationPreferencesController(_ context: AccountContext, focusOnItemTag: NotificationsAndSoundsEntryTag? = nil) -> ViewController { let arguments = NotificationArguments(resetAllNotifications: { confirm(for: context.window, header: strings().notificationSettingsConfirmReset, information: strings().chatConfirmActionUndonable, successHandler: { _ in _ = resetPeerNotificationSettings(network: context.account.network).start() }) }, toggleMessagesPreview: { _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, {$0.withUpdatedDisplayPreviews(!$0.displayPreviews)}).start() }, toggleNotifications: { _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, {$0.withUpdatedEnables(!$0.enabled)}).start() }, notificationTone: { context.bindings.rootNavigation().push(NotificationSoundController(context: context)) }, toggleIncludeUnreadChats: { enable in _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, {$0.withUpdatedTotalUnreadCountDisplayStyle(enable ? .raw : .filtered)}).start() }, toggleCountUnreadMessages: { enable in _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, {$0.withUpdatedTotalUnreadCountDisplayCategory(enable ? .messages : .chats)}).start() }, toggleIncludeGroups: { enable in _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in var tags: PeerSummaryCounterTags = value.totalUnreadCountIncludeTags if enable { tags.insert(.group) } else { tags.remove(.group) } return value.withUpdatedTotalUnreadCountIncludeTags(tags) }).start() }, toggleIncludeChannels: { enable in _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in var tags: PeerSummaryCounterTags = value.totalUnreadCountIncludeTags if enable { tags.insert(.channel) } else { tags.remove(.channel) } return value.withUpdatedTotalUnreadCountIncludeTags(tags) }).start() }, allAcounts: { _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in return value.withUpdatedNotifyAllAccounts(!value.notifyAllAccounts) }).start() }, snoof: { _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in return value.withUpdatedSnoof(!value.showNotificationsOutOfFocus) }).start() }, updateJoinedNotifications: { value in _ = updateGlobalNotificationSettingsInteractively(postbox: context.account.postbox, { settings in var settings = settings settings.contactsJoined = value return settings }).start() }, toggleBadge: { enabled in _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in return value.withUpdatedBadgeEnabled(enabled) }).start() }, toggleRequestUserAttention: { _ = updateInAppNotificationSettingsInteractively(accountManager: context.sharedContext.accountManager, { value in return value.withUpdatedRequestUserAttention(!value.requestUserAttention) }).start() }, toggleInAppSounds: { value in FastSettings.toggleInAppSouds(value) }) let entriesSignal = combineLatest(queue: prepareQueue, appNotificationSettings(accountManager: context.sharedContext.accountManager), globalNotificationSettings(postbox: context.account.postbox), context.sharedContext.activeAccountsWithInfo |> map { $0.accounts }, UNUserNotifications.recurrentAuthorizationStatus(context), context.engine.peers.notificationSoundList()) |> map { inAppSettings, globalSettings, accounts, unAuthStatus, soundList -> [InputDataEntry] in return notificationEntries(settings: inAppSettings, soundList: soundList, globalSettings: globalSettings, accounts: accounts, unAuthStatus: unAuthStatus, arguments: arguments) } let controller = InputDataController(dataSignal: entriesSignal |> map { InputDataSignalValue(entries: $0) }, title: strings().telegramNotificationSettingsViewController, removeAfterDisappear: false, hasDone: false, identifier: "notification-settings") controller.didLoaded = { controller, _ in if let focusOnItemTag = focusOnItemTag { controller.genericView.tableView.scroll(to: .center(id: focusOnItemTag.stableId, innerId: nil, animated: true, focus: .init(focus: true), inset: 0), inset: NSEdgeInsets()) } } return controller }
gpl-2.0
9da5dec819e492e82064871391e6c7f1
50.991071
606
0.709815
5.003652
false
false
false
false
natecook1000/swift
stdlib/public/core/StringTesting.swift
3
1795
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // Declarations to enable ease-of-testing public // @testable struct _StringRepresentation { public var _isASCII: Bool public var _count: Int public var _capacity: Int public enum _Form { case _small case _cocoa(object: AnyObject) case _native(object: AnyObject) case _immortal(address: UInt) } public var _form: _Form public var _objectIdentifier: ObjectIdentifier? { switch _form { case ._cocoa(let object): return ObjectIdentifier(object) case ._native(let object): return ObjectIdentifier(object) default: return nil } } } extension String { public // @testable func _classify() -> _StringRepresentation { var result = _StringRepresentation( _isASCII: _guts._isASCIIOrSmallASCII, _count: _guts.count, _capacity: _guts.capacity, _form: ._small ) if _guts._isSmall { return result } if _guts._isNative { result._form = ._native(object: _guts._owner!) return result } if _guts._isCocoa { result._form = ._cocoa(object: _guts._owner!) return result } if _guts._isUnmanaged { result._form = ._immortal( address: UInt(bitPattern: _guts._unmanagedRawStart)) return result } fatalError() } }
apache-2.0
49cb39c1b946bc211724ba0ef6e61cb5
26.19697
80
0.594429
4.410319
false
false
false
false
dsoisson/SwiftLearning
SwiftLearning.playground/Pages/Collection Types.xcplaygroundpage/Contents.swift
3
15738
/*: [Table of Contents](@first) | [Previous](@previous) | [Next](@next) - - - # Collection Types * callout(Session Overview): Often times in programs you need to group data into a single container where the number of items is unknown. Swift provides 3 main containers known as *collection types* for storing collections of values. *Arrays* are ordered collections of values, *Sets* are unordered collections of unique values, and *Dictionaries* are unordered collections of key-value associations. Please visit the Swift Programming Language Guide section on [Collection Types](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105) for more detail on collection types. */ import Foundation /*: ## When you're allowed to change or *mutate* collections Before we dive into detail on collection types, there's a suttle but easy way to indicate if you can mutate your collection type. We have already seen this with simple data types such as `Int` and `String`, you use `let` and `var`. */ let unmutableArray: [String] = ["One", "Two"] //unmutableArray.append("Three") var mutableArray: [Int] = [1, 2] mutableArray.append(3) //: > **Experiment**: Uncomment the unmutableArray.append statement /*: ## Arrays An *Array* stores values of the same type, `Int`s, `String`s, ect. in ordered manner. The same value of the type can appear multiple times at different positions of the array. */ /*: ### Creating Arrays Swift's *arrays* need to know what type of elements it will contain. You can create an empty array, create an array with a default size and values for each element, create an array by adding multiple arrays together and create arrays using literals. */ /*: **A new empty Array** > You can create an array explicitly with the type or when appropriate use type inference. */ var array: [Int] = [Int]() array = [] print("array has \(array.count) items.") //: The above statements show two ways to create a new array, allowing only to store `Int`s and print the number of elements. /*: **A new Array with default values** >You can create an array with default values by using the *initializer* that accepts a default value and a repeat count of how many elements the array should contain */ let nineNines = [Int](count: 9, repeatedValue: 9) print("nineNines has \(nineNines.count) items.") //: The above statements creates an array nine `Int`s all with a value of 9 and print the number of elements nineNines contains. /*: **A new Array by adding Arrays together** >You can create an array by taking two *arrays* of the same type and adding them together usng the addition operator `+`. The new array's type is inferred from the type of the two arrays added together. */ let twoTwos = [Int](count: 2, repeatedValue: 2) let threeThrees = [Int](count: 3, repeatedValue: 3) let twosAndThrees = twoTwos + threeThrees print("twosAndThrees has \(twosAndThrees.count) items.") let threesAndTwos = threeThrees + twoTwos print("threesAndTwos has \(threesAndTwos.count) items.") //: The above statements creates two arrays by adding two other arrays together. /*: **A new Array using Array literal** >You can create an array by using the literal syntax such as creating an array of `Ints` like `[1, 2, 3, 4, 5]`. */ let numbers = [1, 2, 3, 4, 5] //: The above statement creates an array of numbers containing `Int` data types. /*: ### Accessing data in an `Array` You can access information and elements in an array by using the methods and properties provided by the `Array` collection type. */ print("numbers has \(numbers.count) elements") if numbers.isEmpty { print("numbers is empty") } else { print("numbers is not empty") } var firstNumber = numbers.first var lastNumber = numbers.last //: The above statements use properties of the `Array` collection type for count, empty, first element, and last element. var secondNumber = numbers[1] var thirdNumber = numbers[2] //: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the array. /*: ### Modifying `Array`s Using methods such as `append` and `remove` let you mutate an array. */ var mutableNumbers = numbers mutableNumbers.append(6) mutableNumbers.append(7) mutableNumbers.append(8) mutableNumbers.removeFirst() mutableNumbers.removeLast() mutableNumbers.removeAtIndex(0) mutableNumbers.removeRange(mutableNumbers.startIndex.advancedBy(2)..<mutableNumbers.endIndex) mutableNumbers[0] = 1 mutableNumbers[1] = 2 mutableNumbers.append(3) mutableNumbers.append(4) mutableNumbers.append(5) mutableNumbers[0...4] = [5, 6, 7, 8, 9] mutableNumbers.insert(10, atIndex: mutableNumbers.endIndex) print(mutableNumbers) //: The above statements using the `append`, `insert`, `remove` methods, *subscript syntax* as well as using a range to replace values of indexes. /*: ### Iterating over elements in an `Array` You use the `for-in` loop to iterate over elements in an `Array` */ for number in numbers { print(number) } for (index, number) in numbers.enumerate() { print("Item \(index + 1): \(number)") } //: The first `for-in` loop just pulls out the value for each element in the array, but the second `for-in` loops pulls out the index and value. //: > **Experiment**: Use an `_` underscore instead of `name` in the above for loop. What happens? /*: ## Sets The `Set` collection type stores unique value of the same data type with no defined ordering. You use a `Set` instead of an `Array` when you need to ensure that an element only appears once. */ /*: ### Hash Values for Set Types For a `Set` to ensure that it contains only unique values, each element must provide a value called the *hash value*. A *hash value* is an `Int` that is calulated and is the same for all objects that compare equally. Simple types such as `Int`s, `Double`s, `String`s, and `Bool`s all provide a *hash value* by default. */ let one = 1 let two = "two" let three = M_PI let four = false one.hashValue two.hashValue three.hashValue four.hashValue /*: ### Creating Sets You create a new set collection type by specifing the data type for the element as in `Set<Element>` where `Element` is the data type the set is allowed to store. */ var alphabet = Set<Character>() alphabet = [] /*: The above statements create an empty set that is only allowed to store the Character data type. The second statment assigns *alphabet* to an empty array using the array literal and type inference. */ //: **A new Set using Array literal** var alphabet1: Set<Character> = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] var alphabet2: Set = ["j", "k", "l", "m", "n", "o", "p", "q", "r"] //: You can create a new `Set` using the array literal, but you need to type the variable or constant. `alphabet2` is a shorter way to create a `Set` because it can be inferred that all the values are of the same type, in this case `String`s. Notice that `alphabet1` and `alphabet2` are not of the same type. /*: ### Accessing data in a `Set` Similar to the `Array` collection type, you access information and elements in an `Set` using properties and methods of the `Set` collection type. */ alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"] print("alphabet has \(alphabet.count) elements") if alphabet.isEmpty { print("alphabet is empty") } else { print("alphabet is not empty") } var firstLetter = alphabet.first //: The above statements use properties of the `Set` collection type for count, empty, and first element. var secondLetter = alphabet[alphabet.startIndex.advancedBy(1)] var thirdLetter = alphabet[alphabet.startIndex.advancedBy(2)] //: The above statements use *subscript syntax* by passing the index of the value you want in square brackets after the name of the set. /*: ### Modifying elements in a Set Using methods such as `insert` and `remove` let you mutate a set. */ alphabet.insert("n") alphabet.insert("o") alphabet.insert("p") alphabet.removeFirst() alphabet.removeAtIndex(alphabet.startIndex) alphabet.remove("o") print(alphabet) //: The above statements using the `insert` and `remove` methods to mutate the `Set`. /*: ### Iterating over elements in a Set You use the `for-in` loop to iterate over elements in an `Set` */ for letter in alphabet { print(letter) } for (index, value) in alphabet.enumerate() { print("index: \(index) - value: \(value)") } //: The first `for-in` loop just pulls out the value for each element in the set, but the second `for-in` first sorts the set before the looping starts. /*: ### Set Operations With the `Set` collection type, you can perform set operations in the mathematical sense. */ alphabet = ["a", "b", "c", "d", "e", "v", "w", "x", "y", "z"] let vowels : Set<Character> = ["a", "e", "i", "o", "u"] //: **intersect(_:)** creates a new `Set` of only those values both sets have in common. let intersect = vowels.intersect(alphabet) //: **exclusiveOr(_:)** creates a new `Set` of values from either set, but not from both. let exclusiveOr = vowels.exclusiveOr(alphabet) //: **union(_:)** creates a new `Set` with all values from both sets. let union = vowels.union(alphabet) //: **subtract(_:)** creates a new `Set` with values not in the specified set. let subtract = vowels.subtract(alphabet) /*: ### Set Membership and Equality With the `Set` collection type, you can determine the membership of a set and if one set is equal to another. */ let family : Set = ["Matt", "Annie", "Samuel", "Jack", "Hudson", "Oliver"] let parents : Set = ["Matt", "Annie"] let children : Set = ["Samuel", "Jack", "Hudson", "Oliver"] //: **“is equal” operator (==)** tests if one set is equal to another set. family == parents.union(children) parents == children //: **isSubsetOf(_:)** tests if all of the values of a set are contained in another set. children.isSubsetOf(family) family.isSubsetOf(children) //: **isSupersetOf(_:)** test if a set contains all of the values in another set. family.isSupersetOf(parents) family.isSupersetOf(children) children.isSupersetOf(family) //: **isStrictSubsetOf(_:) or isStrictSupersetOf(_:)** test if a set is a subset or superset, but not equal to, another set. let old = parents old.isStrictSubsetOf(parents) let boys: Set = ["Matt", "Samuel", "Jack", "Hudson", "Oliver"] boys.isStrictSubsetOf(family) //: **isDisjointWith(_:)** test if two sets have any values in common. parents.isDisjointWith(children) family.isDisjointWith(children) /*: ## Dictionaries A `Dictionary` stores associations or mappings between keys of the same data type and values of the same data type in a container with no defined ordering. The value of each element is tied to a unique *key*. It's this unique *key* that enables you to lookup values based on an identifer, just like a real dictionary having the word be the key and the definition the value. */ /*: ### Creating Dictionaries Much like the `Array` and `Set` collection types, you need to specify the data type that the `Dictionary` is allowed to store. Unlike `Array`s and `Set`s, you need to specify the data type for the *Key* and the *Value*. */ var longhand: Dictionary<String, String>? = nil var shorthand: [String: String]? = nil /*: Above shows a long and short way to create a dictionary. */ //: **A new empty Dictionary** var titles = [String: String]() titles["dad"] = "Matt" titles = [:] /*: Above creates an empty `Dictionary`, adds an entry into `titles` and then assigns `titles` to an empty dictionary using the shorthand form and type inference. */ //: **A new Dictionary using Dictionary literal** titles = ["dad": "Matt", "mom": "Annie", "child_1": "Sam", "child_2": "Jack", "child_3": "Hudson", "child_4": "Oliver"] /*: Above creates a `Dictionary` using the literal syntax. Notice the *key: value* mapping separated by a comma, all surrounded by square brackets. */ /*: ### Accessing data in a Dictionary Like the `Array` and `Set` collection types, the `Dictionary` also has the `count` and `isEmpty` properties, but unlike arrays and sets, you access elements using a *key*. */ print("titles has \(titles.count) elements") if titles.isEmpty { print("titles is empty") } else { print("titles is not empty") } var dad = titles["dad"] if dad != nil { print(dad!) } /*: Above statements use the `count` and `isEmpty` properties, as well as use the *key* to retrive a value. It's possible that you use a *key* that does not exist in the dictionary. The `Dictionary` collection type will always return the value as an *Optional*. You then next would need to check for `nil` and *unwrap* the optional to obtain the real value. */ /*: ### Modifying elements in a Dictionary There are two techniques to add/update entries for the `Dictionary` collection type, by using the *subscript syntax* or using a method. */ titles["dog"] = "Carson" titles["child_1"] = "Samuel" var father = titles.updateValue("Mathew", forKey: "dad") var cat = titles.updateValue("Fluffy", forKey: "cat") titles["dog"] = nil cat = titles.removeValueForKey("cat") if cat != nil { print("removed \(cat!)") } /*: The above statements use both the *subscript syntax* and methods for add, updating, and removing entries of a dictionary. Notice that with the method technique, you are returned a value if if the entry exists in the dictionary. */ /*: ### Iterating over elements in a Dictionary Just like the `Array` and `Set` collection types, you iterate over a dictionary using a `for-in` loop. */ for element in titles { print("\(element.0): \(element.1)") } for (key, value) in titles { print("\(key): \(value)") } for title in titles.keys { print("title: \(title)") } for name in titles.values { print("name: \(name)") } let titleNames = [String](titles.keys) let names = [String](titles.values) /*: Above statements use the `for-in` loop to iterate over the `titles` giving you access to the *key* and *value*. You can also access only the *keys* or *values*. */ //: > **Experiment**: Create a array of dictionaries and iterate over the array printing the key and value of each dictionary /*: - - - * callout(Exercise): You have to record all the students for your school. Leveraging arrays, dictionaries, and sets, create table like containers for each class. Your classes are Math, Science, English and History with a total of 17 unique students with 7 students in each class. Print out each class roster and experiment with set operations, membership and equality. **Example Output:** - `Math = Mathew Sheets, John Winters, Sam Smith` - `Science = Sam Smith, Carson Daily, Adam Aarons` - `Union of Math and Science = Mathew Sheets, John Winters, Sam Smith, Carson Daily, Adam Aarons` **Constraints:** - Use Set Operations - intersect - exclusiveOr - union - subtract - Use Set Membership and Equality - is equal - isSubsetOf - isSupersetOf - isStrictSubsetOf - isStrictSupersetOf - isDisjointWith * callout(Checkpoint): At this point, you should have a basic understanding of the collection types provided by the Swift programming language. Using arrays, you can store a collection of ordered values. Using sets, you can store a collection of unordered unique values. Using dictionaries, you can store a collection of key-value associations. With these three collection types, processing and manipulating data will be easier. * callout(Supporting Materials): Chapters and sections from the Guide and Vidoes from WWDC - [Guide: Collection Types](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html) - - - [Table of Contents](@first) | [Previous](@previous) | [Next](@next) */
mit
081a145e32f056eb5dde8b5f97c28d1e
43.954286
690
0.723211
3.909068
false
false
false
false