repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringlengths
1
3
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
Reality-Virtually-Hackathon/Team-2
WorkspaceAR/User Flow VCs/ViewController+Prompts.swift
1
2972
// // ViewController+Prompts.swift // WorkspaceAR // // Created by Avery Lamp on 10/7/17. // Copyright © 2017 Apple. All rights reserved. // import UIKit let hidePromptNotificationName = Notification.Name("HidePromptNotification") extension ViewController{ func checkPrompts(){ if DataManager.shared().userType == nil, let hostClientPickerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "HostClientPickerVC") as? HostClientPickerViewController{ hostClientPickerVC.view.frame = CGRect(x: 0, y: 0, width: 300, height: 200) displayPrompt(viewController: hostClientPickerVC) } } func sendSimpleMessage(text: String, confirm: String = "Okay", size: CGSize = CGSize(width: 300, height: 200)){ if let simpleMessageVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SimpleMessageVC") as? SimpleMessageViewController { simpleMessageVC.view.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height) simpleMessageVC.titleLabel.text = text simpleMessageVC.confirmButton.setTitle(confirm, for: .normal) displayPrompt(viewController: simpleMessageVC) } } func displayPrompt(viewController: UIViewController) { if currentPromptViewController != nil { hidePrompt() } self.view.bringSubview(toFront: fadeView) let animationDistance:CGFloat = 80 let animationDuration = 0.5 self.addChildViewController(viewController) self.view.addSubview(viewController.view) viewController.didMove(toParentViewController: self) viewController.view.center = CGPoint(x: self.view.center.x, y: self.view.center.y - animationDistance) viewController.view.alpha = 0.0 UIView.animate(withDuration: animationDuration) { viewController.view.alpha = 1.0 viewController.view.center.y += animationDistance self.fadeView.alpha = 0.5 } fadeView.isUserInteractionEnabled = true currentPromptViewController = viewController } @objc func hidePrompt(){ if let vc = currentPromptViewController{ let animationDistance:CGFloat = 80 let animationDuration = 0.5 UIView.animate(withDuration: animationDuration, animations: { vc.view.center.y += animationDistance vc.view.alpha = 0.0 self.fadeView.alpha = 0.0 }, completion: { (finished) in vc.view.removeFromSuperview() vc.removeFromParentViewController() self.currentPromptViewController = nil }) fadeView.isUserInteractionEnabled = false } } @objc func fadeViewClicked(sender:UIButton){ print("Fade View clicked") } }
mit
0684bc3a5046af9fd876a3408c8a8722
37.584416
213
0.644901
5.113597
false
false
false
false
CodeEagle/XcodeScriptsKit
build_number.swift
1
1147
#!/usr/bin/env xcrun -sdk macosx swift import Foundation func addBuildNumber() { let buildKey = "CFBundleVersion" let totalKey = "total" var arguments: [String] = CommandLine.arguments let dir = arguments.removeFirst() as NSString let buildInfo = arguments.removeFirst() let infoPlistpath = arguments.removeFirst() var userInfo: [String : Any] = [:] if let info = NSDictionary(contentsOfFile: buildInfo) as? [String : Any] { userInfo = info } let array = dir.components(separatedBy: "/") let userName = array[2] let release = arguments.removeLast() == "1" var count = userInfo[userName] as? Int ?? 0 count += 1 userInfo[userName] = count var total = userInfo[totalKey] as? Int ?? 0 total += 1 userInfo[totalKey] = total _ = (userInfo as NSDictionary).write(toFile: buildInfo, atomically: true) if release { guard let info = NSDictionary(contentsOfFile: infoPlistpath) as? [String : Any] else { return } var f = info f[buildKey] = "\(total)" _ = (f as NSDictionary).write(toFile: infoPlistpath, atomically: true) } } addBuildNumber()
mit
9eb77c61920d1595c3cd5c1e0536e38a
36
103
0.655623
4.067376
false
false
false
false
nakiostudio/EasyPeasy
Example/Tests/NodeTests.swift
1
26391
// The MIT License (MIT) - Copyright (c) 2016 Carlos Vidal // // 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 XCTest @testable import EasyPeasy class NodeTests: XCTestCase { // MARK: Left node func testThatLeftSubnodeIsSet() { // given let node = Node() let leftAttribute = Left() // when _ = node.add(attribute: leftAttribute) // then XCTAssertNotNil(node.left) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) } func testThatLeftSubnodeIsNotSetIfAttributeConditionIsFalse() { // given let node = Node() let leftAttribute = Left().when { false } // when _ = node.add(attribute: leftAttribute) // then XCTAssertNil(node.left) XCTAssertTrue(node.activeAttributes.count == 0) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertNil(node.center) XCTAssertNil(node.right) XCTAssertNil(node.dimension) } func testThatLeftSubnodeIsUpdatedWhenReplacedWithAnotherLeft() { // given let node = Node() let leftAttribute = Left() let leadingAttribute = Leading() _ = node.add(attribute: leftAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.left === leftAttribute) // when _ = node.add(attribute: leadingAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.left === leadingAttribute) XCTAssertNil(node.center) XCTAssertNil(node.right) XCTAssertNil(node.dimension) } func testThatLeftSubnodeIsUpdatedWhenReplacedWithCenterSubnode() { // given let node = Node() let leftAttribute = Left() let centerAttribute = CenterX() _ = node.add(attribute: leftAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.left === leftAttribute) XCTAssertNil(node.center) // when _ = node.add(attribute: centerAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerAttribute) XCTAssertNil(node.left) XCTAssertNil(node.dimension) XCTAssertNil(node.right) } func testThatLeftSubnodeIsNotUpdatedWhenOnlyDimensionSubnodeIsApplied() { // given let node = Node() let leftAttribute = Left() let dimensionAttribute = Width() _ = node.add(attribute: leftAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.left === leftAttribute) XCTAssertNil(node.center) XCTAssertNil(node.dimension) // when _ = node.add(attribute: dimensionAttribute) // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === dimensionAttribute) XCTAssertNotNil(node.left) XCTAssertNotNil(node.dimension) XCTAssertNil(node.center) XCTAssertNil(node.right) } func testThatThereIsNotLayoutConstraintToApplyWhenSameLeftAttributeIsAddedTwice() { // given let node = Node() let superview = UIView() let view = UIView() superview.addSubview(view) let leftAttribute = Left() leftAttribute.createConstraints(for: view) let constraints = node.add(attribute: leftAttribute) XCTAssertTrue(constraints?.0.count == 1) XCTAssertTrue(constraints?.1.count == 0) // when let newConstraints = node.add(attribute: leftAttribute) // then XCTAssertNil(newConstraints) } // MARK: Right node func testThatRightSubnodeIsSet() { // given let node = Node() let rightAttribute = Right() // when _ = node.add(attribute: rightAttribute) // then XCTAssertNotNil(node.right) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) } func testThatRightSubnodeIsNotSetIfAttributeConditionIsFalse() { // given let node = Node() let rightAttribute = Right().when { false } // when _ = node.add(attribute: rightAttribute) // then XCTAssertNil(node.right) XCTAssertTrue(node.activeAttributes.count == 0) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertNil(node.center) XCTAssertNil(node.left) XCTAssertNil(node.dimension) } func testThatRightSubnodeIsUpdatedWhenReplacedWithAnotherRight() { // given let node = Node() let rightAttribute = Right() let trailingAttribute = Trailing() _ = node.add(attribute: rightAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.right === rightAttribute) // when _ = node.add(attribute: trailingAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.right === trailingAttribute) XCTAssertNil(node.center) XCTAssertNil(node.left) XCTAssertNil(node.dimension) } func testThatRightSubnodeIsUpdatedWhenReplacedWithCenterSubnode() { // given let node = Node() let rightAttribute = Right() let centerAttribute = CenterX() _ = node.add(attribute: rightAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.right === rightAttribute) XCTAssertNil(node.center) // when _ = node.add(attribute: centerAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerAttribute) XCTAssertNil(node.left) XCTAssertNil(node.dimension) XCTAssertNil(node.right) } func testThatRightSubnodeIsNotUpdatedWhenOnlyDimensionSubnodeIsApplied() { // given let node = Node() let rightAttribute = Right() let dimensionAttribute = Width() _ = node.add(attribute: rightAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.right === rightAttribute) XCTAssertNil(node.center) XCTAssertNil(node.dimension) // when _ = node.add(attribute: dimensionAttribute) // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === dimensionAttribute) XCTAssertNotNil(node.right) XCTAssertNotNil(node.dimension) XCTAssertNil(node.center) XCTAssertNil(node.left) } func testThatThereIsNotLayoutConstraintToApplyWhenSameRightAttributeIsAddedTwice() { // given let node = Node() let superview = UIView() let view = UIView() superview.addSubview(view) let rightAttribute = Right() rightAttribute.createConstraints(for: view) let constraints = node.add(attribute: rightAttribute) XCTAssertTrue(constraints?.0.count == 1) XCTAssertTrue(constraints?.1.count == 0) // when let newConstraints = node.add(attribute: rightAttribute) // then XCTAssertNil(newConstraints) } // MARK: Center node func testThatCenterSubnodeIsSet() { // given let node = Node() let centerAttribute = CenterX() // when _ = node.add(attribute: centerAttribute) // then XCTAssertNotNil(node.center) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) } func testThatCenterSubnodeIsNotSetIfAttributeConditionIsFalse() { // given let node = Node() let centerAttribute = CenterX().when { false } // when _ = node.add(attribute: centerAttribute) // then XCTAssertNil(node.center) XCTAssertTrue(node.activeAttributes.count == 0) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertNil(node.left) XCTAssertNil(node.right) XCTAssertNil(node.dimension) } func testThatCenterSubnodeIsUpdatedWhenReplacedWithAnotherCenter() { // given let node = Node() let centerAttribute = CenterX() let centerXWithinMarginsAttribute = CenterXWithinMargins() _ = node.add(attribute: centerAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerAttribute) // when _ = node.add(attribute: centerXWithinMarginsAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerXWithinMarginsAttribute) XCTAssertNil(node.left) XCTAssertNil(node.right) XCTAssertNil(node.dimension) } func testThatCenterSubnodeIsUpdatedWhenReplacedWithLeftSubnode() { // given let node = Node() let leftAttribute = FirstBaseline() let centerAttribute = CenterY() _ = node.add(attribute: centerAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerAttribute) XCTAssertNil(node.left) // when _ = node.add(attribute: leftAttribute) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.left === leftAttribute) XCTAssertNil(node.center) XCTAssertNil(node.dimension) XCTAssertNil(node.right) } func testThatCenterSubnodeIsNotUpdatedWhenDimensionSubnodeIsApplied() { // given let node = Node() let centerAttribute = CenterX() let dimensionAttribute = Width() _ = node.add(attribute: centerAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.center === centerAttribute) XCTAssertNil(node.left) XCTAssertNil(node.right) XCTAssertNil(node.dimension) // when _ = node.add(attribute: dimensionAttribute) // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === dimensionAttribute) XCTAssertNotNil(node.center) XCTAssertNotNil(node.dimension) XCTAssertNil(node.left) XCTAssertNil(node.right) } func testThatThereIsNotLayoutConstraintToApplyWhenSameCenterAttributeIsAddedTwice() { // given let node = Node() let superview = UIView() let view = UIView() superview.addSubview(view) let centerAttribute = CenterX() centerAttribute.createConstraints(for: view) let constraints = node.add(attribute: centerAttribute) XCTAssertTrue(constraints?.0.count == 1) XCTAssertTrue(constraints?.1.count == 0) // when let newConstraints = node.add(attribute: centerAttribute) // then XCTAssertNil(newConstraints) } // MARK: Dimension node func testThatDimensionSubnodeIsSet() { // given let node = Node() let dimensionAttribute = Width() // when _ = node.add(attribute: dimensionAttribute) // then XCTAssertNotNil(node.dimension) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) } func testThatDimensionSubnodeIsNotSetIfAttributeConditionIsFalse() { // given let node = Node() let dimensionAttribute = Width().when { false } // when _ = node.add(attribute: dimensionAttribute) // then XCTAssertNil(node.dimension) XCTAssertTrue(node.activeAttributes.count == 0) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertNil(node.center) XCTAssertNil(node.right) XCTAssertNil(node.left) } func testThatDimensionSubnodeIsUpdatedWhenReplacedWithAnotherDimension() { // given let node = Node() let widthAttributeA = Width() let widthAttributeB = Width() _ = node.add(attribute: widthAttributeA) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === widthAttributeA) // when _ = node.add(attribute: widthAttributeB) // then XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === widthAttributeB) XCTAssertNotNil(node.dimension) XCTAssertNil(node.center) XCTAssertNil(node.right) XCTAssertNil(node.left) } func testThatDimensionSubnodeIsNotUpdatedWhenCenterSubnodeIsApplied() { // given let node = Node() let centerAttribute = CenterXWithinMargins() let dimensionAttribute = Width() _ = node.add(attribute: dimensionAttribute) XCTAssertTrue(node.activeAttributes.count == 1) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === dimensionAttribute) XCTAssertNil(node.center) XCTAssertNil(node.left) XCTAssertNil(node.right) // when _ = node.add(attribute: centerAttribute) // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(node.dimension === dimensionAttribute) XCTAssertTrue(node.center === centerAttribute) XCTAssertNil(node.left) XCTAssertNil(node.right) } func testThatThereIsNotLayoutConstraintToApplyWhenSameDimensionAttributeIsAddedTwice() { // given let node = Node() let superview = UIView() let view = UIView() superview.addSubview(view) let widthAttribute = Width() widthAttribute.createConstraints(for: view) let constraints = node.add(attribute: widthAttribute) XCTAssertTrue(constraints?.0.count == 1) XCTAssertTrue(constraints?.1.count == 0) // when let newConstraints = node.add(attribute: widthAttribute) // then XCTAssertNil(newConstraints) } func testThatReloadHandlesCorrectlyEachSubnode() { // given let superview = UIView() let view = UIView() superview.addSubview(view) var value = true let node = Node() let leftAttributeA = LeftMargin().when { value } leftAttributeA.createConstraints(for: view) let leftAttributeB = Left().when { value == false } leftAttributeB.createConstraints(for: view) let rightAttribute = RightMargin() rightAttribute.createConstraints(for: view) let activationGroupA = node.add(attribute: leftAttributeA) let activationGroupB = node.add(attribute: leftAttributeB) let activationGroupC = node.add(attribute: rightAttribute) let activeAttributes = node.activeAttributes let inactiveAttributes = node.inactiveAttributes XCTAssertTrue(activeAttributes.count == 2) XCTAssertTrue(inactiveAttributes.count == 1) XCTAssertTrue(node.left === leftAttributeA) XCTAssertTrue(node.right === rightAttribute) XCTAssertTrue(inactiveAttributes.first === leftAttributeB) XCTAssertNil(node.center) XCTAssertTrue(activationGroupA?.0.count == 1) XCTAssertTrue(activationGroupA?.1.count == 0) XCTAssertNil(activationGroupB) XCTAssertTrue(activationGroupC?.0.count == 1) XCTAssertTrue(activationGroupC?.1.count == 0) // when value = false let reloadActivationGroup = node.reload() // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertTrue(node.left === leftAttributeB) XCTAssertTrue(node.right === rightAttribute) XCTAssertTrue(inactiveAttributes.first === leftAttributeB) XCTAssertNil(node.center) XCTAssertTrue(reloadActivationGroup.0.count == 1) XCTAssertTrue(reloadActivationGroup.1.count == 1) // And again // when value = true let reloadActivationGroupB = node.reload() // then XCTAssertTrue(node.activeAttributes.count == 2) XCTAssertTrue(node.inactiveAttributes.count == 1) XCTAssertTrue(node.left === leftAttributeA) XCTAssertTrue(node.right === rightAttribute) XCTAssertTrue(inactiveAttributes.first === leftAttributeB) XCTAssertNil(node.center) XCTAssertTrue(reloadActivationGroupB.0.count == 1) XCTAssertTrue(reloadActivationGroupB.1.count == 1) } func testThatClearMethodRemovesEverySubnodeAndReturnsTheExpectedConstraints() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() let leftAttributeA = TopMargin().when { true } leftAttributeA.createConstraints(for: view) let leftAttributeB = Top().when { false } leftAttributeB.createConstraints(for: view) let rightAttribute = LastBaseline() rightAttribute.createConstraints(for: view) let dimension = Width() dimension.createConstraints(for: view) let center = CenterXWithinMargins().when { false } center.createConstraints(for: view) _ = node.add(attribute: leftAttributeA) _ = node.add(attribute: leftAttributeB) _ = node.add(attribute: rightAttribute) _ = node.add(attribute: dimension) _ = node.add(attribute: center) XCTAssertTrue(node.left === leftAttributeA) XCTAssertTrue(node.right === rightAttribute) XCTAssertTrue(node.dimension === dimension) XCTAssertTrue(node.activeAttributes.count == 3) XCTAssertTrue(node.inactiveAttributes.count == 2) XCTAssertNil(node.center) // when let constraints = node.clear() // then XCTAssertNil(node.left) XCTAssertNil(node.right) XCTAssertNil(node.dimension) XCTAssertNil(node.center) XCTAssertTrue(node.activeAttributes.count == 0) XCTAssertTrue(node.inactiveAttributes.count == 0) XCTAssertTrue(constraints.count == 3) } func testThatActivationGroupIsTheExpectedAddingAttributes() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() let leftAttributeA = Left(100) leftAttributeA.createConstraints(for: view) let rightAttributeA = Right(100) rightAttributeA.createConstraints(for: view) let activationGroupLeftA = node.add(attribute: leftAttributeA) XCTAssertTrue(activationGroupLeftA!.0.count == 1) XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint) XCTAssertTrue(activationGroupLeftA!.1.count == 0) let activationGroupRightA = node.add(attribute: rightAttributeA) XCTAssertTrue(activationGroupRightA!.0.count == 1) XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint) XCTAssertTrue(activationGroupRightA!.1.count == 0) // when let centerAttribute = CenterX(0.0) centerAttribute.createConstraints(for: view) let activationGroupCenter = node.add(attribute: centerAttribute) // then XCTAssertTrue(activationGroupCenter!.0.count == 1) XCTAssertTrue(activationGroupCenter!.0.first === centerAttribute.layoutConstraint) XCTAssertTrue(activationGroupCenter!.1.count == 2) XCTAssertTrue(activationGroupCenter!.1[0] === leftAttributeA.layoutConstraint) XCTAssertTrue(activationGroupCenter!.1[1] === rightAttributeA.layoutConstraint) } func testThatActivationGroupIsTheExpectedWhenSameAttributeIsAppliedTwice() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() let leftAttributeA = Left(100) leftAttributeA.createConstraints(for: view) let activationGroupLeftA = node.add(attribute: leftAttributeA) XCTAssertTrue(activationGroupLeftA!.0.count == 1) XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint) XCTAssertTrue(activationGroupLeftA!.1.count == 0) // when let activationGroupLeftB = node.add(attribute: leftAttributeA) // then XCTAssertNil(activationGroupLeftB) } func testThatActivationGroupIsTheExpectedWhenShouldInstallIsFalse() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() let leftAttributeA = Left(100).when { false } leftAttributeA.createConstraints(for: view) // when let activationGroupLeftA = node.add(attribute: leftAttributeA) // then XCTAssertNil(activationGroupLeftA) } func testThatActivationGroupIsTheExpectedUponReloadWithNoChanges() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() let leftAttributeA = Left(100) leftAttributeA.createConstraints(for: view) let rightAttributeA = Right(100) rightAttributeA.createConstraints(for: view) let activationGroupLeftA = node.add(attribute: leftAttributeA) XCTAssertTrue(activationGroupLeftA!.0.count == 1) XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint) XCTAssertTrue(activationGroupLeftA!.1.count == 0) let activationGroupRightA = node.add(attribute: rightAttributeA) XCTAssertTrue(activationGroupRightA!.0.count == 1) XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint) XCTAssertTrue(activationGroupRightA!.1.count == 0) // when let activationGroupReload = node.reload() // then XCTAssertTrue(activationGroupReload.0.count == 0) XCTAssertTrue(activationGroupReload.1.count == 0) } func testThatActivationGroupIsTheExpectedUponReloadWithChanges() { // given let superview = UIView() let view = UIView() superview.addSubview(view) let node = Node() var condition = true let leftAttributeA = Left(100).when { condition } leftAttributeA.createConstraints(for: view) let leftAttributeB = Left(100).when { !condition } leftAttributeB.createConstraints(for: view) let rightAttributeA = Right(100) rightAttributeA.createConstraints(for: view) let activationGroupLeftA = node.add(attribute: leftAttributeA) XCTAssertTrue(activationGroupLeftA!.0.count == 1) XCTAssertTrue(activationGroupLeftA!.0.first === leftAttributeA.layoutConstraint) XCTAssertTrue(activationGroupLeftA!.1.count == 0) let activationGroupLeftB = node.add(attribute: leftAttributeB) XCTAssertNil(activationGroupLeftB) let activationGroupRightA = node.add(attribute: rightAttributeA) XCTAssertTrue(activationGroupRightA!.0.count == 1) XCTAssertTrue(activationGroupRightA!.0.first === rightAttributeA.layoutConstraint) XCTAssertTrue(activationGroupRightA!.1.count == 0) // when condition = false let activationGroupReload = node.reload() // then XCTAssertTrue(activationGroupReload.0.count == 1) XCTAssertTrue(activationGroupReload.0.first === leftAttributeB.layoutConstraint) XCTAssertTrue(activationGroupReload.1.count == 1) XCTAssertTrue(activationGroupReload.1.first === leftAttributeA.layoutConstraint) } }
mit
f560afec366f0eb2b1d3fdab5c21bcb8
35.102599
92
0.635179
5.522285
false
false
false
false
shaps80/Peek
Pod/Classes/GraphicsRenderer/PDFRenderer.swift
1
8935
/* Copyright © 03/10/2016 Snippex Ltd 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 /** * Represents a PDF renderer format */ internal final class PDFRendererFormat: RendererFormat { /** Returns a default format, configured for this device - returns: A new format */ internal static func `default`() -> PDFRendererFormat { let bounds = CGRect(x: 0, y: 0, width: 612, height: 792) return PDFRendererFormat(bounds: bounds, documentInfo: [:], flipped: false) } /// Returns the bounds for this format internal let bounds: CGRect /// Returns the associated document info internal var documentInfo: [String: Any] internal var isFlipped: Bool /** Creates a new format with the specified bounds and pageInfo - parameter bounds: The bounds for each page in the PDF - parameter documentInfo: The info associated with this PDF - returns: A new PDF renderer format */ internal init(bounds: CGRect, documentInfo: [String: Any], flipped: Bool) { self.bounds = bounds self.documentInfo = documentInfo self.isFlipped = flipped } /// Creates a new format with the specified document info and whether or not the context should be flipped /// /// - Parameters: /// - documentInfo: The associated PSD document info /// - flipped: If true, the context drawing will be flipped internal init(documentInfo: [String: Any], flipped: Bool) { self.bounds = .zero self.documentInfo = documentInfo self.isFlipped = flipped } } /// Represents a PDF renderer context internal final class PDFRendererContext: RendererContext { /// The underlying CGContext internal let cgContext: CGContext /// The format for this context internal let format: PDFRendererFormat /// The PDF context bounds internal let pdfContextBounds: CGRect // Internal variable for auto-closing pages private var hasOpenPage: Bool = false /// Creates a new context. If an existing page is open, this will also close it for you. /// /// - Parameters: /// - format: The format for this context /// - cgContext: The underlying CGContext to associate with this context /// - bounds: The bounds to use for this context internal init(format: PDFRendererFormat, cgContext: CGContext, bounds: CGRect) { self.format = format self.cgContext = cgContext self.pdfContextBounds = bounds } /// Creates a new PDF page. The bounds will be the same as specified by the document internal func beginPage() { beginPage(withBounds: format.bounds, pageInfo: [:]) } /// Creates a new PDF page. If an existing page is open, this will also close it for you. /// /// - Parameters: /// - bounds: The bounds to use for this page /// - pageInfo: The pageInfo associated to be associated with this page internal func beginPage(withBounds bounds: CGRect, pageInfo: [String : Any]) { var info = pageInfo info[kCGPDFContextMediaBox as String] = bounds let pageInfo = info as CFDictionary endPageIfOpen() cgContext.beginPDFPage(pageInfo) hasOpenPage = true if format.isFlipped { let transform = CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: format.bounds.height) cgContext.concatenate(transform) } } /// Set the URL associated with `rect' to `url' in the PDF context `context'. /// /// - Parameters: /// - url: The url to link to /// - rect: The rect representing the link internal func setURL(_ url: URL, for rect: CGRect) { let url = url as CFURL cgContext.setURL(url, for: rect) } /// Create a PDF destination named `name' at `point' in the current page of the PDF context `context'. /// /// - Parameters: /// - name: A destination name /// - point: A location in the current page internal func addDestination(withName name: String, at point: CGPoint) { let name = name as CFString cgContext.addDestination(name, at: point) } /// Specify a destination named `name' to jump to when clicking in `rect' of the current page of the PDF context `context'. /// /// - Parameters: /// - name: A destination name /// - rect: A rect in the current page internal func setDestinationWithName(_ name: String, for rect: CGRect) { let name = name as CFString cgContext.setDestination(name, for: rect) } // If a page is currently opened, this will close it. Otherwise it does nothing fileprivate func endPageIfOpen() { guard hasOpenPage else { return } cgContext.endPDFPage() } } extension PDFRenderer { internal convenience init(bounds: CGRect) { self.init(bounds: bounds, format: nil) } } /// Represents a PDF renderer internal final class PDFRenderer: Renderer { /// The associated context type internal typealias Context = PDFRendererContext /// Returns the format for this renderer internal let format: PDFRendererFormat /// Creates a new PDF renderer with the specified bounds /// /// - Parameters: /// - bounds: The bounds of the PDF /// - format: The format to use for this PDF internal init(bounds: CGRect, format: PDFRendererFormat? = nil) { guard bounds.size != .zero else { fatalError("size cannot be zero") } let info = format?.documentInfo ?? [:] self.format = PDFRendererFormat(bounds: bounds, documentInfo: info, flipped: format?.isFlipped ?? true) } /// Draws the PDF and writes is to the specified URL /// /// - Parameters: /// - url: The url to write tp /// - actions: The drawing actions to perform /// - Throws: May throw internal func writePDF(to url: URL, withActions actions: (PDFRendererContext) -> Void) throws { var rect = format.bounds let consumer = CGDataConsumer(url: url as CFURL)! let context = CGContext(consumer: consumer, mediaBox: &rect, format.documentInfo as CFDictionary?)! try? runDrawingActions(forContext: context, drawingActions: actions, completionActions: nil) } /// Draws the PDF and returns the associated Data representation /// /// - Parameter actions: The drawing actions to perform /// - Returns: The PDF data internal func pdfData(actions: (PDFRendererContext) -> Void) -> Data { var rect = format.bounds let data = NSMutableData() let consumer = CGDataConsumer(data: data)! let context = CGContext(consumer: consumer, mediaBox: &rect, format.documentInfo as CFDictionary?)! try? runDrawingActions(forContext: context, drawingActions: actions, completionActions: nil) return data as Data } private func runDrawingActions(forContext cgContext: CGContext, drawingActions: (Context) -> Void, completionActions: ((Context) -> Void)? = nil) throws { let context = PDFRendererContext(format: format, cgContext: cgContext, bounds: format.bounds) #if os(OSX) let previousContext = NSGraphicsContext.current NSGraphicsContext.current = NSGraphicsContext(cgContext: context.cgContext, flipped: format.isFlipped) #else UIGraphicsPushContext(context.cgContext) #endif drawingActions(context) completionActions?(context) context.endPageIfOpen() context.cgContext.closePDF() #if os(OSX) NSGraphicsContext.current = previousContext #else UIGraphicsPopContext() #endif } }
mit
e08475d40480896496833872454b9a64
35.917355
158
0.654242
4.837033
false
false
false
false
hooman/swift
test/decl/protocol/special/coding/enum_codable_invalid_codingkeys.swift
3
2032
// RUN: %target-typecheck-verify-swift -verify-ignore-unknown // Enums with a CodingKeys entity which is not a type should not derive // conformance. enum InvalidCodingKeys1 : Codable { // expected-error {{type 'InvalidCodingKeys1' does not conform to protocol 'Decodable'}} // expected-error@-1 {{type 'InvalidCodingKeys1' does not conform to protocol 'Encodable'}} static let CodingKeys = 5 // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum}} // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum}} } // Enums with a CodingKeys entity which does not conform to CodingKey should // not derive conformance. enum InvalidCodingKeys2 : Codable { // expected-error {{type 'InvalidCodingKeys2' does not conform to protocol 'Decodable'}} // expected-error@-1 {{type 'InvalidCodingKeys2' does not conform to protocol 'Encodable'}} enum CodingKeys {} // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' does not conform to CodingKey}} // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' does not conform to CodingKey}} } // Enums with a CodingKeys entity which is not an enum should not derive // conformance. enum InvalidCodingKeys3 : Codable { // expected-error {{type 'InvalidCodingKeys3' does not conform to protocol 'Decodable'}} // expected-error@-1 {{type 'InvalidCodingKeys3' does not conform to protocol 'Encodable'}} struct CodingKeys : CodingKey { // expected-note {{cannot automatically synthesize 'Decodable' because 'CodingKeys' is not an enum}} // expected-note@-1 {{cannot automatically synthesize 'Encodable' because 'CodingKeys' is not an enum}} var stringValue: String init?(stringValue: String) { self.stringValue = stringValue self.intValue = nil } var intValue: Int? init?(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } } }
apache-2.0
f63aff0a998cc42b550fa5ff227e15c7
53.918919
136
0.725886
4.703704
false
false
false
false
lorentey/swift
test/SILGen/vtables_multifile.swift
4
22343
// RUN: %target-swift-emit-silgen %s | %FileCheck %s // RUN: %target-swift-emit-silgen %s -primary-file %S/Inputs/vtables_multifile_2.swift | %FileCheck %S/Inputs/vtables_multifile_2.swift // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module %s -enable-library-evolution -emit-module-path %t/vtables_multifile.swiftmodule // RUN: %target-swift-emit-silgen %S/Inputs/vtables_multifile_3.swift -I %t | %FileCheck %S/Inputs/vtables_multifile_3.swift open class Base<T> { fileprivate func privateMethod1() {} fileprivate func privateMethod2(_: AnyObject) {} fileprivate func privateMethod3(_: Int) {} fileprivate func privateMethod4(_: T) {} } open class Derived : Base<Int> { internal override func privateMethod1() {} // ABI compatible override with same type internal override func privateMethod2(_: AnyObject?) {} // ABI compatible override with different type internal override func privateMethod3(_: Int?) {} // Requires thunking, different type internal override func privateMethod4(_: Int) {} // Requires thunking, same type } open class MoreDerived : Derived { public override func privateMethod1() {} public override func privateMethod2(_: AnyObject?) {} public override func privateMethod3(_: Int?) {} public override func privateMethod4(_: Int) {} } open class MostDerived : MoreDerived { open override func privateMethod1() {} open override func privateMethod2(_: AnyObject?) {} open override func privateMethod3(_: Int?) {} open override func privateMethod4(_: Int) {} } public final class FinalDerived : Base<Int> { internal override func privateMethod1() {} internal override func privateMethod2(_: AnyObject?) {} internal override func privateMethod3(_: Int?) {} internal override func privateMethod4(_: Int) {} } // See Inputs/vtables_multifile_2.swift for overrides in a different file. // See Inputs/vtables_multifile_3.swift for overrides in a different module. // -- // VTable thunks for the more visible overrides of less visible methods dispatch to the // vtable slot for the more visible method. // -- // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV : $@convention(method) (@guaranteed Derived) -> () { // CHECK: bb0(%0 : @guaranteed $Derived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %0 : $Derived, #Derived.privateMethod1!1 : (Derived) -> () -> (), $@convention(method) (@guaranteed Derived) -> () // CHECK-NEXT: apply [[METHOD]](%0) : $@convention(method) (@guaranteed Derived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> () { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $Derived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod2!1 : (Derived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> () // CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed Derived) -> () { // CHECK: bb0(%0 : $Int, %1 : @guaranteed $Derived): // CHECK-NEXT: [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod3!1 : (Derived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed Derived) -> () // CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Optional<Int>, @guaranteed Derived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed Derived) -> () { // CHECK: bb0(%0 : $*Int, %1 : @guaranteed $Derived): // CHECK-NEXT: [[ARG:%.*]] = load [trivial] %0 : $*Int // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod4!1 : (Derived) -> (Int) -> (), $@convention(method) (Int, @guaranteed Derived) -> () // CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Int, @guaranteed Derived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // -- // The subclass can see both the methods of Base and the methods of Derived, // so it overrides both with thunks that dispatch to methods of MoreDerived. // -- // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV : $@convention(method) (@guaranteed MoreDerived) -> () // CHECK: bb0(%0 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %0 : $MoreDerived, #MoreDerived.privateMethod1!1 : (MoreDerived) -> () -> (), $@convention(method) (@guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0) : $@convention(method) (@guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod2!1 : (MoreDerived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : $Int, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod3!1 : (MoreDerived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : $*Int, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[ARG:%.*]] = load [trivial] %0 : $*Int // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod4!1 : (MoreDerived) -> (Int) -> (), $@convention(method) (Int, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Int, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // -- // Thunks override methods of Derived as well. // -- // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA0D0CADyyFTV : $@convention(method) (@guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %0 : $MoreDerived, #MoreDerived.privateMethod1!1 : (MoreDerived) -> () -> (), $@convention(method) (@guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0) : $@convention(method) (@guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod2!1 : (MoreDerived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : $Optional<Int>, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod3!1 : (MoreDerived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (Optional<Int>, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA0D0CADyySiFTV : $@convention(method) (Int, @guaranteed MoreDerived) -> () { // CHECK: bb0(%0 : $Int, %1 : @guaranteed $MoreDerived): // CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $MoreDerived, #MoreDerived.privateMethod4!1 : (MoreDerived) -> (Int) -> (), $@convention(method) (Int, @guaranteed MoreDerived) -> () // CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (Int, @guaranteed MoreDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // -- // Thunks for final overrides do not re-dispatch, even if the override is more // visible. // -- // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed FinalDerived) -> () { // CHECK: bb0(%0 : $Int, %1 : @guaranteed $FinalDerived): // CHECK-NEXT: [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int // user: %4 // CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgF : $@convention(method) (Optional<Int>, @guaranteed FinalDerived) -> () // CHECK-NEXT: apply [[METHOD]]([[ARG]], %1) : $@convention(method) (Optional<Int>, @guaranteed FinalDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed FinalDerived) -> () { // CHECK: bb0(%0 : $*Int, %1 : @guaranteed $FinalDerived): // CHECK-NEXT: [[ARG:%.*]] = load [trivial] %0 : $*Int // CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiF : $@convention(method) (Int, @guaranteed FinalDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = apply [[METHOD]]([[ARG]], %1) : $@convention(method) (Int, @guaranteed FinalDerived) -> () // CHECK-NEXT: [[RESULT:%.*]] = tuple () // CHECK-NEXT: return [[RESULT]] : $() // CHECK-NEXT: } // -- // VTable for Derived. // -- // CHECK-LABEL: sil_vtable [serialized] Derived { // CHECK-NEXT: #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override] // vtable thunk for Base.privateMethod1() dispatching to Derived.privateMethod1() // CHECK-NEXT: #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override] // vtable thunk for Base.privateMethod2(_:) dispatching to Derived.privateMethod2(_:) // CHECK-NEXT: #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override] // vtable thunk for Base.privateMethod3(_:) dispatching to Derived.privateMethod3(_:) // CHECK-NEXT: #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to Derived.privateMethod4(_:) // CHECK-NEXT: #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile7DerivedCACycfC [override] // Derived.__allocating_init() // CHECK-NEXT: #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile7DerivedC14privateMethod1yyF // Derived.privateMethod1() // CHECK-NEXT: #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgF // Derived.privateMethod2(_:) // CHECK-NEXT: #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile7DerivedC14privateMethod3yySiSgF // Derived.privateMethod3(_:) // CHECK-NEXT: #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile7DerivedC14privateMethod4yySiF // Derived.privateMethod4(_:) // CHECK-NEXT: #Derived.deinit!deallocator.1: @$s17vtables_multifile7DerivedCfD // Derived.__deallocating_deinit // CHECK-NEXT: } // -- // VTable for MoreDerived. // -- // CHECK-LABEL: sil_vtable [serialized] MoreDerived { // CHECK-NEXT: #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override] // vtable thunk for Base.privateMethod1() dispatching to MoreDerived.privateMethod1() // CHECK-NEXT: #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override] // vtable thunk for Base.privateMethod2(_:) dispatching to MoreDerived.privateMethod2(_:) // CHECK-NEXT: #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override] // vtable thunk for Base.privateMethod3(_:) dispatching to MoreDerived.privateMethod3(_:) // CHECK-NEXT: #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to MoreDerived.privateMethod4(_:) // CHECK-NEXT: #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile11MoreDerivedCACycfC [override] // MoreDerived.__allocating_init() // CHECK-NEXT: #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyFAA0D0CADyyFTV [override] // vtable thunk for Derived.privateMethod1() dispatching to MoreDerived.privateMethod1() // CHECK-NEXT: #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV [override] // vtable thunk for Derived.privateMethod2(_:) dispatching to MoreDerived.privateMethod2(_:) // CHECK-NEXT: #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV [override] // vtable thunk for Derived.privateMethod3(_:) dispatching to MoreDerived.privateMethod3(_:) // CHECK-NEXT: #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiFAA0D0CADyySiFTV [override] // vtable thunk for Derived.privateMethod4(_:) dispatching to MoreDerived.privateMethod4(_:) // CHECK-NEXT: #MoreDerived.privateMethod1!1: (MoreDerived) -> () -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod1yyF // MoreDerived.privateMethod1() // CHECK-NEXT: #MoreDerived.privateMethod2!1: (MoreDerived) -> (AnyObject?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod2yyyXlSgF // MoreDerived.privateMethod2(_:) // CHECK-NEXT: #MoreDerived.privateMethod3!1: (MoreDerived) -> (Int?) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod3yySiSgF // MoreDerived.privateMethod3(_:) // CHECK-NEXT: #MoreDerived.privateMethod4!1: (MoreDerived) -> (Int) -> () : @$s17vtables_multifile11MoreDerivedC14privateMethod4yySiF // MoreDerived.privateMethod4(_:) // CHECK-NEXT: #MoreDerived.deinit!deallocator.1: @$s17vtables_multifile11MoreDerivedCfD // MoreDerived.__deallocating_deinit // CHECK-NEXT: } // -- // MostDerived just makes public methods open, which does not require thunking. // -- // CHECK-LABEL: sil_vtable [serialized] MostDerived { // CHECK-NEXT: #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [override] // vtable thunk for Base.privateMethod1() dispatching to MostDerived.privateMethod1() // CHECK-NEXT: #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [override] // vtable thunk for Base.privateMethod2(_:) dispatching to MostDerived.privateMethod2(_:) // CHECK-NEXT: #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override] // vtable thunk for Base.privateMethod3(_:) dispatching to MostDerived.privateMethod3(_:) // CHECK-NEXT: #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to MostDerived.privateMethod4(_:) // CHECK-NEXT: #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile11MostDerivedCACycfC [override] // MostDerived.__allocating_init() // CHECK-NEXT: #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyFAA0D0CADyyFTV [override] // vtable thunk for Derived.privateMethod1() dispatching to MostDerived.privateMethod1() // CHECK-NEXT: #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgFAA0D0CADyyAEFTV [override] // vtable thunk for Derived.privateMethod2(_:) dispatching to MostDerived.privateMethod2(_:) // CHECK-NEXT: #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgFAA0D0CADyyAEFTV [override] // vtable thunk for Derived.privateMethod3(_:) dispatching to MostDerived.privateMethod3(_:) // CHECK-NEXT: #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiFAA0D0CADyySiFTV [override] // vtable thunk for Derived.privateMethod4(_:) dispatching to MostDerived.privateMethod4(_:) // CHECK-NEXT: #MoreDerived.privateMethod1!1: (MoreDerived) -> () -> () : @$s17vtables_multifile11MostDerivedC14privateMethod1yyF [override] // MostDerived.privateMethod1() // CHECK-NEXT: #MoreDerived.privateMethod2!1: (MoreDerived) -> (AnyObject?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod2yyyXlSgF [override] // MostDerived.privateMethod2(_:) // CHECK-NEXT: #MoreDerived.privateMethod3!1: (MoreDerived) -> (Int?) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod3yySiSgF [override] // MostDerived.privateMethod3(_:) // CHECK-NEXT: #MoreDerived.privateMethod4!1: (MoreDerived) -> (Int) -> () : @$s17vtables_multifile11MostDerivedC14privateMethod4yySiF [override] // MostDerived.privateMethod4(_:) // CHECK-NEXT: #MostDerived.deinit!deallocator.1: @$s17vtables_multifile11MostDerivedCfD // MostDerived.__deallocating_deinit // CHECK-NEXT: } // -- // FinalDerived adds a final override; make sure we handle this correctly. // -- // CHECK-LABEL: sil_vtable [serialized] FinalDerived { // CHECK-NEXT: #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod1yyF [override] // FinalDerived.privateMethod1() // CHECK-NEXT: #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod2yyyXlSgF [override] // FinalDerived.privateMethod2(_:) // CHECK-NEXT: #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [override] // vtable thunk for Base.privateMethod3(_:) dispatching to FinalDerived.privateMethod3(_:) // CHECK-NEXT: #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile12FinalDerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [override] // vtable thunk for Base.privateMethod4(_:) dispatching to FinalDerived.privateMethod4(_:) // CHECK-NEXT: #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile12FinalDerivedCACycfC [override] // FinalDerived.__allocating_init() // CHECK-NEXT: #FinalDerived.deinit!deallocator.1: @$s17vtables_multifile12FinalDerivedCfD // FinalDerived.__deallocating_deinit // CHECK-NEXT: }
apache-2.0
81178a7a9539ef53e84e152f336bb2fb
86.619608
297
0.708813
3.563477
false
false
false
false
BlakeBarrett/wndw
wtrmrkr/VideoPreviewPlayerViewController.swift
1
804
// // VideoPreviewPlayerViewController.swift // wndw // // Created by Blake Barrett on 6/9/16. // Copyright © 2016 Blake Barrett. All rights reserved. // import Foundation import AVFoundation import AVKit class VideoPreviewPlayerViewController: UIViewController { var url :NSURL? var player :AVPlayer? override func viewDidLoad() { guard let url = url else { return } self.player = AVPlayer(URL: url) let playerController = AVPlayerViewController() playerController.player = player self.addChildViewController(playerController) self.view.addSubview(playerController.view) playerController.view.frame = self.view.frame } override func viewDidAppear(animated: Bool) { player?.play() } }
mit
a861c998456acf8b0deb190927b99756
24.09375
58
0.673724
4.614943
false
false
false
false
aquarchitect/MyKit
Sources/iOS/Frameworks/CollectionLayout/Parapoloid/ParaboloidFlowLayout.swift
1
1424
// // ParaboloidFlowLayout.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // import UIKit open class ParaboloidFlowLayout: SnappingFlowLayout { // MARK: Property open var paraboloidControler: ParaboloidLayoutController? open override class var layoutAttributesClass: AnyClass { return ParaboloidLayoutAttributes.self } // MARK: System Methods open override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { return super.layoutAttributesForElements(in: rect)?.map { if $0.representedElementCategory == .cell { return self.layoutAttributesForItem(at: $0.indexPath) ?? $0 } else { return $0 } } } open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool { return true } open override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? { return (super.layoutAttributesForItem(at: indexPath)?.copy() as? ParaboloidLayoutAttributes).flatMap { guard let contentOffset = self.collectionView?.contentOffset else { return nil } let center = $0.center.convertToCoordinate(of: contentOffset) $0.paraboloidValue = paraboloidControler?.zValue(atPoint: center) return $0 } } }
mit
a3dff7f79109d0a4c4bca0a7c423cd34
29.297872
110
0.668539
5.274074
false
false
false
false
the-blue-alliance/the-blue-alliance-ios
Frameworks/MyTBAKit/Sources/Models/MyTBASubscription.swift
1
2912
import Foundation // https://github.com/the-blue-alliance/the-blue-alliance/blob/364d6da2f3fc464deef5ba580ea37b6cd2816c4a/consts/notification_type.py public enum NotificationType: String, Codable { case upcomingMatch = "upcoming_match" case matchScore = "match_score" case levelStarting = "starting_comp_level" case allianceSelection = "alliance_selection" case awards = "awards_posted" case mediaPosted = "media_posted" case districtPointsUpdated = "district_points_updated" case scheduleUpdated = "schedule_updated" case finalResults = "final_results" case ping = "ping" case broadcast = "broadcast" case matchVideo = "match_video" case eventMatchVideo = "event_match_video" case updateFavorites = "update_favorites" case updateSubscription = "update_subscriptions" case verification = "verification" public func displayString() -> String { switch self { case .upcomingMatch: return "Upcoming Match" case .matchScore: return "Match Score" case .levelStarting: return "Competition Level Starting" case .allianceSelection: return "Alliance Selection" case .awards: return "Awards Posted" case .mediaPosted: return "Media Posted" case .districtPointsUpdated: return "District Points Updated" case .scheduleUpdated: return "Event Schedule Updated" case .finalResults: return "Final Results" case .matchVideo: return "Match Video Added" case .eventMatchVideo: return "Match Video Added" default: return "" // These shouldn't render } } } struct MyTBASubscriptionsResponse: MyTBAResponse, Codable { var subscriptions: [MyTBASubscription]? } public struct MyTBASubscription: MyTBAModel, Equatable, Codable { public init(modelKey: String, modelType: MyTBAModelType, notifications: [NotificationType]) { self.modelKey = modelKey self.modelType = modelType self.notifications = notifications } public static var arrayKey: String { return "subscriptions" } public var modelKey: String public var modelType: MyTBAModelType public var notifications: [NotificationType] public static var fetch: (MyTBA) -> (@escaping ([MyTBAModel]?, Error?) -> Void) -> MyTBAOperation = MyTBA.fetchSubscriptions } extension MyTBA { public func fetchSubscriptions(_ completion: @escaping (_ subscriptions: [MyTBASubscription]?, _ error: Error?) -> Void) -> MyTBAOperation { let method = "\(MyTBASubscription.arrayKey)/list" return callApi(method: method, completion: { (favoritesResponse: MyTBASubscriptionsResponse?, error) in completion(favoritesResponse?.subscriptions, error) }) } }
mit
7d5cff929c95d96221ae02b9c2fafa1a
32.090909
144
0.666896
4.696774
false
false
false
false
witekbobrowski/Stanford-CS193p-Winter-2017
Smashtag/Smashtag/TwitterUser.swift
1
1039
// // TwitterUser.swift // Smashtag // // Created by Witek on 14/07/2017. // Copyright © 2017 Witek Bobrowski. All rights reserved. // import UIKit import CoreData import Twitter class TwitterUser: NSManagedObject { class func findOrCreateTwitterUser(matching twitterInfo: Twitter.User, in context: NSManagedObjectContext) throws -> TwitterUser { let request: NSFetchRequest<TwitterUser> = TwitterUser.fetchRequest() request.predicate = NSPredicate(format: "handle = %@", twitterInfo.screenName) do { let matches = try context.fetch(request) if matches.count > 0 { assert(matches.count == 1, "TwitterUser.findOrCreateTwitterUser -- database inconsistency") return matches[0] } } catch { throw error } let twitterUser = TwitterUser(context: context) twitterUser.handle = twitterInfo.screenName twitterUser.name = twitterInfo.name return twitterUser } }
mit
22ac217d7b4977b5494b56eb5e2699a7
28.657143
134
0.640655
4.827907
false
false
false
false
quran/quran-ios
Sources/Utilities/Extensions/Sequence+Extension.swift
1
1427
// // Sequence+Extension.swift // Quran // // Created by Mohamed Afifi on 2/19/17. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import Foundation public extension Sequence { func flatGroup<U: Hashable>(by key: (Iterator.Element) -> U) -> [U: Iterator.Element] { var categories: [U: Iterator.Element] = [:] for element in self { let key = key(element) categories[key] = element } return categories } } extension Sequence where Iterator.Element: Hashable { public func orderedUnique() -> [Iterator.Element] { var buffer: [Iterator.Element] = [] var added: Set<Iterator.Element> = [] for elem in self { if !added.contains(elem) { buffer.append(elem) added.insert(elem) } } return buffer } }
apache-2.0
9b05a86d3875471074edec44955f3353
30.021739
91
0.634898
4.077143
false
false
false
false
SomeSimpleSolutions/MemorizeItForever
MemorizeItForever/MemorizeItForever/VisualElements/MITextView.swift
1
1000
// // MITextView.swift // MemorizeItForever // // Created by Hadi Zamani on 11/8/16. // Copyright © 2016 SomeSimpleSolutions. All rights reserved. // import UIKit final class MITextView: UITextView, ValidatableProtocol { override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } private func initialize(){ self.translatesAutoresizingMaskIntoConstraints = false self.layer.cornerRadius = 18.0 self.text = " " addBorder() } func applyError(){ self.layer.borderColor = UIColor.red.cgColor self.layer.borderWidth = 3.0 } func clearError(){ addBorder() } private func addBorder(){ self.layer.borderColor = UIColor.lightGray.cgColor self.layer.borderWidth = 1.0 } }
mit
2e0ed74b9561dc5feab576e46fe7282c
23.365854
67
0.630631
4.603687
false
false
false
false
meismyles/SwiftWebVC
SwiftWebVC/SwiftWebVC.swift
1
14962
// // SwiftWebVC.swift // // Created by Myles Ringle on 24/06/2015. // Transcribed from code used in SVWebViewController. // Copyright (c) 2015 Myles Ringle & Sam Vermette. All rights reserved. // import WebKit public protocol SwiftWebVCDelegate: class { func didStartLoading() func didFinishLoading(success: Bool) } public class SwiftWebVC: UIViewController { public weak var delegate: SwiftWebVCDelegate? var storedStatusColor: UIBarStyle? var buttonColor: UIColor? = nil var titleColor: UIColor? = nil var closing: Bool! = false lazy var backBarButtonItem: UIBarButtonItem = { var tempBackBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCBack"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(SwiftWebVC.goBackTapped(_:))) tempBackBarButtonItem.width = 18.0 tempBackBarButtonItem.tintColor = self.buttonColor return tempBackBarButtonItem }() lazy var forwardBarButtonItem: UIBarButtonItem = { var tempForwardBarButtonItem = UIBarButtonItem(image: SwiftWebVC.bundledImage(named: "SwiftWebVCNext"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(SwiftWebVC.goForwardTapped(_:))) tempForwardBarButtonItem.width = 18.0 tempForwardBarButtonItem.tintColor = self.buttonColor return tempForwardBarButtonItem }() lazy var refreshBarButtonItem: UIBarButtonItem = { var tempRefreshBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.refresh, target: self, action: #selector(SwiftWebVC.reloadTapped(_:))) tempRefreshBarButtonItem.tintColor = self.buttonColor return tempRefreshBarButtonItem }() lazy var stopBarButtonItem: UIBarButtonItem = { var tempStopBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.stop, target: self, action: #selector(SwiftWebVC.stopTapped(_:))) tempStopBarButtonItem.tintColor = self.buttonColor return tempStopBarButtonItem }() lazy var actionBarButtonItem: UIBarButtonItem = { var tempActionBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.action, target: self, action: #selector(SwiftWebVC.actionButtonTapped(_:))) tempActionBarButtonItem.tintColor = self.buttonColor return tempActionBarButtonItem }() lazy var webView: WKWebView = { var tempWebView = WKWebView(frame: UIScreen.main.bounds) tempWebView.uiDelegate = self tempWebView.navigationDelegate = self return tempWebView; }() var request: URLRequest! var navBarTitle: UILabel! var sharingEnabled = true //////////////////////////////////////////////// deinit { webView.stopLoading() UIApplication.shared.isNetworkActivityIndicatorVisible = false webView.uiDelegate = nil; webView.navigationDelegate = nil; } public convenience init(urlString: String, sharingEnabled: Bool = true) { var urlString = urlString if !urlString.hasPrefix("https://") && !urlString.hasPrefix("http://") { urlString = "https://"+urlString } self.init(pageURL: URL(string: urlString)!, sharingEnabled: sharingEnabled) } public convenience init(pageURL: URL, sharingEnabled: Bool = true) { self.init(aRequest: URLRequest(url: pageURL), sharingEnabled: sharingEnabled) } public convenience init(aRequest: URLRequest, sharingEnabled: Bool = true) { self.init() self.sharingEnabled = sharingEnabled self.request = aRequest } func loadRequest(_ request: URLRequest) { webView.load(request) } //////////////////////////////////////////////// // View Lifecycle override public func loadView() { view = webView loadRequest(request) } override public func viewDidLoad() { super.viewDidLoad() } override public func viewWillAppear(_ animated: Bool) { assert(self.navigationController != nil, "SVWebViewController needs to be contained in a UINavigationController. If you are presenting SVWebViewController modally, use SVModalWebViewController instead.") updateToolbarItems() navBarTitle = UILabel() navBarTitle.backgroundColor = UIColor.clear if presentingViewController == nil { if let titleAttributes = navigationController!.navigationBar.titleTextAttributes { navBarTitle.textColor = titleAttributes[.foregroundColor] as? UIColor } } else { navBarTitle.textColor = self.titleColor } navBarTitle.shadowOffset = CGSize(width: 0, height: 1); navBarTitle.font = UIFont(name: "HelveticaNeue-Medium", size: 17.0) navBarTitle.textAlignment = .center navigationItem.titleView = navBarTitle; super.viewWillAppear(true) if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) { self.navigationController?.setToolbarHidden(false, animated: false) } else if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) { self.navigationController?.setToolbarHidden(true, animated: true) } } override public func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(true) if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.phone) { self.navigationController?.setToolbarHidden(true, animated: true) } } override public func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(true) UIApplication.shared.isNetworkActivityIndicatorVisible = false } //////////////////////////////////////////////// // Toolbar func updateToolbarItems() { backBarButtonItem.isEnabled = webView.canGoBack forwardBarButtonItem.isEnabled = webView.canGoForward let refreshStopBarButtonItem: UIBarButtonItem = webView.isLoading ? stopBarButtonItem : refreshBarButtonItem let fixedSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.fixedSpace, target: nil, action: nil) let flexibleSpace: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil) if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad) { let toolbarWidth: CGFloat = 250.0 fixedSpace.width = 35.0 let items: NSArray = sharingEnabled ? [fixedSpace, refreshStopBarButtonItem, fixedSpace, backBarButtonItem, fixedSpace, forwardBarButtonItem, fixedSpace, actionBarButtonItem] : [fixedSpace, refreshStopBarButtonItem, fixedSpace, backBarButtonItem, fixedSpace, forwardBarButtonItem] let toolbar: UIToolbar = UIToolbar(frame: CGRect(x: 0.0, y: 0.0, width: toolbarWidth, height: 44.0)) if !closing { toolbar.items = items as? [UIBarButtonItem] if presentingViewController == nil { toolbar.barTintColor = navigationController!.navigationBar.barTintColor } else { toolbar.barStyle = navigationController!.navigationBar.barStyle } toolbar.tintColor = navigationController!.navigationBar.tintColor } navigationItem.rightBarButtonItems = items.reverseObjectEnumerator().allObjects as? [UIBarButtonItem] } else { let items: NSArray = sharingEnabled ? [fixedSpace, backBarButtonItem, flexibleSpace, forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, flexibleSpace, actionBarButtonItem, fixedSpace] : [fixedSpace, backBarButtonItem, flexibleSpace, forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, fixedSpace] if let navigationController = navigationController, !closing { if presentingViewController == nil { navigationController.toolbar.barTintColor = navigationController.navigationBar.barTintColor } else { navigationController.toolbar.barStyle = navigationController.navigationBar.barStyle } navigationController.toolbar.tintColor = navigationController.navigationBar.tintColor toolbarItems = items as? [UIBarButtonItem] } } } //////////////////////////////////////////////// // Target Actions @objc func goBackTapped(_ sender: UIBarButtonItem) { webView.goBack() } @objc func goForwardTapped(_ sender: UIBarButtonItem) { webView.goForward() } @objc func reloadTapped(_ sender: UIBarButtonItem) { webView.reload() } @objc func stopTapped(_ sender: UIBarButtonItem) { webView.stopLoading() updateToolbarItems() } @objc func actionButtonTapped(_ sender: AnyObject) { if let url: URL = ((webView.url != nil) ? webView.url : request.url) { let activities: NSArray = [SwiftWebVCActivitySafari(), SwiftWebVCActivityChrome()] if url.absoluteString.hasPrefix("file:///") { let dc: UIDocumentInteractionController = UIDocumentInteractionController(url: url) dc.presentOptionsMenu(from: view.bounds, in: view, animated: true) } else { let activityController: UIActivityViewController = UIActivityViewController(activityItems: [url], applicationActivities: activities as? [UIActivity]) if floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 && UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { let ctrl: UIPopoverPresentationController = activityController.popoverPresentationController! ctrl.sourceView = view ctrl.barButtonItem = sender as? UIBarButtonItem } present(activityController, animated: true, completion: nil) } } } //////////////////////////////////////////////// @objc func doneButtonTapped() { closing = true UINavigationBar.appearance().barStyle = storedStatusColor! self.dismiss(animated: true, completion: nil) } // MARK: - Class Methods /// Helper function to get image within SwiftWebVCResources bundle /// /// - parameter named: The name of the image in the SwiftWebVCResources bundle class func bundledImage(named: String) -> UIImage? { let image = UIImage(named: named) if image == nil { return UIImage(named: named, in: Bundle(for: SwiftWebVC.classForCoder()), compatibleWith: nil) } // Replace MyBasePodClass with yours return image } } extension SwiftWebVC: WKUIDelegate { // Add any desired WKUIDelegate methods here: https://developer.apple.com/reference/webkit/wkuidelegate } extension SwiftWebVC: WKNavigationDelegate { public func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) { self.delegate?.didStartLoading() UIApplication.shared.isNetworkActivityIndicatorVisible = true updateToolbarItems() } public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { self.delegate?.didFinishLoading(success: true) UIApplication.shared.isNetworkActivityIndicatorVisible = false webView.evaluateJavaScript("document.title", completionHandler: {(response, error) in self.navBarTitle.text = response as! String? self.navBarTitle.sizeToFit() self.updateToolbarItems() }) } public func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) { self.delegate?.didFinishLoading(success: false) UIApplication.shared.isNetworkActivityIndicatorVisible = false updateToolbarItems() } public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) { let url = navigationAction.request.url let hostAddress = navigationAction.request.url?.host if (navigationAction.targetFrame == nil) { if UIApplication.shared.canOpenURL(url!) { UIApplication.shared.openURL(url!) } } // To connnect app store if hostAddress == "itunes.apple.com" { if UIApplication.shared.canOpenURL(navigationAction.request.url!) { UIApplication.shared.openURL(navigationAction.request.url!) decisionHandler(.cancel) return } } let url_elements = url!.absoluteString.components(separatedBy: ":") switch url_elements[0] { case "tel": openCustomApp(urlScheme: "telprompt://", additional_info: url_elements[1]) decisionHandler(.cancel) case "sms": openCustomApp(urlScheme: "sms://", additional_info: url_elements[1]) decisionHandler(.cancel) case "mailto": openCustomApp(urlScheme: "mailto://", additional_info: url_elements[1]) decisionHandler(.cancel) default: //print("Default") break } decisionHandler(.allow) } func openCustomApp(urlScheme: String, additional_info:String){ if let requestUrl: URL = URL(string:"\(urlScheme)"+"\(additional_info)") { let application:UIApplication = UIApplication.shared if application.canOpenURL(requestUrl) { application.openURL(requestUrl) } } } }
mit
a51ca4bbc2572ce1376f609910992801
39.547425
331
0.61068
6.213455
false
false
false
false
Donkey-Tao/SinaWeibo
SinaWeibo/SinaWeibo/Classes/Main/Visitor/TFVisitorView.swift
1
1546
// // TFVisitorView.swift // SinaWeibo // // Created by Donkey-Tao on 2016/9/27. // Copyright © 2016年 http://taofei.me All rights reserved. // import UIKit class TFVisitorView: UIView { //MARK:- 控件的属性 @IBOutlet weak var rotationView: UIImageView! @IBOutlet weak var iconView: UIImageView! @IBOutlet weak var tipsLabel: UILabel! @IBOutlet weak var loginBtn: UIButton! @IBOutlet weak var registerBtn: UIButton! //MARK:- 自定义函数 ///设置访客视图 func setupVisitorViewInfo(iconName : String ,tip :String){ iconView.image = UIImage(named: iconName) tipsLabel.text = tip rotationView.isHidden = true } ///添加rotationView的动画 func addRotationViewAnimation(){ //1.创建动画:CABasicAnimation或者CAKeyframeAnimation来实现 let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z") //2.设置动画的属性 rotationAnimation.fromValue = 0 rotationAnimation.toValue = M_PI * 2 rotationAnimation.repeatCount = MAXFLOAT rotationAnimation.duration = 5 rotationAnimation.isRemovedOnCompletion = false //3.将动画添加到layer中 rotationView.layer.add(rotationAnimation, forKey: nil) } //MARK:- 提供快速通过Xib创建的类方法 class func TFVisitorView() -> TFVisitorView { return Bundle.main.loadNibNamed("TFVisitorView", owner: nil, options: nil)?.first as! TFVisitorView } }
mit
11b6230ffdf9b40303428314c75fbf96
26.519231
107
0.667365
4.571885
false
false
false
false
xedin/swift
test/Sema/enum_raw_representable.swift
7
6632
// RUN: %target-typecheck-verify-swift enum Foo : Int { case a, b, c } var raw1: Int = Foo.a.rawValue var raw2: Foo.RawValue = raw1 var cooked1: Foo? = Foo(rawValue: 0) var cooked2: Foo? = Foo(rawValue: 22) enum Bar : Double { case a, b, c } func localEnum() -> Int { enum LocalEnum : Int { case a, b, c } return LocalEnum.a.rawValue } enum MembersReferenceRawType : Int { case a, b, c init?(rawValue: Int) { self = MembersReferenceRawType(rawValue: rawValue)! } func successor() -> MembersReferenceRawType { return MembersReferenceRawType(rawValue: rawValue + 1)! } } func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] { return values.map { $0.rawValue } } func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] { return serialized.map { T(rawValue: $0)! } } var ints: [Int] = serialize([Foo.a, .b, .c]) var doubles: [Double] = serialize([Bar.a, .b, .c]) var foos: [Foo] = deserialize([1, 2, 3]) var bars: [Bar] = deserialize([1.2, 3.4, 5.6]) // Infer RawValue from witnesses. enum Color : Int { case red case blue init?(rawValue: Double) { return nil } var rawValue: Double { return 1.0 } } var colorRaw: Color.RawValue = 7.5 // Mismatched case types enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}} case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}} } // Recursive diagnostics issue in tryRawRepresentableFixIts() class Outer { // The setup is that we have to trigger the conformance check // while diagnosing the conversion here. For the purposes of // the test I'm putting everything inside a class in the right // order, but the problem can trigger with a multi-file // scenario too. let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}} enum E : Array<Int> { // expected-error {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}} case a } } // rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals func rdar32431736() { enum E : String { case A = "A" case B = "B" } let items1: [String] = ["A", "a"] let items2: [String]? = ["A"] let myE1: E = items1.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}} let myE2: E = items2?.first // expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}} // expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}} } // rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch enum E_32431165 : String { case foo = "foo" case bar = "bar" // expected-note {{'bar' declared here}} } func rdar32431165_1(_: E_32431165) {} func rdar32431165_1(_: Int) {} func rdar32431165_1(_: Int, _: E_32431165) {} rdar32431165_1(E_32431165.baz) // expected-error@-1 {{type 'E_32431165' has no member 'baz'; did you mean 'bar'?}} rdar32431165_1(.baz) // expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}} rdar32431165_1("") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{16-16=E_32431165(rawValue: }} {{18-18=)}} rdar32431165_1(42, "") // expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}} func rdar32431165_2(_: String) {} func rdar32431165_2(_: Int) {} func rdar32431165_2(_: Int, _: String) {} rdar32431165_2(E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{16-16=}} {{30-30=.rawValue}} rdar32431165_2(42, E_32431165.bar) // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}} E_32431165.bar == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}} "bar" == E_32431165.bar // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}} func rdar32432253(_ condition: Bool = false) { let choice: E_32431165 = condition ? .foo : .bar let _ = choice == "bar" // expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}} } func sr8150_helper1(_: Int) {} func sr8150_helper1(_: Double) {} func sr8150_helper2(_: Double) {} func sr8150_helper2(_: Int) {} func sr8150_helper3(_: Foo) {} func sr8150_helper3(_: Bar) {} func sr8150_helper4(_: Bar) {} func sr8150_helper4(_: Foo) {} func sr8150(bar: Bar) { sr8150_helper1(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} sr8150_helper2(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} sr8150_helper3(0.0) // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}} sr8150_helper4(0.0) // expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}} } class SR8150Box { var bar: Bar init(bar: Bar) { self.bar = bar } } // Bonus problem with mutable values being passed. func sr8150_mutable(obj: SR8150Box) { sr8150_helper1(obj.bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{25-25=.rawValue}} var bar = obj.bar sr8150_helper1(bar) // expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}} } struct NotEquatable { } enum ArrayOfNewEquatable : Array<NotEquatable> { } // expected-error@-1{{raw type 'Array<NotEquatable>' is not expressible by a string, integer, or floating-point literal}} // expected-error@-2{{'ArrayOfNewEquatable' declares raw type 'Array<NotEquatable>', but does not conform to RawRepresentable and conformance could not be synthesized}} // expected-error@-3{{RawRepresentable conformance cannot be synthesized because raw type 'Array<NotEquatable>' is not Equatable}}
apache-2.0
dfa293be317497b7d7431ab672e6e86f
33.905263
168
0.674759
3.409769
false
false
false
false
zhiquan911/chance_btc_wallet
chance_btc_wallet/chance_btc_wallet/extension/UILabel+extension.swift
1
1111
// // UILabel+extension.swift // Chance_wallet // // Created by Chance on 15/12/6. // Copyright © 2015年 Chance. All rights reserved. // import Foundation extension UILabel { public func setDecimalStr( _ number: String, color: UIColor? ) { self.text = number if number.range(of: ".") != nil && color != nil { let colorDict = [NSAttributedStringKey.foregroundColor: color!] let re_range = number.range(of: ".")! let index: Int = number.distance(from: number.startIndex, to: re_range.lowerBound) let last = number.length let length = last - index let newRange = NSMakeRange(index, length) let attributedStr = NSMutableAttributedString(string: number) if newRange.location + newRange.length <= attributedStr.length { attributedStr.addAttributes(colorDict, range: newRange) } self.attributedText = attributedStr; } } }
mit
80f29201cd0ce66afa98853ff8224d1a
31.588235
98
0.545126
4.946429
false
false
false
false
wikimedia/wikipedia-ios
Wikipedia/Code/AbuseFilterAlertView.swift
1
3668
enum AbuseFilterAlertType { case warning case disallow func image() -> UIImage? { switch self { case .warning: return #imageLiteral(resourceName: "abuse-filter-flag") case .disallow: return #imageLiteral(resourceName: "abuse-filter-alert") } } } class AbuseFilterAlertView: UIView, Themeable { @IBOutlet private var iconImageView: UIImageView! @IBOutlet private var titleLabel: UILabel! @IBOutlet private var subtitleLabel: UILabel! @IBOutlet private var detailsLabel1: UILabel! @IBOutlet private var detailsLabel2: UILabel! @IBOutlet private var detailsLabel3: UILabel! @IBOutlet private var detailsLabel4: UILabel! @IBOutlet private var detailsLabel5: UILabel! public var theme: Theme = .standard public var type: AbuseFilterAlertType = .disallow { didSet { iconImageView.image = type.image() configureLabels(for: type) } } private func configureLabels(for type: AbuseFilterAlertType) { switch type { case .disallow: titleLabel.text = WMFLocalizedString("abuse-filter-disallow-heading", value: "You cannot publish this edit", comment: "Header text for disallowed edit warning.") subtitleLabel.text = nil detailsLabel1.text = WMFLocalizedString("abuse-filter-disallow-unconstructive", value: "An automated filter has identified this edit as potentially unconstructive or as a vandalism attempt. Please go back and change your edit.", comment: "Label text for unconstructive edit description") detailsLabel2.text = nil detailsLabel3.text = nil detailsLabel4.text = nil detailsLabel5.text = nil case .warning: titleLabel.text = WMFLocalizedString("abuse-filter-warning-heading", value: "This looks like an unconstructive edit, are you sure you want to publish it?", comment: "Header text for unconstructive edit warning") subtitleLabel.text = WMFLocalizedString("abuse-filter-warning-subheading", value: "Your edit may contain:", comment: "Subheading text for potentially unconstructive edit warning") detailsLabel1.text = WMFLocalizedString("abuse-filter-warning-caps", value: "All caps text", comment: "Label text for typing in all capitals") detailsLabel2.text = WMFLocalizedString("abuse-filter-warning-blanking", value: "Deleting sections or full articles", comment: "Label text for blanking sections or articles") detailsLabel3.text = WMFLocalizedString("abuse-filter-warning-spam", value: "Adding spam to articles", comment: "Label text for adding spam to articles") detailsLabel4.text = WMFLocalizedString("abuse-filter-warning-irrelevant", value: "Irrelevant external links or images", comment: "Label text for irrelevant external links and images") detailsLabel5.text = WMFLocalizedString("abuse-filter-warning-repeat", value: "Repeating characters", comment: "Label text for repeating characters") } } func apply(theme: Theme) { self.theme = theme backgroundColor = theme.colors.paperBackground titleLabel.textColor = (type == .disallow) ? theme.colors.error : theme.colors.warning subtitleLabel.textColor = theme.colors.secondaryText detailsLabel1.textColor = theme.colors.secondaryText detailsLabel2.textColor = theme.colors.secondaryText detailsLabel3.textColor = theme.colors.secondaryText detailsLabel4.textColor = theme.colors.secondaryText detailsLabel5.textColor = theme.colors.secondaryText } }
mit
8309185dfcd5004ecf58e609f57cbd7b
54.575758
299
0.702835
4.990476
false
false
false
false
fgengine/quickly
Quickly/ViewControllers/Hamburger/Animation/QHamburgerViewControllerInteractiveAnimation.swift
1
10450
// // Quickly // public final class QHamburgerViewControllerInteractiveAnimation : IQHamburgerViewControllerInteractiveAnimation { public var contentView: UIView! public var currentState: QHamburgerViewControllerState public var targetState: QHamburgerViewControllerState public var contentViewController: IQHamburgerViewController! public var contentShadow: QViewShadow public var contentBeginFrame: CGRect! public var contentEndFrame: CGRect! public var leftSize: CGFloat public var leftViewController: IQHamburgerViewController? public var leftBeginFrame: CGRect! public var leftEndFrame: CGRect! public var rightSize: CGFloat public var rightViewController: IQHamburgerViewController? public var rightBeginFrame: CGRect! public var rightEndFrame: CGRect! public var position: CGPoint public var deltaPosition: CGFloat public var velocity: CGPoint public var acceleration: CGFloat public var finishDistanceRate: CGFloat public var ease: IQAnimationEase public var canFinish: Bool public init( contentShadow: QViewShadow = QViewShadow(color: UIColor.black, opacity: 0.45, radius: 6, offset: CGSize.zero), leftSize: CGFloat = UIScreen.main.bounds.width * 0.6, rightSize: CGFloat = UIScreen.main.bounds.width * 0.6, acceleration: CGFloat = 1200, finishDistanceRate: CGFloat = 0.4, ease: IQAnimationEase = QAnimationEaseQuadraticOut() ) { self.currentState = .idle self.targetState = .idle self.contentShadow = contentShadow self.leftSize = leftSize self.rightSize = rightSize self.position = CGPoint.zero self.deltaPosition = 0 self.velocity = CGPoint.zero self.acceleration = acceleration self.finishDistanceRate = finishDistanceRate self.ease = ease self.canFinish = false } public func prepare( contentView: UIView, currentState: QHamburgerViewControllerState, targetState: QHamburgerViewControllerState, contentViewController: IQHamburgerViewController, leftViewController: IQHamburgerViewController?, rightViewController: IQHamburgerViewController?, position: CGPoint, velocity: CGPoint ) { self.contentView = contentView self.currentState = currentState self.targetState = targetState self.contentViewController = contentViewController self.contentBeginFrame = self._contentFrame(contentView: contentView, state: currentState) self.contentEndFrame = self._contentFrame(contentView: contentView, state: targetState) self.leftViewController = leftViewController self.leftBeginFrame = self._leftFrame(contentView: contentView, state: currentState) self.leftEndFrame = self._leftFrame(contentView: contentView, state: targetState) self.rightViewController = rightViewController self.rightBeginFrame = self._rightFrame(contentView: contentView, state: currentState) self.rightEndFrame = self._rightFrame(contentView: contentView, state: targetState) self.position = position self.velocity = velocity self.contentView.bringSubviewToFront(self.contentViewController.view) self.contentViewController.view.frame = self.contentBeginFrame self.contentViewController.view.shadow = self.contentShadow if let vc = self.leftViewController { vc.view.frame = self.leftBeginFrame if currentState == .left { vc.prepareInteractiveDismiss() } if targetState == .left { vc.prepareInteractivePresent() } } if let vc = self.rightViewController { vc.view.frame = self.rightBeginFrame if currentState == .right { vc.prepareInteractiveDismiss() } if targetState == .right { vc.prepareInteractivePresent() } } } public func update(position: CGPoint, velocity: CGPoint) { var delta: CGFloat = position.x - self.position.x switch self.currentState { case .idle: switch self.targetState { case .idle, .left: break case .right: delta = -delta } case .left: switch self.targetState { case .idle, .right: delta = -delta case .left: break } case .right: break } let distance = self._distance() self.deltaPosition = self.ease.lerp(max(0, min(delta, distance)), from: 0, to: distance) let progress = self.deltaPosition / distance self.contentViewController.view.frame = self.contentBeginFrame.lerp(self.contentEndFrame, progress: progress) self.leftViewController?.view.frame = self.leftBeginFrame.lerp(self.leftEndFrame, progress: progress) self.rightViewController?.view.frame = self.rightBeginFrame.lerp(self.rightEndFrame, progress: progress) self.canFinish = self.deltaPosition > (distance * self.finishDistanceRate) } public func finish(_ complete: @escaping (_ state: QHamburgerViewControllerState) -> Void) { let distance = self._distance() let duration = TimeInterval((distance - self.deltaPosition) / self.acceleration) UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: { self.contentViewController.view.frame = self.contentEndFrame self.leftViewController?.view.frame = self.leftEndFrame self.rightViewController?.view.frame = self.rightEndFrame }, completion: { [weak self] (completed: Bool) in guard let self = self else { return } self.contentViewController.view.frame = self.contentEndFrame self.contentViewController.view.shadow = self.targetState != .idle ? self.contentShadow : nil self.contentViewController = nil if let vc = self.leftViewController { vc.view.frame = self.leftEndFrame if self.currentState == .left { vc.finishInteractiveDismiss() } if self.targetState == .left { vc.finishInteractivePresent() } self.leftViewController = nil } if let vc = self.rightViewController { vc.view.frame = self.rightEndFrame if self.currentState == .left { vc.finishInteractiveDismiss() } if self.targetState == .left { vc.finishInteractivePresent() } self.rightViewController = nil } complete(self.targetState) }) } public func cancel(_ complete: @escaping (_ state: QHamburgerViewControllerState) -> Void) { let duration = TimeInterval(self.deltaPosition / self.acceleration) UIView.animate(withDuration: duration, delay: 0, options: [ .beginFromCurrentState, .layoutSubviews ], animations: { self.contentViewController.view.frame = self.contentBeginFrame self.leftViewController?.view.frame = self.leftBeginFrame self.rightViewController?.view.frame = self.rightBeginFrame }, completion: { [weak self] (completed: Bool) in guard let self = self else { return } self.contentViewController.view.frame = self.contentBeginFrame self.contentViewController.view.shadow = self.currentState != .idle ? self.contentShadow : nil self.contentViewController = nil if let vc = self.leftViewController { vc.view.frame = self.leftBeginFrame if self.currentState == .left { vc.cancelInteractiveDismiss() } if self.targetState == .left { vc.cancelInteractivePresent() } self.leftViewController = nil } if let vc = self.rightViewController { vc.view.frame = self.rightBeginFrame if self.currentState == .left { vc.cancelInteractiveDismiss() } if self.targetState == .left { vc.cancelInteractivePresent() } self.rightViewController = nil } complete(self.currentState) }) } } // MARK: Private private extension QHamburgerViewControllerInteractiveAnimation { func _distance() -> CGFloat { switch self.currentState { case .idle: switch self.targetState { case .idle: return 0 case .left: return self.leftSize case .right: return self.rightSize } case .left: switch self.targetState { case .idle: return self.leftSize case .left: return 0 case .right: return self.leftSize + self.rightSize } case .right: switch self.targetState { case .idle: return self.rightSize case .left: return self.leftSize + self.rightSize case .right: return 0 } } } func _contentFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect { let bounds = contentView.bounds switch state { case .idle: return bounds case .left: return CGRect(x: bounds.origin.x + self.leftSize, y: bounds.origin.y, width: bounds.width, height: bounds.height) case .right: return CGRect(x: bounds.origin.x - self.rightSize, y: bounds.origin.y, width: bounds.width, height: bounds.height) } } func _leftFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect { let bounds = contentView.bounds switch state { case .idle, .right: return CGRect(x: bounds.origin.x - self.leftSize, y: bounds.origin.y, width: self.leftSize, height: bounds.height) case .left: return CGRect(x: bounds.origin.x, y: bounds.origin.y, width: self.leftSize, height: bounds.height) } } func _rightFrame(contentView: UIView, state: QHamburgerViewControllerState) -> CGRect { let bounds = contentView.bounds switch state { case .idle, .left: return CGRect(x: bounds.origin.x + bounds.width, y: bounds.origin.y, width: self.rightSize, height: bounds.height) case .right: return CGRect(x: (bounds.origin.x + bounds.width) - self.rightSize, y: bounds.origin.y, width: self.rightSize, height: bounds.height) } } }
mit
b56a83d3d365f235d196ae3550f3f57c
45.444444
154
0.653301
5.130093
false
false
false
false
KoCMoHaBTa/MHMessageKit
MHMessageKit/Message/Implementation/NotificationCenter+MessageSubscriber.swift
1
2630
// // NSNotificationCenter+MessageSubscriber.swift // MHMessageKit // // Created by Milen Halachev on 1/15/16. // Copyright © 2016 Milen Halachev. All rights reserved. // import Foundation extension NotificationCenter: MessageSubscriber { public func subscribe<M>(_ handler: @escaping (_ message: M) -> Void) -> MessageSubscription where M: Message { guard let messageType = M.self as? NotificationMessage.Type else { NSException(name: NSExceptionName.internalInconsistencyException, reason: "Only messages that also conform to NotificationMessage are supported", userInfo: nil).raise() return NotificationMessageSubscription(observer: "" as NSObjectProtocol) } let observer = self.addObserver(messageType: messageType, handler: { (message) -> Void in if let message = message as? M { handler(message) return } NSLog("Unhandled message \(messageType.notificationName()) - \(message)") }) return NotificationMessageSubscription(observer: observer) } public func subscribe<M>(_ handler: @escaping (_ message: M) -> Void) -> WeakMessageSubscription where M: Message { guard let messageType = M.self as? NotificationMessage.Type else { NSException(name: NSExceptionName.internalInconsistencyException, reason: "Only messages that also conform to NotificationMessage are supported", userInfo: nil).raise() return NotificationWeakMessageSubscription(observer: "" as NSObjectProtocol) } let observer = self.addWeakObserver(messageType: messageType, handler: { (message) -> Void in if let message = message as? M { handler(message) return } NSLog("Unhandled message \(messageType.notificationName()) - \(message)") }) return NotificationWeakMessageSubscription(observer: observer) } public func unsubscribe(from subscription: MessageSubscription) { guard let subscription = subscription as? NotificationMessageSubscription else { NSException(name: NSExceptionName.invalidArgumentException, reason: "Only subscriptions created by NotificationCenter are supported", userInfo: nil).raise() return } self.removeObserver(subscription.observer) } }
mit
665bdff9291b834ea8a4511af91f551c
35.013699
180
0.613541
5.975
false
false
false
false
Josscii/iOS-Demos
UIButtonDemo/UIButtonDemo/ViewController.swift
1
1528
// // ViewController.swift // UIButtonDemo // // Created by josscii on 2017/9/27. // Copyright © 2017年 josscii. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let button = UIButton() button.backgroundColor = .green button.translatesAutoresizingMaskIntoConstraints = false button.setTitle("哈哈", for: .normal) button.setTitleColor(.black, for: .normal) button.setImage(#imageLiteral(resourceName: "love"), for: .normal) button.contentVerticalAlignment = .top button.contentHorizontalAlignment = .left // button.contentEdgeInsets.right = 30 // button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 30, bottom: 30, right: 0) // button.titleEdgeInsets = UIEdgeInsets(top: 30, left: 0, bottom: 0, right: 25) view.addSubview(button) button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true button.heightAnchor.constraint(equalToConstant: 100).isActive = true button.widthAnchor.constraint(equalToConstant: 100).isActive = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
38b26703e89fa88e34a5da1ce5afb4bb
32.065217
87
0.669954
4.843949
false
false
false
false
mownier/photostream
Photostream/UI/Post Discovery/PostDiscoveryViewDelegate.swift
1
4511
// // PostDiscoveryViewDelegate.swift // Photostream // // Created by Mounir Ybanez on 20/12/2016. // Copyright © 2016 Mounir Ybanez. All rights reserved. // import UIKit extension PostDiscoveryViewController { override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { presenter.initialPostWillShow() var condition: Bool = false switch sceneType { case .grid: condition = indexPath.row == presenter.postCount - 10 case .list: condition = indexPath.section == presenter.postCount - 10 } guard condition else { return } presenter.loadMorePosts() } override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { switch sceneType { case .grid: presenter.presentPostDiscoveryAsList(with: indexPath.row) default: break } } } extension PostDiscoveryViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { switch sceneType { case .grid: return gridLayout.itemSize case .list: let item = presenter.post(at: indexPath.section) as? PostListCollectionCellItem prototype.configure(with: item, isPrototype: true) let size = CGSize(width: listLayout.itemSize.width, height: prototype.dynamicHeight) return size } } } extension PostDiscoveryViewController: PostListCollectionCellDelegate { func didTapPhoto(cell: PostListCollectionCell) { guard let index = collectionView![cell]?.section else { return } presenter.likePost(at: index) } func didTapHeart(cell: PostListCollectionCell) { guard let index = collectionView![cell]?.section, let post = presenter.post(at: index) else { return } cell.toggleHeart(liked: post.isLiked) { [unowned self] in self.presenter.toggleLike(at: index) } } func didTapComment(cell: PostListCollectionCell) { guard let index = collectionView![cell]?.section else { return } presenter.presentCommentController(at: index, shouldComment: true) } func didTapCommentCount(cell: PostListCollectionCell) { guard let index = collectionView![cell]?.section else { return } presenter.presentCommentController(at: index) } func didTapLikeCount(cell: PostListCollectionCell) { guard let index = collectionView![cell]?.section else { return } presenter.presentPostLikes(at: index) } } extension PostDiscoveryViewController: PostListCollectionHeaderDelegate { func didTapDisplayName(header: PostListCollectionHeader, point: CGPoint) { willPresentUserTimeline(header: header, point: point) } func didTapAvatar(header: PostListCollectionHeader, point: CGPoint) { willPresentUserTimeline(header: header, point: point) } private func willPresentUserTimeline(header: PostListCollectionHeader, point: CGPoint) { var relativePoint = collectionView!.convert(point, from: header) relativePoint.y += header.frame.height guard let indexPath = collectionView!.indexPathForItem(at: relativePoint) else { return } presenter.presentUserTimeline(at: indexPath.section) } } extension PostDiscoveryViewController { override func scrollViewDidScroll(_ scrollView: UIScrollView) { if scrollHandler.isScrollable { if scrollHandler.isScrollingUp { scrollEventListener?.didScrollUp( with: scrollHandler.offsetDelta, offsetY: scrollHandler.currentOffsetY ) } else if scrollHandler.isScrollingDown { scrollEventListener?.didScrollDown( with: scrollHandler.offsetDelta, offsetY: scrollHandler.currentOffsetY) } scrollHandler.update() } } }
mit
a7bcee142ac8ae23b7de80ae96d36a63
30.319444
160
0.626829
5.796915
false
false
false
false
GocePetrovski/ListCollectionViewKit
ListCollectionViewKit/ListCollectionViewLayoutAttributes.swift
1
1636
// // ListCollectionViewLayoutAttributes.swift // ListCollectionView // // Created by Goce Petrovski on 27/01/2015. // Copyright (c) 2015 Pomarium. All rights reserved. // http://pomarium.com.au import UIKit open class ListCollectionViewLayoutAttributes: UICollectionViewLayoutAttributes { open var editing:Bool = false open var shouldIndentWhileEditing:Bool = true open var editingStyle:ListCollectionViewCellEditingStyle = .delete // MARK: NSCopying override open func copy(with zone: NSZone? = nil) -> Any { let attributes = super.copy(with: zone) as! ListCollectionViewLayoutAttributes attributes.editing = editing attributes.shouldIndentWhileEditing = shouldIndentWhileEditing attributes.editingStyle = editingStyle return attributes } // MARK: Equality override open func isEqual(_ object: Any?) -> Bool { if object == nil { return false } if let attributes = object as? ListCollectionViewLayoutAttributes { if super.isEqual(attributes) == false { return false } if editing != attributes.editing { return false } if shouldIndentWhileEditing != attributes.shouldIndentWhileEditing { return false } if editingStyle != attributes.editingStyle { return false } return true } return super.isEqual(object) } }
mit
cabd8b1c0a480b1b449b493d5f0654bc
26.728814
86
0.586186
5.970803
false
false
false
false
sadawi/MagneticFields
Pod/Classes/Observation.swift
1
2068
// // Observation.swift // Pods // // Created by Sam Williams on 11/28/15. // // import Foundation /** An object that holds a closure that is to be run when a value changes. `Observation` instances are themselves `Observable`, which means they can be chained: ``` let a = Field<String>() let b = Field<String>() let c = Field<String>() a --> b --> c ``` */ public class Observation<T>: Observable { public typealias ValueType = T public var observations = ObservationRegistry<T>() public var value:T? { get { return self.getValue?() } set { self.onChange?(newValue) self.notifyObservers() } } var onChange:(T? -> Void)? var getValue:(Void -> T?)? public func valueChanged(newValue:T?) { self.value = newValue } } /** A mapping of owner objects to Observations. Owner references are weak. Observation references are strong. */ public class ObservationRegistry<V> { var observations:NSMapTable = NSMapTable.weakToStrongObjectsMapTable() public init() { } func clear() { self.observations.removeAllObjects() } func each(closure:(Observation<V> -> Void)) { let enumerator = self.observations.objectEnumerator() while let observation = enumerator?.nextObject() { if let observation = observation as? Observation<V> { closure(observation) } } } func get<U:Observer where U.ValueType==V>(observer:U?) -> Observation<V>? { return self.observations.objectForKey(observer) as? Observation<V> } func setNil(observation:Observation<V>?) { self.observations.setObject(observation, forKey: DefaultObserverKey) } func set(owner:AnyObject, _ observation:Observation<V>?) { self.observations.setObject(observation, forKey: owner) } func remove<U:Observer where U.ValueType==V>(observer:U) { self.observations.removeObjectForKey(observer) } }
mit
a6c3b6da49146a0b8be66bcddf31e011
23.619048
108
0.617988
4.390658
false
false
false
false
seandavidmcgee/HumanKontactBeta
src/keyboardTest/ActivityKeys.swift
1
600
// // ActivityKeys.swift // keyboardTest // // Created by Sean McGee on 7/22/15. // Copyright (c) 2015 3 Callistos Services. All rights reserved. // import Foundation struct ActivityKeys { static let ChooseCall = "com.humankontact.keyboardtest.ChooseCall" static let ChooseText = "com.humankontact.keyboardtest.ChooseText" static let ChooseEmail = "com.humankontact.keyboardtest.ChooseEmail" static let ChoosePerson = "com.humankontact.keyboardtest.ChoosePerson" let ActivityItemsKey = "keyboardtest.items.key" let ActivityItemKey = "keyboardtest.item.key" }
mit
f442f2496c6794708476b93f47cbbba2
29
74
0.738333
3.797468
false
true
false
false
bitjammer/swift
test/decl/protocol/conforms/fixit_stub_editor.swift
8
1027
// RUN: %target-typecheck-verify-swift -diagnostics-editor-mode protocol P1 { func foo1() func foo2() } protocol P2 { func bar1() func bar2() } class C1 : P1, P2 {} // expected-error{{type 'C1' does not conform to protocol 'P1'}} expected-error{{type 'C1' does not conform to protocol 'P2'}} expected-note{{do you want to add protocol stubs?}}{{20-20=\n func foo1() {\n <#code#>\n \}\n\n func foo2() {\n <#code#>\n \}\n\n func bar1() {\n <#code#>\n \}\n\n func bar2() {\n <#code#>\n \}\n}} protocol P3 { associatedtype T1 associatedtype T2 associatedtype T3 } protocol P4 : P3 { associatedtype T4 = T1 associatedtype T5 = T2 associatedtype T6 = T3 } class C2 : P4 {} // expected-error{{type 'C2' does not conform to protocol 'P4'}} expected-error{{type 'C2' does not conform to protocol 'P3'}} expected-note{{do you want to add protocol stubs?}}{{16-16=\n typealias T1 = <#type#>\n\n typealias T2 = <#type#>\n\n typealias T3 = <#type#>\n}}
apache-2.0
59c22abda59e2b3f2d79832b10d749cc
37.037037
397
0.610516
3.07485
false
false
false
false
prolificinteractive/Marker
Marker/Marker/Parser/MarkdownParser.swift
1
5152
// // MarkdownParser.swift // Marker // // Created by Htin Linn on 5/4/16. // Copyright © 2016 Prolific Interactive. All rights reserved. // import Foundation /// Markdown parser. struct MarkdownParser { /// Parser error. /// /// - invalidTagSymbol: Tag symbol is not a Markdown symbol. enum ParserError: LocalizedError { case invalidTagSymbol var errorDescription: String? { return "Invalid Markdown tag." } } // MARK: - Private properties private static let underscoreEmSymbol = Symbol(character: "_") private static let asteriskEmSymbol = Symbol(character: "*") private static let underscoreStrongSymbol = Symbol(rawValue: "__") private static let asteriskStrongSymbol = Symbol(rawValue: "**") private static let tildeStrikethroughSymbol = Symbol(rawValue: "~~") private static let equalUnderlineSymbol = Symbol(rawValue: "==") private static let linkTextOpeningSymbol = Symbol(character: "[") private static let linkTextClosingSymbol = Symbol(character: "]") private static let linkURLOpeningSymbol = Symbol(character: "(") private static let linkURLClosingSymbol = Symbol(character: ")") // MARK: - Static functions /// Parses specified string and returns a tuple containing string stripped of symbols and an array of Markdown elements. /// /// - Parameter string: String to be parsed. /// - Returns: Tuple containing string stripped of tag characters and an array of Markdown elements. /// - Throws: Parser error. static func parse(_ string: String) throws -> (strippedString: String, elements: [MarkdownElement]) { guard let underscoreStrongSymbol = underscoreStrongSymbol, let asteriskStrongSymbol = asteriskStrongSymbol, let tildeStrikethroughSymbol = tildeStrikethroughSymbol, let equalUnderlineSymbol = equalUnderlineSymbol else { return (string, []) } let underscoreEmRule = Rule(symbol: underscoreEmSymbol) let asteriskEmRule = Rule(symbol: asteriskEmSymbol) let underscoreStrongRule = Rule(symbol: underscoreStrongSymbol) let asteriskStrongRule = Rule(symbol: asteriskStrongSymbol) let tildeStrikethroughRule = Rule(symbol: tildeStrikethroughSymbol) let equalUnderlineRule = Rule(symbol: equalUnderlineSymbol) let linkTextRule = Rule(openingSymbol: linkTextOpeningSymbol, closingSymbol: linkTextClosingSymbol) let linkURLRule = Rule(openingSymbol: linkURLOpeningSymbol, closingSymbol: linkURLClosingSymbol) let tokens = try TokenParser.parse(string, using: [underscoreEmRule, asteriskEmRule, underscoreStrongRule, asteriskStrongRule, tildeStrikethroughRule, equalUnderlineRule, linkTextRule, linkURLRule]) guard tokens.count > 0 else { return (string, []) } var strippedString = "" var elements: [MarkdownElement] = [] var i = 0 while i < tokens.count { let token = tokens[i] // For `em`, `strong`, and other single token rules, // it's just a matter of appending the content of matched token and storing the new range. // But, for links, look for the square brackets and make sure that it's followed by parentheses directly. // For everything else including parentheses by themseleves should be ignored. switch token.rule { case .some(underscoreEmRule), .some(asteriskEmRule): let range = strippedString.append(contentOf: token) elements.append(.em(range: range)) case .some(underscoreStrongRule), .some(asteriskStrongRule): let range = strippedString.append(contentOf: token) elements.append(.strong(range: range)) case .some(tildeStrikethroughRule): let range = strippedString.append(contentOf: token) elements.append(.strikethrough(range: range)) case .some(equalUnderlineRule): let range = strippedString.append(contentOf: token) elements.append(.underline(range: range)) case .some(linkTextRule): guard i + 1 < tokens.count, tokens[i + 1].rule == linkURLRule else { fallthrough } let range = strippedString.append(contentOf: token) elements.append(.link(range: range,urlString: tokens[i + 1].string)) i += 1 default: strippedString += token.stringWithRuleSymbols } i += 1 } return (strippedString, elements) } }
mit
d90914377ebdcdcc4f2c2028f6c7fe75
41.925
124
0.596389
5.611111
false
false
false
false
gregomni/swift
stdlib/public/Concurrency/AsyncSequence.swift
3
19806
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2020 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 Swift /// A type that provides asynchronous, sequential, iterated access to its /// elements. /// /// An `AsyncSequence` resembles the `Sequence` type --- offering a list of /// values you can step through one at a time --- and adds asynchronicity. An /// `AsyncSequence` may have all, some, or none of its values available when /// you first use it. Instead, you use `await` to receive values as they become /// available. /// /// As with `Sequence`, you typically iterate through an `AsyncSequence` with a /// `for await`-`in` loop. However, because the caller must potentially wait for values, /// you use the `await` keyword. The following example shows how to iterate /// over `Counter`, a custom `AsyncSequence` that produces `Int` values from /// `1` up to a `howHigh` value: /// /// for await i in Counter(howHigh: 10) { /// print(i, terminator: " ") /// } /// // Prints: 1 2 3 4 5 6 7 8 9 10 /// /// An `AsyncSequence` doesn't generate or contain the values; it just defines /// how you access them. Along with defining the type of values as an associated /// type called `Element`, the `AsyncSequence` defines a `makeAsyncIterator()` /// method. This returns an instance of type `AsyncIterator`. Like the standard /// `IteratorProtocol`, the `AsyncIteratorProtocol` defines a single `next()` /// method to produce elements. The difference is that the `AsyncIterator` /// defines its `next()` method as `async`, which requires a caller to wait for /// the next value with the `await` keyword. /// /// `AsyncSequence` also defines methods for processing the elements you /// receive, modeled on the operations provided by the basic `Sequence` in the /// standard library. There are two categories of methods: those that return a /// single value, and those that return another `AsyncSequence`. /// /// Single-value methods eliminate the need for a `for await`-`in` loop, and instead /// let you make a single `await` call. For example, the `contains(_:)` method /// returns a Boolean value that indicates if a given value exists in the /// `AsyncSequence`. Given the `Counter` sequence from the previous example, /// you can test for the existence of a sequence member with a one-line call: /// /// let found = await Counter(howHigh: 10).contains(5) // true /// /// Methods that return another `AsyncSequence` return a type specific to the /// method's semantics. For example, the `.map(_:)` method returns a /// `AsyncMapSequence` (or a `AsyncThrowingMapSequence`, if the closure you /// provide to the `map(_:)` method can throw an error). These returned /// sequences don't eagerly await the next member of the sequence, which allows /// the caller to decide when to start work. Typically, you'll iterate over /// these sequences with `for await`-`in`, like the base `AsyncSequence` you started /// with. In the following example, the `map(_:)` method transforms each `Int` /// received from a `Counter` sequence into a `String`: /// /// let stream = Counter(howHigh: 10) /// .map { $0 % 2 == 0 ? "Even" : "Odd" } /// for await s in stream { /// print(s, terminator: " ") /// } /// // Prints: Odd Even Odd Even Odd Even Odd Even Odd Even /// @available(SwiftStdlib 5.1, *) @rethrows public protocol AsyncSequence { /// The type of asynchronous iterator that produces elements of this /// asynchronous sequence. associatedtype AsyncIterator: AsyncIteratorProtocol where AsyncIterator.Element == Element /// The type of element produced by this asynchronous sequence. associatedtype Element /// Creates the asynchronous iterator that produces elements of this /// asynchronous sequence. /// /// - Returns: An instance of the `AsyncIterator` type used to produce /// elements of the asynchronous sequence. __consuming func makeAsyncIterator() -> AsyncIterator } @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Returns the result of combining the elements of the asynchronous sequence /// using the given closure. /// /// Use the `reduce(_:_:)` method to produce a single value from the elements of /// an entire sequence. For example, you can use this method on an sequence of /// numbers to find their sum or product. /// /// The `nextPartialResult` closure executes sequentially with an accumulating /// value initialized to `initialResult` and each element of the sequence. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `4`. The `reduce(_:_:)` method sums the values /// received from the asynchronous sequence. /// /// let sum = await Counter(howHigh: 4) /// .reduce(0) { /// $0 + $1 /// } /// print(sum) /// // Prints: 10 /// /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// The `nextPartialResult` closure receives `initialResult` the first /// time the closure runs. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the asynchronous sequence into a new accumulating value, /// for use in the next call of the `nextPartialResult` closure or /// returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( _ initialResult: Result, _ nextPartialResult: (_ partialResult: Result, Element) async throws -> Result ) async rethrows -> Result { var accumulator = initialResult var iterator = makeAsyncIterator() while let element = try await iterator.next() { accumulator = try await nextPartialResult(accumulator, element) } return accumulator } /// Returns the result of combining the elements of the asynchronous sequence /// using the given closure, given a mutable initial value. /// /// Use the `reduce(into:_:)` method to produce a single value from the /// elements of an entire sequence. For example, you can use this method on a /// sequence of numbers to find their sum or product. /// /// The `nextPartialResult` closure executes sequentially with an accumulating /// value initialized to `initialResult` and each element of the sequence. /// /// Prefer this method over `reduce(_:_:)` for efficiency when the result is /// a copy-on-write type, for example an `Array` or `Dictionary`. /// /// - Parameters: /// - initialResult: The value to use as the initial accumulating value. /// The `nextPartialResult` closure receives `initialResult` the first /// time the closure executes. /// - nextPartialResult: A closure that combines an accumulating value and /// an element of the asynchronous sequence into a new accumulating value, /// for use in the next call of the `nextPartialResult` closure or /// returned to the caller. /// - Returns: The final accumulated value. If the sequence has no elements, /// the result is `initialResult`. @inlinable public func reduce<Result>( into initialResult: __owned Result, _ updateAccumulatingResult: (_ partialResult: inout Result, Element) async throws -> Void ) async rethrows -> Result { var accumulator = initialResult var iterator = makeAsyncIterator() while let element = try await iterator.next() { try await updateAccumulatingResult(&accumulator, element) } return accumulator } } @available(SwiftStdlib 5.1, *) @inlinable @inline(__always) func _contains<Source: AsyncSequence>( _ self: Source, where predicate: (Source.Element) async throws -> Bool ) async rethrows -> Bool { for try await element in self { if try await predicate(element) { return true } } return false } @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Returns a Boolean value that indicates whether the asynchronous sequence /// contains an element that satisfies the given predicate. /// /// You can use the predicate to check for an element of a type that doesn’t /// conform to the `Equatable` protocol, or to find an element that satisfies /// a general condition. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `contains(where:)` method checks to see /// whether the sequence produces a value divisible by `3`: /// /// let containsDivisibleByThree = await Counter(howHigh: 10) /// .contains { $0 % 3 == 0 } /// print(containsDivisibleByThree) /// // Prints: true /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate finds a match or the sequence ends. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the passed element represents a match. /// - Returns: `true` if the sequence contains an element that satisfies /// predicate; otherwise, `false`. @inlinable public func contains( where predicate: (Element) async throws -> Bool ) async rethrows -> Bool { return try await _contains(self, where: predicate) } /// Returns a Boolean value that indicates whether all elements produced by the /// asynchronous sequence satisfy the given predicate. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `allSatisfy(_:)` method checks to see whether /// all elements produced by the sequence are less than `10`. /// /// let allLessThanTen = await Counter(howHigh: 10) /// .allSatisfy { $0 < 10 } /// print(allLessThanTen) /// // Prints: false /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate returns `false` or the sequence ends. /// /// If the asynchronous sequence is empty, this method returns `true`. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the passed element satisfies a condition. /// - Returns: `true` if the sequence contains only elements that satisfy /// `predicate`; otherwise, `false`. @inlinable public func allSatisfy( _ predicate: (Element) async throws -> Bool ) async rethrows -> Bool { return try await !contains { try await !predicate($0) } } } @available(SwiftStdlib 5.1, *) extension AsyncSequence where Element: Equatable { /// Returns a Boolean value that indicates whether the asynchronous sequence /// contains the given element. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `contains(_:)` method checks to see whether /// the sequence produces the value `5`: /// /// let containsFive = await Counter(howHigh: 10) /// .contains(5) /// print(containsFive) /// // Prints: true /// /// - Parameter search: The element to find in the asynchronous sequence. /// - Returns: `true` if the method found the element in the asynchronous /// sequence; otherwise, `false`. @inlinable public func contains(_ search: Element) async rethrows -> Bool { for try await element in self { if element == search { return true } } return false } } @available(SwiftStdlib 5.1, *) @inlinable @inline(__always) func _first<Source: AsyncSequence>( _ self: Source, where predicate: (Source.Element) async throws -> Bool ) async rethrows -> Source.Element? { for try await element in self { if try await predicate(element) { return element } } return nil } @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Returns the first element of the sequence that satisfies the given /// predicate. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `first(where:)` method returns the first /// member of the sequence that's evenly divisible by both `2` and `3`. /// /// let divisibleBy2And3 = await Counter(howHigh: 10) /// .first { $0 % 2 == 0 && $0 % 3 == 0 } /// print(divisibleBy2And3 ?? "none") /// // Prints: 6 /// /// The predicate executes each time the asynchronous sequence produces an /// element, until either the predicate finds a match or the sequence ends. /// /// - Parameter predicate: A closure that takes an element of the asynchronous /// sequence as its argument and returns a Boolean value that indicates /// whether the element is a match. /// - Returns: The first element of the sequence that satisfies `predicate`, /// or `nil` if there is no element that satisfies `predicate`. @inlinable public func first( where predicate: (Element) async throws -> Bool ) async rethrows -> Element? { return try await _first(self, where: predicate) } } @available(SwiftStdlib 5.1, *) extension AsyncSequence { /// Returns the minimum element in the asynchronous sequence, using the given /// predicate as the comparison between elements. /// /// Use this method when the asynchronous sequence's values don't conform /// to `Comparable`, or when you want to apply a custom ordering to the /// sequence. /// /// The predicate must be a *strict weak ordering* over the elements. That is, /// for any elements `a`, `b`, and `c`, the following conditions must hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The following example uses an enumeration of playing cards ranks, `Rank`, /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence /// called `RankCounter` produces all elements of the array. The predicate /// provided to the `min(by:)` method sorts ranks based on their `rawValue`: /// /// enum Rank: Int { /// case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king /// } /// /// let min = await RankCounter() /// .min { $0.rawValue < $1.rawValue } /// print(min ?? "none") /// // Prints: ace /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: The sequence’s minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns `nil`. @inlinable @warn_unqualified_access public func min( by areInIncreasingOrder: (Element, Element) async throws -> Bool ) async rethrows -> Element? { var it = makeAsyncIterator() guard var result = try await it.next() else { return nil } while let e = try await it.next() { if try await areInIncreasingOrder(e, result) { result = e } } return result } /// Returns the maximum element in the asynchronous sequence, using the given /// predicate as the comparison between elements. /// /// Use this method when the asynchronous sequence's values don't conform /// to `Comparable`, or when you want to apply a custom ordering to the /// sequence. /// /// The predicate must be a *strict weak ordering* over the elements. That is, /// for any elements `a`, `b`, and `c`, the following conditions must hold: /// /// - `areInIncreasingOrder(a, a)` is always `false`. (Irreflexivity) /// - If `areInIncreasingOrder(a, b)` and `areInIncreasingOrder(b, c)` are /// both `true`, then `areInIncreasingOrder(a, c)` is also /// `true`. (Transitive comparability) /// - Two elements are *incomparable* if neither is ordered before the other /// according to the predicate. If `a` and `b` are incomparable, and `b` /// and `c` are incomparable, then `a` and `c` are also incomparable. /// (Transitive incomparability) /// /// The following example uses an enumeration of playing cards ranks, `Rank`, /// which ranges from `ace` (low) to `king` (high). An asynchronous sequence /// called `RankCounter` produces all elements of the array. The predicate /// provided to the `max(by:)` method sorts ranks based on their `rawValue`: /// /// enum Rank: Int { /// case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king /// } /// /// let max = await RankCounter() /// .max { $0.rawValue < $1.rawValue } /// print(max ?? "none") /// // Prints: king /// /// - Parameter areInIncreasingOrder: A predicate that returns `true` if its /// first argument should be ordered before its second argument; otherwise, /// `false`. /// - Returns: The sequence’s minimum element, according to /// `areInIncreasingOrder`. If the sequence has no elements, returns `nil`. @inlinable @warn_unqualified_access public func max( by areInIncreasingOrder: (Element, Element) async throws -> Bool ) async rethrows -> Element? { var it = makeAsyncIterator() guard var result = try await it.next() else { return nil } while let e = try await it.next() { if try await areInIncreasingOrder(result, e) { result = e } } return result } } @available(SwiftStdlib 5.1, *) extension AsyncSequence where Element: Comparable { /// Returns the minimum element in an asynchronous sequence of comparable /// elements. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `min()` method returns the minimum value /// of the sequence. /// /// let min = await Counter(howHigh: 10) /// .min() /// print(min ?? "none") /// // Prints: 1 /// /// - Returns: The sequence’s minimum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func min() async rethrows -> Element? { return try await self.min(by: <) } /// Returns the maximum element in an asynchronous sequence of comparable /// elements. /// /// In this example, an asynchronous sequence called `Counter` produces `Int` /// values from `1` to `10`. The `max()` method returns the max value /// of the sequence. /// /// let max = await Counter(howHigh: 10) /// .max() /// print(max ?? "none") /// // Prints: 10 /// /// - Returns: The sequence’s maximum element. If the sequence has no /// elements, returns `nil`. @inlinable @warn_unqualified_access public func max() async rethrows -> Element? { return try await self.max(by: <) } }
apache-2.0
731908fc1c680be754c0d0daca53e4db
40.155925
99
0.66276
4.376741
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/Developer/DeveloperTools/PreferredAPIVersion/PreferredAPIVersionViewModel.swift
1
2764
// // Wire // Copyright (C) 2022 Wire Swiss GmbH // // 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 Foundation import WireTransport import WireSyncEngine @available(iOS 14, *) final class PreferredAPIVersionViewModel: ObservableObject { // MARK: - Models struct Section: Identifiable { let id = UUID() let header: String let items: [Item] } struct Item: Identifiable { let id = UUID() let title: String let value: Value } enum Value: Equatable { case noPreference case apiVersion(APIVersion) init(apiVersion: APIVersion?) { if let apiVersion = apiVersion { self = .apiVersion(apiVersion) } else { self = .noPreference } } } enum Event { case itemTapped(Item) } // MARK: - State let sections: [Section] @Published var selectedItemID: Item.ID // MARK: - Life cycle init() { sections = [ Section(header: "", items: [Item(title: "No preference", value: .noPreference)]), Section(header: "Production versions", items: APIVersion.productionVersions.map { Item(title: String($0.rawValue), value: Value(apiVersion: $0)) }), Section(header: "Development versions", items: APIVersion.developmentVersions.map { Item(title: String($0.rawValue), value: Value(apiVersion: $0)) }) ] // Initial selection let selectedItem = sections.flatMap(\.items).first { item in item.value == Value(apiVersion: BackendInfo.preferredAPIVersion) }! selectedItemID = selectedItem.id } // MARK: - Events func handleEvent(_ event: Event) { switch event { case let .itemTapped(item): selectedItemID = item.id switch item.value { case .noPreference: BackendInfo.preferredAPIVersion = nil case .apiVersion(let version): BackendInfo.preferredAPIVersion = version } } } }
gpl-3.0
edcbd0859d285d0220e74fe1d95f5666
24.357798
95
0.603835
4.749141
false
false
false
false
saagarjha/Swimat
Swimat/SwimatViewController.swift
1
3767
import Cocoa class SwimatViewController: NSViewController { let installPath = "/usr/local/bin/" @IBOutlet weak var swimatTabView: NSTabView! @IBOutlet weak var versionLabel: NSTextField! { didSet { guard let infoDictionary = Bundle.main.infoDictionary, let version = infoDictionary["CFBundleShortVersionString"], let build = infoDictionary[kCFBundleVersionKey as String] else { return } versionLabel.stringValue = "Version \(version) (\(build))" } } @IBOutlet weak var installationLabel: NSTextField! { didSet { guard let url = Bundle.main.url(forResource: "Installation", withExtension: "html"), let string = try? NSAttributedString(url: url, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else { return } installationLabel.attributedStringValue = string } } @IBOutlet weak var installButton: NSButton! { didSet { refreshInstallButton() } } @IBOutlet weak var parameterAlignmentCheckbox: NSButton! { didSet { parameterAlignmentCheckbox.state = Preferences.areParametersAligned ? .on : .off } } @IBOutlet weak var removeSemicolonsCheckbox: NSButton! { didSet { removeSemicolonsCheckbox.state = Preferences.areSemicolonsRemoved ? .on : .off } } override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } override func viewDidAppear() { guard let window = view.window else { return } window.titleVisibility = .hidden window.titlebarAppearsTransparent = true } @IBAction func install(_ sender: Any) { // Migrate this to SMJobBless? let path = Bundle.main.bundleURL .appendingPathComponent("Contents", isDirectory: true) .appendingPathComponent("Helpers", isDirectory: true) .appendingPathComponent("swimat") .path var error: NSDictionary? let script = NSAppleScript(source: "do shell script \"ln -s \'\(path)\' \(installPath)swimat\" with administrator privileges") script?.executeAndReturnError(&error) if error != nil { let alert = NSAlert() alert.messageText = "There was an error symlinking swimat." alert.informativeText = "You can try manually linking swimat by running:\n\nln -s /Applications/Swimat.app/Contents/Helpers/swimat \(installPath)swimat" alert.alertStyle = .warning alert.runModal() } refreshInstallButton() } @IBAction func updateParameterAlignment(_ sender: NSButton) { Preferences.areParametersAligned = sender.state == .on preferencesChanged() } @IBAction func updateRemoveSemicolons(_ sender: NSButton) { Preferences.areSemicolonsRemoved = sender.state == .on preferencesChanged() } func preferencesChanged() { let notification = Notification(name: Notification.Name("SwimatPreferencesChangedNotification")) NotificationCenter.default.post(notification) } func refreshInstallButton() { // Check for swimat, fileExists(atPath:) returns false for symlinks if (try? FileManager.default.attributesOfItem(atPath: "\(installPath)swimat")) != nil { installButton.title = "swimat installed to \(installPath)" installButton.isEnabled = false } else { installButton.title = "Install swimat to \(installPath)" installButton.isEnabled = true } } }
mit
1cb0132399c4749e8acd47eec65589fa
35.572816
164
0.626228
5.313117
false
false
false
false
sunshineclt/NKU-Helper
NKU Helper/今天/TodayCell/GeneralTaskCell.swift
1
1167
// // GeneralTaskCell.swift // NKU Helper // // Created by 陈乐天 on 16/7/28. // Copyright © 2016年 陈乐天. All rights reserved. // import UIKit class GeneralTaskCell: MCSwipeTableViewCell { @IBOutlet var containerView: UIView! @IBOutlet var colorView: UIView! @IBOutlet var titleLabel: UILabel! @IBOutlet var descriptionLabel: UILabel! @IBOutlet var timeLabel: UILabel! var task: Task! { didSet { colorView.backgroundColor = task.color?.convertToUIColor() ?? UIColor.gray titleLabel.text = task.title descriptionLabel.text = task.descrip guard let dueDate = task.dueDate else { timeLabel.text = "" return } timeLabel.text = CalendarHelper.getCustomTimeIntervalDisplay(toDate: dueDate) } } override func awakeFromNib() { super.awakeFromNib() containerView.layer.shadowOffset = CGSize(width: 2, height: 2) containerView.layer.shadowColor = UIColor.gray.cgColor containerView.layer.shadowRadius = 2 containerView.layer.shadowOpacity = 0.5 } }
gpl-3.0
60fb4e69b4b18cb8de89c095abff1c60
27.8
89
0.631076
4.682927
false
false
false
false
almazrafi/Metatron
Sources/MPEG/MPEGMedia.swift
1
15527
// // MPEGMedia.swift // Metatron // // Copyright (c) 2016 Almaz Ibragimov // // 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 MPEGMedia { // MARK: Instance Properties private let stream: Stream private var introID3v2TagSlot: MPEGMediaIntroSlot<ID3v2TagCreator> private var outroID3v2TagSlot: MPEGMediaOutroSlot<ID3v2TagCreator> private var outroAPETagSlot: MPEGMediaOutroSlot<APETagCreator> private var outroLyrics3TagSlot: MPEGMediaOutroSlot<Lyrics3TagCreator> private var outroID3v1TagSlot: MPEGMediaOutroSlot<ID3v1TagCreator> private let properties: MPEGProperties // MARK: public var introID3v2Tag: ID3v2Tag? { get { return self.introID3v2TagSlot.tag } set { self.introID3v2TagSlot.tag = newValue } } public var outroID3v2Tag: ID3v2Tag? { get { return self.outroID3v2TagSlot.tag } set { self.outroID3v2TagSlot.tag = newValue } } public var outroAPETag: APETag? { get { return self.outroAPETagSlot.tag } set { self.outroAPETagSlot.tag = newValue } } public var outroLyrics3Tag: Lyrics3Tag? { get { return self.outroLyrics3TagSlot.tag } set { self.outroLyrics3TagSlot.tag = newValue } } public var outroID3v1Tag: ID3v1Tag? { get { return self.outroID3v1TagSlot.tag } set { self.outroID3v1TagSlot.tag = newValue } } // MARK: public var version: MPEGVersion { return self.properties.version } public var layer: MPEGLayer { return self.properties.layer } public var duration: Double { return self.properties.duration } public var bitRate: Int { return self.properties.bitRate } public var sampleRate: Int { return self.properties.sampleRate } public var channelMode: MPEGChannelMode { return self.properties.channelMode } public var copyrighted: Bool { return self.properties.copyrighted } public var original: Bool { return self.properties.original } public var emphasis: MPEGEmphasis { return self.properties.emphasis } public var bitRateMode: MPEGBitRateMode { return self.properties.bitRateMode } public var xingHeader: MPEGXingHeader? { return self.properties.xingHeader } public var vbriHeader: MPEGVBRIHeader? { return self.properties.vbriHeader } public var channels: Int { switch self.channelMode { case MPEGChannelMode.stereo, MPEGChannelMode.jointStereo, MPEGChannelMode.dualChannel: return 2 case MPEGChannelMode.singleChannel: return 1 } } // MARK: public var filePath: String { if let stream = self.stream as? FileStream { return stream.filePath } return "" } public var isReadOnly: Bool { return (!self.stream.isWritable) } // MARK: Initializers public init(fromStream stream: Stream) throws { guard stream.isOpen && stream.isReadable && (stream.length > 0) else { throw MediaError.invalidStream } var range = Range<UInt64>(0..<stream.length) var introID3v2TagSlot: MPEGMediaIntroSlot<ID3v2TagCreator>? var outroID3v2TagSlot: MPEGMediaOutroSlot<ID3v2TagCreator>? var outroAPETagSlot: MPEGMediaOutroSlot<APETagCreator>? var outroLyrics3TagSlot: MPEGMediaOutroSlot<Lyrics3TagCreator>? var outroID3v1TagSlot: MPEGMediaOutroSlot<ID3v1TagCreator>? if let slot = MPEGMediaIntroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) { range = slot.range.upperBound..<range.upperBound while let excess = MPEGMediaIntroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) { range = excess.range.upperBound..<range.upperBound } slot.range = slot.range.lowerBound..<range.lowerBound if slot.tag!.fillingLength > 0 { slot.tag!.fillingLength = Int(min(UInt64(slot.range.count), UInt64(Int.max))) } introID3v2TagSlot = slot } if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroAPETagSlot = slot } if let slot = MPEGMediaOutroSlot(creator: Lyrics3TagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroLyrics3TagSlot = slot if outroAPETagSlot == nil { if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroAPETagSlot = slot } } } if let slot = MPEGMediaOutroSlot(creator: ID3v1TagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroID3v1TagSlot = slot if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroAPETagSlot = slot } if let slot = MPEGMediaOutroSlot(creator: Lyrics3TagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroLyrics3TagSlot = slot if outroAPETagSlot == nil { if let slot = MPEGMediaOutroSlot(creator: APETagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroAPETagSlot = slot } } } } if let slot = MPEGMediaOutroSlot(creator: ID3v2TagCreator.regular, stream: stream, range: range) { range = range.lowerBound..<slot.range.lowerBound outroID3v2TagSlot = slot } guard let properties = MPEGProperties(fromStream: stream, range: range) else { throw MediaError.invalidFormat } self.stream = stream self.introID3v2TagSlot = introID3v2TagSlot ?? MPEGMediaIntroSlot() self.outroID3v2TagSlot = outroID3v2TagSlot ?? MPEGMediaOutroSlot() self.outroAPETagSlot = outroAPETagSlot ?? MPEGMediaOutroSlot() self.outroLyrics3TagSlot = outroLyrics3TagSlot ?? MPEGMediaOutroSlot() self.outroID3v1TagSlot = outroID3v1TagSlot ?? MPEGMediaOutroSlot() self.properties = properties } public convenience init(fromFilePath filePath: String, readOnly: Bool) throws { guard !filePath.isEmpty else { throw MediaError.invalidFile } let stream = FileStream(filePath: filePath) if readOnly { guard stream.openForReading() else { throw MediaError.invalidFile } } else { guard stream.openForUpdating(truncate: false) else { throw MediaError.invalidFile } } guard stream.length > 0 else { throw MediaError.invalidData } try self.init(fromStream: stream) } public convenience init(fromData data: [UInt8], readOnly: Bool) throws { guard !data.isEmpty else { throw MediaError.invalidData } let stream = MemoryStream(data: data) if readOnly { guard stream.openForReading() else { throw MediaError.invalidStream } } else { guard stream.openForUpdating(truncate: false) else { throw MediaError.invalidStream } } try self.init(fromStream: stream) } // MARK: Instance Methods @discardableResult public func save() -> Bool { guard self.stream.isOpen && self.stream.isWritable && (self.stream.length > 0) else { return false } guard self.stream.seek(offset: self.introID3v2TagSlot.range.lowerBound) else { return false } if let data = self.introID3v2TagSlot.tag?.toData() { let range = self.introID3v2TagSlot.range if range.upperBound == 0 { guard self.stream.insert(data: data) else { return false } self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset let framesLowerBound = self.properties.framesRange.lowerBound + UInt64(data.count) let framesUpperBound = self.properties.framesRange.upperBound + UInt64(data.count) self.properties.framesRange = framesLowerBound..<framesUpperBound } else if UInt64(data.count) > UInt64(range.count) { let delta = UInt64(data.count) - UInt64(range.count) guard self.stream.write(data: [UInt8](data.prefix(Int(range.count)))) == Int(range.count) else { return false } guard self.stream.insert(data: [UInt8](data.suffix(Int(delta)))) else { return false } self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset let framesLowerBound = self.properties.framesRange.lowerBound + delta let framesUpperBound = self.properties.framesRange.upperBound + delta self.properties.framesRange = framesLowerBound..<framesUpperBound } else { guard self.stream.write(data: data) == data.count else { return false } if range.upperBound > self.stream.offset { let delta = range.upperBound - self.stream.offset guard self.stream.remove(length: delta) else { return false } self.introID3v2TagSlot.range = range.lowerBound..<self.stream.offset let framesLowerBound = self.properties.framesRange.lowerBound - delta let framesUpperBound = self.properties.framesRange.upperBound - delta self.properties.framesRange = framesLowerBound..<framesUpperBound } } self.introID3v2TagSlot.range = range } else { let rangeLength = UInt64(self.introID3v2TagSlot.range.count) guard self.stream.remove(length: rangeLength) else { return false } self.introID3v2TagSlot.range = 0..<0 let framesLowerBound = self.properties.framesRange.lowerBound - rangeLength let framesUpperBound = self.properties.framesRange.upperBound - rangeLength self.properties.framesRange = framesLowerBound..<framesUpperBound } guard self.stream.seek(offset: self.properties.framesRange.upperBound) else { return false } var nextLowerBound = self.stream.offset if let tag = self.outroID3v2TagSlot.tag { tag.version = ID3v2Version.v4 tag.footerPresent = true tag.fillingLength = 0 if let data = tag.toData() { guard self.stream.write(data: data) == data.count else { return false } self.outroID3v2TagSlot.range = nextLowerBound..<self.stream.offset } else { self.outroID3v2TagSlot.range = 0..<0 } } else { self.outroID3v2TagSlot.range = 0..<0 } nextLowerBound = self.stream.offset if let tag = self.outroAPETagSlot.tag { tag.version = APEVersion.v2 tag.footerPresent = true tag.fillingLength = 0 if let data = tag.toData() { guard self.stream.write(data: data) == data.count else { return false } self.outroAPETagSlot.range = nextLowerBound..<self.stream.offset } else { self.outroAPETagSlot.range = 0..<0 } } else { self.outroAPETagSlot.range = 0..<0 } nextLowerBound = self.stream.offset if let data = self.outroLyrics3TagSlot.tag?.toData() { guard self.stream.write(data: data) == data.count else { return false } self.outroLyrics3TagSlot.range = nextLowerBound..<self.stream.offset } else { self.outroLyrics3TagSlot.range = 0..<0 } nextLowerBound = self.stream.offset if let tag = self.outroID3v1TagSlot.tag { let extVersionAvailable: Bool if self.outroID3v2TagSlot.range.lowerBound > 0 { extVersionAvailable = false } else if self.outroAPETagSlot.range.lowerBound > 0 { extVersionAvailable = false } else if self.outroLyrics3TagSlot.range.lowerBound > 0 { extVersionAvailable = false } else { extVersionAvailable = true } if !extVersionAvailable { switch tag.version { case ID3v1Version.vExt0: tag.version = ID3v1Version.v0 case ID3v1Version.vExt1: tag.version = ID3v1Version.v1 case ID3v1Version.v0, ID3v1Version.v1: break } } if let data = tag.toData() { guard self.stream.write(data: data) == data.count else { return false } self.outroID3v1TagSlot.range = nextLowerBound..<self.stream.offset } else { self.outroID3v1TagSlot.range = 0..<0 } } else { self.outroID3v1TagSlot.range = 0..<0 } self.stream.truncate(length: self.stream.offset) self.stream.synchronize() return true } }
mit
024137f35b45323ae49b194c953da8c6
30.431174
116
0.594384
4.837072
false
false
false
false
18775134221/SwiftBase
SwiftTest/SwiftTest/Classes/Main/Tools/SQLite/SQLiteDatabaseTool.swift
2
6708
// // SQLiteDatabaseTool.swift // SwiftTest // // Created by MAC on 2016/12/31. // Copyright © 2016年 MAC. All rights reserved. // import UIKit class SQLiteDatabaseTool: NSObject { // 创建单例 static var sharedInstance : SQLiteDatabaseTool { struct Static { static let instance : SQLiteDatabaseTool = SQLiteDatabaseTool() } return Static.instance } // 数据库对象 private var db:OpaquePointer? = nil // 创建一个串行队列 private let dbQueue = DispatchQueue(label: "task", attributes: .init(rawValue: 0)) func execQueueSQL(action: @escaping (_ manager: SQLiteDatabaseTool)->()) { // 1.开启一个子线程 dbQueue.async(execute: { action(self) }) } /** 打开数据库 :param: SQLiteName 数据库名称 */ func openDB(SQLiteName: String) { // 0.拿到数据库的路径 let path = SQLiteName.docDir() let cPath = path.cString(using: String.Encoding.utf8)! // 1.打开数据库 /* 1.需要打开的数据库文件的路径, C语言字符串 2.打开之后的数据库对象 (指针), 以后所有的数据库操作, 都必须要拿到这个指针才能进行相关操作 */ // open方法特点: 如果指定路径对应的数据库文件已经存在, 就会直接打开 // 如果指定路径对应的数据库文件不存在, 就会创建一个新的 if sqlite3_open(cPath, &db) != SQLITE_OK { print("打开数据库失败") return } // 2.创建表 if creatTable() { print("创建表成功") }else { print("创建表失败") } } private func creatTable() -> Bool { // 1.编写SQL语句 // 建议: 在开发中编写SQL语句, 如果语句过长, 不要写在一行 // 开发技巧: 在做数据库开发时, 如果遇到错误, 可以先将SQL打印出来, 拷贝到PC工具中验证之后再进行调试 let sql = "CREATE TABLE IF NOT EXISTS T_Person( \n" + "id INTEGER PRIMARY KEY AUTOINCREMENT, \n" + "name TEXT, \n" + "age INTEGER \n" + "); \n" // print(sql) // 2.执行SQL语句 return execSQL(sql: sql) } /** 执行除查询以外的SQL语句 :param: sql 需要执行的SQL语句 :returns: 是否执行成功 true执行成功 false执行失败 */ func execSQL(sql: String) -> Bool { // 0.将Swift字符串转换为C语言字符串 let cSQL = sql.cString(using: String.Encoding.utf8)! // 在SQLite3中, 除了查询意外(创建/删除/新增/更新)都使用同一个函数 /* 1. 已经打开的数据库对象 2. 需要执行的SQL语句, C语言字符串 3. 执行SQL语句之后的回调, 一般传nil 4. 是第三个参数的第一个参数, 一般传nil 5. 错误信息, 一般传nil */ if sqlite3_exec(db, cSQL, nil, nil, nil) != SQLITE_OK { return false } return true } /** 查询所有的数据 :returns: 查询到的字典数组 */ func execRecordSQL(sql: String) ->[[String: AnyObject]] { // 0.将Swift字符串转换为C语言字符串 let cSQL = sql.cString(using: String.Encoding.utf8)! // 1.准备数据 // 准备: 理解为预编译SQL语句, 检测里面是否有错误等等, 它可以提供性能 /* 1.已经开打的数据库对象 2.需要执行的SQL语句 3.需要执行的SQL语句的长度, 传入-1系统自动计算 4.预编译之后的句柄, 已经要想取出数据, 就需要这个句柄 5. 一般传nil */ var stmt: OpaquePointer? = nil if sqlite3_prepare_v2(db, cSQL, -1, &stmt, nil) != SQLITE_OK { print("准备失败") } // 准备成功 var records = [[String: AnyObject]]() // 2.查询数据 // sqlite3_step代表取出一条数据, 如果取到了数据就会返回SQLITE_ROW while sqlite3_step(stmt) == SQLITE_ROW { // 获取一条记录的数据 let record = recordWithStmt(stmt: stmt!) // 将当前获取到的这一条记录添加到数组中 records.append(record) } // 返回查询到的数据 return records } /** 获取一条记录的值 :param: stmt 预编译好的SQL语句 :returns: 字典 */ private func recordWithStmt(stmt: OpaquePointer) ->[String: AnyObject] { // 2.1拿到当前这条数据所有的列 let count = sqlite3_column_count(stmt) // print(count) // 定义字典存储查询到的数据 var record = [String: AnyObject]() for index in 0..<count { // 2.2拿到每一列的名称 let cName = sqlite3_column_name(stmt, index) let name = String(cString: cName!, encoding: String.Encoding.utf8) // print(name) // 2.3拿到每一列的类型 SQLITE_INTEGER let type = sqlite3_column_type(stmt, index) // print("name = \(name) , type = \(type)") switch type { case SQLITE_INTEGER: // 整形 let num = sqlite3_column_int64(stmt, index) record[name!] = Int(num) as AnyObject? case SQLITE_FLOAT: // 浮点型 let double = sqlite3_column_double(stmt, index) record[name!] = Double(double) as AnyObject? case SQLITE3_TEXT: // 文本类型 //let cText = let text = String(cString: sqlite3_column_text(stmt, index)) //(sqlite3_column_text(stmt, index)) // let text = String(cString: cText! , encoding: String.Encoding.utf8) record[name!] = text as AnyObject? case SQLITE_NULL: // 空类型 record[name!] = NSNull() default: // 二进制类型 SQLITE_BLOB // 一般情况下, 不会往数据库中存储二进制数据 print("") } } return record } }
apache-2.0
0faa7a0df3a7b18b847c20103f0dbe1e
25.615764
86
0.491764
3.799578
false
false
false
false
buyiyang/iosstar
iOSStar/Scenes/Discover/Controllers/VoiceAskVC.swift
3
4229
// // VoiceAskVC.swift // iOSStar // // Created by mu on 2017/8/17. // Copyright © 2017年 YunDian. All rights reserved. // import UIKit import SVProgressHUD class VoiceAskVC: BaseTableViewController ,UITextViewDelegate{ @IBOutlet var contentText: UITextView! @IBOutlet var placeholdLabel: UILabel! @IBOutlet weak var countLabel: UILabel! @IBOutlet weak var voice15Btn: UIButton! @IBOutlet weak var voice30Btn: UIButton! @IBOutlet weak var voice60Btn: UIButton! @IBOutlet var switchopen: UISwitch! var starModel: StarSortListModel = StarSortListModel() private var lastVoiceBtn: UIButton? override func viewDidLoad() { super.viewDidLoad() title = "向TA定制" voiceBtnTapped(voice15Btn) navright() } @IBAction func voiceBtnTapped(_ sender: UIButton) { lastVoiceBtn?.isSelected = false sender.isSelected = !sender.isSelected lastVoiceBtn = sender } func navright(){ let share = UIButton.init(type: .custom) share.frame = CGRect.init(x: 0, y: 0, width: 70, height: 30) share.setTitle("发布", for: .normal) share.titleLabel?.font = UIFont.systemFont(ofSize: 17) share.setTitleColor(UIColor.init(hexString: AppConst.Color.main), for: .normal) share.addTarget(self, action: #selector(publish), for: .touchUpInside) let item = UIBarButtonItem.init(customView: share) self.navigationItem.rightBarButtonItem = item NotificationCenter.default.addObserver(self, selector: #selector(textViewNotifitionAction), name: NSNotification.Name.UITextViewTextDidChange, object: nil); NotificationCenter.default.addObserver(self, selector: #selector(textViewNotifitionAction), name: NSNotification.Name.UITextViewTextDidChange, object: nil); } func publish(){ if contentText.text == ""{ SVProgressHUD.showErrorMessage(ErrorMessage: "请输入问答内容", ForDuration: 2, completion: nil) return } let request = AskRequestModel() request.pType = switchopen.isOn ? 1 : 0 request.aType = 2 request.starcode = starModel.symbol request.uask = contentText.text! request.videoUrl = "" request.cType = voice15Btn.isSelected ? 0 : (voice30Btn.isSelected ? 1 : (voice60Btn.isSelected ? 3 : 1)) AppAPIHelper.discoverAPI().videoAskQuestion(requestModel:request, complete: { (result) in if let model = result as? ResultModel{ if model.result == 0{ SVProgressHUD.showSuccessMessage(SuccessMessage: "语音问答成功", ForDuration: 1, completion: { self.navigationController?.popViewController(animated: true) }) } if model.result == 1{ SVProgressHUD.showErrorMessage(ErrorMessage: "时间不足", ForDuration: 2, completion: nil) } } }) { (error) in self.didRequestError(error) } } // 限制不超过200字 func textViewNotifitionAction(userInfo:NSNotification){ let textVStr = contentText.text as! NSString if ((textVStr.length) > 100) { contentText.text = contentText.text.substring(to: contentText.text.index(contentText.text.startIndex, offsetBy: 100)) contentText.resignFirstResponder() return }else{ countLabel.text = "\(textVStr.length)/100" } } func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if (contentText.text.length() > 100){ return false } return true } func textViewDidChange(_ textView: UITextView) { // contentText.text = textView.text if textView.text == "" { placeholdLabel.text = "输入你的问题,可选择公开或者私密,公开提问能被其他用户所见 " placeholdLabel.isHidden = false } else { placeholdLabel.text = "" placeholdLabel.isHidden = true } } }
gpl-3.0
ff50952a8020389c47b1001a17ff15f4
37.074074
164
0.626702
4.579065
false
false
false
false
qmathe/Confetti
Event/Input/Modifiers.swift
1
533
/** Copyright (C) 2017 Quentin Mathe Author: Quentin Mathe <quentin.mathe@gmail.com> Date: November 2017 License: MIT */ import Foundation import Tapestry public struct Modifiers: OptionSet { public let rawValue: Int public init(rawValue: Int) { self.rawValue = rawValue } public static let command = Modifiers(rawValue: 1) public static let option = Modifiers(rawValue: 2) public static let control = Modifiers(rawValue: 4) public static let shift = Modifiers(rawValue: 8) }
mit
909ad47e09596631cc7d9504a1165fbc
22.173913
54
0.690432
3.977612
false
false
false
false
rxwei/dlvm-tensor
Sources/CoreTensor/Index.swift
2
5000
// // Index.swift // CoreTensor // // Copyright 2016-2018 The DLVM Team. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /// Tensor index public struct TensorIndex: ExpressibleByArrayLiteral { var elements: [Int] public init(arrayLiteral elements: Int...) { self.elements = elements } public init(_ indexElements: Int...) { self.elements = indexElements } public init<S: Sequence>(_ indexElements: S) where S.Element == Int { self.elements = Array(indexElements) } public init(repeating repeatedValue: Int, count: Int) { self.elements = Array(repeating: repeatedValue, count: count) } /// Compute the contiguous storage index from high-dimensional tensor /// indices /// - parameter indices: tensor indices /// - returns: index in contiguous storage /// - note: the count of indices must equal the rank of the tensor public func contiguousIndex(in shape: TensorShape) -> Int { /// Row-major order addressing let trimmedShape = shape.prefix(count) return elements.enumerated().reduce(0, { acc, next -> Int in let stride = trimmedShape.isEmpty ? 0 : trimmedShape.dropFirst(next.offset+1).reduce(1, *) return acc + next.element * stride }) } } // MARK: - Equatable, Comparable extension TensorIndex : Comparable { public static func ==(lhs: TensorIndex, rhs: TensorIndex) -> Bool { return lhs.elements == rhs.elements } public static func <(lhs: TensorIndex, rhs: TensorIndex) -> Bool { for (x, y) in zip(lhs.elements, rhs.elements) { /// Less-than at a higher dimension => true if x < y { return true } /// Greater-than at a higher dimension => false if x > y { return false } /// Otherwise, at the same higher dimension => continue } return false } } // MARK: - RandomAccessCollection extension TensorIndex : RandomAccessCollection { public var count: Int { return elements.count } public var dimension: Int { return count - 1 } public subscript(bounds: Range<Int>) -> TensorIndex { get { return TensorIndex(elements[bounds]) } set { elements[bounds] = ArraySlice(newValue.elements) } } public var indices: CountableRange<Int> { return elements.indices } public func index(after i: Int) -> Int { return elements.index(after: i) } public func index(before i: Int) -> Int { return elements.index(before: i) } public var startIndex: Int { return elements.startIndex } public var endIndex: Int { return elements.endIndex } /// Size of i-th dimension /// - parameter i: dimension public subscript(i: Int) -> Int { get { return elements[i] } set { elements[i] = newValue } } } // MARK: - Strideable extension TensorIndex : Strideable { public typealias Stride = Int /// Returns a `Self` `x` such that `self.distance(to: x)` approximates `n`. /// /// If `Stride` conforms to `Integer`, then `self.distance(to: x) == n`. /// /// - Complexity: O(1). public func advanced(by n: Int) -> TensorIndex { guard !isEmpty else { return self } var newIndex = self newIndex[newIndex.endIndex-1] += n return newIndex } /// Returns a stride `x` such that `self.advanced(by: x)` approximates /// `other`. /// /// If `Stride` conforms to `Integer`, then `self.advanced(by: x) == other`. /// /// - Complexity: O(1). public func distance(to other: TensorIndex) -> Int { precondition(count == other.count, "Indices are not in the same dimension") guard let otherLast = other.last, let selfLast = last else { return 0 } return otherLast - selfLast } } public extension TensorShape { /// Returns the row-major order index for the specified tensor index /// - parameter index: tensor index func contiguousIndex(for index: TensorIndex) -> Int { return index.contiguousIndex(in: self) } /// Returns the shape after indexing subscript(index: TensorIndex) -> TensorShape? { guard index.count < rank else { return nil } return dropFirst(index.count) } }
apache-2.0
2dcd96f3cf52149b338f54ab568041b1
28.411765
80
0.6102
4.366812
false
false
false
false
ubclaunchpad/RocketCast
RocketCast/PodcastViewCollectionViewCell.swift
1
2256
// // PodcastViewCollectionViewCell.swift // RocketCast // // Created by Milton Leung on 2016-11-09. // Copyright © 2016 UBCLaunchPad. All rights reserved. // import UIKit class PodcastViewCollectionViewCell: UICollectionViewCell { @IBOutlet weak var coverPhotoView: UIView! @IBOutlet weak var podcastTitle: UILabel! @IBOutlet weak var podcastAuthor: UILabel! @IBOutlet weak var photoWidth: NSLayoutConstraint! @IBOutlet weak var photoHeight: NSLayoutConstraint! var podcast: Podcast! { didSet { podcastTitle.text = podcast.title podcastAuthor.text = podcast.author let url = URL(string: (podcast.imageURL)!) DispatchQueue.global().async { do { let data = try Data(contentsOf: url!) let coverPhoto = UIImageView() coverPhoto.frame = self.coverPhotoView.bounds coverPhoto.layer.cornerRadius = 18 coverPhoto.layer.masksToBounds = true DispatchQueue.main.async { coverPhoto.image = UIImage(data: data) self.coverPhotoView.addSubview(coverPhoto) } } catch let error as NSError{ Log.error("Error: " + error.debugDescription) } } } } var size: Int! { didSet { photoWidth.constant = CGFloat(size) photoHeight.constant = CGFloat(size) } } func setStyling() { let effectsLayer = coverPhotoView.layer effectsLayer.cornerRadius = 14 effectsLayer.shadowColor = UIColor.black.cgColor effectsLayer.shadowOffset = CGSize(width: 0, height: 0) effectsLayer.shadowRadius = 4 effectsLayer.shadowOpacity = 0.4 effectsLayer.shadowPath = UIBezierPath(roundedRect: CGRect(x:coverPhotoView.frame.origin.x, y:coverPhotoView.frame.origin.y, width: photoWidth.constant, height:photoHeight.constant), cornerRadius: coverPhotoView.layer.cornerRadius).cgPath } override func awakeFromNib() { super.awakeFromNib() // Initialization code } }
mit
9da5cfdc46f83c08ac844f91bf29de80
33.692308
246
0.6
5.172018
false
false
false
false
nostramap/nostra-sdk-sample-ios
SearchSample/Swift/SearchSample/KeywordViewController.swift
1
2607
// // KeywordViewcontroller.swift // SearchSample // // Copyright © 2559 Globtech. All rights reserved. // import UIKit import NOSTRASDK class KeywordViewController: UIViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! var keywords: [NTAutocompleteResult]?; var param: NTAutocompleteParameter?; override func viewDidLoad() { super.viewDidLoad(); } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "keywordtoResultSegue" { let resultViewController = segue.destination as! ResultViewController; resultViewController.searchByKeyword(sender as? String); } } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if searchText.characters.count > 0 { param = NTAutocompleteParameter(keyword: searchText); NTAutocompleteService.executeAsync(param!) { (resultSet, error) in DispatchQueue.main.async(execute: { if error == nil { self.keywords = resultSet?.results; } else { self.keywords = []; print("error: \(error?.description)"); } self.tableView.reloadData(); }) } } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder(); } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let keyword = keywords![indexPath.row]; self.performSegue(withIdentifier: "keywordtoResultSegue", sender: keyword.name); } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell"); let keyword = keywords![indexPath.row]; cell?.textLabel?.text = keyword.name; return cell!; } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return keywords != nil ? (keywords?.count)! : 0; } func numberOfSections(in tableView: UITableView) -> Int { return 1 } }
apache-2.0
4797093ae2bf6ffe34eb84354d9d6729
26.723404
112
0.570606
5.922727
false
false
false
false
rudkx/swift
test/Interop/Cxx/class/constructors-irgen.swift
1
9488
// Target-specific tests for C++ constructor call code generation. // RUN: %swift -module-name Swift -target x86_64-apple-macosx10.9 -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=ITANIUM_X64 // RUN: %swift -module-name Swift -target armv7-unknown-linux-androideabi -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=ITANIUM_ARM // RUN: %swift -module-name Swift -target x86_64-unknown-windows-msvc -dump-clang-diagnostics -I %S/Inputs -enable-cxx-interop -emit-ir %s -parse-stdlib -parse-as-library -disable-legacy-type-info | %FileCheck %s -check-prefix=MICROSOFT_X64 import Constructors import TypeClassification typealias Void = () struct UnsafePointer<T> { } struct UnsafeMutablePointer<T> { } struct Int { } struct UInt { } public func createHasVirtualBase() -> HasVirtualBase { // ITANIUM_X64: define swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0) // ITANIUM_X64-NOT: define // ITANIUM_X64: call void @_ZN14HasVirtualBaseC1E7ArgType(%struct.HasVirtualBase* %{{[0-9]+}}, i32 %{{[0-9]+}}) // // ITANIUM_ARM: define protected swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0) // To verify that the thunk is inlined, make sure there's no intervening // `define`, i.e. the call to the C++ constructor happens in // createHasVirtualBase(), not some later function. // ITANIUM_ARM-NOT: define // Note `this` return type. // ITANIUM_ARM: call %struct.HasVirtualBase* @_ZN14HasVirtualBaseC1E7ArgType(%struct.HasVirtualBase* %{{[0-9]+}}, [1 x i32] %{{[0-9]+}}) // // MICROSOFT_X64: define dllexport swiftcc void @"$ss20createHasVirtualBaseSo0bcD0VyF"(%TSo14HasVirtualBaseV* noalias nocapture sret({{.*}}) %0) // MICROSOFT_X64-NOT: define // Note `this` return type and implicit "most derived" argument. // MICROSOFT_X64: call %struct.HasVirtualBase* @"??0HasVirtualBase@@QEAA@UArgType@@@Z"(%struct.HasVirtualBase* %{{[0-9]+}}, i32 %{{[0-9]+}}, i32 1) return HasVirtualBase(ArgType()) } public func createImplicitDefaultConstructor() -> ImplicitDefaultConstructor { // ITANIUM_X64: define swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"() // ITANIUM_X64-NOT: define // ITANIUM_X64: call void @_ZN26ImplicitDefaultConstructorC1Ev(%struct.ImplicitDefaultConstructor* %{{[0-9]+}}) // // ITANIUM_ARM: define protected swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"() // ITANIUM_ARM-NOT: define // Note `this` return type. // ITANIUM_ARM: call %struct.ImplicitDefaultConstructor* @_ZN26ImplicitDefaultConstructorC2Ev(%struct.ImplicitDefaultConstructor* %{{[0-9]+}}) // // MICROSOFT_X64: define dllexport swiftcc i32 @"$ss32createImplicitDefaultConstructorSo0bcD0VyF"() // MICROSOFT_X64-NOT: define // Note `this` return type but no implicit "most derived" argument. // MICROSOFT_X64: call %struct.ImplicitDefaultConstructor* @"??0ImplicitDefaultConstructor@@QEAA@XZ"(%struct.ImplicitDefaultConstructor* %{{[0-9]+}}) return ImplicitDefaultConstructor() } public func createStructWithSubobjectCopyConstructorAndValue() { // ITANIUM_X64-LABEL: define swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"() // ITANIUM_X64: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // ITANIUM_X64: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV // ITANIUM_X64: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // ITANIUM_X64: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_X64: void @_ZN33StructWithCopyConstructorAndValueC1Ev(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]]) // ITANIUM_X64: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_X64: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_X64: call void @_ZN33StructWithCopyConstructorAndValueC1ERKS_(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]]) // ITANIUM_X64: ret void // ITANIUM_ARM-LABEL: define protected swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"() // ITANIUM_ARM: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // ITANIUM_ARM: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV // ITANIUM_ARM: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // ITANIUM_ARM: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_ARM: call %struct.StructWithCopyConstructorAndValue* @_ZN33StructWithCopyConstructorAndValueC2Ev(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]]) // ITANIUM_ARM: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_ARM: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // ITANIUM_ARM: call %struct.StructWithCopyConstructorAndValue* @_ZN33StructWithCopyConstructorAndValueC2ERKS_(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]]) // ITANIUM_ARM: ret void // MICROSOFT_X64-LABEL: define dllexport swiftcc void @"$ss48createStructWithSubobjectCopyConstructorAndValueyyF"() // MICROSOFT_X64: [[MEMBER:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // MICROSOFT_X64: [[OBJ:%.*]] = alloca %TSo42StructWithSubobjectCopyConstructorAndValueV // MICROSOFT_X64: [[TMP:%.*]] = alloca %TSo33StructWithCopyConstructorAndValueV // MICROSOFT_X64: [[MEMBER_AS_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // MICROSOFT_X64: call %struct.StructWithCopyConstructorAndValue* @"??0StructWithCopyConstructorAndValue@@QEAA@XZ"(%struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT]]) // MICROSOFT_X64: [[TMP_STRUCT:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[TMP]] to %struct.StructWithCopyConstructorAndValue* // MICROSOFT_X64: [[MEMBER_AS_STRUCT_2:%.*]] = bitcast %TSo33StructWithCopyConstructorAndValueV* [[MEMBER]] to %struct.StructWithCopyConstructorAndValue* // MICROSOFT_X64: call %struct.StructWithCopyConstructorAndValue* @"??0StructWithCopyConstructorAndValue@@QEAA@AEBU0@@Z"(%struct.StructWithCopyConstructorAndValue* [[TMP_STRUCT]], %struct.StructWithCopyConstructorAndValue* [[MEMBER_AS_STRUCT_2]]) // MICROSOFT_X64: ret void let member = StructWithCopyConstructorAndValue() let obj = StructWithSubobjectCopyConstructorAndValue(member: member) } public func createTemplatedConstructor() { // ITANIUM_X64-LABEL: define swiftcc void @"$ss26createTemplatedConstructoryyF"() // ITANIUM_X64: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV // ITANIUM_X64: [[IVAL:%.*]] = load i32, i32* // ITANIUM_X64: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor* // ITANIUM_X64: call void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]]) // ITANIUM_X64: ret void // ITANIUM_X64-LABEL: define linkonce_odr void @_ZN20TemplatedConstructorC1I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull align 4 dereferenceable(4) {{.*}}, i32 {{.*}}) // ITANIUM_ARM-LABEL: define protected swiftcc void @"$ss26createTemplatedConstructoryyF"() // ITANIUM_ARM: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV // ITANIUM_ARM: [[IVAL:%.*]] = load [1 x i32], [1 x i32]* // ITANIUM_ARM: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor* // ITANIUM_ARM: call %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], [1 x i32] [[IVAL]]) // ITANIUM_ARM: ret void // ITANIUM_ARM-LABEL: define linkonce_odr %struct.TemplatedConstructor* @_ZN20TemplatedConstructorC2I7ArgTypeEET_(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, [1 x i32] {{.*}}) // MICROSOFT_X64-LABEL: define dllexport swiftcc void @"$ss26createTemplatedConstructoryyF"() // MICROSOFT_X64: [[OBJ:%.*]] = alloca %TSo20TemplatedConstructorV // MICROSOFT_X64: [[IVAL:%.*]] = load i32, i32* // MICROSOFT_X64: [[OBJ_AS_STRUCT:%.*]] = bitcast %TSo20TemplatedConstructorV* [[OBJ]] to %struct.TemplatedConstructor* // MICROSOFT_X64: call %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* [[OBJ_AS_STRUCT]], i32 [[IVAL]]) // MICROSOFT_X64: ret void // MICROSOFT_X64-LABEL: define linkonce_odr dso_local %struct.TemplatedConstructor* @"??$?0UArgType@@@TemplatedConstructor@@QEAA@UArgType@@@Z"(%struct.TemplatedConstructor* nonnull returned align 4 dereferenceable(4) {{.*}}, i32 {{.*}}) let templated = TemplatedConstructor(ArgType()) }
apache-2.0
549baf0e7188af5f8b3acc24078bb21c
78.731092
248
0.749789
4.360294
false
false
false
false
MxABC/LBXAlertAction
AlertAction/UIWindow+LBXHierarchy.swift
1
1522
// // AlertAction.swift // // // Created by lbxia on 16/6/20. // Copyright © 2016年 lbx. All rights reserved. // import UIKit /** @abstract UIWindow hierarchy category. */ public extension UIWindow { /** @return Returns the current Top Most ViewController in hierarchy. */ public func topController()->UIViewController? { var topController = rootViewController while let presentedController = topController?.presentedViewController { topController = presentedController } return topController } /** @return Returns the topViewController in stack of topController. */ public func currentTopViewController()->UIViewController? { var currentViewController = topController() while currentViewController != nil && currentViewController is UITabBarController && (currentViewController as! UITabBarController).selectedViewController != nil { currentViewController = (currentViewController as! UITabBarController).selectedViewController } while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil { currentViewController = (currentViewController as! UINavigationController).topViewController } return currentViewController } }
mit
f6028eefd9af623bcc56689f87061726
30.645833
105
0.652403
7.032407
false
false
false
false
penguing27/MarkdownViewer
MarkdownViewer/ListViewController.swift
1
6336
// // ListViewController.swift // MarkdownViewer // // Created by Gen Inagaki on 2017/04/08. // Copyright © 2017年 Gen Inagaki. All rights reserved. // import UIKit import SwiftyDropbox class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var listActivityIndicatorView: UIActivityIndicatorView! var drb: DropboxAPI = DropboxAPI() var loadDataObserver: NSObjectProtocol? var path: String = "" var name: String = "Dropbox" let mySection = ["Folder", "File"] var directories: Array<Files.Metadata> = [] var files: Array<Files.Metadata> = [] private let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = self tableView.dataSource = self title = self.name listActivityIndicatorView.hidesWhenStopped = true listActivityIndicatorView.startAnimating() self.refresh() } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(self.loadDataObserver!) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Refresh private func refresh() { directories = [] files = [] drb.getList(path: self.path) loadDataObserver = NotificationCenter.default.addObserver( forName: .apiGetListComplete, object: nil, queue: nil, using: { notification in self.divideContents() self.tableView.reloadData() self.listActivityIndicatorView.stopAnimating() if self.tableView.refreshControl == nil { self.tableView.refreshControl = self.refreshControl self.refreshControl.addTarget(self, action: #selector(self.pullDownRefresh), for: .valueChanged) } self.refreshControl.endRefreshing() } ) } // Pull down refresh @objc private func pullDownRefresh() { NotificationCenter.default.removeObserver(self.loadDataObserver!) self.refresh() } // Divide directories and files private func divideContents() { for i in 0..<drb.entries.count { if drb.entries[i] is Files.FileMetadata { self.files.append(drb.entries[i]) } else { self.directories.append(drb.entries[i]) } } files.sort { $0.name < $1.name } directories.sort { $0.name < $1.name } } // Number of sections func numberOfSections(in tableView: UITableView) -> Int { return mySection.count } // Sections func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return mySection[section] } // Number of cells func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return self.directories.count } else if section == 1 { return self.files.count } else { return 0 } } // Display name to cells func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "FileListItem") { if indexPath.section == 0 { if directories.count != 0 { cell.textLabel?.text = self.directories[indexPath.row].name cell.accessoryType = UITableViewCellAccessoryType.disclosureIndicator } } else if indexPath.section == 1 { if files.count != 0 { cell.textLabel?.text = self.files[indexPath.row].name cell.accessoryType = UITableViewCellAccessoryType.none } } return cell } return UITableViewCell() } // Selected cell func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) if indexPath.section == 0 { // Directory let entry = self.directories[indexPath.row] let storyboard: UIStoryboard = self.storyboard! let selfView = storyboard.instantiateViewController(withIdentifier: "ListView") as! ListViewController selfView.path = entry.pathDisplay! selfView.name = entry.name self.navigationController?.pushViewController(selfView, animated: true) } else if indexPath.section == 1 { // File navigationItem.backBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: nil, action: nil) let entry = self.files[indexPath.row] self.performSegue(withIdentifier: "showFile", sender: entry) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showFile" { let vc = segue.destination as! FileViewController vc.entry = sender as! Files.Metadata } } // Log out @IBAction func logoutDropbox(_ sender: Any) { let alertController = UIAlertController(title: "", message: "Do you really want to log out?", preferredStyle: .actionSheet) let defaultAction = UIAlertAction(title: "OK", style: .default, handler: {(action: UIAlertAction!) -> Void in self.drb.logout() let storyboard: UIStoryboard = self.storyboard! let loginView = storyboard.instantiateViewController(withIdentifier: "LoginViewNavigation") as! UINavigationController self.present(loginView, animated: true, completion: nil) }) let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil) alertController.addAction(defaultAction) alertController.addAction(cancelAction) self.present(alertController, animated: true, completion: nil) } }
mit
1c7dd9cb914f8e2ecd52ae4883f0de09
36.035088
131
0.615506
5.233884
false
false
false
false
charlon/scout-ios
Scout/Error.swift
1
884
// // Error.swift // Scout // // Created by Charlon Palacay on 4/6/16. // Copyright © 2016 Charlon Palacay. All rights reserved. // struct Error { static let HTTPNotFoundError = Error(title: "Page Not Found", message: "There doesn’t seem to be anything here.") static let NetworkError = Error(title: "Can’t Connect", message: "TurbolinksDemo can’t connect to the server. Did you remember to start it?\nSee README.md for more instructions.") static let UnknownError = Error(title: "Unknown Error", message: "An unknown error occurred.") let title: String let message: String init(title: String, message: String) { self.title = title self.message = message } init(HTTPStatusCode: Int) { self.title = "Server Error" self.message = "The server returned an HTTP \(HTTPStatusCode) response." } }
apache-2.0
d28dd4ca0346c13f9683aa80efd0ad44
32.769231
183
0.664766
3.968326
false
false
false
false
taketo1024/SwiftyAlgebra
Sources/SwmCore/Polynomial/MultivariatePolynomial.swift
1
9018
// // MultivariatePolynomial.swift // // // Created by Taketo Sano on 2021/05/19. // public protocol MultivariatePolynomialIndeterminates: GenericPolynomialIndeterminate where Exponent == MultiIndex<NumberOfIndeterminates> { associatedtype NumberOfIndeterminates: SizeType static var isFinite: Bool { get } static var numberOfIndeterminates: Int { get } static func symbolOfIndeterminate(at i: Int) -> String static func degreeOfIndeterminate(at i: Int) -> Int } extension MultivariatePolynomialIndeterminates { public static var isFinite: Bool { NumberOfIndeterminates.isFixed } public static var numberOfIndeterminates: Int { NumberOfIndeterminates.intValue } public static func degreeOfIndeterminate(at i: Int) -> Int { 1 } public static func degreeOfMonomial(withExponent e: Exponent) -> Int { assert(!isFinite || Exponent.length <= numberOfIndeterminates) return e.indices.enumerated().sum { (i, k) in k * degreeOfIndeterminate(at: i) } } public static func descriptionOfMonomial(withExponent e: Exponent) -> String { let s = e.indices.enumerated().map{ (i, d) in (d != 0) ? Format.power(symbolOfIndeterminate(at: i), d) : "" }.joined() return s.isEmpty ? "1" : s } } public struct BivariatePolynomialIndeterminates<x: PolynomialIndeterminate, y: PolynomialIndeterminate>: MultivariatePolynomialIndeterminates { public typealias Exponent = MultiIndex<_2> public typealias NumberOfIndeterminates = _2 public static func degreeOfIndeterminate(at i: Int) -> Int { switch i { case 0: return x.degree case 1: return y.degree default: fatalError() } } public static func symbolOfIndeterminate(at i: Int) -> String { switch i { case 0: return x.symbol case 1: return y.symbol default: fatalError() } } } public struct TrivariatePolynomialIndeterminates<x: PolynomialIndeterminate, y: PolynomialIndeterminate, z: PolynomialIndeterminate>: MultivariatePolynomialIndeterminates { public typealias Exponent = MultiIndex<_3> public typealias NumberOfIndeterminates = _3 public static func degreeOfIndeterminate(at i: Int) -> Int { switch i { case 0: return x.degree case 1: return y.degree case 2: return z.degree default: fatalError() } } public static func symbolOfIndeterminate(at i: Int) -> String { switch i { case 0: return x.symbol case 1: return y.symbol case 2: return z.symbol default: fatalError() } } } public struct EnumeratedPolynomialIndeterminates<x: PolynomialIndeterminate, n: SizeType>: MultivariatePolynomialIndeterminates { public typealias Exponent = MultiIndex<n> public typealias NumberOfIndeterminates = n public static func degreeOfIndeterminate(at i: Int) -> Int { x.degree } public static func symbolOfIndeterminate(at i: Int) -> String { "\(x.symbol)\(Format.sub(i))" } } public protocol MultivariatePolynomialType: GenericPolynomialType where Indeterminate: MultivariatePolynomialIndeterminates { typealias NumberOfIndeterminates = Indeterminate.NumberOfIndeterminates } extension MultivariatePolynomialType { public static func indeterminate(_ i: Int, exponent: Int = 1) -> Self { let l = Indeterminate.isFinite ? Indeterminate.numberOfIndeterminates : i + 1 let indices = (0 ..< l).map{ $0 == i ? exponent : 0 } let I = MultiIndex<NumberOfIndeterminates>(indices) return .init(elements: [I : .identity] ) } public static var numberOfIndeterminates: Int { NumberOfIndeterminates.intValue } public static func monomial(withExponents I: [Int]) -> Self { monomial(withExponents: Exponent(I)) } public static func monomial(withExponents I: Exponent) -> Self { .init(elements: [I: .identity]) } public func coeff(_ exponent: Int...) -> BaseRing { self.coeff(Exponent(exponent)) } public func evaluate(by values: [BaseRing]) -> BaseRing { assert(!Indeterminate.isFinite || values.count <= Self.numberOfIndeterminates) return elements.sum { (I, a) in a * I.indices.enumerated().multiply{ (i, e) in values.count < i ? .zero : values[i].pow(e) } } } public func evaluate(by values: BaseRing...) -> BaseRing { evaluate(by: values) } } // MARK: MultivariateLaurentPolynomial public struct MultivariatePolynomial<R: Ring, xn: MultivariatePolynomialIndeterminates>: MultivariatePolynomialType { public typealias BaseRing = R public typealias Indeterminate = xn public let elements: [Exponent : R] public init(elements: [Exponent : R]) { assert(elements.keys.allSatisfy{ e in e.indices.allSatisfy{ $0 >= 0 } }) self.elements = elements } public var inverse: Self? { (isConst && constCoeff.isInvertible) ? .init(constCoeff.inverse!) : nil } public static func monomials<S: Sequence>(ofDegree deg: Int, usingIndeterminates indices: S) -> [Self] where S.Element == Int { assert(indices.isUnique) assert(indices.allSatisfy{ $0 >= 0 }) assert( deg == 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) != 0 } || deg > 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) > 0 } || deg < 0 && indices.allSatisfy{ i in Indeterminate.degreeOfIndeterminate(at: i) < 0 } ) func generate(_ deg: Int, _ indices: ArraySlice<Int>) -> [[Int]] { if indices.isEmpty { return deg == 0 ? [[]] : [] } let i = indices.last! let d = Indeterminate.degreeOfIndeterminate(at: i) let c = deg / d // = 0 when |deg| < |d| return (0 ... c).flatMap { e -> [[Int]] in generate(deg - e * d, indices.dropLast()).map { res in res + [e] } } } let exponents = generate(deg, ArraySlice(indices)) let l = indices.max() ?? 0 return exponents.map { list -> Self in let e = Array(repeating: 0, count: l + 1).with { arr in for (i, d) in zip(indices, list) { arr[i] = d } } return monomial(withExponents: Exponent(e)) } } public static func elementarySymmetricPolynomial<S: Sequence>(ofDegree deg: Int, usingIndeterminates indices: S) -> Self where S.Element == Int { assert(indices.isUnique) assert(indices.allSatisfy{ $0 >= 0 }) let n = indices.count if deg > n { return .zero } let max = indices.max() ?? 0 let indexer = indices.makeIndexer() let exponents = (0 ..< n).combinations(ofCount: deg).map { list -> [Int] in // e.g. [0, 1, 3] -> (1, 1, 0, 1) let set = Set(list) return (0 ... max).map { i in set.contains(indexer(i) ?? -1) ? 1 : 0 } } return .init(elements: Dictionary(exponents.map{ (Exponent($0), .identity) } )) } public static var symbol: String { Indeterminate.isFinite ? "\(R.symbol)[\( (0 ..< numberOfIndeterminates).map{ i in Indeterminate.symbolOfIndeterminate(at: i)}.joined(separator: ", ") )]" : "\(R.symbol)[\( (0 ..< 3).map{ i in Indeterminate.symbolOfIndeterminate(at: i)}.joined(separator: ", ") ), …]" } } extension MultivariatePolynomial where Indeterminate.NumberOfIndeterminates: FixedSizeType { public static func monomials(ofDegree deg: Int) -> [Self] { monomials(ofDegree: deg, usingIndeterminates: 0 ..< numberOfIndeterminates) } public static func elementarySymmetricPolynomial(ofDegree deg: Int) -> Self { elementarySymmetricPolynomial(ofDegree: deg, usingIndeterminates: 0 ..< numberOfIndeterminates) } } extension MultivariatePolynomial: ExpressibleByIntegerLiteral where R: ExpressibleByIntegerLiteral {} // MARK: MultivariateLaurentPolynomial public struct MultivariateLaurentPolynomial<R: Ring, xn: MultivariatePolynomialIndeterminates>: MultivariatePolynomialType { public typealias BaseRing = R public typealias Indeterminate = xn public let elements: [Exponent : R] public init(elements: [Exponent : R]) { self.elements = elements } public var inverse: Self? { if isMonomial && leadCoeff.isInvertible { let d = leadExponent let a = leadCoeff return .init(elements: [-d: a.inverse!]) } else { return nil } } }
cc0-1.0
c1f2c33c8a6e9a660fc02e4dc1e19f33
34.356863
172
0.617347
4.630714
false
false
false
false
gupuru/StreetPassBLE-iOS
Example/ViewController.swift
1
4758
// // ViewController.swift // Example // // Created by 新見晃平 on 2016/02/23. // Copyright © 2016年 kohei Niimi. All rights reserved. // import UIKit import StreetPass class ViewController: UIViewController, StreetPassDelegate, UITextFieldDelegate { @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var logTextView: UITextView! @IBOutlet weak var startStopUIButton: UIButton! fileprivate let street: StreetPass = StreetPass() fileprivate var startStopIsOn: Bool = false //MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() // アラート表示の許可をもらう let setting = UIUserNotificationSettings(types: [.sound, .alert], categories: nil) UIApplication.shared.registerUserNotificationSettings(setting) //delegateなど street.delegate = self nameTextField.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func onTouchUpInsideStartStopButton(_ sender: UIButton) { if !startStopIsOn { //buttonの背景色, 文字変更 startStopIsOn = true startStopUIButton.setTitle("Stop", for: UIControlState()) startStopUIButton.backgroundColor = Color().stop() logTextView.text = "" setLogText("Start StreetPass") view.endEditing(true) //textfieldに入っている文言取得 var sendData: String = "" if nameTextField.text != nil { sendData = nameTextField.text! } //bleの設定 let streetPassSettings: StreetPassSettings = StreetPassSettings() .sendData(sendData) .allowDuplicates(false) .isConnect(true) //bleライブラリ開始 street.start(streetPassSettings) } else { //buttonの背景色, 文字変更 startStopIsOn = false startStopUIButton.setTitle("Start", for: UIControlState()) startStopUIButton.backgroundColor = Color().main() setLogText("Stop StreetPass") //bleライブラリ停止 street.stop() } } //MARK: - StreetPassDelegate func centralManagerState(_ state: CentralManagerState) { switch state { case .poweredOn: setLogText("Start central manager") default: setLogText("Failure central manager") break } } func peripheralManagerState(_ state: PeripheralManagerState) { switch state { case .poweredOn: setLogText("Start peripheral manager") break default: setLogText("Failure peripheral manager") break } } func advertisingState() { setLogText("Now, Advertising") } func peripheralDidAddService() { setLogText("Start Service") } func deviceConnectedState(_ connectedDeviceInfo : ConnectedDeviceInfo) { if let status = connectedDeviceInfo.status { switch status { case .success: setLogText("Success Device Connect") case .disConected: setLogText("DisConnect Device") case .failure: setLogText("Connect Failer") } } } public func streetPassError(_ error: Error) { setLogText("error.localizedDescription") } func nearByDevices(_ deveiceInfo: DeveiceInfo) { setLogText("Near by device: \(deveiceInfo.deviceName)") } func receivedData(_ receivedData: ReceivedData) { if let data = receivedData.data { setLogText("Receive Data: \(data)") // Notificationの生成する let myNotification: UILocalNotification = UILocalNotification() myNotification.alertBody = data myNotification.fireDate = Date(timeIntervalSinceNow: 1) myNotification.timeZone = TimeZone.current UIApplication.shared.scheduleLocalNotification(myNotification) } } //MARK: - UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool{ // キーボード閉じる textField.resignFirstResponder() return true } //MARK: - Sub Methods /** textViewに値をいれる */ fileprivate func setLogText(_ text: String) { DispatchQueue.main.async { let log: String = self.logTextView.text self.logTextView.text = log + text + "\n" } } }
mit
f1de6fbc2295087a57a23b49e8e6a61a
28.632258
90
0.592423
5.365654
false
false
false
false
rnystrom/GitHawk
Classes/Search/SearchRecentSectionController.swift
1
2737
// // SearchRecentSectionController.swift // Freetime // // Created by Ryan Nystrom on 9/4/17. // Copyright © 2017 Ryan Nystrom. All rights reserved. // import Foundation import IGListKit import SwipeCellKit protocol SearchRecentSectionControllerDelegate: class { func didSelect(recentSectionController: SearchRecentSectionController, viewModel: SearchRecentViewModel) func didDelete(recentSectionController: SearchRecentSectionController, viewModel: SearchRecentViewModel) } // bridge to NSString for NSObject conformance final class SearchRecentSectionController: ListGenericSectionController<SearchRecentViewModel>, SwipeCollectionViewCellDelegate { weak var delegate: SearchRecentSectionControllerDelegate? lazy var recentStore = SearchRecentStore() init(delegate: SearchRecentSectionControllerDelegate) { self.delegate = delegate super.init() } override func sizeForItem(at index: Int) -> CGSize { return collectionContext.cellSize( with: Styles.Sizes.tableCellHeight + Styles.Sizes.rowSpacing * 2 ) } override func cellForItem(at index: Int) -> UICollectionViewCell { guard let cell = collectionContext?.dequeueReusableCell(of: SearchRecentCell.self, for: self, at: index) as? SearchRecentCell else { fatalError("Missing context or wrong cell type") } cell.delegate = self cell.configure(viewModel: searchViewModel) return cell } override func didSelectItem(at index: Int) { collectionContext?.deselectItem(at: index, sectionController: self, animated: trueUnlessReduceMotionEnabled) delegate?.didSelect(recentSectionController: self, viewModel: searchViewModel) } // MARK: SwipeCollectionViewCellDelegate func collectionView(_ collectionView: UICollectionView, editActionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> [SwipeAction]? { guard orientation == .right else { return nil } let action = DeleteSwipeAction { [weak self] _, _ in guard let strongSelf = self, let object = strongSelf.object else { return } strongSelf.delegate?.didDelete(recentSectionController: strongSelf, viewModel: object) } return [action] } func collectionView(_ collectionView: UICollectionView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeTableOptions { var options = SwipeTableOptions() options.expansionStyle = .destructive return options } // MARK: Private API var searchViewModel: SearchRecentViewModel { return object ?? SearchRecentViewModel(query: .search("")) } }
mit
8e36b3620d08a81e08d45b131c21c22e
36.479452
173
0.729898
5.595092
false
false
false
false
offfffz/PHAssetImageResizer-Bolts
ImageResizer.swift
1
2384
// // ImageResizer.swift // // Created by offz on 7/21/2558 BE. // Copyright (c) 2558 off. All rights reserved. // import Bolts import Photos import FCFileManager public class ImageResizer { let maxConcurrentCount: Int let targetFolderPath: String let sizeToFit: CGSize lazy var imageProcessingQueue: NSOperationQueue = { let queue = NSOperationQueue() queue.qualityOfService = NSQualityOfService.Background queue.maxConcurrentOperationCount = self.maxConcurrentCount return queue }() public init(targetFolderPath: String, sizeToFit: CGSize, maxConcurrentCount: Int = 3) { self.maxConcurrentCount = maxConcurrentCount self.targetFolderPath = targetFolderPath self.sizeToFit = sizeToFit } public func resizeAndCacheAssets(#assets: [PHAsset]) -> BFTask { let imgManager = PHImageManager.defaultManager() var tasks = [BFTask]() var counter = 0 let imageRequestOptions = PHImageRequestOptions() imageRequestOptions.resizeMode = .Exact imageRequestOptions.synchronous = true for asset in assets { let fileName = "\(counter++).jpg" let filePath = targetFolderPath.stringByAppendingPathComponent(fileName) let completionSource = BFTaskCompletionSource() imageProcessingQueue.addOperation(NSBlockOperation(block: { imgManager.requestImageForAsset(asset, targetSize: sizeToFit, contentMode: PHImageContentMode.AspectFit, options: imageRequestOptions, resultHandler: { [unowned self](image, _) -> Void in let imageData = UIImageJPEGRepresentation(image, 0.8) if imageData != nil && FCFileManager.writeFileAtPath(filePath, content: imageData) { completionSource.setResult(filePath) } else { completionSource.setError(NSError(domain: "ImageResizer", code: 101, userInfo:[NSLocalizedDescriptionKey: "Cannot write image to \(filePath)"])) } }) })) tasks.append(completionSource.task) } return BFTask(forCompletionOfAllTasksWithResults: tasks) } }
mit
db644730cb6b6492190a88cfca7b09ab
35.692308
167
0.618289
5.96
false
false
false
false
wisonlin/TimeSound
TimeSound/TimeSound/TSRemindCreateViewController.swift
1
2967
// // TSRemindCreateViewController.swift // TimeSound // // Created by wison on 3/6/16. // Copyright © 2016 HomeStudio. All rights reserved. // import UIKit import RealmSwift class TSRemindCreateViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TSSoundSelectDelegate { // MARK: Properties @IBOutlet weak var tableView : UITableView! @IBOutlet weak var timePicker : UIDatePicker! var time = NSDate(timeIntervalSinceNow: 0) var soundChanged = false var selectedSound = TSSoundManger().soundList.first! // MARK: View Life Cycle override func viewWillAppear(animated: Bool) { if soundChanged { self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: .Fade) } } // MARK: - Actions @IBAction func onSave() { let remind = TSRemind(value: ["time" : time, "sound" : selectedSound, "enable" : true]) let realm = try! Realm() try! realm.write({ realm.add(remind) }) self.navigationController?.popViewControllerAnimated(true) NSNotificationCenter.defaultCenter().postNotificationName("TSDataChanged", object: nil) } @IBAction func onTimePickerValueChanged() { time = (self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)) as! TSTimePickerCell).timePicker!.date } // MARK: - UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 2 } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { switch indexPath.row { case 0: return 216 case 1: return 44 default: return 0 } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { var cell : UITableViewCell! switch indexPath.row { case 0: cell = tableView.dequeueReusableCellWithIdentifier("TSTimePickerCell")! case 1: cell = tableView.dequeueReusableCellWithIdentifier("TSSoundCell")! cell.textLabel!.text = "Sound" cell.detailTextLabel!.text = selectedSound default: break } return cell } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { (segue.destinationViewController as! TSSoundSelectViewController).delegate = self let selectIndex = TSSoundManger().soundList.indexOf(selectedSound)! (segue.destinationViewController as! TSSoundSelectViewController).selectIndex = selectIndex } // MARK: - TSSoundSelectDelegate func onSelectSound(sender: AnyObject, selectedSound: String) { soundChanged = true self.selectedSound = selectedSound } }
mit
a672257fd3b86797d53c7de4e66ef67b
31.593407
129
0.653742
5.392727
false
false
false
false
frootloops/swift
test/SILGen/guaranteed_self.swift
1
26248
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s protocol Fooable { init() func foo(_ x: Int) mutating func bar() mutating func bas() var prop1: Int { get set } var prop2: Int { get set } var prop3: Int { get nonmutating set } } protocol Barrable: class { init() func foo(_ x: Int) func bar() func bas() var prop1: Int { get set } var prop2: Int { get set } var prop3: Int { get set } } struct S: Fooable { var x: C? // Make the type nontrivial, so +0/+1 is observable. // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S init() {} // TODO: Way too many redundant r/r pairs here. Should use +0 rvalues. // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () { // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: copy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] func foo(_ x: Int) { self.foo(x) } func foooo(_ x: (Int, Bool)) { self.foooo(x) } // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> () // CHECK: bb0([[SELF:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF]] mutating func bar() { self.bar() } // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> () // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: copy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] func bas() { self.bas() } var prop1: Int = 0 // Getter for prop1 // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] // Setter for prop1 // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // materializeForSet for prop1 // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop1Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] var prop2: Int { // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] get { return 0 } // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> () // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop2Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) set { } } var prop3: Int { // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int // CHECK: bb0([[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] get { return 0 } // CHECK-LABEL: sil hidden @_T015guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self1SV5prop3Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S): // CHECK-NOT: destroy_value [[SELF]] nonmutating set { } } } // Witness thunk for nonmutating 'foo' // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for mutating 'bar' // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () { // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: load [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for 'bas', which is mutating in the protocol, but nonmutating // in the implementation // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK: end_borrow [[SELF]] // CHECK-NOT: destroy_value [[SELF]] // Witness thunk for prop1 getter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF]] // Witness thunk for prop1 setter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop1 materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop1SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 getter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 setter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop2 materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop2SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) { // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 getter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 nonmutating setter // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness thunk for prop3 nonmutating materializeForSet // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S): // CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } // end sil function '_T015guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW' // // TODO: Expected output for the other cases // struct AO<T>: Fooable { var x: T? init() {} // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK: apply {{.*}} [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } func foo(_ x: Int) { self.foo(x) } mutating func bar() { self.bar() } // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] func bas() { self.bas() } var prop1: Int = 0 var prop2: Int { // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int { // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] get { return 0 } set { } } var prop3: Int { // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] get { return 0 } // CHECK-LABEL: sil hidden @_T015guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK-LABEL: sil hidden [transparent] @_T015guaranteed_self2AOV5prop3Sivm : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed AO<T>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>): // CHECK-NOT: destroy_addr [[SELF_ADDR]] // CHECK: } nonmutating set { } } } // Witness for nonmutating 'foo' // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> () // CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>): // CHECK: apply {{.*}} [[SELF_ADDR]] // CHECK-NOT: destroy_addr [[SELF_ADDR]] // Witness for 'bar', which is mutating in protocol but nonmutating in impl // CHECK-LABEL: sil private [transparent] [thunk] @_T015guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (@inout AO<τ_0_0>) -> () // CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>): // -- NB: This copy is not necessary, since we're willing to assume an inout // parameter is not mutably aliased. // CHECK: apply {{.*}}([[SELF_ADDR]]) // CHECK-NOT: destroy_addr [[SELF_ADDR]] class C: Fooable, Barrable { // Allocating initializer // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C // CHECK: [[SELF1:%.*]] = alloc_ref $C // CHECK-NOT: [[SELF1]] // CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]]) // CHECK-NOT: [[SELF2]] // CHECK: return [[SELF2]] // Initializing constructors still have the +1 in, +1 out convention. // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C { // CHECK: bb0([[SELF:%.*]] : @owned $C): // CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]] // CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]] // CHECK: destroy_value [[MARKED_SELF]] // CHECK: return [[MARKED_SELF_RESULT]] // CHECK: } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc' // @objc thunk for initializing constructor // CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C // CHECK: bb0([[SELF:%.*]] : @owned $C): // CHECK-NOT: copy_value [[SELF]] // CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]]) // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF2]] // CHECK: return [[SELF2]] // CHECK: } // end sil function '_T015guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo' @objc required init() {} // CHECK-LABEL: sil hidden @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $C): // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F' // CHECK-LABEL: sil hidden [thunk] @_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () { // CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } // end sil function '_T015guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo' @objc func foo(_ x: Int) { self.foo(x) } @objc func bar() { self.bar() } @objc func bas() { self.bas() } // CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int // CHECK: bb0([[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}}([[BORROWED_SELF_COPY]]) // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-LABEL: sil hidden [transparent] [thunk] @_T015guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]] // CHECK: apply {{.*}} [[BORROWED_SELF_COPY]] // CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } @objc var prop1: Int = 0 @objc var prop2: Int { get { return 0 } set {} } @objc var prop3: Int { get { return 0 } set {} } } class D: C { // CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D // CHECK: [[SELF1:%.*]] = alloc_ref $D // CHECK-NOT: [[SELF1]] // CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]]) // CHECK-NOT: [[SELF1]] // CHECK-NOT: [[SELF2]] // CHECK: return [[SELF2]] // CHECK-LABEL: sil hidden @_T015guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D // CHECK: bb0([[SELF:%.*]] : @owned $D): // CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D } // CHECK-NEXT: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]] // CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]] // CHECK-NEXT: store [[SELF]] to [init] [[PB]] // CHECK-NOT: [[PB]] // CHECK: [[SELF1:%.*]] = load [take] [[PB]] // CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]] // CHECK-NOT: [[PB]] // CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]]) // CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]] // CHECK-NEXT: store [[SELF2]] to [init] [[PB]] // CHECK-NOT: [[PB]] // CHECK-NOT: [[SELF1]] // CHECK-NOT: [[SUPER1]] // CHECK-NOT: [[SELF2]] // CHECK-NOT: [[SUPER2]] // CHECK: [[SELF_FINAL:%.*]] = load [copy] [[PB]] // CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]] // CHECK-NEXT: return [[SELF_FINAL]] required init() { super.init() } // CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @_T015guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> () // CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $D): // CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] // CHECK: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF_COPY]] // CHECK-NOT: destroy_value [[SELF]] // CHECK: } dynamic override func foo(_ x: Int) { self.foo(x) } } func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) { return (S.foo /*, s.foo*/) } func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) { return (AO.foo /*, ao.foo*/) } // ---------------------------------------------------------------------------- // Make sure that we properly translate in_guaranteed parameters // correctly if we are asked to. // ---------------------------------------------------------------------------- // CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @_T015guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Sequence) (@in FakeElement, @in_guaranteed FakeArray) -> () { // CHECK: bb0([[ARG0_PTR:%.*]] : @trivial $*FakeElement, [[ARG1_PTR:%.*]] : @trivial $*FakeArray): // CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]] // CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement // CHECK: [[FUN:%.*]] = function_ref @_{{.*}} // CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]]) class Z {} public struct FakeGenerator {} public struct FakeArray { var z = Z() } public struct FakeElement {} public protocol FakeGeneratorProtocol { associatedtype Element } extension FakeGenerator : FakeGeneratorProtocol { public typealias Element = FakeElement } public protocol SequenceDefaults { associatedtype Element associatedtype Generator : FakeGeneratorProtocol } extension SequenceDefaults { public func _constrainElement(_: FakeGenerator.Element) {} } public protocol Sequence : SequenceDefaults { func _constrainElement(_: Element) } extension FakeArray : Sequence { public typealias Element = FakeElement public typealias Generator = FakeGenerator func _containsElement(_: Element) {} } // ----------------------------------------------------------------------------- // Make sure that we do not emit extra copy_values when accessing let fields of // guaranteed parameters. // ----------------------------------------------------------------------------- class Kraken { func enrage() {} } func destroyShip(_ k: Kraken) {} class LetFieldClass { let letk = Kraken() var vark = Kraken() // CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () { // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass): // CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Kraken // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]] // CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]]) // CHECK-NEXT: end_borrow [[KRAKEN]] from [[WRITE]] // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]] // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken } // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]] // CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [dynamic] [[KRAKEN_ADDR]] : $*Kraken // CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]] // CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]] // CHECK-NEXT: end_access [[READ]] : $*Kraken // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: destroy_value [[KRAKEN_BOX]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: tuple // CHECK-NEXT: return func letkMethod() { letk.enrage() let ll = letk destroyShip(ll) var lv = letk destroyShip(lv) } // CHECK-LABEL: sil hidden @_T015guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () { // CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass): // CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK-NEXT: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[BORROWED_KRAKEN]] // CHECK-NEXT: apply [[KRAKEN_METH]]([[BORROWED_KRAKEN]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = copy_value [[BORROWED_KRAKEN]] // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]] // CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken } // CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]] // CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken // CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]]) // CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]] // CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken // CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]] // CHECK-NEXT: end_access [[WRITE]] : $*Kraken // CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @_T015guaranteed_self11destroyShipyAA6KrakenCF : $@convention(thin) (@owned Kraken) -> () // CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]]) // CHECK-NEXT: destroy_value [[KRAKEN_BOX]] // CHECK-NEXT: destroy_value [[KRAKEN]] // CHECK-NEXT: tuple // CHECK-NEXT: return func varkMethod() { vark.enrage() let vl = vark destroyShip(vl) var vv = vark destroyShip(vv) } } // ----------------------------------------------------------------------------- // Make sure that in all of the following cases find has only one copy_value in it. // ----------------------------------------------------------------------------- class ClassIntTreeNode { let value : Int let left, right : ClassIntTreeNode init() {} // CHECK-LABEL: sil hidden @_T015guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode { // CHECK-NOT: destroy_value // CHECK: copy_value // CHECK-NOT: copy_value // CHECK-NOT: destroy_value // CHECK: return func find(_ v : Int) -> ClassIntTreeNode { if v == value { return self } if v < value { return left.find(v) } return right.find(v) } }
apache-2.0
3c118ba723c68a66ab710b51c2d9c414
46.539855
268
0.592523
3.426296
false
false
false
false
HighBay/EasyTimer
EasyTimer/ViewController.swift
2
1463
// // ViewController.swift // EasyTimer // // Created by Niklas Fahl on 3/2/16. // Copyright © 2016 High Bay. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // EXAMPLES // Repeat but also execute once immediately let _ = 2.second.interval { print("Repeat every 2 seconds but also execute once right away.") } let _ = 2.second.interval { (timer: Timer) -> Void in print("Repeat every 2 seconds but also execute once right away.") } // Repeat after delay let timer2 = 2.second.delayedInterval { () -> Void in print("Repeat every 2 seconds after 2 second delay.") } timer2.stop() // Delay something let _ = 2.second.delay { () -> Void in print("2 seconds later...") } // Essentially equivalent to delayedInterval let timer = 3.minute.timer(repeats: true, delays: true) { print("3 minutes later...") } timer.start() } func doSomething() { print("Hello") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
bsd-3-clause
2802c73481448e1a6c9f1d81de5254a1
26.074074
80
0.560192
4.777778
false
false
false
false
Burning-Man-Earth/iBurn-iOS
iBurn/BRCDataImporter.swift
1
2768
// // BRCDataImporter.swift // iBurn // // Created by Chris Ballinger on 7/30/17. // Copyright © 2017 Burning Man Earth. All rights reserved. // import Foundation import Mapbox import CocoaLumberjack extension BRCDataImporter { /** This is where Mapbox stores its tile cache */ private static var mapTilesDirectory: URL { guard var cachesUrl = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first, let bundleId = Bundle.main.object(forInfoDictionaryKey: kCFBundleIdentifierKey as String) as? String else { fatalError("Could not get map tiles directory") } cachesUrl.appendPathComponent(bundleId) cachesUrl.appendPathComponent(".mapbox") return cachesUrl } /** Downloads offline tiles directly from official Mapbox server */ @objc public static func downloadMapboxOfflineTiles() { let storage = MGLOfflineStorage.shared let styleURL = URL(string: kBRCMapBoxStyleURL)! let bounds = MGLMapView.brc_bounds let region = MGLTilePyramidOfflineRegion(styleURL: styleURL, bounds: bounds, fromZoomLevel: 13, toZoomLevel: 17) storage.addPack(for: region, withContext: Data(), completionHandler: { pack, error in if let pack = pack { pack.resume() } else if let error = error { DDLogError("Error downloading tiles: \(error)") } }) } /** Copies the bundled Mapbox "offline" tiles to where Mapbox expects them */ @objc public static func copyBundledTilesIfNeeded() { var tilesUrl = mapTilesDirectory if FileManager.default.fileExists(atPath: tilesUrl.path) { DDLogVerbose("Tiles already exist at path \(tilesUrl.path)") // Tiles already exist return } let bundle = Bundle.brc_tilesCache DDLogInfo("Cached tiles not found, copying from bundle... \(bundle.bundleURL) ==> \(tilesUrl)") do { let parentDir = tilesUrl.deletingLastPathComponent() try FileManager.default.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil) try FileManager.default.copyItem(atPath: bundle.bundlePath, toPath: tilesUrl.path) var resourceValues = URLResourceValues() resourceValues.isExcludedFromBackup = true try tilesUrl.setResourceValues(resourceValues) } catch let error { DDLogError("Error copying bundled tiles: \(error)") } } /** Downloads offline tiles from iBurn server */ public static func downloadOfflineTiles() { // TODO: download our own offline tiles } }
mpl-2.0
ef492aa6aaeaebe6f0fe960ab07a84c6
37.430556
121
0.650163
4.985586
false
false
false
false
markusschlegel/DejaTextView
DejaTextView.swift
1
45921
// // DejaTextView.swift // DejaTextView // // Created by Markus Schlegel on 17/05/15. // Copyright (c) 2015 Markus Schlegel. All rights reserved. // import UIKit let animation_duration: Double = 0.2 let animation_spring_damping: CGFloat = 0.8 let grabber_frame: CGRect = CGRectMake(0, 0, 88, 43) let selection_alpha: CGFloat = 0.4 let caret_tap_radius: CGFloat = 20.0 let repositioning_timer_duration: Double = 1.0 let start_grabber_y_offset: CGFloat = 20.0 // while dragging, the start grabber will be vertically positioned at this offset (0 is top edge) let end_grabber_y_offset: CGFloat = 23.0 // while dragging, the end grabber will be vertically positioned at this offset (0 is top edge) let start_grabber_tip_selection_offset: CGFloat = 10.0 // while dragging, the selection start will be set to the tip position + this offset let end_grabber_tip_selection_offset: CGFloat = 10.0 // while dragging, the selection end will be set to the tip position - this offset /// A UITextView subclass with improved text selection and cursor movement tools public class DejaTextView: UITextView { private enum DejaTextGrabberTipDirection { case Down case Up } private enum DejaTextGrabberTipAlignment { case Left case Right case Center } private struct CurvyPath { let startPoint: (CGFloat, CGFloat) let curves: [((CGFloat, CGFloat), (CGFloat, CGFloat), (CGFloat, CGFloat))] func toBezierPath() -> UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPointMake(self.startPoint.0, self.startPoint.1)) for ((x, y), (cp1x, cp1y), (cp2x, cp2y)) in self.curves { path.addCurveToPoint(CGPointMake(x, y), controlPoint1: CGPointMake(cp1x, cp1y), controlPoint2: CGPointMake(cp2x, cp2y)) } return path } func toBezierPath() -> CGPathRef { return self.toBezierPath().CGPath } } private struct LineyPath { let startPoint: (CGFloat, CGFloat) let linePoints: [(CGFloat, CGFloat)] func toBezierPath() -> UIBezierPath { let path = UIBezierPath() path.moveToPoint(CGPointMake(self.startPoint.0, self.startPoint.1)) for (x, y) in self.linePoints { path.addLineToPoint(CGPointMake(x, y)) } return path } func toBezierPath() -> CGPathRef { return self.toBezierPath().CGPath } } private class DejaTextGrabber: UIView { let tipDirection: DejaTextGrabberTipDirection var tipPosition = CGPointZero var extended = true var forcedTipAlignment: DejaTextGrabberTipAlignment? = nil private let _body = CAShapeLayer() private let _leftTriangle = CAShapeLayer() private let _rightTriangle = CAShapeLayer() private let _separator = CAShapeLayer() func transform(animated animated: Bool) { var newOrigin = self.tipPosition if let superView = self.superview { let xtreshold = self.frame.size.width / 2.0 var newPaths: (CGPath, CGPathRef?, CGPathRef?, CGPathRef?) let alignment: DejaTextGrabberTipAlignment if self.forcedTipAlignment != nil { alignment = self.forcedTipAlignment! } else { if self.tipPosition.x < xtreshold { alignment = .Left } else if self.tipPosition.x > superView.frame.size.width - xtreshold { alignment = .Right } else { alignment = .Center } } if alignment == .Left { newOrigin.x -= 14.0 } else if alignment == .Right { newOrigin.x -= 74.0 } else { newOrigin.x -= 44.0 } newPaths = self.paths(tipDirection: self.tipDirection, tipAlignment: alignment, extended: self.extended) if self.tipDirection == .Down { newOrigin.y -= 43.0 } // Morph animation _body.removeAllAnimations() let morphAnimation = CABasicAnimation(keyPath: "path") morphAnimation.duration = animation_duration morphAnimation.fromValue = _body.presentationLayer()!.path morphAnimation.toValue = newPaths.0 _body.path = newPaths.0 if animated { _body.addAnimation(morphAnimation, forKey: "morph") } // Fade animation let fadeAnimation = CABasicAnimation(keyPath: "opacity") fadeAnimation.duration = animation_duration fadeAnimation.fromValue = _leftTriangle.presentationLayer()!.opacity if let left = newPaths.1, right = newPaths.2, separator = newPaths.3 { fadeAnimation.toValue = 1.0 CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) _leftTriangle.opacity = 1.0 _rightTriangle.opacity = 1.0 _separator.opacity = 1.0 CATransaction.commit() _leftTriangle.path = left _rightTriangle.path = right _separator.path = separator } else { fadeAnimation.toValue = 0.0 CATransaction.begin() CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions) _leftTriangle.opacity = 0.0 _rightTriangle.opacity = 0.0 _separator.opacity = 0.0 CATransaction.commit() } if animated && _leftTriangle.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue { _leftTriangle.addAnimation(fadeAnimation, forKey: "fade"); } if animated && _rightTriangle.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue { _rightTriangle.addAnimation(fadeAnimation, forKey: "fade"); } if animated && _separator.animationForKey("fade") == nil && fadeAnimation.fromValue !== fadeAnimation.toValue { _separator.addAnimation(fadeAnimation, forKey: "fade"); } // Frame (position) animation let a: (Void) -> Void = { var newFrame = self.frame newFrame.origin = newOrigin self.frame = newFrame } if animated { UIView.animateWithDuration(animation_duration, delay: 0.0, usingSpringWithDamping: animation_spring_damping, initialSpringVelocity: 0.0, options: [], animations: a, completion: nil) } else { a() } } } init(frame: CGRect, tipDirection: DejaTextGrabberTipDirection) { self.tipDirection = tipDirection super.init(frame: frame) _body.frame = grabber_frame _body.fillColor = UIColor.blackColor().CGColor _body.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).0 _leftTriangle.frame = grabber_frame _leftTriangle.fillColor = UIColor.whiteColor().CGColor _leftTriangle.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).1 _rightTriangle.frame = grabber_frame _rightTriangle.fillColor = UIColor.whiteColor().CGColor _rightTriangle.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).2 _separator.frame = grabber_frame _separator.fillColor = UIColor.whiteColor().CGColor _separator.path = self.paths(tipDirection: self.tipDirection, tipAlignment: .Center, extended: true).3 self.layer.addSublayer(_body) self.layer.addSublayer(_leftTriangle) self.layer.addSublayer(_rightTriangle) self.layer.addSublayer(_separator) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func intrinsicContentSize() -> CGSize { return grabber_frame.size } override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool { if self.extended { return CGRectContainsPoint(self.bounds, point) } else { return CGPathContainsPoint(_body.path, nil, point, false) } } func paths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment, extended: Bool) -> (CGPath, CGPath?, CGPath?, CGPath?) { if extended { return self.extendedPaths(tipDirection: tipDirection, tipAlignment: tipAlignment) } else { return self.unextendedPaths(tipDirection: tipDirection, tipAlignment: tipAlignment) } } func extendedPaths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment) -> (CGPath, CGPath?, CGPath?, CGPath?) { let l, r, c : LineyPath if tipDirection == .Up { l = LineyPath(startPoint: (18, 26), linePoints: [ (25, 19), (25, 33), (18, 26), ]) r = LineyPath(startPoint: (69, 26), linePoints: [ (62, 33), (62, 19), (69, 26), ]) c = LineyPath(startPoint: (43.5, 0), linePoints: [ (44.5, 0), (44.5, 43), (43.5, 43), (43.5, 0), ]) } else { l = LineyPath(startPoint: (18, 26-9), linePoints: [ (25, 19-9), (25, 33-9), (18, 26-9), ]) r = LineyPath(startPoint: (69, 26-9), linePoints: [ (62, 33-9), (62, 19-9), (69, 26-9), ]) c = LineyPath(startPoint: (43.5, 0), linePoints: [ (44.5, 0), (44.5, 43), (43.5, 43), (43.5, 0), ]) } let left: CGPathRef = l.toBezierPath() let right: CGPathRef = r.toBezierPath() let separator: CGPathRef = c.toBezierPath() if tipDirection == .Up && tipAlignment == .Left { return (self.extendedTipUpLeftPaths(), left, right, separator) } else if tipDirection == .Up && tipAlignment == .Right { return (self.extendedTipUpRightPaths(), left, right, separator) } else if tipDirection == .Up && tipAlignment == .Center { return (self.extendedTipUpPaths(), left, right, separator) } else if tipDirection == .Down && tipAlignment == .Left { return (self.extendedTipDownLeftPaths(), left, right, separator) } else if tipDirection == .Down && tipAlignment == .Right { return (self.extendedTipDownRightPaths(), left, right, separator) } else { return (self.extendedTipDownPaths(), left, right, separator) } } func unextendedPaths(tipDirection tipDirection: DejaTextGrabberTipDirection, tipAlignment: DejaTextGrabberTipAlignment) -> (CGPath, CGPath?, CGPath?, CGPath?) { if tipDirection == .Up && tipAlignment == .Left { return (self.unextendedTipUpLeftPaths(), nil, nil, nil) } else if tipDirection == .Up && tipAlignment == .Right { return (self.unextendedTipUpRightPaths(), nil, nil, nil) } else if tipDirection == .Up && tipAlignment == .Center { return (self.unextendedTipUpPaths(), nil, nil, nil) } else if tipDirection == .Down && tipAlignment == .Left { return (self.unextendedTipDownLeftPaths(), nil, nil, nil) } else if tipDirection == .Down && tipAlignment == .Right { return (self.unextendedTipDownRightPaths(), nil, nil, nil) } else { return (self.unextendedTipDownPaths(), nil, nil, nil) } } func extendedTipUpPaths() -> CGPathRef { let b = CurvyPath(startPoint: (44, 0), curves: [ ((53, 9), (44, 0), (53, 9)), ((72, 9), (53, 9), (72, 9)), ((88, 26), (81, 9), (88, 17)), ((72, 43), (88, 35), (81, 43)), ((16, 43), (72, 43), (16, 43)), ((0, 26), (7, 43), (0, 35)), ((16, 9), (0, 17), (7, 9)), ((35, 9), (16, 9), (35, 9)), ((44, 0), (35, 9), (44, 0)), ]) return b.toBezierPath() } func extendedTipUpLeftPaths() -> CGPathRef { let b = CurvyPath(startPoint: (14, 0), curves: [ ((22, 9), (16, 2), (14, 9)), ((72, 9), (22, 9), (72, 9)), ((88, 26), (81, 9), (88, 17)), ((72, 43), (88, 35), (81, 43)), ((16, 43), (72, 43), (16, 43)), ((0, 26), (7, 43), (0, 35)), ((14, 0), (0, 17), (3, 10)), ((14, 0), (14, 0), (14, 0)), ((14, 0), (14, 0), (14, 0)), ]) return b.toBezierPath() } func extendedTipUpRightPaths() -> CGPathRef { let b = CurvyPath(startPoint: (74, 0), curves: [ ((74, 0), (74, 0), (74, 0)), ((74, 0), (74, 0), (74, 0)), ((88, 26), (85, 10), (88, 17)), ((72, 43), (88, 35), (81, 43)), ((16, 43), (72, 43), (16, 43)), ((0, 26), (7, 43), (0, 35)), ((16, 9), (0, 17), (7, 9)), ((66, 9), (16, 9), (66, 9)), ((74, 0), (74, 9), (72, 2)), ]) return b.toBezierPath() } func unextendedTipUpPaths() -> CGPathRef { let b = CurvyPath(startPoint: (44, 0), curves: [ ((47, 5), (44, 0), (46, 3)), ((47, 5), (47, 5), (47, 5)), ((52, 15), (48, 7), (52, 10)), ((44, 23), (52, 20), (48, 23)), ((44, 23), (44, 23), (44, 23)), ((36, 15), (40, 23), (36, 20)), ((41, 5), (36, 10), (40, 7)), ((41, 5), (41, 5), (41, 5)), ((44, 0), (42, 3), (44, 0)), ]) return b.toBezierPath() } func unextendedTipUpLeftPaths() -> CGPathRef { let b = CurvyPath(startPoint: (14, 0), curves: [ ((17, 5), (14, 0), (16, 3)), ((17, 5), (17, 5), (17, 5)), ((22, 15), (18, 7), (22, 10)), ((14, 23), (22, 20), (18, 23)), ((14, 23), (14, 23), (14, 23)), ((6, 15), (10, 23), (6, 20)), ((11, 5), (6, 10), (10, 7)), ((11, 5), (11, 5), (11, 5)), ((14, 0), (12, 3), (14, 0)), ]) return b.toBezierPath() } func unextendedTipUpRightPaths() -> CGPathRef { let b = CurvyPath(startPoint: (74, 0), curves: [ ((77, 5), (74, 0), (76, 3)), ((77, 5), (77, 5), (77, 5)), ((82, 15), (78, 7), (82, 10)), ((74, 23), (82, 20), (78, 23)), ((74, 23), (74, 23), (74, 23)), ((66, 15), (70, 23), (66, 20)), ((71, 5), (66, 10), (70, 7)), ((71, 5), (71, 5), (71, 5)), ((74, 0), (72, 3), (74, 0)), ]) return b.toBezierPath() } func extendedTipDownPaths() -> CGPathRef { let b = CurvyPath(startPoint: (44, 43), curves: [ ((53, 34), (44, 43), (53, 34)), ((72, 34), (53, 34), (72, 34)), ((88, 17), (81, 34), (88, 26)), ((72, 0), (88, 8), (81, 0)), ((16, 0), (72, 0), (16, 0)), ((0, 17), (7, 0), (0, 8)), ((16, 34), (0, 26), (7, 34)), ((35, 34), (16, 34), (35, 34)), ((44, 43), (35, 34), (44, 43)), ]) return b.toBezierPath() } func extendedTipDownLeftPaths() -> CGPathRef { let b = CurvyPath(startPoint: (14, 43), curves: [ ((22, 34), (16, 41), (14, 34)), ((72, 34), (22, 34), (72, 34)), ((88, 17), (81, 34), (88, 26)), ((72, 0), (88, 8), (81, 0)), ((16, 0), (72, 0), (16, 0)), ((0, 17), (7, 0), (0, 8)), ((14, 43), (0, 26), (3, 33)), ((14, 43), (14, 43), (14, 43)), ((14, 43), (14, 43), (14, 43)), ]) return b.toBezierPath() } func extendedTipDownRightPaths() -> CGPathRef { let b = CurvyPath(startPoint: (74, 43), curves: [ ((66, 34), (72, 41), (74, 34)), ((16, 34), (66, 34), (16, 34)), ((0, 17), (7, 34), (0, 26)), ((16, 0), (0, 8), (7, 0)), ((72, 0), (16, 0), (72, 0)), ((88, 17), (81, 0), (88, 8)), ((74, 43), (88, 26), (85, 33)), ((74, 43), (74, 43), (74, 43)), ((74, 43), (74, 43), (74, 43)), ]) return b.toBezierPath() } func unextendedTipDownPaths() -> CGPathRef { let b = CurvyPath(startPoint: (44, 43), curves: [ ((47, 38), (44, 43), (46, 40)), ((47, 38), (47, 38), (47, 38)), ((52, 28), (48, 36), (52, 33)), ((44, 413), (52, 410), (48, 413)), ((44, 413), (44, 413), (44, 413)), ((36, 28), (40, 413), (36, 410)), ((41, 38), (36, 33), (40, 36)), ((41, 38), (41, 38), (41, 38)), ((44, 43), (42, 43-3), (44, 43)), ]) return b.toBezierPath() } func unextendedTipDownLeftPaths() -> CGPathRef { let b = CurvyPath(startPoint: (14, 43), curves: [ ((17, 38), (14, 43), (16, 40)), ((17, 38), (17, 38), (17, 38)), ((22, 28), (18, 36), (22, 33)), ((14, 413), (22, 410), (18, 413)), ((14, 413), (14, 413), (14, 413)), ((6, 28), (10, 413), (6, 410)), ((11, 38), (6, 33), (10, 36)), ((11, 38), (11, 38), (11, 38)), ((14, 43), (12, 40), (14, 43)), ]) return b.toBezierPath() } func unextendedTipDownRightPaths() -> CGPathRef { let b = CurvyPath(startPoint: (74, 43), curves: [ ((77, 38), (74, 43), (76, 40)), ((77, 38), (77, 38), (77, 38)), ((82, 28), (78, 36), (82, 33)), ((74, 413), (82, 410), (78, 413)), ((74, 413), (74, 413), (74, 413)), ((66, 28), (70, 413), (66, 410)), ((71, 38), (66, 33), (70, 36)), ((71, 38), (71, 38), (71, 38)), ((74, 43), (72, 43-3), (74, 43)), ]) return b.toBezierPath() } } // MARK: - Properties private let _startGrabber = DejaTextGrabber(frame: grabber_frame, tipDirection: .Down) private let _endGrabber = DejaTextGrabber(frame: grabber_frame, tipDirection: .Up) private var _selectionLayers = [CALayer]() lazy private var _singleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "singleTapped:") lazy private var _doubleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "doubleTapped:") lazy private var _tripleTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tripleTapped:") lazy private var _startGrabberTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "startGrabberTapped:") lazy private var _endGrabberTapRecognizer: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "endGrabberTapped:") lazy private var _startGrabberPanRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "startGrabberPanned:") lazy private var _endGrabberPanRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: "endGrabberPanned:") private var _keyboardFrame = CGRectZero private var _startGrabberIsBeingManipulated = false private var _endGrabberIsBeingManipulated = false private var _startGrabberRepositioningTimer: NSTimer? private var _endGrabberRepositioningTimer: NSTimer? private var _panOffset = CGPointZero // MARK: - Initialization public override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) self.configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.configure() } private func configure() -> Void { self.addSubview(_startGrabber) self.addSubview(_endGrabber) _singleTapRecognizer.numberOfTapsRequired = 1 _singleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer) _singleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer) super.addGestureRecognizer(_singleTapRecognizer) _doubleTapRecognizer.numberOfTapsRequired = 2 _doubleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer) _doubleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer) super.addGestureRecognizer(_doubleTapRecognizer) _tripleTapRecognizer.numberOfTapsRequired = 3 _tripleTapRecognizer.requireGestureRecognizerToFail(_startGrabberTapRecognizer) _tripleTapRecognizer.requireGestureRecognizerToFail(_endGrabberTapRecognizer) super.addGestureRecognizer(_tripleTapRecognizer) _startGrabber.addGestureRecognizer(_startGrabberTapRecognizer) _endGrabber.addGestureRecognizer(_endGrabberTapRecognizer) _startGrabber.addGestureRecognizer(_startGrabberPanRecognizer) _endGrabber.addGestureRecognizer(_endGrabberPanRecognizer) _startGrabber.hidden = true _endGrabber.hidden = true _keyboardFrame = CGRectMake(0, UIScreen.mainScreen().bounds.height, UIScreen.mainScreen().bounds.width, 1.0) NSNotificationCenter.defaultCenter().addObserverForName(UITextViewTextDidChangeNotification, object: self, queue: NSOperationQueue.mainQueue()) { (notification) in self.selectedTextRangeDidChange() self._endGrabber.extended = false self._endGrabber.transform(animated: false) } NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: NSOperationQueue.mainQueue()) { (notification) in if let info = notification.userInfo { if let frame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { self._keyboardFrame = frame } } } } // MARK: - Misc private func selectedTextRangeDidChange() { for l in _selectionLayers { l.removeFromSuperlayer() } _selectionLayers.removeAll(keepCapacity: true) if let range = self.selectedTextRange { if range.empty { let r = self.caretRectForPosition(range.start) if !_endGrabberIsBeingManipulated { _endGrabber.tipPosition = CGPointMake(r.origin.x + 0.5 * r.size.width, r.origin.y + r.size.height) _endGrabber.transform(animated: false) } _startGrabber.hidden = true _endGrabber.hidden = false } else { let rects: [UITextSelectionRect] = super.selectionRectsForRange(range) as! [UITextSelectionRect] for r in rects { let l = CALayer() l.frame = r.rect l.backgroundColor = self.tintColor.colorWithAlphaComponent(selection_alpha).CGColor _selectionLayers += [l] self.layer.insertSublayer(l, atIndex: 0) } let (topLeft, bottomRight) = self.selectionCorners() if !_startGrabberIsBeingManipulated { _startGrabber.tipPosition = topLeft _startGrabber.transform(animated: false) } if !_endGrabberIsBeingManipulated { _endGrabber.tipPosition = bottomRight _endGrabber.transform(animated: false) } _startGrabber.hidden = false _endGrabber.hidden = false } } } // MARK: - Overrides override public var selectedTextRange: UITextRange? { didSet { self.selectedTextRangeDidChange() } } override public func addGestureRecognizer(gestureRecognizer: UIGestureRecognizer) { // Only allow native scrolling if gestureRecognizer == self.panGestureRecognizer { super.addGestureRecognizer(gestureRecognizer) } } // MARK: - Public methods /** Use this method to add your own gesture recognizers. - parameter gestureRecognizer: An object whose class descends from the UIGestureRecognizer class. */ internal func addGestureRecognizerForReal(gestureRecognizer: UIGestureRecognizer) { super.addGestureRecognizer(gestureRecognizer) } // MARK: - Action methods @objc private func singleTapped(recognizer: UITapGestureRecognizer) { if !self.isFirstResponder() { self.becomeFirstResponder() } let location = recognizer.locationInView(self) let closest = self.closestPositionToPoint(location)! // Check whether the tap happened in the vicinity of the caret if self.selectedRange.length == 0 { let caretRect = self.caretRectForPosition(self.selectedTextRange!.start) let d = distanceFrom(point: location, toRect: caretRect) if d <= caret_tap_radius { self.showEditingMenu() _endGrabber.extended = true _endGrabber.transform(animated: true) return } } // Tap inside or outside of words if self.tokenizer.isPosition(self.closestPositionToPoint(location)!, withinTextUnit: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue) && self.tokenizer.isPosition(self.closestPositionToPoint(location)!, withinTextUnit: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue) { var rightLeft = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)! rightLeft = self.tokenizer.positionFromPosition(rightLeft, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)! let rightLeftRect = self.caretRectForPosition(rightLeft) var leftRight = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue)! leftRight = self.tokenizer.positionFromPosition(leftRight, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue)! let leftRightRect = self.caretRectForPosition(leftRight) if distanceFrom(point: location, toRect: rightLeftRect) < distanceFrom(point: location, toRect: leftRightRect) { self.selectedTextRange = self.textRangeFromPosition(rightLeft, toPosition: rightLeft) } else { self.selectedTextRange = self.textRangeFromPosition(leftRight, toPosition: leftRight) } } else { self.selectedTextRange = self.textRangeFromPosition(closest, toPosition: closest) } self.hideEditingMenu() _endGrabber.extended = false _endGrabber.transform(animated: false) } @objc private func doubleTapped(recognizer: UITapGestureRecognizer) { if !self.isFirstResponder() { self.becomeFirstResponder() } let location = recognizer.locationInView(self) let closest = self.closestPositionToPoint(location)! var range = self.tokenizer.rangeEnclosingPosition(closest, withGranularity: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue) if range == nil { range = self.tokenizer.rangeEnclosingPosition(closest, withGranularity: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue) } if range != nil { self.selectedTextRange = range; } else { var right: UITextPosition? var rightRight: UITextPosition? var left: UITextPosition? var leftLeft: UITextPosition? right = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue) if right != nil { rightRight = self.tokenizer.positionFromPosition(right!, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Right.rawValue) } left = self.tokenizer.positionFromPosition(closest, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue) if left != nil { leftLeft = self.tokenizer.positionFromPosition(left!, toBoundary: UITextGranularity.Word, inDirection: UITextLayoutDirection.Left.rawValue) } let rightRect = self.caretRectForPosition(right!) let leftRect = self.caretRectForPosition(left!) if distanceFrom(point: location, toRect: rightRect) < distanceFrom(point: location, toRect: leftRect) { self.selectedTextRange = self.textRangeFromPosition(right!, toPosition: rightRight!) } else { self.selectedTextRange = self.textRangeFromPosition(left!, toPosition: leftLeft!) } } _startGrabber.extended = true _startGrabber.transform(animated: false) _endGrabber.extended = true _endGrabber.transform(animated: false) self.showEditingMenu() } @objc private func tripleTapped(recognizer: UITapGestureRecognizer) { if !self.isFirstResponder() { self.becomeFirstResponder() } let range = self.textRangeFromPosition(self.beginningOfDocument, toPosition: self.endOfDocument) self.selectedTextRange = range _startGrabber.extended = true _startGrabber.transform(animated: false) _endGrabber.extended = true _endGrabber.transform(animated: false) self.showEditingMenu() } @objc private func startGrabberTapped(recognizer: UITapGestureRecognizer) { if !_startGrabber.extended { self.showEditingMenu() _startGrabber.extended = true _startGrabber.transform(animated: true) return } _startGrabberIsBeingManipulated = true // Set the timer _startGrabberRepositioningTimer?.invalidate() _startGrabberRepositioningTimer = NSTimer.scheduledTimerWithTimeInterval(repositioning_timer_duration, target: self, selector: "startGrabberRepositioningTimerFired:", userInfo: nil, repeats: false) // Set text range according to the button that has been tapped var pos = self.selectedRange.location var len = self.selectedRange.length let location = recognizer.locationInView(_startGrabber) if location.x <= _startGrabber.bounds.size.width / 2.0 { if pos != 0 { pos-- len++ } } else { if len != 1 { pos++ len-- } } self.selectedTextRange = self.textRangeFromPosition(self.positionFromPosition(self.beginningOfDocument, offset: pos)!, toPosition: self.positionFromPosition(self.beginningOfDocument, offset: pos + len)!) // Show editing menu self.showEditingMenu() } @objc private func endGrabberTapped(recognizer: UITapGestureRecognizer) { if !_endGrabber.extended { self.showEditingMenu() _endGrabber.extended = true _endGrabber.transform(animated: true) return } _endGrabberIsBeingManipulated = true // Set the timer _endGrabberRepositioningTimer?.invalidate() _endGrabberRepositioningTimer = NSTimer.scheduledTimerWithTimeInterval(repositioning_timer_duration, target: self, selector: "endGrabberRepositioningTimerFired:", userInfo: nil, repeats: false) // Set text range according to the button that has been tapped var pos = self.selectedRange.location var len = self.selectedRange.length let location = recognizer.locationInView(_endGrabber) if location.x <= _endGrabber.bounds.size.width / 2.0 { if len > 0 { if len != 1 { len-- } } else { if pos != 0 { pos-- } } } else { if len > 0 { if self.text.characters.count != pos + len { len++ } } else { if self.text.characters.count != pos + len { pos++ } } } self.selectedTextRange = self.textRangeFromPosition(self.positionFromPosition(self.beginningOfDocument, offset: pos)!, toPosition: self.positionFromPosition(self.beginningOfDocument, offset: pos + len)!) // Show editing menu self.showEditingMenu() } @objc private func startGrabberRepositioningTimerFired(timer: NSTimer) { // Invalidate timer _startGrabberRepositioningTimer?.invalidate() _startGrabberRepositioningTimer = nil // Snap start grabber self.snapStartGrabberTipPosition() _startGrabber.transform(animated: true) } @objc private func endGrabberRepositioningTimerFired(timer: NSTimer) { // Invalidate timer _endGrabberRepositioningTimer?.invalidate() _endGrabberRepositioningTimer = nil // Snap end grabber self.snapEndGrabberTipPosition() _endGrabber.transform(animated: true) } @objc private func startGrabberPanned(recognizer: UIPanGestureRecognizer) { self.hideEditingMenu() self.bringSubviewToFront(_startGrabber) _startGrabberIsBeingManipulated = true var animated = false // Began if recognizer.state == UIGestureRecognizerState.Began { _panOffset = recognizer.locationInView(_startGrabber) _panOffset.y = start_grabber_y_offset _startGrabber.forcedTipAlignment = .Center if !_startGrabber.extended { _startGrabber.extended = true animated = true } } // Always let location = recognizer.locationInView(self) let tip = CGPointMake(location.x - _panOffset.x + 0.5 * _startGrabber.frame.size.width, location.y - _panOffset.y + 1.0 * _startGrabber.frame.size.height) _startGrabber.tipPosition = tip let pos = CGPointMake(tip.x, tip.y + start_grabber_tip_selection_offset) let textPosition = self.closestPositionToPoint(pos)! let posOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: textPosition) let endOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: self.selectedTextRange!.end) if posOffset < endOffset { self.selectedTextRange = self.textRangeFromPosition(textPosition, toPosition: self.selectedTextRange!.end) } // Ended if recognizer.state == UIGestureRecognizerState.Ended { self.snapStartGrabberTipPosition() animated = true self.showEditingMenu() } // Transform _startGrabber.transform(animated: animated) } @objc private func endGrabberPanned(recognizer: UIPanGestureRecognizer) { self.hideEditingMenu() self.bringSubviewToFront(_endGrabber) _endGrabberIsBeingManipulated = true var animated = false // Began if recognizer.state == UIGestureRecognizerState.Began { _panOffset = recognizer.locationInView(_endGrabber) _panOffset.y = 0.7 * _endGrabber.frame.size.height _endGrabber.forcedTipAlignment = .Center if !_endGrabber.extended { _endGrabber.extended = true animated = true } } // Always let location = recognizer.locationInView(self) let tip = CGPointMake(location.x - _panOffset.x + 0.5 * _endGrabber.frame.size.width, location.y - _panOffset.y) _endGrabber.tipPosition = tip let pos = CGPointMake(tip.x, tip.y - end_grabber_tip_selection_offset) let textPosition = self.closestPositionToPoint(pos)! let posOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: textPosition) let startOffset = self.offsetFromPosition(self.beginningOfDocument, toPosition: self.selectedTextRange!.start) // Set selected range if !(self.selectedRange.length > 0 && posOffset <= startOffset) { if self.selectedRange.length == 0 { self.selectedTextRange = self.textRangeFromPosition(textPosition, toPosition: textPosition) } else { self.selectedTextRange = self.textRangeFromPosition(self.selectedTextRange!.start, toPosition: textPosition) } } // Ended if recognizer.state == UIGestureRecognizerState.Ended { self.snapEndGrabberTipPosition() animated = true self.showEditingMenu() } // Transform _endGrabber.transform(animated: animated) } private func snapStartGrabberTipPosition() { _startGrabber.forcedTipAlignment = nil _startGrabberIsBeingManipulated = false // Move start grabber to final position let topLeft = self.selectionCorners().0 _startGrabber.tipPosition = topLeft } private func snapEndGrabberTipPosition() { _endGrabber.forcedTipAlignment = nil _endGrabberIsBeingManipulated = false // Move end grabber to final position let bottomRight = self.selectionCorners().1 _endGrabber.tipPosition = bottomRight } // MARK: - UITextInput protocol class DejaTextSelectionRect: UITextSelectionRect { override var rect: CGRect { return CGRect(x: -100, y: -100, width: 4, height: 4) } } override public func selectionRectsForRange(range: UITextRange) -> [AnyObject] { return [DejaTextSelectionRect()] } // MARK: - UIResponder override public func canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool { if action == "selectAll:" || action == "select:" { return false } else { return super.canPerformAction(action, withSender: sender) } } // MARK: - Helpers private func showEditingMenu() { let menuController = UIMenuController.sharedMenuController() if !menuController.menuVisible { let rect = self.convertRect(_keyboardFrame, fromView: nil) menuController.setTargetRect(rect, inView: self) menuController.update() menuController.setMenuVisible(true, animated: false) } } private func hideEditingMenu() { let menuController = UIMenuController.sharedMenuController() if menuController.menuVisible { menuController.setMenuVisible(false, animated: false) } } private func distanceFrom(point point: CGPoint, toRect rect: CGRect) -> CGFloat { let center = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect)) let x2 = pow(fabs(center.x - point.x), 2) let y2 = pow(fabs(center.y - point.y), 2) return sqrt(x2 + y2) } private func selectionCorners() -> (CGPoint, CGPoint) { if self.selectedTextRange!.empty { let rect = self.caretRectForPosition(self.selectedTextRange!.start) return (rect.origin, CGPointMake(rect.origin.x + rect.size.width, rect.origin.y + rect.size.height)) } let rects: [UITextSelectionRect] = super.selectionRectsForRange(self.selectedTextRange!) as! [UITextSelectionRect] var topLeft = CGPointMake(CGFloat.max, CGFloat.max) var bottomRight = CGPointMake(CGFloat.min, CGFloat.min) for r in rects { if r.rect.size.width < 0.5 || r.rect.size.height < 0.5 { continue } if r.rect.origin.y < topLeft.y { topLeft.y = r.rect.origin.y topLeft.x = r.rect.origin.x } if r.rect.origin.y + r.rect.size.height > ceil(bottomRight.y) { bottomRight.y = r.rect.origin.y + r.rect.size.height bottomRight.x = r.rect.origin.x + r.rect.size.width } } return (topLeft, bottomRight) } }
mit
9a4b3f884b6791df6a8fa8a33696f44f
35.272512
328
0.523116
5.291047
false
false
false
false
srn214/Floral
Floral/Pods/AutoInch/Sources/Inch.swift
1
6082
// // Inch.swift // ┌─┐ ┌───────┐ ┌───────┐ // │ │ │ ┌─────┘ │ ┌─────┘ // │ │ │ └─────┐ │ └─────┐ // │ │ │ ┌─────┘ │ ┌─────┘ // │ └─────┐│ └─────┐ │ └─────┐ // └───────┘└───────┘ └───────┘ // // Created by lee on 2018/1/22. // Copyright © 2018年 lee. All rights reserved. // import Foundation #if os(iOS) import UIKit public enum Inch { typealias Number = CGFloat } extension Inch { public enum Phone: Int, CaseIterable { case unknown = -1 case i35 case i40 case i47 case i55 case i58Full case i61Full case i65Full var width: Number { switch self { case .unknown: return 0 case .i35: return 320 case .i40: return 320 case .i47: return 375 case .i55: return 414 case .i58Full: return 375 case .i61Full: return 414 case .i65Full: return 414 } } var height: Number { switch self { case .unknown: return 0 case .i35: return 480 case .i40: return 568 case .i47: return 667 case .i55: return 736 case .i58Full: return 812 case .i61Full: return 896 case .i65Full: return 896 } } var scale: CGFloat { switch self { case .unknown: return 0 case .i35: return 2 case .i40: return 2 case .i47: return 2 case .i55: return 3 case .i58Full: return 3 case .i61Full: return 2 case .i65Full: return 3 } } private var size: CGSize { return CGSize(width: width, height: height) } private var native: CGSize { return CGSize(width: width * scale, height: height * scale) } public static func type(size: CGSize = UIScreen.main.bounds.size, scale: CGFloat = UIScreen.main.scale) -> Phone { let width = min(size.width, size.height) * scale let height = max(size.width, size.height) * scale let size = CGSize(width: width, height: height) switch size { case Phone.i35.native: return .i35 case Phone.i40.native: return .i40 case Phone.i47.native: return .i47 case Phone.i55.native: return .i55 case Phone.i58Full.native: return .i58Full case Phone.i61Full.native: return .i61Full case Phone.i65Full.native: return .i65Full default: return .unknown } } public static let current: Phone = type() } } extension Inch.Phone: Equatable { public static func == (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool { return lhs.rawValue == rhs.rawValue } } extension Inch.Phone: Comparable { public static func < (lhs: Inch.Phone, rhs: Inch.Phone) -> Bool { return lhs.rawValue < rhs.rawValue } } extension Int: Inchable {} extension Bool: Inchable {} extension Float: Inchable {} extension Double: Inchable {} extension String: Inchable {} extension CGRect: Inchable {} extension CGSize: Inchable {} extension CGFloat: Inchable {} extension CGPoint: Inchable {} extension UIImage: Inchable {} extension UIColor: Inchable {} extension UIFont: Inchable {} extension UIEdgeInsets: Inchable {} public protocol Inchable { func i35(_ value: Self) -> Self func i40(_ value: Self) -> Self func i47(_ value: Self) -> Self func i55(_ value: Self) -> Self func i58full(_ value: Self) -> Self func i61full(_ value: Self) -> Self func i65full(_ value: Self) -> Self func w320(_ value: Self) -> Self func w375(_ value: Self) -> Self func w414(_ value: Self) -> Self } extension Inchable { public func i35(_ value: Self) -> Self { return matching(type: .i35, value) } public func i40(_ value: Self) -> Self { return matching(type: .i40, value) } public func i47(_ value: Self) -> Self { return matching(type: .i47, value) } public func i55(_ value: Self) -> Self { return matching(type: .i55, value) } public func i58full(_ value: Self) -> Self { return matching(type: .i58Full, value) } public func i61full(_ value: Self) -> Self { return matching(type: .i61Full, value) } public func i65full(_ value: Self) -> Self { return matching(type: .i65Full, value) } public func ifull(_ value: Self) -> Self { return matching([.i58Full, .i61Full, .i65Full], value) } public func w320(_ value: Self) -> Self { return matching(width: 320, value) } public func w375(_ value: Self) -> Self { return matching(width: 375, value) } public func w414(_ value: Self) -> Self { return matching(width: 414, value) } private func matching(type: Inch.Phone, _ value: Self) -> Self { return Inch.Phone.current == type ? value : self } private func matching(width: Inch.Number, _ value: Self) -> Self { return Inch.Phone.current.width == width ? value : self } private func matching(_ types: [Inch.Phone], _ value: Self) -> Self { return types.contains(.current) ? value : self } private func matching(_ range: Range<Inch.Phone>, _ value: Self) -> Self { return range ~= .current ? value : self } private func matching(_ range: ClosedRange<Inch.Phone>, _ value: Self) -> Self { return range ~= .current ? value : self } } #endif
mit
b83d36ef26a915d4410abf946349b637
28.729592
98
0.534066
3.939824
false
false
false
false
bparish628/iFarm-Health
iOS/iFarm-Health/Pods/Charts/Source/Charts/Renderers/XAxisRendererHorizontalBarChart.swift
4
13322
// // XAxisRendererHorizontalBarChart.swift // Charts // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/Charts // import Foundation import CoreGraphics #if !os(OSX) import UIKit #endif open class XAxisRendererHorizontalBarChart: XAxisRenderer { @objc internal var chart: BarChartView? @objc public init(viewPortHandler: ViewPortHandler?, xAxis: XAxis?, transformer: Transformer?, chart: BarChartView?) { super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer) self.chart = chart } open override func computeAxis(min: Double, max: Double, inverted: Bool) { guard let viewPortHandler = self.viewPortHandler else { return } var min = min, max = max if let transformer = self.transformer { // calculate the starting and entry point of the y-labels (depending on // zoom / contentrect bounds) if viewPortHandler.contentWidth > 10 && !viewPortHandler.isFullyZoomedOutX { let p1 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) let p2 = transformer.valueForTouchPoint(CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) if inverted { min = Double(p2.y) max = Double(p1.y) } else { min = Double(p1.y) max = Double(p2.y) } } } computeAxisValues(min: min, max: max) } open override func computeSize() { guard let xAxis = self.axis as? XAxis else { return } let longest = xAxis.getLongestLabel() as NSString let labelSize = longest.size(withAttributes: [NSAttributedStringKey.font: xAxis.labelFont]) let labelWidth = floor(labelSize.width + xAxis.xOffset * 3.5) let labelHeight = labelSize.height let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(rectangleWidth: labelSize.width, rectangleHeight: labelHeight, degrees: xAxis.labelRotationAngle) xAxis.labelWidth = labelWidth xAxis.labelHeight = labelHeight xAxis.labelRotatedWidth = round(labelRotatedSize.width + xAxis.xOffset * 3.5) xAxis.labelRotatedHeight = round(labelRotatedSize.height) } open override func renderAxisLabels(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler else { return } if !xAxis.isEnabled || !xAxis.isDrawLabelsEnabled || chart?.data === nil { return } let xoffset = xAxis.xOffset if xAxis.labelPosition == .top { drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else if xAxis.labelPosition == .topInside { drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottom { drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } else if xAxis.labelPosition == .bottomInside { drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) } else { // BOTH SIDED drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, anchor: CGPoint(x: 0.0, y: 0.5)) drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, anchor: CGPoint(x: 1.0, y: 0.5)) } } /// draws the x-labels on the specified y-position open override func drawLabels(context: CGContext, pos: CGFloat, anchor: CGPoint) { guard let xAxis = self.axis as? XAxis, let transformer = self.transformer, let viewPortHandler = self.viewPortHandler else { return } let labelFont = xAxis.labelFont let labelTextColor = xAxis.labelTextColor let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD let centeringEnabled = xAxis.isCenterAxisLabelsEnabled // pre allocate to save performance (dont allocate in loop) var position = CGPoint(x: 0.0, y: 0.0) for i in stride(from: 0, to: xAxis.entryCount, by: 1) { // only fill x values position.x = 0.0 if centeringEnabled { position.y = CGFloat(xAxis.centeredEntries[i]) } else { position.y = CGFloat(xAxis.entries[i]) } transformer.pointValueToPixel(&position) if viewPortHandler.isInBoundsY(position.y) { if let label = xAxis.valueFormatter?.stringForValue(xAxis.entries[i], axis: xAxis) { drawLabel( context: context, formattedLabel: label, x: pos, y: position.y, attributes: [NSAttributedStringKey.font: labelFont, NSAttributedStringKey.foregroundColor: labelTextColor], anchor: anchor, angleRadians: labelRotationAngleRadians) } } } } @objc open func drawLabel( context: CGContext, formattedLabel: String, x: CGFloat, y: CGFloat, attributes: [NSAttributedStringKey : Any], anchor: CGPoint, angleRadians: CGFloat) { ChartUtils.drawText( context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, anchor: anchor, angleRadians: angleRadians) } open override var gridClippingRect: CGRect { var contentRect = viewPortHandler?.contentRect ?? CGRect.zero let dy = self.axis?.gridLineWidth ?? 0.0 contentRect.origin.y -= dy / 2.0 contentRect.size.height += dy return contentRect } fileprivate var _gridLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2) open override func drawGridLine(context: CGContext, x: CGFloat, y: CGFloat) { guard let viewPortHandler = self.viewPortHandler else { return } if viewPortHandler.isInBoundsY(y) { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: y)) context.strokePath() } } open override func renderAxisLine(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler else { return } if !xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled { return } context.saveGState() context.setStrokeColor(xAxis.axisLineColor.cgColor) context.setLineWidth(xAxis.axisLineWidth) if xAxis.axisLineDashLengths != nil { context.setLineDash(phase: xAxis.axisLineDashPhase, lengths: xAxis.axisLineDashLengths) } else { context.setLineDash(phase: 0.0, lengths: []) } if xAxis.labelPosition == .top || xAxis.labelPosition == .topInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)) context.strokePath() } if xAxis.labelPosition == .bottom || xAxis.labelPosition == .bottomInside || xAxis.labelPosition == .bothSided { context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentTop)) context.addLine(to: CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)) context.strokePath() } context.restoreGState() } open override func renderLimitLines(context: CGContext) { guard let xAxis = self.axis as? XAxis, let viewPortHandler = self.viewPortHandler, let transformer = self.transformer else { return } var limitLines = xAxis.limitLines if limitLines.count == 0 { return } let trans = transformer.valueToPixelMatrix var position = CGPoint(x: 0.0, y: 0.0) for i in 0 ..< limitLines.count { let l = limitLines[i] if !l.isEnabled { continue } context.saveGState() defer { context.restoreGState() } var clippingRect = viewPortHandler.contentRect clippingRect.origin.y -= l.lineWidth / 2.0 clippingRect.size.height += l.lineWidth context.clip(to: clippingRect) position.x = 0.0 position.y = CGFloat(l.limit) position = position.applying(trans) context.beginPath() context.move(to: CGPoint(x: viewPortHandler.contentLeft, y: position.y)) context.addLine(to: CGPoint(x: viewPortHandler.contentRight, y: position.y)) context.setStrokeColor(l.lineColor.cgColor) context.setLineWidth(l.lineWidth) if l.lineDashLengths != nil { context.setLineDash(phase: l.lineDashPhase, lengths: l.lineDashLengths!) } else { context.setLineDash(phase: 0.0, lengths: []) } context.strokePath() let label = l.label // if drawing the limit-value label is enabled if l.drawLabelEnabled && label.characters.count > 0 { let labelLineHeight = l.valueFont.lineHeight let xOffset: CGFloat = 4.0 + l.xOffset let yOffset: CGFloat = l.lineWidth + labelLineHeight + l.yOffset if l.labelPosition == .rightTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y - yOffset), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .rightBottom { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentRight - xOffset, y: position.y + yOffset - labelLineHeight), align: .right, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else if l.labelPosition == .leftTop { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y - yOffset), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } else { ChartUtils.drawText(context: context, text: label, point: CGPoint( x: viewPortHandler.contentLeft + xOffset, y: position.y + yOffset - labelLineHeight), align: .left, attributes: [NSAttributedStringKey.font: l.valueFont, NSAttributedStringKey.foregroundColor: l.valueTextColor]) } } } } }
apache-2.0
180dba1279d024511edf44152c003f7f
34.525333
163
0.538808
5.578727
false
false
false
false
KeepGoing2016/Swift-
DUZB_XMJ/DUZB_XMJ/Classes/Home/Controller/GameViewController.swift
1
6502
// // GameViewController.swift // DUZB_XMJ // // Created by user on 16/12/29. // Copyright © 2016年 XMJ. All rights reserved. // import UIKit fileprivate let kGameCellId = "kGameCellId" fileprivate let kGameHeaderId = "kGameHeaderId" fileprivate let kEdgeMargin:CGFloat = 10 fileprivate let kGameCellW = (kScreenW-2*kEdgeMargin)/3 fileprivate let kGameCellH = kGameCellW*6/5 class GameViewController: BaseViewController { fileprivate lazy var gameVM:GameViewModel = GameViewModel() fileprivate var supplementaryV:CollectionHeaderView? fileprivate lazy var topHeaderView:CollectionHeaderView = { let topHeaderView = CollectionHeaderView.headerView() topHeaderView.frame = CGRect(x: 0, y: -kSectionHeaderH-kIconViewH, width: kScreenW, height: kSectionHeaderH) topHeaderView.groupIconImg.image = UIImage(named: "Img_orange") topHeaderView.groupName.text = "常见" topHeaderView.moreBtn.isHidden = true // let tempF = topHeaderView.groupIconImg.frame // topHeaderView.groupIconImg.frame = CGRect(origin: tempF.origin, size: CGSize(width: 5, height: tempF.size.height)) return topHeaderView }() fileprivate lazy var topIconView:IconView = { let topIconView = IconView(frame: CGRect(x: 0, y: -kIconViewH, width: kScreenW, height: kIconViewH)) return topIconView }() fileprivate lazy var allContentView:UICollectionView = {[weak self] in let layout = UICollectionViewFlowLayout() layout.minimumLineSpacing = 0 layout.minimumInteritemSpacing = 0 layout.itemSize = CGSize(width: kGameCellW, height: kGameCellH) layout.headerReferenceSize = CGSize(width: kScreenW, height: kSectionHeaderH) layout.sectionInset = UIEdgeInsets(top: 0, left: kEdgeMargin, bottom: 0, right: kEdgeMargin) let allContentView = UICollectionView(frame: (self?.view.bounds)!, collectionViewLayout: layout) allContentView.dataSource = self allContentView.backgroundColor = UIColor.white allContentView.register(UINib(nibName: "GameCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: kGameCellId) allContentView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kGameHeaderId) allContentView.contentInset = UIEdgeInsets(top: kIconViewH+kSectionHeaderH, left: 0, bottom: 0, right: 0) allContentView.autoresizingMask = [.flexibleWidth,.flexibleHeight] return allContentView }() /*系统方法*/ override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewWillAppear(_ animated: Bool) { requestData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //MARK:-设置UI extension GameViewController{ fileprivate func setupUI(){ view.backgroundColor = UIColor.white view.addSubview(allContentView) allContentView.addSubview(topHeaderView) allContentView.addSubview(topIconView) baseContentView = allContentView isHiddenAnimation = false //请求数据 // requestData() } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let tempF = topHeaderView.groupIconImg.frame topHeaderView.groupIconImg.frame = CGRect(origin: tempF.origin, size: CGSize(width: 5, height: tempF.size.height)) // if #available(iOS 9.0, *) { // let headV = allContentView.supplementaryView(forElementKind: UICollectionElementKindSectionHeader, at: IndexPath(item: 0, section: 0)) as? CollectionHeaderView // let tempF2 = headV?.groupIconImg.frame // headV?.groupIconImg.frame = CGRect(origin: (tempF2?.origin)!, size: CGSize(width: 5, height: (tempF2?.size.height)!)) // } else { // // Fallback on earlier versions // } let tempF2 = supplementaryV?.groupIconImg.frame supplementaryV?.groupIconImg.frame = CGRect(origin: (tempF2?.origin)!, size: CGSize(width: 5, height: (tempF2?.size.height)!)) } } //MARK:-网络请求 extension GameViewController{ fileprivate func requestData(){ gameVM.loadGameData { DispatchQueue.global().async { var tempArr:[CellGroupModel] = [CellGroupModel]() for tempM in self.gameVM.gameModelArr[0..<10]{ // let tempM = tempM as? GameModel let groupM = CellGroupModel(dict: ["icon_url":tempM.icon_url,"tag_name":tempM.tag_name]) tempArr.append(groupM) } DispatchQueue.main.async { self.topIconView.dataModelArr = tempArr self.allContentView.reloadData() // DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()+1, execute: { // self.isHiddenAnimation = true // }) self.isHiddenAnimation = true } } } } } //MARK:-数据源 extension GameViewController:UICollectionViewDataSource{ func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return gameVM.gameModelArr.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellId, for: indexPath) as! GameCollectionViewCell cell.gameModel = gameVM.gameModelArr[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kGameHeaderId, for: indexPath) as! CollectionHeaderView header.groupName.text = "全部" header.groupIconImg.image = UIImage(named: "Img_orange") header.moreBtn.isHidden = true supplementaryV = header return header } }
apache-2.0
a7baa92ad0d5b6dc70053c0ae2a321b3
40.391026
191
0.665634
5.161471
false
false
false
false
wordpress-mobile/WordPress-iOS
WordPress/Classes/ViewRelated/Cells/InlineEditableMultiLineCell.swift
1
1832
import Foundation // UITableViewCell that displays an editable UITextView to allow text to be modified inline. // The cell height resizes as the text is modified. // The delegate is notified when: // - The height is updated. // - The text is updated. protocol InlineEditableMultiLineCellDelegate: AnyObject { func textViewHeightUpdatedForCell(_ cell: InlineEditableMultiLineCell) func textUpdatedForCell(_ cell: InlineEditableMultiLineCell) } class InlineEditableMultiLineCell: UITableViewCell, NibReusable { // MARK: - Properties @IBOutlet weak var textView: UITextView! @IBOutlet weak var textViewMinHeightConstraint: NSLayoutConstraint! weak var delegate: InlineEditableMultiLineCellDelegate? // MARK: - View override func awakeFromNib() { super.awakeFromNib() configureCell() } func configure(text: String? = nil) { textView.text = text adjustHeight() } } // MARK: - UITextViewDelegate extension InlineEditableMultiLineCell: UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { delegate?.textUpdatedForCell(self) adjustHeight() } } // MARK: - Private Extension private extension InlineEditableMultiLineCell { func configureCell() { textView.font = .preferredFont(forTextStyle: .body) textView.textColor = .text textView.backgroundColor = .clear } func adjustHeight() { let originalHeight = textView.frame.size.height textView.sizeToFit() let textViewHeight = ceilf(Float(max(textView.frame.size.height, textViewMinHeightConstraint.constant))) textView.frame.size.height = CGFloat(textViewHeight) if textViewHeight != Float(originalHeight) { delegate?.textViewHeightUpdatedForCell(self) } } }
gpl-2.0
5c4f994d92768507846c195cb40bf5c1
25.941176
112
0.707424
5.189802
false
false
false
false
Roommate-App/roomy
roomy/Pods/IBAnimatable/Sources/Protocols/Designable/TintDesignable.swift
3
1522
// // Created by Jake Lin on 11/24/15. // Copyright © 2015 IBAnimatable. All rights reserved. // import UIKit public protocol TintDesignable: class { /** Opacity in tint Color (White): from 0 to 1 */ var tintOpacity: CGFloat { get set } /** Opacity in shade Color (Black): from 0 to 1 */ var shadeOpacity: CGFloat { get set } /** tone color */ var toneColor: UIColor? { get set } /** Opacity in tone color: from 0 to 1 */ var toneOpacity: CGFloat { get set } } public extension TintDesignable where Self: UIView { /** configureTintedColor method, should be called in layoutSubviews() method */ public func configureTintedColor() { if !tintOpacity.isNaN && tintOpacity >= 0 && tintOpacity <= 1 { addColorSubview(color: .white, opacity: tintOpacity) } if !shadeOpacity.isNaN && shadeOpacity >= 0 && shadeOpacity <= 1 { addColorSubview(color: .black, opacity: shadeOpacity) } if let toneColor = toneColor { if !toneOpacity.isNaN && toneOpacity >= 0 && toneOpacity <= 1 { addColorSubview(color: toneColor, opacity: toneOpacity) } } } fileprivate func addColorSubview(color: UIColor, opacity: CGFloat) { let subview = UIView(frame: bounds) subview.backgroundColor = color subview.alpha = opacity if layer.cornerRadius > 0 { subview.layer.cornerRadius = layer.cornerRadius } subview.autoresizingMask = [.flexibleWidth, .flexibleHeight] insertSubview(subview, at: 0) } }
mit
c429a43474c74eabbe3533b1e859b792
24.35
75
0.657462
4.09973
false
false
false
false
Off-Piste/Trolley.io
Trolley/Core/Networking/Third Party/Reachability/Reachability.swift
2
10209
/* Copyright (c) 2014, Ashley Mills All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Reachability.swift version 2.2beta2 import SystemConfiguration import PromiseKit import Foundation public enum ReachabilityError: Error { case FailedToCreateWithAddress(sockaddr_in) case FailedToCreateWithHostname(String) case UnableToSetCallback case UnableToSetDispatchQueue case guardFailed(String) case objectNil(Any?) } public let ReachabilityChangedNotification = NSNotification.Name("ReachabilityChangedNotification") func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } let reachability = Unmanaged<Reachability>.fromOpaque(info).takeUnretainedValue() DispatchQueue.main.async { reachability.reachabilityChanged() } } public class Reachability { public typealias NetworkReachable = (Reachability) -> () public typealias NetworkUnreachable = (Reachability) -> () public enum NetworkStatus: CustomStringConvertible { case notReachable, reachableViaWiFi, reachableViaWWAN public var description: String { switch self { case .reachableViaWWAN: return "Cellular" case .reachableViaWiFi: return "WiFi" case .notReachable: return "No Connection" } } } public var whenReachable: NetworkReachable? public var whenUnreachable: NetworkUnreachable? public var reachableOnWWAN: Bool public var currentReachabilityString: String { return "\(currentReachabilityStatus)" } public var currentReachabilityStatus: NetworkStatus { guard isReachable else { return .notReachable } if isReachableViaWiFi { return .reachableViaWiFi } if isRunningOnDevice { return .reachableViaWWAN } return .notReachable } fileprivate var previousFlags: SCNetworkReachabilityFlags? fileprivate var isRunningOnDevice: Bool = { #if (arch(i386) || arch(x86_64)) && os(iOS) return false #else return true #endif }() fileprivate var notifierRunning = false fileprivate var reachabilityRef: SCNetworkReachability? fileprivate let reachabilitySerialQueue = DispatchQueue(label: "uk.co.ashleymills.reachability") required public init(reachabilityRef: SCNetworkReachability) { reachableOnWWAN = true self.reachabilityRef = reachabilityRef } public convenience init?(hostname: String) { guard let ref = SCNetworkReachabilityCreateWithName(nil, hostname) else { return nil } self.init(reachabilityRef: ref) } public convenience init?() { var zeroAddress = sockaddr() zeroAddress.sa_len = UInt8(MemoryLayout<sockaddr>.size) zeroAddress.sa_family = sa_family_t(AF_INET) guard let ref: SCNetworkReachability = withUnsafePointer(to: &zeroAddress, { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) }) else { return nil } self.init(reachabilityRef: ref) } deinit { stopNotifier() reachabilityRef = nil whenReachable = nil whenUnreachable = nil } } extension Reachability: CustomStringConvertible { // MARK: - *** Notifier methods *** public func startNotifier() throws { guard let reachabilityRef = reachabilityRef, !notifierRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = UnsafeMutableRawPointer(Unmanaged<Reachability>.passUnretained(self).toOpaque()) if !SCNetworkReachabilitySetCallback(reachabilityRef, callback, &context) { stopNotifier() throw ReachabilityError.UnableToSetCallback } if !SCNetworkReachabilitySetDispatchQueue(reachabilityRef, reachabilitySerialQueue) { stopNotifier() throw ReachabilityError.UnableToSetDispatchQueue } // Perform an intial check reachabilitySerialQueue.async { self.reachabilityChanged() } notifierRunning = true } public func stopNotifier() { defer { notifierRunning = false } guard let reachabilityRef = reachabilityRef else { return } TRLCoreNetworkingLogger.debug("Stopping Reachability Notifier") SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachabilityRef, nil) } // MARK: - *** Connection test methods *** public var isReachable: Bool { guard isReachableFlagSet else { return false } if isConnectionRequiredAndTransientFlagSet { return false } if isRunningOnDevice { if isOnWWANFlagSet && !reachableOnWWAN { // We don't want to connect when on 3G. return false } } return true } public var isReachableViaWWAN: Bool { // Check we're not on the simulator, we're REACHABLE and check we're on WWAN return isRunningOnDevice && isReachableFlagSet && isOnWWANFlagSet } public var isReachableViaWiFi: Bool { // Check we're reachable guard isReachableFlagSet else { return false } // If reachable we're reachable, but not on an iOS device (i.e. simulator), we must be on WiFi guard isRunningOnDevice else { return true } // Check we're NOT on WWAN return !isOnWWANFlagSet } public var description: String { let W = isRunningOnDevice ? (isOnWWANFlagSet ? "W" : "-") : "X" let R = isReachableFlagSet ? "R" : "-" let c = isConnectionRequiredFlagSet ? "c" : "-" let t = isTransientConnectionFlagSet ? "t" : "-" let i = isInterventionRequiredFlagSet ? "i" : "-" let C = isConnectionOnTrafficFlagSet ? "C" : "-" let D = isConnectionOnDemandFlagSet ? "D" : "-" let l = isLocalAddressFlagSet ? "l" : "-" let d = isDirectFlagSet ? "d" : "-" return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)" } } fileprivate extension Reachability { func reachabilityChanged() { let flags = reachabilityFlags guard previousFlags != flags else { return } let block = isReachable ? whenReachable : whenUnreachable block?(self) TRLCoreNetworkingLogger.debug("Reachability Changed", self.currentReachabilityString) NotificationCenter.default.post(name: ReachabilityChangedNotification, object:self) previousFlags = flags } var isOnWWANFlagSet: Bool { #if os(iOS) return reachabilityFlags.contains(.isWWAN) #else return false #endif } var isReachableFlagSet: Bool { return reachabilityFlags.contains(.reachable) } var isConnectionRequiredFlagSet: Bool { return reachabilityFlags.contains(.connectionRequired) } var isInterventionRequiredFlagSet: Bool { return reachabilityFlags.contains(.interventionRequired) } var isConnectionOnTrafficFlagSet: Bool { return reachabilityFlags.contains(.connectionOnTraffic) } var isConnectionOnDemandFlagSet: Bool { return reachabilityFlags.contains(.connectionOnDemand) } var isConnectionOnTrafficOrDemandFlagSet: Bool { return !reachabilityFlags.intersection([.connectionOnTraffic, .connectionOnDemand]).isEmpty } var isTransientConnectionFlagSet: Bool { return reachabilityFlags.contains(.transientConnection) } var isLocalAddressFlagSet: Bool { return reachabilityFlags.contains(.isLocalAddress) } var isDirectFlagSet: Bool { return reachabilityFlags.contains(.isDirect) } var isConnectionRequiredAndTransientFlagSet: Bool { return reachabilityFlags.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection] } var reachabilityFlags: SCNetworkReachabilityFlags { guard let reachabilityRef = reachabilityRef else { return SCNetworkReachabilityFlags() } var flags = SCNetworkReachabilityFlags() let gotFlags = withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0)) } if gotFlags { return flags } else { return SCNetworkReachabilityFlags() } } }
mit
557f26b1781731756d53bf76fb1a362f
32.038835
137
0.662749
6.005294
false
false
false
false
narner/AudioKit
AudioKit/iOS/AudioKit/User Interface/AKStepper.swift
1
5871
// // AKStepper.swift // AudioKit for iOS // // Created by Aurelius Prochazka on 3/11/17. // Copyright © 2017 Aurelius Prochazka. All rights reserved. // import AudioKit import UIKit /// Incrementor view, normally used for MIDI presets, but could be useful elsehwere open class AKStepper: UIView { var plusPath = UIBezierPath() var minusPath = UIBezierPath() /// Text / label to display open var text = "Value" /// Current value open var value: MIDIByte /// Function to call on change open var callback: (MIDIByte) -> Void /// Handle new touches override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let touch = touches.first { let touchLocation = touch.location(in: self) if minusPath.contains(touchLocation) { if value > 1 { value -= 1 } } if plusPath.contains(touchLocation) { if value < 127 { value += 1 } } self.callback(value) setNeedsDisplay() } } /// Initialize the stepper view @objc public init(text: String, value: MIDIByte, frame: CGRect = CGRect(x: 0, y: 0, width: 440, height: 60), callback: @escaping (MIDIByte) -> Void) { self.callback = callback self.value = value self.text = text super.init(frame: frame) } /// Initialize within Interface Builder required public init?(coder aDecoder: NSCoder) { self.callback = { filename in return } self.value = 0 self.text = "Value" super.init(coder: aDecoder) } /// Draw the stepper override open func draw(_ rect: CGRect) { //// General Declarations let context = UIGraphicsGetCurrentContext()! //// Color Declarations let red = UIColor(red: 1.000, green: 0.150, blue: 0.061, alpha: 1.000) let gray = UIColor(red: 0.866, green: 0.872, blue: 0.867, alpha: 0.925) let green = UIColor(red: 0.000, green: 0.977, blue: 0.000, alpha: 1.000) //// background Drawing let backgroundPath = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 440, height: 60)) gray.setFill() backgroundPath.fill() //// textLabel Drawing let textLabelRect = CGRect(x: 68, y: 0, width: 304, height: 60) let textLabelStyle = NSMutableParagraphStyle() textLabelStyle.alignment = .left let textLabelInset: CGRect = textLabelRect.insetBy(dx: 10, dy: 0) let textLabelTextHeight: CGFloat = text.boundingRect(with: CGSize(width: textLabelInset.width, height: CGFloat.infinity), options: .usesLineFragmentOrigin, attributes: nil, context: nil).height context.saveGState() context.clip(to: textLabelInset) let newText = "\(text): \(value)" newText.draw(in: CGRect(x: textLabelInset.minX, y: textLabelInset.minY + (textLabelInset.height - textLabelTextHeight) / 2, width: textLabelInset.width, height: textLabelTextHeight), withAttributes: nil) context.restoreGState() //// minusGroup //// minusRectangle Drawing let minusRectanglePath = UIBezierPath(roundedRect: CGRect(x: 4, y: 5, width: 60, height: 50), cornerRadius: 16) red.setFill() minusRectanglePath.fill() UIColor.black.setStroke() minusRectanglePath.lineWidth = 2 minusRectanglePath.stroke() //// minus Drawing minusPath = UIBezierPath(rect: CGRect(x: 19, y: 25, width: 31, height: 10)) UIColor.black.setFill() minusPath.fill() //// plusGroup //// plusRectangle Drawing let plusRectanglePath = UIBezierPath(roundedRect: CGRect(x: 376, y: 5, width: 60, height: 50), cornerRadius: 16) green.setFill() plusRectanglePath.fill() UIColor.black.setStroke() plusRectanglePath.lineWidth = 2 plusRectanglePath.stroke() //// plus Drawing plusPath = UIBezierPath() plusPath.move(to: CGPoint(x: 411, y: 15)) plusPath.addCurve(to: CGPoint(x: 411, y: 25), controlPoint1: CGPoint(x: 411, y: 15), controlPoint2: CGPoint(x: 411, y: 19.49)) plusPath.addLine(to: CGPoint(x: 421, y: 25)) plusPath.addLine(to: CGPoint(x: 421, y: 35)) plusPath.addLine(to: CGPoint(x: 411, y: 35)) plusPath.addCurve(to: CGPoint(x: 411, y: 45), controlPoint1: CGPoint(x: 411, y: 40.51), controlPoint2: CGPoint(x: 411, y: 45)) plusPath.addLine(to: CGPoint(x: 401, y: 45)) plusPath.addCurve(to: CGPoint(x: 401, y: 35), controlPoint1: CGPoint(x: 401, y: 45), controlPoint2: CGPoint(x: 401, y: 40.51)) plusPath.addLine(to: CGPoint(x: 391, y: 35)) plusPath.addLine(to: CGPoint(x: 391, y: 25)) plusPath.addLine(to: CGPoint(x: 401, y: 25)) plusPath.addCurve(to: CGPoint(x: 401, y: 15), controlPoint1: CGPoint(x: 401, y: 19.49), controlPoint2: CGPoint(x: 401, y: 15)) plusPath.addLine(to: CGPoint(x: 411, y: 15)) plusPath.addLine(to: CGPoint(x: 411, y: 15)) plusPath.close() UIColor.black.setFill() plusPath.fill() } }
mit
2992a75ef60b2c6a203eb8ce41884eeb
37.366013
120
0.54293
4.511914
false
false
false
false
younata/RSSClient
TethysAppSpecs/UI/Account/OAuthLoginControllerSpec.swift
1
9237
import Quick import UIKit import Nimble import Result import CBGPromise @testable import TethysKit @testable import Tethys final class OAuthLoginControllerSpec: QuickSpec { override func spec() { var subject: OAuthLoginController! var accountService: FakeAccountService! var mainQueue: FakeOperationQueue! var authenticationSessions: [ASWebAuthenticationSession] = [] beforeEach { authenticationSessions = [] accountService = FakeAccountService() mainQueue = FakeOperationQueue() mainQueue.runSynchronously = true subject = OAuthLoginController(accountService: accountService, mainQueue: mainQueue, clientId: "testClientId") { let session = ASWebAuthenticationSession(url: $0, callbackURLScheme: $1, completionHandler: $2) authenticationSessions.append(session) return session } } it("does not yet create any authentication sessions") { expect(authenticationSessions).to(beEmpty()) } describe("-begin()") { var future: Future<Result<Account, TethysError>>! var window: UIWindow! beforeEach { window = UIWindow() subject.window = window future = subject.begin() } it("creates an authentication session") { expect(authenticationSessions).to(haveCount(1)) } it("starts the created authentication session") { expect(authenticationSessions.last?.began).to(beTrue()) } it("sets the session's presentationContextProvider") { expect(authenticationSessions.last?.presentationContextProvider).toNot(beNil()) let provider = authenticationSessions.last?.presentationContextProvider expect(provider?.presentationAnchor(for: authenticationSessions.last!)).to(be(window)) } it("configures the authentication session for inoreader with a custom redirect") { guard let receivedURL = authenticationSessions.last?.url else { return } guard let components = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false) else { fail("Unable to construct URLComponents from \(receivedURL)") return } expect(components.scheme).to(equal("https"), description: "Should make a request to an https url") expect(components.host).to(equal("www.inoreader.com"), description: "Should make a request to inoreader") expect(components.path).to(equal("/oauth2/auth"), description: "Should make a request to the oauth endpoint") expect(components.queryItems).to(haveCount(5), description: "Should have 5 query items") expect(components.queryItems).to(contain( URLQueryItem(name: "redirect_uri", value: "https://tethys.younata.com/oauth"), URLQueryItem(name: "response_type", value: "code"), URLQueryItem(name: "scope", value: "read write"), URLQueryItem(name: "client_id", value: "testClientId") )) guard let stateItem = (components.queryItems ?? []).first(where: { $0.name == "state" }) else { fail("No state query item") return } expect(stateItem.value).toNot(beNil()) } it("sets the expected callback scheme") { expect(authenticationSessions.last?.callbackURLScheme).to(equal("rnews")) } describe("when the user finishes the session successfully") { describe("and everything is hunky-dory") { beforeEach { guard let receivedURL = authenticationSessions.last?.url else { return } guard let components = URLComponents(url: receivedURL, resolvingAgainstBaseURL: false) else { return } guard let stateItem = (components.queryItems ?? []).first(where: { $0.name == "state" }) else { return } authenticationSessions.last?.completionHandler( url(base: "rnews://oauth", queryItems: ["code": "authentication_code", "state": stateItem.value!]), nil ) } it("tells the account service to update it's credentials with the authentication code") { expect(accountService.authenticateCalls).to(equal(["authentication_code"])) } describe("and the account service succeeds") { beforeEach { accountService.authenticatePromises.last?.resolve(.success(Account( kind: .inoreader, username: "a username", id: "an id" ))) } it("resolves the future with the account") { expect(future).to(beResolved()) expect(future.value?.value).to(equal(Account( kind: .inoreader, username: "a username", id: "an id" ))) } } describe("and the account service fails") { beforeEach { accountService.authenticatePromises.last?.resolve(.failure(.unknown)) } it("resolves the future with the error") { expect(future).to(beResolved()) expect(future.value?.error).to(equal(.unknown)) } } } describe("and the csrf doesn't match") { let csrfURL = url(base: "rnews://oauth", queryItems: ["code": "authentication_code", "state": "badValue"]) beforeEach { authenticationSessions.last?.completionHandler( csrfURL, nil ) } it("resolves the future with an invalidResponse error") { expect(future).to(beResolved()) guard let error = future.value?.error else { fail("error not set"); return } switch error { case .network(let url, let networkError): let body = (csrfURL.query ?? "").data(using: .utf8)! expect(networkError).to(equal(.badResponse(body))) expect(url.absoluteString.hasPrefix("https://www.inoreader.com/oauth2/auth")).to( beTruthy(), description: "Expected url to start with https://www.inoreader.com/oauth2/auth" ) default: fail("Expected error to be a badResponse network error, got \(error)") } } } } describe("when the user fails to login") { beforeEach { let error = NSError( domain: ASWebAuthenticationSessionErrorDomain, code: ASWebAuthenticationSessionError.Code.canceledLogin.rawValue, userInfo: nil) authenticationSessions.last?.completionHandler(nil, error) } it("resolves the future with a cancelled error") { expect(future).to(beResolved()) guard let error = future.value?.error else { fail("error not set"); return } switch error { case .network(let url, let networkError): expect(networkError).to(equal(.cancelled)) expect(url.absoluteString.hasPrefix("https://www.inoreader.com/oauth2/auth")).to( beTruthy(), description: "Expected url to start with https://www.inoreader.com/oauth2/auth" ) default: fail("Expected error to be a cancelled network error, got \(error)") } } } } } } func url(base: String, queryItems: [String: String]) -> URL { var components = URLComponents(string: base)! components.queryItems = queryItems.map { key, value in return URLQueryItem(name: key, value: value) } return components.url! }
mit
a65bc10493d95440f2407d748d618f78
42.570755
125
0.501462
6.033312
false
false
false
false
thinkclay/FlourishUI
Pod/Classes/ToggleSwitch.swift
1
5375
import UIKit public class ToggleButton: UIView { var active: Bool = false public var activeBackgroundColor = UIColor(hex: "#6B60AB") { didSet { setNeedsDisplay() } } public var activeBorderColor = UIColor(hex: "#8579CE") { didSet { setNeedsDisplay() } } public var activeInnerShadowColor = UIColor(rgba: [255, 255, 255, 0.5]) { didSet { setNeedsDisplay() } } public var disabledBackgroundColor = UIColor(hex: "#4D428E") { didSet { setNeedsDisplay() } } public var disabledBorderColor = UIColor(hex: "#5C509D") { didSet { setNeedsDisplay() } } public var disabledInnerShadowColor = UIColor(rgba: [255, 255, 255, 0.14]) { didSet { setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func draw(_ rect: CGRect) { let buttonFill = active ? activeBackgroundColor : disabledBackgroundColor let buttonStroke = active ? activeBorderColor : disabledBorderColor let innerShadow = active ? activeInnerShadowColor : disabledInnerShadowColor let x: CGFloat = active ? 35 : 0 let context = UIGraphicsGetCurrentContext()! // Oval with drop shadow let ovalPath = UIBezierPath(ovalIn: CGRect(x: 2, y: 1, width: 20, height: 20)) context.saveGState() context.setShadow(offset: CGSize(width: 0.1, height: -0.1), blur: 2, color: UIColor.black.cgColor) buttonFill.setFill() ovalPath.fill() // Inner shadow context.saveGState() context.clip(to: ovalPath.bounds) context.setShadow(offset: CGSize.zero, blur: 0) context.setAlpha(innerShadow.cgColor.alpha) context.beginTransparencyLayer(auxiliaryInfo: nil) context.setShadow(offset: CGSize(width: 0.1, height: 1), blur: 3, color: UIColor.white.cgColor) context.setBlendMode(.sourceOut) context.beginTransparencyLayer(auxiliaryInfo: nil) let ovalOpaqueShadow = innerShadow.withAlphaComponent(1) ovalOpaqueShadow.setFill() ovalPath.fill() context.endTransparencyLayer() context.endTransparencyLayer() context.restoreGState() context.restoreGState() buttonStroke.setStroke() ovalPath.lineWidth = 1 ovalPath.stroke() frame.origin.x = x } } public class ToggleSlide: UIView { var active: Bool = false public var activeBackgroundColor = UIColor(hex: "#514398") { didSet { setNeedsDisplay() } } public var activeBorderColor = UIColor(hex: "#5B4CA9") { didSet { setNeedsDisplay() } } public var disabledBackgroundColor = UIColor(hex: "#382B76") { didSet { setNeedsDisplay() } } public var disabledBorderColor = UIColor(hex: "#4B3E8D") { didSet { setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func draw(_ rect: CGRect) { let slideFill = active ? activeBackgroundColor : disabledBackgroundColor let slideStroke = active ? activeBorderColor : disabledBorderColor let background = UIBezierPath(roundedRect: CGRect(x: 1, y: 7, width: 48, height: 10), cornerRadius: 10) background.lineWidth = 1 slideFill.setFill() background.fill() slideStroke.setStroke() background.stroke() } } public class ToggleLabel: UIButton { override init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } open class ToggleSwitch: UIView { public var active: Bool = false { didSet { button.active = active slide.active = active button.setNeedsDisplay() slide.setNeedsDisplay() } } public var button = ToggleButton(frame: CGRect(x: 0, y: 1, width: 24, height: 24)) public var slide = ToggleSlide(frame: CGRect(x: 4, y: 0, width: 60, height: 20)) public var label = ToggleLabel(frame: CGRect(x: 70, y: 0, width: 100, height: 22)) public var toggleCallback: (() -> ())? override public init(frame: CGRect) { super.init(frame: frame) backgroundColor = .clear toggleCallback = { print("toggle init") } button.active = active slide.active = active addSubview(slide) addSubview(button) addSubview(label) label.addTarget(self, action: #selector(toggleHandler), for: .touchUpInside) addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleHandler))) addGestureRecognizer(UISwipeGestureRecognizer(target: self, action: #selector(toggleHandler))) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } @objc public func toggleHandler() { UIView.animate( withDuration: 0.15, delay: 0.0, options: .curveEaseIn, animations: { self.button.frame.origin.x = self.active ? 0 : 35 }, completion: { _ in self.active = !self.active self.toggleCallback!() } ) } }
mit
bb8894199b2e9590452635cd7a0e2dd0
24.234742
107
0.656558
4.22231
false
false
false
false
RxLeanCloud/rx-lean-swift
src/RxLeanCloudSwift/Public/RxAVCQL.swift
1
1289
// // RxAVCQL.swift // RxLeanCloudSwift // // Created by WuJun on 14/12/2017. // Copyright © 2017 LeanCloud. All rights reserved. // import Foundation import RxSwift public class RxAVCQL<TEntity> where TEntity: IAVQueryable { public var cql: String public var placeholders: Array<Any>? public init(cql: String) { self.cql = cql } public func execute() -> Observable<Array<TEntity>> { var url = "/cloudQuery?cql=\(self.cql)" if let pValues = self.placeholders { let pStr = AVCorePlugins.sharedInstance.avEncoder.encode(value: pValues) url = "\(url)&pvalues=\(pStr)" } let cmd = AVCommand(relativeUrl: url, method: "GET", data: nil, app: nil) return RxAVClient.sharedInstance.runCommand(cmd: cmd).map({ (avResponse) -> Array<TEntity> in var body = (avResponse.jsonBody)! let results = body["results"] as! Array<Any> return results.map({ (item) -> TEntity in let jsonResult = item as! [String: Any] let state = AVCorePlugins.sharedInstance.objectDecoder.decode(serverResult: jsonResult, decoder: AVCorePlugins.sharedInstance.avDecoder) return TEntity(serverState: state) }) }) } }
mit
c9d0c68bdb630d915df6395b396de14a
32.025641
152
0.621894
3.891239
false
false
false
false
dclelland/GridSpan
GridSpan.swift
1
3194
// // GridSpan.swift // Pods // // Created by Daniel Clelland on 11/03/17. // import UIKit /// A span object representing a rectangular range of cells in a grid. public struct Span { /// A closed range of columns in the grid. /// For example, a value of `0...0` would indicate just the first column. public var columns: ClosedRange<Int> /// A closed range of rows in the grid. /// For example, a value of `0...0` would indicate just the first row. public var rows: ClosedRange<Int> /// Initialize the span with two ranges. public init(columns: ClosedRange<Int>, rows: ClosedRange<Int>) { self.columns = columns self.rows = rows } /// Convenience initializer for initializing the span with for separate components, not unlike CGRect's primary initializer. public init(column: Int, row: Int, columns: Int = 1, rows: Int = 1) { self.init( columns: column...(column + columns - 1), rows: row...(row + rows - 1) ) } } /// A grid struct used to create CGRects aligned to a pixel grid with gutter. public struct Grid { /// The grid's number of columns. public var columns: Int /// The grid's number of rows. public var rows: Int /// The grid's bounds: the frame of reference for all calculations. public var bounds: CGRect /// The grid's gutter: defines the spacing between cells on the grid. public var gutter: CGSize /// Initializes a grid with columns, rows, bounds, and a default gutter. public init(columns: Int, rows: Int, bounds: CGRect, gutter: CGSize = .zero) { self.columns = columns self.rows = rows self.bounds = bounds self.gutter = gutter } /// Calculates a rect for a given span on the grid. /// Rects are aligned to a pixel scale which rounds the output value so that a constant gutter is displayed. /// /// The pixel scale defaults to `UIScreen.main.scale`. public func bounds(for span: Span, scale: CGFloat = UIScreen.main.scale) -> CGRect { let width = (gutter.width + bounds.width) / CGFloat(columns) let height = (gutter.height + bounds.height) / CGFloat(rows) let left = round((CGFloat(span.columns.lowerBound) * width + bounds.minX) * scale) / scale; let top = round((CGFloat(span.rows.lowerBound) * height + bounds.minY) * scale) / scale; let right = round((CGFloat(span.columns.upperBound + 1) * width + bounds.minX - gutter.width) * scale) / scale; let bottom = round((CGFloat(span.rows.upperBound + 1) * height + bounds.minY - gutter.height) * scale) / scale; return CGRect(x: left, y: top, width: right - left, height: bottom - top) } /// Calculates the rect for a given index in the grid, reading left to right and top to bottom. /// /// For example, index 6 on a 4 by 4 grid means the cell at column 2, row 1. public func bounds(for index: Int, scale: CGFloat = UIScreen.main.scale) -> CGRect { return bounds(for: Span(column: index % columns, row: index / columns), scale: scale) } }
mit
db9860770c0c351348b87ef9349c3fff
37.02381
128
0.629305
4.12129
false
false
false
false
Johennes/firefox-ios
Sync/EncryptedJSON.swift
2
3231
/* 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 import FxA import Account import XCGLogger private let log = Logger.syncLogger /** * Turns JSON of the form * * { ciphertext: ..., hmac: ..., iv: ...} * * into a new JSON object resulting from decrypting and parsing the ciphertext. */ public class EncryptedJSON: JSON { var _cleartext: JSON? // Cache decrypted cleartext. var _ciphertextBytes: NSData? // Cache decoded ciphertext. var _hmacBytes: NSData? // Cache decoded HMAC. var _ivBytes: NSData? // Cache decoded IV. var valid: Bool = false var validated: Bool = false let keyBundle: KeyBundle public init(json: String, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(JSON.parse(json)) } public init(json: JSON, keyBundle: KeyBundle) { self.keyBundle = keyBundle super.init(json) } private func validate() -> Bool { if validated { return valid } valid = self["ciphertext"].isString && self["hmac"].isString && self["IV"].isString if (!valid) { validated = true return false } validated = true if let ciphertextForHMAC = self.ciphertextB64 { return keyBundle.verify(hmac: self.hmac, ciphertextB64: ciphertextForHMAC) } else { return false } } public func isValid() -> Bool { return !isError && self.validate() } func fromBase64(str: String) -> NSData { let b = Bytes.decodeBase64(str) return b } var ciphertextB64: NSData? { if let ct = self["ciphertext"].asString { return Bytes.dataFromBase64(ct) } else { return nil } } var ciphertext: NSData { if (_ciphertextBytes != nil) { return _ciphertextBytes! } _ciphertextBytes = fromBase64(self["ciphertext"].asString!) return _ciphertextBytes! } var hmac: NSData { if (_hmacBytes != nil) { return _hmacBytes! } _hmacBytes = NSData(base16EncodedString: self["hmac"].asString!, options: NSDataBase16DecodingOptions.Default) return _hmacBytes! } var iv: NSData { if (_ivBytes != nil) { return _ivBytes! } _ivBytes = fromBase64(self["IV"].asString!) return _ivBytes! } // Returns nil on error. public var cleartext: JSON? { if (_cleartext != nil) { return _cleartext } if (!validate()) { log.error("Failed to validate.") return nil } let decrypted: String? = keyBundle.decrypt(self.ciphertext, iv: self.iv) if (decrypted == nil) { log.error("Failed to decrypt.") valid = false return nil } _cleartext = JSON.parse(decrypted!) return _cleartext! } }
mpl-2.0
7f60889eee7cce5ba489207b7962d32e
24.25
118
0.55927
4.506276
false
false
false
false
sheepy1/SelectionOfZhihu
SelectionOfZhihu/UserDetailModel.swift
1
1144
// // UserDetail.swift // SelectionOfZhihu // // Created by 杨洋 on 16/1/20. // Copyright © 2016年 Sheepy. All rights reserved. // import Foundation class UserDetailModel: NSObject { var ask = 0 as Int64 var answer = 0 as Int64 var post = 0 as Int64 var agree = 0 as Int64 var agreei = 0 as Int64 var agreeiratio = "" var agreeiw = 0 as Int64 var agreeiratiow = "" var ratio = 0 as Int64 var followee = 0 as Int64 var follower = 0 as Int64 var followeri = 0 as Int64 var followiratio = "" var followeriw = 0 as Int64 var followiratiow = "" var thanks = 0 as Int64 var tratio = 0 as Int64 var fav = 0 as Int64 var fratio = 0 as Int64 var logs = 0 as Int64 var mostvote = 0 as Int64 var mostvotepercent = "" var mostvote5 = 0 as Int64 var mostvote5percent = "" var mostvote10 = 0 as Int64 var mostvote10percent = "" var count10000 = 0 as Int64 var count5000 = 0 as Int64 var count2000 = 0 as Int64 var count1000 = 0 as Int64 var count500 = 0 as Int64 var count200 = 0 as Int64 var count100 = 0 as Int64 }
mit
329895c9b36567d417d4a21082e57bfc
24.288889
50
0.630607
3.414414
false
false
false
false
OpsLabJPL/MarsImagesIOS
Pods/SwiftMessages/SwiftMessages/MarginAdjustable+Animation.swift
4
2149
// // MarginAdjustable+Animation.swift // SwiftMessages // // Created by Timothy Moose on 11/5/17. // Copyright © 2017 SwiftKick Mobile. All rights reserved. // import UIKit extension MarginAdjustable where Self: UIView { public func defaultMarginAdjustment(context: AnimationContext) -> UIEdgeInsets { var layoutMargins: UIEdgeInsets = layoutMarginAdditions var safeAreaInsets: UIEdgeInsets if #available(iOS 11, *) { insetsLayoutMarginsFromSafeArea = false safeAreaInsets = self.safeAreaInsets } else { #if SWIFTMESSAGES_APP_EXTENSIONS let application: UIApplication? = nil #else let application: UIApplication? = UIApplication.shared #endif if !context.safeZoneConflicts.isDisjoint(with: [.statusBar]), let app = application, app.statusBarOrientation == .portrait || app.statusBarOrientation == .portraitUpsideDown { let frameInWindow = convert(bounds, to: window) let top = max(0, 20 - frameInWindow.minY) safeAreaInsets = UIEdgeInsets(top: top, left: 0, bottom: 0, right: 0) } else { safeAreaInsets = .zero } } if !context.safeZoneConflicts.isDisjoint(with: .overStatusBar) { safeAreaInsets.top = 0 } layoutMargins = collapseLayoutMarginAdditions ? layoutMargins.collapse(toInsets: safeAreaInsets) : layoutMargins + safeAreaInsets return layoutMargins } } extension UIEdgeInsets { func collapse(toInsets insets: UIEdgeInsets) -> UIEdgeInsets { let top = self.top.collapse(toInset: insets.top) let left = self.left.collapse(toInset: insets.left) let bottom = self.bottom.collapse(toInset: insets.bottom) let right = self.right.collapse(toInset: insets.right) return UIEdgeInsets(top: top, left: left, bottom: bottom, right: right) } } extension CGFloat { func collapse(toInset inset: CGFloat) -> CGFloat { return Swift.max(self, inset) } }
apache-2.0
4c832ec87d1946485a62acc3b5e97005
36.034483
106
0.633147
4.949309
false
false
false
false
hrscy/TodayNews
News/News/Classes/Home/Model/NewsModel.swift
1
17332
// // NewsModel.swift // News // // Created by 杨蒙 on 2018/1/13. // Copyright © 2018年 hrscy. All rights reserved. // import HandyJSON /// 新闻数据模型(首页新闻数据,视频新闻数据,小视频,微头条) struct NewsModel: HandyJSON { var weitoutiaoHeight: CGFloat { // 50 + contentH + 5 + middleViewH + 65 var height: CGFloat = 120 height += contentH height += collectionViewH return height } /// collectionView 高度 var collectionViewH: CGFloat { return Calculate.collectionViewHeight(thumb_image_list.count) } /// collectionView 宽度 var collectionViewW: CGFloat { return Calculate.collectionViewWidth(thumb_image_list.count) } var imageCellHeight: CGFloat { // imageHeight + titleH! + 10 + 40 let imageHeight = screenWidth * 9.0 / 16.0 + titleH return imageHeight + 50 } var girlCellHeight: CGFloat { return contentH + 75 + screenWidth * 1.4 } var jokeCellHeight: CGFloat { // 15 + 50 + 10 + contentH! return 75 + contentH } var cellHeight: CGFloat { // 15 + titleH + 10 + middleViewH + 16 + 10 + bottomViewH + 10 var height: CGFloat = 61 + titleH if video_duration != 0 && video_style == 2 { height += screenWidth * 0.5 } if label_style == .ad && sub_title != "" { height += 40 } if middle_image.url != "" && image_list.count == 0 { return 95 } else { if image_list.count != 0 { if image_list.count == 1 { return 95 } else { height += image3Width } } } return height } var show_more: String = "" let emojiManager = EmojiManager() var ppmmCellHeight: CGFloat { return contentH + 75 + screenWidth * 1.4 } var content = "" var attributedContent: NSMutableAttributedString { return emojiManager.showEmoji(content: content, font: UIFont.systemFont(ofSize: 17)) } var contentH: CGFloat { return content.textHeight(fontSize: 16, width: screenWidth - 30) } var item_id: Int = 0 var cell_flag: Int = 0 var behot_time: Int = 0 var tip: Int = 0 var publish_time: TimeInterval = 0 var publishTime: String { return publish_time.convertString() } var create_time: TimeInterval = 0 var createTime: String { return create_time.convertString() } var source_icon_style: Int = 0 // 1,4,6 右侧视频 var tag_id: Int = 0 var media_info = MediaInfo() var user_info = NewsUserInfo() var user = NewsUserInfo() var preload_web: Int = 0 var cell_layout_style: Int = 0 var group_id: Int = 0 var cell_type: CellType = .none var log_pb = LogPB() var media_name: String = "" var user_repin: Int = 0 var display_url: String = "" var url: String = "" var repin_count: Int = 0 var repinCount: String { return read_count.convertString() } var stick_label: String = "" var show_portrait_article: Bool = false var action_list = [Action]() var user_digg = false var digg_count: Int = 0 var diggCount: String { return digg_count.convertString() } var has_m3u8_video: Bool = false var has_video: Bool = false var item_version: Int = 0 var share_count: Int = 0 var shareCount: String { return share_count.convertString() } var forward_count: Int = 0 var forwardCount: String { guard forward_count != 0 else { return "转发" } return forward_count.convertString() } var source: String = "" var article_alt_url: String = "" var comment_count: Int = 0 var commentCount: String { return comment_count.convertString() } var cursor: Int = 0 var video_style: Int = 0 var show_portrait: Bool = false var stick_style: Int = 0 var ignore_web_transform: Int = 0 var forward_info = ForwardInfo() var is_stick: Bool = false var verified_content: String = "" var share_url: String = "" var bury_count: Int = 0 var buryCount: String { return bury_count.convertString() } var article_sub_type: Int = 0 var allow_download: Bool = false var tag: String = "" var like_count: Int = 0 var likeCount: String { return like_count.convertString() } var level: Int = 0 var read_count: Int = 0 var readCount: String { return read_count.convertString() } var article_type: Int = 0 var user_verified = false var rid: String = "" var title: String = "" var titleH: CGFloat { if video_duration != 0 && video_style == 0 { // // 右侧有图 return title.textHeight(fontSize: 17, width: screenWidth * 0.72 - 30) } else { return title.textHeight(fontSize: 17, width: screenWidth - 30) } } var videoTitleH: CGFloat { return title.textHeight(fontSize: 16, width: screenWidth - 60) } var abstract: String = "" var is_subject: Bool = false var hot: Bool = false // 热 var keywords: String = "" var source_open_url: String = "" var article_url: String = "" var ban_comment: Int = 0 var ugc_recommend = UGCRecommend() var label: String = "" var aggr_type: Int = 0 var has_mp4_video: Int = 0 var hase_image = false var image_list = [ImageList]() var large_image_list = [LargeImage]() var thumb_image_list = [ThumbImage]() var middle_image = MiddleImage() var video_play_info = VideoPlayInfo() var video_detail_info = VideoDetailInfo() var raw_data = SmallVideo() //小视频数据 var video_duration: Int = 0 var video_id: String = "" var videoDuration: String { return video_duration.convertVideoDuration() } var gallary_flag = 0 var gallary_image_count = 0 var large_image = LargeImage() // 广告 var ad_button = ADButton() var ad_id = 0 var ad_label = "" var sub_title = "" var type = "" // app var label_style: NewsLabelStyle = .none // 3 是广告,1是置顶 var app_name = "" var appleid = "" var description = "" var descriptionH: CGFloat { return description.textHeight(fontSize: 13, width: screenWidth - 30) } var download_url = "" var card_type: CardType = .video var is_article = false var is_preview = false var web_url = "" /// 他们也在用 var user_cards = [UserCard]() var position = DongtaiPosition() var repost_params = RepostParam() // 来自。。。 var brand_info = "" } enum CellType: Int, HandyJSONEnum { case none = 0 /// 用户 case user = 32 /// 相关关注 case relatedConcern = 50 } enum NewsLabelStyle: Int, HandyJSONEnum { case none = 0 case topOrLive = 1 // 置顶或直播 case ad = 3 // 广告 } /// 视频类型 enum CardType: String, HandyJSONEnum { case video = "video" // 视频 case adVideo = "ad_video" // 广告视频 case adTextlink = "ad_textlink" // 广告链接 } struct ADButton: HandyJSON { var description: String = "" var download_url: String = "" var id: Int = 0 var web_url: String = "" var app_name: String = "" var track_url: String = "" var ui_type: Int = 0 var click_track_url: String = "" var button_text: String = "" var display_type: Int = 0 var hide_if_exists: Int = 0 var open_url: String = "" var source: String = "" var type: String = "" var package: String = "" var appleid: String = "" var web_title: String = "" } struct SmallVideo: HandyJSON { let emojiManager = EmojiManager() var rich_title: String = "" var group_id: Int = 0 var status = Status() var thumb_image_list = [ThumbImage]() var title: String = "" var attrbutedText: NSMutableAttributedString { return emojiManager.showEmoji(content: title, font: UIFont.systemFont(ofSize: 17)) } var create_time: TimeInterval = 0 var createTime: String { return create_time.convertString() } var recommand_reason: String = "" var first_frame_image_list = [FirstFrameImage]() var action = SmallVideoAction() var app_download = AppDownload() var app_schema: String = "" var interact_label: String = "" var activity: String = "" var large_image_list = [LargeImage]() var group_source: GroupSource = .huoshan var share = Share() var publish_reason = PublishReason() var music = Music() var title_rich_span: String = "" var user = User() var video = Video() var label: String = "" var label_for_list: String = "" var distance: String = "" var detail_schema: String = "" var item_id: Int = 0 var animated_image_list = [AnimatedImage]() var video_neardup_id: Int = 0 /// 他们也在用 var user_cards = [UserCard]() var has_more = false var id = 0 var show_more = "" var show_more_jump_url = "" } /// 小视频类型 enum GroupSource: Int, HandyJSONEnum { case huoshan = 16 case douyin = 19 } struct SmallVideoAction: HandyJSON { var bury_count = 0 var buryCount: String { return bury_count.convertString() } var comment_count = 0 var commentCount: String { return comment_count.convertString() } var digg_count = 0 var diggCount: String { return digg_count.convertString() } var forward_count = 0 var forwardCount: String { return forward_count.convertString() } var play_count = 0 var playCount: String { return play_count.convertString() } var read_count = 0 var readCount: String { return read_count.convertString() } var user_bury = 0 var userBury: String { return user_bury.convertString() } var user_repin = 0 var userRepin: String { return user_repin.convertString() } var user_digg = false } struct AnimatedImage: HandyJSON { var uri: String = "" var image_type: Int = 0 var url_list = [URLList]() var url: String = "" var width: Int = 0 var height: Int = 0 } struct OriginCover: HandyJSON { var uri: String = "" var url_list = [String]() } struct PlayAddr: HandyJSON { var uri: String = "" var url_list = [String]() } struct DownloadAddr: HandyJSON { var uri: String = "" var url_list = [String]() } struct User: HandyJSON { var relation_count = RelationCount() var relation = Relation() var info = Info() } struct Info: HandyJSON { var medals: String = "" var avatar_url: String = "" var schema: String = "" var user_auth_info = UserAuthInfo() var user_id: Int = 0 var desc: String = "" var ban_status: Bool = false var user_verified = false var verified_content: String = "" var media_id: String = "" var name: String = "" var user_decoration: String = "" } struct Relation: HandyJSON { var is_followed = false var is_friend = false var is_following = false var remark_name: String = "" } struct RelationCount: HandyJSON { var followings_count: Int = 0 var followingsCount: String { return followings_count.convertString() } var followers_count: Int = 0 var followersCount: String { return followers_count.convertString() } } struct Music: HandyJSON { var author: String = "" var music_id: Int = 0 var title: String = "" var cover_large: String = "" var album: String = "" var cover_medium: String = "" var cover_thumb: String = "" var cover_hd: String = "" } struct PublishReason: HandyJSON { var noun: String = "" var verb: String = "" } struct AppDownload: HandyJSON { var flag: Int = 0 var text: String = "" } struct Share: HandyJSON { var share_title: String = "" var share_url: String = "" var share_weibo_desc: String = "" var share_cover: String = "" var share_desc: String = "" } struct FirstFrameImage: HandyJSON { var uri: String = "" var image_type: Int = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: Int = 0 var height: Int = 0 } struct Status: HandyJSON { var allow_share: Bool = false var allow_download: Bool = false var allow_comment: Bool = false var is_delete: Bool = false } struct VideoDetailInfo: HandyJSON { var video_preloading_flag: Int = 0 var direct_play: Int = 0 var group_flags: Int = 0 var video_url = [VideoURL]() var detail_video_large_image = DetailVideoLargeImage() var video_third_monitor_url: String = "" var video_watching_count: Int = 0 var videoWatchingCount: String { return video_watching_count.convertString() } var video_id: String = "" var video_watch_count: Int = 0 var videoWatchCount: String { return video_watch_count.convertString() } var video_type: Int = 0 var show_pgc_subscribe: Int = 0 } struct DetailVideoLargeImage: HandyJSON { var height: Int = 0 var url_list: [URLList]! var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: Int = 0 var uri: String = "" } struct VideoURL: HandyJSON { } struct MiddleImage: HandyJSON { var type = ImageType.normal var height: CGFloat = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: CGFloat = 0 var uri: String = "" /// 宽高比 var ratio: CGFloat? { return width / height } } /// 图片的类型 enum ImageType: Int, HandyJSONEnum { case normal = 1 // 一般图片 case gif = 2 // gif 图 } struct ImageList: HandyJSON { var type = ImageType.normal var height: CGFloat = 0 var url_list = [URLList]() var url: NSString = "" var urlString: String { guard url.hasSuffix(".webp") else { return url as String } return url.replacingCharacters(in: NSRange(location: url.length - 5, length: 5), with: ".png") } var width: CGFloat = 0 var uri: String = "" /// 宽高比 var ratio: CGFloat? { return width / height } } struct NewsUserInfo: HandyJSON { var follow: Bool = false var name: String = "" var user_verified: Bool = false var verified_content: String = "" var user_id: Int = 0 var id: Int = 0 var description: String = "" var desc: String = "" var avatar_url: String = "" var follower_count: Int = 0 var followerCount: String { return follower_count.convertString() } var user_decoration: String! var subcribed: Int = 0 var fans_count: Int = 0 var fansCount: String { return fans_count.convertString() } var special_column = [SpecialColumn]() var user_auth_info: String! var media_id: Int = 0 var screen_name = "" var is_followed: Bool = false var is_following: Bool = false // 是否正在关注 var is_blocking: Bool = false var is_blocked: Bool = false var is_friend: Bool = false var medals = [String]() // hot_post (热门内容) } struct ForwardInfo: HandyJSON { var forward_count: Int = 0 var forwardCount: String { return forward_count.convertString() } } struct UGCRecommend: HandyJSON { var activity = "" var reason = "" } struct MediaInfo: HandyJSON { var follow: Bool = false var is_star_user: Bool = false var recommend_reason: String = "" var user_verified: Bool = false var media_id: Int = 0 var verified_content: String = "" var user_id: Int = 0 var recommend_type: Int = 0 var avatar_url: String = "" var name: String = "" } struct LogPB: HandyJSON { var impr_id: String = "" } struct Extra: HandyJSON { } struct Action: HandyJSON { var extra = Extra() var action: Int = 0 var desc: String = "" } struct FilterWord: HandyJSON { var id: String = "" var name: String = "" var is_selected: Bool = false } struct DnsInfo: HandyJSON { } struct OriginalPlayURL: HandyJSON { var main_url: String = "" var backup_url: String = "" } struct VideoPlayInfo: HandyJSON { var status: Int = 0 var dns_info = DnsInfo() var enable_ssl: Bool = false var poster_url: String = "" var message: String = "" var video_list = VideoList() var original_play_url = OriginalPlayURL() var video_duration: Int = 0 var videoDuration: String { return video_duration.convertVideoDuration() } var validate: String = "" } struct NewsDetailImage: HandyJSON { var url: String = "" var width: CGFloat = 0 var height: CGFloat = 0 var rate: CGFloat = 1 var url_list = [URLList]() }
mit
05a09db20e22fe1b9c38e356744f46a5
26.347756
141
0.607384
3.801515
false
false
false
false
ubiregiinc/UbiregiExtensionClient
UbiregiExtensionClientTests/TestHelper.swift
1
2018
import Foundation import Swifter import XCTest func withSwifter(port: UInt16 = 8081, k: (HttpServer) throws -> ()) { let server = HttpServer() try! server.start(port) defer { server.stop() } try! k(server) } func returnJSON(object: [String: AnyObject]) -> HttpRequest -> HttpResponse { return { (response: HttpRequest) in HttpResponse.OK(HttpResponseBody.Json(object)) } } func dictionary(pairs: [(String, String)]) -> [String: String] { var h: [String: String] = [:] for p in pairs { h[p.0] = p.1 } return h } class NotificationTrace: NSObject { var notifications: [NSNotification] override init() { self.notifications = [] } func didReceiveNotification(notification: NSNotification) { self.notifications.append(notification) } func notificationNames() -> [String] { return self.notifications.map { $0.name } } func observeNotification(name: String, object: AnyObject?) { NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveNotification:", name: name, object: object) } } func waitFor(timeout: NSTimeInterval, message: String? = nil, predicate: () -> Bool) { let endTime = NSDate().dateByAddingTimeInterval(timeout) while NSDate().compare(endTime) == NSComparisonResult.OrderedAscending { NSThread.sleepForTimeInterval(0.1) if predicate() { return } } XCTAssert(false, message ?? "Timeout exceeded for waitFor") } func globally(timeout: NSTimeInterval = 1, message: String? = nil, predicate: () -> Bool) { let endTime = NSDate().dateByAddingTimeInterval(timeout) while NSDate().compare(endTime) == NSComparisonResult.OrderedAscending { NSThread.sleepForTimeInterval(0.1) if !predicate() { XCTAssert(false, message ?? "predicate does not hold which expected to hold globally") return } } }
mit
67d0eda71f5181739f2a8aafa70563f8
25.92
127
0.634291
4.534831
false
false
false
false
frtlupsvn/Vietnam-To-Go
Pods/Former/Former/Controllers/FormViewController.swift
1
1715
// // FomerViewController.swift // Former-Demo // // Created by Ryo Aoyama on 7/23/15. // Copyright © 2015 Ryo Aoyama. All rights reserved. // import UIKit public class FormViewController: UIViewController { // MARK: Public public let tableView: UITableView = { let tableView = UITableView(frame: CGRect.zero, style: .Grouped) tableView.backgroundColor = .clearColor() tableView.contentInset.bottom = 10 tableView.sectionHeaderHeight = 0 tableView.sectionFooterHeight = 0 tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.01)) tableView.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: 0.01)) tableView.translatesAutoresizingMaskIntoConstraints = false return tableView }() public lazy var former: Former = Former(tableView: self.tableView) public override func viewDidLoad() { super.viewDidLoad() setup() } // MARK: Private private final func setup() { view.backgroundColor = .groupTableViewBackgroundColor() view.insertSubview(tableView, atIndex: 0) let tableConstraints = [ NSLayoutConstraint.constraintsWithVisualFormat( "V:|-0-[table]-0-|", options: [], metrics: nil, views: ["table": tableView] ), NSLayoutConstraint.constraintsWithVisualFormat( "H:|-0-[table]-0-|", options: [], metrics: nil, views: ["table": tableView] ) ].flatMap { $0 } view.addConstraints(tableConstraints) } }
mit
60da3de14edfb2bd492eeee383a56c7f
30.759259
93
0.589265
5.011696
false
false
false
false
practicalswift/swift
benchmark/single-source/ArraySetElement.swift
2
1244
//===--- ArraySetElement.swift ---------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import TestsUtils // 33% isUniquelyReferenced // 15% swift_rt_swift_isUniquelyReferencedOrPinned_nonNull_native // 18% swift_isUniquelyReferencedOrPinned_nonNull_native public var ArraySetElement = BenchmarkInfo( name: "ArraySetElement", runFunction: run_ArraySetElement, tags: [.runtime, .cpubench] ) // This is an effort to defeat isUniquelyReferenced optimization. Ideally // microbenchmarks list this should be written in C. @inline(never) func storeArrayElement(_ array: inout [Int], _ i: Int) { array[i] = i } public func run_ArraySetElement(_ N: Int) { var array = [Int](repeating: 0, count: 10000) for _ in 0..<10*N { for i in 0..<array.count { storeArrayElement(&array, i) } } }
apache-2.0
a7be43d07c7b5ff6b15b5a6b69e61602
31.736842
81
0.643891
4.319444
false
false
false
false
priyanka16/RPChatUI
RPChatUI/Classes/TimeSlotTableViewCell.swift
1
3881
// // TimeSlotTableViewCell.swift // // // Created by Priyanka // Copyright © 2017 __MyCompanyName__. All rights reserved. // import UIKit let timeTabletWidth: CGFloat = 150 let timeTabletHeight: CGFloat = 50 fileprivate let itemsPerRow: CGFloat = 3 protocol TimeSlotTableViewCellDelegate : class { func didSelectTime() } class TimeSlotTableViewCell: ChatMessageCell { var timeOptions = NSDictionary() fileprivate let sectionInsets = UIEdgeInsets(top: 10.0, left: 10.0, bottom: 9.0, right: 10.0) weak var delegate: TimeSlotTableViewCellDelegate? @IBOutlet weak var daysTableView: UITableView! @IBOutlet weak var timeslotTableView: UITableView! @IBOutlet weak var containerViewTopConstraint: NSLayoutConstraint! func setupCell(message: ChatMessage) { let viewYconstant = super.computedTextAreaHeight(message: message) super.setupWithMessage(message: message) self.messageBubbleView.frame.origin.x = (self.botImageView.bounds.width + 10) containerViewTopConstraint.constant = viewYconstant + 10 if let dict = message.options?[0] { if let timeDict = dict["availableTimeSlots"] as? NSDictionary { timeOptions = timeDict } } } func remainingDaysOfWeek() -> Int { let myCalendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = myCalendar.components(.weekday, from: Date()) let weekDay = myComponents.weekday! - 1 return 7 - weekDay } func dayOfWeek(day: Date) -> Int { let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)! let myComponents = calendar.components(.weekday, from: day) return myComponents.weekday! } func dayOfWeek(dayIndex: Int) -> String { let weekDay = Calendar.current.date(byAdding: .day, value: dayIndex, to: Date()) let dateFormatter = DateFormatter() let daysOfWeek = dateFormatter.shortWeekdaySymbols let dayIndex = dayOfWeek(day: weekDay!)-1 return (daysOfWeek?[dayIndex])! } func dayOfWeekKeyString(dayIndex: Int) -> String { let weekDay = Calendar.current.date(byAdding: .day, value: dayIndex, to: Date()) let dateFormatter = DateFormatter() let daysOfWeek = dateFormatter.weekdaySymbols let dayIndex = dayOfWeek(day: weekDay!)-1 return (daysOfWeek?[dayIndex])! } } extension TimeSlotTableViewCell: UITableViewDataSource { private func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return remainingDaysOfWeek() } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if (tableView == daysTableView) { let cell = tableView.dequeueReusableCell(withIdentifier: "DayNameTableViewCell", for: indexPath) cell.textLabel?.font = UIFont(name: "SFUIText-Regular", size: 16.0) cell.textLabel?.textColor = UIColor(red: 49 / 255.0, green: 63 / 255.0, blue: 72 / 255.0, alpha: 1.0) cell.textLabel?.text = dayOfWeek(dayIndex: indexPath.row) cell.textLabel?.textAlignment = .right return cell } else { let cell = tableView.dequeueReusableCell(withIdentifier: "TimeSlotTubeTableViewCell", for: indexPath) as! TimeSlotTubeTableViewCell let weekdayKey = dayOfWeekKeyString(dayIndex: indexPath.row).lowercased() if let timeSlots = timeOptions.object(forKey: weekdayKey) as? [String] { cell.setupCell(timeDate: timeSlots) } return cell } } }
mit
037428b73fd962dcce1871440568abf4
36.669903
143
0.659536
4.942675
false
false
false
false
lerigos/music-service
iOS_9/Pods/SwiftyVK/Source/SDK/Models/Error.swift
2
2783
import Foundation public class _VKError : ErrorType, CustomStringConvertible { public var domain : String public var code: Int public var desc : String public var userInfo : [NSObject: AnyObject]? ///The reference to a request to the API, in which the error occurred public var request : Request? public var description : String { return "VK.Error \(domain)_(\(code)): \(desc)" } public init(ns: NSError, req: Request?) { self.domain = ns.domain self.code = ns.code self.desc = ns.localizedDescription self.userInfo = ns.userInfo self.request = req if let request = request { VK.Log.put(request, "Init error of error and request \(self)") } } public init(domain: String, code: Int, desc: String, userInfo: [NSObject: AnyObject]?, req: Request?) { self.domain = domain self.code = code self.desc = desc self.userInfo = userInfo self.request = req if let request = request { VK.Log.put(request, "Init custom error \(self)") } } public init(json : JSON, request : Request) { self.request = request domain = "APIError" code = json["error_code"].intValue desc = json["error_msg"].stringValue var info = [NSObject : AnyObject]() for param in json["request_params"].arrayValue { info[param["key"].stringValue] = param["value"].stringValue } for (key, value) in json.dictionaryValue { if key != "request_params" && key != "error_code" { info[key] = value.stringValue } } userInfo = info VK.Log.put(request, "Init error of JSON \(self)") } public func `catch`() { if let request = request { VK.Log.put(request, "Catch error \(self)") } switch self.domain { case "APIError": catchAPIDomain() default: finaly() } } private func catchAPIDomain() { switch code { case 5: request?.authFails += 1 request?.attempts -= 1 Authorizator.autorize(request) case 6, 9, 10: Connection.needLimit = true finaly() case 14: if !sharedCaptchaIsRun { request?.attempts -= 1 СaptchaController.start( sid: userInfo!["captcha_sid"] as! String, imageUrl: userInfo!["captcha_img"] as! String, request: request!) } case 17: request?.attempts -= 1 WebController.validate(request!, validationUrl: userInfo!["redirect_uri"] as! String) default: finaly() } } public func finaly() { if let request = request { request.trySend() } } deinit { if let request = request { request.isAPI ? VK.Log.put(request, "DEINIT \(self)") : () } } }
apache-2.0
9716e9e7752a02c7804f1cbf2a04f0e1
21.256
105
0.589145
4.091176
false
false
false
false
jpsachse/mensa-griebnitzsee
Mensa Griebnitzsee/ViewController.swift
1
6479
// // ViewController.swift // Mensa Griebnitzsee // // Copyright © 2017 Jan Philipp Sachse. All rights reserved. // import UIKit import MensaKit class ViewController: UICollectionViewController { let menuLoader = MenuLoader() var loadedMenu: Menu? let dateFormatter = DateFormatter() let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() dateFormatter.locale = NSLocale.current dateFormatter.dateStyle = .full dateFormatter.timeStyle = .none refreshControl.addTarget(self, action: #selector(updateMenu), for: .valueChanged) collectionView?.addSubview(refreshControl) // support dragging of entries into other apps, because why not collectionView?.dragDelegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) view.layoutIfNeeded() updateCollectionViewLayout() } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { coordinator.animate(alongsideTransition: { [unowned self] (context) in self.updateCollectionViewLayout() }) { (context) in } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) refreshControl.beginRefreshing() let order = Calendar.current.compare(menuLoader.lastUpdatedDate, to: Date(), toGranularity: .day) if order == .orderedSame, let menu = menuLoader.loadMenuFromDisk() { self.loadedMenu = menu self.collectionView?.reloadData() self.refreshControl.endRefreshing() } else { updateMenu() } } @objc func updateMenu() { menuLoader.load { [unowned self] (menu) in self.loadedMenu = menu DispatchQueue.main.async { [unowned self] in self.collectionView?.reloadData() self.refreshControl.endRefreshing() } } } func updateCollectionViewLayout() { if UIApplication.shared.keyWindow?.traitCollection.horizontalSizeClass == .regular { collectionView?.collectionViewLayout = getColumnLayout() } else { collectionView?.collectionViewLayout = getRowLayout() } } func getCommonLayout(with padding: CGFloat) -> UICollectionViewFlowLayout { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical layout.minimumLineSpacing = 10 layout.sectionInset = UIEdgeInsetsMake(padding, padding, padding, padding) layout.headerReferenceSize = CGSize(width: collectionView!.frame.width, height: 40) return layout } func getRowLayout() -> UICollectionViewFlowLayout { let defaultPadding: CGFloat = 10 let rowLayout = getCommonLayout(with: defaultPadding) rowLayout.itemSize = CGSize(width: collectionView!.frame.width - 2 * defaultPadding, height: 100) return rowLayout } func getColumnLayout() -> UICollectionViewFlowLayout { let defaultPadding: CGFloat = 10 let rowLayout = getCommonLayout(with: defaultPadding) rowLayout.itemSize = CGSize(width: collectionView!.frame.width / 2 - 1.5 * defaultPadding, height: 150) return rowLayout } override func numberOfSections(in collectionView: UICollectionView) -> Int { if let loadedMenu = loadedMenu { return loadedMenu.entries.count } return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let loadedMenu = loadedMenu { let entry = loadedMenu.entries[section] if entry.closed { return 1 } return loadedMenu.entries[section].dishes.count } return 1 } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { guard let loadedMenu = loadedMenu, indexPath.section < loadedMenu.entries.count else { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "noDataCell", for: indexPath) cell.layer.cornerRadius = 10 return cell } let entry = loadedMenu.entries[indexPath.section] var cell: UICollectionViewCell! if entry.closed { cell = collectionView.dequeueReusableCell(withReuseIdentifier: "closedCell", for: indexPath) } else { cell = collectionView.dequeueReusableCell(withReuseIdentifier: "menuCell", for: indexPath) if let cell = cell as? MenuCollectionViewCell, indexPath.row < entry.dishes.count { let dish = entry.dishes[indexPath.row] cell.categoryLabel.text = dish.category cell.dishNameLabel.text = dish.name cell.notesLabel.text = dish.notes.joined(separator: ", ") } } cell.layer.cornerRadius = 10 return cell } override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "sectionHeader", for: indexPath) guard let menuHeader = view as? MenuHeaderCollectionReusableView else { return view } if let loadedMenu = loadedMenu { let dateString = dateFormatter.string(from: loadedMenu.entries[indexPath.section].date) menuHeader.label.text = dateString } else { menuHeader.label.text = nil } return view } } extension ViewController: UICollectionViewDragDelegate { func getDragItems(for indexPath: IndexPath) -> [UIDragItem] { guard let loadedMenu = loadedMenu, indexPath.section < loadedMenu.entries.count, indexPath.row < loadedMenu.entries[indexPath.section].dishes.count else { return [] } let dish = loadedMenu.entries[indexPath.section].dishes[indexPath.row] let provider = NSItemProvider(object: dish.description as NSString) let item = UIDragItem(itemProvider: provider) return [item] } func collectionView(_ collectionView: UICollectionView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] { return getDragItems(for: indexPath) } func collectionView(_ collectionView: UICollectionView, itemsForAddingTo session: UIDragSession, at indexPath: IndexPath, point: CGPoint) -> [UIDragItem] { return getDragItems(for: indexPath) } }
mit
ecab3f457758ccc73f10466f345b5506
35.189944
133
0.697437
5.161753
false
false
false
false
adamnemecek/AudioKit
Sources/AudioKit/Internals/Hardware/Device.swift
1
2809
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/ #if os(macOS) /// DeviceID isan AudioDeviceID on macOS public typealias DeviceID = AudioDeviceID #else /// DeviceID is a string on iOS public typealias DeviceID = String #endif import AVFoundation /// Wrapper for audio device selection public struct Device: Equatable, Hashable { /// The human-readable name for the device. public private(set) var name: String /// Number of input channels public private(set) var inputChannelCount: Int? /// Number of output channels public private(set) var outputChannelCount: Int? /// The device identifier. public private(set) var deviceID: DeviceID /// Initialize the device /// /// - Parameters: /// - name: The human-readable name for the device. /// - deviceID: The device identifier. /// - dataSource: String describing data source /// public init(name: String, deviceID: DeviceID, dataSource: String = "") { self.name = name self.deviceID = deviceID #if !os(macOS) if dataSource != "" { self.deviceID = "\(deviceID) \(dataSource)" } #endif } #if os(macOS) /// Initialize the device /// - Parameter deviceID: DeviceID public init(deviceID: DeviceID) { self.init(name: AudioDeviceUtils.name(deviceID), deviceID: deviceID) inputChannelCount = AudioDeviceUtils.inputChannels(deviceID) outputChannelCount = AudioDeviceUtils.outputChannels(deviceID) } #endif #if !os(macOS) /// Initialize the device /// /// - Parameters: /// - portDescription: A port description object that describes a single /// input or output port associated with an audio route. /// public init(portDescription: AVAudioSessionPortDescription) { let portData = [portDescription.uid, portDescription.selectedDataSource?.dataSourceName] let deviceID = portData.compactMap { $0 }.joined(separator: " ") self.init(name: portDescription.portName, deviceID: deviceID) } /// Return a port description matching the devices name. var portDescription: AVAudioSessionPortDescription? { return AVAudioSession.sharedInstance().availableInputs?.filter { $0.portName == name }.first } /// Return a data source matching the devices deviceID. var dataSource: AVAudioSessionDataSourceDescription? { let dataSources = portDescription?.dataSources ?? [] return dataSources.filter { deviceID.contains($0.dataSourceName) }.first } #endif } extension Device: CustomDebugStringConvertible { /// Printout for debug public var debugDescription: String { return "<Device: \(name) (\(deviceID))>" } }
mit
3630290ffa1a1e977971e83c203bde69
32.843373
100
0.673549
4.777211
false
false
false
false
spark/photon-tinker-ios
Photon-Tinker/Global/Extensions/ParticleDevice.swift
1
6166
// // Created by Raimundas Sakalauskas on 2019-05-09. // Copyright (c) 2019 Particle. All rights reserved. // import Foundation extension ParticleDevice { func isRunningTinker() -> Bool { if (self.connected && self.functions.contains("digitalread") && self.functions.contains("digitalwrite") && self.functions.contains("analogwrite") && self.functions.contains("analogread")) { return true } else { return false } } func is3rdGen() -> Bool { return self.type == .argon || self.type == .boron || self.type == .xenon || self.type == .aSeries || self.type == .bSeries || self.type == .xSeries || self.type == .b5SoM } func getName() -> String { if let name = self.name, name.count > 0 { return name } else { return TinkerStrings.Device.NoName } } func getInfoDetails() -> [String: Any] { var info: [String: Any] = [:] info[TinkerStrings.InfoSlider.DeviceCell.DeviceType] = self.type info[TinkerStrings.InfoSlider.DeviceCell.DeviceId] = self.id ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.Serial] = self.serialNumber ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.DeviceOS] = self.systemFirmwareVersion ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.LastIPAddress] = self.lastIPAdress ?? TinkerStrings.InfoSlider.DeviceCell.Unknown if let lastHeard = self.lastHeard { info[TinkerStrings.InfoSlider.DeviceCell.LastHeard] = DateFormatter.localizedString(from: lastHeard, dateStyle: .medium, timeStyle: .short) } else { info[TinkerStrings.InfoSlider.DeviceCell.LastHeard] = TinkerStrings.InfoSlider.DeviceCell.Never } if (self.cellular) { info[TinkerStrings.InfoSlider.DeviceCell.IMEI] = self.imei ?? TinkerStrings.InfoSlider.DeviceCell.Unknown info[TinkerStrings.InfoSlider.DeviceCell.LastICCID] = self.lastIccid ?? TinkerStrings.InfoSlider.DeviceCell.Unknown } return info } func getInfoDetailsOrder() -> [String] { if (self.cellular) { return [TinkerStrings.InfoSlider.DeviceCell.DeviceType, TinkerStrings.InfoSlider.DeviceCell.DeviceId, TinkerStrings.InfoSlider.DeviceCell.Serial, TinkerStrings.InfoSlider.DeviceCell.IMEI, TinkerStrings.InfoSlider.DeviceCell.LastICCID, TinkerStrings.InfoSlider.DeviceCell.DeviceOS, TinkerStrings.InfoSlider.DeviceCell.LastIPAddress, TinkerStrings.InfoSlider.DeviceCell.LastHeard] } else { return [TinkerStrings.InfoSlider.DeviceCell.DeviceType, TinkerStrings.InfoSlider.DeviceCell.DeviceId, TinkerStrings.InfoSlider.DeviceCell.Serial, TinkerStrings.InfoSlider.DeviceCell.DeviceOS, TinkerStrings.InfoSlider.DeviceCell.LastIPAddress, TinkerStrings.InfoSlider.DeviceCell.LastHeard] } } } extension ParticleDeviceType { func getImage() -> UIImage? { switch (self) { case .core: return UIImage(named: "ImgDeviceCore") case .electron: return UIImage(named: "ImgDeviceElectron") case .photon: return UIImage(named: "ImgDevicePhoton") case .P1: return UIImage(named: "ImgDeviceP1") case .raspberryPi: return UIImage(named: "ImgDeviceRaspberryPi") case .redBearDuo: return UIImage(named: "ImgDeviceRedBearDuo") case .bluz: return UIImage(named: "ImgDeviceBluz") case .digistumpOak: return UIImage(named: "ImgDeviceDigistumpOak") case .xenon: return UIImage(named: "ImgDeviceXenon") case .argon: return UIImage(named: "ImgDeviceArgon") case .boron: return UIImage(named: "ImgDeviceBoron") case .xSeries: return UIImage(named: "ImgDeviceXenon") case .aSeries: return UIImage(named: "ImgDeviceArgon") case .bSeries: return UIImage(named: "ImgDeviceBoron") case .b5SoM: return UIImage(named: "ImgDeviceBoron") default: return UIImage(named: "ImgDeviceUnknown") } } func getIconColor() -> UIColor { switch (self) { case .core: return UIColor(rgb: 0x76777A) case .electron: return UIColor(rgb: 0x00AE42) case .photon, .P1: return UIColor(rgb: 0xB31983) case .raspberryPi, .redBearDuo, .ESP32, .bluz: return UIColor(rgb: 0x76777A) case .argon, .aSeries: return UIColor(rgb: 0x00AEEF) case .boron, .bSeries, .b5SoM: return UIColor(rgb: 0xED1C24) case .xenon, .xSeries: return UIColor(rgb: 0xF5A800) default: return UIColor(rgb: 0x76777A) } } func getIconText() -> String { switch (self) { case .core: return "C" case .electron: return "E" case .photon: return "P" case .P1: return "1" case .raspberryPi: return "R" case .redBearDuo: return "D" case .ESP32: return "ES" case .bluz: return "BZ" case .xenon, .xSeries: return "X" case .argon, .aSeries: return "A" case .boron, .bSeries, .b5SoM: return "B" default: return "?" } } }
apache-2.0
db480ea5bf8239dd90794241566e72e3
35.922156
197
0.562115
4.68541
false
false
false
false
ObjectAlchemist/OOUIKit
Sources/Screen/ScreenOR.swift
1
1717
// // ScreenOR.swift // OOSwift // // Created by Karsten Litsche on 01.09.17. // // import UIKit import OOBase /** A screen container that displays primary OR secondary child content depending on condition. The container listens for changes in the adapter and updates content automatically. */ public final class ScreenOR: OOScreen { // MARK: init public init(condition: OOBool, conditionChangeListener: OOEventInform, isTrue primary: @escaping (UIViewController) -> OOScreen, isFalse secondary: @escaping (UIViewController) -> OOScreen) { self.condition = condition self.conditionChangeListener = conditionChangeListener self.primary = primary self.secondary = secondary } // MARK: protocol OOScreen public var ui: UIViewController { let controller = ORContainerViewController(primaryAvailable: condition, primary: primary, secondary: secondary) conditionChangeListener.set(onEvent: { [weak controller] in controller?.update() }) return controller } // MARK: private private let condition: OOBool private let conditionChangeListener: OOEventInform private let primary: (UIViewController) -> OOScreen private let secondary: (UIViewController) -> OOScreen } // convenience initializer public extension ScreenOR { convenience init(condition: OOWritableBool & OOEventInform, isTrue primary: @escaping (UIViewController) -> OOScreen, isFalse secondary: @escaping (UIViewController) -> OOScreen) { self.init(condition: condition, conditionChangeListener: condition, isTrue: primary, isFalse: secondary) } }
mit
9bb62b76c31c4599e3ec92ab390d0ca0
30.796296
184
0.695399
5.110119
false
false
false
false
sekouperry/bemyeyes-ios
BeMyEyes/Source/Other sources/KeychainAccess/Keychain.swift
2
136516
// // Keychain.swift // KeychainAccess // // Created by kishikawa katsumi on 2014/12/24. // Copyright (c) 2014 kishikawa katsumi. All rights reserved. // import Foundation import Security public let KeychainAccessErrorDomain = "com.kishikawakatsumi.KeychainAccess.error" public enum ItemClass { case GenericPassword case InternetPassword } public enum ProtocolType { case FTP case FTPAccount case HTTP case IRC case NNTP case POP3 case SMTP case SOCKS case IMAP case LDAP case AppleTalk case AFP case Telnet case SSH case FTPS case HTTPS case HTTPProxy case HTTPSProxy case FTPProxy case SMB case RTSP case RTSPProxy case DAAP case EPPC case IPP case NNTPS case LDAPS case TelnetS case IMAPS case IRCS case POP3S } public enum AuthenticationType { case NTLM case MSN case DPA case RPA case HTTPBasic case HTTPDigest case HTMLForm case Default } public enum Accessibility { case WhenUnlocked case AfterFirstUnlock case Always case WhenPasscodeSetThisDeviceOnly case WhenUnlockedThisDeviceOnly case AfterFirstUnlockThisDeviceOnly case AlwaysThisDeviceOnly } public enum AuthenticationPolicy : Int { case UserPresence } public enum FailableOf<T> { case Success(Value<T?>) case Failure(NSError) init(_ value: T?) { self = .Success(Value(value)) } init(_ error: NSError) { self = .Failure(error) } public var succeeded: Bool { switch self { case .Success: return true default: return false } } public var failed: Bool { switch self { case .Failure: return true default: return false } } public var error: NSError? { switch self { case .Failure(let error): return error default: return nil } } public var value: T? { switch self { case .Success(let success): return success.value default: return nil } } } public class Value<T> { let value: T init(_ value: T) { self.value = value } } public class Keychain { public var itemClass: ItemClass { return options.itemClass } public var service: String { return options.service } public var accessGroup: String? { return options.accessGroup } public var server: NSURL { return options.server } public var protocolType: ProtocolType { return options.protocolType } public var authenticationType: AuthenticationType { return options.authenticationType } public var accessibility: Accessibility { return options.accessibility } @availability(iOS, introduced=8.0) @availability(OSX, introduced=10.10) public var authenticationPolicy: AuthenticationPolicy? { return options.authenticationPolicy } public var synchronizable: Bool { return options.synchronizable } public var label: String? { return options.label } public var comment: String? { return options.comment } @availability(iOS, introduced=8.0) @availability(OSX, unavailable) public var authenticationPrompt: String? { return options.authenticationPrompt } private let options: Options private let NSFoundationVersionNumber_iOS_7_1 = 1047.25 private let NSFoundationVersionNumber_iOS_8_0 = 1140.11 private let NSFoundationVersionNumber_iOS_8_1 = 1141.1 private let NSFoundationVersionNumber10_9_2 = 1056.13 // MARK: public convenience init() { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } self.init(options) } public convenience init(service: String) { var options = Options() options.service = service self.init(options) } public convenience init(accessGroup: String) { var options = Options() if let bundleIdentifier = NSBundle.mainBundle().bundleIdentifier { options.service = bundleIdentifier } options.accessGroup = accessGroup self.init(options) } public convenience init(service: String, accessGroup: String) { var options = Options() options.service = service options.accessGroup = accessGroup self.init(options) } public convenience init(server: String, protocolType: ProtocolType) { self.init(server: NSURL(string: server)!, protocolType: protocolType) } public convenience init(server: String, protocolType: ProtocolType, authenticationType: AuthenticationType) { self.init(server: NSURL(string: server)!, protocolType: protocolType, authenticationType: .Default) } public convenience init(server: NSURL, protocolType: ProtocolType) { self.init(server: server, protocolType: protocolType, authenticationType: .Default) } public convenience init(server: NSURL, protocolType: ProtocolType, authenticationType: AuthenticationType) { var options = Options() options.itemClass = .InternetPassword options.server = server options.protocolType = protocolType options.authenticationType = authenticationType self.init(options) } private init(_ opts: Options) { options = opts } // MARK: public func accessibility(accessibility: Accessibility) -> Keychain { var options = self.options options.accessibility = accessibility return Keychain(options) } @availability(iOS, introduced=8.0) @availability(OSX, introduced=10.10) public func accessibility(accessibility: Accessibility, authenticationPolicy: AuthenticationPolicy) -> Keychain { var options = self.options options.accessibility = accessibility options.authenticationPolicy = authenticationPolicy return Keychain(options) } public func synchronizable(synchronizable: Bool) -> Keychain { var options = self.options options.synchronizable = synchronizable return Keychain(options) } public func label(label: String) -> Keychain { var options = self.options options.label = label return Keychain(options) } public func comment(comment: String) -> Keychain { var options = self.options options.comment = comment return Keychain(options) } @availability(iOS, introduced=8.0) @availability(OSX, unavailable) public func authenticationPrompt(authenticationPrompt: String) -> Keychain { var options = self.options options.authenticationPrompt = authenticationPrompt return Keychain(options) } // MARK: public func get(key: String) -> String? { return getString(key) } public func getString(key: String) -> String? { let failable = getStringOrError(key) return failable.value } public func getData(key: String) -> NSData? { let failable = getDataOrError(key) return failable.value } public func getStringOrError(key: String) -> FailableOf<String> { let failable = getDataOrError(key) switch failable { case .Success: if let data = failable.value { if let string = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { return FailableOf(string) } return FailableOf(conversionError(message: "failed to convert data to string")) } else { return FailableOf(nil) } case .Failure(let error): return FailableOf(error) } } public func getDataOrError(key: String) -> FailableOf<NSData> { var query = options.query() query[kSecMatchLimit as! String] = kSecMatchLimitOne query[kSecReturnData as! String] = kCFBooleanTrue query[kSecAttrAccount as! String] = key var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let data = result as? NSData { return FailableOf(data) } return FailableOf(securityError(status: Status.UnexpectedError.rawValue)) case errSecItemNotFound: return FailableOf(nil) default: () } return FailableOf(securityError(status: status)) } // MARK: public func set(value: String, key: String) -> NSError? { if let data = value.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) { return set(data, key: key) } return conversionError(message: "failed to convert string to data") } public func set(value: NSData, key: String) -> NSError? { var query = options.query() query[kSecAttrAccount as! String] = key #if os(iOS) if floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) { query[kSecUseNoAuthenticationUI as! String] = kCFBooleanTrue } #endif var status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess, errSecInteractionNotAllowed: var query = options.query() query[kSecAttrAccount as! String] = key var (attributes, error) = options.attributes(key: nil, value: value) if var error = error { println("error:[\(error.code)] \(error.localizedDescription)") return error } else { if status == errSecInteractionNotAllowed && floor(NSFoundationVersionNumber) <= floor(NSFoundationVersionNumber_iOS_8_0) { var error = remove(key) if error != nil { return error } else { return set(value, key: key) } } else { status = SecItemUpdate(query, attributes) } if status != errSecSuccess { return securityError(status: status) } } case errSecItemNotFound: var (attributes, error) = options.attributes(key: key, value: value) if var error = error { println("error:[\(error.code)] \(error.localizedDescription)") return error } else { status = SecItemAdd(attributes, nil) if status != errSecSuccess { return securityError(status: status) } } default: return securityError(status: status) } return nil } // MARK: public func remove(key: String) -> NSError? { var query = options.query() query[kSecAttrAccount as! String] = key let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { return securityError(status: status) } return nil } public func removeAll() -> NSError? { var query = options.query() #if !os(iOS) query[kSecMatchLimit as! String] = kSecMatchLimitAll #endif let status = SecItemDelete(query) if status != errSecSuccess && status != errSecItemNotFound { return securityError(status: status) } return nil } // MARK: public func contains(key: String) -> Bool { var query = options.query() query[kSecAttrAccount as! String] = key var status = SecItemCopyMatching(query, nil) switch status { case errSecSuccess: return true case errSecItemNotFound: return false default: securityError(status: status) return false } } // MARK: public subscript(key: String) -> String? { get { return get(key) } set { if let value = newValue { set(value, key: key) } else { remove(key) } } } // MARK: public class func allKeys(itemClass: ItemClass) -> [(String, String)] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items).map { switch itemClass { case .GenericPassword: return (($0["service"] ?? "") as! String, ($0["key"] ?? "") as! String) case .InternetPassword: return (($0["server"] ?? "") as! String, ($0["key"] ?? "") as! String) } } } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allKeys() -> [String] { return self.dynamicType.prettify(itemClass: itemClass, items: items()).map { $0["key"] as! String } } public class func allItems(itemClass: ItemClass) -> [[String: AnyObject]] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue #if os(iOS) query[kSecReturnData as! String] = kCFBooleanTrue #endif var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return prettify(itemClass: itemClass, items: items) } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } public func allItems() -> [[String: AnyObject]] { return self.dynamicType.prettify(itemClass: itemClass, items: items()) } #if os(iOS) @availability(iOS, introduced=8.0) public func getSharedPassword(completion: (account: String?, password: String?, error: NSError?) -> () = { account, password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: nil) { (credentials, error) -> () in if let credential = credentials.first { let account = credential["account"] let password = credential["password"] completion(account: account, password: password, error: error) } else { completion(account: nil, password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(account: nil, password: nil, error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func getSharedPassword(account: String, completion: (password: String?, error: NSError?) -> () = { password, error -> () in }) { if let domain = server.host { self.dynamicType.requestSharedWebCredential(domain: domain, account: account) { (credentials, error) -> () in if let credential = credentials.first { if let password = credential["password"] { completion(password: password, error: error) } else { completion(password: nil, error: error) } } else { completion(password: nil, error: error) } } } else { let error = securityError(status: Status.Param.rawValue) completion(password: nil, error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func setSharedPassword(password: String, account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(password as String?, account: account, completion: completion) } #endif #if os(iOS) private func setSharedPassword(password: String?, account: String, completion: (error: NSError?) -> () = { e -> () in }) { if let domain = server.host { SecAddSharedWebCredential(domain, account, password) { error -> () in if let error = error { completion(error: error.error) } else { completion(error: nil) } } } else { let error = securityError(status: Status.Param.rawValue) completion(error: error) } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public func removeSharedPassword(account: String, completion: (error: NSError?) -> () = { e -> () in }) { setSharedPassword(nil, account: account, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: nil, account: nil, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(#domain: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain, account: nil, completion: completion) } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func requestSharedWebCredential(#domain: String, account: String, completion: (credentials: [[String: String]], error: NSError?) -> () = { credentials, error -> () in }) { requestSharedWebCredential(domain: domain as String?, account: account as String?, completion: completion) } #endif #if os(iOS) private class func requestSharedWebCredential(#domain: String?, account: String?, completion: (credentials: [[String: String]], error: NSError?) -> ()) { SecRequestSharedWebCredential(domain, account) { (credentials, error) -> () in var remoteError: NSError? if let error = error { remoteError = error.error if remoteError?.code != Int(errSecItemNotFound) { println("error:[\(remoteError!.code)] \(remoteError!.localizedDescription)") } } if let credentials = credentials as? [[String: AnyObject]] { let credentials = credentials.map { credentials -> [String: String] in var credential = [String: String]() if let server = credentials[kSecAttrServer as! String] as? String { credential["server"] = server } if let account = credentials[kSecAttrAccount as! String] as? String { credential["account"] = account } if let password = credentials[kSecSharedPassword.takeUnretainedValue() as! String] as? String { credential["password"] = password } return credential } completion(credentials: credentials, error: remoteError) } else { completion(credentials: [], error: remoteError) } } } #endif #if os(iOS) @availability(iOS, introduced=8.0) public class func generatePassword() -> String { return SecCreateSharedWebCredentialPassword().takeUnretainedValue() as! String } #endif // MARK: private func items() -> [[String: AnyObject]] { var query = options.query() query[kSecMatchLimit as! String] = kSecMatchLimitAll query[kSecReturnAttributes as! String] = kCFBooleanTrue #if os(iOS) query[kSecReturnData as! String] = kCFBooleanTrue #endif var result: AnyObject? var status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(query, UnsafeMutablePointer($0)) } switch status { case errSecSuccess: if let items = result as? [[String: AnyObject]] { return items } case errSecItemNotFound: return [] default: () } securityError(status: status) return [] } private class func prettify(#itemClass: ItemClass, items: [[String: AnyObject]]) -> [[String: AnyObject]] { let items = items.map { attributes -> [String: AnyObject] in var item = [String: AnyObject]() item["class"] = itemClass.description switch itemClass { case .GenericPassword: if let service = attributes[kSecAttrService as! String] as? String { item["service"] = service } if let accessGroup = attributes[kSecAttrAccessGroup as! String] as? String { item["accessGroup"] = accessGroup } case .InternetPassword: if let server = attributes[kSecAttrServer as! String] as? String { item["server"] = server } if let proto = attributes[kSecAttrProtocol as! String] as? String { if let protocolType = ProtocolType(rawValue: proto) { item["protocol"] = protocolType.description } } if let auth = attributes[kSecAttrAuthenticationType as! String] as? String { if let authenticationType = AuthenticationType(rawValue: auth) { item["authenticationType"] = authenticationType.description } } } if let key = attributes[kSecAttrAccount as! String] as? String { item["key"] = key } if let data = attributes[kSecValueData as! String] as? NSData { if let text = NSString(data: data, encoding: NSUTF8StringEncoding) as? String { item["value"] = text } else { item["value"] = data } } if let accessible = attributes[kSecAttrAccessible as! String] as? String { if let accessibility = Accessibility(rawValue: accessible) { item["accessibility"] = accessibility.description } } if let synchronizable = attributes[kSecAttrSynchronizable as! String] as? Bool { item["synchronizable"] = synchronizable ? "true" : "false" } return item } return items } // MARK: private class func conversionError(#message: String) -> NSError { let error = NSError(domain: KeychainAccessErrorDomain, code: Int(Status.ConversionError.rawValue), userInfo: [NSLocalizedDescriptionKey: message]) println("error:[\(error.code)] \(error.localizedDescription)") return error } private func conversionError(#message: String) -> NSError { return self.dynamicType.conversionError(message: message) } private class func securityError(#status: OSStatus) -> NSError { let message = Status(rawValue: status)!.description let error = NSError(domain: KeychainAccessErrorDomain, code: Int(status), userInfo: [NSLocalizedDescriptionKey: message]) println("OSStatus error:[\(error.code)] \(error.localizedDescription)") return error } private func securityError(#status: OSStatus) -> NSError { return self.dynamicType.securityError(status: status) } } struct Options { var itemClass: ItemClass = .GenericPassword var service: String = "" var accessGroup: String? = nil var server: NSURL! var protocolType: ProtocolType! var authenticationType: AuthenticationType = .Default var accessibility: Accessibility = .AfterFirstUnlock var authenticationPolicy: AuthenticationPolicy? var synchronizable: Bool = false var label: String? var comment: String? var authenticationPrompt: String? init() {} } extension Keychain : Printable, DebugPrintable { public var description: String { let items = allItems() if items.isEmpty { return "[]" } var description = "[\n" for item in items { description += " " description += "\(item)\n" } description += "]" return description } public var debugDescription: String { return "\(items())" } } extension Options { func query() -> [String: AnyObject] { var query = [String: AnyObject]() query[kSecClass as! String] = itemClass.rawValue query[kSecAttrSynchronizable as! String] = kSecAttrSynchronizableAny switch itemClass { case .GenericPassword: query[kSecAttrService as! String] = service #if (!arch(i386) && !arch(x86_64)) || !os(iOS) if let accessGroup = self.accessGroup { query[kSecAttrAccessGroup as! String] = accessGroup } #endif case .InternetPassword: query[kSecAttrServer as! String] = server.host query[kSecAttrPort as! String] = server.port query[kSecAttrProtocol as! String] = protocolType.rawValue query[kSecAttrAuthenticationType as! String] = authenticationType.rawValue } #if os(iOS) if authenticationPrompt != nil { if floor(NSFoundationVersionNumber) > floor(NSFoundationVersionNumber_iOS_7_1) { query[kSecUseOperationPrompt as! String] = authenticationPrompt } else { println("Unavailable 'authenticationPrompt' attribute on iOS versions prior to 8.0.") } } #endif return query } func attributes(#key: String?, value: NSData) -> ([String: AnyObject], NSError?) { var attributes: [String: AnyObject] if key != nil { attributes = query() attributes[kSecAttrAccount as! String] = key } else { attributes = [String: AnyObject]() } attributes[kSecValueData as! String] = value if label != nil { attributes[kSecAttrLabel as! String] = label } if comment != nil { attributes[kSecAttrComment as! String] = comment } #if os(iOS) let iOS_7_1_or_10_9_2 = NSFoundationVersionNumber_iOS_7_1 #else let iOS_7_1_or_10_9_2 = NSFoundationVersionNumber10_9_2 #endif if let policy = authenticationPolicy { if floor(NSFoundationVersionNumber) > floor(iOS_7_1_or_10_9_2) { var error: Unmanaged<CFError>? let accessControl = SecAccessControlCreateWithFlags( kCFAllocatorDefault, accessibility.rawValue, SecAccessControlCreateFlags(policy.rawValue), &error ) if let error = error?.takeUnretainedValue() { return (attributes, error.error) } if accessControl == nil { let message = Status.UnexpectedError.description return (attributes, NSError(domain: KeychainAccessErrorDomain, code: Int(Status.UnexpectedError.rawValue), userInfo: [NSLocalizedDescriptionKey: message])) } attributes[kSecAttrAccessControl as! String] = accessControl.takeUnretainedValue() } else { #if os(iOS) println("Unavailable 'Touch ID integration' on iOS versions prior to 8.0.") #else println("Unavailable 'Touch ID integration' on OS X versions prior to 10.10.") #endif } } else { if floor(NSFoundationVersionNumber) <= floor(iOS_7_1_or_10_9_2) && accessibility == .WhenPasscodeSetThisDeviceOnly { #if os(iOS) println("Unavailable 'Accessibility.WhenPasscodeSetThisDeviceOnly' attribute on iOS versions prior to 8.0.") #else println("Unavailable 'Accessibility.WhenPasscodeSetThisDeviceOnly' attribute on OS X versions prior to 10.10.") #endif } else { attributes[kSecAttrAccessible as! String] = accessibility.rawValue } } attributes[kSecAttrSynchronizable as! String] = synchronizable return (attributes, nil) } } // MARK: extension ItemClass : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecClassGenericPassword as! String: self = GenericPassword case kSecClassInternetPassword as! String: self = InternetPassword default: return nil } } public var rawValue: String { switch self { case GenericPassword: return kSecClassGenericPassword as! String case InternetPassword: return kSecClassInternetPassword as! String } } public var description : String { switch self { case GenericPassword: return "GenericPassword" case InternetPassword: return "InternetPassword" } } } extension ProtocolType : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrProtocolFTP as! String: self = FTP case kSecAttrProtocolFTPAccount as! String: self = FTPAccount case kSecAttrProtocolHTTP as! String: self = HTTP case kSecAttrProtocolIRC as! String: self = IRC case kSecAttrProtocolNNTP as! String: self = NNTP case kSecAttrProtocolPOP3 as! String: self = POP3 case kSecAttrProtocolSMTP as! String: self = SMTP case kSecAttrProtocolSOCKS as! String: self = SOCKS case kSecAttrProtocolIMAP as! String: self = IMAP case kSecAttrProtocolLDAP as! String: self = LDAP case kSecAttrProtocolAppleTalk as! String: self = AppleTalk case kSecAttrProtocolAFP as! String: self = AFP case kSecAttrProtocolTelnet as! String: self = Telnet case kSecAttrProtocolSSH as! String: self = SSH case kSecAttrProtocolFTPS as! String: self = FTPS case kSecAttrProtocolHTTPS as! String: self = HTTPS case kSecAttrProtocolHTTPProxy as! String: self = HTTPProxy case kSecAttrProtocolHTTPSProxy as! String: self = HTTPSProxy case kSecAttrProtocolFTPProxy as! String: self = FTPProxy case kSecAttrProtocolSMB as! String: self = SMB case kSecAttrProtocolRTSP as! String: self = RTSP case kSecAttrProtocolRTSPProxy as! String: self = RTSPProxy case kSecAttrProtocolDAAP as! String: self = DAAP case kSecAttrProtocolEPPC as! String: self = EPPC case kSecAttrProtocolIPP as! String: self = IPP case kSecAttrProtocolNNTPS as! String: self = NNTPS case kSecAttrProtocolLDAPS as! String: self = LDAPS case kSecAttrProtocolTelnetS as! String: self = TelnetS case kSecAttrProtocolIMAPS as! String: self = IMAPS case kSecAttrProtocolIRCS as! String: self = IRCS case kSecAttrProtocolPOP3S as! String: self = POP3S default: return nil } } public var rawValue: String { switch self { case FTP: return kSecAttrProtocolFTP as! String case FTPAccount: return kSecAttrProtocolFTPAccount as! String case HTTP: return kSecAttrProtocolHTTP as! String case IRC: return kSecAttrProtocolIRC as! String case NNTP: return kSecAttrProtocolNNTP as! String case POP3: return kSecAttrProtocolPOP3 as! String case SMTP: return kSecAttrProtocolSMTP as! String case SOCKS: return kSecAttrProtocolSOCKS as! String case IMAP: return kSecAttrProtocolIMAP as! String case LDAP: return kSecAttrProtocolLDAP as! String case AppleTalk: return kSecAttrProtocolAppleTalk as! String case AFP: return kSecAttrProtocolAFP as! String case Telnet: return kSecAttrProtocolTelnet as! String case SSH: return kSecAttrProtocolSSH as! String case FTPS: return kSecAttrProtocolFTPS as! String case HTTPS: return kSecAttrProtocolHTTPS as! String case HTTPProxy: return kSecAttrProtocolHTTPProxy as! String case HTTPSProxy: return kSecAttrProtocolHTTPSProxy as! String case FTPProxy: return kSecAttrProtocolFTPProxy as! String case SMB: return kSecAttrProtocolSMB as! String case RTSP: return kSecAttrProtocolRTSP as! String case RTSPProxy: return kSecAttrProtocolRTSPProxy as! String case DAAP: return kSecAttrProtocolDAAP as! String case EPPC: return kSecAttrProtocolEPPC as! String case IPP: return kSecAttrProtocolIPP as! String case NNTPS: return kSecAttrProtocolNNTPS as! String case LDAPS: return kSecAttrProtocolLDAPS as! String case TelnetS: return kSecAttrProtocolTelnetS as! String case IMAPS: return kSecAttrProtocolIMAPS as! String case IRCS: return kSecAttrProtocolIRCS as! String case POP3S: return kSecAttrProtocolPOP3S as! String } } public var description : String { switch self { case FTP: return "FTP" case FTPAccount: return "FTPAccount" case HTTP: return "HTTP" case IRC: return "IRC" case NNTP: return "NNTP" case POP3: return "POP3" case SMTP: return "SMTP" case SOCKS: return "SOCKS" case IMAP: return "IMAP" case LDAP: return "LDAP" case AppleTalk: return "AppleTalk" case AFP: return "AFP" case Telnet: return "Telnet" case SSH: return "SSH" case FTPS: return "FTPS" case HTTPS: return "HTTPS" case HTTPProxy: return "HTTPProxy" case HTTPSProxy: return "HTTPSProxy" case FTPProxy: return "FTPProxy" case SMB: return "SMB" case RTSP: return "RTSP" case RTSPProxy: return "RTSPProxy" case DAAP: return "DAAP" case EPPC: return "EPPC" case IPP: return "IPP" case NNTPS: return "NNTPS" case LDAPS: return "LDAPS" case TelnetS: return "TelnetS" case IMAPS: return "IMAPS" case IRCS: return "IRCS" case POP3S: return "POP3S" } } } extension AuthenticationType : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrAuthenticationTypeNTLM as! String: self = NTLM case kSecAttrAuthenticationTypeMSN as! String: self = MSN case kSecAttrAuthenticationTypeDPA as! String: self = DPA case kSecAttrAuthenticationTypeRPA as! String: self = RPA case kSecAttrAuthenticationTypeHTTPBasic as! String: self = HTTPBasic case kSecAttrAuthenticationTypeHTTPDigest as! String: self = HTTPDigest case kSecAttrAuthenticationTypeHTMLForm as! String: self = HTMLForm case kSecAttrAuthenticationTypeDefault as! String: self = Default default: return nil } } public var rawValue: String { switch self { case NTLM: return kSecAttrAuthenticationTypeNTLM as! String case MSN: return kSecAttrAuthenticationTypeMSN as! String case DPA: return kSecAttrAuthenticationTypeDPA as! String case RPA: return kSecAttrAuthenticationTypeRPA as! String case HTTPBasic: return kSecAttrAuthenticationTypeHTTPBasic as! String case HTTPDigest: return kSecAttrAuthenticationTypeHTTPDigest as! String case HTMLForm: return kSecAttrAuthenticationTypeHTMLForm as! String case Default: return kSecAttrAuthenticationTypeDefault as! String } } public var description : String { switch self { case NTLM: return "NTLM" case MSN: return "MSN" case DPA: return "DPA" case RPA: return "RPA" case HTTPBasic: return "HTTPBasic" case HTTPDigest: return "HTTPDigest" case HTMLForm: return "HTMLForm" case Default: return "Default" } } } extension Accessibility : RawRepresentable, Printable { public init?(rawValue: String) { switch rawValue { case kSecAttrAccessibleWhenUnlocked as! String: self = WhenUnlocked case kSecAttrAccessibleAfterFirstUnlock as! String: self = AfterFirstUnlock case kSecAttrAccessibleAlways as! String: self = Always case kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as! String: self = WhenPasscodeSetThisDeviceOnly case kSecAttrAccessibleWhenUnlockedThisDeviceOnly as! String: self = WhenUnlockedThisDeviceOnly case kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as! String: self = AfterFirstUnlockThisDeviceOnly case kSecAttrAccessibleAlwaysThisDeviceOnly as! String: self = AlwaysThisDeviceOnly default: return nil } } public var rawValue: String { switch self { case WhenUnlocked: return kSecAttrAccessibleWhenUnlocked as! String case AfterFirstUnlock: return kSecAttrAccessibleAfterFirstUnlock as! String case Always: return kSecAttrAccessibleAlways as! String case WhenPasscodeSetThisDeviceOnly: return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as! String case WhenUnlockedThisDeviceOnly: return kSecAttrAccessibleWhenUnlockedThisDeviceOnly as! String case AfterFirstUnlockThisDeviceOnly: return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as! String case AlwaysThisDeviceOnly: return kSecAttrAccessibleAlwaysThisDeviceOnly as! String } } public var description : String { switch self { case WhenUnlocked: return "WhenUnlocked" case AfterFirstUnlock: return "AfterFirstUnlock" case Always: return "Always" case WhenPasscodeSetThisDeviceOnly: return "WhenPasscodeSetThisDeviceOnly" case WhenUnlockedThisDeviceOnly: return "WhenUnlockedThisDeviceOnly" case AfterFirstUnlockThisDeviceOnly: return "AfterFirstUnlockThisDeviceOnly" case AlwaysThisDeviceOnly: return "AlwaysThisDeviceOnly" } } } extension AuthenticationPolicy : RawRepresentable, Printable { public init?(rawValue: Int) { var flags = SecAccessControlCreateFlags.UserPresence switch rawValue { case flags.rawValue: self = UserPresence default: return nil } } public var rawValue: Int { switch self { case UserPresence: return SecAccessControlCreateFlags.UserPresence.rawValue } } public var description : String { switch self { case UserPresence: return "UserPresence" } } } extension FailableOf: Printable, DebugPrintable { public var description: String { switch self { case .Success(let success): if let value = success.value { return "\(value)" } return "nil" case .Failure(let error): return "\(error.localizedDescription)" } } public var debugDescription: String { switch self { case .Success(let success): return "\(success.value)" case .Failure(let error): return "\(error)" } } } extension CFError { var error: NSError { var domain = CFErrorGetDomain(self) as String var code = CFErrorGetCode(self) var userInfo = CFErrorCopyUserInfo(self) as [NSObject: AnyObject] return NSError(domain: domain, code: code, userInfo: userInfo) } } public enum Status : OSStatus { case Success case Unimplemented case Param case Allocate case NotAvailable case ReadOnly case AuthFailed case NoSuchKeychain case InvalidKeychain case DuplicateKeychain case DuplicateCallback case InvalidCallback case DuplicateItem case ItemNotFound case BufferTooSmall case DataTooLarge case NoSuchAttr case InvalidItemRef case InvalidSearchRef case NoSuchClass case NoDefaultKeychain case InteractionNotAllowed case ReadOnlyAttr case WrongSecVersion case KeySizeNotAllowed case NoStorageModule case NoCertificateModule case NoPolicyModule case InteractionRequired case DataNotAvailable case DataNotModifiable case CreateChainFailed case InvalidPrefsDomain case ACLNotSimple case PolicyNotFound case InvalidTrustSetting case NoAccessForItem case InvalidOwnerEdit case TrustNotAvailable case UnsupportedFormat case UnknownFormat case KeyIsSensitive case MultiplePrivKeys case PassphraseRequired case InvalidPasswordRef case InvalidTrustSettings case NoTrustSettings case Pkcs12VerifyFailure case InvalidCertificate case NotSigner case PolicyDenied case InvalidKey case Decode case Internal case UnsupportedAlgorithm case UnsupportedOperation case UnsupportedPadding case ItemInvalidKey case ItemInvalidKeyType case ItemInvalidValue case ItemClassMissing case ItemMatchUnsupported case UseItemListUnsupported case UseKeychainUnsupported case UseKeychainListUnsupported case ReturnDataUnsupported case ReturnAttributesUnsupported case ReturnRefUnsupported case ReturnPersitentRefUnsupported case ValueRefUnsupported case ValuePersistentRefUnsupported case ReturnMissingPointer case MatchLimitUnsupported case ItemIllegalQuery case WaitForCallback case MissingEntitlement case UpgradePending case MPSignatureInvalid case OTRTooOld case OTRIDTooNew case ServiceNotAvailable case InsufficientClientID case DeviceReset case DeviceFailed case AppleAddAppACLSubject case ApplePublicKeyIncomplete case AppleSignatureMismatch case AppleInvalidKeyStartDate case AppleInvalidKeyEndDate case ConversionError case AppleSSLv2Rollback case DiskFull case QuotaExceeded case FileTooBig case InvalidDatabaseBlob case InvalidKeyBlob case IncompatibleDatabaseBlob case IncompatibleKeyBlob case HostNameMismatch case UnknownCriticalExtensionFlag case NoBasicConstraints case NoBasicConstraintsCA case InvalidAuthorityKeyID case InvalidSubjectKeyID case InvalidKeyUsageForPolicy case InvalidExtendedKeyUsage case InvalidIDLinkage case PathLengthConstraintExceeded case InvalidRoot case CRLExpired case CRLNotValidYet case CRLNotFound case CRLServerDown case CRLBadURI case UnknownCertExtension case UnknownCRLExtension case CRLNotTrusted case CRLPolicyFailed case IDPFailure case SMIMEEmailAddressesNotFound case SMIMEBadExtendedKeyUsage case SMIMEBadKeyUsage case SMIMEKeyUsageNotCritical case SMIMENoEmailAddress case SMIMESubjAltNameNotCritical case SSLBadExtendedKeyUsage case OCSPBadResponse case OCSPBadRequest case OCSPUnavailable case OCSPStatusUnrecognized case EndOfData case IncompleteCertRevocationCheck case NetworkFailure case OCSPNotTrustedToAnchor case RecordModified case OCSPSignatureError case OCSPNoSigner case OCSPResponderMalformedReq case OCSPResponderInternalError case OCSPResponderTryLater case OCSPResponderSignatureRequired case OCSPResponderUnauthorized case OCSPResponseNonceMismatch case CodeSigningBadCertChainLength case CodeSigningNoBasicConstraints case CodeSigningBadPathLengthConstraint case CodeSigningNoExtendedKeyUsage case CodeSigningDevelopment case ResourceSignBadCertChainLength case ResourceSignBadExtKeyUsage case TrustSettingDeny case InvalidSubjectName case UnknownQualifiedCertStatement case MobileMeRequestQueued case MobileMeRequestRedirected case MobileMeServerError case MobileMeServerNotAvailable case MobileMeServerAlreadyExists case MobileMeServerServiceErr case MobileMeRequestAlreadyPending case MobileMeNoRequestPending case MobileMeCSRVerifyFailure case MobileMeFailedConsistencyCheck case NotInitialized case InvalidHandleUsage case PVCReferentNotFound case FunctionIntegrityFail case InternalError case MemoryError case InvalidData case MDSError case InvalidPointer case SelfCheckFailed case FunctionFailed case ModuleManifestVerifyFailed case InvalidGUID case InvalidHandle case InvalidDBList case InvalidPassthroughID case InvalidNetworkAddress case CRLAlreadySigned case InvalidNumberOfFields case VerificationFailure case UnknownTag case InvalidSignature case InvalidName case InvalidCertificateRef case InvalidCertificateGroup case TagNotFound case InvalidQuery case InvalidValue case CallbackFailed case ACLDeleteFailed case ACLReplaceFailed case ACLAddFailed case ACLChangeFailed case InvalidAccessCredentials case InvalidRecord case InvalidACL case InvalidSampleValue case IncompatibleVersion case PrivilegeNotGranted case InvalidScope case PVCAlreadyConfigured case InvalidPVC case EMMLoadFailed case EMMUnloadFailed case AddinLoadFailed case InvalidKeyRef case InvalidKeyHierarchy case AddinUnloadFailed case LibraryReferenceNotFound case InvalidAddinFunctionTable case InvalidServiceMask case ModuleNotLoaded case InvalidSubServiceID case AttributeNotInContext case ModuleManagerInitializeFailed case ModuleManagerNotFound case EventNotificationCallbackNotFound case InputLengthError case OutputLengthError case PrivilegeNotSupported case DeviceError case AttachHandleBusy case NotLoggedIn case AlgorithmMismatch case KeyUsageIncorrect case KeyBlobTypeIncorrect case KeyHeaderInconsistent case UnsupportedKeyFormat case UnsupportedKeySize case InvalidKeyUsageMask case UnsupportedKeyUsageMask case InvalidKeyAttributeMask case UnsupportedKeyAttributeMask case InvalidKeyLabel case UnsupportedKeyLabel case InvalidKeyFormat case UnsupportedVectorOfBuffers case InvalidInputVector case InvalidOutputVector case InvalidContext case InvalidAlgorithm case InvalidAttributeKey case MissingAttributeKey case InvalidAttributeInitVector case MissingAttributeInitVector case InvalidAttributeSalt case MissingAttributeSalt case InvalidAttributePadding case MissingAttributePadding case InvalidAttributeRandom case MissingAttributeRandom case InvalidAttributeSeed case MissingAttributeSeed case InvalidAttributePassphrase case MissingAttributePassphrase case InvalidAttributeKeyLength case MissingAttributeKeyLength case InvalidAttributeBlockSize case MissingAttributeBlockSize case InvalidAttributeOutputSize case MissingAttributeOutputSize case InvalidAttributeRounds case MissingAttributeRounds case InvalidAlgorithmParms case MissingAlgorithmParms case InvalidAttributeLabel case MissingAttributeLabel case InvalidAttributeKeyType case MissingAttributeKeyType case InvalidAttributeMode case MissingAttributeMode case InvalidAttributeEffectiveBits case MissingAttributeEffectiveBits case InvalidAttributeStartDate case MissingAttributeStartDate case InvalidAttributeEndDate case MissingAttributeEndDate case InvalidAttributeVersion case MissingAttributeVersion case InvalidAttributePrime case MissingAttributePrime case InvalidAttributeBase case MissingAttributeBase case InvalidAttributeSubprime case MissingAttributeSubprime case InvalidAttributeIterationCount case MissingAttributeIterationCount case InvalidAttributeDLDBHandle case MissingAttributeDLDBHandle case InvalidAttributeAccessCredentials case MissingAttributeAccessCredentials case InvalidAttributePublicKeyFormat case MissingAttributePublicKeyFormat case InvalidAttributePrivateKeyFormat case MissingAttributePrivateKeyFormat case InvalidAttributeSymmetricKeyFormat case MissingAttributeSymmetricKeyFormat case InvalidAttributeWrappedKeyFormat case MissingAttributeWrappedKeyFormat case StagedOperationInProgress case StagedOperationNotStarted case VerifyFailed case QuerySizeUnknown case BlockSizeMismatch case PublicKeyInconsistent case DeviceVerifyFailed case InvalidLoginName case AlreadyLoggedIn case InvalidDigestAlgorithm case InvalidCRLGroup case CertificateCannotOperate case CertificateExpired case CertificateNotValidYet case CertificateRevoked case CertificateSuspended case InsufficientCredentials case InvalidAction case InvalidAuthority case VerifyActionFailed case InvalidCertAuthority case InvaldCRLAuthority case InvalidCRLEncoding case InvalidCRLType case InvalidCRL case InvalidFormType case InvalidID case InvalidIdentifier case InvalidIndex case InvalidPolicyIdentifiers case InvalidTimeString case InvalidReason case InvalidRequestInputs case InvalidResponseVector case InvalidStopOnPolicy case InvalidTuple case MultipleValuesUnsupported case NotTrusted case NoDefaultAuthority case RejectedForm case RequestLost case RequestRejected case UnsupportedAddressType case UnsupportedService case InvalidTupleGroup case InvalidBaseACLs case InvalidTupleCredendtials case InvalidEncoding case InvalidValidityPeriod case InvalidRequestor case RequestDescriptor case InvalidBundleInfo case InvalidCRLIndex case NoFieldValues case UnsupportedFieldFormat case UnsupportedIndexInfo case UnsupportedLocality case UnsupportedNumAttributes case UnsupportedNumIndexes case UnsupportedNumRecordTypes case FieldSpecifiedMultiple case IncompatibleFieldFormat case InvalidParsingModule case DatabaseLocked case DatastoreIsOpen case MissingValue case UnsupportedQueryLimits case UnsupportedNumSelectionPreds case UnsupportedOperator case InvalidDBLocation case InvalidAccessRequest case InvalidIndexInfo case InvalidNewOwner case InvalidModifyMode case UnexpectedError } extension Status : RawRepresentable, Printable { public init?(rawValue: OSStatus) { switch rawValue { case 0: self = Success case -4: self = Unimplemented case -50: self = Param case -108: self = Allocate case -25291: self = NotAvailable case -25292: self = ReadOnly case -25293: self = AuthFailed case -25294: self = NoSuchKeychain case -25295: self = InvalidKeychain case -25296: self = DuplicateKeychain case -25297: self = DuplicateCallback case -25298: self = InvalidCallback case -25299: self = DuplicateItem case -25300: self = ItemNotFound case -25301: self = BufferTooSmall case -25302: self = DataTooLarge case -25303: self = NoSuchAttr case -25304: self = InvalidItemRef case -25305: self = InvalidSearchRef case -25306: self = NoSuchClass case -25307: self = NoDefaultKeychain case -25308: self = InteractionNotAllowed case -25309: self = ReadOnlyAttr case -25310: self = WrongSecVersion case -25311: self = KeySizeNotAllowed case -25312: self = NoStorageModule case -25313: self = NoCertificateModule case -25314: self = NoPolicyModule case -25315: self = InteractionRequired case -25316: self = DataNotAvailable case -25317: self = DataNotModifiable case -25318: self = CreateChainFailed case -25319: self = InvalidPrefsDomain case -25240: self = ACLNotSimple case -25241: self = PolicyNotFound case -25242: self = InvalidTrustSetting case -25243: self = NoAccessForItem case -25244: self = InvalidOwnerEdit case -25245: self = TrustNotAvailable case -25256: self = UnsupportedFormat case -25257: self = UnknownFormat case -25258: self = KeyIsSensitive case -25259: self = MultiplePrivKeys case -25260: self = PassphraseRequired case -25261: self = InvalidPasswordRef case -25262: self = InvalidTrustSettings case -25263: self = NoTrustSettings case -25264: self = Pkcs12VerifyFailure case -26265: self = InvalidCertificate case -26267: self = NotSigner case -26270: self = PolicyDenied case -26274: self = InvalidKey case -26275: self = Decode case -26276: self = Internal case -26268: self = UnsupportedAlgorithm case -26271: self = UnsupportedOperation case -26273: self = UnsupportedPadding case -34000: self = ItemInvalidKey case -34001: self = ItemInvalidKeyType case -34002: self = ItemInvalidValue case -34003: self = ItemClassMissing case -34004: self = ItemMatchUnsupported case -34005: self = UseItemListUnsupported case -34006: self = UseKeychainUnsupported case -34007: self = UseKeychainListUnsupported case -34008: self = ReturnDataUnsupported case -34009: self = ReturnAttributesUnsupported case -34010: self = ReturnRefUnsupported case -34010: self = ReturnPersitentRefUnsupported case -34012: self = ValueRefUnsupported case -34013: self = ValuePersistentRefUnsupported case -34014: self = ReturnMissingPointer case -34015: self = MatchLimitUnsupported case -34016: self = ItemIllegalQuery case -34017: self = WaitForCallback case -34018: self = MissingEntitlement case -34019: self = UpgradePending case -25327: self = MPSignatureInvalid case -25328: self = OTRTooOld case -25329: self = OTRIDTooNew case -67585: self = ServiceNotAvailable case -67586: self = InsufficientClientID case -67587: self = DeviceReset case -67588: self = DeviceFailed case -67589: self = AppleAddAppACLSubject case -67590: self = ApplePublicKeyIncomplete case -67591: self = AppleSignatureMismatch case -67592: self = AppleInvalidKeyStartDate case -67593: self = AppleInvalidKeyEndDate case -67594: self = ConversionError case -67595: self = AppleSSLv2Rollback case -34: self = DiskFull case -67596: self = QuotaExceeded case -67597: self = FileTooBig case -67598: self = InvalidDatabaseBlob case -67599: self = InvalidKeyBlob case -67600: self = IncompatibleDatabaseBlob case -67601: self = IncompatibleKeyBlob case -67602: self = HostNameMismatch case -67603: self = UnknownCriticalExtensionFlag case -67604: self = NoBasicConstraints case -67605: self = NoBasicConstraintsCA case -67606: self = InvalidAuthorityKeyID case -67607: self = InvalidSubjectKeyID case -67608: self = InvalidKeyUsageForPolicy case -67609: self = InvalidExtendedKeyUsage case -67610: self = InvalidIDLinkage case -67611: self = PathLengthConstraintExceeded case -67612: self = InvalidRoot case -67613: self = CRLExpired case -67614: self = CRLNotValidYet case -67615: self = CRLNotFound case -67616: self = CRLServerDown case -67617: self = CRLBadURI case -67618: self = UnknownCertExtension case -67619: self = UnknownCRLExtension case -67620: self = CRLNotTrusted case -67621: self = CRLPolicyFailed case -67622: self = IDPFailure case -67623: self = SMIMEEmailAddressesNotFound case -67624: self = SMIMEBadExtendedKeyUsage case -67625: self = SMIMEBadKeyUsage case -67626: self = SMIMEKeyUsageNotCritical case -67627: self = SMIMENoEmailAddress case -67628: self = SMIMESubjAltNameNotCritical case -67629: self = SSLBadExtendedKeyUsage case -67630: self = OCSPBadResponse case -67631: self = OCSPBadRequest case -67632: self = OCSPUnavailable case -67633: self = OCSPStatusUnrecognized case -67634: self = EndOfData case -67635: self = IncompleteCertRevocationCheck case -67636: self = NetworkFailure case -67637: self = OCSPNotTrustedToAnchor case -67638: self = RecordModified case -67639: self = OCSPSignatureError case -67640: self = OCSPNoSigner case -67641: self = OCSPResponderMalformedReq case -67642: self = OCSPResponderInternalError case -67643: self = OCSPResponderTryLater case -67644: self = OCSPResponderSignatureRequired case -67645: self = OCSPResponderUnauthorized case -67646: self = OCSPResponseNonceMismatch case -67647: self = CodeSigningBadCertChainLength case -67648: self = CodeSigningNoBasicConstraints case -67649: self = CodeSigningBadPathLengthConstraint case -67650: self = CodeSigningNoExtendedKeyUsage case -67651: self = CodeSigningDevelopment case -67652: self = ResourceSignBadCertChainLength case -67653: self = ResourceSignBadExtKeyUsage case -67654: self = TrustSettingDeny case -67655: self = InvalidSubjectName case -67656: self = UnknownQualifiedCertStatement case -67657: self = MobileMeRequestQueued case -67658: self = MobileMeRequestRedirected case -67659: self = MobileMeServerError case -67660: self = MobileMeServerNotAvailable case -67661: self = MobileMeServerAlreadyExists case -67662: self = MobileMeServerServiceErr case -67663: self = MobileMeRequestAlreadyPending case -67664: self = MobileMeNoRequestPending case -67665: self = MobileMeCSRVerifyFailure case -67666: self = MobileMeFailedConsistencyCheck case -67667: self = NotInitialized case -67668: self = InvalidHandleUsage case -67669: self = PVCReferentNotFound case -67670: self = FunctionIntegrityFail case -67671: self = InternalError case -67672: self = MemoryError case -67673: self = InvalidData case -67674: self = MDSError case -67675: self = InvalidPointer case -67676: self = SelfCheckFailed case -67677: self = FunctionFailed case -67678: self = ModuleManifestVerifyFailed case -67679: self = InvalidGUID case -67680: self = InvalidHandle case -67681: self = InvalidDBList case -67682: self = InvalidPassthroughID case -67683: self = InvalidNetworkAddress case -67684: self = CRLAlreadySigned case -67685: self = InvalidNumberOfFields case -67686: self = VerificationFailure case -67687: self = UnknownTag case -67688: self = InvalidSignature case -67689: self = InvalidName case -67690: self = InvalidCertificateRef case -67691: self = InvalidCertificateGroup case -67692: self = TagNotFound case -67693: self = InvalidQuery case -67694: self = InvalidValue case -67695: self = CallbackFailed case -67696: self = ACLDeleteFailed case -67697: self = ACLReplaceFailed case -67698: self = ACLAddFailed case -67699: self = ACLChangeFailed case -67700: self = InvalidAccessCredentials case -67701: self = InvalidRecord case -67702: self = InvalidACL case -67703: self = InvalidSampleValue case -67704: self = IncompatibleVersion case -67705: self = PrivilegeNotGranted case -67706: self = InvalidScope case -67707: self = PVCAlreadyConfigured case -67708: self = InvalidPVC case -67709: self = EMMLoadFailed case -67710: self = EMMUnloadFailed case -67711: self = AddinLoadFailed case -67712: self = InvalidKeyRef case -67713: self = InvalidKeyHierarchy case -67714: self = AddinUnloadFailed case -67715: self = LibraryReferenceNotFound case -67716: self = InvalidAddinFunctionTable case -67717: self = InvalidServiceMask case -67718: self = ModuleNotLoaded case -67719: self = InvalidSubServiceID case -67720: self = AttributeNotInContext case -67721: self = ModuleManagerInitializeFailed case -67722: self = ModuleManagerNotFound case -67723: self = EventNotificationCallbackNotFound case -67724: self = InputLengthError case -67725: self = OutputLengthError case -67726: self = PrivilegeNotSupported case -67727: self = DeviceError case -67728: self = AttachHandleBusy case -67729: self = NotLoggedIn case -67730: self = AlgorithmMismatch case -67731: self = KeyUsageIncorrect case -67732: self = KeyBlobTypeIncorrect case -67733: self = KeyHeaderInconsistent case -67734: self = UnsupportedKeyFormat case -67735: self = UnsupportedKeySize case -67736: self = InvalidKeyUsageMask case -67737: self = UnsupportedKeyUsageMask case -67738: self = InvalidKeyAttributeMask case -67739: self = UnsupportedKeyAttributeMask case -67740: self = InvalidKeyLabel case -67741: self = UnsupportedKeyLabel case -67742: self = InvalidKeyFormat case -67743: self = UnsupportedVectorOfBuffers case -67744: self = InvalidInputVector case -67745: self = InvalidOutputVector case -67746: self = InvalidContext case -67747: self = InvalidAlgorithm case -67748: self = InvalidAttributeKey case -67749: self = MissingAttributeKey case -67750: self = InvalidAttributeInitVector case -67751: self = MissingAttributeInitVector case -67752: self = InvalidAttributeSalt case -67753: self = MissingAttributeSalt case -67754: self = InvalidAttributePadding case -67755: self = MissingAttributePadding case -67756: self = InvalidAttributeRandom case -67757: self = MissingAttributeRandom case -67758: self = InvalidAttributeSeed case -67759: self = MissingAttributeSeed case -67760: self = InvalidAttributePassphrase case -67761: self = MissingAttributePassphrase case -67762: self = InvalidAttributeKeyLength case -67763: self = MissingAttributeKeyLength case -67764: self = InvalidAttributeBlockSize case -67765: self = MissingAttributeBlockSize case -67766: self = InvalidAttributeOutputSize case -67767: self = MissingAttributeOutputSize case -67768: self = InvalidAttributeRounds case -67769: self = MissingAttributeRounds case -67770: self = InvalidAlgorithmParms case -67771: self = MissingAlgorithmParms case -67772: self = InvalidAttributeLabel case -67773: self = MissingAttributeLabel case -67774: self = InvalidAttributeKeyType case -67775: self = MissingAttributeKeyType case -67776: self = InvalidAttributeMode case -67777: self = MissingAttributeMode case -67778: self = InvalidAttributeEffectiveBits case -67779: self = MissingAttributeEffectiveBits case -67780: self = InvalidAttributeStartDate case -67781: self = MissingAttributeStartDate case -67782: self = InvalidAttributeEndDate case -67783: self = MissingAttributeEndDate case -67784: self = InvalidAttributeVersion case -67785: self = MissingAttributeVersion case -67786: self = InvalidAttributePrime case -67787: self = MissingAttributePrime case -67788: self = InvalidAttributeBase case -67789: self = MissingAttributeBase case -67790: self = InvalidAttributeSubprime case -67791: self = MissingAttributeSubprime case -67792: self = InvalidAttributeIterationCount case -67793: self = MissingAttributeIterationCount case -67794: self = InvalidAttributeDLDBHandle case -67795: self = MissingAttributeDLDBHandle case -67796: self = InvalidAttributeAccessCredentials case -67797: self = MissingAttributeAccessCredentials case -67798: self = InvalidAttributePublicKeyFormat case -67799: self = MissingAttributePublicKeyFormat case -67800: self = InvalidAttributePrivateKeyFormat case -67801: self = MissingAttributePrivateKeyFormat case -67802: self = InvalidAttributeSymmetricKeyFormat case -67803: self = MissingAttributeSymmetricKeyFormat case -67804: self = InvalidAttributeWrappedKeyFormat case -67805: self = MissingAttributeWrappedKeyFormat case -67806: self = StagedOperationInProgress case -67807: self = StagedOperationNotStarted case -67808: self = VerifyFailed case -67809: self = QuerySizeUnknown case -67810: self = BlockSizeMismatch case -67811: self = PublicKeyInconsistent case -67812: self = DeviceVerifyFailed case -67813: self = InvalidLoginName case -67814: self = AlreadyLoggedIn case -67815: self = InvalidDigestAlgorithm case -67816: self = InvalidCRLGroup case -67817: self = CertificateCannotOperate case -67818: self = CertificateExpired case -67819: self = CertificateNotValidYet case -67820: self = CertificateRevoked case -67821: self = CertificateSuspended case -67822: self = InsufficientCredentials case -67823: self = InvalidAction case -67824: self = InvalidAuthority case -67825: self = VerifyActionFailed case -67826: self = InvalidCertAuthority case -67827: self = InvaldCRLAuthority case -67828: self = InvalidCRLEncoding case -67829: self = InvalidCRLType case -67830: self = InvalidCRL case -67831: self = InvalidFormType case -67832: self = InvalidID case -67833: self = InvalidIdentifier case -67834: self = InvalidIndex case -67835: self = InvalidPolicyIdentifiers case -67836: self = InvalidTimeString case -67837: self = InvalidReason case -67838: self = InvalidRequestInputs case -67839: self = InvalidResponseVector case -67840: self = InvalidStopOnPolicy case -67841: self = InvalidTuple case -67842: self = MultipleValuesUnsupported case -67843: self = NotTrusted case -67844: self = NoDefaultAuthority case -67845: self = RejectedForm case -67846: self = RequestLost case -67847: self = RequestRejected case -67848: self = UnsupportedAddressType case -67849: self = UnsupportedService case -67850: self = InvalidTupleGroup case -67851: self = InvalidBaseACLs case -67852: self = InvalidTupleCredendtials case -67853: self = InvalidEncoding case -67854: self = InvalidValidityPeriod case -67855: self = InvalidRequestor case -67856: self = RequestDescriptor case -67857: self = InvalidBundleInfo case -67858: self = InvalidCRLIndex case -67859: self = NoFieldValues case -67860: self = UnsupportedFieldFormat case -67861: self = UnsupportedIndexInfo case -67862: self = UnsupportedLocality case -67863: self = UnsupportedNumAttributes case -67864: self = UnsupportedNumIndexes case -67865: self = UnsupportedNumRecordTypes case -67866: self = FieldSpecifiedMultiple case -67867: self = IncompatibleFieldFormat case -67868: self = InvalidParsingModule case -67869: self = DatabaseLocked case -67870: self = DatastoreIsOpen case -67871: self = MissingValue case -67872: self = UnsupportedQueryLimits case -67873: self = UnsupportedNumSelectionPreds case -67874: self = UnsupportedOperator case -67875: self = InvalidDBLocation case -67876: self = InvalidAccessRequest case -67877: self = InvalidIndexInfo case -67878: self = InvalidNewOwner case -67879: self = InvalidModifyMode default: self = UnexpectedError } } public var rawValue: OSStatus { switch self { case Success: return 0 case Unimplemented: return -4 case Param: return -50 case Allocate: return -108 case NotAvailable: return -25291 case ReadOnly: return -25292 case AuthFailed: return -25293 case NoSuchKeychain: return -25294 case InvalidKeychain: return -25295 case DuplicateKeychain: return -25296 case DuplicateCallback: return -25297 case InvalidCallback: return -25298 case DuplicateItem: return -25299 case ItemNotFound: return -25300 case BufferTooSmall: return -25301 case DataTooLarge: return -25302 case NoSuchAttr: return -25303 case InvalidItemRef: return -25304 case InvalidSearchRef: return -25305 case NoSuchClass: return -25306 case NoDefaultKeychain: return -25307 case InteractionNotAllowed: return -25308 case ReadOnlyAttr: return -25309 case WrongSecVersion: return -25310 case KeySizeNotAllowed: return -25311 case NoStorageModule: return -25312 case NoCertificateModule: return -25313 case NoPolicyModule: return -25314 case InteractionRequired: return -25315 case DataNotAvailable: return -25316 case DataNotModifiable: return -25317 case CreateChainFailed: return -25318 case InvalidPrefsDomain: return -25319 case ACLNotSimple: return -25240 case PolicyNotFound: return -25241 case InvalidTrustSetting: return -25242 case NoAccessForItem: return -25243 case InvalidOwnerEdit: return -25244 case TrustNotAvailable: return -25245 case UnsupportedFormat: return -25256 case UnknownFormat: return -25257 case KeyIsSensitive: return -25258 case MultiplePrivKeys: return -25259 case PassphraseRequired: return -25260 case InvalidPasswordRef: return -25261 case InvalidTrustSettings: return -25262 case NoTrustSettings: return -25263 case Pkcs12VerifyFailure: return -25264 case InvalidCertificate: return -26265 case NotSigner: return -26267 case PolicyDenied: return -26270 case InvalidKey: return -26274 case Decode: return -26275 case Internal: return -26276 case UnsupportedAlgorithm: return -26268 case UnsupportedOperation: return -26271 case UnsupportedPadding: return -26273 case ItemInvalidKey: return -34000 case ItemInvalidKeyType: return -34001 case ItemInvalidValue: return -34002 case ItemClassMissing: return -34003 case ItemMatchUnsupported: return -34004 case UseItemListUnsupported: return -34005 case UseKeychainUnsupported: return -34006 case UseKeychainListUnsupported: return -34007 case ReturnDataUnsupported: return -34008 case ReturnAttributesUnsupported: return -34009 case ReturnRefUnsupported: return -34010 case ReturnPersitentRefUnsupported: return -34010 case ValueRefUnsupported: return -34012 case ValuePersistentRefUnsupported: return -34013 case ReturnMissingPointer: return -34014 case MatchLimitUnsupported: return -34015 case ItemIllegalQuery: return -34016 case WaitForCallback: return -34017 case MissingEntitlement: return -34018 case UpgradePending: return -34019 case MPSignatureInvalid: return -25327 case OTRTooOld: return -25328 case OTRIDTooNew: return -25329 case ServiceNotAvailable: return -67585 case InsufficientClientID: return -67586 case DeviceReset: return -67587 case DeviceFailed: return -67588 case AppleAddAppACLSubject: return -67589 case ApplePublicKeyIncomplete: return -67590 case AppleSignatureMismatch: return -67591 case AppleInvalidKeyStartDate: return -67592 case AppleInvalidKeyEndDate: return -67593 case ConversionError: return -67594 case AppleSSLv2Rollback: return -67595 case DiskFull: return -34 case QuotaExceeded: return -67596 case FileTooBig: return -67597 case InvalidDatabaseBlob: return -67598 case InvalidKeyBlob: return -67599 case IncompatibleDatabaseBlob: return -67600 case IncompatibleKeyBlob: return -67601 case HostNameMismatch: return -67602 case UnknownCriticalExtensionFlag: return -67603 case NoBasicConstraints: return -67604 case NoBasicConstraintsCA: return -67605 case InvalidAuthorityKeyID: return -67606 case InvalidSubjectKeyID: return -67607 case InvalidKeyUsageForPolicy: return -67608 case InvalidExtendedKeyUsage: return -67609 case InvalidIDLinkage: return -67610 case PathLengthConstraintExceeded: return -67611 case InvalidRoot: return -67612 case CRLExpired: return -67613 case CRLNotValidYet: return -67614 case CRLNotFound: return -67615 case CRLServerDown: return -67616 case CRLBadURI: return -67617 case UnknownCertExtension: return -67618 case UnknownCRLExtension: return -67619 case CRLNotTrusted: return -67620 case CRLPolicyFailed: return -67621 case IDPFailure: return -67622 case SMIMEEmailAddressesNotFound: return -67623 case SMIMEBadExtendedKeyUsage: return -67624 case SMIMEBadKeyUsage: return -67625 case SMIMEKeyUsageNotCritical: return -67626 case SMIMENoEmailAddress: return -67627 case SMIMESubjAltNameNotCritical: return -67628 case SSLBadExtendedKeyUsage: return -67629 case OCSPBadResponse: return -67630 case OCSPBadRequest: return -67631 case OCSPUnavailable: return -67632 case OCSPStatusUnrecognized: return -67633 case EndOfData: return -67634 case IncompleteCertRevocationCheck: return -67635 case NetworkFailure: return -67636 case OCSPNotTrustedToAnchor: return -67637 case RecordModified: return -67638 case OCSPSignatureError: return -67639 case OCSPNoSigner: return -67640 case OCSPResponderMalformedReq: return -67641 case OCSPResponderInternalError: return -67642 case OCSPResponderTryLater: return -67643 case OCSPResponderSignatureRequired: return -67644 case OCSPResponderUnauthorized: return -67645 case OCSPResponseNonceMismatch: return -67646 case CodeSigningBadCertChainLength: return -67647 case CodeSigningNoBasicConstraints: return -67648 case CodeSigningBadPathLengthConstraint: return -67649 case CodeSigningNoExtendedKeyUsage: return -67650 case CodeSigningDevelopment: return -67651 case ResourceSignBadCertChainLength: return -67652 case ResourceSignBadExtKeyUsage: return -67653 case TrustSettingDeny: return -67654 case InvalidSubjectName: return -67655 case UnknownQualifiedCertStatement: return -67656 case MobileMeRequestQueued: return -67657 case MobileMeRequestRedirected: return -67658 case MobileMeServerError: return -67659 case MobileMeServerNotAvailable: return -67660 case MobileMeServerAlreadyExists: return -67661 case MobileMeServerServiceErr: return -67662 case MobileMeRequestAlreadyPending: return -67663 case MobileMeNoRequestPending: return -67664 case MobileMeCSRVerifyFailure: return -67665 case MobileMeFailedConsistencyCheck: return -67666 case NotInitialized: return -67667 case InvalidHandleUsage: return -67668 case PVCReferentNotFound: return -67669 case FunctionIntegrityFail: return -67670 case InternalError: return -67671 case MemoryError: return -67672 case InvalidData: return -67673 case MDSError: return -67674 case InvalidPointer: return -67675 case SelfCheckFailed: return -67676 case FunctionFailed: return -67677 case ModuleManifestVerifyFailed: return -67678 case InvalidGUID: return -67679 case InvalidHandle: return -67680 case InvalidDBList: return -67681 case InvalidPassthroughID: return -67682 case InvalidNetworkAddress: return -67683 case CRLAlreadySigned: return -67684 case InvalidNumberOfFields: return -67685 case VerificationFailure: return -67686 case UnknownTag: return -67687 case InvalidSignature: return -67688 case InvalidName: return -67689 case InvalidCertificateRef: return -67690 case InvalidCertificateGroup: return -67691 case TagNotFound: return -67692 case InvalidQuery: return -67693 case InvalidValue: return -67694 case CallbackFailed: return -67695 case ACLDeleteFailed: return -67696 case ACLReplaceFailed: return -67697 case ACLAddFailed: return -67698 case ACLChangeFailed: return -67699 case InvalidAccessCredentials: return -67700 case InvalidRecord: return -67701 case InvalidACL: return -67702 case InvalidSampleValue: return -67703 case IncompatibleVersion: return -67704 case PrivilegeNotGranted: return -67705 case InvalidScope: return -67706 case PVCAlreadyConfigured: return -67707 case InvalidPVC: return -67708 case EMMLoadFailed: return -67709 case EMMUnloadFailed: return -67710 case AddinLoadFailed: return -67711 case InvalidKeyRef: return -67712 case InvalidKeyHierarchy: return -67713 case AddinUnloadFailed: return -67714 case LibraryReferenceNotFound: return -67715 case InvalidAddinFunctionTable: return -67716 case InvalidServiceMask: return -67717 case ModuleNotLoaded: return -67718 case InvalidSubServiceID: return -67719 case AttributeNotInContext: return -67720 case ModuleManagerInitializeFailed: return -67721 case ModuleManagerNotFound: return -67722 case EventNotificationCallbackNotFound: return -67723 case InputLengthError: return -67724 case OutputLengthError: return -67725 case PrivilegeNotSupported: return -67726 case DeviceError: return -67727 case AttachHandleBusy: return -67728 case NotLoggedIn: return -67729 case AlgorithmMismatch: return -67730 case KeyUsageIncorrect: return -67731 case KeyBlobTypeIncorrect: return -67732 case KeyHeaderInconsistent: return -67733 case UnsupportedKeyFormat: return -67734 case UnsupportedKeySize: return -67735 case InvalidKeyUsageMask: return -67736 case UnsupportedKeyUsageMask: return -67737 case InvalidKeyAttributeMask: return -67738 case UnsupportedKeyAttributeMask: return -67739 case InvalidKeyLabel: return -67740 case UnsupportedKeyLabel: return -67741 case InvalidKeyFormat: return -67742 case UnsupportedVectorOfBuffers: return -67743 case InvalidInputVector: return -67744 case InvalidOutputVector: return -67745 case InvalidContext: return -67746 case InvalidAlgorithm: return -67747 case InvalidAttributeKey: return -67748 case MissingAttributeKey: return -67749 case InvalidAttributeInitVector: return -67750 case MissingAttributeInitVector: return -67751 case InvalidAttributeSalt: return -67752 case MissingAttributeSalt: return -67753 case InvalidAttributePadding: return -67754 case MissingAttributePadding: return -67755 case InvalidAttributeRandom: return -67756 case MissingAttributeRandom: return -67757 case InvalidAttributeSeed: return -67758 case MissingAttributeSeed: return -67759 case InvalidAttributePassphrase: return -67760 case MissingAttributePassphrase: return -67761 case InvalidAttributeKeyLength: return -67762 case MissingAttributeKeyLength: return -67763 case InvalidAttributeBlockSize: return -67764 case MissingAttributeBlockSize: return -67765 case InvalidAttributeOutputSize: return -67766 case MissingAttributeOutputSize: return -67767 case InvalidAttributeRounds: return -67768 case MissingAttributeRounds: return -67769 case InvalidAlgorithmParms: return -67770 case MissingAlgorithmParms: return -67771 case InvalidAttributeLabel: return -67772 case MissingAttributeLabel: return -67773 case InvalidAttributeKeyType: return -67774 case MissingAttributeKeyType: return -67775 case InvalidAttributeMode: return -67776 case MissingAttributeMode: return -67777 case InvalidAttributeEffectiveBits: return -67778 case MissingAttributeEffectiveBits: return -67779 case InvalidAttributeStartDate: return -67780 case MissingAttributeStartDate: return -67781 case InvalidAttributeEndDate: return -67782 case MissingAttributeEndDate: return -67783 case InvalidAttributeVersion: return -67784 case MissingAttributeVersion: return -67785 case InvalidAttributePrime: return -67786 case MissingAttributePrime: return -67787 case InvalidAttributeBase: return -67788 case MissingAttributeBase: return -67789 case InvalidAttributeSubprime: return -67790 case MissingAttributeSubprime: return -67791 case InvalidAttributeIterationCount: return -67792 case MissingAttributeIterationCount: return -67793 case InvalidAttributeDLDBHandle: return -67794 case MissingAttributeDLDBHandle: return -67795 case InvalidAttributeAccessCredentials: return -67796 case MissingAttributeAccessCredentials: return -67797 case InvalidAttributePublicKeyFormat: return -67798 case MissingAttributePublicKeyFormat: return -67799 case InvalidAttributePrivateKeyFormat: return -67800 case MissingAttributePrivateKeyFormat: return -67801 case InvalidAttributeSymmetricKeyFormat: return -67802 case MissingAttributeSymmetricKeyFormat: return -67803 case InvalidAttributeWrappedKeyFormat: return -67804 case MissingAttributeWrappedKeyFormat: return -67805 case StagedOperationInProgress: return -67806 case StagedOperationNotStarted: return -67807 case VerifyFailed: return -67808 case QuerySizeUnknown: return -67809 case BlockSizeMismatch: return -67810 case PublicKeyInconsistent: return -67811 case DeviceVerifyFailed: return -67812 case InvalidLoginName: return -67813 case AlreadyLoggedIn: return -67814 case InvalidDigestAlgorithm: return -67815 case InvalidCRLGroup: return -67816 case CertificateCannotOperate: return -67817 case CertificateExpired: return -67818 case CertificateNotValidYet: return -67819 case CertificateRevoked: return -67820 case CertificateSuspended: return -67821 case InsufficientCredentials: return -67822 case InvalidAction: return -67823 case InvalidAuthority: return -67824 case VerifyActionFailed: return -67825 case InvalidCertAuthority: return -67826 case InvaldCRLAuthority: return -67827 case InvalidCRLEncoding: return -67828 case InvalidCRLType: return -67829 case InvalidCRL: return -67830 case InvalidFormType: return -67831 case InvalidID: return -67832 case InvalidIdentifier: return -67833 case InvalidIndex: return -67834 case InvalidPolicyIdentifiers: return -67835 case InvalidTimeString: return -67836 case InvalidReason: return -67837 case InvalidRequestInputs: return -67838 case InvalidResponseVector: return -67839 case InvalidStopOnPolicy: return -67840 case InvalidTuple: return -67841 case MultipleValuesUnsupported: return -67842 case NotTrusted: return -67843 case NoDefaultAuthority: return -67844 case RejectedForm: return -67845 case RequestLost: return -67846 case RequestRejected: return -67847 case UnsupportedAddressType: return -67848 case UnsupportedService: return -67849 case InvalidTupleGroup: return -67850 case InvalidBaseACLs: return -67851 case InvalidTupleCredendtials: return -67852 case InvalidEncoding: return -67853 case InvalidValidityPeriod: return -67854 case InvalidRequestor: return -67855 case RequestDescriptor: return -67856 case InvalidBundleInfo: return -67857 case InvalidCRLIndex: return -67858 case NoFieldValues: return -67859 case UnsupportedFieldFormat: return -67860 case UnsupportedIndexInfo: return -67861 case UnsupportedLocality: return -67862 case UnsupportedNumAttributes: return -67863 case UnsupportedNumIndexes: return -67864 case UnsupportedNumRecordTypes: return -67865 case FieldSpecifiedMultiple: return -67866 case IncompatibleFieldFormat: return -67867 case InvalidParsingModule: return -67868 case DatabaseLocked: return -67869 case DatastoreIsOpen: return -67870 case MissingValue: return -67871 case UnsupportedQueryLimits: return -67872 case UnsupportedNumSelectionPreds: return -67873 case UnsupportedOperator: return -67874 case InvalidDBLocation: return -67875 case InvalidAccessRequest: return -67876 case InvalidIndexInfo: return -67877 case InvalidNewOwner: return -67878 case InvalidModifyMode: return -67879 default: return -99999 } } public var description : String { switch self { case Success: return "No error." case Unimplemented: return "Function or operation not implemented." case Param: return "One or more parameters passed to a function were not valid." case Allocate: return "Failed to allocate memory." case NotAvailable: return "No keychain is available. You may need to restart your computer." case ReadOnly: return "This keychain cannot be modified." case AuthFailed: return "The user name or passphrase you entered is not correct." case NoSuchKeychain: return "The specified keychain could not be found." case InvalidKeychain: return "The specified keychain is not a valid keychain file." case DuplicateKeychain: return "A keychain with the same name already exists." case DuplicateCallback: return "The specified callback function is already installed." case InvalidCallback: return "The specified callback function is not valid." case DuplicateItem: return "The specified item already exists in the keychain." case ItemNotFound: return "The specified item could not be found in the keychain." case BufferTooSmall: return "There is not enough memory available to use the specified item." case DataTooLarge: return "This item contains information which is too large or in a format that cannot be displayed." case NoSuchAttr: return "The specified attribute does not exist." case InvalidItemRef: return "The specified item is no longer valid. It may have been deleted from the keychain." case InvalidSearchRef: return "Unable to search the current keychain." case NoSuchClass: return "The specified item does not appear to be a valid keychain item." case NoDefaultKeychain: return "A default keychain could not be found." case InteractionNotAllowed: return "User interaction is not allowed." case ReadOnlyAttr: return "The specified attribute could not be modified." case WrongSecVersion: return "This keychain was created by a different version of the system software and cannot be opened." case KeySizeNotAllowed: return "This item specifies a key size which is too large." case NoStorageModule: return "A required component (data storage module) could not be loaded. You may need to restart your computer." case NoCertificateModule: return "A required component (certificate module) could not be loaded. You may need to restart your computer." case NoPolicyModule: return "A required component (policy module) could not be loaded. You may need to restart your computer." case InteractionRequired: return "User interaction is required, but is currently not allowed." case DataNotAvailable: return "The contents of this item cannot be retrieved." case DataNotModifiable: return "The contents of this item cannot be modified." case CreateChainFailed: return "One or more certificates required to validate this certificate cannot be found." case InvalidPrefsDomain: return "The specified preferences domain is not valid." case ACLNotSimple: return "The specified access control list is not in standard (simple) form." case PolicyNotFound: return "The specified policy cannot be found." case InvalidTrustSetting: return "The specified trust setting is invalid." case NoAccessForItem: return "The specified item has no access control." case InvalidOwnerEdit: return "Invalid attempt to change the owner of this item." case TrustNotAvailable: return "No trust results are available." case UnsupportedFormat: return "Import/Export format unsupported." case UnknownFormat: return "Unknown format in import." case KeyIsSensitive: return "Key material must be wrapped for export." case MultiplePrivKeys: return "An attempt was made to import multiple private keys." case PassphraseRequired: return "Passphrase is required for import/export." case InvalidPasswordRef: return "The password reference was invalid." case InvalidTrustSettings: return "The Trust Settings Record was corrupted." case NoTrustSettings: return "No Trust Settings were found." case Pkcs12VerifyFailure: return "MAC verification failed during PKCS12 import (wrong password?)" case InvalidCertificate: return "This certificate could not be decoded." case NotSigner: return "A certificate was not signed by its proposed parent." case PolicyDenied: return "The certificate chain was not trusted due to a policy not accepting it." case InvalidKey: return "The provided key material was not valid." case Decode: return "Unable to decode the provided data." case Internal: return "An internal error occured in the Security framework." case UnsupportedAlgorithm: return "An unsupported algorithm was encountered." case UnsupportedOperation: return "The operation you requested is not supported by this key." case UnsupportedPadding: return "The padding you requested is not supported." case ItemInvalidKey: return "A string key in dictionary is not one of the supported keys." case ItemInvalidKeyType: return "A key in a dictionary is neither a CFStringRef nor a CFNumberRef." case ItemInvalidValue: return "A value in a dictionary is an invalid (or unsupported) CF type." case ItemClassMissing: return "No kSecItemClass key was specified in a dictionary." case ItemMatchUnsupported: return "The caller passed one or more kSecMatch keys to a function which does not support matches." case UseItemListUnsupported: return "The caller passed in a kSecUseItemList key to a function which does not support it." case UseKeychainUnsupported: return "The caller passed in a kSecUseKeychain key to a function which does not support it." case UseKeychainListUnsupported: return "The caller passed in a kSecUseKeychainList key to a function which does not support it." case ReturnDataUnsupported: return "The caller passed in a kSecReturnData key to a function which does not support it." case ReturnAttributesUnsupported: return "The caller passed in a kSecReturnAttributes key to a function which does not support it." case ReturnRefUnsupported: return "The caller passed in a kSecReturnRef key to a function which does not support it." case ReturnPersitentRefUnsupported: return "The caller passed in a kSecReturnPersistentRef key to a function which does not support it." case ValueRefUnsupported: return "The caller passed in a kSecValueRef key to a function which does not support it." case ValuePersistentRefUnsupported: return "The caller passed in a kSecValuePersistentRef key to a function which does not support it." case ReturnMissingPointer: return "The caller passed asked for something to be returned but did not pass in a result pointer." case MatchLimitUnsupported: return "The caller passed in a kSecMatchLimit key to a call which does not support limits." case ItemIllegalQuery: return "The caller passed in a query which contained too many keys." case WaitForCallback: return "This operation is incomplete, until the callback is invoked (not an error)." case MissingEntitlement: return "Internal error when a required entitlement isn't present, client has neither application-identifier nor keychain-access-groups entitlements." case UpgradePending: return "Error returned if keychain database needs a schema migration but the device is locked, clients should wait for a device unlock notification and retry the command." case MPSignatureInvalid: return "Signature invalid on MP message" case OTRTooOld: return "Message is too old to use" case OTRIDTooNew: return "Key ID is too new to use! Message from the future?" case ServiceNotAvailable: return "The required service is not available." case InsufficientClientID: return "The client ID is not correct." case DeviceReset: return "A device reset has occurred." case DeviceFailed: return "A device failure has occurred." case AppleAddAppACLSubject: return "Adding an application ACL subject failed." case ApplePublicKeyIncomplete: return "The public key is incomplete." case AppleSignatureMismatch: return "A signature mismatch has occurred." case AppleInvalidKeyStartDate: return "The specified key has an invalid start date." case AppleInvalidKeyEndDate: return "The specified key has an invalid end date." case ConversionError: return "A conversion error has occurred." case AppleSSLv2Rollback: return "A SSLv2 rollback error has occurred." case DiskFull: return "The disk is full." case QuotaExceeded: return "The quota was exceeded." case FileTooBig: return "The file is too big." case InvalidDatabaseBlob: return "The specified database has an invalid blob." case InvalidKeyBlob: return "The specified database has an invalid key blob." case IncompatibleDatabaseBlob: return "The specified database has an incompatible blob." case IncompatibleKeyBlob: return "The specified database has an incompatible key blob." case HostNameMismatch: return "A host name mismatch has occurred." case UnknownCriticalExtensionFlag: return "There is an unknown critical extension flag." case NoBasicConstraints: return "No basic constraints were found." case NoBasicConstraintsCA: return "No basic CA constraints were found." case InvalidAuthorityKeyID: return "The authority key ID is not valid." case InvalidSubjectKeyID: return "The subject key ID is not valid." case InvalidKeyUsageForPolicy: return "The key usage is not valid for the specified policy." case InvalidExtendedKeyUsage: return "The extended key usage is not valid." case InvalidIDLinkage: return "The ID linkage is not valid." case PathLengthConstraintExceeded: return "The path length constraint was exceeded." case InvalidRoot: return "The root or anchor certificate is not valid." case CRLExpired: return "The CRL has expired." case CRLNotValidYet: return "The CRL is not yet valid." case CRLNotFound: return "The CRL was not found." case CRLServerDown: return "The CRL server is down." case CRLBadURI: return "The CRL has a bad Uniform Resource Identifier." case UnknownCertExtension: return "An unknown certificate extension was encountered." case UnknownCRLExtension: return "An unknown CRL extension was encountered." case CRLNotTrusted: return "The CRL is not trusted." case CRLPolicyFailed: return "The CRL policy failed." case IDPFailure: return "The issuing distribution point was not valid." case SMIMEEmailAddressesNotFound: return "An email address mismatch was encountered." case SMIMEBadExtendedKeyUsage: return "The appropriate extended key usage for SMIME was not found." case SMIMEBadKeyUsage: return "The key usage is not compatible with SMIME." case SMIMEKeyUsageNotCritical: return "The key usage extension is not marked as critical." case SMIMENoEmailAddress: return "No email address was found in the certificate." case SMIMESubjAltNameNotCritical: return "The subject alternative name extension is not marked as critical." case SSLBadExtendedKeyUsage: return "The appropriate extended key usage for SSL was not found." case OCSPBadResponse: return "The OCSP response was incorrect or could not be parsed." case OCSPBadRequest: return "The OCSP request was incorrect or could not be parsed." case OCSPUnavailable: return "OCSP service is unavailable." case OCSPStatusUnrecognized: return "The OCSP server did not recognize this certificate." case EndOfData: return "An end-of-data was detected." case IncompleteCertRevocationCheck: return "An incomplete certificate revocation check occurred." case NetworkFailure: return "A network failure occurred." case OCSPNotTrustedToAnchor: return "The OCSP response was not trusted to a root or anchor certificate." case RecordModified: return "The record was modified." case OCSPSignatureError: return "The OCSP response had an invalid signature." case OCSPNoSigner: return "The OCSP response had no signer." case OCSPResponderMalformedReq: return "The OCSP responder was given a malformed request." case OCSPResponderInternalError: return "The OCSP responder encountered an internal error." case OCSPResponderTryLater: return "The OCSP responder is busy, try again later." case OCSPResponderSignatureRequired: return "The OCSP responder requires a signature." case OCSPResponderUnauthorized: return "The OCSP responder rejected this request as unauthorized." case OCSPResponseNonceMismatch: return "The OCSP response nonce did not match the request." case CodeSigningBadCertChainLength: return "Code signing encountered an incorrect certificate chain length." case CodeSigningNoBasicConstraints: return "Code signing found no basic constraints." case CodeSigningBadPathLengthConstraint: return "Code signing encountered an incorrect path length constraint." case CodeSigningNoExtendedKeyUsage: return "Code signing found no extended key usage." case CodeSigningDevelopment: return "Code signing indicated use of a development-only certificate." case ResourceSignBadCertChainLength: return "Resource signing has encountered an incorrect certificate chain length." case ResourceSignBadExtKeyUsage: return "Resource signing has encountered an error in the extended key usage." case TrustSettingDeny: return "The trust setting for this policy was set to Deny." case InvalidSubjectName: return "An invalid certificate subject name was encountered." case UnknownQualifiedCertStatement: return "An unknown qualified certificate statement was encountered." case MobileMeRequestQueued: return "The MobileMe request will be sent during the next connection." case MobileMeRequestRedirected: return "The MobileMe request was redirected." case MobileMeServerError: return "A MobileMe server error occurred." case MobileMeServerNotAvailable: return "The MobileMe server is not available." case MobileMeServerAlreadyExists: return "The MobileMe server reported that the item already exists." case MobileMeServerServiceErr: return "A MobileMe service error has occurred." case MobileMeRequestAlreadyPending: return "A MobileMe request is already pending." case MobileMeNoRequestPending: return "MobileMe has no request pending." case MobileMeCSRVerifyFailure: return "A MobileMe CSR verification failure has occurred." case MobileMeFailedConsistencyCheck: return "MobileMe has found a failed consistency check." case NotInitialized: return "A function was called without initializing CSSM." case InvalidHandleUsage: return "The CSSM handle does not match with the service type." case PVCReferentNotFound: return "A reference to the calling module was not found in the list of authorized callers." case FunctionIntegrityFail: return "A function address was not within the verified module." case InternalError: return "An internal error has occurred." case MemoryError: return "A memory error has occurred." case InvalidData: return "Invalid data was encountered." case MDSError: return "A Module Directory Service error has occurred." case InvalidPointer: return "An invalid pointer was encountered." case SelfCheckFailed: return "Self-check has failed." case FunctionFailed: return "A function has failed." case ModuleManifestVerifyFailed: return "A module manifest verification failure has occurred." case InvalidGUID: return "An invalid GUID was encountered." case InvalidHandle: return "An invalid handle was encountered." case InvalidDBList: return "An invalid DB list was encountered." case InvalidPassthroughID: return "An invalid passthrough ID was encountered." case InvalidNetworkAddress: return "An invalid network address was encountered." case CRLAlreadySigned: return "The certificate revocation list is already signed." case InvalidNumberOfFields: return "An invalid number of fields were encountered." case VerificationFailure: return "A verification failure occurred." case UnknownTag: return "An unknown tag was encountered." case InvalidSignature: return "An invalid signature was encountered." case InvalidName: return "An invalid name was encountered." case InvalidCertificateRef: return "An invalid certificate reference was encountered." case InvalidCertificateGroup: return "An invalid certificate group was encountered." case TagNotFound: return "The specified tag was not found." case InvalidQuery: return "The specified query was not valid." case InvalidValue: return "An invalid value was detected." case CallbackFailed: return "A callback has failed." case ACLDeleteFailed: return "An ACL delete operation has failed." case ACLReplaceFailed: return "An ACL replace operation has failed." case ACLAddFailed: return "An ACL add operation has failed." case ACLChangeFailed: return "An ACL change operation has failed." case InvalidAccessCredentials: return "Invalid access credentials were encountered." case InvalidRecord: return "An invalid record was encountered." case InvalidACL: return "An invalid ACL was encountered." case InvalidSampleValue: return "An invalid sample value was encountered." case IncompatibleVersion: return "An incompatible version was encountered." case PrivilegeNotGranted: return "The privilege was not granted." case InvalidScope: return "An invalid scope was encountered." case PVCAlreadyConfigured: return "The PVC is already configured." case InvalidPVC: return "An invalid PVC was encountered." case EMMLoadFailed: return "The EMM load has failed." case EMMUnloadFailed: return "The EMM unload has failed." case AddinLoadFailed: return "The add-in load operation has failed." case InvalidKeyRef: return "An invalid key was encountered." case InvalidKeyHierarchy: return "An invalid key hierarchy was encountered." case AddinUnloadFailed: return "The add-in unload operation has failed." case LibraryReferenceNotFound: return "A library reference was not found." case InvalidAddinFunctionTable: return "An invalid add-in function table was encountered." case InvalidServiceMask: return "An invalid service mask was encountered." case ModuleNotLoaded: return "A module was not loaded." case InvalidSubServiceID: return "An invalid subservice ID was encountered." case AttributeNotInContext: return "An attribute was not in the context." case ModuleManagerInitializeFailed: return "A module failed to initialize." case ModuleManagerNotFound: return "A module was not found." case EventNotificationCallbackNotFound: return "An event notification callback was not found." case InputLengthError: return "An input length error was encountered." case OutputLengthError: return "An output length error was encountered." case PrivilegeNotSupported: return "The privilege is not supported." case DeviceError: return "A device error was encountered." case AttachHandleBusy: return "The CSP handle was busy." case NotLoggedIn: return "You are not logged in." case AlgorithmMismatch: return "An algorithm mismatch was encountered." case KeyUsageIncorrect: return "The key usage is incorrect." case KeyBlobTypeIncorrect: return "The key blob type is incorrect." case KeyHeaderInconsistent: return "The key header is inconsistent." case UnsupportedKeyFormat: return "The key header format is not supported." case UnsupportedKeySize: return "The key size is not supported." case InvalidKeyUsageMask: return "The key usage mask is not valid." case UnsupportedKeyUsageMask: return "The key usage mask is not supported." case InvalidKeyAttributeMask: return "The key attribute mask is not valid." case UnsupportedKeyAttributeMask: return "The key attribute mask is not supported." case InvalidKeyLabel: return "The key label is not valid." case UnsupportedKeyLabel: return "The key label is not supported." case InvalidKeyFormat: return "The key format is not valid." case UnsupportedVectorOfBuffers: return "The vector of buffers is not supported." case InvalidInputVector: return "The input vector is not valid." case InvalidOutputVector: return "The output vector is not valid." case InvalidContext: return "An invalid context was encountered." case InvalidAlgorithm: return "An invalid algorithm was encountered." case InvalidAttributeKey: return "A key attribute was not valid." case MissingAttributeKey: return "A key attribute was missing." case InvalidAttributeInitVector: return "An init vector attribute was not valid." case MissingAttributeInitVector: return "An init vector attribute was missing." case InvalidAttributeSalt: return "A salt attribute was not valid." case MissingAttributeSalt: return "A salt attribute was missing." case InvalidAttributePadding: return "A padding attribute was not valid." case MissingAttributePadding: return "A padding attribute was missing." case InvalidAttributeRandom: return "A random number attribute was not valid." case MissingAttributeRandom: return "A random number attribute was missing." case InvalidAttributeSeed: return "A seed attribute was not valid." case MissingAttributeSeed: return "A seed attribute was missing." case InvalidAttributePassphrase: return "A passphrase attribute was not valid." case MissingAttributePassphrase: return "A passphrase attribute was missing." case InvalidAttributeKeyLength: return "A key length attribute was not valid." case MissingAttributeKeyLength: return "A key length attribute was missing." case InvalidAttributeBlockSize: return "A block size attribute was not valid." case MissingAttributeBlockSize: return "A block size attribute was missing." case InvalidAttributeOutputSize: return "An output size attribute was not valid." case MissingAttributeOutputSize: return "An output size attribute was missing." case InvalidAttributeRounds: return "The number of rounds attribute was not valid." case MissingAttributeRounds: return "The number of rounds attribute was missing." case InvalidAlgorithmParms: return "An algorithm parameters attribute was not valid." case MissingAlgorithmParms: return "An algorithm parameters attribute was missing." case InvalidAttributeLabel: return "A label attribute was not valid." case MissingAttributeLabel: return "A label attribute was missing." case InvalidAttributeKeyType: return "A key type attribute was not valid." case MissingAttributeKeyType: return "A key type attribute was missing." case InvalidAttributeMode: return "A mode attribute was not valid." case MissingAttributeMode: return "A mode attribute was missing." case InvalidAttributeEffectiveBits: return "An effective bits attribute was not valid." case MissingAttributeEffectiveBits: return "An effective bits attribute was missing." case InvalidAttributeStartDate: return "A start date attribute was not valid." case MissingAttributeStartDate: return "A start date attribute was missing." case InvalidAttributeEndDate: return "An end date attribute was not valid." case MissingAttributeEndDate: return "An end date attribute was missing." case InvalidAttributeVersion: return "A version attribute was not valid." case MissingAttributeVersion: return "A version attribute was missing." case InvalidAttributePrime: return "A prime attribute was not valid." case MissingAttributePrime: return "A prime attribute was missing." case InvalidAttributeBase: return "A base attribute was not valid." case MissingAttributeBase: return "A base attribute was missing." case InvalidAttributeSubprime: return "A subprime attribute was not valid." case MissingAttributeSubprime: return "A subprime attribute was missing." case InvalidAttributeIterationCount: return "An iteration count attribute was not valid." case MissingAttributeIterationCount: return "An iteration count attribute was missing." case InvalidAttributeDLDBHandle: return "A database handle attribute was not valid." case MissingAttributeDLDBHandle: return "A database handle attribute was missing." case InvalidAttributeAccessCredentials: return "An access credentials attribute was not valid." case MissingAttributeAccessCredentials: return "An access credentials attribute was missing." case InvalidAttributePublicKeyFormat: return "A public key format attribute was not valid." case MissingAttributePublicKeyFormat: return "A public key format attribute was missing." case InvalidAttributePrivateKeyFormat: return "A private key format attribute was not valid." case MissingAttributePrivateKeyFormat: return "A private key format attribute was missing." case InvalidAttributeSymmetricKeyFormat: return "A symmetric key format attribute was not valid." case MissingAttributeSymmetricKeyFormat: return "A symmetric key format attribute was missing." case InvalidAttributeWrappedKeyFormat: return "A wrapped key format attribute was not valid." case MissingAttributeWrappedKeyFormat: return "A wrapped key format attribute was missing." case StagedOperationInProgress: return "A staged operation is in progress." case StagedOperationNotStarted: return "A staged operation was not started." case VerifyFailed: return "A cryptographic verification failure has occurred." case QuerySizeUnknown: return "The query size is unknown." case BlockSizeMismatch: return "A block size mismatch occurred." case PublicKeyInconsistent: return "The public key was inconsistent." case DeviceVerifyFailed: return "A device verification failure has occurred." case InvalidLoginName: return "An invalid login name was detected." case AlreadyLoggedIn: return "The user is already logged in." case InvalidDigestAlgorithm: return "An invalid digest algorithm was detected." case InvalidCRLGroup: return "An invalid CRL group was detected." case CertificateCannotOperate: return "The certificate cannot operate." case CertificateExpired: return "An expired certificate was detected." case CertificateNotValidYet: return "The certificate is not yet valid." case CertificateRevoked: return "The certificate was revoked." case CertificateSuspended: return "The certificate was suspended." case InsufficientCredentials: return "Insufficient credentials were detected." case InvalidAction: return "The action was not valid." case InvalidAuthority: return "The authority was not valid." case VerifyActionFailed: return "A verify action has failed." case InvalidCertAuthority: return "The certificate authority was not valid." case InvaldCRLAuthority: return "The CRL authority was not valid." case InvalidCRLEncoding: return "The CRL encoding was not valid." case InvalidCRLType: return "The CRL type was not valid." case InvalidCRL: return "The CRL was not valid." case InvalidFormType: return "The form type was not valid." case InvalidID: return "The ID was not valid." case InvalidIdentifier: return "The identifier was not valid." case InvalidIndex: return "The index was not valid." case InvalidPolicyIdentifiers: return "The policy identifiers are not valid." case InvalidTimeString: return "The time specified was not valid." case InvalidReason: return "The trust policy reason was not valid." case InvalidRequestInputs: return "The request inputs are not valid." case InvalidResponseVector: return "The response vector was not valid." case InvalidStopOnPolicy: return "The stop-on policy was not valid." case InvalidTuple: return "The tuple was not valid." case MultipleValuesUnsupported: return "Multiple values are not supported." case NotTrusted: return "The trust policy was not trusted." case NoDefaultAuthority: return "No default authority was detected." case RejectedForm: return "The trust policy had a rejected form." case RequestLost: return "The request was lost." case RequestRejected: return "The request was rejected." case UnsupportedAddressType: return "The address type is not supported." case UnsupportedService: return "The service is not supported." case InvalidTupleGroup: return "The tuple group was not valid." case InvalidBaseACLs: return "The base ACLs are not valid." case InvalidTupleCredendtials: return "The tuple credentials are not valid." case InvalidEncoding: return "The encoding was not valid." case InvalidValidityPeriod: return "The validity period was not valid." case InvalidRequestor: return "The requestor was not valid." case RequestDescriptor: return "The request descriptor was not valid." case InvalidBundleInfo: return "The bundle information was not valid." case InvalidCRLIndex: return "The CRL index was not valid." case NoFieldValues: return "No field values were detected." case UnsupportedFieldFormat: return "The field format is not supported." case UnsupportedIndexInfo: return "The index information is not supported." case UnsupportedLocality: return "The locality is not supported." case UnsupportedNumAttributes: return "The number of attributes is not supported." case UnsupportedNumIndexes: return "The number of indexes is not supported." case UnsupportedNumRecordTypes: return "The number of record types is not supported." case FieldSpecifiedMultiple: return "Too many fields were specified." case IncompatibleFieldFormat: return "The field format was incompatible." case InvalidParsingModule: return "The parsing module was not valid." case DatabaseLocked: return "The database is locked." case DatastoreIsOpen: return "The data store is open." case MissingValue: return "A missing value was detected." case UnsupportedQueryLimits: return "The query limits are not supported." case UnsupportedNumSelectionPreds: return "The number of selection predicates is not supported." case UnsupportedOperator: return "The operator is not supported." case InvalidDBLocation: return "The database location is not valid." case InvalidAccessRequest: return "The access request is not valid." case InvalidIndexInfo: return "The index information is not valid." case InvalidNewOwner: return "The new owner is not valid." case InvalidModifyMode: return "The modify mode is not valid." default: return "Unexpected error has occurred." } } }
mit
2e18d19f7ffc19a787fbd1c59bf79007
33.009965
188
0.603636
5.86283
false
false
false
false
SeriousChoice/SCSwift
SCSwift/Form/SCAttachmentTableCell.swift
1
3539
// // SCAttachmentTableCell.swift // SCSwiftExample // // Created by Nicola Innocenti on 08/01/2022. // Copyright © 2022 Nicola Innocenti. All rights reserved. // import UIKit class SCAttachmentTableCell: UITableViewCell { public var lblTitle: UILabel = { let label = UILabel() label.numberOfLines = 0 return label }() public var imgAttachment: UIImageView = { let image = UIImageView() image.layer.cornerRadius = 3 image.clipsToBounds = true return image }() public var lblFileName: UILabel = { let label = UILabel() label.numberOfLines = 1 return label }() public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) clipsToBounds = true accessoryType = .disclosureIndicator setupLayout() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } private func setupLayout() { let margin = SCFormViewController.cellsMargin contentView.addSubview(lblTitle) lblTitle.sc_pinEdge(toSuperViewEdge: .top, withOffset: margin) lblTitle.sc_pinEdge(toSuperViewEdge: .leading, withOffset: 20) lblTitle.sc_pinEdge(toSuperViewEdge: .bottom, withOffset: -margin) lblTitle.setContentHuggingPriority(.defaultHigh, for: .horizontal) lblTitle.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) contentView.addSubview(imgAttachment) imgAttachment.sc_setDimension(.width, withValue: 30) imgAttachment.sc_setDimension(.height, withValue: 30) imgAttachment.sc_pinEdge(toSuperViewEdge: .trailing, withOffset: -40) imgAttachment.sc_alignAxis(axis: .vertical, toView: lblTitle) contentView.addSubview(lblFileName) lblFileName.sc_pinEdge(toSuperViewEdge: .top, withOffset: margin) lblFileName.sc_pinEdge(toSuperViewEdge: .trailing, withOffset: -40) lblFileName.sc_pinEdge(toSuperViewEdge: .bottom, withOffset: -margin) lblFileName.setContentHuggingPriority(.defaultLow, for: .horizontal) lblFileName.setContentCompressionResistancePriority(.defaultHigh, for: .horizontal) lblTitle.sc_pinEdge(.trailing, toEdge: .leading, ofView: imgAttachment, withOffset: 20, withRelation: .greaterOrEqual) lblTitle.sc_pinEdge(.trailing, toEdge: .leading, ofView: lblFileName, withOffset: -20, withRelation: .greaterOrEqual) } public override func configure(with row: SCFormRow) { lblTitle.text = row.mandatory ? "\(row.title ?? "")*" : row.title if let url = row.attachmentUrl { if let image = UIImage(contentsOfFile: url.absoluteString.replacingOccurrences(of: "file://", with: "")) { imgAttachment.image = image lblFileName.text = nil } else { imgAttachment.image = nil lblFileName.text = url.lastPathComponent } } else { imgAttachment.image = nil lblFileName.text = nil } } }
mit
eed93eadb1bdf2dadbc400550096ad87
35.854167
126
0.651781
5.134978
false
false
false
false
michaello/Aloha
AlohaGIF/ImagePicker/ImageGallery/ImageGalleryView.swift
1
8360
import UIKit import Photos fileprivate func < <T: Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } protocol ImageGalleryPanGestureDelegate: class { func panGestureDidStart() func panGestureDidChange(_ translation: CGPoint) func panGestureDidEnd(_ translation: CGPoint, velocity: CGPoint) func tooLongMovieSelected() } open class ImageGalleryView: UIView { struct Dimensions { static let galleryHeight: CGFloat = 160 static let galleryBarHeight: CGFloat = 24 } var configuration = Configuration() lazy open var collectionView: UICollectionView = { [unowned self] in let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: self.collectionViewLayout) collectionView.translatesAutoresizingMaskIntoConstraints = false collectionView.backgroundColor = self.configuration.mainColor collectionView.showsHorizontalScrollIndicator = false collectionView.dataSource = self collectionView.delegate = self return collectionView }() lazy var collectionViewLayout: UICollectionViewLayout = { [unowned self] in let layout = ImageGalleryLayout() layout.scrollDirection = .horizontal layout.minimumInteritemSpacing = self.configuration.cellSpacing layout.minimumLineSpacing = 2 layout.sectionInset = UIEdgeInsets.zero return layout }() lazy var topSeparator: UIView = { [unowned self] in let view = UIView() view.isHidden = true view.translatesAutoresizingMaskIntoConstraints = false view.addGestureRecognizer(self.panGestureRecognizer) view.backgroundColor = self.configuration.gallerySeparatorColor return view }() lazy var panGestureRecognizer: UIPanGestureRecognizer = { [unowned self] in let gesture = UIPanGestureRecognizer() gesture.addTarget(self, action: #selector(handlePanGestureRecognizer(_:))) return gesture }() open lazy var noImagesLabel: UILabel = { [unowned self] in let label = UILabel() label.isHidden = true label.font = self.configuration.noImagesFont label.textColor = self.configuration.noImagesColor label.text = self.configuration.noImagesTitle label.alpha = 0 label.sizeToFit() self.addSubview(label) return label }() open lazy var selectedStack = ImageStack() lazy var assets = [PHAsset]() weak var delegate: ImageGalleryPanGestureDelegate? var collectionSize: CGSize? var shouldTransform = false var imagesBeforeLoading = 0 var fetchResult: PHFetchResult<AnyObject>? var imageLimit = 0 // MARK: - Initializers public init(configuration: Configuration? = nil) { if let configuration = configuration { self.configuration = configuration } super.init(frame: .zero) configure() } override init(frame: CGRect) { super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func configure() { backgroundColor = configuration.mainColor collectionView.register(ImageGalleryViewCell.self, forCellWithReuseIdentifier: CollectionView.reusableIdentifier) [collectionView, topSeparator].forEach { addSubview($0) } topSeparator.addSubview(configuration.indicatorView) imagesBeforeLoading = 0 fetchPhotos() } // MARK: - Layout open override func layoutSubviews() { super.layoutSubviews() updateNoImagesLabel() } func updateFrames() { let totalWidth = UIScreen.main.bounds.width frame.size.width = totalWidth let collectionFrame = frame.height == Dimensions.galleryBarHeight ? 100 + Dimensions.galleryBarHeight : frame.height topSeparator.frame = CGRect(x: 0, y: 0, width: totalWidth, height: Dimensions.galleryBarHeight) topSeparator.autoresizingMask = [.flexibleLeftMargin, .flexibleRightMargin, .flexibleWidth] configuration.indicatorView.frame = CGRect(x: (totalWidth - configuration.indicatorWidth) / 2, y: (topSeparator.frame.height - configuration.indicatorHeight) / 2, width: configuration.indicatorWidth, height: configuration.indicatorHeight) collectionView.frame = CGRect(x: 0, y: 0, width: totalWidth, height: collectionFrame) collectionSize = CGSize(width: collectionView.frame.height, height: collectionView.frame.height) collectionView.reloadData() } func updateNoImagesLabel() { let height = bounds.height let threshold = Dimensions.galleryBarHeight * 2 UIView.animate(withDuration: 0.25, animations: { if threshold > height || self.collectionView.alpha != 0 { self.noImagesLabel.alpha = 0 } else { self.noImagesLabel.center = CGPoint(x: self.bounds.width / 2, y: height / 2) self.noImagesLabel.alpha = (height > threshold) ? 1 : (height - Dimensions.galleryBarHeight) / threshold } }) } // MARK: - Photos handler func fetchPhotos(_ completion: (() -> Void)? = nil) { AssetManager.fetch(withConfiguration: configuration) { assets in self.assets.removeAll() self.assets.append(contentsOf: assets) self.collectionView.reloadData() completion?() } } // MARK: - Pan gesture recognizer func handlePanGestureRecognizer(_ gesture: UIPanGestureRecognizer) { guard let superview = superview else { return } let translation = gesture.translation(in: superview) let velocity = gesture.velocity(in: superview) switch gesture.state { case .began: delegate?.panGestureDidStart() case .changed: delegate?.panGestureDidChange(translation) case .ended: delegate?.panGestureDidEnd(translation, velocity: velocity) default: break } } func displayNoImagesMessage(_ hideCollectionView: Bool) { collectionView.alpha = hideCollectionView ? 0 : 1 updateNoImagesLabel() } } // MARK: CollectionViewFlowLayout delegate methods extension ImageGalleryView: UICollectionViewDelegateFlowLayout { public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { guard let collectionSize = collectionSize else { return CGSize.zero } return collectionSize } } // MARK: CollectionView delegate methods extension ImageGalleryView: UICollectionViewDelegate { public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { guard let cell = collectionView.cellForItem(at: indexPath) as? ImageGalleryViewCell else { return } for asset in self.selectedStack.assets { self.selectedStack.dropAsset(asset) } // Animate deselecting photos for any selected visible cells guard let visibleCells = collectionView.visibleCells as? [ImageGalleryViewCell] else { return } for cell in visibleCells { if cell.selectedImageView.image != nil && cell.selectedImageView.image != AssetManager.getImage("infoIcon") { UIView.animate(withDuration: 0.2, animations: { cell.selectedImageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) }, completion: { _ in cell.selectedImageView.image = nil }) } } let asset = assets[(indexPath as NSIndexPath).row] AssetManager.selectedAsset = asset AssetManager.resolveAsset(asset, size: CGSize(width: 100, height: 100)) { image in guard let _ = image else { return } if cell.selectedImageView.image != nil { UIView.animate(withDuration: 0.2, animations: { cell.selectedImageView.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) }, completion: { _ in cell.selectedImageView.image = nil }) self.selectedStack.dropAsset(asset) } else if self.imageLimit == 0 || self.imageLimit > self.selectedStack.assets.count { cell.selectedImageView.image = AssetManager.getImage("selectedImageGallery") cell.selectedImageView.transform = CGAffineTransform(scaleX: 0, y: 0) UIView.animate(withDuration: 0.2, animations: { _ in cell.selectedImageView.transform = CGAffineTransform.identity }) self.selectedStack.pushAsset(asset) } } } }
mit
fbb72157f9b508649842bda0357d09cb
31.529183
166
0.708612
5.066667
false
true
false
false
eleks/rnd-nearables-wearables
iOS/BeaconMe/BeaconMe/Model/Favorites.swift
1
1792
// // Favorites.swift // BeaconMe // // Created by Bogdan Shubravyi on 7/27/15. // Copyright (c) 2015 Eleks. All rights reserved. // import UIKit class Favorites { private let favoritesKey = "Favorites" private var cache: Array<String> = [] private var queue = dispatch_queue_create("favoritesQueue", DISPATCH_QUEUE_CONCURRENT); init() { dispatch_barrier_sync(queue) { () in if let storedFavorites = NSUserDefaults.standardUserDefaults().objectForKey(self.favoritesKey) as? [String] { self.cache = storedFavorites } else { self.cache = [] } } } func clear() { dispatch_barrier_async(queue) { () in self.cache.removeAll(keepCapacity: false) self.saveFavorites() } } func getFavorites() -> [String] { var result: [String]! dispatch_sync(queue) { () in result = self.cache } return result } func addFavorite(favorite: String) { dispatch_barrier_async(queue) { () in if !contains(self.cache, favorite) { self.cache.append(favorite) self.saveFavorites() } } } func removeFavorite(favorite: String) { dispatch_barrier_async(queue) { () in if let index = find(self.cache, favorite) { self.cache.removeAtIndex(index) self.saveFavorites() } } } private func saveFavorites() { NSUserDefaults.standardUserDefaults().setObject(self.cache, forKey: self.favoritesKey) NSUserDefaults.standardUserDefaults().synchronize() } }
mit
7607b4bf71172a600bdc1de58dc40ff3
23.547945
121
0.541295
4.559796
false
false
false
false
wjk/SwiftXPC
SwiftXPC/Transport/Connection.swift
1
3458
// // Connection.swift // DOS Prompt // // Created by William Kent on 7/28/14. // Copyright (c) 2014 William Kent. All rights reserved. // import Foundation import dispatch import XPC public final class XPCConnection : XPCObject { public class func createAnonymousConnection() -> XPCConnection { return XPCConnection(nativePointer: xpc_connection_create(nil, nil)) } public convenience init(name: String) { self.init(name: name, queue: nil) } public convenience init(name: String, queue: dispatch_queue_t?) { let namePtr = name.cStringUsingEncoding(NSUTF8StringEncoding) self.init(nativePointer: xpc_connection_create(namePtr!, queue)) } public convenience init(endpoint: XPCEndpoint) { self.init(nativePointer: xpc_connection_create_from_endpoint(endpoint.objectPointer)) } public func setTargetQueue(queue: dispatch_queue_t?) { xpc_connection_set_target_queue(objectPointer, queue) } public func setHandler(block: (XPCObject) -> ()) { xpc_connection_set_event_handler(objectPointer) { ptr in block(XPCObject(nativePointer: ptr)) } } public func suspend() { xpc_connection_suspend(objectPointer) } public func resume() { xpc_connection_resume(objectPointer) } public func sendMessage(message: XPCDictionary) { xpc_connection_send_message(objectPointer, message.objectPointer) } public func sendMessage(message: XPCDictionary, replyHandler: (XPCObject) -> ()) { xpc_connection_send_message_with_reply(objectPointer, message.objectPointer, nil) { obj in replyHandler(XPCObject(nativePointer: obj)) } } public func sendBarrier(barrier: () -> ()) { xpc_connection_send_barrier(objectPointer) { barrier() } } public func cancel() { xpc_connection_cancel(objectPointer) } // MARK: Properties public var name: String? { get { let ptr = xpc_connection_get_name(objectPointer) if ptr != nil { return String.fromCString(ptr) } else { return nil } } } public var effectiveUserIdOfRemotePeer : Int { get { return Int(xpc_connection_get_euid(objectPointer)) } } public var effectiveGroupIdOfRemotePeer : Int { get { return Int(xpc_connection_get_egid(objectPointer)) } } public var processIdOfRemotePeer : Int { get { return Int(xpc_connection_get_pid(objectPointer)) } } public var auditSessionIdOfRemotePeer : Int { get { return Int(xpc_connection_get_asid(objectPointer)) } } } extension XPCDictionary { public var remoteConnection: XPCConnection { get { return XPCConnection(nativePointer: xpc_dictionary_get_remote_connection(objectPointer)) } } // Note: Due to the underlying implementation, this method will only work once. // Subsequent calls will return nil. In addition, if the receiver does not have // a reply context, this method will always return nil. public func createReply() -> XPCDictionary? { let ptr = xpc_dictionary_create_reply(objectPointer) if ptr == nil { return nil } return XPCDictionary(nativePointer: ptr) } }
mit
7ee0517ff464cb977a62e02f8551eeb8
26.664
96
0.629555
4.580132
false
false
false
false
kiliankoe/catchmybus
catchmybus/ConnectionManager.swift
1
3255
// // ConnectionManager.swift // catchmybus // // Created by Kilian Koeltzsch on 13/01/15. // Copyright (c) 2015 Kilian Koeltzsch. All rights reserved. // import Foundation import SwiftyJSON private let _ConnectionManagerSharedInstace = ConnectionManager() class ConnectionManager { // ConnectionManager is a singleton, accessible via ConnectionManager.shared() static func shared() -> ConnectionManager { return _ConnectionManagerSharedInstace } // MARK: - Properties internal var stopDict = [String: Int]() internal var notificationDict = [String: Int]() var connections = [Connection]() var selectedConnection: Connection? { get { return self.selectedConnection } set(newSelection) { self.deselectAll() newSelection!.selected = true self.selectedConnection = newSelection // is this needed? } } var selectedStop: String? // TODO: Should the ConnectionManager be keeping the list of stops as well? // MARK: - init () { loadDefaults() } /** Load internal stopDict, notificationDict and selectedStop from NSUserDefaults */ internal func loadDefaults() { stopDict = NSUserDefaults.standardUserDefaults().dictionaryForKey(kStopDictKey) as! [String: Int] notificationDict = NSUserDefaults.standardUserDefaults().dictionaryForKey(kNotificationDictKey) as! [String: Int] selectedStop = NSUserDefaults.standardUserDefaults().stringForKey(kSelectedStopKey)! } /** Save internal stopDict, notificationDict and selectedStop to NSUserDefaults */ internal func saveDefaults() { NSUserDefaults.standardUserDefaults().setObject(stopDict, forKey: kStopDictKey) NSUserDefaults.standardUserDefaults().setObject(notificationDict, forKey: kNotificationDictKey) NSUserDefaults.standardUserDefaults().setObject(selectedStop, forKey: kSelectedStopKey) NSUserDefaults.standardUserDefaults().synchronize() } // MARK: - Manage list of connections /** Delete all stored connections */ internal func nuke() { connections.removeAll(keepCapacity: false) } /** Set all connections' selected attribute to false */ internal func deselectAll() { for connection in connections { connection.selected = false } } // MARK: - Update Methods /** Update arrival countdowns for known connections and remove connections that lie in the past */ internal func updateConnectionCountdowns() { // Update arrival countdowns for currently known connections for connection in connections { connection.update() } // Remove connections that lie in the past connections = connections.filter { (c: Connection) -> Bool in return c.date.timeIntervalSinceNow > 0 } } /** Make a call to DVBAPI to update list of connections - parameter completion: handler when new data has been stored in connection list, will not be called on error */ internal func updateConnections(completion: (err: NSError?) -> Void) { if let selectedStopName = selectedStop { DVBAPI.DMRequest(selectedStopName, completion: { (data, err) -> () in print(data) completion(err: nil) }) } else { NSLog("Update error: No selected stop") completion(err: NSError(domain: "io.kilian.catchmybus", code: 0, userInfo: [NSLocalizedDescriptionKey: "Update error: No selected stop"])) } } }
mit
6272f17698cefc5c7e1f8a2eae5323b0
26.584746
141
0.742857
4.130711
false
false
false
false
hotpoor-for-Liwei/LiteOS_Hackathon
Hakcathon_170108_哆啦I梦_wifind/ios/hackhuawei/LoginViewController.swift
2
6290
// // ViewController.swift // hackhuawei // // Created by 曾兆阳 on 2017/1/2. // Copyright © 2017年 曾兆阳. All rights reserved. // import UIKit class LoginViewController: UIViewController, UITextFieldDelegate { var backgroundView: UIImageView? var whiteView: UIImageView? var logoView: UIImageView? var closeView: UIImageView? var usernameInput: UITextField? var passwordInput: UITextField? var loginButton: UIButton? var registerButton: UIButton? let kScreenWidth = UIScreen.main.bounds.width let kScreenHeight = UIScreen.main.bounds.height override func viewDidLoad() { super.viewDidLoad() // self.navigationController?.isNavigationBarHidden = true self.backgroundView = UIImageView(frame: self.view.bounds) self.backgroundView?.image = #imageLiteral(resourceName: "background") self.whiteView = UIImageView(image: #imageLiteral(resourceName: "whiteBox_halfCirle")) self.logoView = UIImageView(image: #imageLiteral(resourceName: "logo")) self.logoView?.frame.origin.x = (kScreenWidth - self.logoView!.frame.width) / 2 self.logoView?.frame.origin.y = 60 self.closeView = UIImageView(image: #imageLiteral(resourceName: "cross")) self.closeView?.frame.origin.x = (kScreenWidth - self.closeView!.frame.width) / 2 self.closeView?.frame.origin.y = 617 self.view.addSubview(self.backgroundView!) self.view.addSubview(self.whiteView!) self.view.addSubview(self.logoView!) self.view.addSubview(self.closeView!) self.usernameInput = UITextField(frame: CGRect(x: (kScreenWidth - 350) / 2, y: 305, width: 350, height: 48)) self.usernameInput?.backgroundColor = UIColor.orange self.usernameInput?.borderStyle = .line self.usernameInput?.contentVerticalAlignment = .center self.usernameInput?.contentHorizontalAlignment = .center self.usernameInput?.textAlignment = .center self.usernameInput?.placeholder = "用户名" self.passwordInput = UITextField(frame: CGRect(x: (kScreenWidth - 350) / 2, y: 371, width: 350, height: 48)) self.passwordInput?.backgroundColor = UIColor.orange self.passwordInput?.borderStyle = .line self.passwordInput?.contentVerticalAlignment = .center self.passwordInput?.contentHorizontalAlignment = .center self.passwordInput?.textAlignment = .center self.passwordInput?.isSecureTextEntry = true self.passwordInput?.delegate = self self.passwordInput?.placeholder = "密码" self.loginButton = UIButton(frame: CGRect(x: (kScreenWidth - 94) / 2, y: 460, width: 94, height: 18)) // self.loginButton?.backgroundColor = UIColor.blue self.loginButton?.setTitle("登录", for: .normal) self.loginButton?.setBackgroundImage(#imageLiteral(resourceName: "ellipse"), for: .selected) self.loginButton?.setBackgroundImage(#imageLiteral(resourceName: "ellipse"), for: .highlighted) self.loginButton?.setTitleColor(UIColor.black, for: .normal) self.loginButton?.titleLabel?.font = UIFont.systemFont(ofSize: 30) self.loginButton?.titleLabel?.sizeToFit() self.loginButton?.addTarget(self, action: #selector(LoginViewController.loginButtonClick), for: .touchUpInside) // self.loginButton?.frame.origin = CGPoint(x: (kScreenWidth - self.loginButton!.frame.size.width) / 2, y: 400) // self.registerButton = UIButton(frame: CGRect(x: (kScreenWidth - 200) / 2 + 120, y: 390, width: 80, height: 50)) // self.registerButton?.backgroundColor = UIColor.green // self.registerButton?.setTitle("Register", for: .normal) // print("haha") self.view.addSubview(self.usernameInput!) self.view.addSubview(self.passwordInput!) self.view.addSubview(self.loginButton!) // self.view.addSubview(self.registerButton!) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loginButtonClick() { let network = HWNetwork(path: "/login") network.request.httpBody = "username=\(self.usernameInput!.text!)&password=\(self.passwordInput!.text!)".data(using: String.Encoding.utf8) let dataTask: URLSessionTask = network.session.dataTask(with: network.request as URLRequest) { (data, resp, err) in let res = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) if res == "1" { let navController = HWNavigationController() let homeViewController = HomeViewController() homeViewController.username = self.usernameInput!.text print("aaa") homeViewController.title = self.usernameInput!.text print("bbb") navController.pushViewController(homeViewController, animated: false) navController.modalTransitionStyle = .crossDissolve self.modalTransitionStyle = .crossDissolve DispatchQueue.main.async { self.present(navController, animated: true) { // } } } else { DispatchQueue.main.async { let HUD = MBProgressHUD(view: self.view) self.view.addSubview(HUD!) HUD?.labelText = "用户名或密码错误" HUD?.mode = .text HUD?.dimBackground = true HUD?.show(animated: true, whileExecuting: { sleep(1) }, completionBlock: { HUD?.removeFromSuperview() }) } } } dataTask.resume() } func textFieldShouldReturn(_ textField: UITextField) -> Bool { textField.resignFirstResponder() return true } }
bsd-3-clause
b0ab4e403f90444146bc0ecb718adc27
40.912752
146
0.621617
5.02818
false
false
false
false
pepibumur/Szimpla
Example/ServerTests/ServerSpec.swift
1
2042
import XCTest import Quick import Nimble import Swifter @testable import Szimpla class ServerSpec: QuickSpec { override func spec() { var subject: Server! var httpServer: MockServer! beforeEach { httpServer = MockServer() subject = Server(server: httpServer) } describe("-sessionConfiguration:") { it("should include the URLProtocol") { let inputConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration() let outputConfiguration = subject.sessionConfiguration(fromConfiguration: inputConfiguration) expect(outputConfiguration.protocolClasses?.first).to(be(UrlProtocol.self)) } } describe("-tearUp") { beforeEach { try! subject.tearUp() } it("should start the server") { expect(httpServer.startCalled) == true } it("should register the /stop endpoint") { expect(httpServer.routes.indexOf("/stop")).toNot(beNil()) } it("should register the /start endpoint") { expect(httpServer.routes.indexOf("/start")).toNot(beNil()) } it("should throw an error if we try to start twice") { expect { try subject.tearUp() }.to(throwError()) } } describe("-tearDown") { beforeEach { subject.tearDown() } it("should stop the server") { expect(httpServer.stopCalled) == true } } } } // MARK: - Private class MockServer: HttpServer { var startCalled: Bool = false var stopCalled: Bool = false override func start(listenPort: in_port_t, forceIPv4: Bool) throws { self.startCalled = true } override func stop() { self.stopCalled = true } }
mit
b58193132bbaae84ace6abe47df95753
26.608108
109
0.528893
5.416446
false
true
false
false
googlearchive/cannonball-ios
Cannonball/Theme.swift
1
2404
// // Copyright (C) 2018 Google, Inc. and other contributors. // // 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 open class Theme { let name: String let words: [String] let pictures: [String] init?(jsonDictionary: [String : AnyObject]) { if let optionalName = jsonDictionary["name"] as? String, let optionalWords = jsonDictionary["words"] as? [String], let optionalPictures = jsonDictionary["pictures"] as? [String] { name = optionalName words = optionalWords pictures = optionalPictures } else { name = "" words = [] pictures = [] return nil } } open func getRandomWords(_ wordCount: Int) -> [String] { var wordsCopy = [String](words) // Sort randomly the elements of the dictionary. wordsCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the desired number of words. return Array(wordsCopy[0..<wordCount]) } open func getRandomPicture() -> String? { var picturesCopy = [String](pictures) // Sort randomly the pictures. picturesCopy.sort(by: { (_,_) in return arc4random() < arc4random() }) // Return the first picture. return picturesCopy.first } class func getThemes() -> [Theme] { var themes = [Theme]() let path = Bundle.main.path(forResource: "Themes", ofType: "json")! if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe), let jsonArray = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [AnyObject] { themes = jsonArray.compactMap() { return Theme(jsonDictionary: $0 as! [String : AnyObject]) } } return themes } }
apache-2.0
6151994cf23b0751753adb8f76d7649a
31.053333
109
0.612313
4.518797
false
false
false
false
JasonCanCode/CRUDE-Futures
Pods/BrightFutures/BrightFutures/Future.swift
9
6532
// The MIT License (MIT) // // Copyright (c) 2014 Thomas Visser // // 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 Result /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(@autoclosure(escaping) task: () -> T) -> Future<T, NoError> { return future(Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T>(task: () -> T) -> Future<T, NoError> { return future(Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T>(context: ExecutionContext, task: () -> T) -> Future<T, NoError> { return future(context: context) { () -> Result<T, NoError> in return Result(value: task()) } } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(@autoclosure(escaping) task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on `Queue.global` and wraps the result of the task in a Future public func future<T, E>(task: () -> Result<T, E>) -> Future<T, E> { return future(context: Queue.global.context, task: task) } /// Executes the given task on the given context and wraps the result of the task in a Future public func future<T, E>(context c: ExecutionContext, task: () -> Result<T, E>) -> Future<T, E> { let future = Future<T, E>(); c { future.complete(task()) } return future } /// Can be used to wrap a completionHandler-based Cocoa API /// The completionHandler should have two parameters: a value and an error. public func future<T, E>(method: ((T?, E?) -> Void) -> Void) -> Future<T, BrightFuturesError<E>> { return Future(resolver: { completion -> Void in method { value, error in if let value = value { completion(.Success(value)) } else if let error = error { completion(.Failure(.External(error))) } else { completion(.Failure(.IllegalState)) } } }) } /// Can be used to wrap a typical completionHandler-based Cocoa API /// The completionHandler should have one parameter: the error public func future<E>(method: ((E?) -> Void) -> Void) -> Future<Void, E> { return Future(resolver: { completion -> Void in method { error in if let error = error { completion(.Failure(error)) } else { completion(.Success()) } } }) } /// Can be used to wrap a typical completionHandler-based Cocoa API /// The completionHandler should have one parameter: the value public func future<T>(method: (T -> Void) -> Void) -> Future<T, NoError> { return Future(resolver: { completion -> Void in method { value in completion(.Success(value)) } }) } /// A Future represents the outcome of an asynchronous operation /// The outcome will be represented as an instance of the `Result` enum and will be stored /// in the `result` property. As long as the operation is not yet completed, `result` will be nil. /// Interested parties can be informed of the completion by using one of the available callback /// registration methods (e.g. onComplete, onSuccess & onFailure) or by immediately composing/chaining /// subsequent actions (e.g. map, flatMap, recover, andThen, etc.). /// /// For more info, see the project README.md public final class Future<T, E: ErrorType>: Async<Result<T, E>> { public typealias CompletionCallback = (result: Result<T,E>) -> Void public typealias SuccessCallback = T -> Void public typealias FailureCallback = E -> Void public required init() { super.init() } public required init(result: Future.Value) { super.init(result: result) } public init(value: T, delay: NSTimeInterval) { super.init(result: Result<T, E>(value: value), delay: delay) } public required init<A: AsyncType where A.Value == Value>(other: A) { super.init(other: other) } public convenience init(value: T) { self.init(result: Result(value: value)) } public convenience init(error: E) { self.init(result: Result(error: error)) } public required init(@noescape resolver: (result: Value -> Void) -> Void) { super.init(resolver: resolver) } } /// Short-hand for `lhs.recover(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> T) -> Future<T, NoError> { return lhs.recover(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Short-hand for `lhs.recoverWith(rhs())` /// `rhs` is executed according to the default threading model (see README.md) public func ?? <T, E, E1>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> Future<T, E1>) -> Future<T, E1> { return lhs.recoverWith(context: DefaultThreadingModel(), task: { _ in return rhs() }) } /// Can be used as the value type of a `Future` or `Result` to indicate it can never be a success. /// This is guaranteed by the type system, because `NoValue` has no possible values and thus cannot be created. public enum NoValue { }
mit
757e15be54db72e0b5601772a9f41469
38.349398
112
0.660747
4.064717
false
false
false
false
airbnb/lottie-ios
Sources/Private/CoreAnimation/Layers/BaseCompositionLayer.swift
3
2527
// Created by Cal Stephens on 12/20/21. // Copyright © 2021 Airbnb Inc. All rights reserved. import QuartzCore // MARK: - BaseCompositionLayer /// The base type of `AnimationLayer` that can contain other `AnimationLayer`s class BaseCompositionLayer: BaseAnimationLayer { // MARK: Lifecycle init(layerModel: LayerModel) { baseLayerModel = layerModel super.init() setupSublayers() compositingFilter = layerModel.blendMode.filterName name = layerModel.name } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } /// Called by CoreAnimation to create a shadow copy of this layer /// More details: https://developer.apple.com/documentation/quartzcore/calayer/1410842-init override init(layer: Any) { guard let typedLayer = layer as? Self else { fatalError("\(Self.self).init(layer:) incorrectly called with \(type(of: layer))") } baseLayerModel = typedLayer.baseLayerModel super.init(layer: typedLayer) } // MARK: Internal /// Whether or not this layer render should render any visible content var renderLayerContents: Bool { true } /// Sets up the base `LayerModel` animations for this layer, /// and all child `AnimationLayer`s. /// - Can be overridden by subclasses, which much call `super`. override func setupAnimations(context: LayerAnimationContext) throws { var context = context if renderLayerContents { context = context.addingKeypathComponent(baseLayerModel.name) } try setupLayerAnimations(context: context) try setupChildAnimations(context: context) } func setupLayerAnimations(context: LayerAnimationContext) throws { let context = context.addingKeypathComponent(baseLayerModel.name) try addTransformAnimations(for: baseLayerModel.transform, context: context) if renderLayerContents { try addOpacityAnimation(for: baseLayerModel.transform, context: context) addVisibilityAnimation( inFrame: CGFloat(baseLayerModel.inFrame), outFrame: CGFloat(baseLayerModel.outFrame), context: context) } } func setupChildAnimations(context: LayerAnimationContext) throws { try super.setupAnimations(context: context) } // MARK: Private private let baseLayerModel: LayerModel private func setupSublayers() { if renderLayerContents, let masks = baseLayerModel.masks?.filter({ $0.mode != .none }), !masks.isEmpty { mask = MaskCompositionLayer(masks: masks) } } }
apache-2.0
3f537292bac7a5d3e5d7e34416ed373e
27.704545
93
0.715756
4.584392
false
false
false
false
victorchee/Live
Live/RTMP/Amf0.swift
1
12147
// // Amf0.swift // RTMP // // Created by VictorChee on 2016/12/21. // Copyright © 2016年 VictorChee. All rights reserved. // import Foundation class Amf0Data { enum Amf0DataType:UInt8 { case Amf0_Number = 0x00 case Amf0_Bool = 0x01 case Amf0_String = 0x02 /// Dictionary<String, Any?> case Amf0_Object = 0x03 case Amf0_MovieClip = 0x04 // Reserved, not suppported case Amf0_Null = 0x05 case Amf0_Undefined = 0x06 case Amf0_Reference = 0x07 /// Map case Amf0_ECMAArray = 0x08 case Amf0_ObjectEnd = 0x09 case Amf0_StrictArray = 0x0a case Amf0_Date = 0x0b case Amf0_LongString = 0x0c case Amf0_Unsupported = 0x0d case Amf0_RecordSet = 0x0e // Reserved, not supported case Amf0_XmlDocument = 0x0f case Amf0_TypedObject = 0x10 case Amf0_AVMplushObject = 0x11 } var dataInBytes = [UInt8]() var dataLength: Int { return dataInBytes.count } static func create(_ inputStream: ByteArrayInputStream) -> Amf0Data? { guard let amfTypeRawValue = inputStream.read() else { return nil } // 第一个Byte是AMF类型 guard let amf0Type = Amf0DataType(rawValue: amfTypeRawValue) else { return nil } var amf0Data: Amf0Data switch amf0Type { case .Amf0_Number: amf0Data = Amf0Number() case .Amf0_Bool: amf0Data = Amf0Boolean() case .Amf0_String: amf0Data = Amf0String() case .Amf0_Object: amf0Data = Amf0Object() case .Amf0_Null: amf0Data = Amf0Null() case .Amf0_Undefined: amf0Data = Amf0Undefined() case .Amf0_ECMAArray: amf0Data = Amf0ECMAArray() case .Amf0_StrictArray: amf0Data = Amf0StrictArray() case .Amf0_Date: amf0Data = Amf0Date() default: return nil } amf0Data.decode(inputStream) return amf0Data } func decode(_ inputStream: ByteArrayInputStream) { } } class Amf0Number: Amf0Data { var value: Double! override init() { } init(value: Any) { switch value { case let value as Double: self.value = value case let value as Int: self.value = Double(value) case let value as Int32: self.value = Double(value) case let value as UInt32: self.value = Double(value) case let value as Float64: self.value = Double(value) default: break } } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Number.rawValue) // 8B double value super.dataInBytes += value.bytes.reversed() return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skip self.value = NumberByteOperator.readDouble(inputStream) } static func decode(_ inputStream: ByteArrayInputStream) -> Double { // skip 1B amf type inputStream.read() return NumberByteOperator.readDouble(inputStream) } } class Amf0Null: Amf0Data { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // only 1B amf null type, no value super.dataInBytes.append(Amf0DataType.Amf0_Null.rawValue) return super.dataInBytes } set { super.dataInBytes = newValue } } } class Amf0Boolean: Amf0Data { private var value = false override init() { } init(value: Bool) { self.value = value } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Bool.rawValue) // Write value super.dataInBytes.append(value ? 0x01 : 0x00) return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skip self.value = (inputStream.read() == 0x01) } } class Amf0String: Amf0Data { private var value: String! override init() { } init(value: String) { self.value = value } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } let isLongString = UInt32(value.count) > UInt32(UInt16.max) // 1B type super.dataInBytes.append(isLongString ? Amf0DataType.Amf0_LongString.rawValue : Amf0DataType.Amf0_String.rawValue) let stringInBytes = [UInt8](value.utf8) // Value length if isLongString { // 4B, big endian super.dataInBytes += UInt32(stringInBytes.count).bigEndian.bytes } else { // 2B, big endian super.dataInBytes += UInt16(stringInBytes.count).bigEndian.bytes } // Value in bytes super.dataInBytes += stringInBytes return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped let stringLength = NumberByteOperator.readUInt16(inputStream) var stringInBytes = [UInt8](repeating: 0x00, count: Int(stringLength)) inputStream.read(&stringInBytes, maxLength: Int(stringLength)) self.value = String(bytes: stringInBytes, encoding: .utf8) } static func decode(_ inputStream: ByteArrayInputStream, isAmfObjectKey: Bool) -> String? { if !isAmfObjectKey { // Skip 1B amf type inputStream.read() } let stringLength = NumberByteOperator.readUInt16(inputStream) // 2B的长度数据 var stringInBytes = [UInt8](repeating: 0x00, count: Int(stringLength)) inputStream.read(&stringInBytes, maxLength: Int(stringLength)) return String(bytes: stringInBytes, encoding: .utf8) } } class Amf0Object: Amf0Data { /// 结尾 let endMark: [UInt8] = [0x00, 0x00, 0x09] var properties = [String: Amf0Data]() func setProperties(key: String, value: Any) { switch value { case let value as Double: properties[key] = Amf0Number(value: value) case let value as Int: properties[key] = Amf0Number(value: value) case let value as String: properties[key] = Amf0String(value: value) case let value as Bool: properties[key] = Amf0Boolean(value: value) default: properties[key] = Amf0Number(value: value) break } } override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_Object.rawValue) for (key, value) in properties { let keyInBytes = [UInt8](key.utf8) // Key super.dataInBytes += UInt16(keyInBytes.count).bigEndian.bytes super.dataInBytes += keyInBytes // Value super.dataInBytes += value.dataInBytes } super.dataInBytes += endMark return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped var buffer = [UInt8](repeating: 0x00, count:3) while true { // try read if catch the object end inputStream.tryRead(&buffer, maxLength: 3) if buffer[0] == endMark[0] && buffer[1] == endMark[1] && buffer[2] == endMark[2] { inputStream.read(&buffer, maxLength: 3) break } guard let key = Amf0String.decode(inputStream, isAmfObjectKey: true) else { return } guard let value = Amf0Data.create(inputStream) else { return } properties[key] = value } } } class Amf0StrictArray: Amf0Data { private var arrayItems = [Amf0Data]() override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_StrictArray.rawValue) // 4B count super.dataInBytes += UInt32(arrayItems.count).bigEndian.bytes // Items for item in arrayItems { super.dataInBytes += item.dataInBytes } return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped let arrayCount = NumberByteOperator.readUInt32(inputStream) for _ in 1...arrayCount { guard let item = Amf0Data.create(inputStream) else { return } arrayItems.append(item) } } } class Amf0ECMAArray: Amf0Object { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_ECMAArray.rawValue) super.dataInBytes += UInt32(properties.count).bigEndian.bytes for (key, value) in properties { super.dataInBytes += [UInt8](key.utf8) super.dataInBytes += value.dataInBytes } super.dataInBytes += endMark return super.dataInBytes } set { super.dataInBytes = newValue } } } class Amf0Undefined: Amf0Data { override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // Only 1B amf type super.dataInBytes.append(Amf0DataType.Amf0_Undefined.rawValue) return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped // Amf type has been read, nothing still need to be decode } } class Amf0Date: Amf0Data { private var value: Date! override var dataInBytes: [UInt8] { get { guard super.dataInBytes.isEmpty else { return super.dataInBytes } // 1B type super.dataInBytes.append(Amf0DataType.Amf0_ECMAArray.rawValue) super.dataInBytes += (value.timeIntervalSince1970 * 1000).bytes.reversed() // 2B end super.dataInBytes += [0x00, 0x00] return super.dataInBytes } set { super.dataInBytes = newValue } } override func decode(_ inputStream: ByteArrayInputStream) { // 1B amf type has skipped value = Date(timeIntervalSince1970: NumberByteOperator.readDouble(inputStream) / 1000) } }
mit
c4b7d555d4e9e0326220296def8d5817
30.231959
126
0.553639
4.564218
false
false
false
false
catalanjrj/BarMate
BarMate/BarMate/LoginViewController.swift
1
2661
// // LoginViewController.swift // BarMate // // Created by Jorge Catalan on 6/10/16. // Copyright © 2016 Jorge Catalan. All rights reserved. // import UIKit import Firebase import FirebaseAuth class LoginViewController: UIViewController { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var loginButton: UIButton! override func viewDidLoad() { super.viewDidLoad() // make buttons round self.loginButton.layer.cornerRadius = 8 self.hideKeyboardWhenTappedAround() FIRAuth.auth()?.addAuthStateDidChangeListener({ (auth, user) in if user != nil { self.performSegueWithIdentifier("OrderSegue", sender: nil) } }) } @IBAction func unwindToLoginViewController(segue: UIStoryboardSegue) { try! FIRAuth.auth()!.signOut() } @IBAction func loginButton(sender: AnyObject) { FIRAuth.auth()?.signInWithEmail(emailTextField.text!, password: passwordTextField.text!, completion: {user, error in if error != nil{ let alertController = UIAlertController(title: "Error", message:(error!.localizedDescription) , preferredStyle: .Alert) let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in // ... } alertController.addAction(cancelAction) let OKAction = UIAlertAction(title: "Try Again", style: .Default) { (action) in // ... } alertController.addAction(OKAction) self.presentViewController(alertController, animated: true) { } print(error!.localizedDescription) }else{ print("Success") self.performSegueWithIdentifier("OrderSegue", sender: sender) } }) } @IBOutlet weak var signUpButton: UIButton! } extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) view.addGestureRecognizer(tap) } func dismissKeyboard() { view.endEditing(true) } }
cc0-1.0
fe96369f29fe5f8ccca92bc6a818ab49
28.230769
139
0.542481
6.114943
false
false
false
false
ozpopolam/DoctorBeaver
DoctorBeaver/PetsRepository.swift
1
8647
// // Repository.swift // DoctorBeaver // // Created by Anastasia Stepanova-Kolupakhina on 11.05.16. // Copyright © 2016 Anastasia Stepanova-Kolupakhina. All rights reserved. // import Foundation import CoreData protocol PetsRepositorySettable: class { // can get and set PetsRepository var petsRepository: PetsRepository! { get set } } // Obverver-subject protocol protocol PetsRepositoryStateSubject: class { var observers: [WeakPetsRepositoryStateObserver] { get set } func addObserver(observer: PetsRepositoryStateObserver) func removeObserver(observer: PetsRepositoryStateObserver) func notifyObservers() } // weak-wrapper for PetsRepositoryStateObserver class WeakPetsRepositoryStateObserver { weak var observer: PetsRepositoryStateObserver? init (_ observer: PetsRepositoryStateObserver) { self.observer = observer } } // Obverver protocol protocol PetsRepositoryStateObserver: class { func petsRepositoryDidChange(repository: PetsRepositoryStateSubject) } class PetsRepository: PetsRepositoryStateSubject { let modelName: String private lazy var appDocDirectory: NSURL = { let fileManager = NSFileManager.defaultManager() let urls = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count - 1] }() private lazy var context: NSManagedObjectContext = { var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator return managedObjectContext }() private lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = { let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.appDocDirectory.URLByAppendingPathComponent(self.modelName) do { let options = [NSMigratePersistentStoresAutomaticallyOption: true] try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: options) } catch { print("Error adding persistentStore") } return coordinator }() private lazy var managedObjectModel: NSManagedObjectModel = { let modelUrl = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelUrl)! }() init(withModelName modelName: String) { self.modelName = modelName } func rollback() { context.rollback() } func saveOrRollback() -> Bool { if context.hasChanges { do { try context.save() notifyObservers() // notify all observers that some changes have happened in repository return true } catch { print("Error! Context cannot be saved!") context.rollback() return false } } else { return true } } // MARK: Insertion func insertTaskTypeItemBasicValues() -> TaskTypeItemBasicValues? { if let taskTypeItemBasicValues = TaskTypeItemBasicValues(insertIntoManagedObjectContext: context) { return taskTypeItemBasicValues } else { return nil } } func insertTaskTypeItem() -> TaskTypeItem? { if let taskTypeItem = TaskTypeItem(insertIntoManagedObjectContext: context) { return taskTypeItem } else { return nil } } func insertRealization() -> Realization? { if let realization = Realization(insertIntoManagedObjectContext: context) { return realization } else { return nil } } func insertTask() -> Task? { if let task = Task(insertIntoManagedObjectContext: context) { return task } else { return nil } } func insertPetBasicValues() -> PetBasicValues? { if let petBasicValues = PetBasicValues(insertIntoManagedObjectContext: context) { return petBasicValues } else { return nil } } func insertPet() -> Pet? { if let pet = Pet(insertIntoManagedObjectContext: context), let basicValues = fetchPetBasicValues() { pet.id = NSDate().timeIntervalSince1970 pet.basicValues = basicValues return pet } else { return nil } } func insertProxyPet() -> Pet? { // is used to store copy of settings of already existing pet if let pet = Pet(insertIntoManagedObjectContext: context) { pet.id = -1 return pet } return nil } // MARK: Counting func countAll(entityName: String) -> Int { let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.resultType = .CountResultType do { if let results = try context.executeFetchRequest(fetchRequest) as? [NSNumber] { if let count = results.first?.integerValue { return count } } } catch { print("Counting error!") } return 0 } // MARK: Fetching func fetchAllObjects(forEntityName entityName: String) -> [NSManagedObject] { let fetchRequest = NSFetchRequest(entityName: entityName) do { if let fetchResults = try context.executeFetchRequest(fetchRequest) as? [NSManagedObject] { return fetchResults } } catch { print("Fetching error!") } return [] } func fetchAllPets() -> [Pet] { let managedObjects = fetchAllObjects(forEntityName: Pet.entityName) var pets = [Pet]() for managedObject in managedObjects { if let pet = managedObject as? Pet { pets.append(pet) } } return pets } func fetchAllSelectedPets() -> [Pet] { let fetchRequest = NSFetchRequest(entityName: Pet.entityName) let predicate = NSPredicate(format: "%K == YES", Pet.Keys.selected.rawValue) fetchRequest.predicate = predicate do { if let results = try context.executeFetchRequest(fetchRequest) as? [Pet] { return results } } catch { print("Fetching error!") } return [] } func fetchPetBasicValues() -> PetBasicValues? { let fetchRequest = NSFetchRequest(entityName: PetBasicValues.entityName) fetchRequest.fetchLimit = 1 do { if let results = try context.executeFetchRequest(fetchRequest) as? [PetBasicValues] { return results.first } } catch { print("Fetching error!") } return nil } func fetchTaskTypeItem(withId id: Int) -> TaskTypeItem? { let fetchRequest = NSFetchRequest(entityName: TaskTypeItem.entityName) fetchRequest.fetchLimit = 1 let predicate = NSPredicate(format: "%K == %i", TaskTypeItem.Keys.id.rawValue, id) fetchRequest.predicate = predicate do { if let results = try context.executeFetchRequest(fetchRequest) as? [TaskTypeItem] { return results.first } } catch { print("Fetching error!") } return nil } func fetchAllTaskTypeItems() -> [TaskTypeItem] { let managedObjects = fetchAllObjects(forEntityName: TaskTypeItem.entityName) var taskTypeItems = [TaskTypeItem]() for managedObject in managedObjects { if let taskTypeItem = managedObject as? TaskTypeItem { taskTypeItems.append(taskTypeItem) } } return taskTypeItems } // MARK: Deletion func deleteObject(object: NSManagedObject) { context.deleteObject(object) } func deleteAllObjects(forEntityName entityName: String) { let fetchRequest = NSFetchRequest(entityName: entityName) do { if let fetchResults = try context.executeFetchRequest(fetchRequest) as? [NSManagedObject] { for object in fetchResults { context.deleteObject(object) } context.saveOrRollback() } } catch { print("Some error during cleaning!") } } // MARK: PetsRepositoryStateSubject var observers = [WeakPetsRepositoryStateObserver]() // observers for PetsRepository's state change func addObserver(observer: PetsRepositoryStateObserver) { observers.append(WeakPetsRepositoryStateObserver(observer)) } func removeObserver(observerToRemove: PetsRepositoryStateObserver) { for ind in 0..<observers.count { if let observer = observers[ind].observer { if observerToRemove === observer { observers.removeAtIndex(ind) break } } } } func notifyObservers() { for weakObserver in observers { weakObserver.observer?.petsRepositoryDidChange(self) } } } extension NSManagedObjectContext { public func saveOrRollback() { if hasChanges { do { try save() } catch { print("Context cannot be saved - roll back!") rollback() } } } }
mit
cd834b9af1af1457b42a2dced45f554b
26.803859
115
0.680777
5.119005
false
false
false
false
cdmx/MiniMancera
miniMancera/Model/Option/WhistlesVsZombies/Ground/MOptionWhistlesVsZombiesGround.swift
1
611
import Foundation class MOptionWhistlesVsZombiesGround { private let lanes:[MOptionWhistlesVsZombiesGroundLane] private let count:UInt32 init(area:MOptionWhistlesVsZombiesArea) { lanes = MOptionWhistlesVsZombiesGround.factoryLanes(area:area) count = UInt32(lanes.count) } //MARK: public func randomLane() -> MOptionWhistlesVsZombiesGroundLane { let random:UInt32 = arc4random_uniform(count) let randomInt:Int = Int(random) let lane:MOptionWhistlesVsZombiesGroundLane = lanes[randomInt] return lane } }
mit
c84abacd7bf334bd3e3151cb9aeddb2c
24.458333
70
0.682488
4.736434
false
false
false
false
MBKwon/SwiftList
SwiftList/myList.swift
1
3026
// // myList.swift // SwiftList // // Created by Moonbeom KWON on 2017. 6. 15.. // Copyright © 2017년 mbkyle. All rights reserved. // import Foundation indirect enum myList <A> { case Nil case Cons(A, myList<A>) } extension myList { static func apply<T: NumericType>(values: T...) -> myList<T> { if values.count == 0 { return .Nil } else { if let first = values.first { return .Cons(first, apply(values: Array<T>(values.dropFirst())) ) } return .Nil } } static func apply<T: NumericType>(values: [T]) -> myList<T> { if values.count == 0 { return .Nil } else { if let first = values.first { return .Cons(first, apply(values: Array<T>(values.dropFirst())) ) } return .Nil } } } extension myList { func sum<T: NumericType>(ints: myList<T>) -> T { switch ints { case .Nil: return T(0) case let .Cons(x, xs): return x + sum(ints: xs) } } func product<T: NumericType>(ds: myList<T>) -> T { switch ds { case .Nil: return T(1.0) case let .Cons(x, xs): return x * product(ds: xs) } } } extension myList { func getHead<T>(_ list: myList<T>) -> myList<T> { switch list { case .Nil: return .Nil case let .Cons(x, xs): return .Cons(x, xs) } } func getTail<T>(_ list: myList<T>) -> myList<T> { switch list { case .Nil: return .Nil case let .Cons(_, xs): return xs } } } extension myList { func drop<T>(count: Int, list: myList<T>) -> myList<T> { switch count { case 0: return list default: return drop(count: count-1, list: getTail(list)) } } func dropWhile<T>(list: myList<T>, f: (T) -> Bool) -> myList<T> { switch list { case let .Cons(x, xs): if f(x) { return dropWhile(list: xs, f: f) } fallthrough default: return list } } } extension myList { func foldLeft<T>(acc: T, list: myList<T>, f: (T, T) -> T) -> T { switch list { case .Nil: return acc case let .Cons(x, xs): return foldLeft(acc: f(acc, x), list: xs, f: f) } } func foldRight<T>(acc: T, list: myList<T>, f: (T, T) -> T) -> T { switch list { case .Nil: return acc case let .Cons(x, xs): return f(x, foldRight(acc: acc, list: xs, f: f)) } } }
mit
6eb67b8b127c5fba5fa5e34937dc9e55
19.153333
81
0.421436
3.967192
false
false
false
false
benlangmuir/swift
test/decl/circularity.swift
4
3169
// RUN: %target-typecheck-verify-swift // N.B. Validating the pattern binding initializer for `pickMe` used to cause // recursive validation of the VarDecl. Check that we don't regress now that // this isn't the case. public struct Cyclic { static func pickMe(please: Bool) -> Int { return 42 } public static let pickMe = Cyclic.pickMe(please: true) } struct Node {} struct Parameterized<Value, Format> { func please<NewValue>(_ transform: @escaping (_ otherValue: NewValue) -> Value) -> Parameterized<NewValue, Format> { fatalError() } } extension Parameterized where Value == [Node], Format == String { static var pickMe: Parameterized { fatalError() } } extension Parameterized where Value == Node, Format == String { static let pickMe = Parameterized<[Node], String>.pickMe.please { [$0] } } enum Loop: Circle { struct DeLoop { } } protocol Circle { typealias DeLoop = Loop.DeLoop } class Base { static func foo(_ x: Int) {} } class Sub: Base { var foo = { () -> Int in let x = 42 // FIXME: Bogus diagnostic return foo(1) // expected-error {{cannot convert value of type '()' to closure result type 'Int'}} }() } extension Float { static let pickMe: Float = 1 } extension SIMD3 { init(_ scalar: Scalar) { self.init(repeating: scalar) } } extension SIMD3 where SIMD3.Scalar == Float { static let pickMe = SIMD3(.pickMe) } // Test case with circular overrides protocol P { associatedtype A // expected-note@-1 {{protocol requires nested type 'A'; do you want to add it?}} func run(a: A) } class C1 { func run(a: Int) {} } class C2: C1, P { // expected-note@-1 {{through reference here}} override func run(a: A) {} // expected-error@-1 {{circular reference}} // expected-note@-2 {{while resolving type 'A'}} // expected-note@-3 2{{through reference here}} } // Another crash to the above open class G1<A> { open func run(a: A) {} } class C3: G1<A>, P { // expected-error@-1 {{type 'C3' does not conform to protocol 'P'}} // expected-error@-2 {{cannot find type 'A' in scope}} // expected-note@-3 {{through reference here}} override func run(a: A) {} // expected-error@-1 {{method does not override any method from its superclass}} // expected-error@-2 {{circular reference}} // expected-note@-3 2 {{through reference here}} // expected-note@-4 {{while resolving type 'A'}} } // Another case that triggers circular override checking. protocol P1 { associatedtype X = Int init(x: X) } class C4 { required init(x: Int) {} } class D4 : C4, P1 { // expected-note 3 {{through reference here}} required init(x: X) { // expected-error {{circular reference}} // expected-note@-1 {{while resolving type 'X'}} // expected-note@-2 2{{through reference here}} super.init(x: x) } } // https://github.com/apple/swift/issues/54662 // N.B. This used to compile in 5.1. protocol P_54662 { } class C_54662 { // expected-note {{through reference here}} typealias Nest = P_54662 // expected-error {{circular reference}} expected-note {{through reference here}} } extension C_54662: C_54662.Nest { }
apache-2.0
4f2a4fea871038855af17ccaa149a6db
25.630252
118
0.653203
3.572717
false
false
false
false
insanoid/SwiftyJSONAccelerator
Core/Generator/Model-File-Components/PropertyComponent.swift
1
1368
// // PropertyComponent.swift // SwiftyJSONAccelerator // // Created by Karthik on 09/07/2016. // Copyright © 2016 Karthikeya Udupa K M. All rights reserved. // import Foundation /// A strucutre to store various attributes related to a single property. struct PropertyComponent { /// Name of the property. var name: String /// Type of the property. var type: String /// Constant name that is to be used to encode, decode and read from JSON. var constantName: String /// Original key in the JSON file. var key: String /// Nature of the property, if it is a value type, an array of a value type or an object. var propertyType: PropertyType /// Initialise a property component. /// /// - Parameters: /// - name: Name of the property. /// - type: Type of the property. /// - constantName: Constant name that is to be used to encode, decode and read from JSON. /// - key: Original key in the JSON file. /// - propertyType: Nature of the property, if it is a value type, an array of a value type or an object. init(_ name: String, _ type: String, _ constantName: String, _ key: String, _ propertyType: PropertyType) { self.name = name self.type = type self.constantName = constantName self.key = key self.propertyType = propertyType } }
mit
55e3a770759e623d9bb9949f783659ae
34.973684
111
0.651792
4.155015
false
false
false
false
Kametrixom/Swift-SyncAsync
SyncAsync.playground/Pages/toAsync.xcplaygroundpage/Contents.swift
1
3685
//: [Previous](@previous) import XCPlayground //: The `toAsync` function is the reverse of the `toSync` function. It takes a synchronous function and returns its asynchronous variant //: Let's create a synchronous function func add(a: Int, b: Int) -> Int { return a + b } //: To make it asynchronous, just call `toAsync` on it. The resulting function takes the arguments of the synchronous function plus a completion handler toAsync(add)(1, 2) { result in print("Added: \(result)") } waitABit() // Waits a bit so that the outputs don't get messed up (because it's asynchronous), see Utils.swift //: Like the `toSync` function, the `toAsync` function is overloaded for it to be able to take up to four inputs and an unlimited amount of outputs. To demonstrate this, we'll create a few synchronous functions // Our own error type enum Error: ErrorType { case LessThanZero case DivisionByZero } func sayHi(to: String, isBuddy: Bool) -> (speech: String, friendly: Bool) { switch (to, isBuddy) { case ("Bob", _): return ("...", false) case (_, true): return ("Hey man", true) case (let s, _): return ("Hello, \(s)", true) } } func product(from: Int, through: Int, steps: Int) -> Int { return from.stride(through: through, by: steps).reduce(1, combine: *) } func factorial(n: Int) throws -> Int { guard n >= 0 else { throw Error.LessThanZero } return n < 2 ? 1 : try factorial(n - 1) * n } func divide12345By(val: Double) throws -> (Double, Double, Double, Double, Double) { guard val != 0 else { throw Error.DivisionByZero } return (1 / val, 2 / val, 3 / val, 4 / val, 5 / val) } //: Simply call `toAsync` to convert these to asynchronoous functions let asyncHi = toAsync(sayHi) let asyncProd = toAsync(product) let asyncFactorial = toAsync(factorial) let asyncDivision = toAsync(divide12345By) //: As you can see from the types, throwing functions automatically get converted to functions that take a completion handler, executed when succeeded, and an error handler, executed when an error occured. As with `toSync`, parameter names cannot be preserved. asyncHi("Paul", true) { debugPrint($0) } waitABit() asyncProd(4, 10, 2) { debugPrint($0) } waitABit() asyncFactorial(-3, completionHandler: { debugPrint($0) }, errorHandler: { debugPrint($0) }) waitABit() asyncDivision(19, completionHandler: { debugPrint($0) }, errorHandler: { debugPrint($0) }) waitABit() //: And yes if you really want to, you can chain `toAsync` and `toSync` even though this is utter nonsense toSync(toAsync(sayHi))("Bob", false) /*: I hope this small library helps you, it was really fun to write it anyways. The source file was partly generated automatically, errors are unlikely, also due to the very strict function signatures, however if you happen to find an error, please let me know (@Kametrixom on Twitter, Reddit, StackOverflow, Github, ...) and I'll see what I can do. Suggestions and critique are very welcome as well. If you don't like that the functions are so minimized, I'm sorry, but otherwise it would get very big. Also sorry for any typos, english isn't my native language. If you're able to use my library for anything useful, I wouldn't mind a mention on Twitter ;) Inspiration came from StackOverflow where people often want to make asynchronous tasks synchronous (usually that's a bad thing). They get replies such as "These functions are asynchronous for a reason, don't fight it", etc. but sometimes it's actually pretty useful to have them synchronous, as I mentioned in the beginning. Recently I've been getting into Haskell, where higher-order functions are the norm, which made me write this library in this higher-order function style (I like it :D). */
mit
92d0001b16dc496f3d1ea284f92860c0
50.901408
653
0.733786
3.878947
false
false
false
false
jisudong/study
Study/Study/Study_RxSwift/Platform/DataStructures/Queue.swift
1
4061
// // Queue.swift // Study // // Created by syswin on 2017/7/31. // Copyright © 2017年 syswin. All rights reserved. // struct Queue<T>: Sequence { typealias Generator = AnyIterator<T> private let _resizeFactor = 2 private var _storage: ContiguousArray<T?> private var _count = 0 private var _pushNextIndex = 0 private let _initialCapacity: Int init(capacity: Int) { _initialCapacity = capacity _storage = ContiguousArray<T?>(repeating: nil, count: capacity) } private var dequeueIndex: Int { let index = _pushNextIndex - count return index < 0 ? index + _storage.count : index } var isEmpty: Bool { return count == 0 } var count: Int { return _count } func peek() -> T { precondition(count > 0) return _storage[dequeueIndex]! } mutating private func resizeTo(_ size: Int) { var newStorage = ContiguousArray<T?>(repeating: nil, count: size) let count = _count let dequeueIndex = self.dequeueIndex let spaceToEndOfQueue = _storage.count - dequeueIndex let countElementsInFirstBatch = Swift.min(count, spaceToEndOfQueue) let numberOfElementsInSecondBatch = count - countElementsInFirstBatch newStorage[0 ..< countElementsInFirstBatch] = _storage[dequeueIndex ..< (dequeueIndex + countElementsInFirstBatch)] newStorage[countElementsInFirstBatch ..< (countElementsInFirstBatch + numberOfElementsInSecondBatch)] = _storage[0 ..< numberOfElementsInSecondBatch] _count = count _pushNextIndex = count _storage = newStorage // print("resizeTo --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } mutating func enqueue(_ element: T) { if count == _storage.count { resizeTo(Swift.max(_storage.count, 1) * _resizeFactor) } _storage[_pushNextIndex] = element _pushNextIndex += 1 _count += 1 if _pushNextIndex >= _storage.count { _pushNextIndex -= _storage.count } // print("enqueue --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } private mutating func dequeueElementOnly() -> T { precondition(count > 0) let index = dequeueIndex defer { _storage[index] = nil _count -= 1 // print("dequeueElementOnly --- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } return _storage[index]! } mutating func dequeue() -> T? { if self.count == 0 { return nil } defer { let downsizeLimit = _storage.count / (_resizeFactor * _resizeFactor) if _count < downsizeLimit && downsizeLimit >= _initialCapacity { resizeTo(_storage.count / _resizeFactor) } // print("dequeue ---- _count = \(_count), _pushNextIndex = \(_pushNextIndex), dequeueIndex = \(self.dequeueIndex), _storage.count = \(_storage.count)", _storage) } return dequeueElementOnly() } func makeIterator() -> AnyIterator<T> { var i = dequeueIndex var count = _count return AnyIterator { if count == 0 { return nil } defer { count -= 1 i += 1 } if i >= self._storage.count { i -= self._storage.count } return self._storage[i] } } }
mit
ae373a82ea3584356c42bd048cc273e9
28.405797
183
0.537703
5.104403
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/ColdStartPasslockController.swift
1
3591
// // ColdStartPasslockController.swift // Telegram // // Created by Mikhail Filimonov on 03.11.2020. // Copyright © 2020 Telegram. All rights reserved. // import Cocoa import TGUIKit import SwiftSignalKit class ColdStartPasslockController: ModalViewController { private let valueDisposable = MetaDisposable() private let logoutDisposable = MetaDisposable() private let logoutImpl:() -> Signal<Never, NoError> private let checkNextValue: (String)->Bool init(checkNextValue:@escaping(String)->Bool, logoutImpl:@escaping()->Signal<Never, NoError>) { self.checkNextValue = checkNextValue self.logoutImpl = logoutImpl super.init(frame: NSMakeRect(0, 0, 350, 350)) self.bar = .init(height: 0) } override var isVisualEffectBackground: Bool { return false } override var isFullScreen: Bool { return true } override var background: NSColor { return self.containerBackground } private var genericView:PasscodeLockView { return self.view as! PasscodeLockView } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } override func viewDidLoad() { super.viewDidLoad() genericView.logoutImpl = { [weak self] in guard let window = self?.window else { return } confirm(for: window, information: strings().accountConfirmLogoutText, successHandler: { [weak self] _ in guard let `self` = self else { return } _ = showModalProgress(signal: self.logoutImpl(), for: window).start(completed: { [weak self] in delay(0.2, closure: { [weak self] in self?.close() }) }) }) } var locked = false valueDisposable.set((genericView.value.get() |> deliverOnMainQueue).start(next: { [weak self] value in guard let `self` = self, !locked else { return } if !self.checkNextValue(value) { self.genericView.input.shake() } else { locked = true } })) genericView.update(hasTouchId: false) readyOnce() } override var closable: Bool { return false } override func escapeKeyAction() -> KeyHandlerResult { return .invoked } override func firstResponder() -> NSResponder? { if !(window?.firstResponder is NSText) { return genericView.input } let editor = self.window?.fieldEditor(true, for: genericView.input) if window?.firstResponder != editor { return genericView.input } return editor } override var containerBackground: NSColor { return theme.colors.background.withAlphaComponent(1.0) } override var handleEvents: Bool { return true } override var cornerRadius: CGFloat { return 0 } override var handleAllEvents: Bool { return true } override var responderPriority: HandlerPriority { return .supreme } deinit { logoutDisposable.dispose() valueDisposable.dispose() self.window?.removeAllHandlers(for: self) } override func viewClass() -> AnyClass { return PasscodeLockView.self } }
gpl-2.0
3c270a6656f7075547a65a736f3825a8
25.014493
116
0.572145
5.158046
false
false
false
false
popodidi/HTagView
HTagView/Classes/HTag.swift
1
8793
// // HTag.swift // Pods // // Created by Chang, Hao on 12/12/2016. // // import UIKit protocol HTagDelegate: class { func tagClicked(_ sender: HTag) func tagCancelled(_ sender: HTag) } public class HTag: UIView { weak var delegate: HTagDelegate? // MARK: - HTag Configuration /** Type of tag */ var tagType: HTagType = .cancel { didSet { updateAll() } } /** Title of tag */ var tagTitle: String = "" { didSet { updateAll() } } /** Main background color of tags */ var tagMainBackColor : UIColor = UIColor.white { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Main text color of tags */ var tagMainTextColor : UIColor = UIColor.black { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Secondary background color of tags */ var tagSecondBackColor : UIColor = UIColor.gray { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** Secondary text color of tags */ var tagSecondTextColor : UIColor = UIColor.white { didSet { updateTitlesColorsAndFontsDueToSelection() } } /** The border width to height ratio of HTags. */ var tagBorderWidth :CGFloat = 1 { didSet { updateBorder() } } /** The border color to height ratio of HTags. */ var tagBorderColor :CGColor? = UIColor.darkGray.cgColor { didSet { updateBorder() } } /** The corner radius to height ratio of HTags. */ var tagCornerRadiusToHeightRatio: CGFloat = 0.2 { didSet { updateBorder() } } /** The content EdgeInsets of HTags, which would automatically adjust the position in `.cancel` type. On the other word, usages are the same in both types. */ var tagContentEdgeInsets: UIEdgeInsets = UIEdgeInsets() { didSet { updateAll()} } /** The distance between cancel icon and text */ var tagCancelIconRightMargin: CGFloat = 4 { didSet { updateAll()} } /** The Font of HTags. */ var tagFont: UIFont = UIFont.systemFont(ofSize: 17) { didSet { updateAll() } } /** Specified Width of Tag */ var tagSpecifiedWidth: CGFloat? = nil { didSet { layoutSubviews() } } /** Maximum Width of Tag */ var tagMaximumWidth: CGFloat? = nil { didSet { layoutSubviews() } } /** Elevation of Tag */ var tagElevation: CGFloat = 0 { didSet { layoutSubviews() } } // MARK: - status private(set) var isSelected: Bool = false // MARK: - Subviews var button: UIButton = UIButton(type: .system) var cancelButton: UIButton = UIButton(type: .system) // MARK: - Init override init(frame: CGRect){ super.init(frame: frame) configure() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) configure() } deinit { button.removeObserver(self, forKeyPath: "highlighted") } // MARK: - Configure func configure(){ clipsToBounds = true self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapped))) setupButton() setupCancelButton() updateAll() } // MARK: - button func setupButton() { addSubview(button) button.addTarget(self, action: #selector(tapped), for: .touchUpInside) button.addObserver(self, forKeyPath: "highlighted", options: .new, context: nil) } func setHighlight(_ highlighted: Bool) { let color = isSelected ? tagMainBackColor : tagSecondBackColor backgroundColor = highlighted ? color.darker() : color layer.shadowRadius = highlighted ? 0 : tagElevation * 0.1 } func setSelected(_ selected: Bool) { isSelected = selected updateTitlesColorsAndFontsDueToSelection() } public override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } switch keyPath { case "highlighted": guard let highlighted = change?[.newKey] as? Bool else { break } setHighlight(highlighted) default: break } } // MARK: - cancel button func setupCancelButton() { cancelButton.setImage(UIImage(named: "close_small", in: Bundle(for: self.classForCoder), compatibleWith: nil)?.withRenderingMode(.alwaysTemplate), for: UIControl.State()) cancelButton.addTarget(self, action: #selector(cancelled), for: .touchUpInside) addSubview(cancelButton) cancelButton.isHidden = tagType == .select } // MARK: - Layout public override func layoutSubviews() { button.sizeToFit() // set origin if tagType == .select { button.frame.origin = CGPoint(x: tagContentEdgeInsets.left, y: tagContentEdgeInsets.top) } else { let cancelButtonSide: CGFloat = 16 cancelButton.frame.size = CGSize(width: cancelButtonSide, height: cancelButtonSide) cancelButton.frame.origin = CGPoint(x: tagContentEdgeInsets.left , y: tagContentEdgeInsets.top + button.frame.height/2 - cancelButtonSide/2) button.frame.origin = CGPoint(x: tagContentEdgeInsets.left + cancelButtonSide + tagCancelIconRightMargin , y: tagContentEdgeInsets.top) } // set shadow if tagElevation != 0 { clipsToBounds = false layer.shadowColor = UIColor.black.cgColor layer.shadowOpacity = 0.5 layer.shadowOffset = .zero layer.shadowRadius = tagElevation * 0.1 } // set size let tagHeight = button.frame.maxY + tagContentEdgeInsets.bottom var tagWidth: CGFloat = 0 if let tagSpecifiedWidth = tagSpecifiedWidth { tagWidth = tagSpecifiedWidth } else { tagWidth = button.frame.maxX + tagContentEdgeInsets.right } var shouldSetButtonWidth: Bool = false if let maxWidth = tagMaximumWidth, maxWidth < tagWidth { tagWidth = maxWidth shouldSetButtonWidth = true } else if tagSpecifiedWidth != nil { shouldSetButtonWidth = true } frame.size = CGSize(width: tagWidth, height: tagHeight) if shouldSetButtonWidth { button.frame.size.width = tagWidth - cancelButton.frame.width - tagCancelIconRightMargin - tagContentEdgeInsets.left - tagContentEdgeInsets.right } } func updateAll() { cancelButton.isHidden = tagType == .select updateTitlesColorsAndFontsDueToSelection() updateBorder() button.sizeToFit() layoutIfNeeded() invalidateIntrinsicContentSize() } func updateTitlesColorsAndFontsDueToSelection() { backgroundColor = isSelected ? tagMainBackColor : tagSecondBackColor let textColor = isSelected ? tagMainTextColor : tagSecondTextColor var attributes: [NSAttributedString.Key: Any] = [:] attributes[.font] = tagFont attributes[.foregroundColor] = textColor button.setAttributedTitle(NSAttributedString(string: tagTitle, attributes: attributes), for: .normal) if tagType == .cancel { cancelButton.tintColor = textColor } } func updateBorder() { layer.borderWidth = tagBorderWidth layer.borderColor = tagBorderColor layer.cornerRadius = bounds.height * tagCornerRadiusToHeightRatio } // MARK: - User interaction @objc func tapped(){ delegate?.tagClicked(self) } @objc func cancelled() { delegate?.tagCancelled(self) } } extension UIColor { func lighter(by percentage: CGFloat = 30.0) -> UIColor? { return self.adjust(by: abs(percentage) ) } func darker(by percentage: CGFloat = 30.0) -> UIColor? { return self.adjust(by: -1 * abs(percentage) ) } func adjust(by percentage: CGFloat = 30.0) -> UIColor? { var r: CGFloat = 0 var g: CGFloat = 0 var b: CGFloat = 0 var a: CGFloat = 0 if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: a) }else{ return nil } } }
mit
7b3314b8003c44be2f69732fec26eeb0
31.932584
178
0.599454
5.047646
false
false
false
false
lfaoro/Cast
Cast/PreferenceManager.swift
1
2386
// // Created by Leonardo on 10/16/15. // Copyright © 2015 Leonardo Faoro. All rights reserved. // import Cocoa // Keys in a variable to avoid mistakes private let gistServiceKey = "gistService" private let imageServiceKey = "imageService" private let shortenServiceKey = "shortenService" private let recentActionsKey = "recentActions" private let secretGistsAvailableKey = "secretGistsAvailable" private let gistIsPublicKey = "gistIsPublic" class PreferenceManager { private let userDefaults = NSUserDefaults.standardUserDefaults() init() { registerDefaults() } func registerDefaults() { let standardDefaults = [ gistServiceKey: "GitHub", imageServiceKey: "imgur", shortenServiceKey: "Is.Gd", recentActionsKey: ["Cast": "http://cast.lfaoro.com"], secretGistsAvailableKey: true, gistIsPublicKey: false, ] userDefaults.registerDefaults(standardDefaults) } // MARK: - Defaults properties abstraction // MARK: Gist Options var gistService: String? { get { return userDefaults.objectForKey(gistServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: gistServiceKey) switch newValue! { case "GitHub": secretGistsAvailable = true default: secretGistsAvailable = false } } } var secretGistsAvailable: Bool? { get { return userDefaults.objectForKey(secretGistsAvailableKey) as? Bool } set { userDefaults.setObject(newValue, forKey: secretGistsAvailableKey) } } var gistIsPublic: Bool? { get { return userDefaults.objectForKey(gistIsPublicKey) as? Bool } set { userDefaults.setObject(newValue, forKey: gistIsPublicKey) } } // MARK: Image options var imageService: String? { get { return userDefaults.objectForKey(imageServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: imageServiceKey) } } // MARK: Shortening Options // Binded from OptionsWindow > Segmented control var shortenService: String? { get { return userDefaults.objectForKey(shortenServiceKey) as? String } set { userDefaults.setObject(newValue, forKey: shortenServiceKey) } } var recentActions: [String: String]? { get { return userDefaults.objectForKey(recentActionsKey) as? [String: String] } set { userDefaults.setObject(newValue, forKey: recentActionsKey) app.statusBarItem.menu = createMenu(app.menuSendersAction) } } }
mit
ceb3ca1ed9dacd8a931dffff67ef0ae5
21.083333
74
0.731656
3.75
false
false
false
false
goktugyil/EZSwiftExtensions
Sources/TimePassed.swift
1
1117
// // TimePassed.swift // EZSwiftExtensions // // Created by Jaja Yting on 24/08/2018. // Copyright © 2018 Goktug Yilmaz. All rights reserved. // import Foundation public enum TimePassed { case year(Int) case month(Int) case day(Int) case hour(Int) case minute(Int) case second(Int) case now } extension TimePassed: Equatable { public static func ==(lhs: TimePassed, rhs: TimePassed) -> Bool { switch(lhs, rhs) { case (.year(let a), .year(let b)): return a == b case (.month(let a), .month(let b)): return a == b case (.day(let a), .day(let b)): return a == b case (.hour(let a), .hour(let b)): return a == b case (.minute(let a), .minute(let b)): return a == b case (.second(let a), .second(let b)): return a == b case (.now, .now): return true default: return false } } }
mit
ae2900a5dc71cd41027c428aabd1aa01
20.056604
69
0.46147
4.227273
false
false
false
false
S1U/True-Random
True Random/True Random/RandomInteger.swift
1
2010
// // RandomInteger.swift // True Random // // Created by Stephen on 04/10/2017. // Copyright © 2017 S1U. All rights reserved. // import Foundation import SwiftyJSON import Alamofire class RandomInteger: NSObject { private let apiURL = "https://api.random.org/json-rpc/1/invoke" private let apiKey = "2296a8df-b886-489f-91dd-cc22d3286388" var pool = [UInt]() func from(min: UInt, max: UInt, count: UInt, completionHandler: @escaping ([UInt]) ->()) { // func from(min: UInt, max: UInt, count: UInt) { let urlParams: [String : Any] = ["jsonrpc":"2.0", "method":"generateIntegers", "params": ["apiKey": apiKey, "n": count, "min": min, "max": max, "replacement":false, "base":10], "id":28610] Alamofire.request(apiURL, method: .get, parameters: urlParams, encoding: JSONEncoding.default).responseJSON { response in // if response.result.isSuccess { // let randomJSON = JSON(response.result.value!) // self.updatePool(randomJSON) // } else { // print(response.result.error!) // } switch response.result { case .success(let value): let randomNums = JSON(value)["result", "random", "data"].arrayObject as! [UInt] completionHandler(randomNums) case .failure(let error): print(error) } } } // func updatePool(_ randomJSON: JSON) { // pool = randomJSON["result"]["random"]["data"].arrayObject as! [UInt] // print("pool is \(pool)") // } }
gpl-3.0
275c1119bf8202591aa0c126bbc62538
35.527273
117
0.460926
4.661253
false
false
false
false
huangboju/Moots
UICollectionViewLayout/Blueprints-master/Example-OSX/Common/Extensions/NSViewExtensions.swift
1
1182
import Cocoa extension NSView { static var defaultAnimationDuration: TimeInterval { return 0.2 } static var defaultAnimationTimingFunction: CAMediaTimingFunction { return CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut) } static func animate(duration: TimeInterval = defaultAnimationDuration, timingFunction: CAMediaTimingFunction = defaultAnimationTimingFunction, animations: () -> Void, completion: (() -> Void)? = nil) { NSAnimationContext.runAnimationGroup({ context in context.allowsImplicitAnimation = true context.duration = duration context.timingFunction = timingFunction animations() }, completionHandler: completion) } static func animate(withDuration duration: TimeInterval = defaultAnimationDuration, timingFunction: CAMediaTimingFunction = defaultAnimationTimingFunction, animations: () -> Void) { animate(duration: duration, timingFunction: timingFunction, animations: animations, completion: nil) } }
mit
00b57de83e4e25560b0b26848d8f4fc3
38.4
108
0.654822
7.035714
false
false
false
false