repo_name
stringlengths
7
91
path
stringlengths
8
658
copies
stringclasses
125 values
size
stringlengths
3
6
content
stringlengths
118
674k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6.09
99.2
line_max
int64
17
995
alpha_frac
float64
0.3
0.9
ratio
float64
2
9.18
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
romaonthego/TableViewDataManager
Source/Classes/Components/TextView/TableViewTextViewItem.swift
1
3172
// // TableViewTextViewItem.swift // TableViewDataManager // // Copyright (c) 2016 Roman Efimov (https://github.com/romaonthego) // // 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 class TableViewTextViewItem: TableViewFormItem, TableViewItemFocusable { public var value: String? public var editable: Bool = true public var showsActionBar = true // MARK: Keyboard // public var autocapitalizationType = UITextAutocapitalizationType.Sentences // default is UITextAutocapitalizationTypeSentences public var autocorrectionType = UITextAutocorrectionType.Default // default is UITextAutocorrectionTypeDefault public var spellCheckingType = UITextSpellCheckingType.Default // default is UITextSpellCheckingTypeDefault public var keyboardType = UIKeyboardType.Default // default is UIKeyboardTypeDefault public var keyboardAppearance = UIKeyboardAppearance.Default // default is UIKeyboardAppearanceDefault public var returnKeyType = UIReturnKeyType.Default // default is UIReturnKeyDefault (See note under UIReturnKeyType enum) public var enablesReturnKeyAutomatically = false // default is NO (when YES, will automatically disable return key when text widget has zero-length contents, and will automatically enable when text widget has non-zero-length contents) // MARK: Handlers // public var changeHandler: ((section: TableViewSection, item: TableViewTextViewItem, tableView: UITableView, indexPath: NSIndexPath) -> (Void))? public var beginEditingHandler: ((section: TableViewSection, item: TableViewTextViewItem, tableView: UITableView, indexPath: NSIndexPath) -> (Void))? public var endEditingHandler: ((section: TableViewSection, item: TableViewTextViewItem, tableView: UITableView, indexPath: NSIndexPath) -> (Void))? public var returnKeyHandler: ((section: TableViewSection, item: TableViewTextViewItem, tableView: UITableView, indexPath: NSIndexPath) -> (Void))? // MARK: Instance Lifecycle // public convenience init(text: String?, value: String?) { self.init(text: text) self.value = value } }
mit
384b84deae93e4d7566fd8523f6d8d7b
54.666667
238
0.764817
5.166124
false
false
false
false
jeffreybergier/Hipstapaper
Hipstapaper/Packages/V3WebsiteEdit/Sources/V3WebsiteEdit/Website/FormParent.swift
1
2559
// // Created by Jeffrey Bergier on 2022/07/08. // // MIT License // // Copyright (c) 2021 Jeffrey Bergier // // 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 SwiftUI import V3Model import V3Errors import V3Style import V3Localize internal struct FormParent: View { @V3Style.WebsiteEdit private var style @V3Localize.WebsiteEdit private var text @Navigation private var nav @StateObject private var webState = WebState.newEnvironment() private let selection: Website.Selection internal init(_ selection: Website.Selection) { self.selection = selection } internal var body: some View { NavigationStack { self.selection.view { selection in if selection.count > 1 { FormMulti(selection) } else { FormSingle(selection.first!) .environmentObject(self.webState) } } onEmpty: { self.style.disabled.action(text: self.text.noWebsitesSelected).label } .modifier(FormToolbar(self.selection)) } } } extension Binding where Value == Optional<URL> { // Used for mapping URL model properties to text fields internal func mirror(string: Binding<String>) -> Binding<String> { self.map { $0?.absoluteString ?? string.wrappedValue } set: { string.wrappedValue = $0 return URL(string: $0) } } }
mit
deb76e8658af047e46d21abfb06cf76d
33.12
84
0.661977
4.505282
false
false
false
false
asm-products/giraff-ios
Fun/LoginWithEmailViewController.swift
1
2748
import UIKit protocol LoginWithEmailDelegate: class { func didLoginWithEmail() } class LoginWithEmailViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailTextField: DesignableTextField! @IBOutlet weak var passwordTextField: DesignableTextField! @IBOutlet weak var loginButton: DesignableButton! weak var delegate: LoginWithEmailDelegate? override func viewDidLoad() { super.viewDidLoad() emailTextField.dataValidator = ValidatorFactory.emailValidator passwordTextField.dataValidator = ValidatorFactory.passwordValidator Flurry.logEvent("Login: Login With Email Shown") loginButton.enabled = false } @IBAction func loginButtonDidPress(sender: AnyObject) { FunSession.sharedSession.signIn(emailTextField.text, password: passwordTextField.text) { User.currentUser.email = self.emailTextField.text self.delegate?.didLoginWithEmail() Flurry.logEvent("Login: Login With Email Pressed") // TODO: Show alert if login is not successful // self.presentAlert("Error", message: "Invalid Account") } } func textFieldDidBeginEditing(textField: UITextField) { if let field = textField as? DesignableTextField { field.validated = .Unknown } } func textFieldDidEndEditing(textField: UITextField) { if let field = textField as? DesignableTextField { if SPXFormValidator.validateField(field) { field.validated = .Valid } else { field.validated = .Invalid } } } func textFieldShouldReturn(textField: UITextField) -> Bool { var didResign = textField.resignFirstResponder() if !didResign { return false } if let field = textField as? DesignableTextField { field.nextTextField?.becomeFirstResponder() } if textField.tag == 1 && SPXFormValidator.validateFields([emailTextField, passwordTextField]) { loginButtonDidPress(textField) } return true } @IBAction func textFieldDidChangeEditing(sender: UITextField) { self.loginButton.enabled = SPXFormValidator.validateFields([emailTextField, passwordTextField]) } func presentAlert(title: String, message: String) { var alert = UIAlertController(title: "Error", message: "Invalid Account", preferredStyle: UIAlertControllerStyle.Alert) alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alert, animated: true, completion: nil) } }
agpl-3.0
25beade9c5eb393a927cd92884d41870
33.797468
127
0.666303
5.507014
false
false
false
false
Bouke/HAP
Sources/HAP/Base/Predefined/Characteristics/Characteristic.CarbonMonoxidePeakLevel.swift
1
2097
import Foundation public extension AnyCharacteristic { static func carbonMonoxidePeakLevel( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Carbon monoxide Peak Level", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = .ppm, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> AnyCharacteristic { AnyCharacteristic( PredefinedCharacteristic.carbonMonoxidePeakLevel( value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) as Characteristic) } } public extension PredefinedCharacteristic { static func carbonMonoxidePeakLevel( _ value: Float = 0, permissions: [CharacteristicPermission] = [.read, .events], description: String? = "Carbon monoxide Peak Level", format: CharacteristicFormat? = .float, unit: CharacteristicUnit? = .ppm, maxLength: Int? = nil, maxValue: Double? = 100, minValue: Double? = 0, minStep: Double? = 1, validValues: [Double] = [], validValuesRange: Range<Double>? = nil ) -> GenericCharacteristic<Float> { GenericCharacteristic<Float>( type: .carbonMonoxidePeakLevel, value: value, permissions: permissions, description: description, format: format, unit: unit, maxLength: maxLength, maxValue: maxValue, minValue: minValue, minStep: minStep, validValues: validValues, validValuesRange: validValuesRange) } }
mit
3d99586b070a97313617a64340f5f01c
33.377049
67
0.585598
5.216418
false
false
false
false
Roommate-App/roomy
roomy/roomy/UpdateStatusViewController.swift
1
2716
// // UpdateStatusViewController.swift // roomy // // Created by Ryan Liszewski on 4/18/17. // Copyright © 2017 Poojan Dave. All rights reserved. // import UIKit class UpdateStatusViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { let statuses: [String]! = ["🏚I'm home.", "👋I'm out of the house.", "😴Going to sleep. ", "🚎Coming home soon.", "🌇Need to wake up early.", "🎉Having some people over."] @IBOutlet weak var statusTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() statusTableView.dataSource = self statusTableView.delegate = self statusTableView.rowHeight = UITableViewAutomaticDimension statusTableView .estimatedRowHeight = 120 self.view.layer.cornerRadius = 9.0 //statusTableView.separatorStyle = .none statusTableView.alwaysBounceVertical = false statusTableView.tableFooterView = UIView() statusTableView.reloadData() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func onCloseButtonTapped(_ sender: Any) { self.dismiss(animated: true, completion: nil) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return statuses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = statusTableView.dequeueReusableCell(withIdentifier: R.Identifier.Cell.StatusTableViewCell, for: indexPath) as! StatusTableViewCell cell.statusMessageLabel.text = statuses[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { Roomy.current()?["status_message"] = statuses[indexPath.row] //Roomy.current()?.setObject(Roomy.current()?.status!, forKey: "status_message") //self.delegate.updateStatus(status: "d") Roomy.current()?.saveInBackground(block: { (success, error) in if success { print("Successfully updated status") self.dismiss(animated: true, completion: { }) } else { print("Error") } }) } }
mit
51c8ea51952027c38fee9b8674914d3c
29.647727
150
0.586207
5.526639
false
false
false
false
aputinski/rebound-swift
ReboundTests/Spring.swift
1
5856
// // Spring.swift // Rebound // // Created by Adam Putinski on 8/1/15. // import XCTest @testable import Rebound class SpringSpec: XCTestCase { var system: SpringSystem! var spring: Spring! override func setUp() { system = SpringSystem(looper: SimulationLooper()) spring = system.createSpring() } func testItIsCreatedAtRest() { XCTAssert(spring.isAtRest) XCTAssertEqual(spring.currentValue, 0) XCTAssertEqual(spring.endValue, 0) XCTAssertEqual(spring.velocity, 0) } func testItCanHaveListeners() { let removeToken = spring.addListener() XCTAssertEqual(spring.getListenerCount(), 1) spring.removeListener(removeToken) XCTAssertEqual(spring.getListenerCount(), 0) spring.addListener() spring.addListener() spring.addListener() spring.addListener() XCTAssertEqual(spring.getListenerCount(), 4) spring.removeAllListeners() XCTAssertEqual(spring.getListenerCount(), 0) } func testItPerformsTheExpectedNumericalIntegration() { let expectedValues = [ 9.52848338491667e-05, 0.0280551305179629, 0.0976222162450096, 0.190497295109813, 0.293671406740464, 0.404972861445447, 0.511154620365362, 0.608094950748042, 0.698951264400022, 0.776398779443102, 0.840705433961584, 0.895891857904224, 0.938997248097101, 0.97173377816996, 0.997159213205988, 1.01476258136631, 1.02622082577252, 1.03329564932684, 1.03648946072759, 1.03693989835553, 1.03540388512924, 1.03257859112136, 1.0290563359258, 1.02500642918106, 1.02097461568528, 1.01717719976916, 1.01352576938495, 1.01034175794478, 1.00764258881001, 1.0052779569598, 1.00339015100599, 1.00192189582887, 1.00074860414277, 0.999905475829482, 0.999327247722712, 0.998937454133214, 0.998722961913546, 0.998636250658114, 0.998641642340227, 0.998713318946208, 0.998824878849694, 0.998966054352768, 0.999114736756395, 0.999260176669424, 0.999404175513922, 0.99953287104958, 0.999644341038988, 0.999744018657976, 0.99982527212144, 0.999889854959369, 0.999942754508108, 0.999981940911546, 1.0000098947929, 1.0 ] let expectedVelocities = [ 0.228097133938337, 3.18362795565378, 5.18969355221027, 6.30813323126167, 6.77768007214265, 6.77982070324507, 6.44238061699663, 5.89889697645961, 5.20272072228581, 4.464480016355, 3.73912445737494, 3.0186340411984, 2.37287827903462, 1.81217685432229, 1.30966581693994, 0.899063471343696, 0.571907908370749, 0.303217761832437, 0.103527665273483, -0.0395034891417408, -0.142350714486958, -0.205860785078523, -0.239846237850156, -0.25264329505409, -0.248793645303234, -0.234145130232077, -0.211581130826735, -0.185501057593562, -0.15853434660787, -0.130760368115395, -0.105145469346107, -0.0823722207562575, -0.0615193132781277, -0.0441214723178374, -0.0299690850716248, -0.0180823343233512, -0.0090150795817449, -0.00231313923658305, 0.0027155555738821, 0.00603264077492341, 0.00803456840095728, 0.00909565564543121, 0.00936894907445586, 0.00910612207902817, 0.008453224982293, 0.00758173875580081, 0.00661380014855828, 0.0055701159887829, 0.00457462163674249, 0.00366596517146286, 0.00281474053224796, 0.0020893441663067, 0.00148722044181752, 0.000970784332533191, 0.0 ] var actualValues = [Double]() var actualVelocities = [Double]() spring.addListener(update: { spring in actualValues.append(spring.currentValue) actualVelocities.append(spring.velocity) }) spring.setEndValue(1) var valuesAreClose = true for (index, actualItem) in actualValues.enumerated() { if fabs(actualItem - expectedValues[index]) > 0.0001 { valuesAreClose = false break } } var velocitiesAreClose = true for (index, actualItem) in expectedVelocities.enumerated() { if fabs(actualItem - expectedVelocities[index]) > 0.0001 { velocitiesAreClose = false break } } XCTAssert(valuesAreClose) XCTAssert(velocitiesAreClose) } func testItShouldNotOscillateIfOvershootClampingIsEnabled() { var actualValues = [Double]() spring.addListener(update: { spring in actualValues.append(spring.currentValue) }) spring.overshootClampingEnabled = true spring.setEndValue(1) var didOscillate = false var priorValue: Double = -1 for value in actualValues { if value < priorValue { didOscillate = true break } priorValue = value } XCTAssertFalse(didOscillate) } func testItShouldNotOscillateIfTheSpringHas0Tension() { var actualValues = [Double]() spring.addListener(update: { spring in actualValues.append(spring.currentValue) }) spring.config = SpringConfig.coastingConfigWithOrigamiFriction(7) spring.setVelocity(1000) var didOscillate = false var priorValue: Double = -1 for value in actualValues { if value < priorValue { didOscillate = true break } priorValue = value } XCTAssertFalse(didOscillate) } func testItShouldBeAtRestAfterCallingSetCurrentValue() { let system = SpringSystem(looper: SimulationLooper()) let spring = system.createSpring() spring.setEndValue(1) spring.setCurrentValue(-1.0) XCTAssert(spring.isAtRest) XCTAssertEqual(spring.currentValue, -1.0) XCTAssertEqual(spring.endValue, -1.0) } func testItShouldNotBeAtRestIfTheSkipSetAtRestParameterIsPassedToSetCurrentValueWhileMoving() { let system = SpringSystem(looper: SimulationLooper()) let spring = system.createSpring() spring.setEndValue(1) spring.setCurrentValue(-1.0, skipSetAtRest: true) XCTAssertFalse(spring.isAtRest) XCTAssertEqual(spring.currentValue, -1.0) XCTAssertEqual(spring.endValue, 1.0) } }
bsd-3-clause
c4719dd0e683cbf1747c7f8bc5ed0bc6
35.6
100
0.722336
3.116551
false
true
false
false
gabrielPeart/StatefulViewController
Example/PlaceholderViews/LoadingView.swift
2
1297
// // LoadingView.swift // Example // // Created by Alexander Schuch on 29/08/14. // Copyright (c) 2014 Alexander Schuch. All rights reserved. // import UIKit class LoadingView: BasicPlaceholderView { let label = UILabel() override func setupView() { super.setupView() backgroundColor = UIColor.whiteColor() label.text = "Loading..." label.setTranslatesAutoresizingMaskIntoConstraints(false) centerView.addSubview(label) let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray) activityIndicator.startAnimating() activityIndicator.setTranslatesAutoresizingMaskIntoConstraints(false) centerView.addSubview(activityIndicator) let views = ["label": label, "activity": activityIndicator] let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-[activity]-[label]-|", options: nil, metrics: nil, views: views) let vConstraintsLabel = NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: nil, metrics: nil, views: views) let vConstraintsActivity = NSLayoutConstraint.constraintsWithVisualFormat("V:|[activity]|", options: nil, metrics: nil, views: views) centerView.addConstraints(hConstraints) centerView.addConstraints(vConstraintsLabel) centerView.addConstraints(vConstraintsActivity) } }
mit
ae5bdb6c5e56e7a1333ca509d24f5c8f
32.25641
135
0.773323
4.716364
false
false
false
false
Eiltea/MyWeiBo
MyWeiBo/MyWeiBo/Classes/View/OAuth/EilOAuthViewController.swift
1
2895
// // EilOAuthViewController.swift // MyWeiBo // // Created by Eil.tea on 15/12/7. // Copyright © 2015年 Eil.tea. All rights reserved. // //取消授权接口http://open.weibo.com/wiki/Oauth2/revokeoauth2 import UIKit import SVProgressHUD let APPKEY = "3394881052" let AppSecret = "d96f6ec9fd8a603264b59176b2d2f0e7" let AddressBack = "http://weibo.com/5733683890/info" class EilOAuthViewController: UIViewController , UIWebViewDelegate { private lazy var webView=UIWebView() override func loadView() { view=webView webView.delegate=self } override func viewDidLoad() { super.viewDidLoad() updateUI() let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(AddressBack)" let request = NSURLRequest(URL: NSURL(string: urlString)!) webView.loadRequest(request) } private func updateUI(){ navigationItem.leftBarButtonItem=UIBarButtonItem(title: "取消", target: self, action: "cancel") navigationItem.rightBarButtonItem=UIBarButtonItem(title: "自动填充", target: self, action: "autoFinish") navigationItem.title="微博登陆" } @objc private func autoFinish(){ let jsString = "document.getElementById('userId').value='13717580236';document.getElementById('passwd').value='wulongtao21'" webView.stringByEvaluatingJavaScriptFromString(jsString) } @objc private func cancel(){ dismissViewControllerAnimated(false, completion: nil) } func webViewDidStartLoad(webView: UIWebView) { SVProgressHUD.show() } func webViewDidFinishLoad(webView: UIWebView) { SVProgressHUD.dismiss() } func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { let url=request.URL!.absoluteString if !url.hasPrefix(AddressBack){ return true } if request.URL!.query!.hasPrefix("code="){ let code = request.URL!.query!.substringFromIndex("code=".endIndex) EilUserAccountViewModel.shareAccount.loadAccessToken(code, complete: { (isSuccessed) -> () in if !isSuccessed { self.cancel() SVProgressHUD.showErrorWithStatus("网络错误,重新加载") } SVProgressHUD.dismiss() self.dismissViewControllerAnimated(false, completion: { () -> Void in NSNotificationCenter.defaultCenter().postNotificationName(EilSwitchRootVCNotifation, object: EilWelcomeViewController()) }) }) } SVProgressHUD.dismiss() if request.URL!.query!.hasPrefix("error"){ self.cancel() } return false } }
mit
adedd54342566ed238b761cf5e4994c0
29.55914
140
0.63969
4.728785
false
false
false
false
Hearst-DD/ObjectMapper
Tests/ObjectMapperTests/BasicTypesTestsFromJSON.swift
3
22665
// // BasicTypesFromJSON.swift // ObjectMapper // // Created by Tristan Himmelman on 2015-02-17. // // The MIT License (MIT) // // Copyright (c) 2014-2018 Tristan Himmelman // // 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 import XCTest import ObjectMapper class BasicTypesTestsFromJSON: XCTestCase { let mapper = Mapper<BasicTypes>() override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } // MARK: Test mapping to JSON and back (basic types: Bool, Int, Double, Float, String) func testMappingBoolFromJSON(){ let value: Bool = true let JSONString = "{\"bool\" : \(value), \"boolOpt\" : \(value), \"boolImp\" : \(value)}" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.bool, value) XCTAssertEqual(mappedObject?.boolOptional, value) XCTAssertEqual(mappedObject?.boolImplicityUnwrapped, value) } /// - warning: This test doens't consider integer overflow/underflow. func testMappingIntegerFromJSON(){ func parameterize<T: FixedWidthInteger>(_ type: T.Type) { let value: T = 123 let json: [String: Any] = [ "int": value, "intOpt": value, "intImp": value, "int8": value, "int8Opt": value, "int8Imp": value, "int16": value, "int16Opt": value, "int16Imp": value, "int32": value, "int32Opt": value, "int32Imp": value, "int64": value, "int64Opt": value, "int64Imp": value, "uint": value, "uintOpt": value, "uintImp": value, "uint8": value, "uint8Opt": value, "uint8Imp": value, "uint16": value, "uint16Opt": value, "uint16Imp": value, "uint32": value, "uint32Opt": value, "uint32Imp": value, "uint64": value, "uint64Opt": value, "uint64Imp": value, ] let mappedObject = mapper.map(JSON: json) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.int, 123) XCTAssertEqual(mappedObject?.intOptional, 123) XCTAssertEqual(mappedObject?.intImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int8, 123) XCTAssertEqual(mappedObject?.int8Optional, 123) XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int16, 123) XCTAssertEqual(mappedObject?.int16Optional, 123) XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int32, 123) XCTAssertEqual(mappedObject?.int32Optional, 123) XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.int64, 123) XCTAssertEqual(mappedObject?.int64Optional, 123) XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint, 123) XCTAssertEqual(mappedObject?.uintOptional, 123) XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint8, 123) XCTAssertEqual(mappedObject?.uint8Optional, 123) XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint16, 123) XCTAssertEqual(mappedObject?.uint16Optional, 123) XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint32, 123) XCTAssertEqual(mappedObject?.uint32Optional, 123) XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, 123) XCTAssertEqual(mappedObject?.uint64, 123) XCTAssertEqual(mappedObject?.uint64Optional, 123) XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, 123) } parameterize(Int.self) parameterize(Int8.self) parameterize(Int16.self) parameterize(Int32.self) parameterize(Int64.self) parameterize(UInt.self) parameterize(UInt8.self) parameterize(UInt16.self) parameterize(UInt32.self) parameterize(UInt64.self) } func testMappingIntegerWithOverflowFromJSON(){ let signedValue = Int.max let unsignedValue = UInt.max let json: [String: Any] = [ "int": signedValue, "intOpt": signedValue, "intImp": signedValue, "int8": signedValue, "int8Opt": signedValue, "int8Imp": signedValue, "int16": signedValue, "int16Opt": signedValue, "int16Imp": signedValue, "int32": signedValue, "int32Opt": signedValue, "int32Imp": signedValue, "int64": signedValue, "int64Opt": signedValue, "int64Imp": signedValue, "uint": unsignedValue, "uintOpt": unsignedValue, "uintImp": unsignedValue, "uint8": unsignedValue, "uint8Opt": unsignedValue, "uint8Imp": unsignedValue, "uint16": unsignedValue, "uint16Opt": unsignedValue, "uint16Imp": unsignedValue, "uint32": unsignedValue, "uint32Opt": unsignedValue, "uint32Imp": unsignedValue, "uint64": unsignedValue, "uint64Opt": unsignedValue, "uint64Imp": unsignedValue, ] let mappedObject = mapper.map(JSON: json) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.int, Int.max) XCTAssertEqual(mappedObject?.intOptional, Int.max) XCTAssertEqual(mappedObject?.intImplicityUnwrapped, Int.max) XCTAssertEqual(mappedObject?.int8, 0) XCTAssertEqual(mappedObject?.int8Optional, nil) XCTAssertEqual(mappedObject?.int8ImplicityUnwrapped, nil) XCTAssertEqual(mappedObject?.int16, 0) XCTAssertEqual(mappedObject?.int16Optional, nil) XCTAssertEqual(mappedObject?.int16ImplicityUnwrapped, nil) #if arch(x86_64) || arch(arm64) XCTAssertEqual(mappedObject?.int32, 0) XCTAssertEqual(mappedObject?.int32Optional, nil) XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, nil) XCTAssertEqual(mappedObject?.int64, Int64.max) XCTAssertEqual(mappedObject?.int64Optional, Int64.max) XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, Int64.max) #else XCTAssertEqual(mappedObject?.int32, Int32.max) XCTAssertEqual(mappedObject?.int32Optional, Int32.max) XCTAssertEqual(mappedObject?.int32ImplicityUnwrapped, Int32.max) XCTAssertEqual(mappedObject?.int64, Int64(Int32.max)) XCTAssertEqual(mappedObject?.int64Optional, Int64(Int32.max)) XCTAssertEqual(mappedObject?.int64ImplicityUnwrapped, Int64(Int32.max)) #endif XCTAssertEqual(mappedObject?.uint, UInt.max) XCTAssertEqual(mappedObject?.uintOptional, UInt.max) XCTAssertEqual(mappedObject?.uintImplicityUnwrapped, UInt.max) XCTAssertEqual(mappedObject?.uint8, 0) XCTAssertEqual(mappedObject?.uint8Optional, nil) XCTAssertEqual(mappedObject?.uint8ImplicityUnwrapped, nil) XCTAssertEqual(mappedObject?.uint16, 0) XCTAssertEqual(mappedObject?.uint16Optional, nil) XCTAssertEqual(mappedObject?.uint16ImplicityUnwrapped, nil) #if arch(x86_64) || arch(arm64) XCTAssertEqual(mappedObject?.uint32, 0) XCTAssertEqual(mappedObject?.uint32Optional, nil) XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, nil) XCTAssertEqual(mappedObject?.uint64, UInt64.max) XCTAssertEqual(mappedObject?.uint64Optional, UInt64.max) XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, UInt64.max) #else XCTAssertEqual(mappedObject?.uint32, UInt32.max) XCTAssertEqual(mappedObject?.uint32Optional, UInt32.max) XCTAssertEqual(mappedObject?.uint32ImplicityUnwrapped, UInt32.max) XCTAssertEqual(mappedObject?.uint64, UInt64(UInt32.max)) XCTAssertEqual(mappedObject?.uint64Optional, UInt64(UInt32.max)) XCTAssertEqual(mappedObject?.uint64ImplicityUnwrapped, UInt64(UInt32.max)) #endif } func testMappingDoubleFromJSON(){ let value: Double = 11 let JSONString = "{\"double\" : \(value), \"doubleOpt\" : \(value), \"doubleImp\" : \(value)}" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.double, value) XCTAssertEqual(mappedObject?.doubleOptional, value) XCTAssertEqual(mappedObject?.doubleImplicityUnwrapped, value) } func testMappingFloatFromJSON(){ let value: Float = 11 let JSONString = "{\"float\" : \(value), \"floatOpt\" : \(value), \"floatImp\" : \(value)}" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.float, value) XCTAssertEqual(mappedObject?.floatOptional, value) XCTAssertEqual(mappedObject?.floatImplicityUnwrapped, value) } func testMappingStringFromJSON(){ let value: String = "STRINGNGNGG" let JSONString = "{\"string\" : \"\(value)\", \"stringOpt\" : \"\(value)\", \"stringImp\" : \"\(value)\"}" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.string, value) XCTAssertEqual(mappedObject?.stringOptional, value) XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) } func testMappingAnyObjectFromJSON(){ let value1 = "STRING" let value2: Int = 1234 let value3: Double = 11.11 let JSONString = "{\"anyObject\" : \"\(value1)\", \"anyObjectOpt\" : \(value2), \"anyObjectImp\" : \(value3)}" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.anyObject as? String, value1) XCTAssertEqual(mappedObject?.anyObjectOptional as? Int, value2) XCTAssertEqual(mappedObject?.anyObjectImplicitlyUnwrapped as? Double, value3) } func testMappingStringFromNSStringJSON(){ let value: String = "STRINGNGNGG" let JSONNSString : NSString = "{\"string\" : \"\(value)\", \"stringOpt\" : \"\(value)\", \"stringImp\" : \"\(value)\"}" as NSString let mappedObject = mapper.map(JSONString: JSONNSString as String) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.string, value) XCTAssertEqual(mappedObject?.stringOptional, value) XCTAssertEqual(mappedObject?.stringImplicityUnwrapped, value) } // MARK: Test mapping Arrays to JSON and back (with basic types in them Bool, Int, Double, Float, String) func testMappingBoolArrayFromJSON(){ let value: Bool = true let JSONString = "{\"arrayBool\" : [\(value)], \"arrayBoolOpt\" : [\(value)], \"arrayBoolImp\" : [\(value)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayBool.first, value) XCTAssertEqual(mappedObject?.arrayBoolOptional?.first, value) XCTAssertEqual(mappedObject?.arrayBoolImplicityUnwrapped.first, value) } func testMappingIntArrayFromJSON(){ let value: Int = 1 let JSONString = "{\"arrayInt\" : [\(value)], \"arrayIntOpt\" : [\(value)], \"arrayIntImp\" : [\(value)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayInt.first, value) XCTAssertEqual(mappedObject?.arrayIntOptional?.first, value) XCTAssertEqual(mappedObject?.arrayIntImplicityUnwrapped.first, value) } func testMappingDoubleArrayFromJSON(){ let value: Double = 1.0 let JSONString = "{\"arrayDouble\" : [\(value)], \"arrayDoubleOpt\" : [\(value)], \"arrayDoubleImp\" : [\(value)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayDouble.first, value) XCTAssertEqual(mappedObject?.arrayDoubleOptional?.first, value) XCTAssertEqual(mappedObject?.arrayDoubleImplicityUnwrapped.first, value) } func testMappingFloatArrayFromJSON(){ let value: Float = 1.001 let JSONString = "{\"arrayFloat\" : [\(value)], \"arrayFloatOpt\" : [\(value)], \"arrayFloatImp\" : [\(value)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayFloat.first, value) XCTAssertEqual(mappedObject?.arrayFloatOptional?.first, value) XCTAssertEqual(mappedObject?.arrayFloatImplicityUnwrapped?.first, value) } func testMappingStringArrayFromJSON(){ let value: String = "Stringgggg" let JSONString = "{\"arrayString\" : [\"\(value)\"], \"arrayStringOpt\" : [\"\(value)\"], \"arrayStringImp\" : [\"\(value)\"] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayString.first, value) XCTAssertEqual(mappedObject?.arrayStringOptional?.first, value) XCTAssertEqual(mappedObject?.arrayStringImplicityUnwrapped.first, value) } func testMappingAnyObjectArrayFromJSON(){ let value1 = "STRING" let value2: Int = 1234 let value3: Double = 11.11 let JSONString = "{\"arrayAnyObject\" : [\"\(value1)\"], \"arrayAnyObjectOpt\" : [\(value2)], \"arrayAnyObjectImp\" : [\(value3)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayAnyObject.first as? String, value1) XCTAssertEqual(mappedObject?.arrayAnyObjectOptional?.first as? Int, value2) XCTAssertEqual(mappedObject?.arrayAnyObjectImplicitlyUnwrapped.first as? Double, value3) } // MARK: Test mapping Dictionaries to JSON and back (with basic types in them Bool, Int, Double, Float, String) func testMappingBoolDictionaryFromJSON(){ let key = "key" let value: Bool = true let JSONString = "{\"dictBool\" : { \"\(key)\" : \(value)}, \"dictBoolOpt\" : { \"\(key)\" : \(value)}, \"dictBoolImp\" : { \"\(key)\" : \(value)} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictBool[key], value) XCTAssertEqual(mappedObject?.dictBoolOptional?[key], value) XCTAssertEqual(mappedObject?.dictBoolImplicityUnwrapped[key], value) } func testMappingIntDictionaryFromJSON(){ let key = "key" let value: Int = 11 let JSONString = "{\"dictInt\" : { \"\(key)\" : \(value)}, \"dictIntOpt\" : { \"\(key)\" : \(value)}, \"dictIntImp\" : { \"\(key)\" : \(value)} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictInt[key], value) XCTAssertEqual(mappedObject?.dictIntOptional?[key], value) XCTAssertEqual(mappedObject?.dictIntImplicityUnwrapped[key], value) } func testMappingDoubleDictionaryFromJSON(){ let key = "key" let value: Double = 11 let JSONString = "{\"dictDouble\" : { \"\(key)\" : \(value)}, \"dictDoubleOpt\" : { \"\(key)\" : \(value)}, \"dictDoubleImp\" : { \"\(key)\" : \(value)} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictDouble[key], value) XCTAssertEqual(mappedObject?.dictDoubleOptional?[key], value) XCTAssertEqual(mappedObject?.dictDoubleImplicityUnwrapped[key], value) } func testMappingFloatDictionaryFromJSON(){ let key = "key" let value: Float = 111.1 let JSONString = "{\"dictFloat\" : { \"\(key)\" : \(value)}, \"dictFloatOpt\" : { \"\(key)\" : \(value)}, \"dictFloatImp\" : { \"\(key)\" : \(value)} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictFloat[key], value) XCTAssertEqual(mappedObject?.dictFloatOptional?[key], value) XCTAssertEqual(mappedObject?.dictFloatImplicityUnwrapped?[key], value) } func testMappingStringDictionaryFromJSON(){ let key = "key" let value = "value" let JSONString = "{\"dictString\" : { \"\(key)\" : \"\(value)\"}, \"dictStringOpt\" : { \"\(key)\" : \"\(value)\"}, \"dictStringImp\" : { \"\(key)\" : \"\(value)\"} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictString[key], value) XCTAssertEqual(mappedObject?.dictStringOptional?[key], value) XCTAssertEqual(mappedObject?.dictStringImplicityUnwrapped?[key], value) } func testMappingAnyObjectDictionaryFromJSON(){ let key = "key" let value1 = "STRING" let value2: Int = 1234 let value3: Double = 11.11 let JSONString = "{\"dictAnyObject\" : { \"\(key)\" : \"\(value1)\"}, \"dictAnyObjectOpt\" : { \"\(key)\" : \(value2)}, \"dictAnyObjectImp\" : { \"\(key)\" : \(value3)} }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictAnyObject[key] as? String, value1) XCTAssertEqual(mappedObject?.dictAnyObjectOptional?[key] as? Int, value2) XCTAssertEqual(mappedObject?.dictAnyObjectImplicitlyUnwrapped[key] as? Double, value3) } func testMappingIntEnumFromJSON(){ let value: BasicTypes.EnumInt = .Another let JSONString = "{\"enumInt\" : \(value.rawValue), \"enumIntOpt\" : \(value.rawValue), \"enumIntImp\" : \(value.rawValue) }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumInt, value) XCTAssertEqual(mappedObject?.enumIntOptional, value) XCTAssertEqual(mappedObject?.enumIntImplicitlyUnwrapped, value) } func testMappingIntEnumFromJSONShouldNotCrashWithNonDefinedvalue() { let value = Int.min let JSONString = "{\"enumInt\" : \(value), \"enumIntOpt\" : \(value), \"enumIntImp\" : \(value) }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumInt, BasicTypes.EnumInt.Default) XCTAssertNil(mappedObject?.enumIntOptional) XCTAssertNil(mappedObject?.enumIntImplicitlyUnwrapped) } func testMappingDoubleEnumFromJSON(){ let value: BasicTypes.EnumDouble = .Another let JSONString = "{\"enumDouble\" : \(value.rawValue), \"enumDoubleOpt\" : \(value.rawValue), \"enumDoubleImp\" : \(value.rawValue) }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumDouble, value) XCTAssertEqual(mappedObject?.enumDoubleOptional, value) XCTAssertEqual(mappedObject?.enumDoubleImplicitlyUnwrapped, value) } func testMappingFloatEnumFromJSON(){ let value: BasicTypes.EnumFloat = .Another let JSONString = "{\"enumFloat\" : \(value.rawValue), \"enumFloatOpt\" : \(value.rawValue), \"enumFloatImp\" : \(value.rawValue) }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumFloat, value) XCTAssertEqual(mappedObject?.enumFloatOptional, value) XCTAssertEqual(mappedObject?.enumFloatImplicitlyUnwrapped, value) } func testMappingStringEnumFromJSON(){ let value: BasicTypes.EnumString = .Another let JSONString = "{\"enumString\" : \"\(value.rawValue)\", \"enumStringOpt\" : \"\(value.rawValue)\", \"enumStringImp\" : \"\(value.rawValue)\" }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.enumString, value) XCTAssertEqual(mappedObject?.enumStringOptional, value) XCTAssertEqual(mappedObject?.enumStringImplicitlyUnwrapped, value) } func testMappingEnumIntArrayFromJSON(){ let value: BasicTypes.EnumInt = .Another let JSONString = "{ \"arrayEnumInt\" : [\(value.rawValue)], \"arrayEnumIntOpt\" : [\(value.rawValue)], \"arrayEnumIntImp\" : [\(value.rawValue)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.arrayEnumInt.first, value) XCTAssertEqual(mappedObject?.arrayEnumIntOptional?.first, value) XCTAssertEqual(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first, value) } func testMappingEnumIntArrayFromJSONShouldNotCrashWithNonDefinedvalue() { let value = Int.min let JSONString = "{ \"arrayEnumInt\" : [\(value)], \"arrayEnumIntOpt\" : [\(value)], \"arrayEnumIntImp\" : [\(value)] }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertNil(mappedObject?.arrayEnumInt.first) XCTAssertNil(mappedObject?.arrayEnumIntOptional?.first) XCTAssertNil(mappedObject?.arrayEnumIntImplicitlyUnwrapped.first) } func testMappingEnumIntDictionaryFromJSON(){ let key = "key" let value: BasicTypes.EnumInt = .Another let JSONString = "{ \"dictEnumInt\" : { \"\(key)\" : \(value.rawValue) }, \"dictEnumIntOpt\" : { \"\(key)\" : \(value.rawValue) }, \"dictEnumIntImp\" : { \"\(key)\" : \(value.rawValue) } }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertEqual(mappedObject?.dictEnumInt[key], value) XCTAssertEqual(mappedObject?.dictEnumIntOptional?[key], value) XCTAssertEqual(mappedObject?.dictEnumIntImplicitlyUnwrapped[key], value) } func testMappingEnumIntDictionaryFromJSONShouldNotCrashWithNonDefinedvalue() { let key = "key" let value = Int.min let JSONString = "{ \"dictEnumInt\" : { \"\(key)\" : \(value) }, \"dictEnumIntOpt\" : { \"\(key)\" : \(value) }, \"dictEnumIntImp\" : { \"\(key)\" : \(value) } }" let mappedObject = mapper.map(JSONString: JSONString) XCTAssertNotNil(mappedObject) XCTAssertNil(mappedObject?.dictEnumInt[key]) XCTAssertNil(mappedObject?.dictEnumIntOptional?[key]) XCTAssertNil(mappedObject?.dictEnumIntImplicitlyUnwrapped[key]) } func testObjectModelOptionalDictionnaryOfPrimitives() { let JSON: [String: [String: Any]] = ["dictStringString":["string": "string"], "dictStringBool":["string": false], "dictStringInt":["string": 1], "dictStringDouble":["string": 1.1], "dictStringFloat":["string": Float(1.2)]] let mapper = Mapper<TestCollectionOfPrimitives>() let testSet: TestCollectionOfPrimitives! = mapper.map(JSON: JSON) XCTAssertNotNil(testSet) XCTAssertTrue(testSet.dictStringString.count > 0) XCTAssertTrue(testSet.dictStringInt.count > 0) XCTAssertTrue(testSet.dictStringBool.count > 0) XCTAssertTrue(testSet.dictStringDouble.count > 0) XCTAssertTrue(testSet.dictStringFloat.count > 0) } }
mit
842dcb126339a3bd51466e63af7c34ca
35.793831
224
0.730068
4.028617
false
true
false
false
iwheelbuy/VK
VK/Method/Docs/VK+Method+Docs+Get.swift
1
2152
import Foundation public extension Method.Docs { /// Возвращает расширенную информацию о документах пользователя или сообщества. public struct Get: Strategy { /// Количество документов, информацию о которых нужно вернуть. По умолчанию: все документы. Максимальное количество документов, которое можно получить: 2000. public let count: Int? /// Cмещение, необходимое для выборки определенного подмножества документов. Максимальное значение: 1999 public let offset: Int? /// Идентификатор пользователя или сообщества, которому принадлежат документы. По умолчанию идентификатор текущего пользователя. public let ownerId: Int? /// Специальный ключ доступа для идентификации в API public let token: Token /// Фильтр по типу документа, по умолчанию все типы public let type: Int? public init(count: Int? = nil, offset: Int? = nil, ownerId: Int? = nil, token: Token, type: Int? = nil) { self.count = count self.offset = offset self.ownerId = ownerId self.token = token self.type = type } public var method: String { return "docs.get" } public var parameters: [String: Any] { var dictionary = [String: Any]() dictionary["access_token"] = token if let ownerId = ownerId { dictionary["owner_id"] = ownerId } return dictionary } public var transform: (Object.Response<Object.List<Object.Doc>>) -> [Object.Doc] { return { $0.response.items } } } }
mit
867d47ffd730f4ce28890590979008f2
39.214286
165
0.602131
3.563291
false
false
false
false
dbsystel/DBNetworkStack
Tests/ContainerNetworkTaskTest.swift
1
1244
// // Created by Christian Himmelsbach on 23.07.18. // import XCTest import DBNetworkStack class ContainerNetworkTaskTest: XCTestCase { func testGIVEN_AuthenticatorNetworkTask_WHEN_ResumeTask_THEN_UnderlyingTaskShouldBeResumed() { //Given let taskMock = NetworkTaskMock() let task = ContainerNetworkTask() task.underlyingTask = taskMock //When task.resume() //Then XCTAssert(taskMock.state == .resumed) } func testGIVEN_AuthenticatorNetworkTask_WHEN_SuspendTask_THEN_UnderlyingTaskShouldBeSuspened() { //Given let taskMock = NetworkTaskMock() let task = ContainerNetworkTask() task.underlyingTask = taskMock //When task.suspend() //Then XCTAssert(taskMock.state == .suspended) } func testGIVEN_AuthenticatorNetworkTask_WHEN_CancelTask_THEN_UnderlyingTaskShouldBeCanceled() { // Given let taskMock = NetworkTaskMock() let task = ContainerNetworkTask() task.underlyingTask = taskMock // When task.cancel() // Then XCTAssert(taskMock.state == .canceled) } }
mit
b9131eec96265e67a337f62791668d1a
24.387755
100
0.610932
4.803089
false
true
false
false
awsdocs/aws-doc-sdk-examples
swift/example_code/iam/ListAttachedRolePolicies/Sources/ServiceHandler/ServiceHandler.swift
1
2951
/* A class containing functions that interact with AWS services. Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ // snippet-start:[iam.swift.listattachedrolepolicies.handler] // snippet-start:[iam.swift.listattachedrolepolicies.handler.imports] import Foundation import AWSIAM import ClientRuntime import AWSClientRuntime // snippet-end:[iam.swift.listattachedrolepolicies.handler.imports] /// Errors returned by `ServiceHandler` functions. enum ServiceHandlerError: Error { case noSuchGroup case noSuchRole case noSuchPolicy case noSuchUser } /// A class containing all the code that interacts with the AWS SDK for Swift. public class ServiceHandler { public let client: IamClient /// Initialize and return a new ``ServiceHandler`` object, which is used /// to drive the AWS calls used for the example. The Region string /// `AWS_GLOBAL` is used because users are shared across all Regions. /// /// - Returns: A new ``ServiceHandler`` object, ready to be called to /// execute AWS operations. // snippet-start:[iam.swift.listattachedrolepolicies.handler.init] public init() async { do { client = try IamClient(region: "AWS_GLOBAL") } catch { print("ERROR: ", dump(error, name: "Initializing Amazon IAM client")) exit(1) } } // snippet-end:[iam.swift.listattachedrolepolicies.handler.init] // snippet-start:[iam.swift.listattachedrolepolicies.handler.listattachedrolepolicies] /// Returns a list of AWS Identity and Access Management (IAM) policies /// that are attached to the role. /// /// - Parameter role: The IAM role to return the policy list for. /// /// - Returns: An array of `IamClientTypes.AttachedPolicy` objects /// describing each managed policy that's attached to the role. public func listAttachedRolePolicies(role: String) async throws -> [IamClientTypes.AttachedPolicy] { var policyList: [IamClientTypes.AttachedPolicy] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListAttachedRolePoliciesInput( marker: marker, roleName: role ) let output = try await client.listAttachedRolePolicies(input: input) guard let attachedPolicies = output.attachedPolicies else { return policyList } for attachedPolicy in attachedPolicies { policyList.append(attachedPolicy) } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return policyList } // snippet-end:[iam.swift.listattachedrolepolicies.handler.listattachedrolepolicies] } // snippet-end:[iam.swift.listattachedrolepolicies.handler]
apache-2.0
f952912cd698b15aef94851b3c6e3f8f
35.432099
104
0.665876
4.561051
false
false
false
false
StupidTortoise/personal
iOS/Swift/SimpleAlarm/SimpleAlarm/AlarmControl.swift
1
3422
// // Alarm.swift // SimpleAlarm // // Created by tortoise on 7/27/15. // Copyright (c) 2015 703. All rights reserved. // import Foundation import AVFoundation struct AlarmData { var alarmTime: String? var alarmDays: [String]? var alarmTone: String? var alarmUse = false var alarmLazy = false var alarmGradual = false } class AlarmControl { var alarmDict = Dictionary<String, AlarmData>() var alarmArray = [AlarmData]() var playTimer: NSTimer? var alarmTimer: NSTimer? var audioPlayer: AVAudioPlayer? var isPlay = false init() { var alarmTime = "13:22" var alarm = AlarmData() alarm.alarmTime = alarmTime alarm.alarmDays = ["周一", "周二"] alarm.alarmTone = "夜的钢琴曲" alarm.alarmUse = true alarm.alarmLazy = true alarm.alarmGradual = true alarmDict[alarmTime] = alarm alarmArray.append(alarm) var session = AVAudioSession.sharedInstance() session.setCategory(AVAudioSessionCategoryPlayback, error: nil) session.setActive(true, error: nil) let bundle = NSBundle.mainBundle() let path = bundle.pathForResource("nokia", ofType: "m4r") let url = NSURL.fileURLWithPath(path!) audioPlayer = AVAudioPlayer(contentsOfURL: url!, error: nil) audioPlayer!.prepareToPlay() } var count: Int { get { return alarmArray.count } } subscript(index: Int) -> AlarmData? { if index >= 0 && index < alarmDict.count { return alarmArray[index] } return nil } func run() { self.startAlarmTimer() } private func startAlarmTimer() { if self.alarmTimer == nil { // let interval:Double = 2 self.alarmTimer = NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: "checkAlarm", userInfo: nil, repeats: true) } } // or use @objc @objc private func checkAlarm() { let date = NSDate() let gregorian = NSCalendar(identifier: NSCalendarIdentifierGregorian) let unitFlags = NSCalendarUnit.CalendarUnitHour | NSCalendarUnit.CalendarUnitMinute let dateComp = gregorian!.components(unitFlags, fromDate: date) let currentTime = NSString(format: "%02d:%02d", dateComp.hour, dateComp.minute) as String println("currentTime: \(currentTime)") if let alarmData = self.alarmDict[currentTime] { if self.isPlay == false && audioPlayer != nil { audioPlayer!.volume = 0.0 self.startPlayTimer() audioPlayer!.play() self.isPlay = true } } } private func startPlayTimer() { if self.playTimer == nil { self.playTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateProgress", userInfo: nil, repeats: true) } } @objc private func updateProgress() { let inc = ( 1.0 / (audioPlayer!.duration * 5)) if audioPlayer!.volume - 1 < 0.0000001 { audioPlayer!.volume += Float(inc) println(audioPlayer!.volume) } } }
gpl-2.0
bfc7598499f1cf190ad39b0e76f885e4
26.901639
144
0.569624
4.593792
false
false
false
false
larryhou/swift
Hardware/Hardware/ViewController.swift
1
4651
// // ViewController.swift // Hardware // // Created by larryhou on 10/7/2017. // Copyright © 2017 larryhou. All rights reserved. // import UIKit class ItemCell: UITableViewCell { @IBOutlet var ib_name: UILabel! @IBOutlet var ib_value: UILabel! } class HeaderView: UITableViewHeaderFooterView { static let identifier = "section_header_view" var title: UILabel? override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) let title = UILabel() title.font = UIFont(name: "Courier New", size: 36) title.translatesAutoresizingMaskIntoConstraints = false self.contentView.addSubview(title) self.title = title let map: [String: Any] = ["title": title] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-(10)-[title]-|", options: .alignAllLeft, metrics: nil, views: map)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[title]-|", options: .alignAllCenterY, metrics: nil, views: map)) backgroundView = UIView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { contentView.frame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height) } } class ViewController: UITableViewController { let background = DispatchQueue(label: "data_reload_queue") var data: [CategoryType: [ItemInfo]]! override func viewDidLoad() { super.viewDidLoad() data = [:] Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(reload), userInfo: nil, repeats: true) tableView.register(HeaderView.self, forHeaderFooterViewReuseIdentifier: HeaderView.identifier) self.navigationController?.navigationBar.titleTextAttributes = [.font: UIFont(name: "Courier New", size: 30)!] } @objc func reload() { background.async { HardwareModel.shared.reload() DispatchQueue.main.async { [unowned self] in self.data = [:] self.tableView.reloadData() } } } override func numberOfSections(in tableView: UITableView) -> Int { return 8 } private func filter(_ data: [ItemInfo]) -> [ItemInfo] { return data.filter({$0.parent == -1}) } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let cate = CategoryType(rawValue: section) { if let count = self.data[cate]?.count, count > 0 { return count } let data = HardwareModel.shared.get(category: cate, reload: false) self.data[cate] = data return data.count } return 0 } override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50 } override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: HeaderView.identifier) as! HeaderView if let cate = CategoryType(rawValue: section) { header.title?.text = "\(cate)" } return header } override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let cate = CategoryType(rawValue: section) { return "\(cate)" } return nil } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell") as! ItemCell if let cate = CategoryType(rawValue: indexPath.section), let data = self.data[cate] { let info = data[indexPath.row] cell.ib_value.text = info.value cell.ib_name.text = info.name } return cell } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "review", let cell = sender as? ItemCell { if let index = tableView.indexPath(for: cell), let cate = CategoryType(rawValue: index.section), let data = self.data[cate] { let item = data[index.row] if let dst = segue.destination as? ReviewController { dst.data = item } } } else { super.prepare(for: segue, sender: sender) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
4dd610734e04e7e465e35d71ebbf0771
32.941606
144
0.624731
4.818653
false
false
false
false
SwiftyVK/SwiftyVK
Library/Sources/Networking/URLs/UrlRequestBuilder.swift
2
4296
import Foundation protocol UrlRequestBuilder { func build(type: RequestType, config: Config, capthca: Captcha?, token: Token?) throws -> URLRequest } final class UrlRequestBuilderImpl: UrlRequestBuilder { private let baseUrl = "https://api.vk.com/method/" private let queryBuilder: QueryBuilder private let bodyBuilder: MultipartBodyBuilder init( queryBuilder: QueryBuilder, bodyBuilder: MultipartBodyBuilder ) { self.queryBuilder = queryBuilder self.bodyBuilder = bodyBuilder } func build( type: RequestType, config: Config, capthca: Captcha?, token: Token? ) throws -> URLRequest { var urlRequest: URLRequest switch type { case let .api(method, parameters): urlRequest = try make( from: method, parameters: parameters, config: config, capthca: capthca, token: token ) urlRequest.timeoutInterval = config.attemptTimeout case let .upload(url, media, partType): urlRequest = try make(from: media, url: url, partType: partType) urlRequest.timeoutInterval = media.reduce(0.0) { $0 + Double($1.data.count) } * 0.001 case let .url(url): urlRequest = try make(from: url) urlRequest.timeoutInterval = config.attemptTimeout } return urlRequest } private func make( from apiMethod: String, parameters: RawParameters, config: Config, capthca: Captcha?, token: Token? ) throws -> URLRequest { var req: URLRequest let query = queryBuilder.makeQuery(parameters: parameters, config: config, captcha: capthca, token: token) switch config.httpMethod { case .GET: req = try makeGetRequest(from: apiMethod, query: query) case .POST: req = try makePostRequest(from: apiMethod, query: query) } req.httpMethod = config.httpMethod.rawValue return req } private func makeGetRequest(from apiMethod: String, query: String) throws -> URLRequest { guard let url = URL(string: baseUrl + apiMethod + "?" + query) else { throw VKError.wrongUrl } return URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) } private func makePostRequest(from apiMethod: String, query: String) throws -> URLRequest { guard let url = URL(string: baseUrl + apiMethod) else { throw VKError.wrongUrl } var req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) let charset = String( CFStringConvertEncodingToIANACharSetName( CFStringConvertNSStringEncodingToEncoding(String.Encoding.utf8.rawValue) ) ) req.setValue("application/x-www-form-urlencoded; charset=\(charset)", forHTTPHeaderField: "Content-Type") req.httpBody = query.data(using: .utf8) return req } private func make(from media: [Media], url: String, partType: PartType) throws -> URLRequest { guard let url = URL(string: url) else { throw VKError.wrongUrl } var req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) req.httpMethod = "POST" req.addValue("", forHTTPHeaderField: "Accept-Language") req.addValue("8bit", forHTTPHeaderField: "Content-Transfer-Encoding") req.setValue("multipart/form-data; boundary=\(bodyBuilder.boundary)", forHTTPHeaderField: "Content-Type") req.httpBody = bodyBuilder.makeBody(from: media, partType: partType) return req } private func make(from url: String) throws -> URLRequest { guard let url = URL(string: url) else { throw VKError.wrongUrl } var req = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData) req.httpMethod = "GET" return req } }
mit
1a0970b06e8672fea64ffc586231bece
32.046154
114
0.594739
5.048179
false
true
false
false
szysz3/ios-timetracker
TimeTracker/AddTaskViewController.swift
1
3937
// // ChooseTaskViewController.swift // TimeTracker // // Created by Michał Szyszka on 20.09.2016. // Copyright © 2016 Michał Szyszka. All rights reserved. // import Foundation import UIKit class AddTaskViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { //MARK: Outlets & Actions @IBOutlet weak var bottomContainer: UIView! @IBOutlet weak var navBar: UIView! @IBOutlet weak var btnAddTask: UIButton! @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var textFieldTaskName: UITextField! @IBAction func onTaskNameEditingChanged(_ sender: UITextField) { btnAddTask.isEnabled = !(sender.text?.isEmpty)! } //MARK: Fields & Properties var dataSource: [UIColor]! var selectedIndex = 0 private var selectedTask: Task? var createdTask: Task { get { if let task = selectedTask { return task } selectedTask = Task(taskName: textFieldTaskName.text!, backgroundColor: dataSource[selectedIndex]) return selectedTask! } } //MARK: Methods override func viewDidLoad() { super.viewDidLoad() dataSource = getDataSourceList() initialize() } func getDataSourceList() -> [UIColor]{ var colorList: [UIColor] = [] if let path = Bundle.main.path(forResource: "TaskColors", ofType: "plist"){ if let dict = NSArray(contentsOfFile: path) as NSArray! { for color in dict { let array = color as! NSArray let uiColor = UIColor(colorLiteralRed: Float(array[0] as! String)!, green: Float(array[1] as! String)!, blue: Float(array[2] as! String)!, alpha: Float(array[3] as! String)!) colorList.append(uiColor) } } } return colorList } private func initialize(){ navBar.layer.shadowOffset = CGSize(width: 0, height: 2) navBar.layer.shadowColor = UIColor.gray.cgColor navBar.layer.shadowRadius = 2 navBar.layer.shadowOpacity = 0.8 bottomContainer.layer.shadowOffset = CGSize(width: 0, height: -1) bottomContainer.layer.shadowColor = UIColor.gray.cgColor bottomContainer.layer.shadowRadius = 1 bottomContainer.layer.shadowOpacity = 0.3 btnAddTask.layer.cornerRadius = UIConsts.cornerRadius btnAddTask.layer.borderWidth = UIConsts.borderWidth btnAddTask.layer.borderColor = UIColor.lightGray.cgColor } //MARK: UICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let selectedCell = collectionView.dequeueReusableCell(withReuseIdentifier: AddTaskCellCollectionViewCell.tag, for: indexPath) as! AddTaskCellCollectionViewCell selectedIndex = indexPath.row selectedCell.setCellSelected(true) collectionView.reloadData() } public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let addTaskCell = collectionView.dequeueReusableCell(withReuseIdentifier: AddTaskCellCollectionViewCell.tag, for: indexPath) as! AddTaskCellCollectionViewCell addTaskCell.setColor(dataSource[indexPath.row]) addTaskCell.setCellSelected(indexPath.row == selectedIndex) return addTaskCell } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSource.count } }
mit
98876a2def490db51a6ef8bd7afb32fd
34.763636
128
0.622267
5.48675
false
false
false
false
wibosco/WhiteBoardCodingChallenges
WhiteBoardCodingChallenges/Challenges/CrackingTheCodingInterview/IntersectingNode/SingleLinkedList.swift
1
641
// // SingleLinkedList.swift // WhiteBoardCodingChallenges // // Created by William Boles on 30/05/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit class SingleLinkedList: NSObject { // MARK: Properties var head: LinkedListNode? // MARK: Add func addNode(node: LinkedListNode) { if head == nil { head = node } else { var n = head! while n.next != nil { n = n.next! } n.next = node } } }
mit
8b15da1caaebfab10064872c3d4453b7
16.297297
48
0.439063
4.848485
false
false
false
false
mileswd/mac2imgur
mac2imgur/MenuController.swift
1
1844
/* This file is part of mac2imgur. * * mac2imgur 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. * mac2imgur 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 mac2imgur. If not, see <http://www.gnu.org/licenses/>. */ import Cocoa class MenuController: NSObject, NSMenuDelegate { let menu: NSMenu override init() { self.menu = NSMenu() super.init() menu.delegate = self } /// Creates the menu from scratch. func buildMenu() { menu.removeAllItems() // Menu creation logic } /// Whether the menu should be rebuilt before it is displayed. var shouldRebuildMenu: Bool { return false } /// The title of the menu. var menuTitle: String { return "" } /// Rebuilds the menu, even if it is currently open. func rebuildMenu() { let timer = Timer(timeInterval: 0, target: self, selector: #selector(buildMenu), userInfo: nil, repeats: false) RunLoop.current.add(timer, forMode: .eventTrackingRunLoopMode) } // MARK: NSMenuDelegate func menuNeedsUpdate(_ menu: NSMenu) { if shouldRebuildMenu || menu.numberOfItems == 0 { buildMenu() } } }
gpl-3.0
ac9046d3ed84ec2d52a1021d4fdaab6b
26.522388
71
0.597072
4.716113
false
false
false
false
tad-iizuka/swift-sdk
Source/RestKit/RestRequest.swift
1
11978
/** * Copyright IBM Corporation 2016-2017 * * 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 public struct RestRequest { public static let userAgent: String = { let sdk = "watson-apis-swift-sdk" let sdkVersion = "0.14.1" let operatingSystem: String = { #if os(iOS) return "iOS" #elseif os(watchOS) return "watchOS" #elseif os(tvOS) return "tvOS" #elseif os(macOS) return "macOS" #elseif os(Linux) return "Linux" #else return "Unknown" #endif }() let operatingSystemVersion: String = { let os = ProcessInfo.processInfo.operatingSystemVersion return "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)" }() return "\(sdk)/\(sdkVersion) \(operatingSystem)/\(operatingSystemVersion)" }() private let request: URLRequest private let session = URLSession(configuration: URLSessionConfiguration.default) public init( method: String, url: String, credentials: Credentials, headerParameters: [String: String], acceptType: String? = nil, contentType: String? = nil, queryItems: [URLQueryItem]? = nil, messageBody: Data? = nil) { // construct url with query parameters var urlComponents = URLComponents(string: url)! if let queryItems = queryItems, !queryItems.isEmpty { urlComponents.queryItems = queryItems } // construct basic mutable request var request = URLRequest(url: urlComponents.url!) request.httpMethod = method request.httpBody = messageBody // set the request's user agent request.setValue(RestRequest.userAgent, forHTTPHeaderField: "User-Agent") // set the request's authentication credentials switch credentials { case .apiKey: break case .basicAuthentication(let username, let password): let authData = (username + ":" + password).data(using: .utf8)! let authString = authData.base64EncodedString() request.setValue("Basic \(authString)", forHTTPHeaderField: "Authorization") } // set the request's header parameters for (key, value) in headerParameters { request.setValue(value, forHTTPHeaderField: key) } // set the request's accept type if let acceptType = acceptType { request.setValue(acceptType, forHTTPHeaderField: "Accept") } // set the request's content type if let contentType = contentType { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } self.request = request } public func response(completionHandler: @escaping (Data?, HTTPURLResponse?, Error?) -> Void) { let task = session.dataTask(with: request) { (data, response, error) in completionHandler(data, response as? HTTPURLResponse, error) } task.resume() } public func responseData(completionHandler: @escaping (RestResponse<Data>) -> Void) { response() { data, response, error in guard let data = data else { let result = Result<Data>.failure(RestError.noData) let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result) completionHandler(dataResponse) return } let result = Result.success(data) let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) } } public func responseObject<T: JSONDecodable>( dataToError: ((Data) -> Error?)? = nil, path: [JSONPathType]? = nil, completionHandler: @escaping (RestResponse<T>) -> Void) { response() { data, response, error in // ensure data is not nil guard let data = data else { let result = Result<T>.failure(RestError.noData) let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result) completionHandler(dataResponse) return } // can the data be parsed as an error? if let dataToError = dataToError, let error = dataToError(data) { let result = Result<T>.failure(error) let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) return } // parse json object let result: Result<T> do { let json = try JSON(data: data) let object: T if let path = path { switch path.count { case 0: object = try json.decode() case 1: object = try json.decode(at: path[0]) case 2: object = try json.decode(at: path[0], path[1]) case 3: object = try json.decode(at: path[0], path[1], path[2]) case 4: object = try json.decode(at: path[0], path[1], path[2], path[3]) case 5: object = try json.decode(at: path[0], path[1], path[2], path[3], path[4]) default: throw JSON.Error.keyNotFound(key: "ExhaustedVariadicParameterEncoding") } } else { object = try json.decode() } result = .success(object) } catch { result = .failure(error) } // execute callback let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) } } public func responseArray<T: JSONDecodable>( dataToError: ((Data) -> Error?)? = nil, path: [JSONPathType]? = nil, completionHandler: @escaping (RestResponse<[T]>) -> Void) { response() { data, response, error in // ensure data is not nil guard let data = data else { let result = Result<[T]>.failure(RestError.noData) let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result) completionHandler(dataResponse) return } // can the data be parsed as an error? if let dataToError = dataToError, let error = dataToError(data) { let result = Result<[T]>.failure(error) let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) return } // parse json object let result: Result<[T]> do { let json = try JSON(data: data) var array: [JSON] if let path = path { switch path.count { case 0: array = try json.getArray() case 1: array = try json.getArray(at: path[0]) case 2: array = try json.getArray(at: path[0], path[1]) case 3: array = try json.getArray(at: path[0], path[1], path[2]) case 4: array = try json.getArray(at: path[0], path[1], path[2], path[3]) case 5: array = try json.getArray(at: path[0], path[1], path[2], path[3], path[4]) default: throw JSON.Error.keyNotFound(key: "ExhaustedVariadicParameterEncoding") } } else { array = try json.getArray() } let objects: [T] = try array.map { json in try json.decode() } result = .success(objects) } catch { result = .failure(error) } // execute callback let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) } } public func responseString( dataToError: ((Data) -> Error?)? = nil, completionHandler: @escaping (RestResponse<String>) -> Void) { response() { data, response, error in // ensure data is not nil guard let data = data else { let result = Result<String>.failure(RestError.noData) let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result) completionHandler(dataResponse) return } // can the data be parsed as an error? if let dataToError = dataToError, let error = dataToError(data) { let result = Result<String>.failure(error) let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) return } // parse data as a string guard let string = String(data: data, encoding: .utf8) else { let result = Result<String>.failure(RestError.serializationError) let dataResponse = RestResponse(request: self.request, response: response, data: nil, result: result) completionHandler(dataResponse) return } // execute callback let result = Result.success(string) let dataResponse = RestResponse(request: self.request, response: response, data: data, result: result) completionHandler(dataResponse) } } public func download(to destination: URL, completionHandler: @escaping (HTTPURLResponse?, Error?) -> Void) { let task = session.downloadTask(with: request) { (source, response, error) in guard let source = source else { completionHandler(nil, RestError.invalidFile) return } let fileManager = FileManager.default do { try fileManager.moveItem(at: source, to: destination) } catch { completionHandler(nil, RestError.fileManagerError) } completionHandler(response as? HTTPURLResponse, error) } task.resume() } } public struct RestResponse<T> { public let request: URLRequest? public let response: HTTPURLResponse? public let data: Data? public let result: Result<T> } public enum Result<T> { case success(T) case failure(Error) } public enum Credentials { case apiKey case basicAuthentication(username: String, password: String) } public enum RestError: Error { case noData case serializationError case encodingError case fileManagerError case invalidFile }
apache-2.0
f12b06f412a15efe742ec2f3d1f95987
38.016287
118
0.558524
5.060414
false
false
false
false
hrscy/TodayNews
News/News/Classes/Video/Controller/VideoDetailViewController.swift
1
10343
// // VideoDetailViewController.swift // News // // Created by 杨蒙 on 2018/1/19. // Copyright © 2018年 hrscy. All rights reserved. // import UIKit import BMPlayer import RxSwift import RxCocoa import SnapKit import SVProgressHUD protocol VideoDetailViewControllerDelegate: class { /// 详情控制器将要消失 func VideoDetailViewControllerViewWillDisappear(_ realVideo: RealVideo, _ currentTime: TimeInterval, _ currentIndexPath: IndexPath) } class VideoDetailViewController: UIViewController { weak var delegate: VideoDetailViewControllerDelegate? /// 播放器 private lazy var player: BMPlayer = BMPlayer(customControlView: BMPlayerControlView()) /// 当前视频数据 var video = NewsModel() /// 评论数据 private var comments = [DongtaiComment]() /// 真实视频地址 var realVideo = RealVideo() /// 当前播放的时间 var currentTime: TimeInterval = 0 /// 当前点击的索引 var currentIndexPath = IndexPath(item: 0, section: 0) /// 喜欢按钮 @IBOutlet weak var loveButton: UIButton! @IBOutlet weak var bottomView: UIView! private let disposeBag = DisposeBag() /// 用户信息 view private lazy var userView = VideoDetailUserView.loadViewFromNib() /// 相关新视频的 view private lazy var relatedVideoView = RelatedVideoView() /// tableView private lazy var tableView: UITableView = { let tableView = UITableView() tableView.ym_registerCell(cell: DongtaiCommentCell.self) tableView.tableFooterView = UIView() tableView.separatorStyle = .none tableView.dataSource = self tableView.delegate = self tableView.showsVerticalScrollIndicator = false return tableView }() /// 返回按钮 private lazy var backButton: UIButton = { let backButton = UIButton() backButton.rx.controlEvent(.touchUpInside) .subscribe(onNext: { [weak self] in self!.navigationController?.popViewController(animated: true) }) .disposed(by: disposeBag) backButton.setImage(UIImage(named: "personal_home_back_white_24x24_"), for: .normal) return backButton }() override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) delegate?.VideoDetailViewControllerViewWillDisappear(realVideo, currentTime, currentIndexPath) } override func viewDidLoad() { super.viewDidLoad() // 设置播放器,修改属性 setupUI() // 获取数据 loadNetwork(with: video) // 添加点击事件 addAction() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { // 使用手势返回的时候,调用下面方法手动销毁 player.prepareToDealloc() } } extension VideoDetailViewController { /// 设置播放器,修改属性 private func setupUI() { loveButton.theme_setImage("images.love_video_20x20_", forState: .normal) loveButton.theme_setImage("images.love_video_press_20x20_", forState: .selected) player.delegate = self view.addSubview(player) view.addSubview(backButton) view.addSubview(userView) view.addSubview(tableView) player.snp.makeConstraints { $0.top.equalTo(view.snp.top).offset(isIPhoneX ? 40 : 0) $0.left.right.equalTo(view) $0.height.equalTo(view.snp.width).multipliedBy(9.0 / 16.0) } backButton.snp.makeConstraints { $0.leading.equalTo(view).offset(10) $0.size.equalTo(CGSize(width: 35, height: 35)) $0.top.equalTo(player.snp.top).offset(10) } userView.snp.makeConstraints { $0.top.equalTo(player.snp.bottom) $0.left.right.equalTo(view) $0.height.equalTo(45) } tableView.snp.makeConstraints { $0.top.equalTo(userView.snp.bottom) $0.bottom.equalTo(bottomView.snp.top) $0.left.right.equalTo(view) } } /// 获取数据 private func loadNetwork(with video: NewsModel) { // 需要先获取视频的真实播放地址 NetworkTool.parseVideoRealURL(video_id: video.video_detail_info.video_id, completionHandler: { self.realVideo = $0 // 设置视频播放地址 self.player.setVideo(resource: BMPlayerResource(url: URL(string: $0.video_list.video_1.mainURL)!)) // 设置当前播放的时间 self.player.seek(self.currentTime) }) // 视频详情数据 NetworkTool.loadArticleInformation(from: "click_video", itemId: video.item_id, groupId: video.group_id) { self.userView.userInfo = $0.user_info // 添加相关视频界面 // 使用自定义 view,这里不使用添加子控制器的方式,可参考 RelatedVideoTableViewController self.relatedVideoView.video = self.video self.relatedVideoView.videoDetail = $0 self.tableView.tableHeaderView = self.relatedVideoView } /// 添加上拉刷新 tableView.mj_footer = RefreshAutoGifFooter(refreshingBlock: { [weak self] in // 获取用户详情一般的详情的评论数据 NetworkTool.loadUserDetailNormalDongtaiComents(groupId: self!.video.group_id, offset: self!.comments.count, count: 20, completionHandler: { if self!.tableView.mj_footer.isRefreshing { self!.tableView.mj_footer.endRefreshing() } self!.tableView.mj_footer.pullingPercent = 0.0 if $0.count == 0 { self!.tableView.mj_footer.endRefreshingWithNoMoreData() SVProgressHUD.showInfo(withStatus: "没有更多数据啦!") return } self!.comments += $0 self!.tableView.reloadData() }) }) tableView.mj_footer.beginRefreshing() } } // MARK: - 添加点击事件 extension VideoDetailViewController { /// 添加点击事件 private func addAction() { // 覆盖按钮点击 userView.coverButton.rx.controlEvent(.touchUpInside) .subscribe(onNext: { [weak self] (_) in let userDetailVC = UserDetailViewController2() userDetailVC.userId = self!.userView.userInfo.user_id self!.navigationController?.pushViewController(userDetailVC, animated: true) }) .disposed(by: disposeBag) // 点击了查看更多 relatedVideoView.didSelectCheckMoreButton = { [weak self] in self!.tableView.tableHeaderView = self!.relatedVideoView } // 点击了 relatedVideoView 的 cell relatedVideoView.didSelectCell = { [weak self] in switch $0.card_type { case .video, .adVideo: // 视频、广告视频 // 获取数据 self!.loadNetwork(with: $0) case .adTextlink: // 广告链接 if self!.player.isPlaying { self!.player.pause() } let textLinkVC = TextLinkViewController() textLinkVC.url = $0.web_url self!.navigationController?.pushViewController(textLinkVC, animated: true) } } } /// 评论点击 @IBAction func commentButtonClicked(_ sender: UIButton) { } /// 喜欢点击 @IBAction func loveButtonClicked(_ sender: UIButton) { UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 0.5, options: .curveLinear, animations: { sender.imageView?.transform = CGAffineTransform(scaleX: sender.imageView!.width * 0.2, y: sender.imageView!.width * 0.2) }) { (_) in sender.imageView?.transform = .identity sender.isSelected = !sender.isSelected } } /// 分享点击 @IBAction func shareButtonClicked(_ sender: UIButton) { } } // MARK: - UITableViewDelegate, UITableViewDataSource extension VideoDetailViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.ym_dequeueReusableCell(indexPath: indexPath) as DongtaiCommentCell cell.comment = comments[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let comment = comments[indexPath.row] let postCommentView = PostCommentView.loadViewFromNib() if comment.screen_name != "" { postCommentView.placeholderLabel.text = "回复 \(comment.screen_name):" } else if comment.user.user_id != 0 { if comment.user.screen_name != "" { postCommentView.placeholderLabel.text = "回复 \(comment.user.screen_name):" } } view.addSubview(postCommentView) } } extension VideoDetailViewController: BMPlayerDelegate { func bmPlayer(player: BMPlayer, playerStateDidChange state: BMPlayerState) { } func bmPlayer(player: BMPlayer, loadedTimeDidChange loadedDuration: TimeInterval, totalDuration: TimeInterval) { } func bmPlayer(player: BMPlayer, playTimeDidChange currentTime: TimeInterval, totalTime: TimeInterval) { self.currentTime = currentTime } func bmPlayer(player: BMPlayer, playerIsPlaying playing: Bool) { } func bmPlayer(player: BMPlayer, playerOrientChanged isFullscreen: Bool) { } }
mit
69f9e49c9b06eb48c39de0eee483afad
34.223022
151
0.624898
4.716763
false
false
false
false
haawa799/WaniKani-Kanji-Strokes
WaniKani-Kanji-Strokes/Kanji.swift
1
1192
// // Kanji.swift // StrokeDrawingView // // Created by Andriy K. on 12/4/15. // Copyright © 2015 CocoaPods. All rights reserved. // import UIKit import KanjiBezierPaths class Kanji { let color0 = UIColor(red:0.95, green:0, blue:0.63, alpha:1) let bezierPathes: [UIBezierPath] let kanji: String init(kanji: String) { self.kanji = kanji self.bezierPathes = KanjiBezierPathesHelper.pathesForKanji(kanji) ?? [UIBezierPath]() } } extension UIColor { func lighter(amount : CGFloat = 0.25) -> UIColor { return hueColorWithBrightnessAmount(1 + amount) } func darker(amount : CGFloat = 0.25) -> UIColor { return hueColorWithBrightnessAmount(1 - amount) } private func hueColorWithBrightnessAmount(amount: CGFloat) -> UIColor { var hue : CGFloat = 0 var saturation : CGFloat = 0 var brightness : CGFloat = 0 var alpha : CGFloat = 0 if getHue(&hue, saturation: &saturation, brightness: &brightness, alpha: &alpha) { return UIColor( hue: hue, saturation: saturation, brightness: brightness * amount, alpha: alpha ) } else { return self } } }
mit
6d35fef240c756d8c6db1b74c4b57fdb
21.055556
89
0.63728
3.841935
false
false
false
false
xipengyang/SwiftApp1
we sale assistant/we sale assistant/AddOrderViewController.swift
1
10141
// // AddOrderViewController.swift // we sale assistant // // Created by xipeng yang on 7/02/15. // Copyright (c) 2015 xipeng yang. All rights reserved. // import UIKit //import Cent class AddOrderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate, UISearchDisplayDelegate { @IBOutlet weak var productTblView: UITableView! @IBOutlet weak var custSearchTblView: UITableView! @IBOutlet weak var customerName: UILabel! //@IBOutlet weak var addressField: UITextView! @IBOutlet weak var addProductBtn: MKButton! @IBOutlet weak var searchCustomerBtn: MKButton! @IBOutlet weak var weChatBtn: MKButton! @IBOutlet weak var searchBar: UISearchBar! @IBAction func backButtonClicked(sender: AnyObject) { appDel.rollbackAction() self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func saveButtonClicked(sender: AnyObject) { appDel.saveContextAction() self.dismissViewControllerAnimated(true, completion: nil) } @IBAction func customerButtonClicked(sender: AnyObject) { var current = self.searchBar.hidden self.searchBar.hidden = !current } @IBAction func handleShare(sender: UIButton){ let image = createOrderImage() /* it is VERY important to cast your strings to NSString otherwise the controller cannot display the appropriate sharing options */ // look for "applicationActivities" let activityView = UIActivityViewController( activityItems: [image, "WeSale Assistant"], //applicationActivities: [WeChatSessionActivity()]) applicationActivities: nil) presentViewController(activityView, animated: true, completion: { }) } override func viewDidLoad() { super.viewDidLoad() addProductBtn.titleLabel!.font = UIFont(name: GoogleIconName, size: 30.0) addProductBtn.setTitle(GoogleIcon.e819, forState: UIControlState.Normal) searchCustomerBtn.titleLabel!.font = UIFont(name: GoogleIconName, size: 30.0) searchCustomerBtn.setTitle(GoogleIcon.e60a, forState: UIControlState.Normal) weChatBtn.titleLabel!.font = UIFont(name: GoogleIconName, size: 30.0) weChatBtn.setTitle(GoogleIcon.e61d, forState: UIControlState.Normal) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) prepareData() productTblView.reloadData() } private func prepareData() { if let customer = order?.customer { self.customerName.text = customer.name //self.addressField.text = customer.address } // products = self.order!.products.sortedArrayUsingDescriptors([NSSortDescriptor(key: "productName", ascending: true, selector: "localizedStandardCompare:")]) as! [ProductD] } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if tableView == self.searchDisplayController!.searchResultsTableView { return self.filterdContacts.count } else if tableView == self.productTblView { return self.products.count + 1 } else { return self.contacts.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { //ask for a reusable cell from the tableview, the tableview will create a new one if it doesn't have any if tableView == self.productTblView { var cell: OrderProductCell? cell = self.productTblView.dequeueReusableCellWithIdentifier("product") as? OrderProductCell if (cell == nil) { cell = OrderProductCell(style: UITableViewCellStyle.Default, reuseIdentifier: "product") } if(indexPath.row == products.count){ cell?.topLabel.text = "" let total = amountSum.decimalNumberByRoundingAccordingToBehavior(roundUp) cell?.leftLabel.text = "Total $ \(total)" cell?.rightLabel.text = "" }else { let thisProduct = products[indexPath.row] cell?.topLabel.text = thisProduct.productName cell?.rightLabel.text = thisProduct.quantity!.stringValue cell?.leftLabel.text = "$ \(thisProduct.price!)" if (thisProduct.image != nil) { cell?.leftImage.image = UIImage(data: thisProduct.image!) }else { cell?.leftImage.image = nil } cell?.backgroundColor = UIColor.whiteColor() } return cell! }else { var cell: UITableViewCell? cell = tableView.dequeueReusableCellWithIdentifier("customer")! as UITableViewCell if (cell == nil) { cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "customer") } var customer : Contact if tableView == self.searchDisplayController!.searchResultsTableView { customer = filterdContacts[indexPath.row] } else { customer = contacts[indexPath.row] } // Configure the cell cell?.textLabel?.text = customer.name return cell! } } func filterContentForSearchText(searchText: String, scope: String = "All") { self.filterdContacts = self.contacts.filter({( contact : Contact) -> Bool in let stringMatch = contact.name!.rangeOfString(searchText) return stringMatch != nil }) } func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String?) -> Bool { self.filterContentForSearchText(searchString!, scope: "ALL") return true } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if tableView == self.searchDisplayController!.searchResultsTableView { let selected = filterdContacts[indexPath.row] customerName.text = selected.name! //addressField.text = selected.address let customerD = appDel.getPersonByIdAction(Int(selected.id)!).last self.order?.setValue(customerD, forKey: "customer") self.searchDisplayController!.setActive(false, animated: true) } else if(tableView == self.productTblView && indexPath.row < products.count) { let selectedProduct = products[indexPath.row] let destView :AddProductViewController = self.storyboard?.instantiateViewControllerWithIdentifier("AddProductViewController") as! AddProductViewController destView.product = selectedProduct self.presentViewController(destView, animated: true, completion: nil) } } // Override to support editing the table view. func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete && tableView == self.productTblView && products.count > 0 { // rollback data let selectedProduct = products[indexPath.row] as ProductD appDel.deleteObjectAction(selectedProduct) //products.removeAtIndex(indexPath.row) appDel.saveContextAction() tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) productTblView.reloadData() } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if(segue.identifier == "addProduct") { let destViewController:AddProductViewController = segue.destinationViewController as! AddProductViewController destViewController.order = self.order } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.view.endEditing(true) } func createOrderImage() -> UIImage!{ //Create the UIImage UIGraphicsBeginImageContext(productTblView.frame.size) productTblView.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } // Variable initialization let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate lazy var contacts:[Contact] = { return personDao.getContacts() }() var filterdContacts = [Contact]() var customer: Contact? = nil lazy var order: OrderD? = { [unowned self] in var newOrder = self.appDel.newOrderAction() newOrder.orderDate = NSDate() newOrder.setValue("New", forKey:"status") return newOrder }() var products: [ProductD] { get{ return self.order!.products.sortedArrayUsingDescriptors([NSSortDescriptor(key: "productName", ascending: true, selector: "localizedStandardCompare:")]) as! [ProductD] } } var amountSum: NSDecimalNumber { get{ //return $.reduce(products, initial: 0.0) { (total, element) in var total: NSDecimalNumber = NSDecimalNumber.zero() for product in products { if let amt = product.price{ total = total.decimalNumberByAdding(amt) } } return total } } var roundUp = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundUp, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true) }
mit
cc5b9199671584f75f06f19e0e20404a
40.904959
189
0.642935
5.334561
false
false
false
false
a736220388/FinestFood
FinestFood/FinestFood/classes/Category/CGListViewController/controllers/CGListViewController.swift
1
3554
// // CGListViewController.swift // FinestFood // // Created by qianfeng on 16/8/26. // Copyright © 2016年 qianfeng. All rights reserved. // import UIKit class CGListViewController: BaseViewController { var typeValue:Int? var dataArray:Array<FSFoodMoreListModel>? private var tbView:UITableView? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. createTableView() } func createTableView(){ tbView = UITableView() view.addSubview(tbView!) tbView?.snp_makeConstraints(closure: { [weak self] (make) in make.left.right.bottom.top.equalTo(self!.view) }) tbView?.delegate = self tbView?.dataSource = self } override func downloadData() { let downloader = MyDownloader() let url = String(format: FSFoodMoreListUrl,typeValue!,limit,offset) downloader.downloadWithUrlString(url) downloader.didFailWithError = { error in print(error) } downloader.didFinishWithData = { [weak self] data in let jsonData = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) if jsonData.isKindOfClass(NSDictionary.self){ let dataDict = jsonData["data"] as! NSDictionary let itemsArray = dataDict["items"] as! Array<Dictionary<String,AnyObject>> var dataArr = Array<FSFoodMoreListModel>() for dict in itemsArray{ let model = FSFoodMoreListModel() model.setValuesForKeysWithDictionary(dict) dataArr.append(model) } self!.dataArray = dataArr dispatch_async(dispatch_get_main_queue(), { self!.tbView?.reloadData() }) } } } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension CGListViewController:UITableViewDelegate,UITableViewDataSource{ func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if dataArray == nil { return 0 } return (dataArray?.count)! } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let model = dataArray![indexPath.row] let cell = FoodMoreListCell.createFoodMoreListCellFor(tableView, atIndexPath: indexPath, withModel: model) cell.selectionStyle = .None return cell } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 200 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let model = dataArray![indexPath.row] let detailCtrl = FoodDetailViewController() detailCtrl.id = Int(model.id!) self.navigationController?.pushViewController(detailCtrl, animated: true) } }
mit
8300deb00eca1725ba202ae39aaec346
34.51
114
0.632498
5.276374
false
false
false
false
longsirhero/DinDinShop
DinDinShopDemo/DinDinShopDemo/首页/Views/WCProductDetailAddtionCell.swift
1
2856
// // WCProductDetailAddtionCell.swift // DinDinShopDemo // // Created by longsirHERO on 2017/9/6. // Copyright © 2017年 WingChingYip(https://longsirhero.github.io) All rights reserved. // import UIKit class WCProductDetailAddtionCell: UICollectionViewCell { let imageV:UIImageView = UIImageView() let titleLab:UILabel = UILabel() let priceLab:UILabel = UILabel() let logoImagV:UIImageView = UIImageView() let addressLab:UILabel = UILabel() var model:WCSeasDiscountModel = WCSeasDiscountModel() { didSet { imageV.kf.setImage(with: URL(string: model.logPath!)) titleLab.text = model.goodsName == nil ? model.name : model.goodsName priceLab.text = "¥" + model.primalPrice! addressLab.text = model.originPlace } } override init(frame: CGRect) { super.init(frame: frame) titleLab.font = UIFont.systemFont(ofSize: 15.0) titleLab.numberOfLines = 0 priceLab.textColor = UIColor.flatRed() priceLab.font = UIFont.systemFont(ofSize: 16.0) logoImagV.image = UIImage.init(named: "class8_03") self.contentView.addSubview(imageV) self.contentView.addSubview(titleLab) self.contentView.addSubview(priceLab) self.contentView.addSubview(logoImagV) self.contentView.addSubview(addressLab) imageV.snp.makeConstraints { (make) in make.top.left.equalToSuperview().offset(5) make.bottom.equalToSuperview().offset(-5) make.width.equalTo(100) } titleLab.snp.makeConstraints { (make) in make.left.equalTo(imageV.snp.right).offset(5) make.top.equalTo(imageV.snp.top).offset(0) make.right.equalToSuperview().offset(-5) make.height.equalTo(40) } logoImagV.snp.makeConstraints { (make) in make.left.equalTo(titleLab.snp.left).offset(0) make.width.height.equalTo(20) make.bottom.equalTo(imageV.snp.bottom).offset(0) } addressLab.snp.makeConstraints { (make) in make.left.equalTo(logoImagV.snp.right).offset(10) make.bottom.equalTo(imageV.snp.bottom).offset(0) make.right.equalToSuperview().offset(-5) make.height.equalTo(20) } priceLab.snp.makeConstraints { (make) in make.bottom.equalTo(logoImagV.snp.top).offset(-5) make.left.equalTo(titleLab.snp.left).offset(0) make.right.equalToSuperview().offset(-5) make.height.equalTo(20) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
83c6e2e159ec2f21a8224ab21e4c91a0
30.688889
86
0.601683
4.157434
false
false
false
false
jopamer/swift
tools/swift-swiftsyntax-test/ClassifiedSyntaxTreePrinter.swift
1
2849
import SwiftSyntax import Foundation class ClassifiedSyntaxTreePrinter: SyntaxVisitor { private let classifications: [TokenSyntax: SyntaxClassification] private var currentTag = "" private var skipNextNewline = false private var result = "" // MARK: Public interface init(classifications: [TokenSyntax: SyntaxClassification]) { self.classifications = classifications } func print(tree: SourceFileSyntax) -> String { result = "" visit(tree) // Emit the last closing tag recordCurrentTag("") return result } // MARK: Implementation /// Closes the current tag if it is different from the previous one and opens /// a tag with the specified ID. private func recordCurrentTag(_ tag: String) { if currentTag != tag { if !currentTag.isEmpty { result += "</" + currentTag + ">" } if !tag.isEmpty { result += "<" + tag + ">" } } currentTag = tag } private func visit(_ piece: TriviaPiece) { let tag: String switch piece { case .spaces, .tabs, .verticalTabs, .formfeeds: tag = "" case .newlines, .carriageReturns, .carriageReturnLineFeeds: if skipNextNewline { skipNextNewline = false return } tag = "" case .backticks: tag = "" case .lineComment(let text): // Don't print CHECK lines if text.hasPrefix("// CHECK") { skipNextNewline = true return } tag = "comment-line" case .blockComment: tag = "comment-block" case .docLineComment: tag = "doc-comment-line" case .docBlockComment: tag = "doc-comment-block" case .garbageText: tag = "" } recordCurrentTag(tag) piece.write(to: &result) } private func visit(_ trivia: Trivia) { for piece in trivia { visit(piece) } } private func getTagForSyntaxClassification( _ classification: SyntaxClassification ) -> String { switch (classification) { case .none: return "" case .keyword: return "kw" case .identifier: return "" case .typeIdentifier: return "type" case .dollarIdentifier: return "dollar" case .integerLiteral: return "int" case .floatingLiteral: return "float" case .stringLiteral: return "str" case .stringInterpolationAnchor: return "anchor" case .poundDirectiveKeyword: return "#kw" case .buildConfigId: return "#id" case .attribute: return "attr-builtin" case .objectLiteral: return "object-literal" case .editorPlaceholder: return "placeholder" } } override func visit(_ node: TokenSyntax) { visit(node.leadingTrivia) let classification = classifications[node] ?? SyntaxClassification.none recordCurrentTag(getTagForSyntaxClassification(classification)) result += node.text visit(node.trailingTrivia) } }
apache-2.0
21181bec829cbec8cbf35262e11b1006
25.626168
79
0.648649
4.349618
false
false
false
false
keyOfVv/Cusp
CuspDemo/Classes/Main/DemoMainTableViewController.swift
1
2215
// // DemoMainTableViewController.swift // Cusp // // Created by Ke Yang on 23/12/2016. // Copyright © 2016 com.keyofvv. All rights reserved. // import UIKit import Cusp /** * 1. Scan * 2. Connect * 3. GATT */ class DemoMainTableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() title = "Cusp Demos" NotificationCenter.default.addObserver(self, selector: #selector(self.didReceiveNotification(notification:)), name: NSNotification.Name.CuspStateDidChange, object: nil) // CuspCentral.default.scanForUUIDString(nil, completion: { (advertisements) in // // }) { (error) in // // error raised while scanning // } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: UITableViewCell if let c = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier") { cell = c } else { cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "reuseIdentifier") } switch indexPath.row { case 0: cell.textLabel?.text = "Scan" case 1: cell.textLabel?.text = "Scan->Connect->Subscribe->Unsubscribe->Disconnect" case 2: cell.textLabel?.text = "Scan->Connect->ReadRSSI" default: break } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { switch indexPath.row { case 0: let scanDemoVC = ScanTableViewController(style: UITableViewStyle.plain) navigationController?.pushViewController(scanDemoVC, animated: true) case 1: let connTBVC = ConnectTableViewController() navigationController?.pushViewController(connTBVC, animated: true) case 2: let scrTBVC = SCRTableViewController() navigationController?.pushViewController(scrTBVC, animated: true) default: break } } } // MARK: - extension DemoMainTableViewController { func didReceiveNotification(notification: Notification) { dog(notification) } }
mit
8dc68f1ed228748a1c88c11bc14871d2
26
170
0.726739
3.925532
false
false
false
false
HarukaMa/iina
iina/VideoTime.swift
1
2287
// // SimpleTime.swift // iina // // Created by lhc on 25/7/16. // Copyright © 2016年 lhc. All rights reserved. // import Foundation class VideoTime { static let infinite = VideoTime(999, 0, 0) static let zero = VideoTime(0) var second: Double var h: Int { get { return (Int(second) / 3600) } } var m: Int { get { return (Int(second) % 3600) / 60 } } var s: Int { get { return (Int(second) % 3600) % 60 } } var stringRepresentation: String { get { if self == Constants.Time.infinite { return "End" } let ms = (m < 10 ? "0\(m)" : "\(m)") let ss = (s < 10 ? "0\(s)" : "\(s)") let hs = (h > 0 ? "\(h):" : "") return "\(hs)\(ms):\(ss)" } } convenience init?(_ format: String) { let split = format.characters.split(separator: ":").map { (seq) -> Int? in return Int(String(seq)) } if !(split.contains {$0 == nil}) { // if no nil in array if split.count == 2 { self.init(0, split[0]!, split[1]!) } else if split.count == 3 { self.init(split[0]!, split[1]!, split[2]!) } else { return nil } } else { return nil } } init(_ second: Double) { self.second = second } init(_ hour: Int, _ minute: Int, _ second: Int) { self.second = Double(hour * 3600 + minute * 60 + second) } /** whether self in [min, max) */ func between(_ min: VideoTime, _ max: VideoTime) -> Bool { return self >= min && self < max } } extension VideoTime: Comparable { } func <(lhs: VideoTime, rhs: VideoTime) -> Bool { // ignore additional digits and compare the time in milliseconds return Int(lhs.second * 1000) < Int(rhs.second * 1000) } func ==(lhs: VideoTime, rhs: VideoTime) -> Bool { // ignore additional digits and compare the time in milliseconds return Int(lhs.second * 1000) == Int(rhs.second * 1000) } func *(lhs: VideoTime, rhs: Double) -> VideoTime { return VideoTime(lhs.second * rhs) } func /(lhs: VideoTime?, rhs: VideoTime?) -> Double? { if let lhs = lhs, let rhs = rhs { return lhs.second / rhs.second } else { return nil } } func -(lhs: VideoTime, rhs: VideoTime) -> VideoTime { return VideoTime(lhs.second - rhs.second) }
gpl-3.0
01a857cf3e292c4df1b9270b1667840f
20.148148
78
0.558231
3.403875
false
false
false
false
devxoul/Drrrible
Drrrible/Sources/ViewControllers/VersionViewController.swift
1
3964
// // VersionViewController.swift // Drrrible // // Created by Suyeol Jeon on 19/04/2017. // Copyright © 2017 Suyeol Jeon. All rights reserved. // import UIKit import ReactorKit import ReusableKit final class VersionViewController: BaseViewController, View { // MARK: Constants fileprivate struct Reusable { static let cell = ReusableCell<VersionCell>() } fileprivate struct Metric { static let iconViewTop = 35.f static let iconViewSize = 100.f static let iconViewBottom = 0.f } // MARK: UI fileprivate let iconView = UIImageView(image: #imageLiteral(resourceName: "Icon512")).then { $0.layer.borderColor = UIColor.db_border.cgColor $0.layer.borderWidth = 1 $0.layer.cornerRadius = Metric.iconViewSize * 13.5 / 60 $0.layer.minificationFilter = CALayerContentsFilter.trilinear $0.clipsToBounds = true } fileprivate let tableView = UITableView(frame: .zero, style: .grouped).then { $0.register(Reusable.cell) } // MARK: Initializing init(reactor: VersionViewReactor) { defer { self.reactor = reactor } super.init() self.title = "version".localized } required convenience init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: View Life Cycle override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .db_background self.tableView.dataSource = self self.tableView.contentInset.top = Metric.iconViewTop + Metric.iconViewSize + Metric.iconViewBottom self.tableView.addSubview(self.iconView) self.view.addSubview(self.tableView) } override func setupConstraints() { self.tableView.snp.makeConstraints { make in make.edges.equalToSuperview() } self.iconView.snp.makeConstraints { make in make.top.equalTo(Metric.iconViewTop - self.tableView.contentInset.top) make.centerX.equalToSuperview() make.size.equalTo(Metric.iconViewSize) } } // MARK: Binding func bind(reactor: VersionViewReactor) { // Action self.rx.viewWillAppear .map { _ in Reactor.Action.checkForUpdates } .bind(to: reactor.action) .disposed(by: self.disposeBag) // State reactor.state .subscribe(onNext: { [weak self] _ in self?.tableView.reloadData() }) .disposed(by: self.disposeBag) } } extension VersionViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeue(Reusable.cell, for: indexPath) if indexPath.row == 0 { cell.textLabel?.text = "current_version".localized cell.detailTextLabel?.text = self.reactor?.currentState.currentVersion cell.isLoading = false } else { cell.textLabel?.text = "latest_version".localized cell.detailTextLabel?.text = self.reactor?.currentState.latestVersion cell.isLoading = self.reactor?.currentState.isLoading ?? false } return cell } } private final class VersionCell: UITableViewCell { fileprivate let activityIndicatorView = UIActivityIndicatorView(style: .gray) override var accessoryView: UIView? { didSet { if self.accessoryView === self.activityIndicatorView { self.activityIndicatorView.startAnimating() } else { self.activityIndicatorView.stopAnimating() } } } var isLoading: Bool { get { return self.activityIndicatorView.isAnimating } set { self.accessoryView = newValue ? self.activityIndicatorView : nil } } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .value1, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
bf8a4dcc2665ee9345b98868c035da1c
25.959184
102
0.698965
4.38385
false
false
false
false
hachinobu/CleanQiitaClient
Utility/AccessTokenStorage.swift
1
707
// // AccessTokenStorage.swift // CleanQiitaClient // // Created by Takahiro Nishinobu on 2016/09/23. // Copyright © 2016年 hachinobu. All rights reserved. // import Foundation public struct AccessTokenStorage { private static let key: String = "accessToken" public static func fetch() -> String? { let dummy = "hoge" if AuthInfo.clientId == dummy && AuthInfo.clientSecret == dummy { return "" } return UserDefaults.standard.string(forKey: key) } public static func save(accesToken: String) -> Bool { UserDefaults.standard.set(accesToken, forKey: key) return UserDefaults.standard.synchronize() } }
mit
fb565cc4dc8f096689b03e68d3b092ee
24.142857
73
0.639205
4.215569
false
false
false
false
Alexiuce/Tip-for-day
SingleDataFlowDemo/SingleDataFlowDemo/TableViewController.swift
1
4895
// // TableViewController.swift // SingleDataFlowDemo // // Created by alexiuce  on 2017/8/2. // Copyright © 2017年 alexiuce . All rights reserved. // import UIKit class TableViewController: UITableViewController { enum Section : Int { case input = 0, todos, max } var todos : [String] = [] override func viewDidLoad() { super.viewDidLoad() ToDoStore.shareStore.getToDoItems { (data) in self.todos += data self.title = "TODO - \(self.todos.count)" self.tableView.reloadData() } // 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() } @IBAction func addButtonClicked(_ sender: UIBarButtonItem) { let inputPath = IndexPath(row: 0, section: Section.input.rawValue) guard let inputCell = tableView.cellForRow(at: inputPath) as? TableViewInputCell, let text = inputCell.textFiled.text else { return } todos.insert(text, at: 0) inputCell.textFiled.text = "" sender.isEnabled = false title = "TODO - \(todos.count)" let insertPath = IndexPath(row: 0, section: Section.todos.rawValue) tableView.insertRows(at: [insertPath], with: .top) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return Section.max.rawValue } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows guard let section = Section.init(rawValue: section) else { fatalError() } switch section { case .input: return 1 case .todos : return todos.count case .max : fatalError() } return 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let section = Section.init(rawValue: indexPath.section) else { fatalError() } switch section { case .input: // reture input cell let cell = tableView.dequeueReusableCell(withIdentifier: "InputReused", for: indexPath) as! TableViewInputCell cell.delegate = self return cell case .todos: // normal cell let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) cell.textLabel?.text = todos[indexPath.row] return cell default: fatalError() } } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. if indexPath.section == Section.input.rawValue { return false } return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source todos.remove(at: indexPath.row) tableView.deleteRows(at: [indexPath], with: .bottom) title = "TODO - \(todos.count)" } } /* // Override to support rearranging the table view. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> 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 prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } extension TableViewController : TableViewInputCellDelegate{ func inputChanged(cell: TableViewInputCell, text: String) { let itemLengthEngouth = text.characters.count > 3 navigationItem.rightBarButtonItem?.isEnabled = itemLengthEngouth } }
mit
e5e95f42a6e8f6ee3d6827971fdd3e50
32.265306
136
0.638037
5.062112
false
false
false
false
stripe/stripe-ios
StripeUICore/StripeUICore/Source/Helpers/StackViewWithSeparator.swift
1
7563
// // StackViewWithSeparator.swift // StripeUICore // // Created by Cameron Sabol on 9/22/21. // Copyright © 2021 Stripe, Inc. All rights reserved. // import UIKit /// For internal SDK use only @objc(STP_Internal_StackViewWithSeparator) @_spi(STP) public class StackViewWithSeparator: UIStackView { public static let borderlessInset: CGFloat = 10 public enum SeparatoryStyle { case full case partial } public var separatorStyle: SeparatoryStyle = .full { didSet { for view in arrangedSubviews { if let substackView = view as? StackViewWithSeparator { substackView.separatorStyle = separatorStyle } } } } public var separatorColor: UIColor = .clear { didSet { separatorLayer.strokeColor = separatorColor.cgColor backgroundView.layer.borderColor = separatorColor.cgColor } } /// Commonly referred to as `borderWidth` public override var spacing: CGFloat { didSet { backgroundView.layer.borderWidth = spacing separatorLayer.lineWidth = spacing layoutMargins = UIEdgeInsets( top: spacing, left: spacing, bottom: spacing, right: spacing) } } public var drawBorder: Bool = false { didSet { isLayoutMarginsRelativeArrangement = drawBorder if drawBorder { addSubview(backgroundView) sendSubviewToBack(backgroundView) } else { backgroundView.removeFromSuperview() } } } public var borderCornerRadius: CGFloat { get { return backgroundView.layer.cornerRadius } set { backgroundView.layer.cornerRadius = newValue } } public var borderColor: UIColor = .systemGray3 { didSet { backgroundView.layer.borderColor = borderColor.cgColor } } @objc override public var isUserInteractionEnabled: Bool { didSet { if isUserInteractionEnabled { backgroundView.backgroundColor = customBackgroundColor } else { backgroundView.backgroundColor = customBackgroundDisabledColor } } } public var hideShadow: Bool = false { didSet { if hideShadow { backgroundView.layer.shadowOffset = .zero backgroundView.layer.shadowColor = UIColor.clear.cgColor backgroundView.layer.shadowOpacity = 0 backgroundView.layer.shadowRadius = 0 backgroundView.layer.shadowOpacity = 0 } else { configureDefaultShadow() } } } public var customBackgroundColor: UIColor? = InputFormColors.backgroundColor { didSet { if isUserInteractionEnabled { backgroundView.backgroundColor = customBackgroundColor } } } public var customBackgroundDisabledColor: UIColor? = InputFormColors.disabledBackgroundColor { didSet { if isUserInteractionEnabled { backgroundView.backgroundColor = customBackgroundColor } } } private let separatorLayer = CAShapeLayer() let backgroundView: UIView = { let view = UIView() view.backgroundColor = InputFormColors.backgroundColor view.autoresizingMask = [.flexibleWidth, .flexibleHeight] // copied from configureDefaultShadow to avoid recursion on init view.layer.shadowOffset = CGSize(width: 0, height: 2) view.layer.shadowColor = UIColor.black.cgColor view.layer.shadowOpacity = 0.05 view.layer.shadowRadius = 4 return view }() func configureDefaultShadow() { backgroundView.layer.shadowOffset = CGSize(width: 0, height: 2) backgroundView.layer.shadowColor = UIColor.black.cgColor backgroundView.layer.shadowOpacity = 0.05 backgroundView.layer.shadowRadius = 4 } override public func layoutSubviews() { if backgroundView.superview == self { sendSubviewToBack(backgroundView) } super.layoutSubviews() if separatorLayer.superlayer == nil { layer.addSublayer(separatorLayer) } separatorLayer.strokeColor = separatorColor.cgColor let path = UIBezierPath() path.lineWidth = spacing if spacing > 0 { // inter-view separators let nonHiddenArrangedSubviews = arrangedSubviews.filter({ !$0.isHidden }) let isRTL = traitCollection.layoutDirection == .rightToLeft for view in nonHiddenArrangedSubviews { if axis == .vertical { switch separatorStyle { case .full: if view == nonHiddenArrangedSubviews.last { continue } path.move(to: CGPoint(x: view.frame.minX, y: view.frame.maxY + 0.5 * spacing)) path.addLine( to: CGPoint(x: view.frame.maxX, y: view.frame.maxY + 0.5 * spacing)) case .partial: // no-op in partial break } } else { // .horizontal switch separatorStyle { case .full: if (!isRTL && view == nonHiddenArrangedSubviews.first) || (isRTL && view == nonHiddenArrangedSubviews.last) { continue } path.move(to: CGPoint(x: view.frame.minX - 0.5 * spacing, y: view.frame.minY)) path.addLine( to: CGPoint(x: view.frame.minX - 0.5 * spacing, y: view.frame.maxY)) case .partial: assert(!drawBorder, "Can't combine partial separator style in a horizontal stack with draw border") if 2 * StackViewWithSeparator.borderlessInset * spacing >= view.frame.width { continue } // These values are chosen to optimize for use in STPCardFormView with borderless style path.move(to: CGPoint(x: view.frame.minX + StackViewWithSeparator.borderlessInset * spacing, y: view.frame.maxY)) path.addLine( to: CGPoint(x: view.frame.maxX - StackViewWithSeparator.borderlessInset * spacing, y: view.frame.maxY)) } } } } separatorLayer.path = path.cgPath backgroundView.layer.shadowPath = hideShadow ? nil : UIBezierPath(roundedRect: bounds, cornerRadius: borderCornerRadius).cgPath } public override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) // CGColor's must be manually updated when the trait collection changes backgroundView.layer.borderColor = borderColor.cgColor separatorLayer.strokeColor = separatorColor.cgColor } }
mit
ec44902bdfd6ec406a177d9c8024a750
34.336449
138
0.560169
5.884825
false
false
false
false
DuckDeck/ViewChaos
ViewChaosDemo/ViewChaosDemo/TableViewController.swift
1
4699
// // TableViewController.swift // ViewChaosDemo // // Created by Stan Hu on 2018/11/19. // Copyright © 2018 Qfq. All rights reserved. // import UIKit class TableViewController: UIViewController { let tb = UITableView() var arrSource = [String]() let word = "摄影小哥似乎看穿了我的心思,却不知道为什么用着佳能1D的大佬,极力向我推荐索尼,莫非是最近看到了姨夫的微笑?现在看来价格差距不算大的横向型号有大法A6000L,佳能M6和富士XA5。于是我在贴吧论坛开始转悠,基本的论调是大法性能优秀,佳能镜头便宜,富士直出色彩美丽。看完一圈以后,我又看了看小哥拍的照片,告诉自己,专业的人考虑专业的事情,我这样的小白不需要想太多,闭着眼睛买就对了(双11来了时间不多了!),于是赶上双11狗东不送赠品降价(我也用不着赠品,SD卡屯了好几张,相机包淘宝50买个mini的就好),就像快门声一样咔嚓一下,手就没了,不,是草就没了" override func viewDidLoad() { super.viewDidLoad() view.tag = 111 tb.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height) tb.dataSource = self tb.delegate = self tb.register(UITableViewCell.self, forCellReuseIdentifier: "cell") for _ in 0..<20{ var start = Int(arc4random()) % word.count var end = Int(arc4random()) % word.count if start > end{ (start,end) = (end,start) } else if start == end{ start = 0 } arrSource.append(word.substring(from: start, to: end)) } tb.tableFooterView = UIView() tb.separatorStyle = .singleLine view.addSubview(tb) // Do any additional setup after loading the view. } } extension TableViewController:UITableViewDataSource,UITableViewDelegate{ func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return arrSource.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = arrSource[indexPath.row] cell.textLabel?.numberOfLines = 0 return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let cell = tableView.cellForRow(at: indexPath) print(cell!.textLabel!.frame) if let fm = view.window?.convert(cell!.textLabel!.frame, from: cell!){ print(fm) } } } extension String{ func substring(from: Int?, to: Int?) -> String { if let start = from { guard start < self.count else { return "" } } if let end = to { guard end >= 0 else { return "" } } if let start = from, let end = to { guard end - start >= 0 else { return "" } } let startIndex: String.Index if let start = from, start >= 0 { startIndex = self.index(self.startIndex, offsetBy: start) } else { startIndex = self.startIndex } let endIndex: String.Index if let end = to, end >= 0, end < self.count { endIndex = self.index(self.startIndex, offsetBy: end + 1) } else { endIndex = self.endIndex } return String(self[startIndex ..< endIndex]) } func substring(from: Int) -> String { return self.substring(from: from, to: nil) } func substring(to: Int) -> String { return self.substring(from: nil, to: to) } func substring(from: Int?, length: Int) -> String { guard length > 0 else { return "" } let end: Int if let start = from, start > 0 { end = start + length - 1 } else { end = length - 1 } return self.substring(from: from, to: end) } func substring(length: Int, to: Int?) -> String { guard let end = to, end > 0, length > 0 else { return "" } let start: Int if let end = to, end - length > 0 { start = end - length + 1 } else { start = 0 } return self.substring(from: start, to: to) } }
mit
1ff1d824d5663210d23066868b27c6ea
28.507042
296
0.550358
3.734403
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/SwiftApp/UIScrollView/collectionview/RayHeaderChangeCollectionViewController.swift
1
3375
// // RayHeaderChangeCollectionViewController.swift // SwiftApp // // Created by wuyp on 2019/5/12. // Copyright © 2019 raymond. All rights reserved. // import UIKit class RayHeaderChangeCollectionViewController: RayBaseViewController { lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 20 layout.minimumInteritemSpacing = 0 layout.sectionInset = UIEdgeInsets(top: 10, left: 15, bottom: 10, right: 15) let list = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout) list.frame = self.view.bounds list.layer.borderColor = UIColor.red.cgColor list.layer.borderWidth = 0.5 list.dataSource = self list.delegate = self list.backgroundColor = .clear list.register(RayBaseCollectionViewCell.self, forCellWithReuseIdentifier: "cell") list.register(RayCollectionHeaderReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header") return list }() override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = .white // self.view.addSubview(collectionView) } } extension RayHeaderChangeCollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func numberOfSections(in collectionView: UICollectionView) -> Int { return 2 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { switch section { case 0: return 2 case 1: return 5 default: return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! RayBaseCollectionViewCell cell.setTitleAndSubTitle(title: "\(indexPath.item)", subTitle: "section\(indexPath.section)") return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { if kind == UICollectionView.elementKindSectionFooter { return UICollectionReusableView() } let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! RayCollectionHeaderReusableView header.titleLbl.text = "Section Header: \(indexPath.section)" header.backgroundColor = UIColor.purple return header } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSize(width: kScreenWidth, height: 250) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: kScreenWidth, height: 50) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { } }
apache-2.0
bcfce901edf270986dc83fe4bed77738
38.694118
170
0.705098
5.867826
false
false
false
false
VernonVan/SmartClass
SmartClass/Resource/View/PPT/PPTViewController.swift
1
4198
// // PPTViewController.swift // SmartClass // // Created by Vernon on 16/4/23. // Copyright © 2016年 Vernon. All rights reserved. // import UIKit //import ShowFramework protocol CanvasPopoverDelegate { func changeCanvasSize(_ size: Double) func changeCanvasColor(_ color: UIColor) func changeCanvasAlpha(_ alpha: Float) } class PPTViewController: UIViewController, UIPopoverPresentationControllerDelegate, CanvasPopoverDelegate { @IBOutlet weak var toolbar: UIToolbar! @IBOutlet weak var toolbarBottomConstraint: NSLayoutConstraint! var pptURL: URL? var isCanvas = false var isShowToolbar = false { didSet { if isShowToolbar == false { UIView.animate(withDuration: 0.2, animations: { self.toolbarBottomConstraint.constant -= 44 }) } else { UIView.animate(withDuration: 0.2, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 6, options: UIViewAnimationOptions(), animations: { self.toolbarBottomConstraint.constant += 44 }, completion: nil) } } } lazy var pptView: PPTView = { let height = self.view.frame.size.height let width = height * (4/3) let pptView = PPTView(frame: CGRect(x: (self.view.frame.size.width - width) / 2, y: 0.0, width: width, height: height), pptURL: self.pptURL!) pptView.scalesPageToFit = true return pptView }() // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showToolbarOrNot)) isShowToolbar = true view.addGestureRecognizer(tapGesture) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) view.addSubview(pptView) view.addSubview(toolbar) } override var shouldAutorotate : Bool { return true } override var preferredInterfaceOrientationForPresentation : UIInterfaceOrientation { return .landscapeRight } override var supportedInterfaceOrientations : UIInterfaceOrientationMask { return [.landscapeRight, .landscapeLeft] } // MARK: - Actions @IBAction func closeAction(_ sender: UIBarButtonItem) { dismiss(animated: true, completion: nil) } @IBAction func canvasAction(_ sender: UIBarButtonItem) { isCanvas = !isCanvas if isCanvas { toolbar.items![3].tintColor = ThemeGreenColor pptView.canvasState() performSegue(withIdentifier: "canvasPopover", sender: sender) } else { toolbar.items![3].tintColor = UIColor.white pptView.playState() } } func showToolbarOrNot() { isShowToolbar = !isShowToolbar } // MARK: - Segue override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "canvasPopover" { let popoverViewController = segue.destination as! CanvasPopoverViewController popoverViewController.modalPresentationStyle = .popover popoverViewController.popoverPresentationController!.delegate = self popoverViewController.delegate = self popoverViewController.color = pptView.getCanvasColor() popoverViewController.size = pptView.getCanvasSize() popoverViewController.alpha = pptView.getCanvasAlpha() } } // MARK: - UIPopoverPresentationControllerDelegate func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } // MARK: - CanvasPopoverDelegate func changeCanvasSize(_ size: Double) { pptView.setCanvasSize(size) } func changeCanvasColor(_ color: UIColor) { pptView.setCanvasColor(color) } func changeCanvasAlpha(_ alpha: Float) { pptView.setCanvasAlpha(alpha) } }
mit
945d3400751587577f95cf82915356e7
27.154362
163
0.625507
5.179012
false
false
false
false
Norod/Filterpedia
Filterpedia/customFilters/ColorDirectedBlur.swift
1
9507
// // ColorDirectedBlur.swift // Filterpedia // // Created by Simon Gladman on 29/12/2015. // Copyright © 2015 Simon Gladman. All rights reserved. // // 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/> import CoreImage /// **HomogeneousColorBlur** /// /// _A filter that applies a box filter with circular kernel to similar colors based /// on distance in a three dimensional RGB configuration space_ /// /// - Authors: Simon Gladman /// - Date: May 2016 class HomogeneousColorBlur: CIFilter { var inputImage: CIImage? var inputColorThreshold: CGFloat = 0.2 var inputRadius: CGFloat = 10 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Homogeneous Color Blur", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputColorThreshold": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.2, kCIAttributeDisplayName: "Color Threshold", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Radius", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 40, kCIAttributeType: kCIAttributeTypeScalar], ] } let kernel = CIKernel(string: "kernel vec4 colorDirectedBlurKernel(sampler image, float radius, float threshold)" + "{" + " int r = int(radius);" + " float n = 0.0;" + " vec2 d = destCoord();" + " vec3 thisPixel = sample(image, samplerCoord(image)).rgb;" + " vec3 accumulator = vec3(0.0, 0.0, 0.0);" + " for (int x = -r; x <= r; x++) " + " { " + " for (int y = -r; y <= r; y++) " + " { " + " vec3 offsetPixel = sample(image, samplerTransform(image, d + vec2(x ,y))).rgb; \n" + " float distanceMultiplier = step(length(vec2(x,y)), radius); \n" + " float colorMultiplier = step(distance(offsetPixel, thisPixel), threshold); \n" + " accumulator += offsetPixel * distanceMultiplier * colorMultiplier; \n" + " n += distanceMultiplier * colorMultiplier; \n" + " }" + " }" + " return vec4(accumulator / n, 1.0); " + "}") override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = kernel else { return nil } let arguments = [inputImage, inputRadius, inputColorThreshold * sqrt(3.0)] as [Any] return kernel.apply( withExtent: inputImage.extent, roiCallback: { (index, rect) in return rect }, arguments: arguments) } } /// **ColorDirectedBlur** /// /// _A filter that applies a box blur based on a surrounding quadrant of the nearest color._ /// /// Uses a similar approach to Kuwahara Filter - creates averages of squares of pixels /// in the north east, north west, south east and south west of the current pixel and /// outputs the box blur of the quadrant with the closest color distance to the current /// pixel. A threshold parameter prevents any blurring if the distances are too great. /// /// The final effect blurs within areas of a similar color while keeeping edge detail. /// /// - Authors: Simon Gladman /// - Date: April 2016 class ColorDirectedBlur: CIFilter { var inputImage: CIImage? var inputThreshold: CGFloat = 0.5 var inputIterations: CGFloat = 4 var inputRadius: CGFloat = 10 override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Color Directed Blur", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputThreshold": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 0.5, kCIAttributeDisplayName: "Threshold", kCIAttributeMin: 0, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 1, kCIAttributeType: kCIAttributeTypeScalar], "inputIterations": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 4, kCIAttributeDisplayName: "Iterations", kCIAttributeMin: 1, kCIAttributeSliderMin: 1, kCIAttributeSliderMax: 10, kCIAttributeType: kCIAttributeTypeScalar], "inputRadius": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDefault: 10, kCIAttributeDisplayName: "Radius", kCIAttributeMin: 3, kCIAttributeSliderMin: 3, kCIAttributeSliderMax: 20, kCIAttributeType: kCIAttributeTypeScalar], ] } let kernel = CIKernel(string: "kernel vec4 colorDirectedBlurKernel(sampler image, float radius, float threshold)" + "{" + " int r = int(radius);" + " float n = 0.0;" + " vec2 d = destCoord();" + " vec3 thisPixel = sample(image, samplerCoord(image)).rgb;" + " vec3 nwAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 neAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 swAccumulator = vec3(0.0, 0.0, 0.0);" + " vec3 seAccumulator = vec3(0.0, 0.0, 0.0);" + " for (int x = 0; x <= r; x++) " + " { " + " for (int y = 0; y <= r; y++) " + " { " + " nwAccumulator += sample(image, samplerTransform(image, d + vec2(-x ,-y))).rgb; " + " neAccumulator += sample(image, samplerTransform(image, d + vec2(x ,-y))).rgb; " + " swAccumulator += sample(image, samplerTransform(image, d + vec2(-x ,y))).rgb; " + " seAccumulator += sample(image, samplerTransform(image, d + vec2(x ,y))).rgb; " + " n = n + 1.0; " + " } " + " } " + " nwAccumulator /= n;" + " neAccumulator /= n;" + " swAccumulator /= n;" + " seAccumulator /= n;" + " float nwDiff = distance(thisPixel, nwAccumulator); " + " float neDiff = distance(thisPixel, neAccumulator); " + " float swDiff = distance(thisPixel, swAccumulator); " + " float seDiff = distance(thisPixel, seAccumulator); " + " if (nwDiff >= threshold && neDiff >= threshold && swDiff >= threshold && seDiff >= threshold)" + " {return vec4(thisPixel, 1.0);}" + " if(nwDiff < neDiff && nwDiff < swDiff && nwDiff < seDiff) " + " { return vec4 (nwAccumulator, 1.0 ); }" + " if(neDiff < nwDiff && neDiff < swDiff && neDiff < seDiff) " + " { return vec4 (neAccumulator, 1.0 ); }" + " if(swDiff < nwDiff && swDiff < neDiff && swDiff < seDiff) " + " { return vec4 (swAccumulator, 1.0 ); }" + " if(seDiff < nwDiff && seDiff < neDiff && seDiff < swDiff) " + " { return vec4 (seAccumulator, 1.0 ); }" + " return vec4(thisPixel, 1.0); " + "}" ) override var outputImage: CIImage? { guard let inputImage = inputImage, let kernel = kernel else { return nil } let accumulator = CIImageAccumulator(extent: inputImage.extent, format: kCIFormatARGB8) accumulator?.setImage(inputImage) for _ in 0 ... Int(inputIterations) { let final = kernel.apply(withExtent: inputImage.extent, roiCallback: { (index, rect) in return rect }, arguments: [(accumulator?.image())!, inputRadius, 1 - inputThreshold]) accumulator?.setImage(final!) } return accumulator?.image() } }
gpl-3.0
54e7620421961a3329c2da041b847fe2
37.8
117
0.542184
4.574591
false
false
false
false
paulofaria/SwiftHTTPServer
Mustache/Compiling/Expression.swift
3
3519
// The MIT License // // Copyright (c) 2015 Gwendal Roué // // 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. /** The type for expressions that appear in tags: `name`, `user.name`, `uppercase(user.name)`, etc. */ enum Expression { // {{ . }} case ImplicitIterator // {{ identifier }} case Identifier(identifier: String) // {{ <expression>.identifier }} case Scoped(baseExpression: Wrapper, identifier: String) // {{ <expression>(<expression>) }} case Filter(filterExpression: Wrapper, argumentExpression: Wrapper, partialApplication: Bool) // Recursive enums need wrapper class class Wrapper { let expression: Expression init(_ expression: Expression) { self.expression = expression } } // Factory methods static func identifier(identifier: String) -> Expression { return .Identifier(identifier: identifier) } static func scoped(baseExpression baseExpression: Expression, identifier: String) -> Expression { return .Scoped(baseExpression: Wrapper(baseExpression), identifier: identifier) } static func filter(filterExpression filterExpression: Expression, argumentExpression: Expression, partialApplication: Bool) -> Expression { return .Filter(filterExpression: Wrapper(filterExpression), argumentExpression: Wrapper(argumentExpression), partialApplication: partialApplication) } } /** Expression conforms to Equatable so that the Compiler can check that section tags have matching openings and closings: {{# person }}...{{/ person }} is OK but {{# foo }}...{{/ bar }} is not. */ extension Expression: Equatable { } func ==(lhs: Expression, rhs: Expression) -> Bool { switch (lhs, rhs) { case (.ImplicitIterator, .ImplicitIterator): return true case (.Identifier(let lIdentifier), .Identifier(let rIdentifier)): return lIdentifier == rIdentifier case (.Scoped(let lBase, let lIdentifier), .Scoped(let rBase, let rIdentifier)): return lBase.expression == rBase.expression && lIdentifier == rIdentifier case (.Filter(let lFilter, let lArgument, let lPartialApplication), .Filter(let rFilter, let rArgument, let rPartialApplication)): return lFilter.expression == rFilter.expression && lArgument.expression == rArgument.expression && lPartialApplication == rPartialApplication default: return false } }
mit
c315c2e8e7098c5202e14d87e98366ee
37.23913
156
0.700398
4.906555
false
false
false
false
yuhaifei123/WeiBo_Swift
WeiBo_Swift/WeiBo_Swift/class/add(添加按钮)/view/Compose_ViewController.swift
1
2941
// // Compose_ViewController.swift // WeiBo_Swift // // Created by 虞海飞 on 2017/1/20. // Copyright © 2017年 虞海飞. All rights reserved. // 写微博view import UIKit /// 定义枚举 /// /// close -- 关闭了控制器 enum Season : String{ case close = "close" } //定义协议 protocol composeViewDelegate { func closeComposeViewController(season:String); } class Compose_ViewController: UIViewController { var delegate:composeViewDelegate? override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white; setUpView(); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func setUpView(){ addNavView(); } /// 添加 nav 方法 func addNavView(){ self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action:#selector(navItemClose)); self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: UIBarButtonItemStyle.plain, target: self, action: #selector(published)); //不能点击 self.navigationItem.rightBarButtonItem?.isEnabled = false; //添加微博 title topview.addSubview(label1); topview.addSubview(label2); self.navigationItem.titleView = topview; label1.snp.makeConstraints { (make) in make.top.equalTo(0); make.left.equalTo(0); make.right.equalTo(0); make.height.equalTo(14); } label2.snp.makeConstraints { (make) in make.top.equalTo(label1.snp.bottom).offset(2); make.height.equalTo(label1.snp.height); make.left.equalTo(label1.snp.left); make.width.equalTo(label1.snp.width); } } /// 点击关闭,监听 func navItemClose(){ self.tabBarController!.selectedIndex = 0; } /// 点击发表,监听 func published(){ } // MARK - 懒加载 public lazy var topview : UIView = { let view = UIView(); view.frame = CGRect(x: 0, y: 0, width: 100, height: 32); return view; }(); public lazy var label1 : UILabel = { let label1 : UILabel = UILabel(); label1.text = "发送微博" label1.font = UIFont.systemFont(ofSize: 15) label1.sizeToFit(); return label1; }(); public lazy var label2 : UILabel = { let label2 : UILabel = UILabel(); label2.text = "weiBoDemo" label2.font = UIFont.systemFont(ofSize: 13); label2.textColor = UIColor.darkGray; label2.sizeToFit(); return label2; }(); }
apache-2.0
c0752560342131895310188db1e65c5d
21.544
158
0.559972
4.5088
false
false
false
false
masters3d/xswift
exercises/crypto-square/Sources/CryptoSquareExample.swift
1
2709
import Foundation private extension String { func stripCharacters(_ charToRemove: String) -> String { var returnString = "" self.characters.forEach { if !charToRemove.contains(String($0)) { returnString.append($0) }} return returnString } var stripWhiteSpace: String { return stripCharacters(" ") } var stripPunctuations: String { return stripCharacters(",.!?") } var stripSymbols: String { return stripCharacters("#$%^&") } } struct Crypto { func segmentSorter(_ value: String, spacing: Int) -> [String] { var tempCounter = 0 var tempString: String = "" for each in value.characters { if tempCounter % spacing == 0 && tempCounter != 0 { tempString += " \(each)" } else { tempString += "\(each)" } tempCounter += 1 } return (tempString.components(separatedBy: " ") ) } func getSquareSize(_ text: String, floorNoCeling: Bool = false) -> Int { let tempDouble = Double(text.characters.count) let tempRoot = tempDouble.squareRoot() let tempCeil = ceil(tempRoot) let tempFloor = floor(tempRoot) if floorNoCeling { return Int(tempFloor) } else { return Int(tempCeil)} } func normalizer(_ textInput: String) -> String { return textInput.stripSymbols.stripPunctuations.stripWhiteSpace.lowercased() } var ciphertext: String { var plaintextSegmentsArray = [[Character]]() for each in plaintextSegments { plaintextSegmentsArray.append(Array(each.characters)) } var ciphertextReturn = "" for i in 0 ..< plaintextSegmentsArray[0].count { for e in 0 ..< plaintextSegmentsArray.count { if i < plaintextSegmentsArray[e].count { ciphertextReturn.append(plaintextSegmentsArray[e][i]) } }} return ciphertextReturn } var normalizeCiphertext: String { let sizeNormal: Int = (ciphertext.characters.count == self.size * self.size ) ? getSquareSize(self.ciphertext) : getSquareSize(self.ciphertext, floorNoCeling: true) return segmentSorter(ciphertext, spacing: sizeNormal).joined(separator: " ") } var plaintextSegments: [String] { return segmentSorter(self.normalizePlaintext, spacing: self.size) } var textValue: String = "" var normalizePlaintext: String = "" var size: Int = 0 init (_ value: String) { self.textValue = value self.normalizePlaintext = normalizer(value) self.size = getSquareSize(self.normalizePlaintext) } }
mit
9d849bd84c9edccc5f22c2a25beaff47
31.638554
172
0.610188
4.576014
false
false
false
false
SteveBarnegren/TweenKit
Example-iOS/Example/BezierExampleModel.swift
1
3407
// // BezierExampleModel.swift // Example // // Created by Steven Barnegren on 30/03/2017. // Copyright © 2017 Steve Barnegren. All rights reserved. // import Foundation import UIKit protocol BezierDemoModel { // The number of points that the curve should have var numberOfPoints: Int {get} // Straight-line connects that should be drawn between points (eg. to show handles) var connections: [(Int, Int)] {get} // The start position for each point func startPositionForPoint(atIndex index: Int) -> CGPoint // Make a bezier path from points func makePath(fromPoints points: [CGPoint]) -> UIBezierPath } struct QuadCurveDemoModel: BezierDemoModel { // 0. Start // 1. control // 2. end var numberOfPoints: Int { return 3 } func startPositionForPoint(atIndex index: Int) -> CGPoint { let sideMargin = CGFloat(70.0) switch index { case 0: return CGPoint(x: sideMargin, y: UIScreen.main.bounds.size.height/2) case 1: return CGPoint(x: UIScreen.main.bounds.size.width/2, y: UIScreen.main.bounds.size.height/2 - 100) case 2: return CGPoint(x: UIScreen.main.bounds.size.width - sideMargin, y: UIScreen.main.bounds.size.height/2) default: fatalError() } } func makePath(fromPoints points: [CGPoint]) -> UIBezierPath { let start = points[0] let control = points[1] let end = points[2] let path = UIBezierPath() path.move(to: start) path.addQuadCurve(to: end, controlPoint: control) return path } var connections: [(Int, Int)] { return [] } } struct CubicCurveDemoModel: BezierDemoModel { // 0. Start // 1. control1 // 2. control2 // 3. end var numberOfPoints: Int { return 4 } func startPositionForPoint(atIndex index: Int) -> CGPoint { let sideMargin = CGFloat(70.0) let controlOffsetY = CGFloat(100.0) let horizontalLength = UIScreen.main.bounds.size.width - (sideMargin*2) switch index { case 0: return CGPoint(x: sideMargin, y: UIScreen.main.bounds.size.height/2) case 1: return CGPoint(x: sideMargin + (horizontalLength/3), y: UIScreen.main.bounds.size.height/2 + controlOffsetY) case 2: return CGPoint(x: sideMargin + (horizontalLength/3*2), y: UIScreen.main.bounds.size.height/2 - controlOffsetY) case 3: return CGPoint(x: sideMargin + horizontalLength, y: UIScreen.main.bounds.size.height/2) default: fatalError() } } func makePath(fromPoints points: [CGPoint]) -> UIBezierPath { let start = points[0] let cp1 = points[1] let cp2 = points[2] let end = points[3] let path = UIBezierPath() path.move(to: start) path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2) return path } var connections: [(Int, Int)] { return [(0, 1), (3, 2)] } }
mit
2156938f9bf0f2d667abd530eecf1512
26.467742
87
0.552261
4.389175
false
false
false
false
nst/Brainfuck
Brainfuck/Brainfuck/main.swift
1
2294
// // main.swift // Brainfuck // // Created by Nicolas Seriot on 01.05.17. // Copyright © 2017 Nicolas Seriot. All rights reserved. // import Foundation let helloWorld = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>." func f1() { let b = try! Brainfuck(helloWorld) let result = try! b.run() print(result) } func f2() { let b = try! Brainfuck(helloWorld, userInput: "", dataSize: 10) let result = try! b.run() print(result) } func f3() { do { let b = try Brainfuck(helloWorld) while b.canRun() { if let s = try b.step() { print(s) } } } catch let e { print(e) } } func f4() { do { let b = try Brainfuck("++++++[>++++++<-]>.") // 6x6 == 0x24 == '$' while b.canRun() { print("------------------------------------------------------------------------------------") b.printStep() b.printInstructions() b.printData(upToIndex: 10) if let putByte = try b.step() { print(" PUT: " + String(format: "%02X", putByte)) // let s = Character(UnicodeScalar(putByte)) // print(s, separator: "", terminator: "") } } print("------------------------------------------------------------------------------------") b.printExecutionSummary() // print(b.outputString()) } catch let e { print(e) } } func f5() { let path = "/tmp/x.png" let bl = try! Brainloller(imagePath: path) let (coords, s1) = bl.brainfuck() print(s1) let outPath = "/Users/nst/Desktop/out.png" bl.magnifiedProgramWithTrace(programPath: path, outPath: outPath, coordinates: coords) let bf = try! Brainfuck(s1) let s2 = try! bf.run() print(coords) print(s2) } func f6() { let path = "/Users/nst/Desktop/braincopter1.png" let bl = try! Braincopter(imagePath: path) let (_, s1) = bl.brainfuck() print(s1) let bf = try! Brainfuck(s1) let s2 = try! bf.run() print(s2) } f1() f2() f3() f4() //f5() //f6()
mit
d4e6dc921f02a33b2a804be91093c6f0
22.397959
130
0.43044
3.484802
false
false
false
false
WestlakeAPC/game-off-2016
external/Fiber2D/Fiber2D/PhysicsWorld+Joints.swift
1
3338
// // PhysicsWorld+Joints.swift // Fiber2D // // Created by Andrey Volodin on 20.09.16. // Copyright © 2016 s1ddok. All rights reserved. // public extension PhysicsWorld { /** * Adds a joint to this physics world. * * This joint will be added to this physics world at next frame. * @attention If this joint is already added to another physics world, it will be removed from that world first and then add to this world. * @param joint A pointer to an existing PhysicsJoint object. */ public func add(joint: PhysicsJoint) { guard joint.world == nil else { fatalError("Can not add joint already added to other world!") } joint.world = self if let idx = delayRemoveJoints.index(where: { $0 === joint } ) { delayRemoveJoints.remove(at: idx) return } if delayAddJoints.index(where: { $0 === joint } ) == nil { delayAddJoints.append(joint) } } /** * Remove a joint from this physics world. * * If this world is not locked, the joint is removed immediately, otherwise at next frame. * If this joint is connected with a body, it will be removed from the body also. * @param joint A pointer to an existing PhysicsJoint object. */ public func remove(joint: PhysicsJoint) { guard joint.world === self else { print("Joint is not in this world") return } let idx = delayAddJoints.index { $0 === joint } let removedFromDelayAdd = idx != nil if removedFromDelayAdd { delayAddJoints.remove(at: idx!) } if cpSpaceIsLocked(chipmunkSpace) != 0 { guard !removedFromDelayAdd else { return } if !delayRemoveJoints.contains { $0 === joint } { delayRemoveJoints.append(joint) } } else { doRemove(joint: joint) } } /** * Remove all joints from this physics world. * * @attention This function is invoked in the destructor of this physics world, you do not use this api in common. */ public func removeAllJoints() { for joint in joints { remove(joint: joint) } } } internal extension PhysicsWorld { internal func updateJoints() { guard cpSpaceIsLocked(chipmunkSpace) != 0 else { return } for joint in delayAddJoints { if joint.chipmunkInitJoint() { joints.append(joint) } } delayAddJoints.removeAll() for joint in delayRemoveJoints { doRemove(joint: joint) } delayRemoveJoints.removeAll() } internal func doRemove(joint: PhysicsJoint) { for constraint in joint.chipmunkConstraints { cpSpaceRemoveConstraint(chipmunkSpace, constraint) } joints.removeObject(joint) joint.world = nil if let ba = joint.bodyA { ba.remove(joint: joint) } if let bb = joint.bodyB { bb.remove(joint: joint) } } }
apache-2.0
ae68a01bb36bc666b7b8393473bc60ee
27.279661
143
0.546299
4.491252
false
false
false
false
davejlin/treehouse
swift/swift2/fotofun/Pods/ReactiveCocoa/ReactiveCocoa/Swift/FoundationExtensions.swift
22
1958
// // FoundationExtensions.swift // ReactiveCocoa // // Created by Justin Spahr-Summers on 2014-10-19. // Copyright (c) 2014 GitHub. All rights reserved. // import Foundation import enum Result.NoError extension NSNotificationCenter { /// Returns a producer of notifications posted that match the given criteria. /// If the `object` is deallocated before starting the producer, it will /// terminate immediatelly with an Interrupted event. Otherwise, the producer /// will not terminate naturally, so it must be explicitly disposed to avoid /// leaks. public func rac_notifications(name: String? = nil, object: AnyObject? = nil) -> SignalProducer<NSNotification, NoError> { // We're weakly capturing an optional reference here, which makes destructuring awkward. let objectWasNil = (object == nil) return SignalProducer { [weak object] observer, disposable in guard object != nil || objectWasNil else { observer.sendInterrupted() return } let notificationObserver = self.addObserverForName(name, object: object, queue: nil) { notification in observer.sendNext(notification) } disposable += { self.removeObserver(notificationObserver) } } } } private let defaultSessionError = NSError(domain: "org.reactivecocoa.ReactiveCocoa.rac_dataWithRequest", code: 1, userInfo: nil) extension NSURLSession { /// Returns a producer that will execute the given request once for each /// invocation of start(). public func rac_dataWithRequest(request: NSURLRequest) -> SignalProducer<(NSData, NSURLResponse), NSError> { return SignalProducer { observer, disposable in let task = self.dataTaskWithRequest(request) { data, response, error in if let data = data, response = response { observer.sendNext((data, response)) observer.sendCompleted() } else { observer.sendFailed(error ?? defaultSessionError) } } disposable += { task.cancel() } task.resume() } } }
unlicense
c5a814c1c4b3dd1532db3ef4be0eda32
31.633333
128
0.724208
4.157113
false
false
false
false
ahmetkgunay/AKGPushAnimator
Examples/AKGPushAnimatorTableviewDemo/AKGPushAnimatorTableviewDemo/BaseViewController.swift
1
1325
// // BaseViewController.swift // AKGPushAnimatorTableviewDemo // // Created by AHMET KAZIM GUNAY on 12/05/2017. // Copyright © 2017 AHMET KAZIM GUNAY. All rights reserved. // import UIKit import AKGPushAnimator class BaseViewController: UIViewController, UINavigationControllerDelegate { let pushAnimator = AKGPushAnimator() let interactionAnimator = AKGInteractionAnimator() override func viewDidLoad() { super.viewDidLoad() } func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .push { interactionAnimator.attachToViewController(toVC) } pushAnimator.isReverseTransition = operation == .pop return pushAnimator } func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { return interactionAnimator.transitionInProgress ? interactionAnimator : nil } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
mit
e13495b1639a96391b24ab28686c1a14
35.777778
246
0.750755
5.99095
false
false
false
false
xusader/firefox-ios
Client/Frontend/Browser/SearchEngines.swift
3
6585
/* 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 import Shared let DefaultSearchEngineName = "Yahoo" private let OrderedEngineNames = "search.orderedEngineNames" private let DisabledEngineNames = "search.disabledEngineNames" private let ShowSearchSuggestionsOptIn = "search.suggestions.showOptIn" private let ShowSearchSuggestions = "search.suggestions.show" /** * Manage a set of Open Search engines. * * The search engines are ordered. Individual search engines can be enabled and disabled. The * first search engine is distinguished and labeled the "default" search engine; it can never be * disabled. Search suggestions should always be sourced from the default search engine. * * Two additional bits of information are maintained: whether the user should be shown "opt-in to * search suggestions" UI, and whether search suggestions are enabled. * * Consumers will almost always use `defaultEngine` if they want a single search engine, and * `quickSearchEngines()` if they want a list of enabled quick search engines (possibly empty, * since the default engine is never included in the list of enabled quick search engines, and * it is possible to disable every non-default quick search engine). * * The search engines are backed by a write-through cache into a ProfilePrefs instance. This class * is not thread-safe -- you should only access it on a single thread (usually, the main thread)! */ class SearchEngines { let prefs: Prefs init(prefs: Prefs) { self.prefs = prefs // By default, show search suggestions opt-in and don't show search suggestions automatically. self.shouldShowSearchSuggestionsOptIn = prefs.boolForKey(ShowSearchSuggestionsOptIn) ?? true self.shouldShowSearchSuggestions = prefs.boolForKey(ShowSearchSuggestions) ?? false self.disabledEngineNames = getDisabledEngineNames() self.orderedEngines = getOrderedEngines() } var defaultEngine: OpenSearchEngine { get { return self.orderedEngines[0] } set(defaultEngine) { // The default engine is always enabled. self.enableEngine(defaultEngine) // The default engine is always first in the list. var orderedEngines = self.orderedEngines.filter({ engine in engine.shortName != defaultEngine.shortName }) orderedEngines.insert(defaultEngine, atIndex: 0) self.orderedEngines = orderedEngines } } func isEngineDefault(engine: OpenSearchEngine) -> Bool { return defaultEngine.shortName == engine.shortName } // The keys of this dictionary are used as a set. private var disabledEngineNames: [String: Bool]! { didSet { self.prefs.setObject(self.disabledEngineNames.keys.array, forKey: DisabledEngineNames) } } var orderedEngines: [OpenSearchEngine]! { didSet { self.prefs.setObject(self.orderedEngines.map({ (engine) in engine.shortName }), forKey: OrderedEngineNames) } } var quickSearchEngines: [OpenSearchEngine]! { get { return self.orderedEngines.filter({ (engine) in !self.isEngineDefault(engine) && self.isEngineEnabled(engine) }) } } var shouldShowSearchSuggestionsOptIn: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestionsOptIn, forKey: ShowSearchSuggestionsOptIn) } } var shouldShowSearchSuggestions: Bool { didSet { self.prefs.setObject(shouldShowSearchSuggestions, forKey: ShowSearchSuggestions) } } func isEngineEnabled(engine: OpenSearchEngine) -> Bool { return disabledEngineNames.indexForKey(engine.shortName) == nil } func enableEngine(engine: OpenSearchEngine) { disabledEngineNames.removeValueForKey(engine.shortName) } func disableEngine(engine: OpenSearchEngine) { if isEngineDefault(engine) { // Can't disable default engine. return } disabledEngineNames[engine.shortName] = true } private func getDisabledEngineNames() -> [String: Bool] { if let disabledEngineNames = self.prefs.stringArrayForKey(DisabledEngineNames) { var disabledEngineDict = [String: Bool]() for engineName in disabledEngineNames { disabledEngineDict[engineName] = true } return disabledEngineDict } else { return [String: Bool]() } } // Get all known search engines, with the default search engine first, but the others in no // particular order. class func getUnorderedEngines() -> [OpenSearchEngine] { var error: NSError? let path = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent("Locales/en-US/searchplugins") if path == nil { println("Error: Could not find search engine directory") return [] } let directory = NSFileManager.defaultManager().contentsOfDirectoryAtPath(path!, error: &error) if error != nil { println("Could not fetch search engines") return [] } var engines = [OpenSearchEngine]() let parser = OpenSearchParser(pluginMode: true) for file in directory! { let fullPath = path!.stringByAppendingPathComponent(file as! String) let engine = parser.parse(fullPath) engines.append(engine!) } return engines.sorted({ e, _ in e.shortName == DefaultSearchEngineName }) } // Get all known search engines, possibly as ordered by the user. private func getOrderedEngines() -> [OpenSearchEngine] { let unorderedEngines = SearchEngines.getUnorderedEngines() if let orderedEngineNames = prefs.stringArrayForKey(OrderedEngineNames) { var orderedEngines = [OpenSearchEngine]() for engineName in orderedEngineNames { for engine in unorderedEngines { if engine.shortName == engineName { orderedEngines.append(engine) } } } return orderedEngines } else { // We haven't persisted the engine order, so return whatever order we got from disk. return unorderedEngines } } }
mpl-2.0
694d7de908b00e8f6db253c5f277b7af
37.735294
119
0.663781
4.992418
false
false
false
false
apple/swift-format
Sources/SwiftFormatPrettyPrint/Comment.swift
1
3319
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2019 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 // //===----------------------------------------------------------------------===// import Foundation import SwiftFormatConfiguration import SwiftSyntax extension StringProtocol { /// Trims whitespace from the end of a string, returning a new string with no trailing whitespace. /// /// If the string is only whitespace, an empty string is returned. /// /// - Returns: The string with trailing whitespace removed. func trimmingTrailingWhitespace() -> String { if isEmpty { return String() } let scalars = unicodeScalars var idx = scalars.index(before: scalars.endIndex) while scalars[idx].properties.isWhitespace { if idx == scalars.startIndex { return String() } idx = scalars.index(before: idx) } return String(String.UnicodeScalarView(scalars[...idx])) } } struct Comment { enum Kind { case line, docLine, block, docBlock /// The length of the characters starting the comment. var prefixLength: Int { switch self { // `//`, `/*` case .line, .block: return 2 // `///`, `/**` case .docLine, .docBlock: return 3 } } var prefix: String { switch self { case .line: return "//" case .block: return "/*" case .docBlock: return "/**" case .docLine: return "///" } } } let kind: Kind var text: [String] var length: Int init(kind: Kind, text: String) { self.kind = kind switch kind { case .line, .docLine: self.text = [text.trimmingTrailingWhitespace()] self.text[0].removeFirst(kind.prefixLength) self.length = self.text.reduce(0, { $0 + $1.count + kind.prefixLength + 1 }) case .block, .docBlock: var fulltext: String = text fulltext.removeFirst(kind.prefixLength) fulltext.removeLast(2) let lines = fulltext.split(separator: "\n", omittingEmptySubsequences: false) // The last line in a block style comment contains the "*/" pattern to end the comment. The // trailing space(s) need to be kept in that line to have space between text and "*/". var trimmedLines = lines.dropLast().map({ $0.trimmingTrailingWhitespace() }) if let lastLine = lines.last { trimmedLines.append(String(lastLine)) } self.text = trimmedLines self.length = self.text.reduce(0, { $0 + $1.count }) + kind.prefixLength + 3 } } func print(indent: [Indent]) -> String { switch self.kind { case .line, .docLine: let separator = "\n" + kind.prefix return kind.prefix + self.text.joined(separator: separator) case .block, .docBlock: let separator = "\n" return kind.prefix + self.text.joined(separator: separator) + "*/" } } mutating func addText(_ text: [String]) { for line in text { self.text.append(line) self.length += line.count + self.kind.prefixLength + 1 } } }
apache-2.0
b0f125ad3644ed911f1c4be33ab11818
30.311321
100
0.609521
4.180101
false
false
false
false
augmify/Eureka
Source/Cells.swift
2
30434
// Cells.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 Foundation import UIKit // MARK: LabelCell public class LabelCellOf<T: Equatable>: Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func setup() { super.setup() selectionStyle = .None } public override func update() { super.update() } } public typealias LabelCell = LabelCellOf<String> // MARK: ButtonCell public class ButtonCellOf<T: Equatable>: Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func setup() { super.setup() } public override func update() { super.update() textLabel?.textColor = tintColor selectionStyle = row.isDisabled ? .None : .Default accessoryType = .None editingAccessoryType = accessoryType textLabel?.textAlignment = .Center var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) textLabel?.textColor = UIColor(red: red, green: green, blue: blue, alpha: row.isDisabled ? 0.3 : 1.0) } } public typealias ButtonCell = ButtonCellOf<String> // MARK: FieldCell public protocol FieldTypeInitiable { init?(string stringValue: String) } extension Int: FieldTypeInitiable { public init?(string stringValue: String){ self.init(stringValue, radix: 10) } } extension Float: FieldTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension String: FieldTypeInitiable { public init?(string stringValue: String){ self.init(stringValue) } } extension NSURL: FieldTypeInitiable {} public class _FieldCell<T where T: Equatable, T: FieldTypeInitiable> : Cell<T>, UITextFieldDelegate, TextFieldCell { lazy public var textField : UITextField = { let textField = UITextField() textField.translatesAutoresizingMaskIntoConstraints = false return textField }() public var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal) textLabel?.setContentCompressionResistancePriority(1000, forAxis: .Horizontal) return textLabel } private var dynamicConstraints = [NSLayoutConstraint]() public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } deinit { titleLabel?.removeObserver(self, forKeyPath: "text") imageView?.removeObserver(self, forKeyPath: "image") } public override func setup() { super.setup() selectionStyle = .None contentView.addSubview(titleLabel!) contentView.addSubview(textField) titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) imageView?.addObserver(self, forKeyPath: "image", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) textField.addTarget(self, action: "textFieldDidChange:", forControlEvents: .EditingChanged) } public func valueFromString(string: String?) -> T? { if let formatter = (row as? FieldRowConformance)?.formatter { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = nil let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil formatter.getObjectValue(value, forString: string!, errorDescription: errorDesc) return value as? T } else{ return row.value } } public override func update() { super.update() if let title = row.title { textField.textAlignment = title.isEmpty ? .Left : .Right textField.clearButtonMode = title.isEmpty ? .WhileEditing : .Never } else{ textField.textAlignment = .Left textField.clearButtonMode = .WhileEditing } textField.delegate = self detailTextLabel?.text = nil textField.text = row.displayValueFor?(row.value) textField.enabled = !row.isDisabled textField.textColor = row.isDisabled ? .grayColor() : .blackColor() textField.font = .preferredFontForTextStyle(UIFontTextStyleBody) if let placeholder = (row as? FieldRowConformance)?.placeholder { if let color = (row as? FieldRowConformance)?.placeholderColor { textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSForegroundColorAttributeName: color]) } else{ textField.placeholder = (row as? FieldRowConformance)?.placeholder } } } public override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textField.canBecomeFirstResponder() } public override func cellBecomeFirstResponder() -> Bool { return textField.becomeFirstResponder() } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] where ((obj === titleLabel && keyPathValue == "text") || (obj === imageView && keyPathValue == "image")) && changeType.unsignedLongValue == NSKeyValueChange.Setting.rawValue { contentView.setNeedsUpdateConstraints() } } // Mark: Helpers public override func updateConstraints(){ contentView.removeConstraints(dynamicConstraints) var views : [String: AnyObject] = ["textField": textField] dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-11-[textField]-11-|", options: .AlignAllBaseline, metrics: nil, views: ["textField": textField]) if let label = titleLabel, _ = label.text { dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("V:|-11-[titleLabel]-11-|", options: .AlignAllBaseline, metrics: nil, views: ["titleLabel": label]) dynamicConstraints.append(NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: textField, attribute: .CenterY, multiplier: 1, constant: 0)) } if let image = imageView?.image { views["image"] = image if let text = titleLabel?.text where !text.isEmpty { views["label"] = titleLabel! dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[image]-[label]-[textField]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .Width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .Equal : .GreaterThanOrEqual, toItem: contentView, attribute: .Width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:[image]-[textField]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) } } else{ if let text = titleLabel?.text where !text.isEmpty { views["label"] = titleLabel! dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-[textField]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views) dynamicConstraints.append(NSLayoutConstraint(item: textField, attribute: .Width, relatedBy: (row as? FieldRowConformance)?.textFieldPercentage != nil ? .Equal : .GreaterThanOrEqual, toItem: contentView, attribute: .Width, multiplier: (row as? FieldRowConformance)?.textFieldPercentage ?? 0.3, constant: 0.0)) } else{ dynamicConstraints += NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textField]-|", options: .AlignAllLeft, metrics: nil, views: views) } } contentView.addConstraints(dynamicConstraints) super.updateConstraints() } public func textFieldDidChange(textField : UITextField){ guard let textValue = textField.text else { row.value = nil return } if let fieldRow = row as? FieldRowConformance, let formatter = fieldRow.formatter where fieldRow.useFormatterDuringInput { let value: AutoreleasingUnsafeMutablePointer<AnyObject?> = AutoreleasingUnsafeMutablePointer<AnyObject?>.init(UnsafeMutablePointer<T>.alloc(1)) let errorDesc: AutoreleasingUnsafeMutablePointer<NSString?> = nil if formatter.getObjectValue(value, forString: textValue, errorDescription: errorDesc) { row.value = value.memory as? T if var selStartPos = textField.selectedTextRange?.start { let oldVal = textField.text textField.text = row.displayValueFor?(row.value) if let f = formatter as? FormatterProtocol { selStartPos = f.getNewPosition(forPosition: selStartPos, inTextField: textField, oldValue: oldVal, newValue: textField.text) } textField.selectedTextRange = textField.textRangeFromPosition(selStartPos, toPosition: selStartPos) } return } } guard !textValue.isEmpty else { row.value = nil return } guard let newValue = T.init(string: textValue) else { row.updateCell() return } row.value = newValue } //MARK: TextFieldDelegate public func textFieldDidBeginEditing(textField: UITextField) { formViewController()?.beginEditing(self) if let fieldRowConformance = (row as? FieldRowConformance), let _ = fieldRowConformance.formatter where !fieldRowConformance.useFormatterDuringInput { textField.text = row.displayValueFor?(row.value) } } public func textFieldDidEndEditing(textField: UITextField) { textFieldDidChange(textField) formViewController()?.endEditing(self) if let fieldRowConformance = (row as? FieldRowConformance), let _ = fieldRowConformance.formatter where !fieldRowConformance.useFormatterDuringInput { textField.text = row.displayValueFor?(row.value) } } } public class TextCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .Default textField.autocapitalizationType = .Sentences textField.keyboardType = .Default } } public class IntCell : _FieldCell<Int>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .Default textField.autocapitalizationType = .None textField.keyboardType = .NumberPad } } public class PhoneCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.keyboardType = .PhonePad } } public class NameCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .No textField.autocapitalizationType = .Words textField.keyboardType = .NamePhonePad } } public class EmailCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .No textField.autocapitalizationType = .None textField.keyboardType = .EmailAddress } } public class PasswordCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .No textField.autocapitalizationType = .None textField.keyboardType = .ASCIICapable textField.secureTextEntry = true } } public class DecimalCell : _FieldCell<Float>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.keyboardType = .DecimalPad } } public class URLCell : _FieldCell<NSURL>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.keyboardType = .URL } } public class TwitterCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .No textField.autocapitalizationType = .None textField.keyboardType = .Twitter } } public class AccountCell : _FieldCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textField.autocorrectionType = .No textField.autocapitalizationType = .None textField.keyboardType = .ASCIICapable } } public class DateCell : Cell<NSDate>, CellType { lazy public var datePicker : UIDatePicker = { return UIDatePicker() }() private var _detailColor : UIColor! public required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func setup() { super.setup() datePicker.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: .ValueChanged) } public override func update() { super.update() setModeToDatePicker(datePicker) accessoryType = .None editingAccessoryType = .None selectionStyle = row.isDisabled ? .None : .Default detailTextLabel?.text = row.displayValueFor?(row.value) } public override func didSelect() { super.didSelect() formViewController()?.tableView?.deselectRowAtIndexPath(row.indexPath()!, animated: true) } override public var inputView : UIView? { if let v = row.value{ datePicker.setDate(v, animated:row is CountDownRow) } return datePicker } func datePickerValueChanged(sender: UIDatePicker){ row.value = sender.date detailTextLabel?.text = row.displayValueFor!(row.value!) setNeedsLayout() } public func setModeToDatePicker(datePicker : UIDatePicker){ switch row { case is DateRow: datePicker.datePickerMode = .Date case is TimeRow: datePicker.datePickerMode = .Time case is DateTimeRow: datePicker.datePickerMode = .DateAndTime case is CountDownRow: datePicker.datePickerMode = .CountDownTimer default: datePicker.datePickerMode = .Date } datePicker.minimumDate = (row as? _DateFieldRow)?.minimumDate datePicker.maximumDate = (row as? _DateFieldRow)?.maximumDate if let minuteIntervalValue = (row as? _DateFieldRow)?.minuteInterval{ datePicker.minuteInterval = minuteIntervalValue } } public override func cellCanBecomeFirstResponder() -> Bool { return canBecomeFirstResponder() } public override func canBecomeFirstResponder() -> Bool { return !row.isDisabled; } public override func becomeFirstResponder() -> Bool { _detailColor = detailTextLabel?.textColor return super.becomeFirstResponder() } public override func highlight() { detailTextLabel?.textColor = tintColor } public override func unhighlight() { detailTextLabel?.textColor = _detailColor } } public class _TextAreaCell<T: Equatable> : Cell<T>, UITextViewDelegate { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public lazy var placeholderLabel : UILabel = { let v = UILabel() v.translatesAutoresizingMaskIntoConstraints = false return v }() public lazy var textView : UITextView = { let v = UITextView() v.translatesAutoresizingMaskIntoConstraints = false return v }() private var dynamicConstraints = [NSLayoutConstraint]() deinit { placeholderLabel.removeObserver(self, forKeyPath: "text") } public override func setup() { super.setup() height = { 110 } textView.delegate = self textLabel?.text = nil textView.font = .preferredFontForTextStyle(UIFontTextStyleBody) placeholderLabel.text = (row as? TextAreaProtocol)?.placeholder placeholderLabel.numberOfLines = 0 placeholderLabel.sizeToFit() textView.addSubview(placeholderLabel) placeholderLabel.font = .systemFontOfSize(textView.font!.pointSize) placeholderLabel.textColor = UIColor(white: 0, alpha: 0.22) selectionStyle = .None contentView.addSubview(textView) contentView.addSubview(placeholderLabel) placeholderLabel.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) let views : [String: AnyObject] = ["textView": textView, "label": placeholderLabel] contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-8-[label]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[textView]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraint(NSLayoutConstraint(item: textView, attribute: .Top, relatedBy: .Equal, toItem: contentView, attribute: .Top, multiplier: 1, constant: 0)) contentView.addConstraint(NSLayoutConstraint(item: textView, attribute: .Bottom, relatedBy: .Equal, toItem: contentView, attribute: .Bottom, multiplier: 1, constant: 0)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[textView]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) } public override func update() { super.update() placeholderLabel.hidden = textView.text.characters.count != 0 textView.keyboardType = .Default textView.editable = !row.isDisabled textView.textColor = row.isDisabled ? .grayColor() : .blackColor() } public override func cellCanBecomeFirstResponder() -> Bool { return !row.isDisabled && textView.canBecomeFirstResponder() } public override func cellBecomeFirstResponder() -> Bool { return textView.becomeFirstResponder() } public func textViewDidChange(textView: UITextView) { placeholderLabel.hidden = textView.text.characters.count != 0 row.value = textView.text as? T } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let keyPathValue = keyPath, let changeType = change?[NSKeyValueChangeKindKey] where obj === placeholderLabel && keyPathValue == "text" && changeType.unsignedLongValue == NSKeyValueChange.Setting.rawValue{ contentView.setNeedsUpdateConstraints() } } } public class TextAreaCell : _TextAreaCell<String>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() textView.text = row.value } } public class CheckCell : Cell<Bool>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() accessoryType = row.value == true ? .Checkmark : .None editingAccessoryType = accessoryType selectionStyle = .Default var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 tintColor.getRed(&red, green: &green, blue: &blue, alpha: &alpha) if row.isDisabled { tintColor = UIColor(red: red, green: green, blue: blue, alpha: 0.3) selectionStyle = .None } else { tintColor = UIColor(red: red, green: green, blue: blue, alpha: 1) } } public override func setup() { super.setup() accessoryType = .Checkmark editingAccessoryType = accessoryType } public override func didSelect() { row.value = row.value ?? false ? false : true formViewController()?.tableView?.deselectRowAtIndexPath(row.indexPath()!, animated: true) row.updateCell() } } public class SwitchCell : Cell<Bool>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public var switchControl: UISwitch? { return accessoryView as? UISwitch } public override func setup() { super.setup() selectionStyle = .None accessoryView = UISwitch() editingAccessoryView = accessoryView switchControl?.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged) } public override func update() { super.update() switchControl?.on = row.value ?? false switchControl?.enabled = !row.isDisabled } func valueChanged() { row.value = switchControl?.on.boolValue ?? false } } public class SegmentedCell<T: Equatable> : Cell<T>, CellType { public var titleLabel : UILabel? { textLabel?.translatesAutoresizingMaskIntoConstraints = false textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal) return textLabel } lazy public var segmentedControl : UISegmentedControl = { let result = UISegmentedControl() result.translatesAutoresizingMaskIntoConstraints = false result.setContentHuggingPriority(500, forAxis: .Horizontal) return result }() private var dynamicConstraints : [NSLayoutConstraint]? required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { dynamicConstraints = nil super.init(style: style, reuseIdentifier: reuseIdentifier) } deinit { titleLabel?.removeObserver(self, forKeyPath: "text") } public override func setup() { super.setup() selectionStyle = .None contentView.addSubview(titleLabel!) contentView.addSubview(segmentedControl) titleLabel?.addObserver(self, forKeyPath: "text", options: NSKeyValueObservingOptions.Old.union(.New), context: nil) segmentedControl.addTarget(self, action: "valueChanged", forControlEvents: .ValueChanged) contentView.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .CenterY, relatedBy: .Equal, toItem: contentView, attribute: .CenterY, multiplier: 1, constant: 0)) } public override func update() { super.update() detailTextLabel?.text = nil updateSegmentedControl() segmentedControl.selectedSegmentIndex = selectedIndex() ?? UISegmentedControlNoSegment segmentedControl.enabled = !row.isDisabled } func valueChanged() { row.value = (row as! SegmentedRow<T>).options[segmentedControl.selectedSegmentIndex] } public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) { if let obj = object, let changeType = change, let _ = keyPath where obj === titleLabel && keyPath == "text" && changeType[NSKeyValueChangeKindKey]?.unsignedLongValue == NSKeyValueChange.Setting.rawValue{ contentView.setNeedsUpdateConstraints() } } func updateSegmentedControl() { segmentedControl.removeAllSegments() for item in items().enumerate() { segmentedControl.insertSegmentWithTitle(item.element, atIndex: item.index, animated: false) } } public override func updateConstraints() { if let dynConst = dynamicConstraints { contentView.removeConstraints(dynConst) } dynamicConstraints = [] var views : [String: AnyObject] = ["segmentedControl": segmentedControl] if (titleLabel?.text?.isEmpty == false) { views["titleLabel"] = titleLabel dynamicConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[titleLabel]-16-[segmentedControl]-|", options: .AlignAllCenterY, metrics: nil, views: views) dynamicConstraints?.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|-12-[titleLabel]-12-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views)) } else{ dynamicConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[segmentedControl]-|", options: .AlignAllCenterY, metrics: nil, views: views) } contentView.addConstraints(dynamicConstraints!) super.updateConstraints() } func items() -> [String] {// or create protocol for options var result = [String]() for object in (row as! SegmentedRow<T>).options{ result.append(row.displayValueFor?(object) ?? "") } return result } func selectedIndex() -> Int? { guard let value = row.value else { return nil } return (row as! SegmentedRow<T>).options.indexOf(value) } } public class AlertSelectorCell<T: Equatable> : Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() accessoryType = .None editingAccessoryType = accessoryType selectionStyle = row.isDisabled ? .None : .Default } public override func didSelect() { super.didSelect() formViewController()?.tableView?.deselectRowAtIndexPath(row.indexPath()!, animated: true) } } public class PushSelectorCell<T: Equatable> : Cell<T>, CellType { required public init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) } public override func update() { super.update() accessoryType = .DisclosureIndicator editingAccessoryType = accessoryType selectionStyle = row.isDisabled ? .None : .Default } }
mit
38053e671f5e298ffbce69c9765bb1a9
37.426768
324
0.662483
5.359986
false
false
false
false
realm/SwiftLint
Source/SwiftLintFramework/Rules/Style/VerticalParameterAlignmentOnCallRule.swift
1
6097
import SourceKittenFramework struct VerticalParameterAlignmentOnCallRule: ASTRule, ConfigurationProviderRule, OptInRule { var configuration = SeverityConfiguration(.warning) init() {} static let description = RuleDescription( identifier: "vertical_parameter_alignment_on_call", name: "Vertical Parameter Alignment On Call", description: "Function parameters should be aligned vertically if they're in multiple lines in a method call.", kind: .style, nonTriggeringExamples: [ Example(""" foo(param1: 1, param2: bar param3: false, param4: true) """), Example(""" foo(param1: 1, param2: bar) """), Example(""" foo(param1: 1, param2: bar param3: false, param4: true) """), Example(""" foo( param1: 1 ) { _ in } """), Example(""" UIView.animate(withDuration: 0.4, animations: { blurredImageView.alpha = 1 }, completion: { _ in self.hideLoading() }) """), Example(""" UIView.animate(withDuration: 0.4, animations: { blurredImageView.alpha = 1 }, completion: { _ in self.hideLoading() }) """), Example(""" foo(param1: 1, param2: { _ in }, param3: false, param4: true) """), Example(""" foo({ _ in bar() }, completion: { _ in baz() } ) """), Example(""" foo(param1: 1, param2: [ 0, 1 ], param3: 0) """), Example(""" myFunc(foo: 0, bar: baz == 0) """) ], triggeringExamples: [ Example(""" foo(param1: 1, param2: bar ↓param3: false, param4: true) """), Example(""" foo(param1: 1, param2: bar ↓param3: false, param4: true) """), Example(""" foo(param1: 1, param2: bar ↓param3: false, ↓param4: true) """), Example(""" foo(param1: 1, ↓param2: { _ in }) """), Example(""" foo(param1: 1, param2: { _ in }, param3: 2, ↓param4: 0) """), Example(""" foo(param1: 1, param2: { _ in }, ↓param3: false, param4: true) """), Example(""" myFunc(foo: 0, ↓bar: baz == 0) """) ] ) func validate(file: SwiftLintFile, kind: SwiftExpressionKind, dictionary: SourceKittenDictionary) -> [StyleViolation] { guard kind == .call, case let arguments = dictionary.enclosedArguments, arguments.count > 1, let firstArgumentOffset = arguments.first?.offset, case let contents = file.stringView, var firstArgumentPosition = contents.lineAndCharacter(forByteOffset: firstArgumentOffset) else { return [] } var visitedLines = Set<Int>() var previousArgumentWasMultiline = false let lastIndex = arguments.count - 1 let violatingOffsets: [ByteCount] = arguments.enumerated().compactMap { idx, argument in defer { previousArgumentWasMultiline = isMultiline(argument: argument, file: file) } guard let offset = argument.offset, let (line, character) = contents.lineAndCharacter(forByteOffset: offset), line > firstArgumentPosition.line else { return nil } let (firstVisit, _) = visitedLines.insert(line) guard character != firstArgumentPosition.character && firstVisit else { return nil } // if this is the first element on a new line after a closure with multiple lines, // we reset the reference position if previousArgumentWasMultiline && firstVisit { firstArgumentPosition = (line, character) return nil } // never trigger on a trailing closure if idx == lastIndex, isTrailingClosure(dictionary: dictionary, file: file) { return nil } return offset } return violatingOffsets.map { StyleViolation(ruleDescription: Self.description, severity: configuration.severity, location: Location(file: file, byteOffset: $0)) } } private func isMultiline(argument: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let offset = argument.bodyOffset, let length = argument.bodyLength, case let contents = file.stringView, let (startLine, _) = contents.lineAndCharacter(forByteOffset: offset), let (endLine, _) = contents.lineAndCharacter(forByteOffset: offset + length) else { return false } return endLine > startLine } private func isTrailingClosure(dictionary: SourceKittenDictionary, file: SwiftLintFile) -> Bool { guard let offset = dictionary.offset, let length = dictionary.length, case let start = min(offset, offset + length - 1), case let byteRange = ByteRange(location: start, length: length), let text = file.stringView.substringWithByteRange(byteRange) else { return false } return !text.hasSuffix(")") } }
mit
b86f2acb8788aa15e11a1fa6180472d8
32.229508
119
0.486433
5.390957
false
false
false
false
alblue/swift
stdlib/public/core/SmallString.swift
1
10150
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @_fixed_layout @usableFromInline internal struct _SmallString { @usableFromInline internal typealias RawBitPattern = (UInt64, UInt64) // Small strings are values; store them raw @usableFromInline internal var _storage: RawBitPattern @inlinable internal var rawBits: RawBitPattern { @inline(__always) get { return _storage } } @inlinable internal var leadingRawBits: UInt64 { @inline(__always) get { return _storage.0 } @inline(__always) set { _storage.0 = newValue } } @inlinable internal var trailingRawBits: UInt64 { @inline(__always) get { return _storage.1 } @inline(__always) set { _storage.1 = newValue } } @inlinable @inline(__always) internal init(rawUnchecked bits: RawBitPattern) { self._storage = bits } @inlinable @inline(__always) internal init(raw bits: RawBitPattern) { self.init(rawUnchecked: bits) _invariantCheck() } @inlinable @inline(__always) internal init(_ object: _StringObject) { _sanityCheck(object.isSmall) self.init(raw: object.rawBits) } @inlinable @inline(__always) internal init() { self.init(raw: _StringObject(empty:()).rawBits) } } // TODO extension _SmallString { @inlinable internal static var capacity: Int { @inline(__always) get { #if arch(i386) || arch(arm) return 10 #else return 15 #endif } } @inlinable internal var discriminator: _StringObject.Discriminator { @inline(__always) get { let value = _storage.1 &>> _StringObject.Nibbles.discriminatorShift return _StringObject.Discriminator(UInt8(truncatingIfNeeded: value)) } @inline(__always) set { _storage.1 &= _StringObject.Nibbles.largeAddressMask _storage.1 |= ( UInt64(truncatingIfNeeded: newValue._value) &<< _StringObject.Nibbles.discriminatorShift) } } @inlinable internal var capacity: Int { @inline(__always) get { return _SmallString.capacity } } @inlinable internal var count: Int { @inline(__always) get { return discriminator.smallCount } } @inlinable internal var unusedCapacity: Int { @inline(__always) get { return capacity &- count } } @inlinable internal var isASCII: Bool { @inline(__always) get { return discriminator.smallIsASCII } } // Give raw, nul-terminated code units. This is only for limited internal // usage: it always clears the discriminator and count (in case it's full) @inlinable internal var zeroTerminatedRawCodeUnits: RawBitPattern { @inline(__always) get { return ( self._storage.0, self._storage.1 & _StringObject.Nibbles.largeAddressMask) } } @inlinable internal func computeIsASCII() -> Bool { // TODO(String micro-performance): Evaluate other expressions, e.g. | first let asciiMask: UInt64 = 0x8080_8080_8080_8080 let raw = zeroTerminatedRawCodeUnits return (raw.0 & asciiMask == 0) && (raw.1 & asciiMask == 0) } } // Internal invariants extension _SmallString { #if !INTERNAL_CHECKS_ENABLED @inlinable @inline(__always) internal func _invariantCheck() {} #else @usableFromInline @inline(never) @_effects(releasenone) internal func _invariantCheck() { _sanityCheck(count <= _SmallString.capacity) _sanityCheck(isASCII == computeIsASCII()) } #endif // INTERNAL_CHECKS_ENABLED internal func _dump() { #if INTERNAL_CHECKS_ENABLED print(""" smallUTF8: count: \(self.count), codeUnits: \( self.map { String($0, radix: 16) }.joined() ) """) #endif // INTERNAL_CHECKS_ENABLED } } // Provide a RAC interface extension _SmallString: RandomAccessCollection, MutableCollection { @usableFromInline internal typealias Index = Int @usableFromInline internal typealias Element = UInt8 @usableFromInline internal typealias SubSequence = _SmallString @inlinable internal var startIndex: Int { @inline(__always) get { return 0 } } @inlinable internal var endIndex: Int { @inline(__always) get { return count } } @inlinable internal subscript(_ idx: Int) -> UInt8 { @inline(__always) get { _sanityCheck(idx >= 0 && idx <= 15) if idx < 8 { return leadingRawBits._uncheckedGetByte(at: idx) } else { return trailingRawBits._uncheckedGetByte(at: idx &- 8) } } @inline(__always) set { _sanityCheck(idx >= 0 && idx <= 15) if idx < 8 { leadingRawBits._uncheckedSetByte(at: idx, to: newValue) } else { trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue) } } } @usableFromInline // testable internal subscript(_ bounds: Range<Index>) -> SubSequence { @inline(__always) get { // TODO(String performance): In-vector-register operation return self.withUTF8 { utf8 in let rebased = UnsafeBufferPointer(rebasing: utf8[bounds]) return _SmallString(rebased)._unsafelyUnwrappedUnchecked } } } } extension _SmallString { @inlinable @inline(__always) internal func withUTF8<Result>( _ f: (UnsafeBufferPointer<UInt8>) throws -> Result ) rethrows -> Result { var raw = self.zeroTerminatedRawCodeUnits return try Swift.withUnsafeBytes(of: &raw) { rawBufPtr in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeBufferPointer(start: ptr, count: self.count)) } } // Overwrite stored code units, including uninitialized. `f` should return the // new count. @inlinable @inline(__always) internal mutating func withMutableCapacity( _ f: (UnsafeMutableBufferPointer<UInt8>) throws -> Int ) rethrows { let len = try withUnsafeMutableBytes(of: &self._storage) { (rawBufPtr: UnsafeMutableRawBufferPointer) -> Int in let ptr = rawBufPtr.baseAddress._unsafelyUnwrappedUnchecked .assumingMemoryBound(to: UInt8.self) return try f(UnsafeMutableBufferPointer( start: ptr, count: _SmallString.capacity)) } _sanityCheck(len <= _SmallString.capacity) discriminator = .small(withCount: len, isASCII: self.computeIsASCII()) } } // Creation extension _SmallString { // Direct from UTF-8 @inlinable @inline(__always) internal init?(_ input: UnsafeBufferPointer<UInt8>) { let count = input.count guard count <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a masked unaligned // vector load let ptr = input.baseAddress._unsafelyUnwrappedUnchecked let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8)) let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0 let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0 let discriminator = _StringObject.Discriminator.small( withCount: count, isASCII: isASCII) self.init(raw: (leading, trailing | discriminator.rawBits)) } @usableFromInline // @testable internal init?(_ base: _SmallString, appending other: _SmallString) { let totalCount = base.count + other.count guard totalCount <= _SmallString.capacity else { return nil } // TODO(SIMD): The below can be replaced with just be a couple vector ops var result = base var writeIdx = base.count for readIdx in 0..<other.count { result[writeIdx] = other[readIdx] writeIdx &+= 1 } _sanityCheck(writeIdx == totalCount) let isASCII = base.isASCII && other.isASCII let discriminator = _StringObject.Discriminator.small( withCount: totalCount, isASCII: isASCII) let (leading, trailing) = result.zeroTerminatedRawCodeUnits self.init(raw: (leading, trailing | discriminator.rawBits)) } } #if _runtime(_ObjC) && !(arch(i386) || arch(arm)) // Cocoa interop extension _SmallString { // Resiliently create from a tagged cocoa string // @_effects(readonly) // @opaque @usableFromInline // testable internal init(taggedCocoa cocoa: AnyObject) { self.init() self.withMutableCapacity { let len = _bridgeTagged(cocoa, intoUTF8: $0) _sanityCheck(len != nil && len! < _SmallString.capacity, "Internal invariant violated: large tagged NSStrings") return len._unsafelyUnwrappedUnchecked } self._invariantCheck() } } #endif extension UInt64 { // Fetches the `i`th byte, from least-significant to most-significant // // TODO: endianess awareness day @inlinable @inline(__always) internal func _uncheckedGetByte(at i: Int) -> UInt8 { _sanityCheck(i >= 0 && i < MemoryLayout<UInt64>.stride) let shift = UInt64(truncatingIfNeeded: i) &* 8 return UInt8(truncatingIfNeeded: (self &>> shift)) } // Sets the `i`th byte, from least-significant to most-significant // // TODO: endianess awareness day @inlinable @inline(__always) internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) { _sanityCheck(i >= 0 && i < MemoryLayout<UInt64>.stride) let shift = UInt64(truncatingIfNeeded: i) &* 8 let valueMask: UInt64 = 0xFF &<< shift self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift) } } @inlinable @inline(__always) internal func _bytesToUInt64( _ input: UnsafePointer<UInt8>, _ c: Int ) -> UInt64 { // FIXME: This should be unified with _loadPartialUnalignedUInt64LE. // Unfortunately that causes regressions in literal concatenation tests. (Some // owned to guaranteed specializations don't get inlined.) var r: UInt64 = 0 var shift: Int = 0 for idx in 0..<c { r = r | (UInt64(input[idx]) &<< shift) shift = shift &+ 8 } return r }
apache-2.0
ebb579fd9f07dd7d938d5e1f1679afa5
28.591837
80
0.660493
4.195949
false
false
false
false
firebase/firebase-ios-sdk
FirebaseCombineSwift/Tests/Unit/Auth/AuthStateDidChangePublisherTests.swift
2
9375
// Copyright 2020 Google LLC // // 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 FirebaseCore import FirebaseAuth import FirebaseCombineSwift import Combine import XCTest class AuthStateDidChangePublisherTests: XCTestCase { static let apiKey = Credentials.apiKey static let accessTokenTimeToLive: TimeInterval = 60 * 60 static let refreshToken = "REFRESH_TOKEN" static let accessToken = "ACCESS_TOKEN" static let email = "[email protected]" static let password = "secret" static let localID = "LOCAL_ID" static let displayName = "Johnny Appleseed" static let passwordHash = "UkVEQUNURUQ=" class MockSignUpNewUserResponse: FIRSignUpNewUserResponse { override var idToken: String { return AuthStateDidChangePublisherTests.accessToken } override var refreshToken: String { return AuthStateDidChangePublisherTests.refreshToken } override var approximateExpirationDate: Date { Date(timeIntervalSinceNow: AuthStateDidChangePublisherTests.accessTokenTimeToLive) } } class MockGetAccountInfoResponseUser: FIRGetAccountInfoResponseUser { override var localID: String { return AuthStateDidChangePublisherTests.localID } override var email: String { return AuthStateDidChangePublisherTests.email } override var displayName: String { return AuthStateDidChangePublisherTests.displayName } } class MockGetAccountInfoResponse: FIRGetAccountInfoResponse { override var users: [FIRGetAccountInfoResponseUser] { return [MockGetAccountInfoResponseUser(dictionary: [:])] } } class MockVerifyPasswordResponse: FIRVerifyPasswordResponse { override var localID: String { return AuthStateDidChangePublisherTests.localID } override var email: String { return AuthStateDidChangePublisherTests.email } override var displayName: String { return AuthStateDidChangePublisherTests.displayName } override var idToken: String { return AuthStateDidChangePublisherTests.accessToken } override var approximateExpirationDate: Date { Date(timeIntervalSinceNow: AuthStateDidChangePublisherTests.accessTokenTimeToLive) } override var refreshToken: String { return AuthStateDidChangePublisherTests.refreshToken } } class MockAuthBackend: AuthBackendImplementationMock { override func signUpNewUser(_ request: FIRSignUpNewUserRequest, callback: @escaping FIRSignupNewUserCallback) { XCTAssertEqual(request.apiKey, AuthStateDidChangePublisherTests.apiKey) XCTAssertNil(request.email) XCTAssertNil(request.password) XCTAssertTrue(request.returnSecureToken) let response = MockSignUpNewUserResponse() callback(response, nil) } override func getAccountInfo(_ request: FIRGetAccountInfoRequest, callback: @escaping FIRGetAccountInfoResponseCallback) { XCTAssertEqual(request.apiKey, AuthStateDidChangePublisherTests.apiKey) XCTAssertEqual(request.accessToken, AuthStateDidChangePublisherTests.accessToken) let response = MockGetAccountInfoResponse() callback(response, nil) } override func verifyPassword(_ request: FIRVerifyPasswordRequest, callback: @escaping FIRVerifyPasswordResponseCallback) { let response = MockVerifyPasswordResponse() callback(response, nil) } } override class func setUp() { FirebaseApp.configureForTests() } override class func tearDown() { FirebaseApp.app()?.delete { success in if success { print("Shut down app successfully.") } else { print("💥 There was a problem when shutting down the app..") } } } override func setUp() { do { try Auth.auth().signOut() } catch {} } func testPublisherEmitsOnMainThread() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) let expect = expectation(description: "Publisher emits on main thread") let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in XCTAssertTrue(Thread.isMainThread) expect.fulfill() } Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) cancellable.cancel() } func testSubscribersCanReceiveOnNonMainThread() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) let expect = expectation(description: "Subscribers can receive events on non-main threads") let cancellable = Auth.auth().authStateDidChangePublisher() .receive(on: DispatchQueue.global()) .sink { user in XCTAssertFalse(Thread.isMainThread) expect.fulfill() } Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) cancellable.cancel() } func testPublisherEmitsWhenAttached() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) let subscriptionActivatedExpectation = expectation(description: "Publisher emits value as soon as it is subscribed") let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in XCTAssertNil(user) subscriptionActivatedExpectation.fulfill() } wait(for: [subscriptionActivatedExpectation], timeout: expectationTimeout) cancellable.cancel() } func testPublisherEmitsWhenUserIsSignedIn() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) let signedInExpectation = expectation(description: "Publisher emits value when user is signed in") let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in print("Running on the main thread? \(Thread.isMainThread)") if let user = user, user.isAnonymous { signedInExpectation.fulfill() } } Auth.auth().signInAnonymously() wait(for: [signedInExpectation], timeout: expectationTimeout) cancellable.cancel() } // Listener should not fire for signing in again. func testPublisherDoesNotEmitWhenUserSignsInAgain() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) var expect = expectation(description: "Publisher emits value when user is signed in") let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in if let user = user, user.isAnonymous { expect.fulfill() } } // Sign in, expect the publisher to emit Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) // Sign in again, expect the publisher NOT to emit expect = expectation(description: "Publisher does not emit when user sign in again") expect.isInverted = true Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) cancellable.cancel() } // Listener should fire for signing out. func testPublisherEmitsWhenUserSignsOut() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) var expect = expectation(description: "Publisher emits value when user is signed in") var shouldUserBeNil = false let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in if shouldUserBeNil { if user == nil { expect.fulfill() } } else { if let user = user, user.isAnonymous { expect.fulfill() } } } // sign in first Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) // now sign out expect = expectation(description: "Publisher emits value when user signs out") shouldUserBeNil = true do { try Auth.auth().signOut() } catch {} wait(for: [expect], timeout: expectationTimeout) cancellable.cancel() } // Listener should no longer fire once detached. func testPublisherNoLongerEmitsWhenDetached() { // given FIRAuthBackend.setBackendImplementation(MockAuthBackend()) var expect = expectation(description: "Publisher emits value when user is signed in") var shouldUserBeNil = false let cancellable = Auth.auth().authStateDidChangePublisher() .sink { user in if shouldUserBeNil { if user == nil { expect.fulfill() } } else { if let user = user, user.isAnonymous { expect.fulfill() } } } // sign in first Auth.auth().signInAnonymously() wait(for: [expect], timeout: expectationTimeout) // detach the publisher expect = expectation(description: "Publisher no longer emits once detached") expect.isInverted = true cancellable.cancel() shouldUserBeNil = true do { try Auth.auth().signOut() } catch {} wait(for: [expect], timeout: expectationTimeout) } }
apache-2.0
855c073e2f2b2f1cb853561ae87147a7
31.769231
95
0.704652
4.943038
false
true
false
false
eoger/firefox-ios
Storage/Bookmarks/Bookmarks.swift
3
20175
/* 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 import Shared import Deferred import SwiftyJSON private let log = Logger.syncLogger public protocol SearchableBookmarks: AnyObject { func bookmarksByURL(_ url: URL) -> Deferred<Maybe<Cursor<BookmarkItem>>> } public protocol SyncableBookmarks: AnyObject, ResettableSyncStorage, AccountRemovalDelegate { // TODO func isUnchanged() -> Deferred<Maybe<Bool>> func getLocalBookmarksModifications(limit: Int) -> Deferred<Maybe<(deletions: [GUID], additions: [BookmarkMirrorItem])>> func getLocalDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func treesForEdges() -> Deferred<Maybe<(local: BookmarkTree, buffer: BookmarkTree)>> func treeForMirror() -> Deferred<Maybe<BookmarkTree>> func applyLocalOverrideCompletionOp(_ op: LocalOverrideCompletionOp, itemSources: ItemSources) -> Success func applyBufferUpdatedCompletionOp(_ op: BufferUpdatedCompletionOp) -> Success } public protocol BookmarkBufferStorage: AnyObject { func isEmpty() -> Deferred<Maybe<Bool>> func applyRecords(_ records: [BookmarkMirrorItem]) -> Success func doneApplyingRecordsAfterDownload() -> Success func validate() -> Success func getBufferedDeletions() -> Deferred<Maybe<[(GUID, Timestamp)]>> func applyBufferCompletionOp(_ op: BufferCompletionOp, itemSources: ItemSources) -> Success // Only use for diagnostics. func synchronousBufferCount() -> Int? func getUpstreamRecordCount() -> Deferred<Int?> } public protocol MirrorItemSource: AnyObject { func getMirrorItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func prefetchMirrorItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } public protocol BufferItemSource: AnyObject { func getBufferItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func getBufferChildrenGUIDsForParent(_ guid: GUID) -> Deferred<Maybe<[GUID]>> func prefetchBufferItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } public protocol LocalItemSource: AnyObject { func getLocalItemWithGUID(_ guid: GUID) -> Deferred<Maybe<BookmarkMirrorItem>> func getLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Deferred<Maybe<[GUID: BookmarkMirrorItem]>> where T.Iterator.Element == GUID func prefetchLocalItemsWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID } open class ItemSources { open let local: LocalItemSource open let mirror: MirrorItemSource open let buffer: BufferItemSource public init(local: LocalItemSource, mirror: MirrorItemSource, buffer: BufferItemSource) { self.local = local self.mirror = mirror self.buffer = buffer } open func prefetchWithGUIDs<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID { return self.local.prefetchLocalItemsWithGUIDs(guids) >>> { self.mirror.prefetchMirrorItemsWithGUIDs(guids) } >>> { self.buffer.prefetchBufferItemsWithGUIDs(guids) } } } public struct BookmarkRoots { // These match Places on desktop. public static let RootGUID = "root________" public static let MobileFolderGUID = "mobile______" public static let MenuFolderGUID = "menu________" public static let ToolbarFolderGUID = "toolbar_____" public static let UnfiledFolderGUID = "unfiled_____" public static let FakeDesktopFolderGUID = "desktop_____" // Pseudo. Never mentioned in a real record. // This is the order we use. public static let RootChildren: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.MobileFolderGUID, ] public static let DesktopRoots: [GUID] = [ BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ] public static let Real = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, ]) public static let All = Set<GUID>([ BookmarkRoots.RootGUID, BookmarkRoots.MobileFolderGUID, BookmarkRoots.MenuFolderGUID, BookmarkRoots.ToolbarFolderGUID, BookmarkRoots.UnfiledFolderGUID, BookmarkRoots.FakeDesktopFolderGUID, ]) /** * Sync records are a horrible mess of Places-native GUIDs and Sync-native IDs. * For example: * {"id":"places", * "type":"folder", * "title":"", * "description":null, * "children":["menu________","toolbar_____", * "tags________","unfiled_____", * "jKnyPDrBQSDg","T6XK5oJMU8ih"], * "parentid":"2hYxKgBwvkEH"}" * * We thus normalize on the extended Places IDs (with underscores) for * local storage, and translate to the Sync IDs when creating an outbound * record. * We translate the record's ID and also its parent. Evidence suggests that * we don't need to translate children IDs. * * TODO: We don't create outbound records yet, so that's why there's no * translation in that direction yet! */ public static func translateIncomingRootGUID(_ guid: GUID) -> GUID { return [ "places": RootGUID, "root": RootGUID, "mobile": MobileFolderGUID, "menu": MenuFolderGUID, "toolbar": ToolbarFolderGUID, "unfiled": UnfiledFolderGUID ][guid] ?? guid } public static func translateOutgoingRootGUID(_ guid: GUID) -> GUID { return [ RootGUID: "places", MobileFolderGUID: "mobile", MenuFolderGUID: "menu", ToolbarFolderGUID: "toolbar", UnfiledFolderGUID: "unfiled" ][guid] ?? guid } /* public static let TagsFolderGUID = "tags________" public static let PinnedFolderGUID = "pinned______" */ static let RootID = 0 static let MobileID = 1 static let MenuID = 2 static let ToolbarID = 3 static let UnfiledID = 4 } /** * This partly matches Places's nsINavBookmarksService, just for sanity. * * It is further extended to support the types that exist in Sync, so we can use * this to store mirrored rows. * * These are only used at the DB layer. */ public enum BookmarkNodeType: Int { case bookmark = 1 case folder = 2 case separator = 3 case dynamicContainer = 4 case livemark = 5 case query = 6 // No microsummary: those turn into bookmarks. } public func == (lhs: BookmarkMirrorItem, rhs: BookmarkMirrorItem) -> Bool { if lhs.type != rhs.type || lhs.guid != rhs.guid || lhs.dateAdded != rhs.dateAdded || lhs.serverModified != rhs.serverModified || lhs.isDeleted != rhs.isDeleted || lhs.hasDupe != rhs.hasDupe || lhs.pos != rhs.pos || lhs.faviconID != rhs.faviconID || lhs.localModified != rhs.localModified || lhs.parentID != rhs.parentID || lhs.parentName != rhs.parentName || lhs.feedURI != rhs.feedURI || lhs.siteURI != rhs.siteURI || lhs.title != rhs.title || lhs.description != rhs.description || lhs.bookmarkURI != rhs.bookmarkURI || lhs.tags != rhs.tags || lhs.keyword != rhs.keyword || lhs.folderName != rhs.folderName || lhs.queryID != rhs.queryID { return false } if let lhsChildren = lhs.children, let rhsChildren = rhs.children { return lhsChildren == rhsChildren } return lhs.children == nil && rhs.children == nil } public struct BookmarkMirrorItem: Equatable { public let guid: GUID public let type: BookmarkNodeType public let dateAdded: Timestamp? public var serverModified: Timestamp public let isDeleted: Bool public let hasDupe: Bool public let parentID: GUID? public let parentName: String? // Livemarks. public let feedURI: String? public let siteURI: String? // Separators. let pos: Int? // Folders, livemarks, bookmarks and queries. public let title: String? let description: String? // Bookmarks and queries. let bookmarkURI: String? let tags: String? let keyword: String? // Queries. let folderName: String? let queryID: String? // Folders. public let children: [GUID]? // Internal stuff. let faviconID: Int? public let localModified: Timestamp? let syncStatus: SyncStatus? public func copyWithDateAdded(_ dateAdded: Timestamp) -> BookmarkMirrorItem { return BookmarkMirrorItem( guid: self.guid, type: self.type, dateAdded: dateAdded, serverModified: self.serverModified, isDeleted: self.isDeleted, hasDupe: self.hasDupe, parentID: self.parentID, parentName: self.parentName, feedURI: self.feedURI, siteURI: self.siteURI, pos: self.pos, title: self.title, description: self.description, bookmarkURI: self.bookmarkURI, tags: self.tags, keyword: self.keyword, folderName: self.folderName, queryID: self.queryID, children: self.children, faviconID: self.faviconID, localModified: self.localModified, syncStatus: self.syncStatus) } public func copyWithParentID(_ parentID: GUID, parentName: String?) -> BookmarkMirrorItem { return BookmarkMirrorItem( guid: self.guid, type: self.type, dateAdded: self.dateAdded, serverModified: self.serverModified, isDeleted: self.isDeleted, hasDupe: self.hasDupe, parentID: parentID, parentName: parentName, feedURI: self.feedURI, siteURI: self.siteURI, pos: self.pos, title: self.title, description: self.description, bookmarkURI: self.bookmarkURI, tags: self.tags, keyword: self.keyword, folderName: self.folderName, queryID: self.queryID, children: self.children, faviconID: self.faviconID, localModified: self.localModified, syncStatus: self.syncStatus) } // Ignores internal metadata and GUID; a pure value comparison. // Does compare child GUIDs! public func sameAs(_ rhs: BookmarkMirrorItem) -> Bool { if self.type != rhs.type || self.dateAdded != rhs.dateAdded || self.isDeleted != rhs.isDeleted || self.pos != rhs.pos || self.parentID != rhs.parentID || self.parentName != rhs.parentName || self.feedURI != rhs.feedURI || self.siteURI != rhs.siteURI || self.title != rhs.title || (self.description ?? "") != (rhs.description ?? "") || self.bookmarkURI != rhs.bookmarkURI || self.tags != rhs.tags || self.keyword != rhs.keyword || self.folderName != rhs.folderName || self.queryID != rhs.queryID { return false } if let lhsChildren = self.children, let rhsChildren = rhs.children { return lhsChildren == rhsChildren } return self.children == nil && rhs.children == nil } public func asJSON() -> JSON { return self.asJSONWithChildren(self.children) } public func asJSONWithChildren(_ children: [GUID]?) -> JSON { var out: [String: Any] = [:] out["id"] = BookmarkRoots.translateOutgoingRootGUID(self.guid) func take(_ key: String, _ val: String?) { guard let val = val else { return } out[key] = val } if self.isDeleted { out["deleted"] = true return JSON(out) } out["dateAdded"] = self.dateAdded out["hasDupe"] = self.hasDupe // TODO: this should never be nil! if let parentID = self.parentID { out["parentid"] = BookmarkRoots.translateOutgoingRootGUID(parentID) take("parentName", titleForSpecialGUID(parentID) ?? self.parentName ?? "") } func takeBookmarkFields() { take("title", self.title) take("bmkUri", self.bookmarkURI) take("description", self.description) if let tags = self.tags { let tagsJSON = JSON(parseJSON: tags) if let tagsArray = tagsJSON.array, tagsArray.every({ $0.type == SwiftyJSON.Type.string }) { out["tags"] = tagsArray } else { out["tags"] = [] } } else { out["tags"] = [] } take("keyword", self.keyword) } func takeFolderFields() { take("title", titleForSpecialGUID(self.guid) ?? self.title) take("description", self.description) if let children = children { if BookmarkRoots.RootGUID == self.guid { // Only the root contains roots, and so only its children // need to be translated. out["children"] = children.map(BookmarkRoots.translateOutgoingRootGUID) } else { out["children"] = children } } } switch self.type { case .query: out["type"] = "query" take("folderName", self.folderName) take("queryId", self.queryID) takeBookmarkFields() case .bookmark: out["type"] = "bookmark" takeBookmarkFields() case .livemark: out["type"] = "livemark" take("siteUri", self.siteURI) take("feedUri", self.feedURI) takeFolderFields() case .folder: out["type"] = "folder" takeFolderFields() case .separator: out["type"] = "separator" if let pos = self.pos { out["pos"] = pos } case .dynamicContainer: // Sigh. preconditionFailure("DynamicContainer not supported.") } return JSON(out) } // The places root is a folder but has no parentName. public static func folder(_ guid: GUID, dateAdded: Timestamp?, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, children: [GUID]) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .folder, dateAdded: dateAdded, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: children, faviconID: nil, localModified: nil, syncStatus: nil) } public static func livemark(_ guid: GUID, dateAdded: Timestamp?, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String?, description: String?, feedURI: String, siteURI: String) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .livemark, dateAdded: dateAdded, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: feedURI, siteURI: siteURI, pos: nil, title: title, description: description, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func separator(_ guid: GUID, dateAdded: Timestamp?, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, pos: Int) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .separator, dateAdded: dateAdded, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: pos, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func bookmark(_ guid: GUID, dateAdded: Timestamp?, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, URI: String, tags: String, keyword: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .bookmark, dateAdded: dateAdded, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func query(_ guid: GUID, dateAdded: Timestamp?, modified: Timestamp, hasDupe: Bool, parentID: GUID, parentName: String?, title: String, description: String?, URI: String, tags: String, keyword: String?, folderName: String?, queryID: String?) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) let parent = BookmarkRoots.translateIncomingRootGUID(parentID) return BookmarkMirrorItem(guid: id, type: .query, dateAdded: dateAdded, serverModified: modified, isDeleted: false, hasDupe: hasDupe, parentID: parent, parentName: parentName, feedURI: nil, siteURI: nil, pos: nil, title: title, description: description, bookmarkURI: URI, tags: tags, keyword: keyword, folderName: folderName, queryID: queryID, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } public static func deleted(_ type: BookmarkNodeType, guid: GUID, modified: Timestamp) -> BookmarkMirrorItem { let id = BookmarkRoots.translateIncomingRootGUID(guid) return BookmarkMirrorItem(guid: id, type: type, dateAdded: nil, serverModified: modified, isDeleted: true, hasDupe: false, parentID: nil, parentName: nil, feedURI: nil, siteURI: nil, pos: nil, title: nil, description: nil, bookmarkURI: nil, tags: nil, keyword: nil, folderName: nil, queryID: nil, children: nil, faviconID: nil, localModified: nil, syncStatus: nil) } }
mpl-2.0
b236b3500c98fb3d99d639d7afc11df5
37.355513
283
0.620421
4.911149
false
false
false
false
benlangmuir/swift
test/Sema/property_wrappers.swift
2
2739
// RUN: %target-swift-frontend -typecheck -disable-availability-checking -dump-ast %s | %FileCheck %s struct Transaction { var state: Int? } @propertyWrapper struct WrapperWithClosureArg<Value> { var wrappedValue: Value init(wrappedValue: Value, reset: @escaping (Value, inout Transaction) -> Void) { self.wrappedValue = wrappedValue } } // rdar://problem/59685601 // CHECK-LABEL: R_59685601 struct R_59685601 { // CHECK: argument_list implicit labels=wrappedValue:reset: // CHECK-NEXT: argument label=wrappedValue // CHECK-NEXT: property_wrapper_value_placeholder_expr implicit type='String' // CHECK-NEXT: opaque_value_expr implicit type='String' // CHECK-NEXT: string_literal_expr type='String' @WrapperWithClosureArg(reset: { value, transaction in transaction.state = 10 }) private var value = "hello" } @propertyWrapper struct Wrapper<Value> { var wrappedValue: Value } // CHECK-LABEL: struct_decl{{.*}}TestInitSubscript struct TestInitSubscript { enum Color: CaseIterable { case pink } // CHECK: argument_list labels=wrappedValue: // CHECK-NEXT: argument label=wrappedValue // CHECK-NEXT: subscript_expr type='TestInitSubscript.Color' // CHECK: argument_list implicit // CHECK-NEXT: argument // CHECK-NOT: property_wrapper_value_placeholder_expr implicit type='Int' // CHECK: integer_literal_expr type='Int' @Wrapper(wrappedValue: Color.allCases[0]) var color: Color } @propertyWrapper public class SR_15940Bar<Value> { private var _value: Value public var wrappedValue: Value { get { _value } set { _value = newValue } } public init(wrappedValue value: @autoclosure @escaping () -> Value) { self._value = value() } } // CHECK-LABEL: struct_decl{{.*}}SR_15940_A struct SR_15940_A { // CHECK: argument_list implicit labels=wrappedValue: // CHECK-NEXT: argument label=wrappedValue // CHECK-NEXT: autoclosure_expr implicit type='() -> Bool?' discriminator=0 captures=(<opaque_value> ) escaping // CHECK: autoclosure_expr implicit type='() -> Bool?' discriminator=1 escaping @SR_15940Bar var a: Bool? } // CHECK-LABEL: struct_decl{{.*}}SR_15940_B struct SR_15940_B { // CHECK: argument_list implicit labels=wrappedValue: // CHECK-NEXT: argument label=wrappedValue // CHECK-NEXT: autoclosure_expr implicit type='() -> Bool' location={{.*}}.swift:[[@LINE+2]]:30 range=[{{.+}}] discriminator=0 captures=(<opaque_value> ) escaping // CHECK: autoclosure_expr implicit type='() -> Bool' location={{.*}}.swift:[[@LINE+1]]:30 range=[{{.+}}] discriminator=1 escaping @SR_15940Bar var b: Bool = false }
apache-2.0
a2e4f64769dd2061c367b3025e01cead
32
168
0.669222
3.809458
false
false
false
false
McNight/ChronoDiderot
ChronoDiderot/Tabs/EDTViewController.swift
1
4631
// // EDTViewController.swift // ChronoDiderot // // Created by McNight on 16/10/2015. // Copyright © 2015 McNight. All rights reserved. // import UIKit import CDKit import SVProgressHUD extension NSData { func sha1() -> String { var digest = [UInt8](count:Int(CC_SHA1_DIGEST_LENGTH), repeatedValue: 0) CC_SHA1(self.bytes, CC_LONG(self.length), &digest) let hexBytes = digest.map { String(format: "%02hhx", $0) } return hexBytes.joinWithSeparator("") } } class EDTViewController: UITableViewController { @IBOutlet weak var lastImportationCell: UITableViewCell! @IBOutlet weak var numberOfEventsCell: UITableViewCell! @IBOutlet weak var refreshBarButtonItem: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() let exporter = CDExporter() exporter.requestAuthorization { authorized, error in if authorized { if CDHelpers.sharedHelper.customCalendarCreated() == false { exporter.createCalendar() } } else { SVProgressHUD.showErrorWithStatus("Erreur lors de l'authorisation... \(error?.localizedDescription)") } } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) self.updateUserInterface() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func launchDownloadAndImportation() { SVProgressHUD.setDefaultMaskType(.Gradient) SVProgressHUD.showWithStatus("Téléchargement en cours...") let downloader = CDDownloader() downloader.startDownload { formerData -> Void in if let data = formerData { SVProgressHUD.showWithStatus("Importation en cours...") let hash = data.sha1() if let previousHash = CDHelpers.sharedHelper.downloadedDataHash() where previousHash == hash { if let lastParsedDate = CDHelpers.sharedHelper.eventsParsedDate() where NSCalendar.currentCalendar().isDate(lastParsedDate, inSameDayAsDate: NSDate()) { SVProgressHUD.showInfoWithStatus("Rien n'a changé !") self.refreshBarButtonItem.enabled = true return } } CDHelpers.sharedHelper.setDownloadedDataHash(hash) let scraper = CDScraper() scraper.startScrapingData(data) { events in let numberOfEvents = events.count CDHelpers.sharedHelper.storeEventsParsedCount(numberOfEvents) let exporter = CDExporter() let exporterResult = exporter.createOrUpdateEvents(events) switch exporterResult { case .CalendarNotCreated, .CalendarNotFound: exporter.createCalendar() exporter.createOrUpdateEvents(events) SVProgressHUD.showSuccessWithStatus("Événements importés avec succès !") case .FailureCreate: SVProgressHUD.showErrorWithStatus("Erreur lors de la création des événements") case .FailureUpdate: SVProgressHUD.showErrorWithStatus("Erreur lors de la mise à jour des événements") case .SuccessCreate: SVProgressHUD.showSuccessWithStatus("Événements importés avec succès !") case .SuccessUpdate: SVProgressHUD.showSuccessWithStatus("Événements mis à jour avec succès !") case .NothingSpecial: SVProgressHUD.showInfoWithStatus("Ce message ne devrait pas s'afficher...") } self.updateUserInterface() } } else { SVProgressHUD.showErrorWithStatus("Une erreur est survenue...") } } } func updateUserInterface() { self.refreshBarButtonItem.enabled = true let lastParsedDate = CDHelpers.sharedHelper.eventsParsedDate() let eventsParsedCount = CDHelpers.sharedHelper.eventsParsedCount() let lastImportationCellText = lastParsedDate != nil ? CDHelpers.dateFormatter.stringFromDate(lastParsedDate!) : "Jamais" let numberOfEventsCellText = eventsParsedCount != -1 ? "\(eventsParsedCount) événéments" : "Aucun" self.lastImportationCell.detailTextLabel!.text = lastImportationCellText self.numberOfEventsCell.detailTextLabel!.text = numberOfEventsCellText } // MARK: - Actions @IBAction func refreshBarButtonItemPressed(sender: UIBarButtonItem) { sender.enabled = false self.launchDownloadAndImportation() } // MARK: - Table View Delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { if indexPath.section == 1 && indexPath.row == 0 { let URLString = CDHelpers.sharedHelper.CDM1InformatiqueURL let URL = NSURL(string: URLString)! UIApplication.sharedApplication().openURL(URL) } tableView.deselectRowAtIndexPath(indexPath, animated: true) } }
mit
32cb39c0a11ea43f4394907591f27018
30.121622
122
0.727312
4.076106
false
false
false
false
benlangmuir/swift
test/Serialization/autolinking-inlinable-inferred.swift
5
7163
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_public.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_public.swiftmodule -module-link-name autolinking_public -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_other.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_other.swiftmodule -module-link-name autolinking_other -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_private.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_private.swiftmodule -module-link-name autolinking_private -I %t -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_other2.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_other2.swiftmodule -module-link-name autolinking_other2 -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_indirect.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_indirect.swiftmodule -module-link-name autolinking_indirect -I %t -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_implementation_only.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_implementation_only.swiftmodule -module-link-name autolinking_implementation_only_BAD -I %t -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module %S/Inputs/autolinking_module_inferred.swift -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-module-path %t/autolinking_module_inferred.swiftmodule -module-link-name autolinking_module_inferred -I %t -swift-version 4 // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D NORMAL_IMPORT | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -implicit-check-not BAD %s // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_IMPORT | %FileCheck -check-prefix CHECK -check-prefix CHECK-IMPL_ONLY -implicit-check-not BAD %s // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D NORMAL_AND_IMPLEMENTATION_ONLY | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -implicit-check-not BAD %s // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_AND_NORMAL | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -implicit-check-not BAD %s // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D EXPORTED_AND_IMPLEMENTATION_ONLY | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -implicit-check-not BAD %s // RUN: %target-swift-frontend -disable-implicit-concurrency-module-import -disable-implicit-string-processing-module-import -emit-ir %s -I %t -swift-version 4 -enable-objc-interop -D IMPLEMENTATION_ONLY_AND_EXPORTED | %FileCheck -check-prefix CHECK -check-prefix CHECK-NORMAL -implicit-check-not BAD %s // Linux uses a different autolinking mechanism, based on // swift-autolink-extract. This file tests the Darwin mechanism. /// UNSUPPORTED: autolink-extract #if NORMAL_IMPORT import autolinking_module_inferred #elseif IMPLEMENTATION_ONLY_IMPORT @_implementationOnly import autolinking_module_inferred #elseif NORMAL_AND_IMPLEMENTATION_ONLY import autolinking_module_inferred @_implementationOnly import autolinking_module_inferred #elseif IMPLEMENTATION_ONLY_AND_NORMAL @_implementationOnly import autolinking_module_inferred import autolinking_module_inferred #elseif EXPORTED_AND_IMPLEMENTATION_ONLY @_exported import autolinking_module_inferred @_implementationOnly import autolinking_module_inferred #elseif IMPLEMENTATION_ONLY_AND_EXPORTED @_implementationOnly import autolinking_module_inferred @_exported import autolinking_module_inferred #else #error("must pick an import mode to test") #endif bfunc() // CHECK: !llvm.linker.options = !{ // CHECK-NORMAL-SAME: [[MODULE:![0-9]+]], // CHECK-NORMAL-SAME: [[PUBLIC:![0-9]+]], // CHECK-NORMAL-SAME: [[SWIFTONONESUPPORT:![0-9]+]], // CHECK-NORMAL-SAME: [[SWIFTCORE:![0-9]+]], // This is the same set as the above, just in a different order due to a // different traversal of the transitive import graph. // CHECK-IMPL_ONLY-SAME: [[SWIFTONONESUPPORT:![0-9]+]], // CHECK-IMPL_ONLY-SAME: [[SWIFTCORE:![0-9]+]], // CHECK-IMPL_ONLY-SAME: [[MODULE:![0-9]+]], // CHECK-IMPL_ONLY-SAME: [[PUBLIC:![0-9]+]], // CHECK-SAME: [[PRIVATE:![0-9]+]], // CHECK-SAME: [[OTHER:![0-9]+]], // CHECK-SAME: [[INDIRECT:![0-9]+]], // CHECK-SAME: [[OTHER2:![0-9]+]], // CHECK-SAME: [[OBJC:![0-9]+]] // CHECK-SAME: } // CHECK-DAG: [[MODULE]] = !{!{{"-lautolinking_module_inferred"|"/DEFAULTLIB:autolinking_module_inferred.lib"}}} // CHECK-DAG: [[PUBLIC]] = !{!{{"-lautolinking_public"|"/DEFAULTLIB:autolinking_public.lib"}}} // CHECK-DAG: [[SWIFTONONESUPPORT]] = !{!{{"-lswiftSwiftOnoneSupport"|"/DEFAULTLIB:swiftSwiftOnoneSupport.lib"}}} // CHECK-DAG: [[SWIFTCORE]] = !{!{{"-lswiftCore"|"/DEFAULTLIB:swiftCore.lib"}}} // CHECK-DAG: [[OTHER]] = !{!{{"-lautolinking_other"|"/DEFAULTLIB:autolinking_other.lib"}}} // CHECK-DAG: [[OTHER2]] = !{!{{"-lautolinking_other2"|"/DEFAULTLIB:autolinking_other2.lib"}}} // CHECK-DAG: [[OBJC]] = !{!{{"-lobjc"|"/DEFAULTLIB:objc.lib"}}} // We don't actually care about these two. As long as we autolink the libraries // that get used, we're okay. // CHECK-DAG: [[PRIVATE]] = !{!{{"-lautolinking_private"|"/DEFAULTLIB:autolinking_private.lib"}}} // CHECK-DAG: [[INDIRECT]] = !{!{{"-lautolinking_indirect"|"/DEFAULTLIB:autolinking_indirect.lib"}}}
apache-2.0
0345cad4d7802f2cdff7080e7c62c79f
83.270588
421
0.76951
3.544285
false
false
false
false
satyamexilant/TimeApp
Model-2.swift
1
11196
import Foundation typealias PersonType = Person.PersonType //MARK: Person Model class CitsEvent { let createdDateTime: Date let updatedDateTime: Date init (_ createdDateTime: Date, updatedDateTime: Date) { self.createdDateTime = createdDateTime self.updatedDateTime = updatedDateTime } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Person Model class Person { enum PersonType { case Student case Trainer } let personId: String let firstName: String let lastName: String let phoneNumber: String let personType: PersonType let event: CitsEvent? init(_ personId: String, _ firstName: String, _ lastName: String,_ phoneNumber: String, _ personType: PersonType , _ event: CitsEvent? ) { self.personId = personId self.firstName = firstName self.lastName = lastName self.phoneNumber = phoneNumber self.personType = personType self.event = event } required init(withData: Any?) throws { guard let _ = withData else { return } } } //Person extension extension Person { //add any methods here or computed properties. } //MARK: Profile Model class Profile { var person: Person? var personId: String var profileId: Int? var skillSet: [String]? var mailId: String var profileImageUrl: String var event : CitsEvent? init(_ person: Person?, _ profileId: Int?, _ skillSet: [String] = [""], _ mailId: String = "", _ profileImageUrl: String = "", _ event: CitsEvent?) { self.person = person self.personId = person?.personId ?? "" self.profileId = profileId self.skillSet = skillSet self.mailId = mailId self.profileImageUrl = profileImageUrl self.event = event } convenience init(_ person: Person?, _ skillSet: [String] = [""],_ mailId: String = "",_ profileImageUrl: String = "",_ event: CitsEvent?) { self.init(person,nil,skillSet,mailId,profileImageUrl,event) } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Profile extension extension Profile { //add any methods here or computed properties. } //MARK: Group Model class Group { enum GroupType { case online case classRoom } var groupId: Int? var groupName: String var groupDescription: String var groupType: GroupType var personIds: [String] //They are personId's and in future we could have more than one admin's for a for a group var event : CitsEvent? init(_ groupId: Int?, _ groupName: String, _ groupDescription: String, adminId personIds: [String],_ groupType: GroupType, _ event: CitsEvent) { self.groupId = groupId self.groupName = groupName self.groupDescription = groupDescription self.groupType = groupType self.personIds = personIds self.event = event } convenience init(_ groupName: String, _ groupDescription: String, adminId personIds: [String],_ groupType: GroupType, _ event: CitsEvent) { self.init(nil,groupName,groupDescription,adminId:personIds,groupType,event) } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Group extension extension Group{ //add any methods here or computed properties. } //MARK: UsersGroup Model class UsersGroup { var person: Person? var personId:String var groupId:Int var personType:Person.PersonType init(_ personId:String,_ groupId: Int, _ personType: PersonType) { self.personId = personId self.groupId = groupId self.personType = personType } init (_ person: Person,_ groupId: Int, _ personType: PersonType) { self.person = person self.personId = person.personId self.groupId = groupId self.personType = personType } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: UsersGroup extension extension UsersGroup{ //add any methods here or computed properties. } //MARK: Session Model class Session { let sessionId: Int? var name: String var dateTime: Date var latitude: Double var longitude: Double var type: String var event: CitsEvent init(id: Int?,name: String,dateTime: Date, location latitude: Double,location longitude: Double, type: String, on event: CitsEvent) { self.sessionId = id self.name = name self.dateTime = dateTime self.latitude = latitude self.longitude = longitude self.type = type self.event = event } convenience init(name: String,dateTime: Date, location latitude: Double,location longitude: Double, type: String, on event: CitsEvent) { self.init(id: nil,name: name,dateTime: dateTime,location: latitude,location: longitude,type: type,on: event) } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Session extension extension Session{ //add any methods here or computed properties. } //MARK: SessionMaterial Model class SessionMaterial { let session: Session let materialId: Int var materialName: String var materialUrl: String let uploadedDate: Date let fileType: String let fileSize: String init( _ session: Session ,id materialId: Int, name materialName: String, url materialUrl: String,on uploadedDate:Date,_ fileType:String, _ fileSize:String ) { self.session = session self.materialId = materialId self.materialName = materialName self.materialUrl = materialUrl self.uploadedDate = uploadedDate self.fileType = fileType self.fileSize = fileSize } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: SessionMaterial extension extension SessionMaterial{ //add any methods here or computed properties. } //MARK: User Session Model class UserSession { var person:Person var sessionId:Int init(_ person: Person, _ sessionId: Int) { self.person = person self.sessionId = sessionId } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Session Members class SessionMembers { let session: Session? let personId: String let personType: PersonType let mailId: String init(_ session: Session?,_ personId: String, _ personType: PersonType, _ mailId: String) { self.session = session self.personId = personId self.personType = personType self.mailId = mailId } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: UserSession extension extension UserSession{ //add any methods here or computed properties. } //MARK: UserRequests Model class UserRequests { enum RequestType { case reqToJoinGroup case reqToJoinSession case inviteToJoinSession case inviteToJoinGroup } var requestor: Person? var receiver: Person? var session: Session? let requestId: Int? var group: Group let requestorId: String let receiverId: String var requestType: RequestType init(_ requestId: Int?,_ requestor: Person, _ receiver: Person ,_ session: Session,_ group:Group, _ requestType: RequestType) { self.requestor = requestor self.receiver = receiver self.session = session self.group = group self.requestId = requestId self.requestorId = requestor.personId self.receiverId = receiver.personId self.requestType = requestType } convenience init(_ requestor: Person, _ receiver: Person ,_ session: Session,_ group:Group, _ requestType: RequestType) { self.init (nil,requestor,receiver,session,group,requestType) } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: UserRequests extension extension UserRequests{ //add any methods here or computed properties. } //MARK: UserActivity Model class UserActivity { let person: Person let personId: String let activityId:Int? let activityTime:String let activity:Activity let session: Session init(_ activityId: Int?,_ person: Person , _ activityTime: String, _ activity: Activity, _ session: Session) { self.activityId = activityId self.person = person self.personId = person.personId self.activityTime = activityTime self.activity = activity self.session = session } convenience init( _ person: Person ,_ activityTime: String, _ activity: Activity, _ session : Session) { self.init(nil,person,activityTime,activity,session) } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: UserActivity extension extension UserActivity{ //add any methods here or computed properties. } //MARK: Activity Model class Activity { enum ActivityType { case uploadedMaterial } let activityType: ActivityType let activityTime: String let activityDescription: String init(_ activityType: ActivityType, _ activityTime: String, _ activityDescription: String) { self.activityType = activityType self.activityTime = activityTime self.activityDescription = activityDescription } required init(withData: Any?) throws { guard let _ = withData else { return } } } //MARK: Activity extension extension Activity{ //add any methods here or computed properties. }
mit
b305c6a964463bff37c6a3fda632b767
21.373695
162
0.576009
4.708158
false
false
false
false
khizkhiz/swift
benchmark/single-source/ProtocolDispatch.swift
2
682
//===--- ProtocolDispatch.swift -------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import TestsUtils @inline(never) public func run_ProtocolDispatch(N: Int) { let x = someProtocolFactory() for _ in 0...1000000 * N { x.getValue() } }
apache-2.0
d3e662bb122a118129d63766b096665d
27.416667
80
0.573314
4.671233
false
false
false
false
Ehrippura/firefox-ios
Client/Frontend/Home/RemoteTabsPanel.swift
1
27503
/* 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 import Account import Shared import SnapKit import Storage import Sync import XCGLogger private let log = Logger.browserLogger private struct RemoteTabsPanelUX { static let HeaderHeight = SiteTableViewControllerUX.RowHeight // Not HeaderHeight! static let RowHeight = SiteTableViewControllerUX.RowHeight static let HeaderBackgroundColor = UIColor(rgb: 0xf8f8f8) static let EmptyStateTitleTextColor = UIColor.darkGray static let EmptyStateInstructionsTextColor = UIColor.gray static let EmptyStateInstructionsWidth = 170 static let EmptyStateTopPaddingInBetweenItems: CGFloat = 15 // UX TODO I set this to 8 so that it all fits on landscape static let EmptyStateSignInButtonColor = UIColor(red: 0.3, green: 0.62, blue: 1, alpha: 1) static let EmptyStateSignInButtonTitleColor = UIColor.white static let EmptyStateSignInButtonCornerRadius: CGFloat = 4 static let EmptyStateSignInButtonHeight = 44 static let EmptyStateSignInButtonWidth = 200 // Backup and active strings added in Bug 1205294. static let EmptyStateInstructionsSyncTabsPasswordsBookmarksString = NSLocalizedString("Sync your tabs, bookmarks, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsSyncTabsPasswordsString = NSLocalizedString("Sync your tabs, passwords and more.", comment: "Text displayed when the Sync home panel is empty, describing the features provided by Sync to invite the user to log in.") static let EmptyStateInstructionsGetTabsBookmarksPasswordsString = NSLocalizedString("Get your open tabs, bookmarks, and passwords from your other devices.", comment: "A re-worded offer about Sync, displayed when the Sync home panel is empty, that emphasizes one-way data transfer, not syncing.") static let HistoryTableViewHeaderChevronInset: CGFloat = 10 static let HistoryTableViewHeaderChevronSize: CGFloat = 20 static let HistoryTableViewHeaderChevronLineWidth: CGFloat = 3.0 } private let RemoteClientIdentifier = "RemoteClient" private let RemoteTabIdentifier = "RemoteTab" class RemoteTabsPanel: UIViewController, HomePanel { weak var homePanelDelegate: HomePanelDelegate? fileprivate lazy var tableViewController: RemoteTabsTableViewController = RemoteTabsTableViewController() fileprivate lazy var historyBackButton: HistoryBackButton = { let button = HistoryBackButton() button.addTarget(self, action: #selector(RemoteTabsPanel.historyBackButtonWasTapped), for: .touchUpInside) return button }() var profile: Profile! init() { super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(RemoteTabsPanel.notificationReceived(_:)), name: NotificationProfileDidFinishSyncing, object: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() tableViewController.profile = profile tableViewController.remoteTabsPanel = self view.backgroundColor = UIConstants.PanelBackgroundColor addChildViewController(tableViewController) self.view.addSubview(tableViewController.view) self.view.addSubview(historyBackButton) historyBackButton.snp.makeConstraints { make in make.top.left.right.equalTo(self.view) make.height.equalTo(50) make.bottom.equalTo(tableViewController.view.snp.top) } tableViewController.view.snp.makeConstraints { make in make.top.equalTo(historyBackButton.snp.bottom) make.left.right.bottom.equalTo(self.view) } tableViewController.didMove(toParentViewController: self) } deinit { NotificationCenter.default.removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil) NotificationCenter.default.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil) } func notificationReceived(_ notification: Notification) { switch notification.name { case NotificationFirefoxAccountChanged, NotificationProfileDidFinishSyncing: DispatchQueue.main.async { print(notification.name) self.tableViewController.refreshTabs() } break default: // no need to do anything at all log.warning("Received unexpected notification \(notification.name)") break } } @objc fileprivate func historyBackButtonWasTapped(_ gestureRecognizer: UITapGestureRecognizer) { _ = self.navigationController?.popViewController(animated: true) } } enum RemoteTabsError { case notLoggedIn case noClients case noTabs case failedToSync func localizedString() -> String { switch self { case .notLoggedIn: return "" // This does not have a localized string because we have a whole specific screen for it. case .noClients: return Strings.EmptySyncedTabsPanelNullStateDescription case .noTabs: return NSLocalizedString("You don’t have any tabs open in Firefox on your other devices.", comment: "Error message in the remote tabs panel") case .failedToSync: return NSLocalizedString("There was a problem accessing tabs from your other devices. Try again in a few moments.", comment: "Error message in the remote tabs panel") } } } protocol RemoteTabsPanelDataSource: UITableViewDataSource, UITableViewDelegate { } class RemoteTabsPanelClientAndTabsDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? fileprivate var clientAndTabs: [ClientAndTabs] init(homePanel: HomePanel, clientAndTabs: [ClientAndTabs]) { self.homePanel = homePanel self.clientAndTabs = clientAndTabs } func numberOfSections(in tableView: UITableView) -> Int { return self.clientAndTabs.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.clientAndTabs[section].tabs.count } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return RemoteTabsPanelUX.HeaderHeight } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let clientTabs = self.clientAndTabs[section] let client = clientTabs.client let view = tableView.dequeueReusableHeaderFooterView(withIdentifier: RemoteClientIdentifier) as! TwoLineHeaderFooterView view.frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: RemoteTabsPanelUX.HeaderHeight) view.textLabel?.text = client.name view.contentView.backgroundColor = RemoteTabsPanelUX.HeaderBackgroundColor /* * A note on timestamps. * We have access to two timestamps here: the timestamp of the remote client record, * and the set of timestamps of the client's tabs. * Neither is "last synced". The client record timestamp changes whenever the remote * client uploads its record (i.e., infrequently), but also whenever another device * sends a command to that client -- which can be much later than when that client * last synced. * The client's tabs haven't necessarily changed, but it can still have synced. * Ideally, we should save and use the modified time of the tabs record itself. * This will be the real time that the other client uploaded tabs. */ let timestamp = clientTabs.approximateLastSyncTime() let label = NSLocalizedString("Last synced: %@", comment: "Remote tabs last synced time. Argument is the relative date string.") view.detailTextLabel?.text = String(format: label, Date.fromTimestamp(timestamp).toRelativeTimeString()) let image: UIImage? if client.type == "desktop" { image = UIImage(named: "deviceTypeDesktop") image?.accessibilityLabel = NSLocalizedString("computer", comment: "Accessibility label for Desktop Computer (PC) image in remote tabs list") } else { image = UIImage(named: "deviceTypeMobile") image?.accessibilityLabel = NSLocalizedString("mobile device", comment: "Accessibility label for Mobile Device image in remote tabs list") } view.imageView.image = image view.mergeAccessibilityLabels() return view } fileprivate func tabAtIndexPath(_ indexPath: IndexPath) -> RemoteTab { return clientAndTabs[indexPath.section].tabs[indexPath.item] } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: RemoteTabIdentifier, for: indexPath) as! TwoLineTableViewCell let tab = tabAtIndexPath(indexPath) cell.setLines(tab.title, detailText: tab.URL.absoluteString) // TODO: Bug 1144765 - Populate image with cached favicons. return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let tab = tabAtIndexPath(indexPath) if let homePanel = self.homePanel { // It's not a bookmark, so let's call it Typed (which means History, too). homePanel.homePanelDelegate?.homePanel(homePanel, didSelectURL: tab.URL, visitType: VisitType.typed) } } } // MARK: - class RemoteTabsPanelErrorDataSource: NSObject, RemoteTabsPanelDataSource { weak var homePanel: HomePanel? var error: RemoteTabsError var notLoggedCell: UITableViewCell? init(homePanel: HomePanel, error: RemoteTabsError) { self.homePanel = homePanel self.error = error self.notLoggedCell = nil } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let cell = self.notLoggedCell { cell.updateConstraints() } return tableView.bounds.height } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { // Making the footer height as small as possible because it will disable button tappability if too high. return 1 } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return UIView() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch error { case .notLoggedIn: let cell = RemoteTabsNotLoggedInCell(homePanel: homePanel) self.notLoggedCell = cell return cell default: let cell = RemoteTabsErrorCell(error: self.error) self.notLoggedCell = nil return cell } } } // MARK: - class RemoteTabsErrorCell: UITableViewCell { static let Identifier = "RemoteTabsErrorCell" init(error: RemoteTabsError) { super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) separatorInset = UIEdgeInsets(top: 0, left: 1000, bottom: 0, right: 0) let containerView = UIView() contentView.addSubview(containerView) let imageView = UIImageView() imageView.image = UIImage(named: "emptySync") containerView.addSubview(imageView) imageView.snp.makeConstraints { (make) -> Void in make.top.equalTo(containerView) make.centerX.equalTo(containerView) } let titleLabel = UILabel() titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = NSTextAlignment.center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor containerView.addSubview(titleLabel) let instructionsLabel = UILabel() instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = error.localizedString() instructionsLabel.textAlignment = NSTextAlignment.center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 containerView.addSubview(instructionsLabel) titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(imageView) } instructionsLabel.snp.makeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems / 2) make.centerX.equalTo(containerView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } containerView.snp.makeConstraints { make in // Let the container wrap around the content make.top.equalTo(imageView.snp.top) make.left.bottom.right.equalTo(instructionsLabel) // And then center it in the overlay view that sits on top of the UITableView make.centerX.equalTo(contentView) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView.snp.centerY).offset(HomePanelUX.EmptyTabContentOffset).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).offset(20).priority(1000) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - class RemoteTabsNotLoggedInCell: UITableViewCell { static let Identifier = "RemoteTabsNotLoggedInCell" var homePanel: HomePanel? var instructionsLabel: UILabel var signInButton: UIButton var titleLabel: UILabel var emptyStateImageView: UIImageView init(homePanel: HomePanel?) { let titleLabel = UILabel() let instructionsLabel = UILabel() let signInButton = UIButton() let imageView = UIImageView() self.instructionsLabel = instructionsLabel self.signInButton = signInButton self.titleLabel = titleLabel self.emptyStateImageView = imageView super.init(style: .default, reuseIdentifier: RemoteTabsErrorCell.Identifier) self.homePanel = homePanel let createAnAccountButton = UIButton(type: .system) imageView.image = UIImage(named: "emptySync") contentView.addSubview(imageView) titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont titleLabel.text = Strings.EmptySyncedTabsPanelStateTitle titleLabel.textAlignment = NSTextAlignment.center titleLabel.textColor = RemoteTabsPanelUX.EmptyStateTitleTextColor contentView.addSubview(titleLabel) instructionsLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight instructionsLabel.text = Strings.EmptySyncedTabsPanelStateDescription instructionsLabel.textAlignment = NSTextAlignment.center instructionsLabel.textColor = RemoteTabsPanelUX.EmptyStateInstructionsTextColor instructionsLabel.numberOfLines = 0 contentView.addSubview(instructionsLabel) signInButton.backgroundColor = RemoteTabsPanelUX.EmptyStateSignInButtonColor signInButton.setTitle(NSLocalizedString("Sign in", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState()) signInButton.setTitleColor(RemoteTabsPanelUX.EmptyStateSignInButtonTitleColor, for: UIControlState()) signInButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.subheadline) signInButton.layer.cornerRadius = RemoteTabsPanelUX.EmptyStateSignInButtonCornerRadius signInButton.clipsToBounds = true signInButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELsignIn), for: UIControlEvents.touchUpInside) contentView.addSubview(signInButton) createAnAccountButton.setTitle(NSLocalizedString("Create an account", comment: "See http://mzl.la/1Qtkf0j"), for: UIControlState()) createAnAccountButton.titleLabel?.font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.caption1) createAnAccountButton.addTarget(self, action: #selector(RemoteTabsNotLoggedInCell.SELcreateAnAccount), for: UIControlEvents.touchUpInside) contentView.addSubview(createAnAccountButton) imageView.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(instructionsLabel) // Sets proper top constraint for iPhone 6 in portait and for iPad. make.centerY.equalTo(contentView).offset(HomePanelUX.EmptyTabContentOffset + 30).priority(100) // Sets proper top constraint for iPhone 4, 5 in portrait. make.top.greaterThanOrEqualTo(contentView.snp.top).priority(1000) } titleLabel.snp.makeConstraints { make in make.top.equalTo(imageView.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(imageView) } createAnAccountButton.snp.makeConstraints { (make) -> Void in make.centerX.equalTo(signInButton) make.top.equalTo(signInButton.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc fileprivate func SELsignIn() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToSignIn(homePanel) } } @objc fileprivate func SELcreateAnAccount() { if let homePanel = self.homePanel { homePanel.homePanelDelegate?.homePanelDidRequestToCreateAccount(homePanel) } } override func updateConstraints() { if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) && !(DeviceInfo.deviceModel().range(of: "iPad") != nil) { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.left.lessThanOrEqualTo(contentView.snp.left).offset(80).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.right.lessThanOrEqualTo(contentView.snp.centerX).offset(-30).priority(1000) } signInButton.snp.remakeConstraints { make in make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) make.centerY.equalTo(emptyStateImageView).offset(2*RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) // Sets proper landscape layout for bigger phones: iPhone 6 and on. make.right.greaterThanOrEqualTo(contentView.snp.right).offset(-70).priority(100) // Sets proper landscape layout for smaller phones: iPhone 4 & 5. make.left.greaterThanOrEqualTo(contentView.snp.centerX).offset(10).priority(1000) } } else { instructionsLabel.snp.remakeConstraints { make in make.top.equalTo(titleLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.centerX.equalTo(contentView) make.width.equalTo(RemoteTabsPanelUX.EmptyStateInstructionsWidth) } signInButton.snp.remakeConstraints { make in make.centerX.equalTo(contentView) make.top.equalTo(instructionsLabel.snp.bottom).offset(RemoteTabsPanelUX.EmptyStateTopPaddingInBetweenItems) make.height.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonHeight) make.width.equalTo(RemoteTabsPanelUX.EmptyStateSignInButtonWidth) } } super.updateConstraints() } } fileprivate class RemoteTabsTableViewController: UITableViewController { weak var remoteTabsPanel: RemoteTabsPanel? var profile: Profile! var tableViewDelegate: RemoteTabsPanelDataSource? { didSet { tableView.dataSource = tableViewDelegate tableView.delegate = tableViewDelegate } } fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = { return UILongPressGestureRecognizer(target: self, action: #selector(RemoteTabsTableViewController.longPress(_:))) }() override func viewDidLoad() { super.viewDidLoad() tableView.addGestureRecognizer(longPressRecognizer) tableView.register(TwoLineHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: RemoteClientIdentifier) tableView.register(TwoLineTableViewCell.self, forCellReuseIdentifier: RemoteTabIdentifier) tableView.rowHeight = RemoteTabsPanelUX.RowHeight tableView.separatorInset = UIEdgeInsets.zero tableView.delegate = nil tableView.dataSource = nil refreshControl = UIRefreshControl() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) refreshControl?.addTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged) refreshTabs() } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) refreshControl?.removeTarget(self, action: #selector(RemoteTabsTableViewController.refreshTabs), for: .valueChanged) } fileprivate func startRefreshing() { if let refreshControl = self.refreshControl { let height = -refreshControl.bounds.size.height tableView.setContentOffset(CGPoint(x: 0, y: height), animated: true) refreshControl.beginRefreshing() } } func endRefreshing() { if self.refreshControl?.isRefreshing ?? false { self.refreshControl?.endRefreshing() } self.tableView.isScrollEnabled = true self.tableView.reloadData() } func updateDelegateClientAndTabData(_ clientAndTabs: [ClientAndTabs]) { guard let remoteTabsPanel = remoteTabsPanel else { return } if clientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noClients) } else { let nonEmptyClientAndTabs = clientAndTabs.filter { $0.tabs.count > 0 } if nonEmptyClientAndTabs.count == 0 { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .noTabs) } else { self.tableViewDelegate = RemoteTabsPanelClientAndTabsDataSource(homePanel: remoteTabsPanel, clientAndTabs: nonEmptyClientAndTabs) tableView.allowsSelection = true } } } @objc fileprivate func refreshTabs() { guard let remoteTabsPanel = remoteTabsPanel else { return } assert(Thread.isMainThread) tableView.isScrollEnabled = false tableView.allowsSelection = false tableView.tableFooterView = UIView(frame: CGRect.zero) // Short circuit if the user is not logged in if !profile.hasSyncableAccount() { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .notLoggedIn) self.endRefreshing() return } self.profile.getCachedClientsAndTabs().uponQueue(DispatchQueue.main) { result in if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } // Fetch the tabs from the cloud if it has been more than 5 seconds since the last sync. let lastSyncTime = self.profile.prefs.timestampForKey(PrefsKeys.KeyLastRemoteTabSyncTime) ?? 0 if Date.now() > lastSyncTime && Date.now() - lastSyncTime > OneSecondInMilliseconds * 5 { self.startRefreshing() self.profile.getClientsAndTabs().uponQueue(DispatchQueue.main) { result in // We set the last sync time to now, regardless of whether the sync was successful, to avoid trying to sync over // and over again in cases whether the client is unable to sync (e.g. when there is no network connectivity). self.profile.prefs.setTimestamp(Date.now(), forKey: PrefsKeys.KeyLastRemoteTabSyncTime) if let clientAndTabs = result.successValue { self.updateDelegateClientAndTabData(clientAndTabs) } self.endRefreshing() } } else { // If we failed before and didn't sync, show the failure delegate if let _ = result.failureValue { self.tableViewDelegate = RemoteTabsPanelErrorDataSource(homePanel: remoteTabsPanel, error: .failedToSync) } self.endRefreshing() } } } @objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) { guard longPressGestureRecognizer.state == UIGestureRecognizerState.began else { return } let touchPoint = longPressGestureRecognizer.location(in: tableView) guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return } presentContextMenu(for: indexPath) } } extension RemoteTabsTableViewController: HomePanelContextMenu { func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) { guard let contextMenu = completionHandler() else { return } self.present(contextMenu, animated: true, completion: nil) } func getSiteDetails(for indexPath: IndexPath) -> Site? { guard let tab = (tableViewDelegate as? RemoteTabsPanelClientAndTabsDataSource)?.tabAtIndexPath(indexPath) else { return nil } return Site(url: String(describing: tab.URL), title: tab.title) } func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? { return getDefaultContextMenuActions(for: site, homePanelDelegate: remoteTabsPanel?.homePanelDelegate) } }
mpl-2.0
2fd5cf74813bf72344776c53d54ded0c
43.717073
300
0.700847
5.367096
false
false
false
false
insidegui/WWDC
Packages/ConfCore/ConfCore/ContentsResponse.swift
1
1938
// // ContentsResponse.swift // WWDC // // Created by Guilherme Rambo on 21/02/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Foundation public struct ContentsResponse: Decodable { public let events: [Event] public let rooms: [Room] public let tracks: [Track] public let resources: [RelatedResource] public let instances: [SessionInstance] public let sessions: [Session] init(events: [Event], rooms: [Room], tracks: [Track], resources: [RelatedResource], instances: [SessionInstance], sessions: [Session]) { self.events = events self.rooms = rooms self.resources = resources self.tracks = tracks self.instances = instances self.sessions = sessions } // MARK: - Decodable private enum CodingKeys: String, CodingKey { case response, rooms, tracks, sessions, events, contents, resources } public init(from decoder: Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) var sessions = try container.decodeIfPresent([Session].self, forKey: .contents) ?? [] let instances = try container.decodeIfPresent(ConditionallyDecodableCollection<SessionInstance>.self, forKey: .contents).map { Array($0) } ?? [] // remove duplicated sessions instances.forEach { instance in guard let index = sessions.firstIndex(where: { $0.identifier == instance.session?.identifier }) else { return } sessions.remove(at: index) } events = try container.decodeIfPresent(key: .events) ?? [] rooms = try container.decodeIfPresent(key: .rooms) ?? [] resources = try container.decodeIfPresent(key: .resources) ?? [] tracks = try container.decodeIfPresent(key: .tracks) ?? [] self.instances = instances self.sessions = sessions } }
bsd-2-clause
70ba41096a8e19116d9c7148526cb7f3
31.283333
152
0.640681
4.622912
false
false
false
false
harrywynn/ICNDbKit
ICNDbKit/ICNDbKit.swift
1
9418
// // ICNDbKit.swift // // Copyright (c) 2016 Harry J Wynn IV // // 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 ICNDbKit { public typealias ChuckNorrisJokes = (_ array: Array<Dictionary<String, AnyObject>>?) -> Void public typealias ChuckNorrisList = (_ array: Array<String>?) -> Void public typealias ChuckNorrisNumber = (_ int: Int?) -> Void /** Fetches an `Array` of random jokes. - parameter completion: The completion handler, returns an an `Array` of jokes */ public static func fetchRandomJoke(completion: @escaping ChuckNorrisJokes) { fetchRandomJoke(count: nil, categories: nil, firstName: nil, lastName: nil, completion: completion) } /** Fetches an `Array` of random jokes. - parameter count: the number of jokes to fetch - parameter completion: The completion handler, returns an an `Array` of jokes */ public static func fetchRandomJoke(count: Int?, completion: @escaping ChuckNorrisJokes) { fetchRandomJoke(count: count, categories: nil, firstName: nil, lastName: nil, completion: completion) } /** Fetches an `Array` of random jokes. - parameter count: the number of jokes to fetch - parameter categories: categories to restrict the jokes - parameter completion: The completion handler, returns an an `Array` of jokes */ public static func fetchRandomJoke(count: Int?, categories: Array<String>?, completion: @escaping ChuckNorrisJokes) { fetchRandomJoke(count: count, categories: categories, firstName: nil, lastName: nil, completion: completion) } /** Fetches an `Array` of random jokes. - parameter count: the number of jokes to fetch - parameter categories: categories to restrict the jokes - parameter firstName: string to replace the first name in the jokes - parameter lastName: string to replace the last name in the jokes - parameter completion: The completion handler, returns an an `Array` of jokes */ public static func fetchRandomJoke(count: Int?, categories: Array<String>?, firstName: String?, lastName: String?, completion: @escaping ChuckNorrisJokes) { var get = "http://api.icndb.com/jokes/random" // get more than 1 joke if (count != nil && count! > 1) { get += "/\(count!)" } // appending query string if (categories != nil || firstName != nil || lastName != nil) { get += "?" } // limit it to certain categories if (categories != nil) { get += "limitTo=[\(categories!.joined())]&" } // replace first name (Chuck) in joke if (firstName != nil) { get += "firstName=\(firstName!)&" } // replace last name (Norris) in joke if (lastName != nil) { get += "lastName=\(lastName!)&" } let request = NSMutableURLRequest(url:NSURL(string: get) as! URL) request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in let res = response as! HTTPURLResponse // check for success if (error == nil && res.statusCode == 200) { do { // load as json let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, AnyObject> // more than one joke will already be an array if let jokes = jsonObject["value"] as? Array<Dictionary<String, AnyObject>> { completion(jokes) } else { // single joke comes back as just a dictionary, so put in an array var jokes = Array<Dictionary<String, AnyObject>>() jokes.append(jsonObject["value"] as! Dictionary<String, AnyObject>) completion(jokes) } } catch { completion(nil) } } else { completion(nil) } }); dataTask.resume() } /** Fetches all of the available joke categories. - parameter id: the joke to fetch - parameter completion: The completion handler, returns an an `Array` of jokes */ public static func fetchJoke(id: Int, completion: @escaping ChuckNorrisJokes) { let get = "http://api.icndb.com/jokes/\(id)" let request = NSMutableURLRequest(url:NSURL(string: get) as! URL) request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in let res = response as! HTTPURLResponse // check for success if (error == nil && res.statusCode == 200) { do { // load as json let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, AnyObject> var jokes = Array<Dictionary<String, AnyObject>>() jokes.append(jsonObject["value"] as! Dictionary<String, AnyObject>) completion(jokes) } catch { completion(nil) } } else { completion(nil) } }); dataTask.resume() } /** Fetches the total number of available jokes. - parameter completion: The completion handler, returns an `Int` with the count */ public static func fetchJokeCount(completion: @escaping ChuckNorrisNumber) { let get = "http://api.icndb.com/jokes/count" let request = NSMutableURLRequest(url:NSURL(string: get) as! URL) request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in let res = response as! HTTPURLResponse // check for success if (error == nil && res.statusCode == 200) { do { // load as json let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, AnyObject> let count = jsonObject["value"] as! Int completion(count) } catch { completion(nil) } } else { completion(nil) } }); dataTask.resume() } /** Fetches all of the available joke categories. - parameter completion: The completion handler, returns an `Array` of categories */ public static func fetchJokeCategories(completion: @escaping ChuckNorrisList) { let get = "http://api.icndb.com/categories" let request = NSMutableURLRequest(url:NSURL(string: get) as! URL) request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData request.httpMethod = "GET" let dataTask = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in let res = response as! HTTPURLResponse // check for success if (error == nil && res.statusCode == 200) { do { // load as json let jsonObject = try JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, AnyObject> let categories = jsonObject["value"] as! Array<String> completion(categories) } catch { completion(nil) } } else { completion(nil) } }); dataTask.resume() } }
mit
4ba641649d32a3f90e071b860daa2f36
40.672566
160
0.587704
4.941238
false
false
false
false
ZB0106/MCSXY
MCSXY/MCSXY/Tools/NetworkTools/MCRequestTool.swift
1
3397
// // MCRequestTool.swift // MCSXY // // Created by 瞄财网 on 2017/6/22. // Copyright © 2017年 瞄财网. All rights reserved. // import UIKit import Alamofire import SwiftyJSON typealias RequestModelBlock = () -> ZB_NetWorkModel public typealias HandelerDataBlock<T> = (_ jsonData :T) -> Void public typealias handelerFailureBlock = (_ failure :Error) -> Void fileprivate enum ZB_HttpMethod :String{ case get = "GET" case head = "HEAD" case post = "POST" case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" } class MCRequestTool: NSObject { static let defaultsessionManager = SessionManager.default static let backGroundSessionManager = SessionManager.init(configuration: URLSessionConfiguration.background(withIdentifier: "com.miaocaiwang.MCSXY.ZB_Background")) static let sharedInsatance = MCRequestTool() private override init() { } } //mark 请求 extension MCRequestTool { class func ZB_request(requestModelBlock :RequestModelBlock, requestHandel :@escaping HandelerDataBlock<Any>, failureHandel :@escaping handelerFailureBlock) -> Void { let requestModel = requestModelBlock() let urlString = requestModel.baseUrl + (requestModel.APIUrl ?? "") //处理网络请求中的参数 self .handelRequestModelForSend(requestModel: requestModel) let dataRequest = defaultsessionManager.request(urlString, method: HTTPMethod.init(rawValue: requestModel.httpMethod)!, parameters: requestModel.paragram, headers: requestModel.httpHeader) dataRequest.validate().responseJSON { (response) in switch response.result.isSuccess{ case true: print(response.result.value!) if let value = response.result.value { let json = JSON(value) requestHandel(json) } case false: print(response.result.error!) if let error = response.result.error { failureHandel(error) } } //请求完成时处理参数 self.handelRequestModelForCompletion(requestModel: requestModel) } } } extension MCRequestTool { class func handelRequestModelForSend(requestModel :ZB_NetWorkModel) -> Void { switch requestModel.isShowLoading { case .activityView: break case .customLoadingView: break case .refreshView: break case.NotShowLoding: break } switch requestModel.isNeedWIFI { case true: break case false: break } } class func handelRequestModelForCompletion(requestModel :ZB_NetWorkModel) -> Void { switch requestModel.isShowLoading { case .activityView: break case .customLoadingView: break case .refreshView: break case.NotShowLoding: break } if let alertString = requestModel.alertString { } switch requestModel.isCache { case .all: break case .diskCache: break case .memoryCache: break case .notAllowed: break } } }
mit
c869191c07151332720c4a5fe41ab60e
28.298246
196
0.60988
4.606897
false
false
false
false
17thDimension/AudioKit
Examples/OSX/Swift/AudioKitDemo/AudioKitDemo/ProcessingViewController.swift
1
2701
// // ProcessingViewController.swift // AudioKitDemo // // Created by Nicholas Arner on 3/1/15. // Copyright (c) 2015 AudioKit. All rights reserved. // class ProcessingViewController: NSViewController { @IBOutlet var sourceSegmentedControl: NSSegmentedControl! @IBOutlet var maintainPitchSwitch: NSButton! @IBOutlet var pitchSlider: NSSlider! var isPlaying = false var pitchToMaintain:Float let conv: ConvolutionInstrument let audioFilePlayer = AudioFilePlayer() override init() { conv = ConvolutionInstrument(input: audioFilePlayer.auxilliaryOutput) pitchToMaintain = 1.0 super.init() } required init?(coder aDecoder: NSCoder) { conv = ConvolutionInstrument(input: audioFilePlayer.auxilliaryOutput) pitchToMaintain = 1.0 super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() AKOrchestra.addInstrument(audioFilePlayer) AKOrchestra.addInstrument(conv) } @IBAction func start(sender:NSButton) { if (!isPlaying) { conv.play() audioFilePlayer.play() isPlaying = true } } @IBAction func stop(sender:NSButton) { if (isPlaying) { conv.stop() audioFilePlayer.stop() isPlaying = false } } @IBAction func wetnessChanged(sender:NSSlider) { AKTools.setProperty(conv.dryWetBalance, withSlider: sender) } @IBAction func impulseResponseChanged(sender:NSSlider) { AKTools.setProperty(conv.dishWellBalance, withSlider: sender) } @IBAction func speedChanged(sender:NSSlider) { AKTools.setProperty(audioFilePlayer.speed, withSlider: sender) if (maintainPitchSwitch.state == 1 && fabs(audioFilePlayer.speed.floatValue) > 0.1) { audioFilePlayer.scaling.floatValue = pitchToMaintain / fabs(audioFilePlayer.speed.floatValue) AKTools.setSlider(pitchSlider, withProperty: audioFilePlayer.scaling) } } @IBAction func pitchChanged(sender:NSSlider) { AKTools.setProperty(audioFilePlayer.scaling, withSlider: sender) } @IBAction func togglePitchMaintenance(sender:NSButton) { if sender.state == 1 { pitchSlider.enabled = false pitchToMaintain = fabs(audioFilePlayer.speed.floatValue) * audioFilePlayer.scaling.floatValue } else { pitchSlider.enabled = true } } @IBAction func fileChanged(sender:NSSegmentedControl) { audioFilePlayer.sampleMix.floatValue = Float(sender.selectedSegment) } }
lgpl-3.0
59aaece5ea903f59f1b4545aad67e192
29.011111
105
0.65013
4.955963
false
false
false
false
kstaring/swift
test/Interpreter/SDK/CoreFoundation_casting.swift
65
1959
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import CoreFoundation import Foundation class SwiftClass { } func genericCast<T>(_ x: AnyObject, _: T.Type) -> T? { return x as? T } func genericCastUnconditional<T>(_ x: AnyObject, _: T.Type) -> T { return x as! T } // Check _cfTypeID() on a Swift class let nsObject = NSObject() let swiftObject = SwiftClass() assert(CFGetTypeID(nsObject) == CFGetTypeID(swiftObject)) // Check CFString <-> AnyObject func testCFStringAnyObject() { // Create a CFString let cfStr: CFString = CFStringCreateWithCString(nil, "Swift", CFStringBuiltInEncodings.ASCII.rawValue) // CHECK: Swift print(cfStr) // Convert it to AnyObject let anyObject: AnyObject = cfStr // CHECK: Swift print(anyObject) // Convert it back to a CFString let cfStr2 = anyObject as! CFString // CHECK: Swift print(cfStr2) // Conditional cast through a generic to a CFString if let cfStr3 = genericCast(anyObject, CFString.self) { // CHECK: Swift print(cfStr3) } else { print("Conditional cast failed") } // Forced cast through a generic to a CFString let cfStr4 = genericCastUnconditional(anyObject, CFString.self) // CHECK: Swift print(cfStr4) // CHECK: done print("done") } testCFStringAnyObject() // Check CFString.Type <-> AnyObject.Type func testCFStringAnyObjectType() { let cfStr: CFString = CFStringCreateWithCString(nil, "Swift", CFStringBuiltInEncodings.ASCII.rawValue) let cfStrType = type(of: cfStr) // CHECK: [[STRING_CLASS:(NS|CF).*String]] print(cfStrType) // Convert to AnyObject.Type let anyObjectType: AnyObject.Type = cfStrType // CHECK: [[STRING_CLASS]] print(anyObjectType) // Convert back to CFString.Type let cfStrType2 = anyObjectType as! CFString.Type // CHECK: [[STRING_CLASS]] print(cfStrType2) // CHECK: done print("done") } testCFStringAnyObjectType()
apache-2.0
8bb59925f9f7607c22cfeaef806b6197
21.517241
86
0.701889
3.767308
false
true
false
false
dfuerle/kuroo
kuroo/LocationManager.swift
1
1873
// // LocationManager.swift // kuroo // // Copyright © 2016 Dmitri Fuerle. All rights reserved. // import Foundation import CoreLocation protocol LocationManagerDelegate: class { func locationManager(_ manager: LocationManager, didUpdateLocation location: CLLocation) } class LocationManager: NSObject, CLLocationManagerDelegate { var locationManager = CLLocationManager() weak var delegate: LocationManagerDelegate? var location: CLLocation? { get { return locationManager.location } } var completionBlock: (CLAuthorizationStatus) -> Void = {_ in } // MARK: - Init override init() { super.init() locationManager.delegate = self } // MARK: - Public func auth(completion: @escaping (_ authorizationStatus: CLAuthorizationStatus) -> Void) { locationManager.startUpdatingLocation() let authorizationStatus = CLLocationManager.authorizationStatus() switch authorizationStatus { case .notDetermined: completionBlock = completion locationManager.requestAlwaysAuthorization() case .restricted, .denied, .authorizedAlways, .authorizedWhenInUse: completion(authorizationStatus) } } // MARK: - CLLocationManagerDelegate internal func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .authorizedAlways || status == .authorizedWhenInUse { } completionBlock(status) completionBlock = {_ in } } internal func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let delegate = self.delegate { delegate.locationManager(self, didUpdateLocation: locations.first!) } } }
gpl-2.0
3027aec9642a4718343645f2f0962a2a
29.193548
119
0.665598
6.03871
false
false
false
false
antlr/antlr4
runtime/Swift/Sources/Antlr4/tree/pattern/RuleTagToken.swift
7
5201
/* Copyright (c) 2012-2017 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ /// /// A _org.antlr.v4.runtime.Token_ object representing an entire subtree matched by a parser /// rule; e.g., `<expr>`. These tokens are created for _org.antlr.v4.runtime.tree.pattern.TagChunk_ /// chunks where the tag corresponds to a parser rule. /// public class RuleTagToken: Token, CustomStringConvertible { /// /// This is the backing field for _#getRuleName_. /// private let ruleName: String /// /// The token type for the current token. This is the token type assigned to /// the bypass alternative for the rule during ATN deserialization. /// private let bypassTokenType: Int /// /// This is the backing field for _#getLabel_. /// private let label: String? public var visited = false /// /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ with the specified rule /// name and bypass token type and no label. /// /// - Parameter ruleName: The name of the parser rule this rule tag matches. /// - Parameter bypassTokenType: The bypass token type assigned to the parser rule. /// /// - Throws: ANTLRError.illegalArgument if `ruleName` is `null` /// or empty. /// public convenience init(_ ruleName: String, _ bypassTokenType: Int) { self.init(ruleName, bypassTokenType, nil) } /// /// Constructs a new instance of _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ with the specified rule /// name, bypass token type, and label. /// /// - Parameter ruleName: The name of the parser rule this rule tag matches. /// - Parameter bypassTokenType: The bypass token type assigned to the parser rule. /// - Parameter label: The label associated with the rule tag, or `null` if /// the rule tag is unlabeled. /// /// - Throws: ANTLRError.illegalArgument if `ruleName` is `null` /// or empty. /// public init(_ ruleName: String, _ bypassTokenType: Int, _ label: String?) { self.ruleName = ruleName self.bypassTokenType = bypassTokenType self.label = label } /// /// Gets the name of the rule associated with this rule tag. /// /// - Returns: The name of the parser rule associated with this rule tag. /// public final func getRuleName() -> String { return ruleName } /// /// Gets the label associated with the rule tag. /// /// - Returns: The name of the label associated with the rule tag, or /// `null` if this is an unlabeled rule tag. /// public final func getLabel() -> String? { return label } /// /// Rule tag tokens are always placed on the _#DEFAULT_CHANNEL_. /// public func getChannel() -> Int { return RuleTagToken.DEFAULT_CHANNEL } /// /// This method returns the rule tag formatted with `<` and `>` /// delimiters. /// public func getText() -> String? { if let label = label { return "<\(label):\(ruleName)>" } return "<\(ruleName)>" } /// /// Rule tag tokens have types assigned according to the rule bypass /// transitions created during ATN deserialization. /// public func getType() -> Int { return bypassTokenType } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns 0. /// public func getLine() -> Int { return 0 } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1. /// public func getCharPositionInLine() -> Int { return -1 } /// /// /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1. /// public func getTokenIndex() -> Int { return -1 } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1. /// public func getStartIndex() -> Int { return -1 } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns -1. /// public func getStopIndex() -> Int { return -1 } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns `null`. /// public func getTokenSource() -> TokenSource? { return nil } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ always returns `null`. /// public func getInputStream() -> CharStream? { return nil } public func getTokenSourceAndStream() -> TokenSourceAndStream { return TokenSourceAndStream.EMPTY } /// /// The implementation for _org.antlr.v4.runtime.tree.pattern.RuleTagToken_ returns a string of the form /// `ruleName:bypassTokenType`. /// public var description: String { return ruleName + ":" + String(bypassTokenType) } }
bsd-3-clause
ae6a93a9765972896e8eb3eaaba79189
29.063584
109
0.616228
4.287716
false
false
false
false
CodeInventorGroup/CIComponentKit
Sources/CIComponentKit/CICActivityView.swift
1
3316
// // CICActivityView.swift // CIComponentKit // // Created by ManoBoo on 2017/10/14. // Copyright © 2017年 club.codeinventor. All rights reserved. // 苹果大部分App中的指示器都是这个style import UIKit public class CICActivityView: UIView { static let `default` = CICActivityView.init(frame: .zero) var strokeColor = UIColor.cic.hex(hex: 0x808080).cgColor var fillColor = UIColor.clear { didSet { self.backgroundColor = fillColor } } var lineWidth: CGFloat = 4.0 static let hud: UIVisualEffectView = { let hud = UIVisualEffectView.init(effect: UIBlurEffect.init(style: .extraLight)) .backgroundColor(.white) hud.layer.cornerRadius = 8.0 hud.layer.masksToBounds = true hud.contentView.addSubview(CICActivityView.default) return hud }() /// 动画停止是是否隐藏,和系统UIActivityView保持一致 var isHideWhenStopped = true let shape = CAShapeLayer.init() private let animationKey = "CICActivityView_animationKey" override public func draw(_ rect: CGRect) { super.draw(rect) let center = CGPoint.init(x: rect.width/2, y: rect.height/2) let half = CGFloat.maximum(rect.width, rect.height) / 2.0 let path = UIBezierPath.init(arcCenter: center, radius: half * 0.9, startAngle: 0.0, endAngle: CGFloat.pi * 2.0, clockwise: false) shape.strokeColor = strokeColor shape.fillColor = UIColor.clear.cgColor shape.strokeStart = 0 shape.strokeEnd = 0.8 shape.path = path.cgPath shape.lineWidth = lineWidth shape.lineJoin = CAShapeLayerLineJoin.round shape.lineCap = CAShapeLayerLineCap.round self.layer.addSublayer(shape) } public func startAnimation() { self.backgroundColor = fillColor self.isHidden = false let animation1 = CABasicAnimation.init() animation1.keyPath = "transform.rotation.z" animation1.toValue = 2 * CFloat.pi animation1.duration = 1.25 animation1.repeatCount = HUGE self.layer.add(animation1, forKey: animationKey) } public func stopAnimation() { self.layer.removeAnimation(forKey: animationKey) self.isHidden = isHideWhenStopped } } extension CICHUD { /// 类似于MBProgressHUB 一样的加载框 public class func showActivityView(superView: UIView? = UIApplication.shared.keyWindow, backgroundSize: CGSize = 100.makeSize, hudSize: CGSize = 60.makeSize) { guard let superView = superView else { return } CICActivityView.hud.removeFromSuperview() let hud = CICActivityView.hud.size(backgroundSize) .center(superView.cic.internalCenter) CICActivityView.default.size(hudSize) .center(hud.cic.internalCenter) superView.addSubview(hud) CICActivityView.default.startAnimation() } // hide activityView public class func hideActivityView() { CICActivityView.hud.removeFromSuperview() } }
mit
5939755075e57907e8cf95cc4ec2e0de
32.010204
91
0.617929
4.59517
false
false
false
false
TouchInstinct/LeadKit
Sources/Classes/DataLoading/RxNetworkOperationModel.swift
1
3650
// // Copyright (c) 2018 Touch Instinct // // 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 RxSwift import RxCocoa open class RxNetworkOperationModel<LoadingStateType: NetworkOperationState>: NetworkOperationModel where LoadingStateType.DataSourceType: RxDataSource { public typealias DataSourceType = LoadingStateType.DataSourceType public typealias ResultType = DataSourceType.ResultType public typealias ErrorHandler = (Error, LoadingStateType) -> LoadingStateType private let stateRelay = BehaviorRelay<LoadingStateType>(value: .initialState) var currentRequestDisposable: Disposable? private(set) var dataSource: DataSourceType private let errorHandler: ErrorHandler open var stateDriver: Driver<LoadingStateType> { stateRelay.asDriver() } /// Model initializer with data source and custom error handler. /// /// - Parameters: /// - dataSource: Data source for network operation. /// - customErrorHandler: Custom error handler for state update. Pass nil for default error handling. public init(dataSource: DataSourceType, customErrorHandler: ErrorHandler? = nil) { self.errorHandler = customErrorHandler ?? { .errorState(error: $0, after: $1) } self.dataSource = dataSource } /// Performs request to given data source public func execute() { currentRequestDisposable?.dispose() state = .initialLoadingState(after: state) requestResult(from: dataSource) } /// Replaces current data source with new one. /// /// - Parameter newDataSource: A new data source to use. public func replaceDataSource(with newDataSource: DataSourceType) { dataSource = newDataSource } func onGot(error: Error) { state = errorHandler(error, state) } func onGot(result: ResultType, from dataSource: DataSourceType) { state = .resultState(result: result, from: dataSource, after: state) } func requestResult(from dataSource: DataSourceType) { currentRequestDisposable = dataSource .resultSingle() .observe(on: MainScheduler.instance) .subscribe(onSuccess: { [weak self] result in self?.onGot(result: result, from: dataSource) }, onFailure: { [weak self] error in self?.onGot(error: error) }) } var state: LoadingStateType { get { stateRelay.value } set { stateRelay.accept(newValue) } } }
apache-2.0
b7bb71beca38d4772b30c5f124d472a6
35.5
107
0.684384
4.899329
false
false
false
false
ra1028/VueFlux
VueFlux/VueFlux.swift
1
3424
/// Manages a State and commits the action received via dispatcher to mutations. open class Store<State: VueFlux.State> { private let dispatcher = Dispatcher<State>() private let sharedDispatcher = Dispatcher<State>.shared private let commitProcedure: CancelableProcedure<State.Action> private let dispatcherKey: Dispatcher<State>.Observers.Key private let sharedDispatcherKey: Dispatcher<State>.Observers.Key /// An action proxy that dispatches actions via shared dispatcher. /// Action is dispatched to all stores which have same generic type of State. public static var actions: Actions<State> { return .init(dispatcher: Dispatcher<State>.shared) } /// A action proxy that dispatches actions via dispatcher retained by `self`. public let actions: Actions<State> /// A proxy for computed properties to be published of State. public let computed: Computed<State> /// Initialize a new store. /// /// - Parameters: /// - state: A state to be managed in `self`. /// - mutations: A mutations for mutates the state. /// - executor: An executor to dispatch actions on. public init(state: State, mutations: State.Mutations, executor: Executor) { let commitProcedure = CancelableProcedure<State.Action> { action in mutations.commit(action: action, state: state) } let commit: (State.Action) -> Void = { action in executor.execute { commitProcedure.execute(with: action) } } self.commitProcedure = commitProcedure actions = .init(dispatcher: dispatcher) computed = .init(state: state) dispatcherKey = dispatcher.subscribe(commit) sharedDispatcherKey = sharedDispatcher.subscribe(commit) } deinit { commitProcedure.cancel() dispatcher.unsubscribe(for: dispatcherKey) sharedDispatcher.unsubscribe(for: sharedDispatcherKey) } } /// Represents a state can be managed in Store. public protocol State: class { associatedtype Action associatedtype Mutations: VueFlux.Mutations where Mutations.State == Self } /// Represents a proxy for functions to mutate a State. public protocol Mutations { associatedtype State: VueFlux.State /// Mutate a state by given action. /// The only way to actually mutate state in a Store. func commit(action: State.Action, state: State) } /// A proxy of functions for dispatching actions. public struct Actions<State: VueFlux.State> { private let dispatcher: Dispatcher<State> /// Create the proxy. /// /// - Parameters: /// - dispather: A dispatcher to dispatch the actions to. fileprivate init(dispatcher: Dispatcher<State>) { self.dispatcher = dispatcher } /// Dispatch given action to dispatcher. /// /// - Parameters: /// - action: An action to be dispatch. public func dispatch(action: State.Action) { dispatcher.dispatch(action: action) } } /// A proxy of properties to be published of State. public struct Computed<State: VueFlux.State> { /// A state to be publish properties by `self`. public let state: State /// Create the proxy. /// /// - Parameters: /// - state: A state to be proxied. fileprivate init(state: State) { self.state = state } }
mit
3509b38e86dc830fab5de97c1558ec8b
32.90099
81
0.660631
4.595973
false
false
false
false
manuelCarlos/Swift-Playgrounds
StructsToJSON.playground/Contents.swift
1
3235
//: # Swift 3: JSON-serializable structs using protocols import Foundation //: ### Defining the protocols protocol JSONRepresentable { var JSONRepresentation: Any { get } } protocol JSONSerializable: JSONRepresentable {} extension JSONSerializable { var JSONRepresentation: Any { var representation = [String : Any]() print("entrou", Mirror(reflecting: self).children ) for case let (label?, value) in Mirror(reflecting: self).children { print("0", label) switch value { case let value as [String : Any]: representation[label] = value print("1") case let value as [Any]: if let val = value as? [JSONSerializable] { representation[label] = val.map({ $0.JSONRepresentation }) print("1,1") } else { representation[label] = value print("1.2") } print("2") case let value: representation[label] = value print("3") default: print("4") } } print("saiu") return representation as Any } } extension JSONSerializable { func toJSON() -> String? { let representation = JSONRepresentation print(representation) guard JSONSerialization.isValidJSONObject(representation) else { print("Invalid JSON Representation") return nil } do { let data = try JSONSerialization.data(withJSONObject: representation, options: []) return String(data: data, encoding: .utf8) } catch { print("something bad") return nil } } } //: ### Define the Structures while conforming to the protocol struct Author: JSONSerializable { let name: String } struct Book: JSONSerializable { let title: String let isbn: String let pages: Int let authors:[JSONSerializable] let extra:[String: Any] } struct Library: JSONSerializable{ let books: [JSONSerializable] } //: ### Create a sample object for serialization let book = Book( title: "Mirage", isbn: "0399158081", pages: 397, authors: [ Author(name: "Clive Cussler"), Author(name:"Jack Du Brul") ], extra: [ "foo": "bar", "baz": 142.226 ] ) let book2 = Book( title: "End", isbn: "0399158081", pages: 397, authors: [ Author(name: "Clive Cussler"), Author(name:"Jack Du Brul") ], extra: [ "foo": "bar", "baz": 142.226 ] ) let lib = Library(books: [book, book2]) //: ### Use the protocols to convert the data to JSON //: #### (Enums have poor support from Mirror for this to work for now...) if let json = book.toJSON() { print(json) } if let json = lib.toJSON() { print(json) }
mit
f9ba39ca48cc65f8e5a44d31e9f7be7d
22.613139
94
0.506028
4.857357
false
false
false
false
ArthurDevNL/WWDC15App
WWDC15/AppDelegate.swift
1
2661
// // AppDelegate.swift // WWDC15 // // Created by Arthur Hemmer on 14/04/15. // Copyright (c) 2015 Arthur. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let font = UIFont(name: "AvenirNext-Regular", size: CGFloat(21)) let attributes = [NSFontAttributeName: font!, NSForegroundColorAttributeName: UIColor.whiteColor()] UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal) let titleFont = UIFont(name: "AvenirNext-Medium", size: CGFloat(21)) let titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor(), NSFontAttributeName: titleFont!] UINavigationBar.appearance().titleTextAttributes = titleTextAttributes 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
ddcd87027c054909d1ad9311d46f8751
48.277778
285
0.746712
5.661702
false
false
false
false
austinzheng/swift
test/Interpreter/dynamic_cast_dict_unconditional_type_metadata.swift
69
926
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop // rdar://problem/28022201 exposed an ABI mismatch bug between the C++ code // in the runtime and standard library hook functions written in Swift, which // led to dynamic cast operations on sets and dictionaries generating corrupt // type metadata. Exercising this bug requires that the first instantiation of // a specific dictionary type in the process be through a dynamic cast. We // then bridge to ObjC, so that the resulting NSDictionary subclass is forced // to recover the underlying Dictionary's generic environment from the // corrupted class metadata instead of getting it passed in from the compiler. import Foundation let a: [String: Int] = ["foo": 1] let b: Any = a let c = b as! [String: Any] let d = (c as AnyObject) as! NSDictionary _ = d.object(forKey: "foo" as NSString) // CHECK: ok print("ok")
apache-2.0
e6c1cb4dcc98a99ca251d7174dac467e
36.04
78
0.74406
3.991379
false
false
false
false
ZacharyKhan/ZKCarousel
ZKCarousel/Classes/ZKCarousel.swift
1
7118
// // ZKCarousel.swift // Delego // // Created by Zachary Khan on 6/8/17. // Copyright © 2017 ZacharyKhan. All rights reserved. // import UIKit @objc public protocol ZKCarouselDelegate: AnyObject { func carouselDidScroll() } final public class ZKCarousel: UIView, UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource { // MARK: - Properties private var timer: Timer = Timer() public var interval: Double = 1.0 public var delegate: ZKCarouselDelegate? public var slides: [ZKCarouselSlide] = [] { didSet { updateUI() } } /// Calculates the index of the currently visible ZKCarouselCell public var currentlyVisibleIndex: Int? { var visibleRect = CGRect() visibleRect.origin = collectionView.contentOffset visibleRect.size = collectionView.bounds.size let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY) return collectionView.indexPathForItem(at: visiblePoint)?.item } private lazy var tapGesture: UITapGestureRecognizer = { let tap = UITapGestureRecognizer(target: self, action: #selector(tapGestureHandler(tap:))) return tap }() public lazy var pageControl: UIPageControl = { let control = UIPageControl() control.currentPage = 0 control.hidesForSinglePage = true control.pageIndicatorTintColor = .lightGray control.currentPageIndicatorTintColor = UIColor(red:0.20, green:0.60, blue:0.86, alpha:1.0) control.translatesAutoresizingMaskIntoConstraints = false return control }() public lazy var collectionView: UICollectionView = { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal let cv = UICollectionView(frame: .zero, collectionViewLayout: layout) cv.delegate = self cv.dataSource = self cv.isPagingEnabled = true cv.register(ZKCarouselCell.self, forCellWithReuseIdentifier: ZKCarouselCell.identifier) cv.clipsToBounds = true cv.backgroundColor = .clear cv.showsHorizontalScrollIndicator = false cv.bounces = false cv.translatesAutoresizingMaskIntoConstraints = false return cv }() // MARK: - Default Methods public override init(frame: CGRect) { super.init(frame: frame) setupCarousel() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupCarousel() } // MARK: - Internal Methods private func setupCarousel() { backgroundColor = .clear addSubview(collectionView) collectionView.topAnchor.constraint(equalTo: topAnchor).isActive = true collectionView.leftAnchor.constraint(equalTo: leftAnchor).isActive = true collectionView.rightAnchor.constraint(equalTo: rightAnchor).isActive = true collectionView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true collectionView.addGestureRecognizer(tapGesture) addSubview(pageControl) pageControl.leftAnchor.constraint(equalTo: leftAnchor, constant: 16).isActive = true pageControl.rightAnchor.constraint(equalTo: rightAnchor, constant: -16).isActive = true pageControl.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -8).isActive = true pageControl.heightAnchor.constraint(equalToConstant: 25).isActive = true bringSubviewToFront(pageControl) } @objc private func tapGestureHandler(tap: UITapGestureRecognizer?) { var visibleRect = CGRect() visibleRect.origin = collectionView.contentOffset visibleRect.size = collectionView.bounds.size let visiblePoint = CGPoint(x: visibleRect.midX, y: visibleRect.midY) let visibleIndexPath: IndexPath = collectionView.indexPathForItem(at: visiblePoint) ?? IndexPath(item: 0, section: 0) let index = visibleIndexPath.item let indexPathToShow = IndexPath(item: index == slides.count - 1 ? 0 : index + 1, section: 0) collectionView.selectItem(at: indexPathToShow, animated: true, scrollPosition: .centeredHorizontally) } private func updateUI() { DispatchQueue.main.async { self.collectionView.reloadData() self.pageControl.numberOfPages = self.slides.count self.pageControl.size(forNumberOfPages: self.slides.count) } } // MARK: - Exposed Methods public func start() { timer = Timer.scheduledTimer(timeInterval: interval, target: self, selector: #selector(tapGestureHandler(tap:)), userInfo: nil, repeats: true) timer.fire() } public func stop() { timer.invalidate() } public func disableTap() { /* This method is provided in case you want to remove the * default gesture and provide your own. The default gesture * changes the slides on tap. */ collectionView.removeGestureRecognizer(tapGesture) } // MARK: - UICollectionViewDelegate & DataSource public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ZKCarouselCell.identifier, for: indexPath) as? ZKCarouselCell else { return ZKCarouselCell() } cell.slide = slides[indexPath.item] return cell } public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return slides.count } public func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: collectionView.frame.width, height: collectionView.frame.height) } public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 0 } // MARK: - UIScrollViewDelegate public func scrollViewDidScroll(_ scrollView: UIScrollView) { if let index = currentlyVisibleIndex { pageControl.currentPage = index } } public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { delegate?.carouselDidScroll() } }
mit
697e2e5b3ec5e56d4c6c01ca4005afa1
38.104396
177
0.636645
5.781478
false
false
false
false
snailjj/iOSDemos
SnailSwiftDemos/Pods/SQLite.swift/Sources/SQLite/Typed/Expression.swift
4
4210
// // SQLite.swift // https://github.com/stephencelis/SQLite.swift // Copyright © 2014-2015 Stephen Celis. // // 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. // public protocol ExpressionType : Expressible { // extensions cannot have inheritance clauses associatedtype UnderlyingType = Void var template: String { get } var bindings: [Binding?] { get } init(_ template: String, _ bindings: [Binding?]) } extension ExpressionType { public init(literal: String) { self.init(literal, []) } public init(_ identifier: String) { self.init(literal: identifier.quote()) } public init<U : ExpressionType>(_ expression: U) { self.init(expression.template, expression.bindings) } } /// An `Expression` represents a raw SQL fragment and any associated bindings. public struct Expression<Datatype> : ExpressionType { public typealias UnderlyingType = Datatype public var template: String public var bindings: [Binding?] public init(_ template: String, _ bindings: [Binding?]) { self.template = template self.bindings = bindings } } public protocol Expressible { var expression: Expression<Void> { get } } extension Expressible { // naïve compiler for statements that can’t be bound, e.g., CREATE TABLE // FIXME: make internal (0.12.0) public func asSQL() -> String { let expressed = expression var idx = 0 return expressed.template.characters.reduce("") { template, character in let transcoded: String if character == "?" { transcoded = transcode(expressed.bindings[idx]) idx += 1 } else { transcoded = String(character) } return template + transcoded } } } extension ExpressionType { public var expression: Expression<Void> { return Expression(template, bindings) } public var asc: Expressible { return " ".join([self, Expression<Void>(literal: "ASC")]) } public var desc: Expressible { return " ".join([self, Expression<Void>(literal: "DESC")]) } } extension ExpressionType where UnderlyingType : Value { public init(value: UnderlyingType) { self.init("?", [value.datatypeValue]) } } extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Value { public static var null: Self { return self.init(value: nil) } public init(value: UnderlyingType.WrappedType?) { self.init("?", [value?.datatypeValue]) } } extension Value { public var expression: Expression<Void> { return Expression(value: self).expression } } public let rowid = Expression<Int64>("ROWID") public func cast<T: Value, U: Value>(_ expression: Expression<T>) -> Expression<U> { return Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) } public func cast<T: Value, U: Value>(_ expression: Expression<T?>) -> Expression<U?> { return Expression("CAST (\(expression.template) AS \(U.declaredDatatype))", expression.bindings) }
apache-2.0
0098973aadd8bc56c7e2f834cc00ab1d
27.612245
100
0.671897
4.517723
false
false
false
false
kesun421/firefox-ios
Client/Frontend/Reader/ReaderModeHandlers.swift
10
6321
/* 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 import GCDWebServers struct ReaderModeHandlers { static var readerModeCache: ReaderModeCache = DiskReaderModeCache.sharedInstance static func register(_ webServer: WebServer, profile: Profile) { // Register our fonts and css, which we want to expose to web content that we present in the WebView webServer.registerMainBundleResourcesOfType("ttf", module: "reader-mode/fonts") webServer.registerMainBundleResource("Reader.css", module: "reader-mode/styles") // Register a handler that simply lets us know if a document is in the cache or not. This is called from the // reader view interstitial page to find out when it can stop showing the 'Loading...' page and instead load // the readerized content. webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page-exists") { (request: GCDWebServerRequest?) -> GCDWebServerResponse! in guard let stringURL = request?.query["url"] as? String, let url = URL(string: stringURL) else { return GCDWebServerResponse(statusCode: 500) } let status = readerModeCache.contains(url) ? 200 : 404 return GCDWebServerResponse(statusCode: status) } // Register the handler that accepts /reader-mode/page?url=http://www.example.com requests. webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page") { (request: GCDWebServerRequest?) -> GCDWebServerResponse! in if let url = request?.query["url"] as? String { if let url = URL(string: url), url.isWebPage() { do { let readabilityResult = try readerModeCache.get(url) // We have this page in our cache, so we can display it. Just grab the correct style from the // profile and then generate HTML from the Readability results. var readerModeStyle = DefaultReaderModeStyle if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) { if let style = ReaderModeStyle(dict: dict) { readerModeStyle = style } } if let html = ReaderModeUtils.generateReaderContent(readabilityResult, initialStyle: readerModeStyle), let response = GCDWebServerDataResponse(html: html) { // Apply a Content Security Policy that disallows everything except images from anywhere and fonts and css from our internal server response.setValue("default-src 'none'; img-src *; style-src http://localhost:*; font-src http://localhost:*", forAdditionalHeader: "Content-Security-Policy") return response } } catch _ { // This page has not been converted to reader mode yet. This happens when you for example add an // item via the app extension and the application has not yet had a change to readerize that // page in the background. // // What we do is simply queue the page in the ReadabilityService and then show our loading // screen, which will periodically call page-exists to see if the readerized content has // become available. ReadabilityService.sharedInstance.process(url, cache: readerModeCache) if let readerViewLoadingPath = Bundle.main.path(forResource: "ReaderViewLoading", ofType: "html") { do { let readerViewLoading = try NSMutableString(contentsOfFile: readerViewLoadingPath, encoding: String.Encoding.utf8.rawValue) readerViewLoading.replaceOccurrences(of: "%ORIGINAL-URL%", with: url.absoluteString, options: NSString.CompareOptions.literal, range: NSRange(location: 0, length: readerViewLoading.length)) readerViewLoading.replaceOccurrences(of: "%LOADING-TEXT%", with: NSLocalizedString("Loading content…", comment: "Message displayed when the reader mode page is loading. This message will appear only when sharing to Firefox reader mode from another app."), options: NSString.CompareOptions.literal, range: NSRange(location: 0, length: readerViewLoading.length)) readerViewLoading.replaceOccurrences(of: "%LOADING-FAILED-TEXT%", with: NSLocalizedString("The page could not be displayed in Reader View.", comment: "Message displayed when the reader mode page could not be loaded. This message will appear only when sharing to Firefox reader mode from another app."), options: NSString.CompareOptions.literal, range: NSRange(location: 0, length: readerViewLoading.length)) readerViewLoading.replaceOccurrences(of: "%LOAD-ORIGINAL-TEXT%", with: NSLocalizedString("Load original page", comment: "Link for going to the non-reader page when the reader view could not be loaded. This message will appear only when sharing to Firefox reader mode from another app."), options: NSString.CompareOptions.literal, range: NSRange(location: 0, length: readerViewLoading.length)) return GCDWebServerDataResponse(html: readerViewLoading as String) } catch _ { } } } } } let errorString = NSLocalizedString("There was an error converting the page", comment: "Error displayed when reader mode cannot be enabled") return GCDWebServerDataResponse(html: errorString) // TODO Needs a proper error page } } }
mpl-2.0
168405fd3b89942346a1b69395c5a2db
77.012346
334
0.614812
5.813247
false
false
false
false
HabitRPG/habitrpg-ios
Habitica API Client/Habitica API Client/User/PurchaseGemsCall.swift
1
849
// // PurchaseGemsCall.swift // Habitica API Client // // Created by Phillip Thelen on 21.05.18. // Copyright © 2018 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models import ReactiveSwift public class PurchaseGemsCall: ResponseObjectCall<EmptyResponseProtocol, APIEmptyResponse> { public init(receipt: [String: Any], recipient: String?, stubHolder: StubHolderProtocol? = StubHolder(responseCode: 200, stubFileName: "user.json")) { var data = ["transaction": receipt] if let recipient = recipient { data["gift"] = ["uuid": recipient] } let json = try? JSONSerialization.data(withJSONObject: data, options: []) super.init(httpMethod: .POST, endpoint: "iap/ios/verify", postData: json, stubHolder: stubHolder, errorHandler: PrintNetworkErrorHandler()) } }
gpl-3.0
bcf864fb6c0676755f8ef536b77b2191
37.545455
153
0.70283
4.326531
false
false
false
false
domenicosolazzo/practice-swift
CoreMotion/Retrieving Accelerometer Data/Retrieving Accelerometer Data/ViewController.swift
1
869
// // ViewController.swift // Retrieving Accelerometer Data // // Created by Domenico on 21/05/15. // License MIT // import UIKit import CoreMotion class ViewController: UIViewController { lazy var motionManager = CMMotionManager() override func viewDidLoad() { super.viewDidLoad() if motionManager.isAccelerometerAvailable{ _ = OperationQueue() motionManager.startAccelerometerUpdates(to: OperationQueue.main) { [weak self] (data: CMAccelerometerData?, error: Error?) in print("X = \(data?.acceleration.x)") print("Y = \(data?.acceleration.y)") print("Z = \(data?.acceleration.z)") } } else { print("Accelerometer is not available") } } }
mit
533c1f8078a2350dcf461e10c815bf52
24.558824
137
0.547756
5.266667
false
false
false
false
maghov/IS-213
LoginV1/LoginV1/ViewController.swift
1
6448
// // ViewController.swift // Roombooking // ViewContoller handles the login and signup. There is also a button to the help page. // Created by Gruppe10 on 21.04.2017. // Copyright © 2017 Gruppe10. All rights reserved. // import UIKit import FirebaseAuth var userID = FIRAuth.auth()!.currentUser!.email! class ViewController: UIViewController, UITextFieldDelegate, UIAlertViewDelegate { //Is going to handle the auto login. @IBAction func switchAutoLogOn(_ sender: UISwitch) { if sender.isOn == true { // autoLogIn() //if sender.isOn = true. //The user will be remaind logged in when the app restarts. } else { //sender.isOn == false //The user must login every time. } } @IBOutlet weak var segmentController: UISegmentedControl! @IBOutlet weak var emailText: UITextField! @IBOutlet weak var passwordText: UITextField! @IBOutlet weak var confirmPasswordText: UITextField! @IBOutlet weak var buttonLogin: UIButton! //Button that handles the login and sign up. @IBAction func loginButtonPressed(_ sender: UIButton) { //checks if the email and password fields are NOT empty. if emailText.text != "" && passwordText.text != "" { //checks if the segmentController is on 0 for login. if segmentController.selectedSegmentIndex == 0 //Login user { FIRAuth.auth()?.signIn(withEmail: emailText.text!, password: passwordText.text!, completion: { (user, error) in if user != nil { //Sign in successfull -Send user to Tab bar controller self.performSegue(withIdentifier: "segue1", sender: self) print(userID) } else { if let myError = error?.localizedDescription { print(myError) let alert = UIAlertController(title: "Error", message: myError, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { print("ERROR") } } }) } else // Sign up user. SegmentController is now on 1. { if passwordText.text == confirmPasswordText.text{ FIRAuth.auth()?.createUser(withEmail: emailText.text!, password: passwordText.text!, completion: { (user, error) in if user != nil { self.performSegue(withIdentifier: "segue1", sender: self) } else { if let myError = error?.localizedDescription { print(myError) let alert = UIAlertController(title: "Error", message: myError, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } else { print("ERROR") } } }) } else { //Display error message to the user if the passwords are not the same. print("ERROR! Passwords not similar.") let alert = UIAlertController(title: "Error", message: "Passwords do not match", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } }else{// Display error message if there are any emty fiels. let alert = UIAlertController(title: "Error", message: "Empty field(s)", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) } } //Handles the segue between Login and Sign up. @IBAction func SegmentControllerView(_ sender: UISegmentedControl) { if segmentController.selectedSegmentIndex == 0 { buttonLogin.setTitle("Login", for: .normal) confirmPasswordText.isHidden = true } else { buttonLogin.setTitle("Sign up", for: .normal) confirmPasswordText.isHidden = false } } // Function that handles the auto login. // This does not work as its supposed. Needs help func autoLogIn(){ if FIRAuth.auth()?.currentUser != nil { performSegue(withIdentifier: "segue1", sender: self) } } // override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(true) // if the user does not logout. The user will be send directly to home page. if FIRAuth.auth()?.currentUser != nil { // performSegue(withIdentifier: "segue1", sender: self) print(userID) } } override func viewDidLoad() { super.viewDidLoad() //Makes the confirmPassord textfield hidden as default. confirmPasswordText.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //Hides keyboard when user touches outside textfield override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.view.endEditing(true) } }
mit
bd6e0828a7f912536447840ab9234d10
39.29375
146
0.530169
5.69523
false
false
false
false
timvermeulen/DraughtsCloud
Sources/App/Table.swift
1
279
enum Table: String { case whitePositions = "white-positions" case blackPositions = "black-positions" case whiteMoves = "white-moves" case blackMoves = "black-moves" static let all: [Table] = [.whitePositions, .blackPositions, .whiteMoves, .blackMoves] }
mit
4842a405dac9339147e6a0f8922e9263
33.875
90
0.688172
3.821918
false
false
false
false
cinema6/RCAnalytics
Example/Tests/URI.swift
1
13225
// // URI.swift // RCAnalytics // // Created by Josh Minzner on 4/12/16. // Copyright © 2016 CocoaPods. All rights reserved. // import Quick; import Nimble; import Foundation; @testable import RCAnalytics; class URISpec: QuickSpec { override func spec() { describe("URI") { it("should handle an href") { let url = URI(href: "http://user:[email protected]:8080/p/a/t/h?query=string&funny=ha%20ha#hash"); expect(url.href).to(equal("http://user:[email protected]:8080/p/a/t/h?query=string&funny=ha%20ha#hash")); expect(url.protoc).to(equal("http:")); expect(url.host).to(equal("host.com:8080")); expect(url.auth).to(equal("user:pass")); expect(url.hostname).to(equal("host.com")); expect(url.port).to(equal("8080")); expect(url.pathname).to(equal("/p/a/t/h")); expect(url.search).to(equal("?query=string&funny=ha%20ha")); expect(url.path).to(equal("/p/a/t/h?query=string&funny=ha%20ha")); expect(url.query).to(equal([ "query": "string", "funny": "ha ha" ])); expect(url.hash).to(equal("#hash")); } it("should handle a minimal URL") { let url = URI(href: "https://www.reelcontent.com"); expect(url.href).to(equal("https://www.reelcontent.com")); expect(url.protoc).to(equal("https:")); expect(url.host).to(equal("www.reelcontent.com")); expect(url.auth).to(beNil()); expect(url.hostname).to(equal("www.reelcontent.com")); expect(url.port).to(beNil()); expect(url.pathname).to(equal("/")); expect(url.search).to(equal("")); expect(url.path).to(equal("/")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should treat a non-url as a path") { let url = URI(href: "foo.com"); expect(url.href).to(equal("foo.com")); expect(url.protoc).to(beNil()); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(equal("foo.com")); expect(url.search).to(equal("")); expect(url.path).to(equal("foo.com")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle just a protocol") { let url = URI(href: "ftp://"); expect(url.href).to(equal("ftp://")); expect(url.protoc).to(equal("ftp:")); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(beNil()); expect(url.search).to(equal("")); expect(url.path).to(beNil()); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle the seperate parts of a url") { let url = URI( protoc: "http", hostname: "reelcontent.com", auth: "josh:password", port: "80", pathname: "hey/there", query: [ "what": "is up?", "its": "all good!" ], hash: "good-stuff" ); expect(url.href).to(equal("http://josh:[email protected]:80/hey/there?its=all%20good%21&what=is%20up%3F#good-stuff")); expect(url.protoc).to(equal("http:")); expect(url.host).to(equal("reelcontent.com:80")); expect(url.auth).to(equal("josh:password")); expect(url.hostname).to(equal("reelcontent.com")); expect(url.port).to(equal("80")); expect(url.pathname).to(equal("/hey/there")); expect(url.search).to(equal("?its=all%20good%21&what=is%20up%3F")); expect(url.path).to(equal("/hey/there?its=all%20good%21&what=is%20up%3F")); expect(url.query).to(equal([ "what": "is up?", "its": "all good!" ])); expect(url.hash).to(equal("#good-stuff")); } it("should handle minimal parts of a URL") { let url = URI( protoc: "https", hostname: "reelcontent.com" ); expect(url.href).to(equal("https://reelcontent.com/")); expect(url.protoc).to(equal("https:")); expect(url.host).to(equal("reelcontent.com")); expect(url.auth).to(beNil()); expect(url.hostname).to(equal("reelcontent.com")); expect(url.port).to(beNil()); expect(url.pathname).to(equal("/")); expect(url.search).to(equal("")); expect(url.path).to(equal("/")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle just a protocol") { let url = URI(protoc: "ftp"); expect(url.href).to(equal("ftp:")); expect(url.protoc).to(equal("ftp:")); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(beNil()); expect(url.search).to(equal("")); expect(url.path).to(beNil()); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle just a hostname") { let url = URI(hostname: "platform.reelcontent.com"); expect(url.href).to(equal("//platform.reelcontent.com/")); expect(url.protoc).to(beNil()); expect(url.host).to(equal("platform.reelcontent.com")); expect(url.auth).to(beNil()); expect(url.hostname).to(equal("platform.reelcontent.com")); expect(url.port).to(beNil()); expect(url.pathname).to(equal("/")); expect(url.search).to(equal("")); expect(url.path).to(equal("/")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle just a pathname") { let url = URI(pathname: "foo/bar"); expect(url.href).to(equal("/foo/bar")); expect(url.protoc).to(beNil()); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(equal("/foo/bar")); expect(url.search).to(equal("")); expect(url.path).to(equal("/foo/bar")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(beNil()); } it("should handle just a query") { let url = URI(query: [ "hello": "its me!" ]); expect(url.href).to(equal("?hello=its%20me%21")); expect(url.protoc).to(beNil()); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(beNil()); expect(url.search).to(equal("?hello=its%20me%21")); expect(url.path).to(equal("?hello=its%20me%21")); expect(url.query).to(equal([ "hello": "its me!" ])); expect(url.hash).to(beNil()); } it("should handle just a hash") { let url = URI(hash: "cool"); expect(url.href).to(equal("#cool")); expect(url.protoc).to(beNil()); expect(url.host).to(beNil()); expect(url.auth).to(beNil()); expect(url.hostname).to(beNil()); expect(url.port).to(beNil()); expect(url.pathname).to(beNil()); expect(url.search).to(equal("")); expect(url.path).to(beNil()); expect(url.query).to(equal([String: String]())); expect(url.hash).to(equal("#cool")); } it("should handle protocols with colons, pathnames with leading /, and hashs with leading #") { let url = URI(protoc: "https:", hostname: "foo.com", pathname: "/foo/bar", hash: "#winning"); expect(url.href).to(equal("https://foo.com/foo/bar#winning")); expect(url.protoc).to(equal("https:")); expect(url.host).to(equal("foo.com")); expect(url.auth).to(beNil()); expect(url.hostname).to(equal("foo.com")); expect(url.port).to(beNil()); expect(url.pathname).to(equal("/foo/bar")); expect(url.search).to(equal("")); expect(url.path).to(equal("/foo/bar")); expect(url.query).to(equal([String: String]())); expect(url.hash).to(equal("#winning")); } it("should be equitible") { expect(URI(href: "http://www.foo.com")).to(equal(URI(href: "http://www.foo.com"))); expect(URI(href: "http://www.foo.com")).notTo(equal(URI(href: "https://www.foo.com"))); } describe("instance") { var url: URI!; beforeEach { url = URI(protoc: "https", hostname: "platform.reelcontent.com", port: "443", pathname: "/api/root/foo"); } describe("methods:") { describe("toNSURL()") { var result: NSURL!; beforeEach { result = url.toNSURL(); } it("should return an NSURL representing the URI") { expect(result).to(equal(NSURL(string: url.href))); } } } } describe("static") { describe("methods:") { describe("encode()") { var string: String!; beforeEach { string = "This is a test string; all the correct chars' are encoded: This fn is #1! (Hell yes.) ! # $ & ' ( ) * + , / : ; = ? @ % [ ]\n" + "\n" + "\" < > \\ ^ ` { } | ~"; } it("should escape all URI-incompatible characters") { expect(URI.encode(string)).to(equal("This%20is%20a%20test%20string%3B%20all%20the%20correct%20chars%27%20are%20encoded%3A%20This%20fn%20is%20%231%21%20%28Hell%20yes.%29%20%21%20%23%20%24%20%26%20%27%20%28%20%29%20%2A%20%2B%20%2C%20%2F%20%3A%20%3B%20%3D%20%3F%20%40%20%25%20%5B%20%5D%0A%0A%22%20%3C%20%3E%20%5C%20%5E%20%60%20%7B%20%7D%20%7C%20~")); } } describe("decode()") { var string: String!; beforeEach { string = "This is a test string; all the correct chars' are encoded: This fn is #1! (Hell yes.) ! # $ & ' ( ) * + , / : ; = ? @ % [ ]\n" + "\n" + "\" < > \\ ^ ` { } | ~"; } it("should convert the string back to normal") { expect(URI.decode(URI.encode(string))).to(equal(string)); } } } } } } }
mit
c6c180f6f39d1b3edf5a173b0752e539
44.133106
375
0.428615
4.188787
false
false
false
false
shineycode/cocoaconf-ble
talk-demo/source/central/ListenerViewController.swift
1
5734
// // ListenerViewController.swift // talk-demo // // Created by Shiney Code on 10/25/15. // Copyright © 2015 Shiney Code. All rights reserved. // import UIKit import CoreBluetooth class ListenerViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, SimpleCentralDelegate { // MARK: Outlets @IBOutlet weak var scanButton: UIButton! @IBOutlet weak var serviceIDTextField: UITextField! @IBOutlet weak var tableView: UITableView! private var isScanning: Bool = false var simpleCentral: SimpleCentral! // Doing this in order to make this view controller a SimpleCentralDelegate // MARK: Data and data source // Using a lazy stored property to avoid declaring this property as an optional or an implictly // unwrapped optional. The downside is that your instance does not get created until accessed. // See: http://blog.scottlogic.com/2014/11/20/swift-initialisation.html lazy private var dataSource: ListenerTableViewDataSource = { return ListenerTableViewDataSource() }() var selectedPeripheralData: PeripheralData? var peripheralStore = PeripheralStore() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) simpleCentral = SimpleCentral(delegate: self) } } extension ListenerViewController { override func viewDidLoad() { tableView.dataSource = self tableView.delegate = self self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") } override func viewWillAppear(animated: Bool) { toggleScanMode(startScanning: true) // Become SimpleCentral's delegate whenever we're visible simpleCentral.delegate = self super.viewWillAppear(animated) } } extension ListenerViewController { @IBAction func startScanButton(sender: UIButton) { if !isScanning { clearDataSource() toggleScanMode(startScanning: true) } else { toggleScanMode(startScanning: false) } } } // MARK: UITableViewDataSource/UITableViewDelegate methods extension ListenerViewController { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource.countOfRows } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell: UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) if let peripheralProfile = peripheralAtIndexPath(indexPath) { cell.textLabel?.text = peripheralProfile.displayName } else { cell.textLabel?.text = "Unknown peripheral" } return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) // Save the selected PeripheralProfile so the segue can be prepared selectedPeripheralData = peripheralAtIndexPath(indexPath) performSegueWithIdentifier("ListenerListDetailSegue", sender: self) // Stop scanning for new peripherals toggleScanMode(startScanning: false) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "ListenerListDetailSegue" { let destinationViewController: ListenerDetailViewController = segue.destinationViewController as! ListenerDetailViewController destinationViewController.peripheralData = selectedPeripheralData destinationViewController.peripheralStore = peripheralStore destinationViewController.simpleCentral = simpleCentral } } } // MARK: SimpleCentralDelegate methods extension ListenerViewController { func discoveredPeripheral(peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { // Add discovered peripheral to our general data store let peripheralData = peripheralStore.addDiscoverPeripheral(peripheral, advertisementData: advertisementData, RSSI: RSSI) dataSource.addItem(peripheralData.identifier) // Update the tableview with newest peripheral reloadData() } } // MARK: Private methods extension ListenerViewController { func peripheralAtIndexPath(indexPath: NSIndexPath) -> PeripheralData? { let identifier = dataSource.itemAtIndexPath(indexPath) return peripheralStore.peripheralWithIdentifier(identifier) } func toggleScanMode(startScanning startScanning: Bool) { // -- if startScanning { scanButton.setTitle("Stop Scan", forState: UIControlState.Normal) let uuid = String.convertToCBUUID(serviceIDTextField.text) simpleCentral.startListening(uuid) } else { scanButton.setTitle("Start Scan", forState: UIControlState.Normal) simpleCentral.stopListening() } isScanning = !isScanning } func clearDataSource() { dataSource.clear() reloadData() } func reloadData() { dispatch_async(dispatch_get_main_queue()) { let delay = 1.0 // delay by 1 second let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))) dispatch_after(when, dispatch_get_main_queue(), { // Update the tableview with newest peripheral self.tableView.reloadData() }) } } }
mit
bac30d301a1414fb0a4eedc48f467eec
34.395062
138
0.676958
5.576848
false
false
false
false
taxfix/native-navigation
lib/ios/native-navigation/TabViewManager.swift
1
2182
// // TabViewManager.swift // NativeNavigation // // Created by Leland Richardson on 8/10/16. // Copyright © 2016 Airbnb. All rights reserved. // import React // MARK: - TabView final class TabView: UIView { // init(implementation: ReactNavigationImplementation) { // super.init() // self.implementation = implementation // } // required init?(coder aDecoder: NSCoder) { // fatalError("init(coder:) has not been implemented") // } // MARK: Internal @objc func setRoute(_ route: String!) { self.route = route } @objc func setConfig(_ config: [String: AnyObject]) { self.prevConfig = self.renderedConfig self.renderedConfig = config implementation.reconcileTabConfig( tabBarItem: tabBarItem, prev: prevConfig, next: renderedConfig ); } @objc func setProps(_ props: [String: AnyObject]) { self.props = props } func getViewController() -> UIViewController? { if let viewController = viewController { return viewController } // TODO(lmr): handle non-RN tabs if let route = route { let vc = ReactViewController(moduleName: route, props: props).prepareViewControllerForPresenting() vc.tabBarItem = tabBarItem viewController = vc } return viewController } // MARK: Private private var implementation: ReactNavigationImplementation = ReactNavigationCoordinator.sharedInstance.navigation private var viewController: UIViewController? private var tabBarItem: UITabBarItem = UITabBarItem() private var route: String? private var props: [String: AnyObject] = [:] private var prevConfig: [String: AnyObject] = [:] private var renderedConfig: [String: AnyObject] = [:] } // MARK: - TabViewManager private let VERSION: Int = 1 @objc(TabViewManager) final class TabViewManager: RCTViewManager { override static func requiresMainQueueSetup() -> Bool { return true } override func view() -> UIView! { return TabView() // return TabView(implementation: ReactNavigationCoordinator.sharedInstance.navigation) } override func constantsToExport() -> [AnyHashable: Any] { return [ "VERSION": VERSION ] } }
mit
eccddedd1ff4f4367c603c1d177fdeea
22.451613
114
0.689592
4.327381
false
true
false
false
daaavid/TIY-Assignments
37--Venue-Menu/Venue-Menu/Venue-Menu/DetailViewController.swift
1
2589
// // DetailViewController.swift // Venue-Menu // // Created by david on 11/26/15. // Copyright © 2015 The Iron Yard. All rights reserved. // import UIKit import CoreData import MapKit class DetailViewController: UIViewController { @IBOutlet weak var mapView: MKMapView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var typeLabel: UILabel! @IBOutlet weak var addressLabel: UILabel! @IBOutlet weak var phoneLabel: UILabel! @IBOutlet weak var favoriteButton: UIButton! var venue: NSManagedObject? var location: Location! var delegate: FavoriteWasChosenProtocol? let heartImg = UIImage(named: "heart.png") let filledHeartImg = UIImage(named: "filledheart.png") override func viewDidLoad() { super.viewDidLoad() print(delegate) if let _ = venue { print(venue) nameLabel.text = venue!.valueForKey("name") as? String typeLabel.text = venue!.valueForKey("type") as? String addressLabel.text = venue!.valueForKey("address") as? String phoneLabel.text = venue!.valueForKey("phone") as? String if (venue!.valueForKey("favorite") as! Bool) == true { favoriteButton.setImage(heartImg, forState: .Normal) } showPins() } } func showPins() { let venuePin = MKPointAnnotation() if let venueLat = venue!.valueForKey("lat") as? Double { if let venueLng = venue!.valueForKey("lng") as? Double { venuePin.coordinate = CLLocationCoordinate2DMake(venueLat, venueLng) mapView.addAnnotation(venuePin) } } let selfPin = MKPointAnnotation() selfPin.coordinate = CLLocationCoordinate2DMake(location.lat, location.lng) mapView.addAnnotation(selfPin) mapView.showAnnotations([venuePin, selfPin], animated: true) } @IBAction func favoriteButtonPressed(sender: UIButton) { favoriteButton.spin() if (venue!.valueForKey("favorite") as! Bool) == true { venue?.setValue(false, forKey: "favorite") favoriteButton.setImage(heartImg, forState: .Normal) } else { venue?.setValue(true, forKey: "favorite") favoriteButton.setImage(filledHeartImg, forState: .Normal) delegate?.favoriteVenueWasChosen(venue!) } } }
cc0-1.0
a2b9dc5885306a61fc8137a7990d8d2c
28.409091
84
0.590417
4.910816
false
false
false
false
elliottminns/blackfire
Sources/Blackfire/HTTPResponse.swift
2
1646
import Foundation public class HTTPResponse { let connection: Connection public var status: Int public var headers: [String: String] var body: Buffer { didSet { if body.size > 0 { self.headers["Content-Length"] = "\(body.size)" } } } init(connection: Connection) { self.connection = connection self.status = 200 self.headers = [:] self.body = Buffer(size: 0) } func send() { let status = HTTPStatus(status: self.status) var http = "HTTP/1.1 \(status.stringValue)\r\n" for (key, value) in headers { http += "\(key): \(value)\r\n" } http += "\r\n" http += self.body.toString() connection.write(http) } public func send(status: Int) { self.status = status self.send() } public func send(text: String) { self.headers["Content-Type"] = "text/plain" self.body = Buffer(string: text) send() } public func send(html: String) { self.headers["Content-Type"] = "text/html" self.body = Buffer(string: html) send() } public func send(json: Any) { self.headers["Content-Type"] = "application/json" do { if JSONSerialization.isValidJSONObject(json) { let data = try JSONSerialization.data(withJSONObject: json, options: []) self.body = Buffer(data: data) } else { self.status = 500 } } catch { self.status = 500 } send() } public func send(data: Data) { connection.write(data: data) } public func send(error: String) { status = 500 self.body = Buffer(string: error) self.send() } }
apache-2.0
0e22b0513f56e91b0efead689095ebe1
19.575
80
0.580802
3.674107
false
false
false
false
cafbuddy/cafbuddy-iOS
Caf Buddy/LoginViewController.swift
1
21482
// // LoginViewController.swift // Caf Buddy // // Created by Armaan Bindra on 11/15/14 and Jacob Forster on 2/28/15. // Copyright (c) 2015 St. Olaf Acm. All rights reserved. // import Foundation import UIKit extension String { subscript (r: Range<Int>) -> String { get { let startIndex = advance(self.startIndex, r.startIndex) let endIndex = advance(startIndex, r.endIndex - r.startIndex) return self[Range(start: startIndex, end: endIndex)] } } } let BREAKFAST = "Breakfast" let LUNCH = "Lunch" let DINNER = "Dinner" class LogInViewController: UIViewController,PFLogInViewControllerDelegate,PFSignUpViewControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { let screenSize: CGRect = UIScreen.mainScreen().bounds var collectionViewMain : UICollectionView? var mealsArrayUpcoming = NSMutableArray() var mealsArrayPending = NSMutableArray() var numMeals = 0 var showChatScreen = false var chatScreenMatchId = "" override func viewDidLoad() { super.viewDidLoad() println("View Did Load") startMealScreen() } init(chatScreen:Bool,matchId:String) { let alert = UIAlertView() alert.title = "New Message" alert.message = "You got a new message from your buddy!" alert.addButtonWithTitle("Cancel") alert.show() showChatScreen = chatScreen chatScreenMatchId = matchId super.init(nibName: nil, bundle: nil) } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func startMealScreen() { println("Start Meal Screen Called") if var currentUser = PFUser.currentUser() { if var emailVerified = currentUser.objectForKey("emailVerified") as? Bool { println("Current User is \(currentUser.email)") navigationController?.navigationBar.barTintColor = colorWithHexString(COLOR_ACCENT_BLUE) navigationItem.title = "Upcoming Meals" navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : UIColor.whiteColor()] initInterface() } else { showLoginView() showEmailNotVerifiedAlert() } } else { showLoginView() } } func showEmailNotVerifiedAlert() { let alert = UIAlertView() alert.title = "Email Not Verified" alert.message = "Please Check and Verify Your Email Before Logging In" alert.addButtonWithTitle("Cancel") alert.show() } func showChatViewController(matchId:String) { let chatVC = ChatViewController(myMatchId: matchId ) navigationController?.pushViewController(chatVC, animated: false) } override func viewDidAppear(animated: Bool) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadTableFromServer", name:ReloadMealTableNotification, object: nil) //println("email verified is \(emailVerified)") super.viewDidAppear(animated) println("View Did Appear Called") if(showChatScreen){ showChatViewController(chatScreenMatchId) } else{ startMealScreen() } } func chatButtonWasPressed(sender : UIButton!) { showChatViewController("test") } func showLoginView() { let logInViewController:PFLogInViewController = MyLoginViewController() logInViewController.delegate = self let signUpViewController = MySignUpViewController() signUpViewController.delegate = self logInViewController.signUpController = signUpViewController presentViewController(logInViewController, animated: true, completion: nil) } // MARK: Login View Controller Delegate Methods func logInViewController(logInController: PFLogInViewController!, shouldBeginLogInWithUsername username: String!, password: String!) -> Bool { if ((username != nil) && (password != nil) && (countElements(username) != 0) && (countElements(password) != 0)) { return true } let alert = UIAlertView() alert.title = "Missing Information" alert.message = "Make Sure You Fill Out All Your Information" alert.addButtonWithTitle("Cancel") alert.show() return false } func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) { dismissViewControllerAnimated(true, completion: nil) println("User Login Succesful") /* PFInstallation *installation = [PFInstallation currentInstallation]; installation[@"user"] = [PFUser currentUser]; [installation saveInBackground];*/ let installation = PFInstallation.currentInstallation() installation["userId"] = PFUser.currentUser() installation.saveInBackground() //goToMainFeed() //updateInterface() } func logInViewController(logInController: PFLogInViewController!, didFailToLogInWithError error: NSError!) { println("Failed to Log In") } func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController!) { navigationController?.popViewControllerAnimated(true) } func signUpViewControllerDidCancelSignUp(signUpController: MySignUpViewController!) { println("User Dismissed the Sign Up View Controller") } func signUpViewController(signUpController: MySignUpViewController!, shouldBeginSignUp info: [NSObject : AnyObject]!) -> Bool { //println(info) var message = "" var isValid = true var emailEnd = "" for (key, value) in info { let fieldValue: AnyObject? = value println("Key is \(key) and values is \(value)") if key == "username" { var email = value as String let emailLength = countElements(email) if emailLength > 11 { emailEnd = email[(emailLength-11)...(emailLength-1)] } else { isValid = false message = message+"Sorry Email too short." } if (email.rangeOfString("@") == nil) { isValid = false println("Email Invalid does not contain @ sign") message = message+" Email does not contain @ sign." break } if (emailEnd != "@stolaf.edu" ) { isValid = false println("Sorry we only accept St Olaf Emails") message = message+" Email Invalid, Sorry we only accept St Olaf Emails." break } } if ((fieldValue == nil) || fieldValue?.length == 0) { // check completion isValid = false; break; } if ((fieldValue == nil) || fieldValue?.length < 8) { // check completion isValid = false; message = message+" Password needs to be at least 8 characters long." break; } } if(!isValid){ let alert = UIAlertView() alert.title = "Error!" alert.message = message alert.addButtonWithTitle("Cancel") alert.show() } return isValid } func signUpViewController(signUpController: MySignUpViewController!, didSignUpUser user: PFUser!) { dismissViewControllerAnimated(true, completion: nil) } func signUpViewController(signUpController: MySignUpViewController!, didFailToSignUpWithError error: NSError!) { println("Failed to sign up...") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func initInterface() { var screenWidth = Float(self.view.frame.size.width) var screenHeight = Float(self.view.frame.size.height) let collectionViewLayout : UICollectionViewFlowLayout = UICollectionViewFlowLayout() collectionViewLayout.minimumLineSpacing = 15 collectionViewLayout.sectionInset = UIEdgeInsetsMake(15, 15, 15, 15) collectionViewLayout.itemSize = CGSizeMake(screenSize.width - 30, 150) collectionViewLayout.headerReferenceSize = CGSizeMake(screenSize.width, 40) collectionViewMain = UICollectionView(frame: CGRectMake(0, CGFloat(NAV_BAR_HEIGHT) + CGFloat(STATUS_BAR_HEIGHT), screenSize.width, screenSize.height - (CGFloat(NAV_BAR_HEIGHT) + CGFloat(STATUS_BAR_HEIGHT) + CGFloat(TAB_BAR_HEIGHT))), collectionViewLayout: collectionViewLayout) collectionViewMain!.delegate = self; collectionViewMain!.dataSource = self; collectionViewMain!.alwaysBounceVertical = true collectionViewMain!.registerClass(MealListingCell.self, forCellWithReuseIdentifier: "mealCell") collectionViewMain!.registerClass(MealListingHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header") collectionViewMain!.backgroundColor = colorWithHexString(COLOR_MAIN_BACKGROUND_OFFWHITE) self.view.addSubview(collectionViewMain!) } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 4 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let mealCell = collectionViewMain!.dequeueReusableCellWithReuseIdentifier("mealCell", forIndexPath: indexPath) as MealListingCell mealCell.backgroundColor = UIColor.whiteColor() var theMealStatus = MealStatus.Confirmed if (indexPath.section == 1) { theMealStatus = MealStatus.Pending } if (indexPath.item%3 == 0) { mealCell.setMealDetails(MealType.Breakfast, theMealStatus : theMealStatus) } else if (indexPath.item%3 == 1) { mealCell.setMealDetails(MealType.Lunch, theMealStatus : theMealStatus) } else { mealCell.setMealDetails(MealType.Dinner, theMealStatus : theMealStatus) } mealCell.buttonChatAndStatus.addTarget(self, action: "chatButtonWasPressed:", forControlEvents: UIControlEvents.TouchUpInside) return mealCell } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 2 } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { var headerView = collectionViewMain!.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "header", forIndexPath: indexPath) as MealListingHeader if (indexPath.section == 0) { headerView.setTitle("Upcoming", sectionIndex : indexPath.section) } else { headerView.setTitle("Pending", sectionIndex : indexPath.section) } return headerView } /* func reloadTableFromServer() { var userObjectID = PFUser.currentUser().objectId //println(userObjectID) //println("Something should print") PFCloud.callFunctionInBackground("getMealsToday", withParameters:["objectID":userObjectID]) { (result: AnyObject!, error: NSError!) -> Void in if error == nil { //println("Something should print") //println(result) //var test = "{\"firstName\":\"John\", \"lastName\":\"Doe\"}" let testData = (result as NSString).dataUsingEncoding(NSUTF8StringEncoding) let jsonObject = JSON(data: testData!, options: nil, error: nil) //println(jsonObject[0]["createdAt"].stringValue) //Empty All Arrays self.mealsArrayU.removeAllObjects() self.mealsArrayP.removeAllObjects() //println("NumMeals is \(self.numMeals)") for (var i=0;i<jsonObject.count;i++) { self.numMeals = jsonObject.count var meal = jsonObject[i]["type"].stringValue var mealItem = Dictionary<String, String>() mealItem["matchId"] = jsonObject[i]["matchId"].stringValue//Adding Found matchIds to array if meal=="0" { mealItem["meals"] = BREAKFAST } else if meal=="1" { mealItem["meals"] = LUNCH } else if meal=="2" { mealItem["meals"] = DINNER } mealItem["mealId"] = jsonObject[i]["objectId"].stringValue if !(jsonObject[i]["matched"].stringValue=="true") { mealItem["ifMatched"] = "false" var sTime = jsonObject[i]["start"]["iso"].stringValue var formatterS = NSDateFormatter() formatterS.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatterS.timeZone = NSTimeZone(forSecondsFromGMT: 0) var dateS = formatterS.dateFromString(sTime) formatterS.timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.localTimeZone().secondsFromGMT) formatterS.dateFormat = "hh:mm a" var localSTime = formatterS.stringFromDate(dateS!) mealItem["startTime"] = localSTime var eTime = jsonObject[i]["end"]["iso"].stringValue var formatterE = NSDateFormatter() formatterE.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatterE.timeZone = NSTimeZone(forSecondsFromGMT: 0) var dateE = formatterE.dateFromString(eTime) formatterE.timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.localTimeZone().secondsFromGMT) formatterE.dateFormat = "hh:mm a" var localETime = formatterE.stringFromDate(dateE!) mealItem["endTime"] = localETime mealItem["matchString"] = "Finding Match" mealItem["mealTimeRange"] = "\(localSTime) - \(localETime)" } else { var sTime = jsonObject[i]["start"]["iso"].stringValue var formatterS = NSDateFormatter() formatterS.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" formatterS.timeZone = NSTimeZone(forSecondsFromGMT: 0) var dateS = formatterS.dateFromString(sTime) formatterS.timeZone = NSTimeZone(forSecondsFromGMT: NSTimeZone.localTimeZone().secondsFromGMT) formatterS.dateFormat = "hh:mm a" var localSTime = formatterS.stringFromDate(dateS!) mealItem["startTime"] = localSTime mealItem["endTime"] = "" mealItem["ifMatched"] = "true" mealItem["matchString"] = "Match Found" mealItem["mealTimeRange"] = "" } if (jsonObject[i]["matched"].stringValue=="true") { self.mealsArrayU.addObject(mealItem) } else if(jsonObject[i]["matched"].stringValue=="false") { self.mealsArrayP.addObject(mealItem) } } //println(self.mealsArrayU) //println("Pause") //println(self.mealsArrayP) //self.mainTableView.reloadData() //self.updateInterface() /*dispatch_async(dispatch_get_main_queue(), { () -> Void in self.mainTableView.reloadData() })*/ } else{ println("error") } } } */ // MARK: Table Methods /*func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { if mealsArrayU.count == 0 { return 1} return mealsArrayU.count } if mealsArrayP.count == 0 { return 1} return mealsArrayP.count } func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool { if indexPath.section == 1 { if mealsArrayP.count == 0 { return false} return true } return false } func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) { if (editingStyle == UITableViewCellEditingStyle.Delete) { var query = PFQuery(className:"Meals") query.whereKey("objectId", equalTo: mealsArrayP[indexPath.row]["mealId"] as String) mealsArrayP.removeObjectAtIndex(indexPath.row) self.mainTableView.reloadData() query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in if error == nil { // The find succeeded. NSLog("Successfully retrieved \(objects.count) scores.") // Do something with the found objects for object in objects { NSLog("%@", object.objectId) object.deleteInBackgroundWithBlock({ (succeeded: Bool, error: NSError!) in if succeeded { //self.reloadTableFromServer() } }) } } else { // Log details of the failure NSLog("Error: %@ %@", error, error.userInfo!) } } } } /*func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { //if first section if (section == 0) { return "Upcoming Meals" } //if second section return "Pending Matches" }*/ func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { var view = UIView(frame: CGRectMake(0, 0, tableView.frame.size.width, 18)) /* Create custom view to display section header... */ var label = UILabel() label.font = UIFont.boldSystemFontOfSize(16.0) label.textAlignment = NSTextAlignment.Center label.frame = CGRectMake(0, 0, tableView.frame.size.width, 50) var string = "Test" if (section == 0) { string = "Upcoming Meals" } else{ //if second section string = "Pending Matches" } /* Section header is in 0th index... */ label.text = string view.addSubview(label) view.backgroundColor = colorWithHexString(COLOR_MAIN_BACKGROUND_OFFWHITE) return view; } func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 50.0 } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var mealsArray:NSMutableArray! if (indexPath.section == 0) {mealsArray = mealsArrayU if mealsArrayU.count == 0 { return} } else {mealsArray = mealsArrayP if mealsArrayP.count == 0 { return} } if( mealsArray[indexPath.row]["ifMatched"] as String == "true" ) { //let chatVC = ChatViewController(myMatchId: mealsArray[indexPath.row]["matchId"] as String ) let chatVC = ChatViewControllerTest(myMatchId: mealsArray[indexPath.row]["matchId"] as String ) UIView.beginAnimations("ShowDetails", context: nil) UIView.setAnimationCurve(UIViewAnimationCurve.EaseInOut) UIView.setAnimationDuration(0.5) navigationController?.pushViewController(chatVC, animated: false) let theView = navigationController?.view UIView.setAnimationTransition(UIViewAnimationTransition.FlipFromRight, forView: theView!, cache: false) //UIView.setAnimationTransition(UIViewAnimationTransition.CurlUp, forView: theView!, cache: false) UIView.commitAnimations() mainTableView.allowsSelection = false } } func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) { } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 180.0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var customcell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as CustomTableViewCell var mealsArray:NSMutableArray! if (indexPath.section == 0) { customcell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator mealsArray = mealsArrayU if mealsArrayU.count == 0 { customcell.loadItem("You have",rangeOfTime: "",timeOfMeal: "NO",matching: "Upcoming Meals!!") return customcell } } else {mealsArray = mealsArrayP if mealsArrayP.count == 0 { customcell.loadItem("You have",rangeOfTime: "",timeOfMeal: "NO",matching: "Pending Matches!!") return customcell } } println(mealsArray) customcell.whichMeal.text = mealsArray[indexPath.row]["meals"] as? String var tempMealType = mealsArray[indexPath.row]["meals"] as String var tempStartTime = mealsArray[indexPath.row]["startTime"] as String var tempMatchingString = mealsArray[indexPath.row]["matchString"] as String! var tempMealRange = mealsArray[indexPath.row]["mealTimeRange"] as String if (mealsArray[indexPath.row]["ifMatched"] as String == "true") { customcell.loadItem("\(tempMealType)",rangeOfTime: "",timeOfMeal: "\(tempStartTime)",matching: "\(tempMatchingString)") } else { customcell.loadItem("\(tempMealType)",rangeOfTime: "\(tempMealRange)",timeOfMeal: "",matching: "\(tempMatchingString)") } return customcell }*/ }
mit
d98966781c6d9c0f6649c2910332d4e6
34.864775
285
0.641188
5.04154
false
false
false
false
Acidburn0zzz/firefox-ios
WidgetKit/OpenTabs/TabProvider.swift
1
2788
/* 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 SwiftUI import WidgetKit import UIKit import Combine struct TabProvider: TimelineProvider { public typealias Entry = OpenTabsEntry var tabsDict: [String: SimpleTab] = [:] func placeholder(in context: Context) -> OpenTabsEntry { OpenTabsEntry(date: Date(), favicons: [String: Image](), tabs: []) } func getSnapshot(in context: Context, completion: @escaping (OpenTabsEntry) -> Void) { let allOpenTabs = SiteArchiver.tabsToRestore(tabsStateArchivePath: tabsStateArchivePath()).1 let openTabs = allOpenTabs.values.filter { !$0.isPrivate } var tabFaviconDictionary = [String : Image]() let simpleTabs = SimpleTab.getSimpleTabs() for (_ , tab) in simpleTabs { guard !tab.imageKey.isEmpty else { continue } let fetchedImage = FaviconFetcher.getFaviconFromDiskCache(imageKey: tab.imageKey) let bundledFavicon = getBundledFavicon(siteUrl: tab.url) let letterFavicon = FaviconFetcher.letter(forUrl: tab.url ?? URL(string: "about:blank")!) let image = bundledFavicon ?? fetchedImage ?? letterFavicon tabFaviconDictionary[tab.imageKey] = Image(uiImage: image) } let openTabsEntry = OpenTabsEntry(date: Date(), favicons: tabFaviconDictionary, tabs: openTabs) completion(openTabsEntry) } func getBundledFavicon(siteUrl: URL?) -> UIImage? { guard let url = siteUrl else { return nil } // Get the bundled favicon if available guard let bundled = FaviconFetcher.getBundledIcon(forUrl: url), let image = UIImage(contentsOfFile: bundled.filePath) else { return nil } return image } func getTimeline(in context: Context, completion: @escaping (Timeline<OpenTabsEntry>) -> Void) { getSnapshot(in: context, completion: { openTabsEntry in let timeline = Timeline(entries: [openTabsEntry], policy: .atEnd) completion(timeline) }) } fileprivate func tabsStateArchivePath() -> String? { let profilePath: String? profilePath = FileManager.default.containerURL( forSecurityApplicationGroupIdentifier: AppInfo.sharedContainerIdentifier)?.appendingPathComponent("profile.profile").path guard let path = profilePath else { return nil } return URL(fileURLWithPath: path).appendingPathComponent("tabsState.archive").path } } struct OpenTabsEntry: TimelineEntry { let date: Date let favicons: [String : Image] let tabs: [SimpleTab] }
mpl-2.0
301e979d51dd41f6b32d6024b49e8556
41.242424
177
0.672166
4.623549
false
false
false
false
LuAndreCast/iOS_AudioRecordersAndPlayers
player_SystemSound/SystemSound/SoundSystem.swift
1
1351
// // SoundSystem.swift // SystemSound // // Created by Luis Castillo on 1/28/17. // Copyright © 2017 lc. All rights reserved. // import Foundation import AudioToolbox class SoundSystem: NSObject { private var soundID:SystemSoundID = 0 override init() { super.init() }//eoc //MARK: - Setup func setup()->Bool { guard let soundURLPath:URL = Bundle.main.url(forResource: "MetalBell", withExtension: "wav") else { print("sound path invalid") return false } guard let soundURL:CFURL = soundURLPath as CFURL? else { print("CFURL conversion failed") return false } let status:OSStatus = AudioServicesCreateSystemSoundID(soundURL, &soundID) switch status { case noErr: print("No Errors") return true default: print("Something Happen") return false } }//eom //MARK: - Actions func playSound( vibrate:Bool = true) { AudioServicesPlaySystemSound(self.soundID) if vibrate { AudioServicesPlayAlertSound(kSystemSoundID_Vibrate) } }//eom func unsetup() { AudioServicesDisposeSystemSoundID(self.soundID) }//eom }
mit
017ec0b00d695b67ecfffed7c6631418
21.131148
107
0.56
4.909091
false
false
false
false
IngmarStein/swift
stdlib/public/core/ContiguousArrayBuffer.swift
1
22643
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims /// Class used whose sole instance is used as storage for empty /// arrays. The instance is defined in the runtime and statically /// initialized. See stdlib/runtime/GlobalObjects.cpp for details. /// Because it's statically referenced, it requires non-lazy realization /// by the Objective-C runtime. @objc_non_lazy_realization internal final class _EmptyArrayStorage : _ContiguousArrayStorageBase { init(_doNotCallMe: ()) { _sanityCheckFailure("creating instance of _EmptyArrayStorage") } #if _runtime(_ObjC) override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { return try body(UnsafeBufferPointer(start: nil, count: 0)) } // FIXME(ABI)#26 (Type Checker): remove 'Void' arguments here and elsewhere in this file, they // are a workaround for an old compiler limitation. override func _getNonVerbatimBridgedCount(_ dummy: Void) -> Int { return 0 } override func _getNonVerbatimBridgedHeapBuffer( _ dummy: Void ) -> _HeapBuffer<Int, AnyObject> { return _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, 0, 0) } #endif override func canStoreElements(ofDynamicType _: Any.Type) -> Bool { return false } /// A type that every element in the array is. override var staticElementType: Any.Type { return Void.self } } /// The empty array prototype. We use the same object for all empty /// `[Native]Array<Element>`s. internal var _emptyArrayStorage : _EmptyArrayStorage { return Builtin.bridgeFromRawPointer( Builtin.addressof(&_swiftEmptyArrayStorage)) } // FIXME(ABI)#141 : This whole class is a workaround for // <rdar://problem/18560464> Can't override generic method in generic // subclass. If it weren't for that bug, we'd override // _withVerbatimBridgedUnsafeBuffer directly in // _ContiguousArrayStorage<Element>. // rdar://problem/19341002 class _ContiguousArrayStorage1 : _ContiguousArrayStorageBase { #if _runtime(_ObjC) /// If the `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements and return the result. /// Otherwise, return `nil`. final override func _withVerbatimBridgedUnsafeBuffer<R>( _ body: (UnsafeBufferPointer<AnyObject>) throws -> R ) rethrows -> R? { var result: R? try self._withVerbatimBridgedUnsafeBufferImpl { result = try body($0) } return result } /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. internal func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { _sanityCheckFailure( "Must override _withVerbatimBridgedUnsafeBufferImpl in derived classes") } #endif } // The class that implements the storage for a ContiguousArray<Element> @_versioned final class _ContiguousArrayStorage<Element> : _ContiguousArrayStorage1 { deinit { _elementPointer.deinitialize(count: countAndCapacity.count) _fixLifetime(self) } #if _runtime(_ObjC) /// If `Element` is bridged verbatim, invoke `body` on an /// `UnsafeBufferPointer` to the elements. internal final override func _withVerbatimBridgedUnsafeBufferImpl( _ body: (UnsafeBufferPointer<AnyObject>) throws -> Void ) rethrows { if _isBridgedVerbatimToObjectiveC(Element.self) { let count = countAndCapacity.count let elements = UnsafeRawPointer(_elementPointer) .assumingMemoryBound(to: AnyObject.self) defer { _fixLifetime(self) } try body(UnsafeBufferPointer(start: elements, count: count)) } } /// Returns the number of elements in the array. /// /// - Precondition: `Element` is bridged non-verbatim. override internal func _getNonVerbatimBridgedCount(_ dummy: Void) -> Int { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") return countAndCapacity.count } /// Bridge array elements and return a new buffer that owns them. /// /// - Precondition: `Element` is bridged non-verbatim. override internal func _getNonVerbatimBridgedHeapBuffer(_ dummy: Void) -> _HeapBuffer<Int, AnyObject> { _sanityCheck( !_isBridgedVerbatimToObjectiveC(Element.self), "Verbatim bridging should be handled separately") let count = countAndCapacity.count let result = _HeapBuffer<Int, AnyObject>( _HeapBufferStorage<Int, AnyObject>.self, count, count) let resultPtr = result.baseAddress let p = _elementPointer for i in 0..<count { (resultPtr + i).initialize(to: _bridgeAnythingToObjectiveC(p[i])) } _fixLifetime(self) return result } #endif /// Returns `true` if the `proposedElementType` is `Element` or a subclass of /// `Element`. We can't store anything else without violating type /// safety; for example, the destructor has static knowledge that /// all of the elements can be destroyed as `Element`. override func canStoreElements( ofDynamicType proposedElementType: Any.Type ) -> Bool { #if _runtime(_ObjC) return proposedElementType is Element.Type #else // FIXME: Dynamic casts don't currently work without objc. // rdar://problem/18801510 return false #endif } /// A type that every element in the array is. override var staticElementType: Any.Type { return Element.self } internal final var _elementPointer : UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(self, Element.self)) } } @_fixed_layout internal struct _ContiguousArrayBuffer<Element> : _ArrayBufferProtocol { /// Make a buffer with uninitialized elements. After using this /// method, you must either initialize the `count` elements at the /// result's `.firstElementAddress` or set the result's `.count` /// to zero. internal init( _uninitializedCount uninitializedCount: Int, minimumCapacity: Int ) { let realMinimumCapacity = Swift.max(uninitializedCount, minimumCapacity) if realMinimumCapacity == 0 { self = _ContiguousArrayBuffer<Element>() } else { _storage = Builtin.allocWithTailElems_1( _ContiguousArrayStorage<Element>.self, realMinimumCapacity._builtinWordValue, Element.self) let storageAddr = UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(_storage)) let endAddr = storageAddr + _swift_stdlib_malloc_size(storageAddr) let realCapacity = endAddr.assumingMemoryBound(to: Element.self) - firstElementAddress _initStorageHeader( count: uninitializedCount, capacity: realCapacity) } } /// Initialize using the given uninitialized `storage`. /// The storage is assumed to be uninitialized. The returned buffer has the /// body part of the storage initialized, but not the elements. /// /// - Warning: The result has uninitialized elements. /// /// - Warning: storage may have been stack-allocated, so it's /// crucial not to call, e.g., `malloc_size` on it. internal init(count: Int, storage: _ContiguousArrayStorage<Element>) { _storage = storage _initStorageHeader(count: count, capacity: count) } internal init(_ storage: _ContiguousArrayStorageBase) { _storage = storage } /// Initialize the body part of our storage. /// /// - Warning: does not initialize elements internal func _initStorageHeader(count: Int, capacity: Int) { #if _runtime(_ObjC) let verbatim = _isBridgedVerbatimToObjectiveC(Element.self) #else let verbatim = false #endif // We can initialize by assignment because _ArrayBody is a trivial type, // i.e. contains no references. _storage.countAndCapacity = _ArrayBody( count: count, capacity: capacity, elementTypeIsBridgedVerbatim: verbatim) } /// True, if the array is native and does not need a deferred type check. internal var arrayPropertyIsNativeTypeChecked: Bool { return true } /// A pointer to the first element. internal var firstElementAddress: UnsafeMutablePointer<Element> { return UnsafeMutablePointer(Builtin.projectTailElems(_storage, Element.self)) } internal var firstElementAddressIfContiguous: UnsafeMutablePointer<Element>? { return firstElementAddress } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. internal func withUnsafeBufferPointer<R>( _ body: (UnsafeBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body(UnsafeBufferPointer(start: firstElementAddress, count: count)) } /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. internal mutating func withUnsafeMutableBufferPointer<R>( _ body: (UnsafeMutableBufferPointer<Element>) throws -> R ) rethrows -> R { defer { _fixLifetime(self) } return try body( UnsafeMutableBufferPointer(start: firstElementAddress, count: count)) } //===--- _ArrayBufferProtocol conformance -----------------------------------===// /// Create an empty buffer. internal init() { _storage = _emptyArrayStorage } internal init(_buffer buffer: _ContiguousArrayBuffer, shiftedToStartIndex: Int) { _sanityCheck(shiftedToStartIndex == 0, "shiftedToStartIndex must be 0") self = buffer } internal mutating func requestUniqueMutableBackingBuffer( minimumCapacity: Int ) -> _ContiguousArrayBuffer<Element>? { if _fastPath(isUniquelyReferenced() && capacity >= minimumCapacity) { return self } return nil } internal mutating func isMutableAndUniquelyReferenced() -> Bool { return isUniquelyReferenced() } internal mutating func isMutableAndUniquelyReferencedOrPinned() -> Bool { return isUniquelyReferencedOrPinned() } /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. internal func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? { return self } @_versioned internal func getElement(_ i: Int) -> Element { _sanityCheck(i >= 0 && i < count, "Array index out of range") return firstElementAddress[i] } /// Get or set the value of the ith element. internal subscript(i: Int) -> Element { get { return getElement(i) } nonmutating set { _sanityCheck(i >= 0 && i < count, "Array index out of range") // FIXME: Manually swap because it makes the ARC optimizer happy. See // <rdar://problem/16831852> check retain/release order // firstElementAddress[i] = newValue var nv = newValue let tmp = nv nv = firstElementAddress[i] firstElementAddress[i] = tmp } } /// The number of elements the buffer stores. internal var count: Int { get { return _storage.countAndCapacity.count } nonmutating set { _sanityCheck(newValue >= 0) _sanityCheck( newValue <= capacity, "Can't grow an array buffer past its capacity") _storage.countAndCapacity.count = newValue } } /// Traps unless the given `index` is valid for subscripting, i.e. /// `0 ≤ index < count`. @inline(__always) func _checkValidSubscript(_ index : Int) { _precondition( (index >= 0) && (index < count), "Index out of range" ) } /// The number of elements the buffer can store without reallocation. internal var capacity: Int { return _storage.countAndCapacity.capacity } /// Copy the elements in `bounds` from this buffer into uninitialized /// memory starting at `target`. Return a pointer "past the end" of the /// just-initialized memory. @discardableResult internal func _copyContents( subRange bounds: Range<Int>, initializing target: UnsafeMutablePointer<Element> ) -> UnsafeMutablePointer<Element> { _sanityCheck(bounds.lowerBound >= 0) _sanityCheck(bounds.upperBound >= bounds.lowerBound) _sanityCheck(bounds.upperBound <= count) let initializedCount = bounds.upperBound - bounds.lowerBound target.initialize( from: firstElementAddress + bounds.lowerBound, count: initializedCount) _fixLifetime(owner) return target + initializedCount } /// Returns a `_SliceBuffer` containing the given `bounds` of values /// from this buffer. internal subscript(bounds: Range<Int>) -> _SliceBuffer<Element> { get { return _SliceBuffer( owner: _storage, subscriptBaseAddress: subscriptBaseAddress, indices: bounds, hasNativeBuffer: true) } set { fatalError("not implemented") } } /// Returns `true` iff this buffer's storage is uniquely-referenced. /// /// - Note: This does not mean the buffer is mutable. Other factors /// may need to be considered, such as whether the buffer could be /// some immutable Cocoa container. internal mutating func isUniquelyReferenced() -> Bool { return _isUnique(&_storage) } /// Returns `true` iff this buffer's storage is either /// uniquely-referenced or pinned. NOTE: this does not mean /// the buffer is mutable; see the comment on isUniquelyReferenced. internal mutating func isUniquelyReferencedOrPinned() -> Bool { return _isUniqueOrPinned(&_storage) } #if _runtime(_ObjC) /// Convert to an NSArray. /// /// - Precondition: `Element` is bridged to Objective-C. /// /// - Complexity: O(1). internal func _asCocoaArray() -> _NSArrayCore { if count == 0 { return _emptyArrayStorage } if _isBridgedVerbatimToObjectiveC(Element.self) { return _storage } return _SwiftDeferredNSArray(_nativeStorage: _storage) } #endif /// An object that keeps the elements stored in this buffer alive. internal var owner: AnyObject { return _storage } /// An object that keeps the elements stored in this buffer alive. internal var nativeOwner: AnyObject { return _storage } /// A value that identifies the storage used by the buffer. /// /// Two buffers address the same elements when they have the same /// identity and count. internal var identity: UnsafeRawPointer { return UnsafeRawPointer(firstElementAddress) } /// Returns `true` iff we have storage for elements of the given /// `proposedElementType`. If not, we'll be treated as immutable. func canStoreElements(ofDynamicType proposedElementType: Any.Type) -> Bool { return _storage.canStoreElements(ofDynamicType: proposedElementType) } /// Returns `true` if the buffer stores only elements of type `U`. /// /// - Precondition: `U` is a class or `@objc` existential. /// /// - Complexity: O(*n*) func storesOnlyElementsOfType<U>( _: U.Type ) -> Bool { _sanityCheck(_isClassOrObjCExistential(U.self)) if _fastPath(_storage.staticElementType is U.Type) { // Done in O(1) return true } // Check the elements for x in self { if !(x is U) { return false } } return true } internal var _storage: _ContiguousArrayStorageBase } /// Append the elements of `rhs` to `lhs`. internal func += <Element, C : Collection>( lhs: inout _ContiguousArrayBuffer<Element>, rhs: C ) where C.Iterator.Element == Element { let oldCount = lhs.count let newCount = oldCount + numericCast(rhs.count) if _fastPath(newCount <= lhs.capacity) { lhs.count = newCount (lhs.firstElementAddress + oldCount).initialize(from: rhs) } else { var newLHS = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCount, minimumCapacity: _growArrayCapacity(lhs.capacity)) newLHS.firstElementAddress.moveInitialize( from: lhs.firstElementAddress, count: oldCount) lhs.count = 0 swap(&lhs, &newLHS) (lhs.firstElementAddress + oldCount).initialize(from: rhs) } } extension _ContiguousArrayBuffer : RandomAccessCollection { /// The position of the first element in a non-empty collection. /// /// In an empty collection, `startIndex == endIndex`. internal var startIndex: Int { return 0 } /// The collection's "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `index(after:)`. internal var endIndex: Int { return count } internal typealias Indices = CountableRange<Int> } extension Sequence { public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { return _copySequenceToContiguousArray(self) } } internal func _copySequenceToContiguousArray< S : Sequence >(_ source: S) -> ContiguousArray<S.Iterator.Element> { let initialCapacity = source.underestimatedCount var builder = _UnsafePartiallyInitializedContiguousArrayBuffer<S.Iterator.Element>( initialCapacity: initialCapacity) var iterator = source.makeIterator() // FIXME(performance): use _copyContents(initializing:). // Add elements up to the initial capacity without checking for regrowth. for _ in 0..<initialCapacity { builder.addWithExistingCapacity(iterator.next()!) } // Add remaining elements, if any. while let element = iterator.next() { builder.add(element) } return builder.finish() } extension Collection { public func _copyToContiguousArray() -> ContiguousArray<Iterator.Element> { return _copyCollectionToContiguousArray(self) } } extension _ContiguousArrayBuffer { internal func _copyToContiguousArray() -> ContiguousArray<Element> { return ContiguousArray(_buffer: self) } } /// This is a fast implementation of _copyToContiguousArray() for collections. /// /// It avoids the extra retain, release overhead from storing the /// ContiguousArrayBuffer into /// _UnsafePartiallyInitializedContiguousArrayBuffer. Since we do not support /// ARC loops, the extra retain, release overhead cannot be eliminated which /// makes assigning ranges very slow. Once this has been implemented, this code /// should be changed to use _UnsafePartiallyInitializedContiguousArrayBuffer. internal func _copyCollectionToContiguousArray< C : Collection >(_ source: C) -> ContiguousArray<C.Iterator.Element> { let count: Int = numericCast(source.count) if count == 0 { return ContiguousArray() } let result = _ContiguousArrayBuffer<C.Iterator.Element>( _uninitializedCount: count, minimumCapacity: 0) var p = result.firstElementAddress var i = source.startIndex for _ in 0..<count { // FIXME(performance): use _copyContents(initializing:). p.initialize(to: source[i]) source.formIndex(after: &i) p += 1 } _expectEnd(i, source) return ContiguousArray(_buffer: result) } /// A "builder" interface for initializing array buffers. /// /// This presents a "builder" interface for initializing an array buffer /// element-by-element. The type is unsafe because it cannot be deinitialized /// until the buffer has been finalized by a call to `finish`. internal struct _UnsafePartiallyInitializedContiguousArrayBuffer<Element> { internal var result: _ContiguousArrayBuffer<Element> internal var p: UnsafeMutablePointer<Element> internal var remainingCapacity: Int /// Initialize the buffer with an initial size of `initialCapacity` /// elements. @inline(__always) // For performance reasons. init(initialCapacity: Int) { if initialCapacity == 0 { result = _ContiguousArrayBuffer() } else { result = _ContiguousArrayBuffer( _uninitializedCount: initialCapacity, minimumCapacity: 0) } p = result.firstElementAddress remainingCapacity = result.capacity } /// Add an element to the buffer, reallocating if necessary. @inline(__always) // For performance reasons. mutating func add(_ element: Element) { if remainingCapacity == 0 { // Reallocate. let newCapacity = max(_growArrayCapacity(result.capacity), 1) var newResult = _ContiguousArrayBuffer<Element>( _uninitializedCount: newCapacity, minimumCapacity: 0) p = newResult.firstElementAddress + result.capacity remainingCapacity = newResult.capacity - result.capacity newResult.firstElementAddress.moveInitialize( from: result.firstElementAddress, count: result.capacity) result.count = 0 swap(&result, &newResult) } addWithExistingCapacity(element) } /// Add an element to the buffer, which must have remaining capacity. @inline(__always) // For performance reasons. mutating func addWithExistingCapacity(_ element: Element) { _sanityCheck(remainingCapacity > 0, "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity") remainingCapacity -= 1 p.initialize(to: element) p += 1 } /// Finish initializing the buffer, adjusting its count to the final /// number of elements. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inline(__always) // For performance reasons. mutating func finish() -> ContiguousArray<Element> { // Adjust the initialized count of the buffer. result.count = result.capacity - remainingCapacity return finishWithOriginalCount() } /// Finish initializing the buffer, assuming that the number of elements /// exactly matches the `initialCount` for which the initialization was /// started. /// /// Returns the fully-initialized buffer. `self` is reset to contain an /// empty buffer and cannot be used afterward. @inline(__always) // For performance reasons. mutating func finishWithOriginalCount() -> ContiguousArray<Element> { _sanityCheck(remainingCapacity == result.capacity - result.count, "_UnsafePartiallyInitializedContiguousArrayBuffer has incorrect count") var finalResult = _ContiguousArrayBuffer<Element>() swap(&finalResult, &result) remainingCapacity = 0 return ContiguousArray(_buffer: finalResult) } }
apache-2.0
a1273f7814dfdd354b7d033906913d50
31.813043
96
0.695994
4.762516
false
false
false
false
koher/Alamofire
Source/Manager.swift
1
21263
// Alamofire.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // 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 /** Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`. */ public class Manager { // MARK: - Properties /** A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly for any ad hoc requests. */ public static let sharedInstance: Manager = { let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. :returns: The default header values. */ public static let defaultHTTPHeaders: [String: String] = { // Accept-Encoding HTTP Header; see http://tools.ietf.org/html/rfc7230#section-4.2.3 let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5" // Accept-Language HTTP Header; see http://tools.ietf.org/html/rfc7231#section-5.3.5 let acceptLanguage: String = { var components: [String] = [] for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as! [String]) { let q = 1.0 - (Double(index) * 0.1) components.append("\(languageCode);q=\(q)") if q <= 0.5 { break } } return join(",", components) }() // User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3 let userAgent: String = { if let info = NSBundle.mainBundle().infoDictionary { let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown" let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown" let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown" let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown" var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 { return mutableUserAgent as String } } return "Alamofire" }() return [ "Accept-Encoding": acceptEncoding, "Accept-Language": acceptLanguage, "User-Agent": userAgent ] }() let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL) /// The underlying session. public let session: NSURLSession /// The session delegate handling all the task and session delegate callbacks. public let delegate: SessionDelegate /// Whether to start requests immediately after being constructed. `true` by default. public var startRequestsImmediately: Bool = true /// The background completion handler closure provided by the UIApplicationDelegate `application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation will automatically call the handler. If you need to handle your own events before the handler is called, then you need to override the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished. `nil` by default. public var backgroundCompletionHandler: (() -> Void)? // MARK: - Lifecycle /** Initializes the Manager instance with the given configuration and server trust policy. :param: configuration The configuration used to construct the managed session. `nil` by default. :param: serverTrustPolicyManager The server trust policy manager to use for evaluating all server trust challenges. `nil` by default. */ required public init(configuration: NSURLSessionConfiguration? = nil, serverTrustPolicyManager: ServerTrustPolicyManager? = nil) { self.delegate = SessionDelegate() self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil) self.session.serverTrustPolicyManager = serverTrustPolicyManager self.delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in if let strongSelf = self { strongSelf.backgroundCompletionHandler?() } } } deinit { self.session.invalidateAndCancel() } // MARK: - Request /** Creates a request for the specified method, URL string, parameters, and parameter encoding. :param: method The HTTP method. :param: URLString The URL string. :param: parameters The parameters. `nil` by default. :param: encoding The parameter encoding. `.URL` by default. :param: headers The HTTP headers. `nil` by default. :returns: The created request. */ public func request( method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request { let mutableURLRequest = URLRequest(method, URLString, headers: headers) let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0 return request(encodedURLRequest) } /** Creates a request for the specified URL request. If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned. :param: URLRequest The URL request :returns: The created request. */ public func request(URLRequest: URLRequestConvertible) -> Request { var dataTask: NSURLSessionDataTask! dispatch_sync(self.queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) } let request = Request(session: self.session, task: dataTask) delegate[request.delegate.task] = request.delegate if self.startRequestsImmediately { request.resume() } return request } // MARK: - SessionDelegate /** Responsible for handling all delegate callbacks for the underlying session. */ public final class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate { private var subdelegates: [Int: Request.TaskDelegate] = [:] private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT) subscript(task: NSURLSessionTask) -> Request.TaskDelegate? { get { var subdelegate: Request.TaskDelegate? dispatch_sync(self.subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] } return subdelegate } set { dispatch_barrier_async(self.subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue } } } // MARK: - NSURLSessionDelegate // MARK: Override Closures /// NSURLSessionDelegate override closure for `URLSession:didBecomeInvalidWithError:` method. public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)? /// NSURLSessionDelegate override closure for `URLSession:didReceiveChallenge:completionHandler:` method. public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))? /// NSURLSessionDelegate override closure for `URLSessionDidFinishEventsForBackgroundURLSession:` method. public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)? // MARK: Delegate Methods public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) { self.sessionDidBecomeInvalidWithError?(session, error) } public func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) { var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling var credential: NSURLCredential! if let sessionDidReceiveChallenge = self.sessionDidReceiveChallenge { (disposition, credential) = sessionDidReceiveChallenge(session, challenge) } else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust { let host = challenge.protectionSpace.host if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host), serverTrust = challenge.protectionSpace.serverTrust { if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) { disposition = .UseCredential credential = NSURLCredential(forTrust: serverTrust) } else { disposition = .CancelAuthenticationChallenge } } } completionHandler(disposition, credential) } public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) { self.sessionDidFinishEventsForBackgroundURLSession?(session) } // MARK: - NSURLSessionTaskDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`. public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`. public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`. public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream!)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`. public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`. public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)? // MARK: Delegate Methods public func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) { var redirectRequest: NSURLRequest? = request if let taskWillPerformHTTPRedirection = self.taskWillPerformHTTPRedirection { redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request) } completionHandler(redirectRequest) } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) { if let taskDidReceiveChallenge = self.taskDidReceiveChallenge { completionHandler(taskDidReceiveChallenge(session, task, challenge)) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler) } else { URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler) } } public func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) { if let taskNeedNewBodyStream = self.taskNeedNewBodyStream { completionHandler(taskNeedNewBodyStream(session, task)) } else if let delegate = self[task] { delegate.URLSession(session, task: task, needNewBodyStream: completionHandler) } } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) { if let taskDidSendBodyData = self.taskDidSendBodyData { taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend) } else if let delegate = self[task] as? Request.UploadTaskDelegate { delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend) } } public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) { if let taskDidComplete = self.taskDidComplete { taskDidComplete(session, task, error) } else if let delegate = self[task] { delegate.URLSession(session, task: task, didCompleteWithError: error) self[task] = nil } } // MARK: - NSURLSessionDataDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`. public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`. public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`. public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)? /// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`. public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse!)? // MARK: Delegate Methods public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) { var disposition: NSURLSessionResponseDisposition = .Allow if let dataTaskDidReceiveResponse = self.dataTaskDidReceiveResponse { disposition = dataTaskDidReceiveResponse(session, dataTask, response) } completionHandler(disposition) } public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) { if let dataTaskDidBecomeDownloadTask = self.dataTaskDidBecomeDownloadTask { dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask) } else { let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask) self[downloadTask] = downloadDelegate } } public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) { if let dataTaskDidReceiveData = self.dataTaskDidReceiveData { dataTaskDidReceiveData(session, dataTask, data) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, didReceiveData: data) } } public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) { if let dataTaskWillCacheResponse = self.dataTaskWillCacheResponse { completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse)) } else if let delegate = self[dataTask] as? Request.DataTaskDelegate { delegate.URLSession(session, dataTask: dataTask, willCacheResponse: proposedResponse, completionHandler: completionHandler) } else { completionHandler(proposedResponse) } } // MARK: - NSURLSessionDownloadDelegate // MARK: Override Closures /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`. public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`. public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)? /// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`. public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)? // MARK: Delegate Methods public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) { if let downloadTaskDidFinishDownloadingToURL = self.downloadTaskDidFinishDownloadingToURL { downloadTaskDidFinishDownloadingToURL(session, downloadTask, location) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location) } } public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) { if let downloadTaskDidWriteData = self.downloadTaskDidWriteData { downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite) } } public func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) { if let downloadTaskDidResumeAtOffset = self.downloadTaskDidResumeAtOffset { downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes) } else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate { delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes) } } } }
mit
d6f87c4588f423e1a52f3659bf8a58fc
50.231325
563
0.695546
6.352256
false
false
false
false
Alarson93/mmprogressswift
Example/MMProgressSwift/AppDelegate.swift
1
2977
// // AppDelegate.swift // MMProgressSwift // // Created by Alex Larson on 03/21/2016. // Copyright (c) 2016 Alex Larson. All rights reserved. // import UIKit import MMProgressSwift @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. setupKVN() return true } func setupKVN() { // MMProgressConfiguration *configuration = [[MMProgressConfiguration alloc] init]; // RTSpinKitView *spinner = [[RTSpinKitView alloc] initWithStyle:RTSpinKitViewStyleWave]; // // spinner.color = [UIColor whiteColor]; // // configuration.loadingIndicator = spinner; // configuration.fullScreen = NO; // configuration.backgroundType = MMProgressBackgroundTypeBlurred; // configuration.backgroundColor = [UIColor colorWithRed:255.0 / 255.0 green:100.0 / 255.0 blue:20.0 / 255.0 alpha:0.5]; // configuration.statusColor = [UIColor whiteColor]; // configuration.presentAnimated = YES; // // [MMProgress setConfiguration:configuration]; } 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 throttle down OpenGL ES frame rates. 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 inactive 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:. } }
mit
013e4cc4648990b3cea1b77b57231111
43.432836
285
0.722875
5.159445
false
true
false
false
SwiftGFX/SwiftMath
Sources/float3x3+Extensions.swift
1
978
// // float3x3+Extensions.swift // org.SwiftGFX.SwiftMath // // Created by Eugene Bokhan on 28.02.20. // // #if !NOSIMD import Foundation import simd extension float3x3: Codable { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let c1 = try values.decode(SIMD3<Float>.self, forKey: .column1) let c2 = try values.decode(SIMD3<Float>.self, forKey: .column2) let c3 = try values.decode(SIMD3<Float>.self, forKey: .column3) self.init(c1, c2, c3) } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(self.columns.0, forKey: .column1) try container.encode(self.columns.1, forKey: .column2) try container.encode(self.columns.2, forKey: .column3) } private enum CodingKeys: String, CodingKey { case column1, column2, column3 } } #endif
bsd-2-clause
dd156239f3c1ed45a54677c851d2a777
26.166667
71
0.664622
3.372414
false
false
false
false
mperovic/my41
my41/Classes/DebugCPU.swift
1
5880
// // DebugCPUView.swift // my41 // // Created by Miroslav Perovic on 11/15/14. // Copyright (c) 2014 iPera. All rights reserved. // import Foundation import Cocoa class DebugCPUViewController: NSViewController { @IBOutlet weak var cpuRegistersView: NSView! @IBOutlet weak var cpuRegisterA: NSTextField! @IBOutlet weak var cpuRegisterB: NSTextField! @IBOutlet weak var cpuRegisterC: NSTextField! @IBOutlet weak var cpuRegisterM: NSTextField! @IBOutlet weak var cpuRegisterN: NSTextField! @IBOutlet weak var cpuRegisterP: NSTextField! @IBOutlet weak var cpuRegisterQ: NSTextField! @IBOutlet weak var cpuRegisterPC: NSTextField! @IBOutlet weak var cpuRegisterG: NSTextField! @IBOutlet weak var cpuRegisterT: NSTextField! @IBOutlet weak var cpuRegisterXST: NSTextField! @IBOutlet weak var cpuRegisterST: NSTextField! @IBOutlet weak var cpuRegisterR: NSTextField! @IBOutlet weak var cpuRegisterCarry: NSTextField! @IBOutlet weak var cpuPowerMode: NSTextField! @IBOutlet weak var cpuSelectedRAM: NSTextField! @IBOutlet weak var cpuSelectedPeripheral: NSTextField! @IBOutlet weak var cpuMode: NSTextField! @IBOutlet weak var cpuStack1: NSTextField! @IBOutlet weak var cpuStack2: NSTextField! @IBOutlet weak var cpuStack3: NSTextField! @IBOutlet weak var cpuStack4: NSTextField! @IBOutlet weak var cpuRegisterKY: NSTextField! @IBOutlet weak var cpuRegisterFI: NSTextField! @IBOutlet weak var displayRegistersView: NSView! @IBOutlet weak var displayRegisterA: NSTextField! @IBOutlet weak var displayRegisterB: NSTextField! @IBOutlet weak var displayRegisterC: NSTextField! @IBOutlet weak var displayRegisterE: NSTextField! @IBOutlet weak var traceSwitch: NSButton! var debugContainerViewController: DebugContainerViewController? override func viewDidLoad() { self.cpuRegistersView.wantsLayer = true self.cpuRegistersView.layer?.masksToBounds = true self.cpuRegistersView.layer?.borderWidth = 2.0 self.cpuRegistersView.layer?.borderColor = CGColor(gray: 0.75, alpha: 1.0) self.cpuRegistersView.layer?.cornerRadius = 6.0 self.displayRegistersView.wantsLayer = true self.displayRegistersView.layer?.masksToBounds = true self.displayRegistersView.layer?.borderWidth = 2.0 self.displayRegistersView.layer?.borderColor = CGColor(gray: 0.75, alpha: 1.0) self.displayRegistersView.layer?.cornerRadius = 6.0 cpu.debugCPUViewController = self NotificationCenter.default.addObserver( self, selector: #selector(DebugCPUViewController.updateDisplay), name: NSNotification.Name(rawValue: kCPUDebugUpdateDisplay), object: nil ) updateDisplay() } @objc func updateDisplay() { populateCPURegisters() populateDisplayRegisters() } func populateCPURegisters() { cpuRegisterA.stringValue = cpu.digitsToString(cpu.reg.A.digits) cpuRegisterB.stringValue = cpu.digitsToString(cpu.reg.B.digits) cpuRegisterC.stringValue = cpu.digitsToString(cpu.reg.C.digits) cpuRegisterM.stringValue = cpu.digitsToString(cpu.reg.M.digits) cpuRegisterN.stringValue = cpu.digitsToString(cpu.reg.N.digits) cpuRegisterP.stringValue = cpu.bits4ToString(cpu.reg.P) cpuRegisterQ.stringValue = cpu.bits4ToString(cpu.reg.Q) cpuRegisterPC.stringValue = NSString(format:"%04X", cpu.reg.PC) as String cpuRegisterG.stringValue = cpu.digitsToString(cpu.reg.G) cpuRegisterT.stringValue = NSString(format:"%02X", cpu.reg.T) as String let strXST = String(cpu.reg.XST, radix:2) cpuRegisterXST.stringValue = pad(string: strXST, toSize: 6) let strST = String(cpu.reg.ST, radix:2) cpuRegisterST.stringValue = pad(string: strST, toSize: 8) if cpu.reg.R == 0 { cpuRegisterR.stringValue = "P" } else { cpuRegisterR.stringValue = "Q" } switch cpu.powerMode { case .deepSleep: cpuPowerMode.stringValue = "D" case .lightSleep: cpuPowerMode.stringValue = "L" case .powerOn: cpuPowerMode.stringValue = "P" } if cpu.reg.carry == 0 { cpuRegisterCarry.stringValue = "T" } else { cpuRegisterCarry.stringValue = "F" } switch cpu.reg.mode { case .dec_mode: cpuMode.stringValue = "D" case .hex_mode: cpuMode.stringValue = "H" } cpuStack1.stringValue = NSString(format:"%04X", cpu.reg.stack[0]) as String cpuStack2.stringValue = NSString(format:"%04X", cpu.reg.stack[1]) as String cpuStack3.stringValue = NSString(format:"%04X", cpu.reg.stack[2]) as String cpuStack4.stringValue = NSString(format:"%04X", cpu.reg.stack[3]) as String cpuRegisterKY.stringValue = NSString(format:"%02X", cpu.reg.KY) as String cpuRegisterFI.stringValue = NSString(format:"%04X", cpu.reg.FI) as String cpuSelectedRAM.stringValue = NSString(format:"%03X", cpu.reg.ramAddress) as String cpuSelectedPeripheral.stringValue = NSString(format:"%02X", cpu.reg.peripheral) as String } func pad(string : String, toSize: Int) -> String { var padded = string for _ in 0..<toSize - string.characters.count { padded = "0" + padded } return padded } func populateDisplayRegisters() { if let display = calculatorController.display { displayRegisterA.stringValue = display.digits12ToString(display.registers.A) displayRegisterB.stringValue = display.digits12ToString(display.registers.B) displayRegisterC.stringValue = display.digits12ToString(display.registers.C) displayRegisterE.stringValue = NSString(format:"%03X", display.registers.E) as String } } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { let segid = segue.identifier ?? "(none)" if TRACE != 0 { print("\(#function) hit, segue ID = \(segid)") } } @IBAction func traceAction(sender: AnyObject) { if sender as! NSObject == traceSwitch { if traceSwitch.state == NSControl.StateValue.on { TRACE = 1 } else { TRACE = 0 } let defaults = UserDefaults.standard defaults.set(TRACE, forKey: "traceActive") defaults.synchronize() } } }
bsd-3-clause
163184932a1d637e5059fc3fcf8a8e48
34.853659
91
0.75034
3.464938
false
false
false
false
github/Nimble
Nimble/Utils/Stringers.swift
77
1289
import Foundation func _identityAsString(value: AnyObject?) -> String { if value == nil { return "nil" } return NSString(format: "<%p>", unsafeBitCast(value!, Int.self)) } func _arrayAsString<T>(items: [T], joiner: String = ", ") -> String { return items.reduce("") { accum, item in let prefix = (accum.isEmpty ? "" : joiner) return accum + prefix + "\(item)" } } @objc protocol NMBStringer { func NMB_stringify() -> String } func stringify<S: SequenceType>(value: S) -> String { var generator = value.generate() var strings = [String]() var value: S.Generator.Element? do { value = generator.next() if value != nil { strings.append(stringify(value)) } } while value != nil let str = ", ".join(strings) return "[\(str)]" } extension NSArray : NMBStringer { func NMB_stringify() -> String { let str = self.componentsJoinedByString(", ") return "[\(str)]" } } func stringify<T>(value: T) -> String { if value is Double { return NSString(format: "%.4f", (value as Double)) } return toString(value) } func stringify<T>(value: T?) -> String { if let unboxed = value { return stringify(unboxed) } return "nil" }
apache-2.0
e0e211524d122e35217a26c49a4afc43
22.436364
69
0.577967
3.83631
false
false
false
false
ninjaprox/SL-BeginngerCook
BeginnerCook/ViewController.swift
1
2631
/* * Copyright (c) 2015 Razeware LLC * * 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 class ViewController: UIViewController { @IBOutlet var listView: UIScrollView! @IBOutlet var bgImage: UIImageView! var selectedImage: UIImageView? let transition = PopAnimation() override func viewDidLoad() { super.viewDidLoad() } func didTapImageView(tap: UITapGestureRecognizer) { selectedImage = tap.view as? UIImageView let index = tap.view!.tag let selectedHerb = herbs[index] //present details view controller let herbDetails = storyboard!.instantiateViewControllerWithIdentifier("HerbDetailsViewController") as! HerbDetailsViewController herbDetails.transitioningDelegate = self herbDetails.herb = selectedHerb presentViewController(herbDetails, animated: true, completion: nil) } } extension ViewController: UIViewControllerTransitioningDelegate { func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.originFrame = selectedImage!.superview!.convertRect(selectedImage!.frame, toView: nil) transition.presenting = true return transition } func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { transition.presenting = false return transition } }
mit
9fb93e9f8143df042a693dd8ec28580e
39.492308
217
0.741543
5.48125
false
false
false
false
benlangmuir/swift
test/refactoring/ConvertAsync/convert_bool.swift
7
20768
// REQUIRES: objc_interop // REQUIRES: concurrency // RUN: %empty-directory(%t) // RUN: %build-clang-importer-objc-overlays import Foundation import ConvertBoolObjC func boolWithErr() async throws -> Bool { true } func boolWithErr(completion: @escaping (Bool, Error?) -> Void) {} func multipleBoolWithErr() async throws -> (String, Bool, Bool) { ("", true, true) } func multipleBoolWithErr(completion: @escaping (String?, Bool, Bool, Error?) -> Void) {} func optionalBoolWithErr() async throws -> (String, Bool, Bool) { ("", true, true) } func optionalBoolWithErr(completion: @escaping (String?, Bool?, Bool, Error?) -> Void) {} func testConvertBool() async throws { // All 7 of the below should generate the same refactoring. // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if !b { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if b { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if !b && err != nil { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if b && err != nil { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if err != nil && b == false { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if b == true && err == nil { } else { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR %s boolWithErr { b, err in if !b && err == nil { } else { fatalError("oh no \(err!)") } print("not err") } // BOOL-WITH-ERR: do { // BOOL-WITH-ERR-NEXT: let b = try await boolWithErr() // BOOL-WITH-ERR-NEXT: print("not err") // BOOL-WITH-ERR-NEXT: } catch let err { // BOOL-WITH-ERR-NEXT: fatalError("oh no \(err)") // BOOL-WITH-ERR-NEXT: } // These 3 should both generate the same refactoring. // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR2 %s boolWithErr { success, err in if success == true && err == nil { print("hi") } else { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR2 %s boolWithErr { success, err in if success && err == nil { print("hi") } else { fatalError("oh no \(err!)") } print("not err") } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR2 %s boolWithErr { success, err in if err == nil { print("hi") } else if !success { fatalError("oh no \(err!)") } print("not err") } // BOOL-WITH-ERR2: do { // BOOL-WITH-ERR2-NEXT: let success = try await boolWithErr() // BOOL-WITH-ERR2-NEXT: print("hi") // BOOL-WITH-ERR2-NEXT: print("not err") // BOOL-WITH-ERR2-NEXT: } catch let err { // BOOL-WITH-ERR2-NEXT: fatalError("oh no \(err)") // BOOL-WITH-ERR2-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR3 %s boolWithErr { failure, err in if failure { print("a \(err!)") } else if .random() { print("b") } else { print("c") } } // BOOL-WITH-ERR3: do { // BOOL-WITH-ERR3-NEXT: let failure = try await boolWithErr() // BOOL-WITH-ERR3-NEXT: if .random() { // BOOL-WITH-ERR3-NEXT: print("b") // BOOL-WITH-ERR3-NEXT: } else { // BOOL-WITH-ERR3-NEXT: print("c") // BOOL-WITH-ERR3-NEXT: } // BOOL-WITH-ERR3-NEXT: } catch let err { // BOOL-WITH-ERR3-NEXT: print("a \(err)") // BOOL-WITH-ERR3-NEXT: } // Don't handle the below example as the force unwrap of err takes place under a different condition. // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-DONT-HANDLE %s boolWithErr { success, err in if !success { if err != nil { fatalError("oh no \(err!)") } } if !success { _ = err != nil ? fatalError("oh no \(err!)") : fatalError("some worries") } print("not err") } // BOOL-DONT-HANDLE: let success = try await boolWithErr() // BOOL-DONT-HANDLE-NEXT: if !success { // BOOL-DONT-HANDLE-NEXT: if <#err#> != nil { // BOOL-DONT-HANDLE-NEXT: fatalError("oh no \(<#err#>!)") // BOOL-DONT-HANDLE-NEXT: } // BOOL-DONT-HANDLE-NEXT: } // BOOL-DONT-HANDLE-NEXT: if !success { // BOOL-DONT-HANDLE-NEXT: _ = <#err#> != nil ? fatalError("oh no \(<#err#>!)") : fatalError("some worries") // BOOL-DONT-HANDLE-NEXT: } // BOOL-DONT-HANDLE-NEXT: print("not err") // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-DONT-HANDLE2 %s boolWithErr { success, err in if !success { func doThings() { fatalError("oh no \(err!)") } doThings() } if !success { let doThings = { fatalError("oh no \(err!)") } doThings() } if !success { while err != nil { fatalError("oh no \(err!)") } } if !success { for _: Int in [] { fatalError("oh no \(err!)") } } print("not err") } // FIXME: The 'err' in doThings() should become a placeholder (rdar://78509286). // BOOL-DONT-HANDLE2: let success = try await boolWithErr() // BOOL-DONT-HANDLE2-NEXT: if !success { // BOOL-DONT-HANDLE2-NEXT: func doThings() { // BOOL-DONT-HANDLE2-NEXT: fatalError("oh no \(err!)") // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: doThings() // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: if !success { // BOOL-DONT-HANDLE2-NEXT: let doThings = { // BOOL-DONT-HANDLE2-NEXT: fatalError("oh no \(<#err#>!)") // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: doThings() // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: if !success { // BOOL-DONT-HANDLE2-NEXT: while <#err#> != nil { // BOOL-DONT-HANDLE2-NEXT: fatalError("oh no \(<#err#>!)") // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: if !success { // BOOL-DONT-HANDLE2-NEXT: for _: Int in [] { // BOOL-DONT-HANDLE2-NEXT: fatalError("oh no \(<#err#>!)") // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: } // BOOL-DONT-HANDLE2-NEXT: print("not err") // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-DONT-HANDLE3 %s boolWithErr { success, err in if !success { fatalError("oh no maybe \(String(describing: err))") } print("not err") } // err is not force unwrapped, so don't handle. // BOOL-DONT-HANDLE3: let success = try await boolWithErr() // BOOL-DONT-HANDLE3-NEXT: if !success { // BOOL-DONT-HANDLE3-NEXT: fatalError("oh no maybe \(String(describing: <#err#>))") // BOOL-DONT-HANDLE3-NEXT: } // BOOL-DONT-HANDLE3-NEXT: print("not err") // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-DONT-HANDLE4 %s boolWithErr { failure, err in if failure { print("a") } else if .random() { print("b \(err!)") } else { print("c") } } // Don't handle the case where the err unwrap occurs in an unrelated else if // clause. // BOOL-DONT-HANDLE4: let failure = try await boolWithErr() // BOOL-DONT-HANDLE4-NEXT: if failure { // BOOL-DONT-HANDLE4-NEXT: print("a") // BOOL-DONT-HANDLE4-NEXT: } else if .random() { // BOOL-DONT-HANDLE4-NEXT: print("b \(<#err#>!)") // BOOL-DONT-HANDLE4-NEXT: } else { // BOOL-DONT-HANDLE4-NEXT: print("c") // BOOL-DONT-HANDLE4-NEXT: } // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR-SILLY %s boolWithErr { success, err in if success == false && err == nil { print("ummm wat \(err!)") return } print("not err") } // BOOL-WITH-ERR-SILLY: let success = try await boolWithErr() // BOOL-WITH-ERR-SILLY-NEXT: if success == false && <#err#> == nil { // BOOL-WITH-ERR-SILLY-NEXT: print("ummm wat \(<#err#>!)") // BOOL-WITH-ERR-SILLY-NEXT: <#return#> // BOOL-WITH-ERR-SILLY-NEXT: } // BOOL-WITH-ERR-SILLY-NEXT: print("not err") // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=BOOL-WITH-ERR-SILLY2 %s boolWithErr { success, err in if success { print("ummm wat \(err!)") } else { print("ummm wat \(err!)") } } // The err unwrap is in both blocks, so it's not clear what to classify as. // BOOL-WITH-ERR-SILLY2: let success = try await boolWithErr() // BOOL-WITH-ERR-SILLY2-NEXT: if success { // BOOL-WITH-ERR-SILLY2-NEXT: print("ummm wat \(<#err#>!)") // BOOL-WITH-ERR-SILLY2-NEXT: } else { // BOOL-WITH-ERR-SILLY2-NEXT: print("ummm wat \(<#err#>!)") // BOOL-WITH-ERR-SILLY2-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=MULTI-BOOL-WITH-ERR %s multipleBoolWithErr { str, b1, b2, err in if !b1 && !b2 { print("a \(err!)") } if b1, b2 { print("b \(err!)") } if !b1 { print("c \(err!)") } if !b2 { print("d \(err!)") } } // Don't handle the case where multiple flag checks are done in a single // condition, because it's not exactly clear what the user is doing. It's a // little unfortunate that we'll allow multiple flag checks in separate // conditions, but both of these cases seem somewhat uncommon, and there's no // real way to completely enforce a single flag param across e.g multiple calls // to the same function, so this is probably okay for now. // MULTI-BOOL-WITH-ERR: do { // MULTI-BOOL-WITH-ERR-NEXT: let (str, b1, b2) = try await multipleBoolWithErr() // MULTI-BOOL-WITH-ERR-NEXT: } catch let err { // MULTI-BOOL-WITH-ERR-NEXT: if !<#b1#> && !<#b2#> { // MULTI-BOOL-WITH-ERR-NEXT: print("a \(err)") // MULTI-BOOL-WITH-ERR-NEXT: } // MULTI-BOOL-WITH-ERR-NEXT: if <#b1#>, <#b2#> { // MULTI-BOOL-WITH-ERR-NEXT: print("b \(err)") // MULTI-BOOL-WITH-ERR-NEXT: } // MULTI-BOOL-WITH-ERR-NEXT: print("c \(err)") // MULTI-BOOL-WITH-ERR-NEXT: print("d \(err)") // MULTI-BOOL-WITH-ERR-NEXT: } // We cannot use refactor-check-compiles, as a placeholder cannot be force unwrapped. // RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=OPT-BOOL-WITH-ERR %s optionalBoolWithErr { str, optBool, b, err in if optBool != nil { print("a \(err!)") } if optBool == nil { print("b \(err!)") } if optBool == true { print("c \(err!)") } if ((optBool) == (false)) { print("d \(err!)") } if optBool == false { print("e \(String(describing: err))") } if optBool != true { print("f \(err!)") } if b { print("g \(err!)") } } // It's a little unfortunate that print("a \(<#err#>!)") gets classified in the success // block below, but it doesn't seem like a case that's likely to come up, as optBool // would then be inaccessible in the error block. // OPT-BOOL-WITH-ERR: do { // OPT-BOOL-WITH-ERR-NEXT: let (str, optBool, b) = try await optionalBoolWithErr() // OPT-BOOL-WITH-ERR-NEXT: print("a \(<#err#>!)") // OPT-BOOL-WITH-ERR-NEXT: if <#optBool#> == false { // OPT-BOOL-WITH-ERR-NEXT: print("e \(String(describing: <#err#>))") // OPT-BOOL-WITH-ERR-NEXT: } // OPT-BOOL-WITH-ERR-NEXT: if <#optBool#> != true { // OPT-BOOL-WITH-ERR-NEXT: print("f \(<#err#>!)") // OPT-BOOL-WITH-ERR-NEXT: } // OPT-BOOL-WITH-ERR-NEXT: } catch let err { // OPT-BOOL-WITH-ERR-NEXT: print("b \(err)") // OPT-BOOL-WITH-ERR-NEXT: print("c \(err)") // OPT-BOOL-WITH-ERR-NEXT: print("d \(err)") // OPT-BOOL-WITH-ERR-NEXT: print("g \(err)") // OPT-BOOL-WITH-ERR-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=OBJC-BOOL-WITH-ERR %s ClassWithHandlerMethods.firstBoolFlagSuccess("") { str, success, unrelated, err in if !unrelated { print(err!) } if !success { print("oh no") } if !success { print(err!) } if success { print("woo") } if str != nil { print("also woo") } } // OBJC-BOOL-WITH-ERR: do { // OBJC-BOOL-WITH-ERR-NEXT: let (str, unrelated) = try await ClassWithHandlerMethods.firstBoolFlagSuccess("") // OBJC-BOOL-WITH-ERR-NEXT: if !unrelated { // OBJC-BOOL-WITH-ERR-NEXT: print(<#err#>!) // OBJC-BOOL-WITH-ERR-NEXT: } // OBJC-BOOL-WITH-ERR-NEXT: print("woo") // OBJC-BOOL-WITH-ERR-NEXT: print("also woo") // OBJC-BOOL-WITH-ERR-NEXT: } catch let err { // OBJC-BOOL-WITH-ERR-NEXT: print("oh no") // OBJC-BOOL-WITH-ERR-NEXT: print(err) // OBJC-BOOL-WITH-ERR-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=OBJC-BOOL-WITH-ERR2 %s ClassWithHandlerMethods.secondBoolFlagFailure("") { str, unrelated, failure, err in if unrelated { print(err!) } if failure { print("oh no") } if failure { print(err!) } if !failure { print("woo") } if str != nil { print("also woo") } if failure && err == nil { print("wat") } if failure && err != nil { print("neat") } if failure, let _ = err { print("neato") } } // OBJC-BOOL-WITH-ERR2: do { // OBJC-BOOL-WITH-ERR2-NEXT: let (str, unrelated) = try await ClassWithHandlerMethods.secondBoolFlagFailure("") // OBJC-BOOL-WITH-ERR2-NEXT: if unrelated { // OBJC-BOOL-WITH-ERR2-NEXT: print(<#err#>!) // OBJC-BOOL-WITH-ERR2-NEXT: } // OBJC-BOOL-WITH-ERR2-NEXT: print("woo") // OBJC-BOOL-WITH-ERR2-NEXT: print("also woo") // OBJC-BOOL-WITH-ERR2-NEXT: if <#failure#> && <#err#> == nil { // OBJC-BOOL-WITH-ERR2-NEXT: print("wat") // OBJC-BOOL-WITH-ERR2-NEXT: } // OBJC-BOOL-WITH-ERR2-NEXT: } catch let err { // OBJC-BOOL-WITH-ERR2-NEXT: print("oh no") // OBJC-BOOL-WITH-ERR2-NEXT: print(err) // OBJC-BOOL-WITH-ERR2-NEXT: print("neat") // OBJC-BOOL-WITH-ERR2-NEXT: print("neato") // OBJC-BOOL-WITH-ERR2-NEXT: } // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=OBJC-BOOL-WITH-ERR-FALLBACK %s ClassWithHandlerMethods.firstBoolFlagSuccess("") { str, success, unrelated, err in guard success && success == .random() else { fatalError() } print("much success", unrelated, str) } // OBJC-BOOL-WITH-ERR-FALLBACK: var str: String? = nil // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: let success: Bool // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: var unrelated: Bool? = nil // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: var err: Error? = nil // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: do { // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: (str, unrelated) = try await ClassWithHandlerMethods.firstBoolFlagSuccess("") // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: success = true // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: } catch { // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: err = error // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: success = false // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: } // OBJC-BOOL-WITH-ERR-FALLBACK-EMPTY: // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: guard success && success == .random() else { fatalError() } // OBJC-BOOL-WITH-ERR-FALLBACK-NEXT: print("much success", unrelated, str) // RUN: %refactor-check-compiles -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):3 -I %S/Inputs -I %t -target %target-triple %clang-importer-sdk-nosource | %FileCheck -check-prefix=OBJC-BOOL-WITH-ERR-FALLBACK2 %s ClassWithHandlerMethods.secondBoolFlagFailure("") { str, unrelated, failure, err in guard !failure && failure == .random() else { fatalError() } print("much fails", unrelated, str) } // OBJC-BOOL-WITH-ERR-FALLBACK2: var str: String? = nil // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: var unrelated: Bool? = nil // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: let failure: Bool // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: var err: Error? = nil // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: do { // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: (str, unrelated) = try await ClassWithHandlerMethods.secondBoolFlagFailure("") // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: failure = false // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: } catch { // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: err = error // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: failure = true // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: } // OBJC-BOOL-WITH-ERR-FALLBACK2-EMPTY: // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: guard !failure && failure == .random() else { fatalError() } // OBJC-BOOL-WITH-ERR-FALLBACK2-NEXT: print("much fails", unrelated, str) }
apache-2.0
5e059df7423c6062a956080f4ec7aa85
40.370518
247
0.6263
3.104335
false
false
false
false
gregomni/swift
test/decl/protocol/existential_member_accesses_self_assoctype.swift
2
61159
// RUN: %target-typecheck-verify-swift -disable-availability-checking -requirement-machine-abstract-signatures=on //===----------------------------------------------------------------------===// // Use of protocols with Self or associated type requirements //===----------------------------------------------------------------------===// struct Struct<T> { class Inner {} struct InnerGeneric<T> {} } class Class<T> {} protocol P1 { associatedtype Q // Methods func covariantSelf1() -> Self func covariantSelf2() -> Self? func covariantSelf3() -> Self.Type func covariantSelf4() -> (Self, Self) func covariantSelf5() -> Array<Self> func covariantSelf6() -> [String : Self] func covariantSelf7(_: (Self) -> Void) func covariantSelf8(_: (Self...) -> Void) func covariantSelfComplex(_: (Self.Type) -> Void, _: (Self.Type...) -> Void, _: (Array<Self>) -> Void, _: (Array<Array<Self>?>) -> Void, _: (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] func covariantAssoc1() -> Q func covariantAssoc2() -> Q? func covariantAssoc3() -> Q.Type func covariantAssoc4() -> (Q, Q) func covariantAssoc5() -> Array<Q> func covariantAssoc6() -> [String : Q] func covariantAssoc7(_: (Q) -> Void) func covariantAssoc8(_: (Q...) -> Void) func covariantAssocComplex(_: (Q.Type) -> Void, _: (Q.Type...) -> Void, _: (Array<Q>) -> Void, _: (Array<Array<Q>?>) -> Void, _: (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] func contravariantSelf1(_: Self?) func contravariantSelf2(_: () -> Self) func contravariantSelf3(_: Array<() -> Self>) func contravariantSelf4(_: [String : () -> Self]) func contravariantSelf5(_: () -> (Self, Self)) func contravariantSelf6(_: ((Self) -> Void) -> Void) func contravariantSelf7() -> (Self) -> Void func contravariantSelf8() -> Array<((Self) -> Void)?> func contravariantSelf9(_: [String : (() -> Self)?]) func contravariantSelf10() -> (Array<[String : Self??]>) -> Void func contravariantSelf11(_: Self.Type) func contravariantAssoc1(_: Q?) func contravariantAssoc2(_: () -> Q) func contravariantAssoc3(_: Array<() -> Q>) func contravariantAssoc4(_: [String : () -> Q]) func contravariantAssoc5(_: () -> (Q, Q)) func contravariantAssoc6(_: ((Q) -> Void) -> Void) func contravariantAssoc7() -> (Q) -> Void func contravariantAssoc8() -> Array<((Q) -> Void)?> func contravariantAssoc9(_: [String : (() -> Q)?]) func contravariantAssoc10() -> (Array<[String : Q??]>) -> Void func contravariantAssoc11(_: Q.Type) func invariantSelf1(_: inout Self) func invariantSelf2(_: (inout Self) -> Void) func invariantSelf3(_: inout Array<() -> Self>) func invariantSelf4(_: Struct<Self>) func invariantSelf5() -> Struct<Self> func invariantSelf6() -> Struct<Self>.Inner func invariantSelf7(_: (Struct<Self>) -> Void) func invariantSelf8(_: Struct<(Self) -> Void>) func invariantSelf9(_: Struct<() -> Self>) func invariantSelf10(_: any P1 & Class<Self>) func invariantSelf11() -> Struct<Self>.InnerGeneric<Void> func invariantAssoc1(_: inout Q) func invariantAssoc2(_: (inout Q) -> Void) func invariantAssoc3(_: inout Array<() -> Q>) func invariantAssoc4(_: Struct<Q>) func invariantAssoc5() -> Struct<Q> func invariantAssoc6() -> Struct<Q>.Inner func invariantAssoc7(_: (Struct<Q>) -> Void) func invariantAssoc8(_: Struct<(Q) -> Void>) func invariantAssoc9(_: Struct<() -> Q>) func invariantAssoc10(_: any P1 & Class<Q>) func invariantAssoc11() -> Struct<Q>.InnerGeneric<Void> // Properties var covariantSelfProp1: Self { get } var covariantSelfProp2: Self? { get } var covariantSelfProp3: Self.Type { get } var covariantSelfProp4: (Self, Self) { get } var covariantSelfProp5: Array<Self> { get } var covariantSelfProp6: [String : Self] { get } var covariantSelfProp7: ((Self) -> Void) -> Void { get } var covariantSelfProp8: ((Self...) -> Void) -> Void { get } var covariantSelfPropComplex: ((Self.Type) -> Void, (Self.Type...) -> Void, (Array<Self>) -> Void, (Array<Array<Self>?>) -> Void, (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] { get } var covariantAssocProp1: Q { get } var covariantAssocProp2: Q? { get } var covariantAssocProp3: Q.Type { get } var covariantAssocProp4: (Q, Q) { get } var covariantAssocProp5: Array<Q> { get } var covariantAssocProp6: [String : Q] { get } var covariantAssocProp7: ((Q) -> Void) -> Void { get } var covariantAssocProp8: ((Q...) -> Void) -> Void { get } var covariantAssocPropComplex: ((Q.Type) -> Void, (Q.Type...) -> Void, (Array<Q>) -> Void, (Array<Array<Q>?>) -> Void, (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] { get } var contravariantSelfProp1: (Self?) -> Void { get } var contravariantSelfProp2: (() -> Self) -> Void { get } var contravariantSelfProp3: (Array<() -> Self>) -> Void { get } var contravariantSelfProp4: ([String : () -> Self]) -> Void { get } var contravariantSelfProp5: (() -> (Self, Self)) -> Void { get } var contravariantSelfProp6: (((Self) -> Void) -> Void) -> Void { get } var contravariantSelfProp7: (Self) -> Void { get } var contravariantSelfProp8: Array<((Self) -> Void)?> { get } var contravariantSelfProp9: ([String : (() -> Self)?]) -> Void { get } var contravariantSelfProp10: (Array<[String : Self??]>) -> Void { get } var contravariantSelfProp11: (Self.Type) -> Void { get } var contravariantAssocProp1: (Q?) -> Void { get } var contravariantAssocProp2: (() -> Q) -> Void { get } var contravariantAssocProp3: (Array<() -> Q>) -> Void { get } var contravariantAssocProp4: ([String : () -> Q]) -> Void { get } var contravariantAssocProp5: (() -> (Q, Q)) -> Void { get } var contravariantAssocProp6: (((Q) -> Void) -> Void) -> Void { get } var contravariantAssocProp7: (Q) -> Void { get } var contravariantAssocProp8: Array<((Q) -> Void)?> { get } var contravariantAssocProp9: ([String : (() -> Q)?]) -> Void { get } var contravariantAssocProp10: (Array<[String : Q??]>) -> Void { get } var contravariantAssocProp11: (Q.Type) -> Void { get } var invariantSelfProp1: (inout Self) -> Void { get } var invariantSelfProp2: ((inout Self) -> Void) -> Void { get } var invariantSelfProp3: (inout Array<() -> Self>) -> Void { get } var invariantSelfProp4: (Struct<Self>) -> Void { get } var invariantSelfProp5: Struct<Self> { get } var invariantSelfProp6: Struct<Self>.Inner { get } var invariantSelfProp7: ((Struct<Self>) -> Void) -> Void { get } var invariantSelfProp8: (Struct<(Self) -> Void>) -> Void { get } var invariantSelfProp9: (Struct<() -> Self>) -> Void { get } var invariantSelfProp10: (any P1 & Class<Self>) -> Void { get } var invariantSelfProp11: Struct<Self>.InnerGeneric<Void> { get } var invariantAssocProp1: (inout Q) -> Void { get } var invariantAssocProp2: ((inout Q) -> Void) -> Void { get } var invariantAssocProp3: (inout Array<() -> Q>) -> Void { get } var invariantAssocProp4: (Struct<Q>) -> Void { get } var invariantAssocProp5: Struct<Q> { get } var invariantAssocProp6: Struct<Q>.Inner { get } var invariantAssocProp7: ((Struct<Q>) -> Void) { get } var invariantAssocProp8: (Struct<(Q) -> Void>) { get } var invariantAssocProp9: (Struct<() -> Q>) -> Void { get } var invariantAssocProp10: (any P1 & Class<Q>) -> Void { get } var invariantAssocProp11: Struct<Q>.InnerGeneric<Void> { get } // Subscripts subscript(covariantSelfSubscript1 _: Void) -> Self { get } subscript(covariantSelfSubscript2 _: Void) -> Self? { get } subscript(covariantSelfSubscript3 _: Void) -> Self.Type { get } subscript(covariantSelfSubscript4 _: Void) -> (Self, Self) { get } subscript(covariantSelfSubscript5 _: Void) -> Array<Self> { get } subscript(covariantSelfSubscript6 _: Void) -> [String : Self] { get } subscript(covariantSelfSubscript7 _: (Self) -> Void) -> Self { get } subscript(covariantSelfSubscript8 _: (Self...) -> Void) -> Self { get } subscript(covariantSelfSubscriptComplex _: (Self.Type) -> Void, _: (Self.Type...) -> Void, _: (Array<Self>) -> Void, _: (Array<Array<Self>?>) -> Void, _: (() -> Self?) -> Void ) -> [String : () -> (Self, Self)] { get } subscript(covariantAssocSubscript1 _: Void) -> Q { get } subscript(covariantAssocSubscript2 _: Void) -> Q? { get } subscript(covariantAssocSubscript3 _: Void) -> Q.Type { get } subscript(covariantAssocSubscript4 _: Void) -> (Q, Q) { get } subscript(covariantAssocSubscript5 _: Void) -> Array<Q> { get } subscript(covariantAssocSubscript6 _: Void) -> [String : Q] { get } subscript(covariantAssocSubscript7 _: (Q) -> Void) -> Q { get } subscript(covariantAssocSubscript8 _: (Q...) -> Void) -> Self { get } subscript(covariantAssocSubscriptComplex _: (Q.Type) -> Void, _: (Q.Type...) -> Void, _: (Array<Q>) -> Void, _: (Array<Array<Q>?>) -> Void, _: (() -> Q?) -> Void ) -> [String : () -> (Q, Q)] { get } subscript(contravariantSelfSubscript1 _: Self?) -> Void { get } subscript(contravariantSelfSubscript2 _: () -> Self) -> Void { get } subscript(contravariantSelfSubscript3 _: Array<() -> Self>) -> Void { get } subscript(contravariantSelfSubscript4 _: [String : () -> Self]) -> Void { get } subscript(contravariantSelfSubscript5 _: () -> (Self, Self)) -> Void { get } subscript(contravariantSelfSubscript6 _: ((Self) -> Void) -> Void) -> Void { get } subscript(contravariantSelfSubscript7 _: Void) -> (Self) -> Void { get } subscript(contravariantSelfSubscript8 _: Void) -> Array<((Self) -> Void)?> { get } subscript(contravariantSelfSubscript9 _: [String : (() -> Self)?]) -> Void { get } subscript(contravariantSelfSubscript10 _: Void) -> (Array<[String : Self??]>) -> Void { get } subscript(contravariantSelfSubscript11 _: Self.Type) -> Void { get } subscript(contravariantAssocSubscript1 _: Q?) -> Void { get } subscript(contravariantAssocSubscript2 _: () -> Q) -> Void { get } subscript(contravariantAssocSubscript3 _: Array<() -> Q>) -> Void { get } subscript(contravariantAssocSubscript4 _: [String : () -> Q]) -> Void { get } subscript(contravariantAssocSubscript5 _: () -> (Q, Q)) -> Void { get } subscript(contravariantAssocSubscript6 _: ((Q) -> Void) -> Void) -> Void { get } subscript(contravariantAssocSubscript7 _: Void) -> (Q) -> Void { get } subscript(contravariantAssocSubscript8 _: Void) -> Array<((Q) -> Void)?> { get } subscript(contravariantAssocSubscript9 _: [String : (() -> Q)?]) -> Void { get } subscript(contravariantAssocSubscript10 _: Void) -> (Array<[String : Q??]>) -> Void { get } subscript(contravariantAssocSubscript11 _: Q.Type) -> Void { get } subscript(invariantSelfSubscript1 _: Struct<Self>) -> Void { get } subscript(invariantSelfSubscript2 _: Void) -> Struct<Self> { get } subscript(invariantSelfSubscript3 _: Void) -> Struct<Self>.Inner { get } subscript(invariantSelfSubscript4 _: (Struct<Self>) -> Void) -> Void { get } subscript(invariantSelfSubscript5 _: Struct<(Self) -> Void>) -> Void { get } subscript(invariantSelfSubscript6 _: Struct<() -> Self>) -> Void { get } subscript(invariantSelfSubscript7 _: any P1 & Class<Self>) -> Void { get } subscript(invariantSelfSubscript8 _: Void) -> Struct<Self>.InnerGeneric<Void> { get } subscript(invariantAssocSubscript1 _: Struct<Q>) -> Void { get } subscript(invariantAssocSubscript2 _: Void) -> Struct<Q> { get } subscript(invariantAssocSubscript3 _: Void) -> Struct<Q>.Inner { get } subscript(invariantAssocSubscript4 _: (Struct<Q>) -> Void) -> Void { get } subscript(invariantAssocSubscript5 _: Struct<(Q) -> Void>) -> Void { get } subscript(invariantAssocSubscript6 _: Struct<() -> Q>) -> Void { get } subscript(invariantAssocSubscript7 _: any P1 & Class<Q>) -> Void { get } subscript(invariantAssocSubscript8 _: Void) -> Struct<Q>.InnerGeneric<Void> { get } } extension P1 { func opaqueResultTypeMethod() -> some P1 { self } var opaqueResultTypeProp: some P1 { self } subscript(opaqueResultTypeSubscript _: Bool) -> some P1 { self } } do { func testP1(arg: any P1) { let _: any P1 = arg.covariantSelf1() let _: (any P1)? = arg.covariantSelf2() let _: any P1.Type = arg.covariantSelf3() let _: (any P1, any P1) = arg.covariantSelf4() let _: Array<any P1> = arg.covariantSelf5() let _: [String : any P1] = arg.covariantSelf6() arg.covariantSelf7 { (_: any P1) in } arg.covariantSelf8 { (_: any P1...) in } let _: [String : () -> (any P1, any P1)] = arg.covariantSelfComplex( { (_: any P1.Type) in }, { (_: any P1.Type...) in }, { (_: Array<any P1>) in }, { (_: Array<Array<any P1>?>) in }, { (_: () -> (any P1)?) in } ) let _: Any = arg.covariantAssoc1() let _: Any? = arg.covariantAssoc2() let _: Any.Type = arg.covariantAssoc3() let _: (Any, Any) = arg.covariantAssoc4() let _: Array<Any> = arg.covariantAssoc5() let _: [String : Any] = arg.covariantAssoc6() arg.covariantAssoc7 { (_: Any) in } arg.covariantAssoc8 { (_: Any...) in } let _: [String : () -> (Any, Any)] = arg.covariantAssocComplex( { (_: Any.Type) in }, { (_: Any.Type...) in }, { (_: Array<Any>) in }, { (_: Array<Array<Any>?>) in }, { (_: () -> Any?) in } ) let _: any P1 = arg.covariantSelfProp1 let _: (any P1)? = arg.covariantSelfProp2 let _: any P1.Type = arg.covariantSelfProp3 let _: (any P1, any P1) = arg.covariantSelfProp4 let _: Array<any P1> = arg.covariantSelfProp5 let _: [String : any P1] = arg.covariantSelfProp6 let _: ((any P1) -> Void) -> Void = arg.covariantSelfProp7 let _: ((any P1...) -> Void) -> Void = arg.covariantSelfProp8 let _: ( (any P1.Type) -> Void, (any P1.Type...) -> Void, (Array<any P1>) -> Void, (Array<Array<any P1>?>) -> Void, (() -> (any P1)?) -> Void ) -> [String : () -> (any P1, any P1)] = arg.covariantSelfPropComplex let _: Any = arg.covariantAssocProp1 let _: Any? = arg.covariantAssocProp2 let _: Any.Type = arg.covariantAssocProp3 let _: (Any, Any) = arg.covariantAssocProp4 let _: Array<Any> = arg.covariantAssocProp5 let _: [String : Any] = arg.covariantAssocProp6 let _: ((Any) -> Void) -> Void = arg.covariantAssocProp7 let _: ((Any...) -> Void) -> Void = arg.covariantAssocProp8 let _: ( (Any.Type) -> Void, (Any.Type...) -> Void, (Array<Any>) -> Void, (Array<Array<Any>?>) -> Void, (() -> Any?) -> Void ) -> [String : () -> (Any, Any)] = arg.covariantAssocPropComplex let _: any P1 = arg[covariantSelfSubscript1: ()] let _: (any P1)? = arg[covariantSelfSubscript2: ()] let _: any P1.Type = arg[covariantSelfSubscript3: ()] let _: (any P1, any P1) = arg[covariantSelfSubscript4: ()] let _: Array<any P1> = arg[covariantSelfSubscript5: ()] let _: [String : any P1] = arg[covariantSelfSubscript6: ()] let _: any P1 = arg[covariantSelfSubscript7: { (_: any P1) in }] let _: any P1 = arg[covariantSelfSubscript8: { (_: any P1...) in }] let _: [String : () -> (any P1, any P1)] = arg[ covariantSelfSubscriptComplex: { (_: any P1.Type) in }, { (_: any P1.Type...) in }, { (_: Array<any P1>) in }, { (_: Array<Array<any P1>?>) in }, { (_: () -> (any P1)?) in } ] let _: Any = arg[covariantAssocSubscript1: ()] let _: Any? = arg[covariantAssocSubscript2: ()] let _: Any.Type = arg[covariantAssocSubscript3: ()] let _: (Any, Any) = arg[covariantAssocSubscript4: ()] let _: Array<Any> = arg[covariantAssocSubscript5: ()] let _: [String : Any] = arg[covariantAssocSubscript6: ()] let _: Any = arg[covariantAssocSubscript7: { (_: Any) in }] let _: Any = arg[covariantAssocSubscript8: { (_: Any...) in }] let _: [String : () -> (Any, Any)] = arg[ covariantAssocSubscriptComplex: { (_: Any.Type) in }, { (_: Any.Type...) in }, { (_: Array<Any>) in }, { (_: Array<Array<Any>?>) in }, { (_: () -> Any?) in } ] let _: any P1 = arg.opaqueResultTypeMethod() let _: any P1 = arg.opaqueResultTypeProp let _: any P1 = arg[opaqueResultTypeSubscript: true] arg.contravariantSelf1(0) // expected-error {{member 'contravariantSelf1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf2(0) // expected-error {{member 'contravariantSelf2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf3(0) // expected-error {{member 'contravariantSelf3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf4(0) // expected-error {{member 'contravariantSelf4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf5(0) // expected-error {{member 'contravariantSelf5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf6(0) // expected-error {{member 'contravariantSelf6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf7() // expected-error {{member 'contravariantSelf7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf8() // expected-error {{member 'contravariantSelf8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf9(0) // expected-error {{member 'contravariantSelf9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf10() // expected-error {{member 'contravariantSelf10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelf11(0) // expected-error {{member 'contravariantSelf11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc1(0) // expected-error {{member 'contravariantAssoc1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc2(0) // expected-error {{member 'contravariantAssoc2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc3(0) // expected-error {{member 'contravariantAssoc3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc4(0) // expected-error {{member 'contravariantAssoc4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc5(0) // expected-error {{member 'contravariantAssoc5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc6(0) // expected-error {{member 'contravariantAssoc6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc7() // expected-error {{member 'contravariantAssoc7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc8() // expected-error {{member 'contravariantAssoc8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc9(0) // expected-error {{member 'contravariantAssoc9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc10() // expected-error {{member 'contravariantAssoc10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssoc11(0) // expected-error {{member 'contravariantAssoc11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf1(0) // expected-error {{member 'invariantSelf1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf2(0) // expected-error {{member 'invariantSelf2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf3(0) // expected-error {{member 'invariantSelf3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf4(0) // expected-error {{member 'invariantSelf4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf5() // expected-error {{member 'invariantSelf5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf6() // expected-error {{member 'invariantSelf6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf7(0) // expected-error {{member 'invariantSelf7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf8(0) // expected-error {{member 'invariantSelf8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf9(0) // expected-error {{member 'invariantSelf9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf10(0) // expected-error {{member 'invariantSelf10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelf11() // expected-error {{member 'invariantSelf11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc1(0) // expected-error {{member 'invariantAssoc1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc2(0) // expected-error {{member 'invariantAssoc2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc3(0) // expected-error {{member 'invariantAssoc3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc4(0) // expected-error {{member 'invariantAssoc4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc5() // expected-error {{member 'invariantAssoc5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc6() // expected-error {{member 'invariantAssoc6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc7(0) // expected-error {{member 'invariantAssoc7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc8(0) // expected-error {{member 'invariantAssoc8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc9(0) // expected-error {{member 'invariantAssoc9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc10(0) // expected-error {{member 'invariantAssoc10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssoc11() // expected-error {{member 'invariantAssoc11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp1 // expected-error {{member 'contravariantSelfProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp2 // expected-error {{member 'contravariantSelfProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp3 // expected-error {{member 'contravariantSelfProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp4 // expected-error {{member 'contravariantSelfProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp5 // expected-error {{member 'contravariantSelfProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp6 // expected-error {{member 'contravariantSelfProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp7 // expected-error {{member 'contravariantSelfProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp8 // expected-error {{member 'contravariantSelfProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp9 // expected-error {{member 'contravariantSelfProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp10 // expected-error {{member 'contravariantSelfProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantSelfProp11 // expected-error {{member 'contravariantSelfProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp1 // expected-error {{member 'contravariantAssocProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp2 // expected-error {{member 'contravariantAssocProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp3 // expected-error {{member 'contravariantAssocProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp4 // expected-error {{member 'contravariantAssocProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp5 // expected-error {{member 'contravariantAssocProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp6 // expected-error {{member 'contravariantAssocProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp7 // expected-error {{member 'contravariantAssocProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp8 // expected-error {{member 'contravariantAssocProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp9 // expected-error {{member 'contravariantAssocProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp10 // expected-error {{member 'contravariantAssocProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.contravariantAssocProp11 // expected-error {{member 'contravariantAssocProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp1 // expected-error {{member 'invariantSelfProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp2 // expected-error {{member 'invariantSelfProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp3 // expected-error {{member 'invariantSelfProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp4 // expected-error {{member 'invariantSelfProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp5 // expected-error {{member 'invariantSelfProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp6 // expected-error {{member 'invariantSelfProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp7 // expected-error {{member 'invariantSelfProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp8 // expected-error {{member 'invariantSelfProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp9 // expected-error {{member 'invariantSelfProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp10 // expected-error {{member 'invariantSelfProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantSelfProp11 // expected-error {{member 'invariantSelfProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp1 // expected-error {{member 'invariantAssocProp1' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp2 // expected-error {{member 'invariantAssocProp2' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp3 // expected-error {{member 'invariantAssocProp3' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp4 // expected-error {{member 'invariantAssocProp4' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp5 // expected-error {{member 'invariantAssocProp5' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp6 // expected-error {{member 'invariantAssocProp6' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp7 // expected-error {{member 'invariantAssocProp7' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp8 // expected-error {{member 'invariantAssocProp8' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp9 // expected-error {{member 'invariantAssocProp9' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp10 // expected-error {{member 'invariantAssocProp10' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg.invariantAssocProp11 // expected-error {{member 'invariantAssocProp11' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript2: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript3: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript7: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript9: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript10: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantSelfSubscript11: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript2: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript3: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript7: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript9: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript10: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[contravariantAssocSubscript11: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript2: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript3: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript7: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantSelfSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript1: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript2: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript3: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript4: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript5: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript6: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript7: 0] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} arg[invariantAssocSubscript8: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1'; consider using a generic constraint instead}} } } protocol P1_TypeMemberOnInstanceAndViceVersa { static func static_covariantSelfMethod() -> Self static var static_covariantSelfProp: Self { get } static subscript(static_covariantSelfSubscript _: Void) -> Self { get } static func static_invariantSelfMethod() -> Struct<Self> static var static_invariantSelfProp: Struct<Self> { get } static subscript(static_invariantSelfSubscript _: Void) -> Struct<Self> { get } func covariantSelfMethod() -> Self func invariantSelfMethod() -> Struct<Self> var invariantSelfProp: Struct<Self> { get } subscript(invariantSelfSubscript _: Void) -> Struct<Self> { get } } do { // Test that invalid reference errors prevail over unsupported existential // member accesses. func test(protoMeta: (any P1_TypeMemberOnInstanceAndViceVersa).Type, existMeta: any P1_TypeMemberOnInstanceAndViceVersa.Type, instance: any P1_TypeMemberOnInstanceAndViceVersa) { // P1_TypeMemberOnInstanceAndViceVersa.Protocol protoMeta.static_invariantSelfMethod() // expected-error {{static member 'static_invariantSelfMethod' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} protoMeta.static_invariantSelfProp // expected-error {{static member 'static_invariantSelfProp' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} protoMeta[static_invariantSelfSubscript: ()] // expected-error {{static member 'subscript' cannot be used on protocol metatype '(any P1_TypeMemberOnInstanceAndViceVersa).Type'}} _ = protoMeta.covariantSelfMethod // ok protoMeta.invariantSelfMethod // expected-error {{member 'invariantSelfMethod' cannot be used on value of type '(any P1_TypeMemberOnInstanceAndViceVersa).Type'; consider using a generic constraint instead}} protoMeta.invariantSelfProp // expected-error {{instance member 'invariantSelfProp' cannot be used on type 'any P1_TypeMemberOnInstanceAndViceVersa'}} protoMeta[invariantSelfSubscript: ()] // expected-error {{instance member 'subscript' cannot be used on type 'any P1_TypeMemberOnInstanceAndViceVersa'}} // P1_TypeMemberOnInstanceAndViceVersa.Type _ = existMeta.static_covariantSelfMethod // ok _ = existMeta.static_covariantSelfProp // ok _ = existMeta[static_covariantSelfSubscript: ()] // ok existMeta.static_invariantSelfMethod // expected-error {{member 'static_invariantSelfMethod' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta.static_invariantSelfProp // expected-error {{member 'static_invariantSelfProp' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta[static_invariantSelfSubscript: ()] // expected-error {{member 'subscript' cannot be used on value of type 'any P1_TypeMemberOnInstanceAndViceVersa.Type'; consider using a generic constraint instead}} existMeta.invariantSelfMethod // expected-error {{instance member 'invariantSelfMethod' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} existMeta.invariantSelfProp // expected-error {{instance member 'invariantSelfProp' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} existMeta[invariantSelfSubscript: ()] // expected-error {{instance member 'subscript' cannot be used on type 'P1_TypeMemberOnInstanceAndViceVersa'}} // P1_TypeMemberOnInstanceAndViceVersa instance.static_invariantSelfMethod // expected-error {{static member 'static_invariantSelfMethod' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} instance.static_invariantSelfProp // expected-error {{static member 'static_invariantSelfProp' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} instance[static_invariantSelfSubscript: ()] // expected-error {{static member 'subscript' cannot be used on instance of type 'any P1_TypeMemberOnInstanceAndViceVersa'}} } } // A protocol member accessed with an existential value might have generic // constraints that require the ability to spell an opened archetype in order // to be satisfied. Such are // - superclass requirements, when the object is a non-'Self'-rooted type // parameter, and the subject is dependent on 'Self', e.g. U : G<Self.A> // - same-type requirements, when one side is dependent on 'Self', and the // other is a non-'Self'-rooted type parameter, e.g. U.Element == Self. // // Because opened archetypes are not part of the surface language, these // constraints render the member inaccessible. // // Note: 'Self'-rooted type parameters that are invalid in the context of the // existential base type are ignored -- the underlying requirement failure is // considered a more pressing issue. protocol UnfulfillableGenericRequirements { associatedtype A } extension UnfulfillableGenericRequirements { func method1() where A : Class<Self> {} func method2() where A: Sequence, A.Element == Self {} func method3<U>(_: U) -> U {} func method4<U>(_: U) where U : Class<Self.A> {} // expected-note@-1 3 {{where 'U' = 'Bool'}} func method5<U>(_: U) where U: Sequence, Self == U.Element {} // expected-note@-1 {{where 'U' = 'Bool'}} // expected-note@+1 2 {{where 'U' = 'Bool'}} func method6<U>(_: U) where U: UnfulfillableGenericRequirements, A: Sequence, A.Element: Sequence, U.A == A.Element.Element {} func method7<U>(_: U) where U: UnfulfillableGenericRequirements & Class<Self> {} func method8<U>(_: U) where U == Self.A {} } do { let exist: any UnfulfillableGenericRequirements exist.method1() // expected-error {{instance method 'method1()' requires that 'Self.A' inherit from 'Class<Self>'}} exist.method2() // expected-error@-1 {{instance method 'method2()' requires the types 'Self' and 'Self.A.Element' be equivalent}} // expected-error@-2 {{instance method 'method2()' requires that 'Self.A' conform to 'Sequence'}} _ = exist.method3(false) // ok exist.method4(false) // expected-error@-1 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>'}} // expected-error@-2 {{member 'method4' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method5(false) // expected-error@-1 {{instance method 'method5' requires that 'Bool' conform to 'Sequence'}} // expected-error@-2 {{member 'method5' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method7(false) // expected-error@-1 {{instance method 'method7' requires that 'U' conform to 'UnfulfillableGenericRequirements'}} // expected-error@-2 {{member 'method7' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} exist.method8(false) // expected-error@-1 {{member 'method8' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} } // Make sure this also works in a generic context! struct G<X, Y, Z> { func doIt() { let exist: any UnfulfillableGenericRequirements exist.method8(false) // expected-error@-1 {{member 'method8' cannot be used on value of type 'any UnfulfillableGenericRequirements'; consider using a generic constraint instead}} } } protocol UnfulfillableGenericRequirementsDerived1: UnfulfillableGenericRequirements where A == Bool {} protocol UnfulfillableGenericRequirementsDerived2: UnfulfillableGenericRequirements where A == Class<Self> {} do { // Test that 'Self' dependencies are computed relative to the base type. let exist1: any UnfulfillableGenericRequirementsDerived1 let exist2: any UnfulfillableGenericRequirementsDerived2 exist1.method4(false) // expected-error@-1 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>}} exist2.method4(false) // expected-error@-1 {{member 'method4' cannot be used on value of type 'any UnfulfillableGenericRequirementsDerived2'; consider using a generic constraint instead}} // expected-error@-2 {{instance method 'method4' requires that 'Bool' inherit from 'Class<Self.A>'}} } protocol UnfulfillableGenericRequirementsDerived3: UnfulfillableGenericRequirements where A: Sequence, A.Element: Sequence {} do { // Test that 'Self'-rooted type parameters that are invalid in the context of // the existential base type are ignored. let exist1: any UnfulfillableGenericRequirements let exist2: any UnfulfillableGenericRequirementsDerived3 exist1.method6(false) // expected-error@-1 {{instance method 'method6' requires that 'Self.A.Element' conform to 'Sequence'}} // expected-error@-2 {{instance method 'method6' requires that 'Self.A' conform to 'Sequence'}} // expected-error@-3 {{instance method 'method6' requires that 'Bool' conform to 'UnfulfillableGenericRequirements'}} exist2.method6(false) // expected-error@-1 {{member 'method6' cannot be used on value of type 'any UnfulfillableGenericRequirementsDerived3'; consider using a generic constraint instead}} // expected-error@-2 {{instance method 'method6' requires that 'Bool' conform to 'UnfulfillableGenericRequirements'}} } // Test that we don't determine existential availability based on type // parameters that are invalid in the context of the existential base type -- // the requirement failure is a more pressing issue. protocol InvalidTypeParameters { associatedtype A } extension InvalidTypeParameters { func method1() -> A.A where A: InvalidTypeParameters {} func method2(_: A.A) where A: InvalidTypeParameters {} func method3(_: A.A, _: A) where A: InvalidTypeParameters {} } do { let exist: any InvalidTypeParameters exist.method1() // expected-error {{instance method 'method1()' requires that 'Self.A' conform to 'InvalidTypeParameters'}} exist.method2(false) // expected-error {{instance method 'method2' requires that 'Self.A' conform to 'InvalidTypeParameters'}} exist.method3(false, false) // expected-error {{instance method 'method3' requires that 'Self.A' conform to 'InvalidTypeParameters'}} // expected-error@-1 {{member 'method3' cannot be used on value of type 'any InvalidTypeParameters'; consider using a generic constraint instead}} } protocol GenericRequirementFailures { associatedtype A } extension GenericRequirementFailures where A == Never { func method1() {} func method2() -> Self {} func method3(_: A) {} } extension GenericRequirementFailures where A: GenericRequirementFailures { func method4() {} } do { let exist: any GenericRequirementFailures exist.method1() // expected-error {{referencing instance method 'method1()' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} exist.method2() // expected-error {{referencing instance method 'method2()' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} exist.method3(false) // expected-error {{referencing instance method 'method3' on 'GenericRequirementFailures' requires the types 'Self.A' and 'Never' be equivalent}} // expected-error@-1 {{member 'method3' cannot be used on value of type 'any GenericRequirementFailures'; consider using a generic constraint instead}} exist.method4() // expected-error {{referencing instance method 'method4()' on 'GenericRequirementFailures' requires that 'Self.A' conform to 'GenericRequirementFailures'}} } protocol GenericRequirementFailuresDerived: GenericRequirementFailures where A: GenericRequirementFailures {} do { let exist: any GenericRequirementFailuresDerived exist.method4() // ok } // Settable storage members with a 'Self' result type may not be used with an // existential base. protocol P2 { subscript() -> Self { get set } var prop: Self { get set } } func takesP2(p2: any P2) { _ = p2[] // expected-error@-1{{member 'subscript' cannot be used on value of type 'any P2'; consider using a generic constraint instead}} _ = p2.prop // expected-error@-1{{member 'prop' cannot be used on value of type 'any P2'; consider using a generic constraint instead}} } protocol MiscTestsProto { associatedtype R : IteratorProtocol, Sequence func getR() -> R associatedtype Assoc subscript() -> Assoc { get } var getAssoc: Assoc? { get } } do { func miscTests(_ arg: any MiscTestsProto) { var r: any Sequence & IteratorProtocol = arg.getR() r.makeIterator() // expected-warning {{result of call to 'makeIterator()' is unused}} r.next() // expected-warning {{result of call to 'next()' is unused}} r.nonexistent() // expected-error {{value of type 'any IteratorProtocol & Sequence' has no member 'nonexistent'}} arg[] // expected-warning {{expression of type 'Any' is unused}} arg.getAssoc // expected-warning {{expression of type 'Any?' is unused}} } } // Test that covariant erasure turns metatypes into existential metatypes. protocol CovariantMetatypes { associatedtype Q func covariantSelfMetatype1(_: (Self.Type.Type.Type) -> Void) func covariantSelfMetatype2() -> (Self.Type, Self.Type.Type) func covariantAssocMetatype1(_: (Q.Type.Type.Type) -> Void) func covariantAssocMetatype2() -> (Q.Type, Q.Type.Type) var covariantSelfMetatypeProp1: Self.Type.Type.Type { get } var covariantSelfMetatypeProp2: (Self.Type, Self.Type.Type) { get } var covariantAssocMetatypeProp1: Q.Type.Type.Type { get } var covariantAssocMetatypeProp2: (Q.Type, Q.Type.Type) { get } subscript(covariantSelfMetatypeSubscript1 _: (Self.Type.Type.Type) -> Void) -> Self.Type { get } subscript(covariantSelfMetatypeSubscript2 _: Void) -> (Self.Type, Self.Type.Type) { get } subscript(covariantAssocMetatypeSubscript1 _: (Q.Type.Type.Type) -> Void) -> Q.Type { get } subscript(covariantAssocMetatypeSubscript2 _: Void) -> (Q.Type, Q.Type.Type) { get } } do { func testCovariantMetatypes(arg: any CovariantMetatypes) { arg.covariantSelfMetatype1 { (_: any CovariantMetatypes.Type.Type.Type) in } let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg.covariantSelfMetatype2() arg.covariantAssocMetatype1 { (_: Any.Type.Type.Type) in } let _: (Any.Type, Any.Type.Type) = arg.covariantAssocMetatype2() let _: any CovariantMetatypes.Type.Type.Type = arg.covariantSelfMetatypeProp1 let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg.covariantSelfMetatypeProp2 let _: Any.Type.Type.Type = arg.covariantAssocMetatypeProp1 let _: (Any.Type, Any.Type.Type) = arg.covariantAssocMetatypeProp2 let _: any CovariantMetatypes.Type = arg[covariantSelfMetatypeSubscript1: { (_: any CovariantMetatypes.Type.Type.Type) in }] let _: (any CovariantMetatypes.Type, any CovariantMetatypes.Type.Type) = arg[covariantSelfMetatypeSubscript2: ()] let _: Any.Type = arg[covariantAssocMetatypeSubscript1: { (_: Any.Type.Type.Type) in }] let _: (Any.Type, Any.Type.Type) = arg[covariantAssocMetatypeSubscript2: ()] } } // Test that a reference to a 'Self'-rooted dependent member type does not // affect the ability to reference a protocol member on an existential when // it is *fully* concrete. protocol ConcreteAssocTypes { associatedtype A1 where A1 == Struct<Self> associatedtype A2 where A2 == (Bool, Self) associatedtype A3 where A3 == any Class<A4> & ConcreteAssocTypes associatedtype A4 func method1(_: A1) func method2() -> Struct<A2> func method3(_: A3) var property1: A1 { get } var property2: A2 { get } var property3: A3 { get } subscript(subscript1 _: A3) -> Bool { get } subscript(subscript2 _: Bool) -> A1 { get } subscript(subscript3 _: A2) -> Bool { get } associatedtype A5 where A5 == Bool associatedtype A6 where A6 == any ConcreteAssocTypes associatedtype A7 where A7 == A8.A5 associatedtype A8: ConcreteAssocTypes func method4(_: Struct<A5>, _: A6.Type, _: () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes var property4: (Struct<A5>, A6.Type, () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes { get } subscript(subscript4 _: Struct<A5>, _: A6.Type, _: () -> A5) -> any Class<Struct<A7>.Inner> & ConcreteAssocTypes { get } } do { func test(arg: any ConcreteAssocTypes) { _ = arg.method1 // expected-error {{member 'method1' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.method2 // expected-error {{member 'method2' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.method3 // expected-error {{member 'method3' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg.property1 // expected-error {{member 'property1' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} // Covariant 'Self' erasure works in conjunction with concrete associated types. let _: (Bool, any ConcreteAssocTypes) = arg.property2 // ok _ = arg.property3 // expected-error {{member 'property3' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript1: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript2: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} _ = arg[subscript3: false] // expected-error {{member 'subscript' cannot be used on value of type 'any ConcreteAssocTypes'; consider using a generic constraint instead}} let _: ( Struct<Bool>, (any ConcreteAssocTypes).Type, () -> Bool ) -> any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg.method4 let _: ( Struct<Bool>, (any ConcreteAssocTypes).Type, () -> Bool ) -> any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg.property4 let _: any Class<Struct<Bool>.Inner> & ConcreteAssocTypes = arg[ // FIXME: Sema thinks (any ConcreteAssocTypes).self is a function ref. // expected-warning@+1 {{use of protocol 'ConcreteAssocTypes' as a type must be written 'any ConcreteAssocTypes'}} subscript4: Struct<Bool>(), ConcreteAssocTypes.self, { true } ] } } protocol ConcreteAssocTypeComposition1 { associatedtype A func method(_: A) } protocol ConcreteAssocTypeComposition2 where A == Bool { associatedtype A } do { let exist: any ConcreteAssocTypeComposition1 & ConcreteAssocTypeComposition2 exist.method(true) // ok } // Edge case: an associated type can be resolved through a class conformance. class Class1Simple: ConcreteAssocTypeThroughClass { typealias A = Bool } class Class1Generic<A>: ConcreteAssocTypeThroughClass { } protocol ConcreteAssocTypeThroughClass { associatedtype A } protocol ConcreteAssocTypeThroughClassRefined: ConcreteAssocTypeThroughClass { func method(_: A) } extension ConcreteAssocTypeThroughClassRefined { func test(arg1: any ConcreteAssocTypeThroughClassRefined & Class1Generic<Self>, arg2: any ConcreteAssocTypeThroughClassRefined & Class1Simple) { arg1.method(self) // ok arg2.method(true) // ok } } protocol ConcreteAssocTypeCollision1 where A == Bool { associatedtype A func method(_: A) } protocol ConcreteAssocTypeCollision2 where A == Never { associatedtype A } do { let exist: any ConcreteAssocTypeCollision1 & ConcreteAssocTypeCollision2 // FIXME: Should 'A' be ambiguous here? exist.method(true) } class BadConformanceClass: CompositionBrokenClassConformance_a {} // expected-error@-1 {{type 'BadConformanceClass' does not conform to protocol 'CompositionBrokenClassConformance_a'}} protocol CompositionBrokenClassConformance_a { associatedtype A // expected-note {{protocol requires nested type 'A'; do you want to add it?}} } protocol CompositionBrokenClassConformance_b: CompositionBrokenClassConformance_a { func method(_: A) } do { // FIXME: Should GenericSignature::getConcreteType return the null type instead // of the error type here for Self.A, despite the broken conformance? let exist: any CompositionBrokenClassConformance_b & BadConformanceClass exist.method(false) // expected-error {{type of expression is ambiguous without more context}} } /// Covariant Associated Type Erasure class Class2Base {} class Class2Derived<T>: Class2Base {} protocol CovariantAssocTypeErasure { associatedtype A1 associatedtype A2: AnyObject associatedtype A3: CovariantAssocTypeErasure associatedtype A4: Class2Base associatedtype A5: Class2Derived<Self> associatedtype A6: CovariantAssocTypeErasure & Class2Base associatedtype A7: Class2Derived<Self> & CovariantAssocTypeErasure associatedtype B1 where B1 == Optional<A1> associatedtype B2 where B2 == (A2, Bool) associatedtype B3 where B3 == A3.Type associatedtype B4 where B4 == Array<A4> associatedtype B5 where B5 == Dictionary<String, A5> func method1() -> A1 func method2() -> A2 func method3() -> A3 func method4() -> A4 func method5() -> A5 func method6() -> A6 func method7() -> A7 func method8() -> B1 func method9() -> B2 func method10() -> B3 func method11() -> B4 func method12() -> B5 } protocol CovariantAssocTypeErasureDerived: CovariantAssocTypeErasure where A1: CovariantAssocTypeErasureDerived, A2: Class2Base, A3: CovariantAssocTypeErasureDerived, A4: CovariantAssocTypeErasureDerived, A5: CovariantAssocTypeErasureDerived, A6: CovariantAssocTypeErasureDerived, A7: Sequence {} do { let exist: any CovariantAssocTypeErasure let _: Any = exist.method1() let _: AnyObject = exist.method2() let _: any CovariantAssocTypeErasure = exist.method3() let _: Class2Base = exist.method4() let _: Class2Base = exist.method5() let _: any Class2Base & CovariantAssocTypeErasure = exist.method6() let _: any Class2Base & CovariantAssocTypeErasure = exist.method7() let _: Any? = exist.method8() let _: (AnyObject, Bool) = exist.method9() let _: any CovariantAssocTypeErasure.Type = exist.method10() let _: Array<Class2Base> = exist.method11() let _: Dictionary<String, Class2Base> = exist.method12() } do { let exist: any CovariantAssocTypeErasureDerived let _: any CovariantAssocTypeErasureDerived = exist.method1() let _: Class2Base = exist.method2() let _: any CovariantAssocTypeErasureDerived = exist.method3() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method4() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method5() let _: any Class2Base & CovariantAssocTypeErasureDerived = exist.method6() let _: any Class2Base & CovariantAssocTypeErasure & Sequence = exist.method7() let _: (any CovariantAssocTypeErasureDerived)? = exist.method8() let _: (Class2Base, Bool) = exist.method9() let _: any CovariantAssocTypeErasureDerived.Type = exist.method10() let _: Array<any Class2Base & CovariantAssocTypeErasureDerived> = exist.method11() let _: Dictionary<String, any Class2Base & CovariantAssocTypeErasureDerived> = exist.method12() }
apache-2.0
6578f858afc42e9da68628f8a188c0f5
63.650106
222
0.706617
3.926489
false
false
false
false
LYM-mg/MGDYZB
MGDYZB简单封装版/MGDYZB/Class/Profile/Controller/ProfileViewController.swift
1
6291
// // ProfileViewController.swift // MGDYZB // // Created by ming on 16/10/30. // Copyright © 2016年 ming. All rights reserved. // 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles // github: https://github.com/LYM-mg // import UIKit private let KProfileViewCellID = "KProfileViewCellID" class ProfileViewController: BaseViewController { // MARK: - lazy fileprivate lazy var headerView: ProfileHeaderView = { let hdView = ProfileHeaderView.profileHeaderView() hdView.delegate = self return hdView }() fileprivate lazy var tableView: UITableView = { let tbView = UITableView(frame: self.view.bounds, style: UITableView.Style.grouped) tbView.dataSource = self tbView.delegate = self // tbView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: KProfileViewCellID) return tbView }() fileprivate lazy var dataArr = [ProfileModel]() // 数据源 override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } // MARK: - extension ProfileViewController { override func setUpMainView() { // 0.给ContentView进行赋值 contentView = tableView tableView.frame = CGRect(x: 0, y: -MGStatusHeight, width: kScreenW, height: self.view.height) view.addSubview(tableView) tableView.tableHeaderView = headerView loadData() super.setUpMainView() } func loadData() { DispatchQueue.global().async { let row1Data = ProfileModel(icon: "order_yellowMark", title: "开播提示") let row2Data = ProfileModel(icon: "order_yellowMark", title: "票务查询") let row3Data = ProfileModel(icon: "order_yellowMark", title: "设置选项") let row4Data = ProfileModel(icon: "order_yellowMark", title: "手游中心", detailTitle: "玩游戏领鱼丸") self.dataArr.append(row1Data) self.dataArr.append(row2Data) self.dataArr.append(row3Data) self.dataArr.append(row4Data) DispatchQueue.main.async(execute: { () -> Void in self.tableView.reloadData() self.loadDataFinished() }) } } } // MARK: - UITableViewDataSource extension ProfileViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 1 { return dataArr.count }else { return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell = tableView.dequeueReusableCell(withIdentifier: KProfileViewCellID) if cell == nil { cell = UITableViewCell(style: UITableViewCell.CellStyle.value1, reuseIdentifier: KProfileViewCellID) cell!.accessoryType = UITableViewCell.AccessoryType.disclosureIndicator } let model = dataArr[(indexPath as NSIndexPath).row] cell!.textLabel?.text = model.title cell!.imageView?.image = UIImage(named: model.icon) cell!.detailTextLabel?.text = model.detailTitle return cell! } } // MARK: - UITableViewDelegate extension ProfileViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 5 } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return 5 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 1 { switch indexPath.row { case 0: // 开播提示 break case 1: // 票务查询 let webviewVc = WKWebViewController(navigationTitle: "票务中心", urlStr: "http://www.douyu.com/h5mobile/eticket/dealLog") show(webviewVc, sender: nil) case 2: // break case 3: // 手游中心 let gameCenterVc = GameCenterViewController() show(gameCenterVc, sender: nil) default: break } } } } // MARK: - UITableViewDelegate extension ProfileViewController: ProfileHeaderViewDelegate { func ProfileHeaderViewSettingBtnClicked() { let settingVC = SettingViewController(style: UITableView.Style.grouped) self.navigationController?.pushViewController(settingVC, animated: true) } func ProfileHeaderViewLetterBtnClicked() { self.show(UIViewController(), sender: nil) } func ProfileHeaderViewLoginBtnClicked() { self.show(UIViewController(), sender: nil) } func ProfileHeaderViewRegistBtnClicked() { self.show(UIViewController(), sender: nil) } func ProfileHeaderViewMenuDidClicked(_ view: UIView) { let tag = view.tag as Int switch (tag) { case 101: show(WKWebViewController(navigationTitle: "排行榜", urlStr: "https://www.douyu.com/directory/rank_list/game"), sender: self) case 102: show(WKWebViewController(navigationTitle: "我的关注", urlStr: "https://www.douyu.com/room/my_follow"), sender: self) case 103: print("103") case 104: show(WKWebViewController(navigationTitle: "鱼翅充值", urlStr: "https://cz.douyu.com/"), sender: self) print("104") default: print("default") } } }
mit
0eaeaab2189ad3ee811f6e1f3bde231d
32.521739
137
0.619163
4.875889
false
false
false
false
entotsu/TKSwarmAlert
TKSwarmAlert/Examples/ViewController.swift
1
1838
// // ViewController.swift // blurTest // // Created by Takuya Okamoto on 2015/08/17. // Copyright (c) 2015年 Uniface. All rights reserved. // import UIKit import TKSwarmAlert class ViewController: UIViewController { let swAlert = TKSwarmAlert(backgroundType: .blur) override func viewDidLoad() { super.viewDidLoad() makeSampleBackGround() let showButton = UIButton() showButton.backgroundColor = UIColor(red:0.976471, green: 0.635294, blue: 0.168627, alpha: 1) showButton.frame = CGRect(x: 0, y: 0, width: 100, height: 100) showButton.center = CGPoint(x: view.center.x, y: view.center.y - 100) showButton.setTitle("show", for: UIControl.State()) showButton.addTarget(self, action: #selector(ViewController.onTapShowButton), for: UIControl.Event.touchUpInside) view.addSubview(showButton) let spawnButton = UIButton() spawnButton.frame = CGRect(x: 20, y: 40, width: 100, height: 44) spawnButton.backgroundColor = UIColor.gray spawnButton.alpha = 0.6 spawnButton.setTitle("spawn", for: UIControl.State()) spawnButton.addTarget(self, action: #selector(ViewController.onTapSpawnButton), for: UIControl.Event.touchUpInside) swAlert.addSubStaticView(spawnButton) swAlert.didDissmissAllViews = { print("didDissmissAllViews") } } @objc func onTapShowButton() { self.showAlert() } @objc func onTapSpawnButton() { self.swAlert.spawn(self.makeSampleViews1()) self.swAlert.addNextViews(self.makeSampleViews2()) } func showAlert() { swAlert.show(self.makeSampleViews1()) swAlert.addNextViews(self.makeSampleViews3()) swAlert.addNextViews(self.makeSampleViews4()) } }
mit
39fac7bded7e85ec8e05a8c204b75cba
30.655172
123
0.658497
3.974026
false
false
false
false
exponent/exponent
packages/expo-system-ui/ios/ExpoSystemUI/ExpoSystemUIModule.swift
2
1991
// Copyright 2021-present 650 Industries. (AKA Expo) All rights reserved. import ExpoModulesCore public class ExpoSystemUIModule: Module { public func definition() -> ModuleDefinition { name("ExpoSystemUI") onCreate { // TODO: Maybe read from the app manifest instead of from Info.plist. // Set / reset the initial color on reload and app start. let color = Bundle.main.object(forInfoDictionaryKey: "RCTRootViewBackgroundColor") as? Int Self.setBackgroundColorAsync(color: color) } function("getBackgroundColorAsync") { () -> String? in Self.getBackgroundColor() } function("setBackgroundColorAsync") { (color: Int) in Self.setBackgroundColorAsync(color: color) } } static func getBackgroundColor() -> String? { var color: String? EXUtilities.performSynchronously { // Get the root view controller of the delegate window. if let window = UIApplication.shared.delegate?.window, let backgroundColor = window?.rootViewController?.view.backgroundColor?.cgColor { color = EXUtilities.hexString(with: backgroundColor) } } return color } static func setBackgroundColorAsync(color: Int?) { EXUtilities.performSynchronously { if color == nil { if let window = UIApplication.shared.delegate?.window { window?.backgroundColor = nil window?.rootViewController?.view.backgroundColor = UIColor.white } return } let backgroundColor = EXUtilities.uiColor(color) // Set the app-wide window, this could have future issues when running multiple React apps, // i.e. dev client can't use expo-system-ui. // Without setting the window backgroundColor, native-stack modals will show the wrong color. if let window = UIApplication.shared.delegate?.window { window?.backgroundColor = backgroundColor window?.rootViewController?.view.backgroundColor = backgroundColor } } } }
bsd-3-clause
1a3b42b1ac284aabf76e9e255346448d
35.2
142
0.69111
4.844282
false
false
false
false
tomco/ObjectMapper
ObjectMapper/Core/Operators.swift
1
14212
// // Operators.swift // ObjectMapper // // Created by Tristan Himmelman on 2014-10-09. // Copyright (c) 2014 hearst. All rights reserved. // /** * This file defines a new operator which is used to create a mapping between an object and a JSON key value. * There is an overloaded operator definition for each type of object that is supported in ObjectMapper. * This provides a way to add custom logic to handle specific types of objects */ infix operator <- {} // MARK:- Objects with Basic types /// Object of Basic type public func <- <T>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.basicType(&left, object: right.value()) } else { ToJSON.basicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional object of basic type public func <- <T>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped optional object of basic type public func <- <T>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalBasicType(&left, object: right.value()) } else { ToJSON.optionalBasicType(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Raw Representable types /// Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T, right: Map) { left <- (right, EnumTransform()) } /// Optional Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T?, right: Map) { left <- (right, EnumTransform()) } /// Implicitly Unwrapped Optional Object of Raw Representable type public func <- <T: RawRepresentable>(inout left: T!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Arrays of Raw Representable type /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T], right: Map) { left <- (right, EnumTransform()) } /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T]?, right: Map) { left <- (right, EnumTransform()) } /// Array of Raw Representable object public func <- <T: RawRepresentable>(inout left: [T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Dictionaries of Raw Representable type /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T], right: Map) { left <- (right, EnumTransform()) } /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T]?, right: Map) { left <- (right, EnumTransform()) } /// Dictionary of Raw Representable object public func <- <T: RawRepresentable>(inout left: [String: T]!, right: Map) { left <- (right, EnumTransform()) } // MARK:- Transforms /// Object of Basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.basicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /// Optional object of basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T?, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /// Implicitly unwrapped optional object of basic type with Transform public func <- <T, Transform: TransformType where Transform.Object == T>(inout left: T!, right: (Map, Transform)) { if right.0.mappingType == MappingType.FromJSON { let value: T? = right.1.transformFromJSON(right.0.currentValue) FromJSON.optionalBasicType(&left, object: value) } else { let value: Transform.JSON? = right.1.transformToJSON(left) ToJSON.optionalBasicType(value, key: right.0.currentKey!, dictionary: &right.0.JSONDictionary) } } /// Array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Implicitly unwrapped optional array of Basic type with Transform public func <- <T: TransformType>(inout left: [T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONArrayWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONArrayWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object], right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.basicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]?, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } /// Implicitly unwrapped optional dictionary of Basic type with Transform public func <- <T: TransformType>(inout left: [String: T.Object]!, right: (Map, T)) { let (map, transform) = right if map.mappingType == MappingType.FromJSON { let values = fromJSONDictionaryWithTransform(map.currentValue, transform: transform) FromJSON.optionalBasicType(&left, object: values) } else { let values = toJSONDictionaryWithTransform(left, transform: transform) ToJSON.optionalBasicType(values, key: map.currentKey!, dictionary: &map.JSONDictionary) } } private func fromJSONArrayWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [T.Object] { if let values = input as? [AnyObject] { return values.filterMap { value in return transform.transformFromJSON(value) } } else { return [] } } private func fromJSONDictionaryWithTransform<T: TransformType>(input: AnyObject?, transform: T) -> [String: T.Object] { if let values = input as? [String: AnyObject] { return values.filterMap { value in return transform.transformFromJSON(value) } } else { return [:] } } private func toJSONArrayWithTransform<T: TransformType>(input: [T.Object]?, transform: T) -> [T.JSON]? { return input?.filterMap { value in return transform.transformToJSON(value) } } private func toJSONDictionaryWithTransform<T: TransformType>(input: [String: T.Object]?, transform: T) -> [String: T.JSON]? { return input?.filterMap { value in return transform.transformToJSON(value) } } // MARK:- Mappable Objects - <T: Mappable> /// Object conforming to Mappable public func <- <T: Mappable>(inout left: T, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.object(&left, object: right.currentValue) } else { ToJSON.object(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional Mappable objects public func <- <T: Mappable>(inout left: T?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped optional Mappable objects public func <- <T: Mappable>(inout left: T!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObject(&left, object: right.currentValue) } else { ToJSON.optionalObject(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Dictionary of Mappable objects - Dictionary<String, T: Mappable> /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectDictionary(&left, object: right.currentValue) } else { ToJSON.objectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionary(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionary(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Dictionary of Mappable objects <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.objectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped Optional Dictionary of Mappable object <String, T: Mappable> public func <- <T: Mappable>(inout left: Dictionary<String, [T]>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectDictionaryOfArrays(&left, object: right.currentValue) } else { ToJSON.optionalObjectDictionaryOfArrays(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Array of Mappable objects - Array<T: Mappable> /// Array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectArray(&left, object: right.currentValue) } else { ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<T>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } // MARK:- Array of Array of Mappable objects - Array<Array<T: Mappable>> /// Array of Array Mappable objects public func <- <T: Mappable>(inout left: Array<Array<T>>, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.objectArray(&left, object: right.currentValue) } else { ToJSON.objectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Optional array of Mappable objects public func <- <T: Mappable>(inout left:Array<Array<T>>?, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } } /// Implicitly unwrapped Optional array of Mappable objects public func <- <T: Mappable>(inout left: Array<Array<T>>!, right: Map) { if right.mappingType == MappingType.FromJSON { FromJSON.optionalObjectArray(&left, object: right.currentValue) } else { ToJSON.optionalObjectArray(left, key: right.currentKey!, dictionary: &right.JSONDictionary) } }
mit
edc386be59a5b430626e82ee18ba8ee7
36.700265
125
0.721362
4.005637
false
false
false
false
macc704/iKF
iKF/KFNoteReadViewController.swift
1
1174
// // KFNoteReadViewController.swift // iKF // // Created by Yoshiaki Matsuzawa on 2014-09-03. // Copyright (c) 2014 Yoshiaki Matsuzawa. All rights reserved. // import UIKit class KFNoteReadViewController: UIViewController { var readView:KFNoteReadView!; var note:KFNote?; required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } init(view: KFNoteReadView){ super.init(nibName: nil, bundle: nil); self.readView = view; } override func loadView() { super.loadView(); self.view = self.readView; } //- (void)viewWillAppear:(BOOL)animated 反映されない override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated); if(self.note != nil){ self.readView._webView.kfModel = self.note!; self.note!.beenRead = true; self.note!.notify(); self.readView.model = self.note!; self.readView.load(); KFAppUtils.executeInBackThread({ KFService.getInstance().readPost(self.note!); return; }); } } }
gpl-2.0
72afcca5f25cc6c2cbe80831d0c30ff8
24.26087
63
0.580895
4.034722
false
false
false
false
toggl/superday
teferi/UI/Modules/Goals/GoalList/Views/GoalCell.swift
1
2071
import UIKit class GoalCell: UITableViewCell { static let cellIdentifier = "goalCell" @IBOutlet private weak var dateLabel: UILabel! @IBOutlet private weak var categoryLabel: UILabel! @IBOutlet private weak var progressIndicator: UIProgressView! @IBOutlet private weak var durationLabel: UILabel! @IBOutlet private weak var percentageLabel: UILabel! @IBOutlet private weak var bottomSpacing: NSLayoutConstraint! var isCurrentGoal = false { didSet { bottomSpacing.constant = isCurrentGoal ? 40 : 12 dateLabel.isHidden = isCurrentGoal } } var goal: Goal! { didSet { let dateFormatter = DateFormatter() dateFormatter.dateFormat = "EEEE MMMM d" dateLabel.text = dateFormatter.string(from: goal.date).uppercased() if goal.category == .unknown { categoryLabel.text = "No goal" categoryLabel.textColor = UIColor.lightGray progressIndicator.progress = 0 durationLabel.text = nil percentageLabel.text = nil } else { let completion = goal.targetTime == 0 ? 0 : Float(goal.timeSoFar / goal.targetTime) categoryLabel.text = goal.category.description + (completion >= 1 ? "🏆" : "") categoryLabel.textColor = UIColor.almostBlack progressIndicator.tintColor = goal.category.color progressIndicator.layer.cornerRadius = 2 progressIndicator.progress = completion durationLabel.text = formatedElapsedTimeText(for: goal.timeSoFar) percentageLabel.text = "\(Int(completion * 100))%" } } } override func awakeFromNib() { super.awakeFromNib() separatorInset = UIEdgeInsetsMake(0, 16, 0, 0) } }
bsd-3-clause
52bfe301fbbd6d70e12e1bb9dd012d12
31.3125
99
0.558511
5.858357
false
false
false
false
alexruperez/ARDeepLinkButton
ARDeepLinkButtonTests/ARDeepLinkButtonTests.swift
1
780
// // ARDeepLinkButtonTests.swift // ARDeepLinkButtonTests // // Created by alexruperez on 31/1/16. // Copyright © 2016 alexruperez. All rights reserved. // import XCTest @testable import ARDeepLinkButton class ARDeepLinkButtonTests: XCTestCase { var deepLinkButton: ARDeepLinkButton? override func setUp() { super.setUp() self.deepLinkButton = ARDeepLinkButton() } override func tearDown() { self.deepLinkButton = nil super.tearDown() } func testAppStoreId() { self.deepLinkButton?.iTunesURL = "https://itunes.apple.com/us/app/madbike/id1067596651?mt=8" XCTAssert(self.deepLinkButton?.appStoreId == "1067596651", "appStoreId generated incorrectly") } }
mit
c4b6359dec358b639785fbaf44fc5ff9
22.606061
102
0.653402
4.078534
false
true
false
false