repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cruzdiego/PannablePickerView | Example/PannablePickerView/AsAnInputViewTableViewController.swift | 1 | 1665 | //
// AsAnInputViewTableViewController.swift
// PannablePickerView
//
// Created by Diego Alberto Cruz Castillo on 12/26/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import PannablePickerView
class AsAnInputViewTableViewController: UITableViewController{
//MARK: - Properties
//MARK: IBOutlets
@IBOutlet weak var yearTextField: UITextField?
//MARK: Variables
public lazy var pannablePickerView:UIView = {
let pickerView = PannablePickerView()
pickerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200)
pickerView.addTarget(self, action: #selector(valueChanged(_:)), for: .valueChanged)
pickerView.backgroundColor = UIColor(red: 0.180, green: 0.659, blue: 0.929, alpha: 1.00)
pickerView.minValue = 2005
pickerView.maxValue = 2015
pickerView.value = 2015
pickerView.unit = "year"
return pickerView
}()
//MARK: - Public methods
//MARK: View events
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
yearTextField?.becomeFirstResponder()
}
//MARK: - Private methods
//MARK: Actions
@objc private func valueChanged(_ sender:PannablePickerView){
let valueText = String(format: "%0.0f", sender.value)
yearTextField?.text = "\(valueText)"
}
}
//MARK: - Delegate methods
//MARK: UITextFieldDelegate
extension AsAnInputViewTableViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
textField.inputView = pannablePickerView
return true
}
}
| mit | ec2f453ed56b9620bfee77c886704d98 | 31.627451 | 96 | 0.682692 | 4.521739 | false | false | false | false |
achinet/LEOTab | Pod/Classes/LEOCollectionViewController.swift | 1 | 4186 | import UIKit
public class LEOCollectionViewController: UIViewController {
public var collectionView : UICollectionView!
var layout : LEOCollectionViewFlowLayout!
public var leoNavigationBar : LEONavigationBar?
public var controllers : Array <UIViewController>? {
didSet {
if let letControllers = controllers {
for vc in letControllers {
if let leoVc = vc as? LEOTableViewController {
leoVc.leoNavigationBar = self.leoNavigationBar
}
}
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
layout = LEOCollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.sectionInset = UIEdgeInsetsZero
layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
layout.itemSize = self.view.frame.size
collectionView.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "MyCell")
self.automaticallyAdjustsScrollViewInsets = false
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast
self.collectionView.backgroundColor = UIColor.clearColor()
self.view.addSubview(collectionView)
self.SetupCollectionViewController()
if self.navigationController?.navigationBar is LEONavigationBar {
self.leoNavigationBar = self.navigationController?.navigationBar as? LEONavigationBar
}
}
func SetupCollectionViewController() {
self.navigationItem.title = nil
self.navigationItem.hidesBackButton = true
}
public func getCurrentIndexPath() -> NSIndexPath? {
let visibleRect = CGRect(origin: self.collectionView.contentOffset, size: self.collectionView.bounds.size)
let visiblePoint = CGPointMake(CGRectGetMidX(visibleRect), CGRectGetMidY(visibleRect))
return self.collectionView.indexPathForItemAtPoint(visiblePoint)
}
}
extension LEOCollectionViewController: UICollectionViewDelegateFlowLayout {
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return collectionView.frame.size
}
}
extension LEOCollectionViewController : UICollectionViewDataSource {
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let letControllers = controllers {
return letControllers.count
}
return 0
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath)
let vc = controllers![indexPath.row]
cell.contentView.addSubview((vc.view)!)
cell.contentView.userInteractionEnabled = true;
return cell;
}
public func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let currentIndexPathRow = getCurrentIndexPath()?.row, viewController = controllers?[currentIndexPathRow] {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("LEO_WillDisappearCell", object: viewController)
}
if let viewController = controllers?[indexPath.row] {
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("LEO_willDisplayCell", object: viewController)
}
}
public func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
//Do nothing yet
}
} | mit | ea8f70a8ee61f80543f7b9e1a67e9606 | 42.164948 | 176 | 0.701147 | 6.520249 | false | false | false | false |
12207480/PureLayout | PureLayout/Example-iOS/Demos/iOSDemo4ViewController.swift | 1 | 4104 | //
// iOSDemo4ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
class iOSDemo4ViewController: UIViewController {
let blueLabel: UILabel = {
let label = UILabel.newAutoLayoutView()
label.backgroundColor = .blueColor()
label.numberOfLines = 1
label.lineBreakMode = .ByClipping
label.textColor = .whiteColor()
label.text = NSLocalizedString("Lorem ipsum", comment: "")
return label
}()
let redLabel: UILabel = {
let label = UILabel.newAutoLayoutView()
label.backgroundColor = .redColor()
label.numberOfLines = 0
label.textColor = .whiteColor()
label.text = NSLocalizedString("Lorem ipsum", comment: "")
return label
}()
let greenView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .greenColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueLabel)
view.addSubview(redLabel)
view.addSubview(greenView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
/**
NOTE: To observe the effect of leading & trailing attributes, you need to change the OS language setting from a left-to-right language,
such as English, to a right-to-left language, such as Arabic.
This demo project includes localized strings for Arabic, so you will see the Lorem Ipsum text in Arabic if the system is set to that language.
See this method of easily forcing the simulator's language from Xcode: http://stackoverflow.com/questions/8596168/xcode-run-project-with-specified-localization
*/
let smallPadding: CGFloat = 20.0
let largePadding: CGFloat = 50.0
if (!didSetupConstraints) {
// Prevent the blueLabel from compressing smaller than required to fit its single line of text
blueLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical)
// Position the single-line blueLabel at the top of the screen spanning the width, with some small insets
blueLabel.autoPinToTopLayoutGuideOfViewController(self, withInset: smallPadding)
blueLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: smallPadding)
blueLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: smallPadding)
// Make the redLabel 60% of the width of the blueLabel
redLabel.autoMatchDimension(.Width, toDimension: .Width, ofView: blueLabel, withMultiplier: 0.6)
// The redLabel is positioned below the blueLabel, with its leading edge to its superview, and trailing edge to the greenView
redLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: blueLabel, withOffset: smallPadding)
redLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: smallPadding)
redLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: largePadding)
// The greenView is positioned below the blueLabel, with its leading edge to the redLabel, and trailing edge to its superview
greenView.autoPinEdge(.Leading, toEdge: .Trailing, ofView: redLabel, withOffset: largePadding)
greenView.autoPinEdge(.Top, toEdge: .Bottom, ofView: blueLabel, withOffset: smallPadding)
greenView.autoPinEdgeToSuperviewEdge(.Trailing, withInset: smallPadding)
// Match the greenView's height to its width (keeping a consistent aspect ratio)
greenView.autoMatchDimension(.Width, toDimension: .Height, ofView: greenView)
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
| mit | 72df97ec83b2103fd73c16966b5130ae | 43.129032 | 167 | 0.661062 | 5.523553 | false | false | false | false |
wwczwt/sdfad | PageController/PageController+ContainerView.swift | 1 | 1348 | //
// PageController+ContainerView.swift
// PageController
//
// Created by Hirohisa Kawasaki on 6/26/15.
// Copyright (c) 2015 Hirohisa Kawasaki. All rights reserved.
//
import UIKit
extension PageController {
class ContainerView: UIScrollView {
weak var controller: PageController? {
didSet {
delegate = controller
}
}
override init(frame: CGRect) {
super.init(frame: frame)
configure()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configure()
}
func configure() {
directionalLockEnabled = true
showsHorizontalScrollIndicator = false
showsVerticalScrollIndicator = false
scrollsToTop = false
pagingEnabled = true
}
override func layoutSubviews() {
super.layoutSubviews()
if frame.size == CGSizeZero {
return
}
if needsRecenter() {
cancelTouches()
recenter(relativeView: self)
controller?.loadPages()
}
}
func cancelTouches() {
panGestureRecognizer.enabled = false
panGestureRecognizer.enabled = true
}
}
} | mit | e7ff808df8a154bad14cb21292fd5539 | 22.258621 | 62 | 0.535608 | 5.835498 | false | true | false | false |
Sankra/ImageToImg | ImageToImg/HTMLGenerator.swift | 1 | 720 | import Foundation
open class HTMLGenerator {
let imageBasePath: String
let textAlign: String
public init() {
imageBasePath = "http://hjerpbakk.com/s/"
textAlign = "center"
}
open func imgHtml(_ imageName: String, width: CGFloat, height: CGFloat) -> String {
let imageUrl = imageBasePath + imageName.replacingOccurrences(of: " ", with: "-")
return "<div style=\"width:100%; text-align:\(textAlign)\">\r\n\t<img src=\"\(imageUrl)\" alt=\"\((imageName as NSString).deletingPathExtension)\" width=\"\(formatNumber(width / 2))\">\r\n</div>"
}
func formatNumber(_ number: CGFloat) -> NSString {
return (NSString(format: "%.01f", number))
}
}
| mit | 5c2c103e6d7ffa1d078cbd06d7bd20c8 | 35 | 203 | 0.620833 | 4.186047 | false | false | false | false |
adudney/RaycastV2 | RaycastV2/Level1.swift | 1 | 3556 | //
// Level1.swift
// RaycastV2
//
// Created by Isaac Dudney on 7/11/15.
// Copyright (c) 2015 Andrew Dudney. All rights reserved.
//
import Foundation
func level1() -> Level {
//var level = Level(size: IRect(point1: IVector(x: 0, y: 0), point2: IVector(x: 100, y: 75)), walls:[], enemies:[], spawn: IVector(x: 2, y: 2), exit: IRect(point1: IVector(x: 45, y: 45), point2: IVector(x: 50, y: 50)))
var level = Level(size: ISize(width: 60, height: 55), walls:[], enemies:[], spawn: IVector(x: 2, y: 2), exit: IRect(point1: IVector(x: 30, y: 45), point2: IVector(x: 35, y: 50)))
level.walls = [ILineSeg(point1: IVector(x: 5, y: 0), point2: IVector(x: 5, y: 10)),
ILineSeg(point1: IVector(x: 5, y: 10), point2: IVector(x: 15, y: 10)),
ILineSeg(point1: IVector(x: 5, y: 15), point2: IVector(x: 15, y: 15)),
ILineSeg(point1: IVector(x: 15, y: 10), point2: IVector(x: 15, y: 15)),
ILineSeg(point1: IVector(x: 7, y: 0), point2: IVector(x: 7, y: 25)),
ILineSeg(point1: IVector(x: 5, y: 15), point2: IVector(x: 5, y: 25)),
ILineSeg(point1: IVector(x: 5, y: 25), point2: IVector(x: 7, y: 25)),
ILineSeg(point1: IVector(x: 0, y: 30), point2: IVector(x: 30, y: 30)),
ILineSeg(point1: IVector(x: 30, y: 30), point2: IVector(x: 30, y: 10)),
ILineSeg(point1: IVector(x: 35, y: 10), point2: IVector(x: 25, y: 10)),
ILineSeg(point1: IVector(x: 35, y: 10), point2: IVector(x: 40, y: 15)),
ILineSeg(point1: IVector(x: 45, y: 0), point2: IVector(x: 45, y: 15)),
ILineSeg(point1: IVector(x: 40, y: 15), point2: IVector(x: 35, y: 20)),
ILineSeg(point1: IVector(x: 45, y: 15), point2: IVector(x: 40, y: 20)),
ILineSeg(point1: IVector(x: 35, y: 20), point2: IVector(x: 40, y: 25)),
ILineSeg(point1: IVector(x: 40, y: 20), point2: IVector(x: 45, y: 25)),
ILineSeg(point1: IVector(x: 40, y: 25), point2: IVector(x: 35, y: 30)),
ILineSeg(point1: IVector(x: 45, y: 25), point2: IVector(x: 40, y: 30)),
ILineSeg(point1: IVector(x: 40, y: 30), point2: IVector(x: 45, y: 35)),
ILineSeg(point1: IVector(x: 35, y: 30), point2: IVector(x: 40, y: 35)),
ILineSeg(point1: IVector(x: 45, y: 35), point2: IVector(x: 50, y: 35)),
ILineSeg(point1: IVector(x: 40, y: 35), point2: IVector(x: 25, y: 35)),
ILineSeg(point1: IVector(x: 25, y: 35), point2: IVector(x: 25, y: 50)),
ILineSeg(point1: IVector(x: 50, y: 35), point2: IVector(x: 50, y: 50)),
ILineSeg(point1: IVector(x: 50, y: 50), point2: IVector(x: 25, y: 50))]
let waypoints: [Waypoint] = [Waypoint(pos: IVector(x: 5, y: 20),
speed: 1,
shots: [Shot(speed: 2,
rotationDirection: .CW,
rotation: 40)])]
level.enemies = [Enemy(waypoints: waypoints,
zone: IRect(point1: IVector(x: 6, y: 21), point2: IVector(x: 8, y: 23)),
row: 1)]
//let level = Level(size: ISize(width: 20, height: 20), walls:[], enemies:[], spawn: IVector(x: 5, y: 5), exit: IRect(point1: IVector(x: 45, y: 45), point2: IVector(x: 50, y: 50)))
return level
} | mit | f6a4fe4f0e702fcd2dbd2f404aaee7aa | 66.113208 | 222 | 0.509843 | 2.941274 | false | false | false | false |
jokechat/swift3-novel | swift_novels/Pods/SnapKit/Source/ConstraintMaker.swift | 15 | 7224 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// 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.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
public class ConstraintMaker {
public var left: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.left)
}
public var top: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.top)
}
public var bottom: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottom)
}
public var right: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.right)
}
public var leading: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leading)
}
public var trailing: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailing)
}
public var width: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.width)
}
public var height: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.height)
}
public var centerX: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerX)
}
public var centerY: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerY)
}
@available(*, deprecated:3.0, message:"Use lastBaseline instead")
public var baseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
public var lastBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.lastBaseline)
}
@available(iOS 8.0, OSX 10.11, *)
public var firstBaseline: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.firstBaseline)
}
@available(iOS 8.0, *)
public var leftMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leftMargin)
}
@available(iOS 8.0, *)
public var rightMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.rightMargin)
}
@available(iOS 8.0, *)
public var bottomMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.bottomMargin)
}
@available(iOS 8.0, *)
public var leadingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.leadingMargin)
}
@available(iOS 8.0, *)
public var trailingMargin: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.trailingMargin)
}
@available(iOS 8.0, *)
public var centerXWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerXWithinMargins)
}
@available(iOS 8.0, *)
public var centerYWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerYWithinMargins)
}
public var edges: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.edges)
}
public var size: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.size)
}
public var center: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.center)
}
@available(iOS 8.0, *)
public var margins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.margins)
}
@available(iOS 8.0, *)
public var centerWithinMargins: ConstraintMakerExtendable {
return self.makeExtendableWithAttributes(.centerWithinMargins)
}
private let view: ConstraintView
private var descriptions = [ConstraintDescription]()
internal init(view: ConstraintView) {
self.view = view
self.view.translatesAutoresizingMaskIntoConstraints = false
}
internal func makeExtendableWithAttributes(_ attributes: ConstraintAttributes) -> ConstraintMakerExtendable {
let description = ConstraintDescription(view: self.view, attributes: attributes)
self.descriptions.append(description)
return ConstraintMakerExtendable(description)
}
internal static func prepareConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) -> [Constraint] {
let maker = ConstraintMaker(view: view)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
return constraints
}
internal static func makeConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) {
let maker = ConstraintMaker(view: view)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: false)
}
}
internal static func remakeConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) {
self.removeConstraints(view: view)
self.makeConstraints(view: view, closure: closure)
}
internal static func updateConstraints(view: ConstraintView, closure: (_ make: ConstraintMaker) -> Void) {
guard view.snp.constraints.count > 0 else {
self.makeConstraints(view: view, closure: closure)
return
}
let maker = ConstraintMaker(view: view)
closure(maker)
let constraints = maker.descriptions
.map { $0.constraint }
.filter { $0 != nil }
.map { $0! }
for constraint in constraints {
constraint.activateIfNeeded(updatingExisting: true)
}
}
internal static func removeConstraints(view: ConstraintView) {
let constraints = view.snp.constraints
for constraint in constraints {
constraint.deactivateIfNeeded()
}
}
}
| apache-2.0 | c0dcb0f63d4c68a4de84d6be6768198e | 34.067961 | 127 | 0.681617 | 5.539877 | false | false | false | false |
Explora-codepath/explora | Explora/SignUpViewController.swift | 1 | 5654 | //
// SignUpViewController.swift
// Explora
//
// Created by admin on 10/18/15.
// Copyright © 2015 explora-codepath. All rights reserved.
//
import UIKit
import Parse
import ParseFacebookUtilsV4
class SignUpViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var submitButton: UIButton!
weak var delegate: LoginDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func submitButtonPressed(sender: AnyObject) {
if (!validateFields()) {
// Do nothing if fields are not valid
return;
}
let user = PFUser()
user.username = self.usernameField.text
user.password = self.passwordField.text
user.email = self.emailField.text
// other fields can be set just like with PFObject
user.createdEvents = []
user.participatingEvents = []
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if let error = error {
let errorString = error.userInfo["error"] as? NSString
// Show the errorString somewhere and let the user try again.
print (errorString)
let alertController = UIAlertController(title: "Error Signing Up", message: error.description, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
// Hooray! Let them use the app now.
print ("success signing up")
let alertController = UIAlertController(title: "Success", message: "Sign up was successful!", preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.delegate?.handleLoginSuccess(user)
})
})
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
@IBAction func signUpWithFacebookButtonPressed(sender: AnyObject) {
PFFacebookUtils.logInInBackgroundWithReadPermissions(nil) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
user.getUserInfo()
let message = "Sign up was successful!"
print(message)
let alertController = UIAlertController(title: "Facebook Signup", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: { () -> Void in
self.delegate?.handleLoginSuccess(user)
})
})
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let message = "Uh oh. There was an error signing up through Facebook."
print(message)
let alertController = UIAlertController(title: "Facebook Signup", message: message, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
func validateFields() -> Bool {
var valid = true
var errorMessage = ""
if (self.usernameField.text == "") {
valid = false
errorMessage = "Please fill in a user name."
} else if (self.emailField.text == "") {
valid = false
errorMessage = "Please fill in an email."
} else if (self.passwordField.text == "") {
valid = false
errorMessage = "Please fill in a password."
}
if !valid {
let alertController = UIAlertController(title: "Error Signing Up", message: errorMessage, preferredStyle: UIAlertControllerStyle.Alert)
let button = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
alertController.addAction(button)
self.presentViewController(alertController, animated: true, completion: nil)
}
return valid
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 038d2db801613240e060fa7fb2528699 | 41.825758 | 156 | 0.613833 | 5.48835 | false | false | false | false |
nikhilsinghmus/csound | iOS/Csound iOS Swift Examples/Csound iOS SwiftExamples/AudioInTestViewController.swift | 3 | 2883 | /*
AudioInTestViewController.swift
Nikhil Singh, Dr. Richard Boulanger
Adapted from the Csound iOS Examples by Steven Yi and Victor Lazzarini
This file is part of Csound iOS SwiftExamples.
The Csound for iOS Library is free software; you can redistribute it
and/or modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
Csound 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Csound; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA
*/
import UIKit
class AudioInTestViewController: BaseCsoundViewController {
@IBOutlet var mLeftDelayTimeSlider: UISlider!
@IBOutlet var mLeftFeedbackSlider: UISlider!
@IBOutlet var mRightDelayTimeSlider: UISlider!
@IBOutlet var mRightFeedbackSlider: UISlider!
@IBOutlet var mSwitch: UISwitch!
override func viewDidLoad() {
title = "11. Mic: Stereo Delay"
super.viewDidLoad()
}
@IBAction func toggleOnOff(_ sender: UISwitch) {
print("Status: \(sender.isOn)")
if sender.isOn {
let tempFile = Bundle.main.path(forResource: "audioInTest", ofType: "csd")
csound.stop()
csound = CsoundObj()
csound.useAudioInput = true
csound.add(self)
let csoundUI: CsoundUI = CsoundUI(csoundObj: csound)
csoundUI.add(mLeftDelayTimeSlider, forChannelName: "leftDelayTime")
csoundUI.add(mLeftFeedbackSlider, forChannelName: "leftFeedback")
csoundUI.add(mRightDelayTimeSlider, forChannelName: "rightDelayTime")
csoundUI.add(mRightFeedbackSlider, forChannelName: "rightFeedback")
csound.play(tempFile)
} else {
csound.stop()
}
}
@IBAction func showInfo(_ sender: UIButton) {
infoVC.preferredContentSize = CGSize(width: 300, height: 120)
infoText = "This example shows audio processing in real-time with independent delay-time and feedback settings for each channel."
displayInfo(sender)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension AudioInTestViewController: CsoundObjListener {
func csoundObjCompleted(_ csoundObj: CsoundObj!) {
DispatchQueue.main.async { [unowned self] in
self.mSwitch.isOn = false
}
}
}
| lgpl-2.1 | 7a4c276004dea4f3f1c23cb616950495 | 33.73494 | 137 | 0.682622 | 4.49766 | false | false | false | false |
jisudong/study | MyPlayground.playground/Pages/扩展.xcplaygroundpage/Contents.swift | 1 | 1662 | //: [Previous](@previous)
import Foundation
// 扩展
/*
* 添加计算型属性
扩展可以添加新的计算型属性,但是不可以添加存储型属性,也不可以为已有属性添加属性观察器
* 添加构造器
扩展能为类添加新的便利构造器,但是它们不能为类添加新的指定构造器或析构器。指定构造器和析构器必须总是由原始的类实现来提供。
结构体和枚举类型可以在扩展里添加指定构造器。
如果你使用扩展为一个值类型添加构造器,同时该值类型的原始实现中未定义任何定制的构造器且所有存储属性提供了默认值,那么我们就可以在扩展中的构造器里调用默认构造器和逐一成员构造器
如果你使用扩展提供了一个新的构造器,你依旧有责任确保构造过程能够让实例完全初始化
* 添加方法
通过扩展添加的实例方法也可以修改该实例本身。结构体和枚举类型中修改 self 或其属性的方法必须将该实例方法标注为 mutating,正如来自原始实现的可变方法一样
* 添加下标
* 添加嵌套类型
*/
struct Point {
var x = 0.0, y = 0.0
}
struct Size {
var width = 0.0, height = 0.0
}
struct Rect {
var origin = Point()
var size = Size()
}
extension Rect {
init(center: Point, size: Size) {
let originX = center.x - (size.width / 2)
let originY = center.y - (size.height / 2)
self.init(origin: Point(x: originX, y: originY), size: size)//调用逐一成员构造器
}
init(x: Double, y: Double, width: Double, height: Double) {
}
}
| mit | e194150924361329642dc811242a178c | 19.170213 | 88 | 0.683544 | 2.481675 | false | false | false | false |
harenbrs/swix | swixUseCases/swix-iOSb6/swix/matrix/matrix.swift | 2 | 5556 | //
// matrix2d.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
struct matrix {
let n: Int
var rows: Int
var columns: Int
var count: Int
var shape: (Int, Int)
var flat:ndarray
var T:matrix {return transpose(self)}
var I:matrix {return inv(self)}
var pI:matrix {return pinv(self)}
init(columns: Int, rows: Int) {
self.n = rows * columns
self.rows = rows
self.columns = columns
self.shape = (rows, columns)
self.count = n
self.flat = zeros(rows * columns)
}
func copy()->matrix{
var y = zeros_like(self)
y.flat = self.flat.copy()
return y
}
subscript(i: String) -> ndarray {
get {
assert(i == "diag", "Currently the only support x[string] is x[\"diag\"]")
var size = rows < columns ? rows : columns
var i = arange(size)
return self[i*columns.double + i]
}
set {
assert(i == "diag", "Currently the only support x[string] is x[\"diag\"]")
var m = shape.0
var n = shape.1
var min_mn = m < n ? m : n
var j = n.double * arange(min_mn)
self[j + j/n.double] = newValue
}
}
func indexIsValidForRow(r: Int, c: Int) -> Bool {
return r >= 0 && r < rows && c>=0 && c < columns
}
func dot(y: matrix) -> matrix{
return self *! y
}
subscript(i: Int, j: Int) -> Double {
// x[0,0]
get {
var nI = i
var nJ = j
if nI < 0 {nI = rows + i}
if nJ < 0 {nJ = rows + j}
assert(indexIsValidForRow(nI, c:nJ), "Index out of range")
return flat[nI * columns + nJ]
}
set {
var nI = i
var nJ = j
if nI < 0 {nI = rows + i}
if nJ < 0 {nJ = rows + j}
assert(indexIsValidForRow(nI, c:nJ), "Index out of range")
flat[nI * columns + nJ] = newValue
}
}
subscript(i: Range<Int>, k: Int) -> ndarray {
// x[0..<2, 0]
get {
var idx = asarray(i)
return self[idx, k]
}
set {
var idx = asarray(i)
self[idx, k] = newValue
}
}
subscript(r: Range<Int>, c: Range<Int>) -> matrix {
// x[0..<2, 0..<2]
get {
var rr = asarray(r)
var cc = asarray(c)
return self[rr, cc]
}
set {
var rr = asarray(r)
var cc = asarray(c)
self[rr, cc] = newValue
}
}
subscript(i: Int, k: Range<Int>) -> ndarray {
// x[0, 0..<2]
get {
var idx = asarray(k)
return self[i, idx]
}
set {
var idx = asarray(k)
self[i, idx] = newValue
}
}
subscript(or: ndarray, oc: ndarray) -> matrix {
// the main method.
// x[array(1,2), array(3,4)]
get {
var r = or.copy()
var c = oc.copy()
if r.max() < 0.0 {r += 1.0 * rows.double}
if c.max() < 0.0 {c += 1.0 * columns.double}
var (j, i) = meshgrid(r, c)
var idx = (j.flat*columns.double + i.flat)
var z = flat[idx]
var zz = reshape(z, (r.n, c.n))
return zz
}
set {
var r = or.copy()
var c = oc.copy()
if r.max() < 0.0 {r += 1.0 * rows.double}
if c.max() < 0.0 {c += 1.0 * columns.double}
if r.n > 0 && c.n > 0{
var (j, i) = meshgrid(r, c)
var idx = j.flat*columns.double + i.flat
flat[idx] = newValue.flat
}
}
}
subscript(r: ndarray) -> ndarray {
// flat indexing
get {return self.flat[r]}
set {self.flat[r] = newValue }
}
subscript(i: String, k:Int) -> ndarray {
// x["all", 0]
get {
var idx = arange(shape.0)
var x:ndarray = self.flat[idx * self.columns.double + k.double]
return x
}
set {
var idx = arange(shape.0)
self.flat[idx * self.columns.double + k.double] = newValue
}
}
subscript(i: Int, k: String) -> ndarray {
// x[0, "all"]
get {
assert(k == "all", "Only 'all' supported")
var idx = arange(shape.1)
var x:ndarray = self.flat[i.double * self.columns.double + idx]
return x
}
set {
assert(k == "all", "Only 'all' supported")
var idx = arange(shape.1)
self.flat[i.double * self.columns.double + idx] = newValue
}
}
subscript(i: ndarray, k: Int) -> ndarray {
// x[array(1,2), 0]
get {
var idx = i.copy()
var x:ndarray = self.flat[idx * self.columns.double + k.double]
return x
}
set {
var idx = i.copy()
self.flat[idx * self.columns.double + k.double] = newValue
}
}
subscript(i: Int, k: ndarray) -> ndarray {
// x[0, array(1,2)]
get {
var x:ndarray = self.flat[i.double * self.columns.double + k]
return x
}
set {
self.flat[i.double * self.columns.double + k] = newValue
}
}
}
| mit | 67b3058de9d0c472f966d4546ec0c2dd | 25.711538 | 86 | 0.444744 | 3.547893 | false | false | false | false |
argon/mas | Carthage/Checkouts/Quick/Externals/Nimble/Sources/Nimble/Adapters/NMBExpectation.swift | 2 | 6995 | #if canImport(Darwin) && !SWIFT_PACKAGE
import class Foundation.NSObject
import typealias Foundation.TimeInterval
import enum Dispatch.DispatchTimeInterval
private func from(objcPredicate: NMBPredicate) -> Predicate<NSObject> {
return Predicate { actualExpression in
let result = objcPredicate.satisfies(({ try actualExpression.evaluate() }),
location: actualExpression.location)
return result.toSwift()
}
}
private func from(matcher: NMBMatcher, style: ExpectationStyle) -> Predicate<NSObject> {
// Almost same as `Matcher.toClosure`
let closure: (Expression<NSObject>, FailureMessage) throws -> Bool = { expr, msg in
switch style {
case .toMatch:
return matcher.matches(
// swiftlint:disable:next force_try
({ try! expr.evaluate() }),
failureMessage: msg,
location: expr.location
)
case .toNotMatch:
return !matcher.doesNotMatch(
// swiftlint:disable:next force_try
({ try! expr.evaluate() }),
failureMessage: msg,
location: expr.location
)
}
}
return Predicate._fromDeprecatedClosure(closure)
}
// Equivalent to Expectation, but for Nimble's Objective-C interface
public class NMBExpectation: NSObject {
// swiftlint:disable identifier_name
internal let _actualBlock: () -> NSObject?
internal var _negative: Bool
internal let _file: FileString
internal let _line: UInt
internal var _timeout: DispatchTimeInterval = .seconds(1)
// swiftlint:enable identifier_name
@objc public init(actualBlock: @escaping () -> NSObject?, negative: Bool, file: FileString, line: UInt) {
self._actualBlock = actualBlock
self._negative = negative
self._file = file
self._line = line
}
private var expectValue: Expectation<NSObject> {
return expect(_file, line: _line) {
self._actualBlock() as NSObject?
}
}
@objc public var withTimeout: (TimeInterval) -> NMBExpectation {
return { timeout in self._timeout = timeout.dispatchInterval
return self
}
}
@objc public var to: (NMBMatcher) -> NMBExpectation {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred))
} else {
self.expectValue.to(from(matcher: matcher, style: .toMatch))
}
return self
}
}
@objc public var toWithDescription: (NMBMatcher, String) -> NMBExpectation {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.to(from(objcPredicate: pred), description: description)
} else {
self.expectValue.to(from(matcher: matcher, style: .toMatch), description: description)
}
return self
}
}
@objc public var toNot: (NMBMatcher) -> NMBExpectation {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred))
} else {
self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch))
}
return self
}
}
@objc public var toNotWithDescription: (NMBMatcher, String) -> NMBExpectation {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toNot(from(objcPredicate: pred), description: description)
} else {
self.expectValue.toNot(from(matcher: matcher, style: .toNotMatch), description: description)
}
return self
}
}
@objc public var notTo: (NMBMatcher) -> NMBExpectation { return toNot }
@objc public var notToWithDescription: (NMBMatcher, String) -> NMBExpectation { return toNotWithDescription }
@objc public var toEventually: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventually(
from(matcher: matcher, style: .toMatch),
timeout: self._timeout,
description: nil
)
}
}
}
@objc public var toEventuallyWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventually(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventually(
from(matcher: matcher, style: .toMatch),
timeout: self._timeout,
description: description
)
}
}
}
@objc public var toEventuallyNot: (NMBMatcher) -> Void {
return { matcher in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: nil
)
} else {
self.expectValue.toEventuallyNot(
from(matcher: matcher, style: .toNotMatch),
timeout: self._timeout,
description: nil
)
}
}
}
@objc public var toEventuallyNotWithDescription: (NMBMatcher, String) -> Void {
return { matcher, description in
if let pred = matcher as? NMBPredicate {
self.expectValue.toEventuallyNot(
from(objcPredicate: pred),
timeout: self._timeout,
description: description
)
} else {
self.expectValue.toEventuallyNot(
from(matcher: matcher, style: .toNotMatch),
timeout: self._timeout,
description: description
)
}
}
}
@objc public var toNotEventually: (NMBMatcher) -> Void {
return toEventuallyNot
}
@objc public var toNotEventuallyWithDescription: (NMBMatcher, String) -> Void {
return toEventuallyNotWithDescription
}
@objc public class func failWithMessage(_ message: String, file: FileString, line: UInt) {
fail(message, location: SourceLocation(file: file, line: line))
}
}
#endif
| mit | 1804692a87393b1c4a73a36ba5181cb4 | 34.150754 | 113 | 0.556254 | 5.364264 | false | false | false | false |
niekang/WeiBo | WeiBo/Class/View/Main/VisitorView/VisitorView.swift | 1 | 9855 | //
// VisitorView.swift
// WeiBo
//
// Created by 聂康 on 2017/6/20.
// Copyright © 2017年 com.nk. All rights reserved.
//
import UIKit
class VisitorView: UIView {
var visitorInfoDictionary:[String:String]?{
didSet{
guard let imageName = visitorInfoDictionary?["image"],
let message = visitorInfoDictionary?["tip"] else{
return
}
tipLab.text(message)
if imageName == "" {
startAnimation()
return
}
imageView.image = UIImage(named:imageName)
houseImageView.isHidden = true
maskImageView.isHidden = true
}
}
//中间图像
lazy var imageView = UIImageView(image: UIImage(named: "visitordiscover_feed_image_smallicon"))
//首页小房子
lazy var houseImageView = UIImageView(image: UIImage(named:"visitordiscover_feed_image_house"))
// 首页遮罩图像
lazy var maskImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
//提示标签
lazy var tipLab = UILabel().fontSize(16).numberOfLines(0)
//注册按钮
lazy var registerBtn = UIButton().title("注册").textColor(UIColor.orange).backgroundImage("common_button_white_disable")
//登录按钮
lazy var logBtn = UIButton().title("登录").textColor(UIColor.orange).backgroundImage("common_button_white_disable")
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.white
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension VisitorView {
func setup() {
addSubview(imageView)
addSubview(houseImageView)
addSubview(maskImageView)
addSubview(tipLab)
addSubview(registerBtn)
addSubview(logBtn)
for subview in subviews {
subview.translatesAutoresizingMaskIntoConstraints = false
}
//添加约束
addConstrains()
}
func startAnimation() {
let anima = CABasicAnimation(keyPath: "transform.rotation")
anima.toValue = 2 * Double.pi
anima.repeatCount = MAXFLOAT
anima.duration = 15
anima.isRemovedOnCompletion = false
imageView.layer.add(anima, forKey: "rotation")
}
func addConstrains() {
//中间图片
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: imageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1,
constant: 0))
//小房子
addConstraint(NSLayoutConstraint(item: houseImageView,
attribute: .centerX,
relatedBy: .equal,
toItem: self,
attribute: .centerX,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: houseImageView,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1,
constant: 0))
//标签
addConstraint(NSLayoutConstraint(item: tipLab,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 220))
addConstraint(NSLayoutConstraint(item: tipLab,
attribute: .top,
relatedBy: .equal,
toItem: imageView,
attribute: .bottom,
multiplier: 1,
constant: 20))
addConstraint(NSLayoutConstraint(item: tipLab,
attribute: .centerX,
relatedBy: .equal,
toItem: imageView,
attribute: .centerX,
multiplier: 1,
constant: 0))
//注册按钮
addConstraint(NSLayoutConstraint(item: registerBtn,
attribute: .left,
relatedBy: .equal,
toItem: tipLab,
attribute: .left,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: registerBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 80))
addConstraint(NSLayoutConstraint(item: registerBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLab,
attribute: .bottom,
multiplier: 1,
constant: 20))
//登录按钮
addConstraint(NSLayoutConstraint(item: logBtn,
attribute: .right,
relatedBy: .equal,
toItem: tipLab,
attribute: .right,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: logBtn,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1,
constant: 80))
addConstraint(NSLayoutConstraint(item: logBtn,
attribute: .top,
relatedBy: .equal,
toItem: tipLab,
attribute: .bottom,
multiplier: 1,
constant: 20))
//遮罩视图
addConstraint(NSLayoutConstraint(item: maskImageView,
attribute: .left,
relatedBy: .equal,
toItem: self,
attribute: .left,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: maskImageView,
attribute: .right,
relatedBy: .equal,
toItem: self,
attribute: .right,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: maskImageView,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1,
constant: 0))
addConstraint(NSLayoutConstraint(item: maskImageView,
attribute: .bottom,
relatedBy: .equal,
toItem: registerBtn,
attribute: .bottom,
multiplier: 1,
constant: 20))
}
}
| apache-2.0 | 25aa3362c1cae22a27bd66e4c7155726 | 39.231405 | 122 | 0.368221 | 7.618153 | false | false | false | false |
dreamsxin/swift | test/SILGen/instrprof_operators.swift | 6 | 2058 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen -profile-generate %s | FileCheck %s
// CHECK: sil hidden @[[F_OPERATORS:.*operators.*]] :
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 0
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
func operators(a : Bool, b : Bool) {
let c = a && b
let d = a || b
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 3
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
let e = c ? a : b
// CHECK-NOT: builtin "int_instrprof_increment"
}
// CHECK: implicit closure
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 1
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
// CHECK-NOT: builtin "int_instrprof_increment"
// CHECK: implicit closure
// CHECK: %[[NAME:.*]] = string_literal utf8 "{{.*}}instrprof_operators.swift:[[F_OPERATORS]]"
// CHECK: %[[HASH:.*]] = integer_literal $Builtin.Int64,
// CHECK: %[[NCOUNTS:.*]] = integer_literal $Builtin.Int32, 4
// CHECK: %[[INDEX:.*]] = integer_literal $Builtin.Int32, 2
// CHECK: builtin "int_instrprof_increment"(%[[NAME]] : {{.*}}, %[[HASH]] : {{.*}}, %[[NCOUNTS]] : {{.*}}, %[[INDEX]] : {{.*}})
// CHECK-NOT: builtin "int_instrprof_increment"
| apache-2.0 | a22761aaeec59489e0d290d6d814dce1 | 54.621622 | 127 | 0.576774 | 3.319355 | false | false | false | false |
mlilback/rc2SwiftClient | MacClient/session/sidebar/SidebarFileController.swift | 1 | 27382 | //
// SidebarFileController.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import MJLLogger
import ReactiveSwift
import SwiftyUserDefaults
import Rc2Common
import Networking
import Model
class FileRowData: Equatable {
var sectionName: String?
var file: AppFile?
init(name: String?, file: AppFile?) {
self.sectionName = name
self.file = file
}
static public func == (lhs: FileRowData, rhs: FileRowData) -> Bool {
if lhs.sectionName != nil && lhs.sectionName == rhs.sectionName { return true }
if rhs.file != nil && lhs.file != nil && lhs.file?.fileId == rhs.file?.fileId { return true }
return false
}
}
protocol FileViewControllerDelegate: class {
func fileSelectionChanged(_ file: AppFile?, forEditing: Bool)
}
let FileDragTypes = [NSPasteboard.PasteboardType(kUTTypeFileURL as String)]
let addFileSegmentIndex: Int = 0
let removeFileSegmentIndex: Int = 1
// swiftlint:disable type_body_length
class SidebarFileController: AbstractSessionViewController, NSTableViewDataSource, NSTableViewDelegate, NSOpenSavePanelDelegate, NSMenuDelegate
{
// MARK: properties
let sectionNames: [String] = ["Source Files", "Images", "Other"]
@IBOutlet var tableView: NSTableView!
@IBOutlet var addRemoveButtons: NSSegmentedControl?
@IBOutlet var messageView: NSView?
@IBOutlet var messageLabel: NSTextField?
@IBOutlet var messageButtons: NSStackView?
private var getInfoPopover: NSPopover?
private var fileInfoController: FileInfoController?
var rowData: [FileRowData] = [FileRowData]()
weak var delegate: FileViewControllerDelegate?
lazy var importPrompter: MacFileImportSetup? = { MacFileImportSetup() }()
var fileImporter: FileImporter?
private var fileChangeDisposable: Disposable?
/// used to disable interface when window is busy
private var busyDisposable: Disposable?
fileprivate var selectionChangeInProgress = false
fileprivate var formatMenu: NSMenu?
var selectedFile: AppFile? { didSet { fileSelectionChanged() } }
// MARK: - lifecycle
override func awakeFromNib() {
super.awakeFromNib()
if addRemoveButtons != nil {
let menu = NSMenu(title: "new document format")
for (index, aType) in FileType.creatableFileTypes.enumerated() {
let mi = NSMenuItem(title: aType.details ?? "unknown", action: #selector(addDocumentOfType(_:)), keyEquivalent: "")
mi.representedObject = index
menu.addItem(mi)
}
menu.autoenablesItems = false
//NOTE: the action method of the menu item wasn't being called the first time. This works all times.
NotificationCenter.default.addObserver(self, selector: #selector(addFileMenuAction(_:)), name: NSMenu.didSendActionNotification, object: menu)
addRemoveButtons?.setMenu(menu, forSegment: 0)
addRemoveButtons?.target = self
formatMenu = menu
}
if tableView != nil {
tableView.setDraggingSourceOperationMask(.copy, forLocal: true)
tableView.setDraggingSourceOperationMask(.copy, forLocal: false)
tableView.draggingDestinationFeedbackStyle = .none
tableView.registerForDraggedTypes(FileDragTypes)
}
adjustForFileSelectionChange()
}
override func sessionChanged() {
fileChangeDisposable?.dispose()
fileChangeDisposable = session.workspace.fileChangeSignal.observe(on: UIScheduler()).take(during: session.lifetime).observe(on: UIScheduler()).observeValues(filesRefreshed)
loadData()
tableView.reloadData()
if selectedFile != nil {
fileSelectionChanged()
}
if rowData.count == 0 {
messageView?.isHidden = false
} else {
messageView?.isHidden = true
}
}
override func appStatusChanged() {
// don't observe if session not set yet
guard let session = sessionOptional else { return }
busyDisposable = appStatus?.busySignal.observe(on: UIScheduler()).take(during: session.lifetime).observeValues { [weak self] isBusy in
guard let tv = self?.tableView else { return }
if isBusy {
tv.unregisterDraggedTypes()
} else {
tv.registerForDraggedTypes(FileDragTypes)
}
}
}
func loadData() {
guard let session = sessionOptional else { Log.warn("loadData called without a session", .app); return }
var sectionedFiles = [[AppFile](), [AppFile](), [AppFile]()]
for aFile in session.workspace.files.sorted(by: { $1.name > $0.name }) {
if aFile.fileType.isSource {
sectionedFiles[0].append(aFile)
} else if aFile.fileType.isImage {
sectionedFiles[1].append(aFile)
} else {
sectionedFiles[2].append(aFile)
}
}
rowData.removeAll()
for i in 0..<sectionNames.count where sectionedFiles[i].count > 0 {
rowData.append(FileRowData(name: sectionNames[i], file: nil))
rowData.append(contentsOf: sectionedFiles[i].map({ return FileRowData(name: nil, file: $0) }))
}
}
fileprivate func adjustForFileSelectionChange() {
addRemoveButtons?.setEnabled(selectedFile != nil, forSegment: removeFileSegmentIndex)
}
@objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let action = menuItem.action else {
return false
}
switch action {
case #selector(editFile(_:)):
let fileName = selectedFile?.name ?? ""
menuItem.title = String.localizedStringWithFormat(NSLocalizedString("Edit File", comment: ""), fileName)
guard let file = selectedFile, file.fileSize <= MaxEditableFileSize else { return false }
return file.fileType.isEditable
case #selector(promptToImportFiles(_:)):
return true
case #selector(exportSelectedFile(_:)):
return selectedFile != nil
case #selector(exportAllFiles(_:)), #selector(exportZippedFiles(_:)):
return true
default:
return false
}
}
//as the delegate for the action menu, need to enable/disable items
func menuNeedsUpdate(_ menu: NSMenu) {
menu.items.forEach { item in
guard let action = item.action else { return }
switch action {
case #selector(promptToImportFiles(_:)):
item.isEnabled = true
case #selector(editFile(_:)):
item.isEnabled = selectedFile != nil && selectedFile!.fileSize <= MaxEditableFileSize
default:
item.isEnabled = selectedFile != nil
}
}
}
func fileDataIndex(fileId: Int) -> Int? {
for (idx, data) in rowData.enumerated() where data.file?.fileId == fileId {
return idx
}
return nil
}
// NSMenu calls this method before an item's action is called. we listen to it from the add button's menu
@objc func addFileMenuAction(_ note: Notification) {
guard let menuItem = note.userInfo?["MenuItem"] as? NSMenuItem,
let index = menuItem.representedObject as? Int
else { return }
let fileType = FileType.creatableFileTypes[index]
let prompt = NSLocalizedString("Filename:", comment: "")
let baseName = NSLocalizedString("Untitled", comment: "default file name")
DispatchQueue.main.async {
self.promptForFilename(prompt: prompt, baseName: baseName, type: fileType) { (name) in
guard let newName = name else { return }
self.session.create(fileName: newName, contentUrl: self.fileTemplate(forType: fileType)) { result in
// the id of the file that was created
switch result {
case .failure(let err):
Log.error("error creating empty file: \(err)", .app)
self.appStatus?.presentError(err, session: self.session)
case .success(let fid):
self.select(fileId: fid)
}
}
}
}
}
// MARK: - actions
@IBAction func createFirstFile(_ sender: Any?) {
guard let button = sender as? NSButton else { return }
DispatchQueue.main.async {
switch button.tag {
case 0: self.promptToImportFiles(sender)
case 1:
self.formatMenu?.popUp(positioning: nil, at: NSPoint.zero, in: self.messageButtons)
default: break
}
// NSAnimationContext.runAnimationGroup({ (context) in
// context.allowsImplicitAnimation = true
self.messageView?.animator().isHidden = true
// }, completionHandler: nil)
}
// messageView?.isHidden = true
}
@IBAction func deleteFile(_ sender: Any?) {
guard let file = selectedFile else {
Log.error("deleteFile should never be called without selected file", .app)
return
}
let defaults = UserDefaults.standard
if defaults[.suppressDeleteFileWarnings] {
self.actuallyPerformDelete(file: file)
return
}
confirmAction(message: NSLocalizedString(LocalStrings.deleteFileWarning, comment: ""),
infoText: String(format: NSLocalizedString(LocalStrings.deleteFileWarningInfo, comment: ""), file.name),
buttonTitle: NSLocalizedString("Delete", comment: ""),
defaultToCancel: true,
suppressionKey: .suppressDeleteFileWarnings)
{ (confirmed) in
guard confirmed else { return }
self.actuallyPerformDelete(file: file)
}
}
@IBAction func duplicateFile(_ sender: Any?) {
guard let file = selectedFile else {
Log.error("duplicateFile should never be called without selected file", .app)
return
}
let prompt = NSLocalizedString("Filename:", comment: "")
let baseName = NSLocalizedString("Untitled", comment: "default file name")
DispatchQueue.main.async {
self.promptForFilename(prompt: prompt, baseName: baseName, type: file.fileType) { (name) in
guard let newName = name else { return }
self.session.duplicate(file: file, to: newName)
.updateProgress(status: self.appStatus!, actionName: "Duplicate \(file.name)")
.startWithResult { result in
// the id of the file that was created
switch result {
case .failure(let rerror):
Log.error("error duplicating file: \(rerror)", .app)
self.appStatus?.presentError(rerror, session: self.session)
case .success(let fid):
self.select(fileId: fid)
}
}
}
}
}
@IBAction func renameFile(_ sender: Any?) {
guard let cellView = tableView.view(atColumn: 0, row: tableView.selectedRow, makeIfNecessary: false) as? EditableTableCellView else
{
Log.warn("renameFile: failed to get tableViewCell", .app)
return
}
guard let file = cellView.objectValue as? AppFile else {
Log.error("renameFile: no file for file cell view", .app)
return
}
cellView.validator = { self.validateRename(file: file, newName: $0) }
cellView.textField?.isEditable = true
tableView.editColumn(0, row: tableView.selectedRow, with: nil, select: true)
cellView.editText { value in
cellView.textField?.isEditable = false
cellView.textField?.stringValue = file.name
guard var name = value else { return }
if !name.hasSuffix(".\(file.fileType.fileExtension)") {
name += ".\(file.fileType.fileExtension)"
}
self.session.rename(file: file, to: name)
.updateProgress(status: self.appStatus!, actionName: "Rename \(file.name)")
.startWithResult { result in
if case .failure(let error) = result {
Log.error("error duplicating file: \(error)", .app)
self.appStatus?.presentError(error, session: self.session)
return
}
self.select(fileId: file.fileId)
}
}
}
@IBAction func editFile(_ sender: Any) {
delegate?.fileSelectionChanged(selectedFile, forEditing: true)
}
/// called to display info about a specific file
@IBAction func inforForFile(_ sender: Any) {
if getInfoPopover == nil {
// setup the popup and view controller
fileInfoController = FileInfoController()
assert(fileInfoController != nil)
getInfoPopover = NSPopover()
getInfoPopover?.behavior = .transient
getInfoPopover?.contentViewController = fileInfoController
}
// getInfoPopover!.contentSize = fileInfoController!.view.frame.size
var rowIdx = -1
if let button = sender as? NSButton { // if the sender is a button, it's tag was set to the row index
rowIdx = button.tag
} else {
rowIdx = tableView.selectedRow // otherwise, use selected row
}
guard rowIdx >= 0 && rowIdx < rowData.count else { Log.warn("invalid file for info", .app); return }
fileInfoController?.file = rowData[rowIdx].file
self.getInfoPopover?.show(relativeTo: tableView.rect(ofRow: rowIdx), of: tableView, preferredEdge: .maxX)
}
// never gets called, but file type menu items must have an action or addFileMenuAction never gets called
@IBAction func addDocumentOfType(_ menuItem: NSMenuItem) {
}
@IBAction func segButtonClicked(_ sender: Any?) {
switch addRemoveButtons!.selectedSegment {
case addFileSegmentIndex:
//should never be called since a menu is attached
assertionFailure("segButtonClicked should never be called for addSegment")
case removeFileSegmentIndex:
deleteFile(sender)
default:
assertionFailure("unknown segment selected")
}
}
@IBAction func promptToImportFiles(_ sender: Any?) {
if nil == importPrompter {
importPrompter = MacFileImportSetup()
}
importPrompter!.performFileImport(view.window!, workspace: session.workspace) { files in
guard files != nil else { return } //user canceled import
self.importFiles(files!)
}
}
@IBAction func exportSelectedFile(_ sender: Any?) {
let defaults = UserDefaults.standard
let savePanel = NSSavePanel()
savePanel.isExtensionHidden = false
savePanel.allowedFileTypes = [(selectedFile?.fileType.fileExtension)!]
savePanel.nameFieldStringValue = (selectedFile?.name)!
if let bmarkData = defaults[.lastExportDirectory] {
do {
savePanel.directoryURL = try (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL)
} catch {
}
}
savePanel.beginSheetModal(for: view.window!) { result in
do {
let bmark = try (savePanel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
defaults[.lastExportDirectory] = bmark
} catch let err as NSError {
Log.error("why did we get error creating export bookmark: \(err)", .app)
}
savePanel.close()
if result == .OK && savePanel.url != nil {
do {
try Foundation.FileManager.default.copyItem(at: self.session.fileCache.cachedUrl(file: self.selectedFile!), to: savePanel.url!)
} catch let error as NSError {
Log.error("failed to copy file for export: \(error)", .app)
let alert = NSAlert(error: error)
alert.beginSheetModal(for: self.view.window!, completionHandler: { (_) -> Void in
//do nothing
})
}
}
}
}
@IBAction func exportZippedFiles(_ sender: Any?) {
let defaults = UserDefaults.standard
let panel = NSSavePanel()
panel.isExtensionHidden = false
panel.allowedFileTypes = ["zip"]
panel.nameFieldStringValue = session.workspace.name + ".zip"
if let bmarkData = defaults[.lastExportDirectory] {
do {
panel.directoryURL = try (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL)
} catch {
}
}
panel.beginSheetModal(for: view.window!) { response in
do {
let urlbmark = try (panel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
defaults[.lastExportDirectory] = urlbmark
} catch let err as NSError {
Log.warn("why did we get error creating export bookmark: \(err)", .app)
}
panel.close()
guard response == .OK, let destination = panel.url else { return }
self.exportAll(to: destination)
}
}
@IBAction func exportAllFiles(_ sender: Any?) {
let defaults = UserDefaults.standard
let panel = NSOpenPanel()
panel.allowsMultipleSelection = false
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.resolvesAliases = true
panel.canCreateDirectories = true
if let bmarkData = defaults[.lastExportDirectory] {
panel.directoryURL = try? (NSURL(resolvingBookmarkData: bmarkData, options: [], relativeTo: nil, bookmarkDataIsStale: nil) as URL)
}
panel.prompt = NSLocalizedString("Export All Files", comment: "")
panel.message = NSLocalizedString("Select File Destination", comment: "")
panel.beginSheetModal(for: view.window!) { response in
do {
let urlbmark = try (panel.directoryURL as NSURL?)?.bookmarkData(options: [], includingResourceValuesForKeys: nil, relativeTo: nil)
defaults[.lastExportDirectory] = urlbmark
} catch let err as NSError {
Log.warn("why did we get error creating export bookmark: \(err)", .app)
}
panel.close()
guard response == .OK && panel.urls.count > 0, let destination = panel.urls.first else { return }
self.exportAll(to: destination)
}
}
// MARK: - private methods
private func exportAll(to destination: URL) {
let fm = FileManager()
let zip = destination.pathExtension == "zip"
var tmpDir: URL?
let folderDest: URL
if zip {
do {
tmpDir = try fm.createTemporaryDirectory()
folderDest = tmpDir!.appendingPathComponent(destination.deletingPathExtension().lastPathComponent)
try fm.createDirectory(at: folderDest, withIntermediateDirectories: true)
} catch {
appStatus?.presentError(Rc2Error(type: .cocoa, nested: nil, severity: .error, explanation: "Failed to create temporary directory"), session: session)
return
}
} else {
folderDest = destination
}
let urls = self.session.workspace.files.map { (self.session.fileCache.cachedUrl(file: $0), $0.name) }
// use a producer to allow updating of progress
let producer = SignalProducer<ProgressUpdate, Rc2Error> { observer, _ in
var copiedCount: Double = 0
do {
observer.send(value: ProgressUpdate(.start))
for (aUrl, fileName) in urls {
observer.send(value: ProgressUpdate(.value, message: "Exporting \(fileName)", value: copiedCount / Double(urls.count), error: nil, disableInput: true))
let destUrl = folderDest.appendingPathComponent(fileName)
if destUrl.fileExists() { try? fm.removeItem(at: destUrl) }
try fm.copyItem(at: aUrl, to: destUrl)
copiedCount += 1.0
}
if zip {
// need to compress destFolder to a zip file
// TODO: map progress: argument to a Progress object that will be updating observer
do {
try fm.zipItem(at: folderDest, to: destination, shouldKeepParent: true, compressionMethod: .deflate, progress: nil)
} catch {
Log.error("error zipping export: \(error)")
throw Rc2Error(type: .application, nested: error, severity: .error, explanation: "failed to zip files")
}
}
observer.sendCompleted()
} catch let error as NSError {
observer.send(error: Rc2Error(type: .cocoa, nested: error, explanation: "Error exporting file: \(error)"))
Log.error("failed to copy file for export: \(error)", .app)
} catch let rc2error as Rc2Error {
observer.send(error: rc2error)
}
if let tdir = tmpDir {
do { try fm.removeItem(at: tdir) } catch { Log.warn("failed to delete temporary directory") }
}
}
DispatchQueue.global(qos: .userInitiated).async {
producer
.updateProgress(status: self.appStatus!, actionName: NSLocalizedString("Export Files", comment: ""))
.start()
}
}
fileprivate func select(fileId: Int) {
// the id of the file that was created
guard let fidx = self.fileDataIndex(fileId: fileId) else {
Log.warn("selecting unknown file \(fileId)", .app)
return
}
tableView.selectRowIndexes(IndexSet(integer: fidx), byExtendingSelection: false)
}
fileprivate func actuallyPerformDelete(file: AppFile) {
self.session.remove(file: file)
.updateProgress(status: self.appStatus!, actionName: "Delete \(file.name)")
.startWithResult { result in
DispatchQueue.main.async {
switch result {
case .failure(let error):
self.appStatus?.presentError(error, session: self.session)
case .success:
self.delegate?.fileSelectionChanged(nil, forEditing: false)
}
}
}
}
/// prompts for a filename
///
/// - Parameters:
/// - prompt: label shown to user
/// - baseName: base file name (without extension)
/// - type: the type of file being prompted for
/// - handler: called when complete. If value is nil, the user canceled the prompt
private func promptForFilename(prompt: String, baseName: String, type: FileType, handler: @escaping (String?) -> Void)
{
let fileExtension = ".\(type.fileExtension)"
let prompter = InputPrompter(prompt: prompt, defaultValue: baseName + fileExtension, suffix: fileExtension)
prompter.minimumStringLength = type.fileExtension.count + 1
let fileNames = session.workspace.files.map { return $0.name }
prompter.validator = { (proposedName) in
return fileNames.filter({ $0.caseInsensitiveCompare(proposedName) == .orderedSame }).count == 0
}
prompter.prompt(window: self.view.window!) { (gotValue, value) in
guard gotValue, var value = value else { handler(nil); return }
if !value.hasSuffix(fileExtension) {
value += fileExtension
}
handler(value)
}
}
private func validateRename(file: AppFile, newName: String?) -> Bool {
guard var name = newName else { return true } //empty is allowable
if !name.hasSuffix(".\(file.fileType.fileExtension)") {
name += ".\(file.fileType.fileExtension)"
}
guard name.count > 3 else { return false }
//if same name, is valid
guard name.caseInsensitiveCompare(file.name) != .orderedSame else { return true }
//no duplicate names
let fileNames = session.workspace.files.map { return $0.name }
guard fileNames.filter({ $0.caseInsensitiveCompare(name) == .orderedSame }).count == 0 else { return false }
return true
}
private func importFiles(_ files: [FileImporter.FileToImport]) {
let converter = { (iprogress: FileImporter.ImportProgress) -> ProgressUpdate? in
return ProgressUpdate(.value, message: iprogress.status, value: iprogress.percentComplete)
}
do {
fileImporter = try FileImporter(files, fileCache: self.session.fileCache, connectInfo: session.conInfo)
} catch {
let myError = Rc2Error(type: .file, nested: error)
appStatus?.presentError(myError, session: session)
return
}
//save reference so ARC doesn't dealloc importer
fileImporter!.producer()
.updateProgress(status: appStatus!, actionName: "Import", determinate: true, converter: converter)
.start
{ [weak self] event in
switch event {
case .failed(let error):
var message = error.localizedDescription
if let neterror = error.nestedError { message = neterror.localizedDescription }
Log.error("got import error \(message)", .app)
self?.fileImporter = nil //free up importer
case .completed:
NotificationCenter.default.post(name: .filesImported, object: self?.fileImporter!)
self?.fileImporter = nil //free up importer
case .interrupted:
Log.info("import canceled", .app)
self?.fileImporter = nil //free up importer
default:
break
}
}
}
/// returns URL to template for the passed in file type
func fileTemplate(forType fileType: FileType) -> URL? {
do {
let templateDir = try AppInfo.subdirectory(type: .applicationSupportDirectory, named: Resources.fileTemplateDirName)
let userFile = templateDir.appendingPathComponent("default.\(fileType.fileExtension)")
if FileManager.default.fileExists(atPath: userFile.path) {
return userFile
}
} catch {
// ignore error, just use builtin template
}
return Bundle(for: type(of: self)).url(forResource: "default", withExtension: fileType.fileExtension, subdirectory: Resources.fileTemplateDirName)
}
// MARK: - TableView datasource/delegate implementation
func numberOfRows(in tableView: NSTableView) -> Int {
return rowData.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let data = rowData[row]
if data.sectionName != nil {
// swiftlint:disable:next force_cast
let tview = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "string"), owner: nil) as! NSTableCellView
tview.textField!.stringValue = data.sectionName!
return tview
} else {
// swiftlint:disable:next force_cast
let fview = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "file"), owner: nil) as! EditableTableCellView
fview.objectValue = data.file
fview.textField?.stringValue = data.file!.name
fview.infoButton?.tag = row
return fview
}
}
func tableView(_ tableView: NSTableView, isGroupRow row: Int) -> Bool {
return rowData[row].sectionName != nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
if tableView.selectedRow >= 0 {
selectedFile = rowData[tableView.selectedRow].file
} else {
selectedFile = nil
}
adjustForFileSelectionChange()
delegate?.fileSelectionChanged(selectedFile, forEditing: false)
}
func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
return rowData[row].file != nil
}
func tableView(_ tableView: NSTableView, writeRowsWith rowIndexes: IndexSet, to pboard: NSPasteboard) -> Bool {
guard let row = rowIndexes.last, let file = rowData[row].file else { return false }
let url = session.fileCache.cachedUrl(file: file) as NSURL
pboard.declareTypes(url.writableTypes(for: pboard), owner: nil)
url.write(to: pboard)
return true
}
func tableView(_ tableView: NSTableView, validateDrop info: NSDraggingInfo, proposedRow row: Int, proposedDropOperation dropOperation: NSTableView.DropOperation) -> NSDragOperation
{
return importPrompter!.validateTableViewDrop(info)
}
func tableView(_ tableView: NSTableView, acceptDrop info: NSDraggingInfo, row: Int, dropOperation: NSTableView.DropOperation) -> Bool
{
importPrompter!.acceptTableViewDrop(info, workspace: session.workspace, window: view.window!) { (files) in
self.importFiles(files)
}
return true
}
}
// MARK: - FileHandler implementation
extension SidebarFileController: FileHandler {
func filesRefreshed(_ changes: [AppWorkspace.FileChange]) {
//TODO: ideally should figure out what file was changed and animate the tableview update instead of refreshing all rows
loadData()
//preserve selection
let selFile = selectedFile
tableView.reloadData()
if selFile != nil, let idx = rowData.index(where: { $0.file?.fileId ?? -1 == selFile!.fileId }) {
tableView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
}
}
func fileSelectionChanged() {
guard !selectionChangeInProgress else { return }
selectionChangeInProgress = true
// defer { selectionChangeInProgress = false }
guard let file = selectedFile else {
DispatchQueue.main.async {
self.tableView.selectRowIndexes(IndexSet(), byExtendingSelection: false)
self.selectionChangeInProgress = false
}
return
}
guard let idx = fileDataIndex(fileId: file.fileId) else {
Log.info("failed to find file to select", .app)
self.selectionChangeInProgress = false
return
}
DispatchQueue.main.async {
self.tableView.selectRowIndexes(IndexSet(integer: idx), byExtendingSelection: false)
self.selectionChangeInProgress = false
}
}
}
// MARK: - Accessory Classes
//least hackish way to get segment's menu to show immediately if set, otherwise perform control's action
class AddRemoveSegmentedCell: NSSegmentedCell {
override var action: Selector? {
get {
if self.menu(forSegment: self.selectedSegment) != nil { return nil }
return super.action!
}
set { super.action = newValue }
}
}
class FileTableView: NSTableView {
override func menu(for event: NSEvent) -> NSMenu? {
let row = self.row(at: convert(event.locationInWindow, from: nil))
if row != -1 { //if right click is over a row, select that row
selectRowIndexes(IndexSet(integer: row), byExtendingSelection: false)
}
return super.menu(for: event)
}
}
| isc | a5a96ce023d626fbb09f070793f641a8 | 36.253061 | 181 | 0.715204 | 3.837561 | false | false | false | false |
freshteapot/learnalist-ios | learnalist-ios/learnalist-ios/AddEditNavigationController.swift | 1 | 4614 | import UIKit
class AddEditNavigationController: UINavigationController, UINavigationControllerDelegate {
var listType:String = "v0"
var editType:String = "new"
var uuid:String!
init(uuid: String, listType: String) {
super.init(nibName: nil, bundle: nil)
self.listType = listType
self.editType = "edit"
self.uuid = uuid
}
init(listType: String, editType: String) {
super.init(nibName: nil, bundle: nil)
self.listType = listType
self.editType = editType
self.uuid = LearnalistModel.getUUID()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = []
self.delegate = self
let model = UIApplication.getModel()
// There is a chance that the uuid is not uuid and is from_uuid. If a bug appears, it might be linked to this.
if listType == "v1" {
let aList = (self.editType == "edit") ? model.getListByUuid(self.uuid) : AlistV1.NewList(self.uuid)
let vc = V1EditListViewController(
aList: aList as! AlistV1
)
self.setViewControllers([vc], animated: false)
} else if listType == "v2" {
let vc = V2AddEditListItemViewController()
self.setViewControllers([vc], animated: false)
} else {
print("@Todo")
return
}
if self.editType == "new" {
self.toAdd()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
print("in: didShow")
}
public func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
print("in: willShow")
viewController.edgesForExtendedLayout = []
}
public func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
print("in: animationController UINavigationControllerOperation")
return nil
}
public func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
print("in: animationController UIViewControllerAnimatedTransitioning")
return nil
}
func cancelList() {
view.endEditing(true)
print("Cancel List from AddEditNaviationController.")
self.dismiss(animated: false, completion: nil)
}
func afterListSave() {
print("After List Save from AddEditNaviationController.")
self.dismiss(animated: false, completion: nil)
}
func toList() {
print("To List from AddEditNaviationController.")
if listType == "v1" {
self.popViewController(animated: false)
} else if listType == "v2" {
self.popViewController(animated: false)
} else {
print("@Todo")
}
}
func toInfo(info: AlistInfo) {
let vc = EditListInfoViewController(info: info)
if listType == "v1" {
vc.onSave.subscribe(on: self, callback: (self.topViewController as! V1EditListViewController).onSaveInfo)
vc.onDelete.subscribe(on: self, callback: (self.topViewController as! V1EditListViewController).onDeleteList)
} else if listType == "v2" {
// vc.onSave.subscribe(on: self, callback: (self.topViewController as! V2EditListViewController).onSaveInfo)
} else {
print("@Todo")
}
self.pushViewController(vc, animated: false)
}
func toAdd() {
if listType == "v1" {
let vc = V1AddEditListItemViewController()
vc.onSave.subscribe(on: self, callback: (self.topViewController as! V1EditListViewController).onSaveItem)
self.pushViewController(vc, animated: false)
} else if listType == "v2" {
let vc = V2AddEditListItemViewController()
self.pushViewController(vc, animated: false)
} else {
print("@Todo")
}
}
}
| mit | 7c6e4440ec533d0e33f8ad793c2955ce | 35.912 | 253 | 0.64456 | 4.887712 | false | false | false | false |
cathandnya/Pixitail | pixiViewer/Classes/Widget/WidgetViewController.swift | 1 | 9056 | //
// WidgetViewController.swift
// pixiViewer
//
// Created by nya on 2014/10/14.
//
//
import UIKit
import NotificationCenter
let sectionHeaderHeight: CGFloat = 16
class WidgetViewController: UITableViewController, NCWidgetProviding {
fileprivate var activityViews = Dictionary<Int, UIActivityIndicatorView>()
override func viewDidLoad() {
super.viewDidLoad()
NSLog("viewDidLoad")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
EntriesItemList.sharedInstance.refresh()
for item in EntriesItemList.sharedInstance.list {
item.entries.load()
}
reloadData()
}
deinit {
NSLog("deinit")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
refresh()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if let block = handler {
NSLog("viewWillDisappear completionHandler")
block(.noData)
handler = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
if EntriesItemList.sharedInstance.count == 0 {
return 1
} else {
return EntriesItemList.sharedInstance.count
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if EntriesItemList.sharedInstance.count == 0 {
return 44
} else {
return WidgetCell.heightForWidth(self.view.frame.size.width)
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if EntriesItemList.sharedInstance.count == 0 {
return 0
} else {
return sectionHeaderHeight
}
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if EntriesItemList.sharedInstance.count == 0 {
return nil
}
let view = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: sectionHeaderHeight))
view.backgroundColor = UIColor.clear
let label = UILabel(frame: CGRect(x: 5, y: 0, width: 310 - 21 - 5, height: sectionHeaderHeight))
label.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
label.backgroundColor = UIColor.clear
label.font = UIFont.boldSystemFont(ofSize: 11)
label.textColor = UIColor.white.withAlphaComponent(0.7)
label.text = EntriesItemList.sharedInstance[section].name
view.addSubview(label)
var activityView: UIActivityIndicatorView
if let activity = activityViews[section] {
activityView = activity
activityView.removeFromSuperview()
} else {
activityView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.white)
activityView.hidesWhenStopped = true
activityView.layer.setValue(0.6, forKeyPath: "transform.scale")
activityViews[section] = activityView
}
activityView.frame = CGRect(x: 320 - 21 - 5, y: -2, width: 21, height: 21)
activityView.autoresizingMask = UIViewAutoresizing.flexibleLeftMargin
view.addSubview(activityView)
return view
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if EntriesItemList.sharedInstance.count == 0 {
return tableView.dequeueReusableCell(withIdentifier: "no_item", for: indexPath) as UITableViewCell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! WidgetCell
cell.selectionStyle = UITableViewCellSelectionStyle.none
cell.entries = EntriesItemList.sharedInstance[(indexPath as NSIndexPath).section].entries
cell.context = self.extensionContext
return cell
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if EntriesItemList.sharedInstance.count == 0 {
var url: URL?
#if PIXITAIL
url = URL(string: "pixitail://org.cathand.pixitail/settings/widget")
#else
url = URL(string: "illustail://org.cathand.illustail/settings/widget")
#endif
if let u = url {
extensionContext?.open(u, completionHandler: nil)
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
func updatePreferredContentSize() {
if EntriesItemList.sharedInstance.count == 0 {
preferredContentSize = CGSize(width: 0, height: 44)
} else {
preferredContentSize = CGSize(width: 0, height: CGFloat(EntriesItemList.sharedInstance.count) * (WidgetCell.heightForWidth(self.view.frame.size.width) + sectionHeaderHeight))
}
}
func reloadData() {
updatePreferredContentSize()
tableView.reloadData()
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return UIEdgeInsets.zero
//marginInsets = defaultMarginInsets
//return defaultMarginInsets
}
fileprivate var handler: ((NCUpdateResult) -> Void)?
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
NSLog("widgetPerformUpdateWithCompletionHandler")
completionHandler(.noData)
//handler = completionHandler
refresh()
}
fileprivate var updateResult = NCUpdateResult.noData
fileprivate var loaded = true
func refreshEnd() {
if loaded {
return
}
for item in EntriesItemList.sharedInstance.list {
if item.entries.isLoading {
return;
}
}
if let block = handler {
NSLog("completionHandler")
block(.noData)
handler = nil
}
loaded = true
}
func refresh() {
if !loaded {
if let block = handler {
NSLog("completionHandler")
block(.noData)
handler = nil
}
return
}
updateResult = .noData
loaded = false
if EntriesItemList.sharedInstance.list.count > 0 {
var section = 0
for item in EntriesItemList.sharedInstance.list {
weak var activity = activityViews[section]
activity?.startAnimating()
DispatchQueue.global().async { [weak self] in
if let me = self {
let ret = item.entries.refresh()
if ret == NCUpdateResult.failed {
me.updateResult = ret
} else if ret == NCUpdateResult.newData {
me.updateResult = ret
}
item.entries.save()
DispatchQueue.main.async {
activity?.stopAnimating()
if let me = self {
for cell in me.tableView.visibleCells as! [WidgetCell] {
cell.setNeedsLayout()
}
me.refreshEnd()
}
}
}
}
section += 1
}
} else {
if let block = handler {
NSLog("completionHandler")
block(.noData)
handler = nil
}
loaded = true
}
reloadData()
}
}
| mit | 84d2a7dacc48867acdf4651a9da9a66c | 27.749206 | 177 | 0.699426 | 4.413255 | false | false | false | false |
Adorkable-forkable/SwiftRecord | Example-iOS/SwiftRecordExample/SwiftRecordExample/AppDelegate.swift | 1 | 6142 | //
// AppDelegate.swift
// SwiftRecordExample
//
// Created by Zaid on 5/8/15.
// Copyright (c) 2015 ark. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.ark.SwiftRecordExample" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SwiftRecordExample", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SwiftRecordExample.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 6a0655d1bb482f65042a3023bcd18d3c | 54.333333 | 290 | 0.716542 | 5.756326 | false | false | false | false |
cplaverty/KeitaiWaniKani | WaniKaniKit/Database/ResourceRepository.swift | 1 | 16684 | //
// ResourceRepository.swift
// WaniKaniKit
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import FMDB
import os
public extension NSNotification.Name {
static let waniKaniAssignmentsDidChange = NSNotification.Name("waniKaniAssignmentsDidChange")
static let waniKaniLevelProgressionDidChange = NSNotification.Name("waniKaniLevelProgressionDidChange")
static let waniKaniReviewStatisticsDidChange = NSNotification.Name("waniKaniReviewStatisticsDidChange")
static let waniKaniStudyMaterialsDidChange = NSNotification.Name("waniKaniStudyMaterialsDidChange")
static let waniKaniSubjectsDidChange = NSNotification.Name("waniKaniSubjectsDidChange")
static let waniKaniUserInformationDidChange = NSNotification.Name("waniKaniUserInformationDidChange")
}
public extension CFNotificationName {
private static let notificationBaseName = "uk.me.laverty.keitaiWaniKani.notifications"
static let waniKaniAssignmentsDidChange = CFNotificationName("\(notificationBaseName).waniKaniAssignmentsDidChange" as CFString)
static let waniKaniLevelProgressionDidChange = CFNotificationName("\(notificationBaseName).waniKaniLevelProgressionDidChange" as CFString)
static let waniKaniReviewStatisticsDidChange = CFNotificationName("\(notificationBaseName).waniKaniReviewStatisticsDidChange" as CFString)
static let waniKaniStudyMaterialsDidChange = CFNotificationName("\(notificationBaseName).waniKaniStudyMaterialsDidChange" as CFString)
static let waniKaniSubjectsDidChange = CFNotificationName("\(notificationBaseName).waniKaniSubjectsDidChange" as CFString)
static let waniKaniUserInformationDidChange = CFNotificationName("\(notificationBaseName).waniKaniUserInformationDidChange" as CFString)
}
extension ResourceType {
var associatedCFNotificationName: CFNotificationName {
switch self {
case .assignments:
return .waniKaniAssignmentsDidChange
case .levelProgression:
return .waniKaniLevelProgressionDidChange
case .reviewStatistics:
return .waniKaniReviewStatisticsDidChange
case .studyMaterials:
return .waniKaniStudyMaterialsDidChange
case .subjects:
return .waniKaniSubjectsDidChange
case .user:
return .waniKaniUserInformationDidChange
}
}
var associatedNotificationName: NSNotification.Name {
switch self {
case .assignments:
return .waniKaniAssignmentsDidChange
case .levelProgression:
return .waniKaniLevelProgressionDidChange
case .reviewStatistics:
return .waniKaniReviewStatisticsDidChange
case .studyMaterials:
return .waniKaniStudyMaterialsDidChange
case .subjects:
return .waniKaniSubjectsDidChange
case .user:
return .waniKaniUserInformationDidChange
}
}
func getLastUpdateDate(in database: FMDatabase) throws -> Date? {
let table = Tables.resourceLastUpdate
let query = "SELECT \(table.dataUpdatedAt) FROM \(table) WHERE \(table.resourceType) = ?"
return try database.dateForQuery(query, values: [rawValue])
}
func setLastUpdateDate(_ lastUpdate: Date, in database: FMDatabase) throws {
os_log("Setting last update date for resource %@ to %@", type: .debug, rawValue, lastUpdate as NSDate)
let table = Tables.resourceLastUpdate
let query = """
INSERT OR REPLACE INTO \(table.name)
(\(table.resourceType.name), \(table.dataUpdatedAt.name))
VALUES (?, ?)
"""
let values: [Any] = [rawValue, lastUpdate]
try database.executeUpdate(query, values: values)
}
}
public class ResourceRepository: ResourceRepositoryReader {
private let api: WaniKaniAPIProtocol
public init(databaseManager: DatabaseManager, api: WaniKaniAPIProtocol) {
self.api = api
super.init(databaseManager: databaseManager)
}
public convenience init(databaseManager: DatabaseManager, apiKey: String, networkActivityDelegate: NetworkActivityDelegate? = nil) {
let api = WaniKaniAPI(apiKey: apiKey)
api.networkActivityDelegate = networkActivityDelegate
self.init(databaseManager: databaseManager, api: api)
}
public func getLastUpdateDate(for resourceType: ResourceType) throws -> Date? {
guard let databaseQueue = self.databaseQueue else {
throw ResourceRepositoryError.noDatabase
}
return try databaseQueue.inDatabase { database in
return try resourceType.getLastUpdateDate(in: database)
}
}
public func getEarliestLastUpdateDate(for resourceTypes: [ResourceType]) throws -> Date? {
guard let databaseQueue = self.databaseQueue else {
throw ResourceRepositoryError.noDatabase
}
return try databaseQueue.inDatabase { database in
return try resourceTypes.lazy.compactMap({ try $0.getLastUpdateDate(in: database) }).min()
}
}
@discardableResult public func updateUser(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
guard let databaseQueue = self.databaseQueue else {
let progress = Progress(totalUnitCount: 1)
progress.completedUnitCount = 1
DispatchQueue.global().async {
completionHandler(.error(ResourceRepositoryError.noDatabase))
}
return progress
}
let resourceType = ResourceType.user
let requestStartTime = Date()
let lastUpdate = try? databaseQueue.inDatabase { database in
return try resourceType.getLastUpdateDate(in: database)
}
if let lastUpdate = lastUpdate, requestStartTime.timeIntervalSince(lastUpdate) < minimumFetchInterval {
os_log("Skipping resource fetch: %.3f < %.3f", type: .info, requestStartTime.timeIntervalSince(lastUpdate), minimumFetchInterval)
let progress = Progress(totalUnitCount: 1)
progress.completedUnitCount = 1
DispatchQueue.global().async {
completionHandler(.noData)
}
return progress
}
return api.fetchResource(ofType: .user) { result in
switch result {
case let .failure(error):
os_log("Got error when fetching: %@", type: .error, error as NSError)
completionHandler(.error(error))
case let .success(resource):
guard let data = resource.data as? UserInformation else {
os_log("No data available", type: .debug)
self.notifyNoData(databaseQueue: databaseQueue, resourceType: resourceType, requestStartTime: requestStartTime, completionHandler: completionHandler)
return
}
if let lastUpdate = lastUpdate, resource.dataUpdatedAt < lastUpdate {
os_log("No change from last update", type: .debug)
self.notifyNoData(databaseQueue: databaseQueue, resourceType: resourceType, requestStartTime: requestStartTime, completionHandler: completionHandler)
return
}
var databaseError: Error? = nil
databaseQueue.inImmediateTransaction { (database, rollback) in
os_log("Writing to database", type: .debug)
do {
try data.write(to: database)
os_log("Setting last update date for resource %@ to %@", type: .info, resourceType.rawValue, requestStartTime as NSDate)
try resourceType.setLastUpdateDate(requestStartTime, in: database)
} catch {
databaseError = error
rollback.pointee = true
}
}
if let error = databaseError {
os_log("Error writing to database", type: .error, error as NSError)
completionHandler(.error(error))
return
}
os_log("Fetch of resource %@ finished successfully", type: .info, resourceType.rawValue)
DispatchQueue.main.async {
self.postNotifications(for: resourceType)
}
completionHandler(.success)
}
}
}
@discardableResult public func updateAssignments(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
return updateResourceCollection(ofType: .assignments,
minimumFetchInterval: minimumFetchInterval,
requestForLastUpdateDate: { .assignments(filter: $0.map { AssignmentFilter(updatedAfter: $0) }) },
completionHandler: completionHandler)
}
@discardableResult public func updateLevelProgression(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
return updateResourceCollection(ofType: .levelProgression,
minimumFetchInterval: minimumFetchInterval,
requestForLastUpdateDate: { .levelProgressions(filter: $0.map { LevelProgressionFilter(updatedAfter: $0) }) },
completionHandler: completionHandler)
}
@discardableResult public func updateReviewStatistics(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
return updateResourceCollection(ofType: .reviewStatistics,
minimumFetchInterval: minimumFetchInterval,
requestForLastUpdateDate: { .reviewStatistics(filter: $0.map { ReviewStatisticFilter(updatedAfter: $0) }) },
completionHandler: completionHandler)
}
@discardableResult public func updateStudyMaterials(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
return updateResourceCollection(ofType: .studyMaterials,
minimumFetchInterval: minimumFetchInterval,
requestForLastUpdateDate: { .studyMaterials(filter: $0.map { StudyMaterialFilter(updatedAfter: $0) }) },
completionHandler: completionHandler)
}
@discardableResult public func updateSubjects(minimumFetchInterval: TimeInterval, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
return updateResourceCollection(ofType: .subjects,
minimumFetchInterval: minimumFetchInterval,
requestForLastUpdateDate: { .subjects(filter: $0.map { SubjectFilter(updatedAfter: $0) }) },
completionHandler: completionHandler)
}
private func updateResourceCollection(ofType resourceType: ResourceType, minimumFetchInterval: TimeInterval, requestForLastUpdateDate: (Date?) -> ResourceCollectionRequestType, completionHandler: @escaping (ResourceRefreshResult) -> Void) -> Progress {
guard let databaseQueue = self.databaseQueue else {
let progress = Progress(totalUnitCount: 1)
progress.completedUnitCount = 1
DispatchQueue.global().async {
completionHandler(.error(ResourceRepositoryError.noDatabase))
}
return progress
}
let requestStartTime = Date()
let lastUpdate = try? databaseQueue.inDatabase { database in
return try resourceType.getLastUpdateDate(in: database)
}
if let lastUpdate = lastUpdate, requestStartTime.timeIntervalSince(lastUpdate) < minimumFetchInterval {
os_log("Skipping resource fetch: %.3f < %.3f", type: .debug, requestStartTime.timeIntervalSince(lastUpdate), minimumFetchInterval)
let progress = Progress(totalUnitCount: 1)
progress.completedUnitCount = 1
DispatchQueue.global().async {
completionHandler(.noData)
}
return progress
}
if let lastUpdate = lastUpdate {
os_log("Fetching resource %@ (updated since %@)", type: .info, resourceType.rawValue, lastUpdate as NSDate)
} else {
os_log("Fetching resource %@", type: .info, resourceType.rawValue)
}
let type = requestForLastUpdateDate(lastUpdate)
var totalPagesReceived = 0
return api.fetchResourceCollection(ofType: type) { result -> Bool in
switch result {
case .failure(WaniKaniAPIError.noContent):
os_log("No data available", type: .debug)
self.notifyNoData(databaseQueue: databaseQueue, resourceType: resourceType, requestStartTime: requestStartTime, completionHandler: completionHandler)
return false
case let .failure(error):
os_log("Got error when fetching: %@", type: .error, error as NSError)
completionHandler(.error(error))
return false
case let .success(resources):
guard resources.totalCount > 0 else {
os_log("No data available (response nil or total count zero)", type: .debug)
self.notifyNoData(databaseQueue: databaseQueue, resourceType: resourceType, requestStartTime: requestStartTime, completionHandler: completionHandler)
return false
}
totalPagesReceived += 1
let isLastPage = totalPagesReceived == resources.estimatedPageCount
var databaseError: Error? = nil
databaseQueue.inImmediateTransaction { (database, rollback) in
os_log("Writing %d entries to database (page %d of %d)", type: .debug, resources.data.count, totalPagesReceived, resources.estimatedPageCount)
do {
try resources.write(to: database)
if isLastPage {
try resourceType.setLastUpdateDate(requestStartTime, in: database)
}
} catch {
databaseError = error
rollback.pointee = true
}
}
if let error = databaseError {
os_log("Error writing to database", type: .error, error as NSError)
completionHandler(.error(error))
return false
}
if isLastPage {
os_log("Fetch of resource %@ finished successfully", type: .info, resourceType.rawValue)
DispatchQueue.main.async {
self.postNotifications(for: resourceType)
}
completionHandler(.success)
return false
}
return true
}
}
}
private func notifyNoData(databaseQueue: FMDatabaseQueue, resourceType: ResourceType, requestStartTime: Date, completionHandler: (ResourceRefreshResult) -> Void) {
do {
try databaseQueue.inDatabase { database in
try resourceType.setLastUpdateDate(requestStartTime, in: database)
}
completionHandler(.noData)
} catch {
completionHandler(.error(error))
}
}
private func postNotifications(for resourceType: ResourceType) {
os_log("Sending notifications for resource %@", type: .debug, resourceType.rawValue)
NotificationCenter.default.post(name: resourceType.associatedNotificationName, object: self)
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), resourceType.associatedCFNotificationName, nil, nil, true)
}
}
| mit | 9c702647f6fde628e7952cb0c3fd2cf1 | 47.923754 | 256 | 0.619613 | 5.872228 | false | false | false | false |
Urinx/Device-9 | Device 9/Device 9/Constants.swift | 1 | 680 | //
// Constants.swift
// Device 9
//
// Created by Eular on 12/8/15.
// Copyright © 2015 Eular. All rights reserved.
//
import Foundation
let WXCode = "wx6349772cbf442ce6"
let AppDownload = "http://pre.im/cctv"
let Urinx = "http://urinx.github.io"
let ShareTimelineNotif = "shareToTimeline"
let ShareFriendNotif = "shareToFriend"
let SettingNotif = "gotoSetting"
let UserDefaultSuiteName = "group.device9SharedDefaults"
let WXShareTitle = "Device 9"
let WXShareDescription = "超用心的誠意之作,讓通知中心變得從來沒有這麼好用"
let AuthorMobile = "+8618827359451"
let AuthorEmail = "[email protected]"
let PreAppKey = "32851046811c8f4775fc9ee605751cf8" | apache-2.0 | c2a3cb42f4ccf1a00be6aa711fe16397 | 27.727273 | 56 | 0.762282 | 2.731602 | false | false | false | false |
mentrena/SyncKit | Example/CoreData/SyncKitCoreDataExample/SyncKitCoreDataExample/Company/CoreData/CoreDataCompanyWireframe.swift | 1 | 2044 | //
// CoreDataCompanyWireframe.swift
// SyncKitCoreDataExample
//
// Created by Manuel Entrena on 21/06/2019.
// Copyright © 2019 Manuel Entrena. All rights reserved.
//
import UIKit
import CoreData
import SyncKit
class CoreDataCompanyWireframe: CompanyWireframe {
let navigationController: UINavigationController
let managedObjectContext: NSManagedObjectContext
let employeeWireframe: EmployeeWireframe
let synchronizer: CloudKitSynchronizer?
let settingsManager: SettingsManager
init(navigationController: UINavigationController, managedObjectContext: NSManagedObjectContext, employeeWireframe: EmployeeWireframe, synchronizer: CloudKitSynchronizer?, settingsManager: SettingsManager) {
self.navigationController = navigationController
self.managedObjectContext = managedObjectContext
self.employeeWireframe = employeeWireframe
self.synchronizer = synchronizer
self.settingsManager = settingsManager
}
func show() {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "Company") as! CompanyViewController
let interactor = CoreDataCompanyInteractor(managedObjectContext: managedObjectContext,
shareController: synchronizer)
let presenter = DefaultCompanyPresenter(view: viewController,
interactor: interactor,
wireframe: self,
synchronizer: synchronizer,
canEdit: true,
settingsManager: settingsManager)
viewController.presenter = presenter
interactor.delegate = presenter
navigationController.viewControllers = [viewController]
}
func show(company: Company, canEdit: Bool) {
employeeWireframe.show(company: company, canEdit: canEdit)
}
}
| mit | 3101ed989c80a82a6b2953abdcb73707 | 43.413043 | 211 | 0.658346 | 6.787375 | false | false | false | false |
peterk9/card-2.io-iOS-SDK-master | SampleApp-Swift/SampleApp-Swift/FinalViewController.swift | 1 | 1725 | //
// FinalViewController.swift
// RBCInstaBank
//
// Created by Kevin Peters on 2015-08-14.
// Copyright © 2015 Punskyy, Roman. All rights reserved.
//
import UIKit
class FinalViewController: UIViewController {
@IBOutlet weak var eSignBtn: UIButton!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var thankyou: UILabel!
@IBOutlet weak var rbcLogi: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
self.rbcLogi.alpha = 0
self.thankyou.alpha = 0
self.rbcLogi.hidden = true
self.thankyou.hidden = true
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func eSignButtonPress(sender: AnyObject) {
self.eSignBtn.hidden = true
self.label1.hidden = true
self.label2.hidden = true
UIView.animateWithDuration(1.0, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
self.rbcLogi.hidden = false
self.thankyou.hidden = false
self.rbcLogi.alpha = 1
self.thankyou.alpha = 1
}, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f0928888c858f7fd815e1231b46badd6 | 29.785714 | 125 | 0.649072 | 4.364557 | false | false | false | false |
peacemoon/HanekeSwift | Haneke.playground/section-1.swift | 24 | 1111 | // Open this playground from the Haneke workspace after building the Haneke framework. See: http://stackoverflow.com/a/24049021/143378
import Haneke
/// Initialize a JSON cache and fetch/cache a JSON response.
func example1() {
let cache = Cache<JSON>(name: "github")
let URL = NSURL(string: "https://api.github.com/users/haneke")!
cache.fetch(URL: URL).onSuccess { JSON in
println(JSON.dictionary?["bio"])
}
}
/// Set a image view image from a url using the shared image cache and resizing.
func example2() {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let URL = NSURL(string: "https://avatars.githubusercontent.com/u/8600207?v=2")!
imageView.hnk_setImageFromURL(URL)
}
/// Set and fetch data from the shared data cache
func example3() {
let cache = Shared.dataCache
let data = "SGVscCEgSSdtIHRyYXBwZWQgaW4gYSBCYXNlNjQgc3RyaW5nIQ==".asData()
cache.set(value: data, key: "secret")
cache.fetch(key: "secret").onSuccess { data in
println(NSString(data:data, encoding:NSUTF8StringEncoding))
}
}
| apache-2.0 | bd5aa82653aa4a42d1d0d71c1748a85d | 33.71875 | 134 | 0.692169 | 3.504732 | false | false | false | false |
PseudoSudoLP/Bane | Carthage/Checkouts/Moya/Moya+RxSwift.swift | 1 | 3013 | //
// Moya+RxSwift.swift
// Moya
//
// Created by Andre Carvalho on 2015-06-05
// Copyright (c) 2015 Ash Furrow. All rights reserved.
//
import Foundation
import RxSwift
/// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures.
public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> {
/// Current requests that have not completed or errored yet.
/// Note: Do not access this directly. It is public only for unit-testing purposes (sigh).
public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>()
/// Initializes a reactive provider.
override public init(endpointsClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping(), endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEnpointResolution(), stubResponses: Bool = false, stubBehavior: MoyaStubbedBehavior = MoyaProvider.DefaultStubBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil) {
super.init(endpointsClosure: endpointsClosure, endpointResolver: endpointResolver, stubResponses: stubResponses, networkActivityClosure: networkActivityClosure)
}
/// Designated request-making method.
public func request(token: T) -> Observable<MoyaResponse> {
let endpoint = self.endpoint(token)
return defer { [weak self] () -> Observable<MoyaResponse> in
if let existingObservable = self?.inflightRequests[endpoint] {
return existingObservable
}
let observable: Observable<MoyaResponse> = AnonymousObservable { observer in
let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in
if let error = error {
if let statusCode = statusCode {
observer.on(.Error(NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo)))
} else {
observer.on(.Error(error))
}
} else {
if let data = data {
observer.on(.Next(RxBox(MoyaResponse(statusCode: statusCode!, data: data, response: response))))
}
observer.on(.Completed)
}
}
return AnonymousDisposable {
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = nil
cancellableToken?.cancel()
objc_sync_exit(weakSelf)
}
}
}
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = observable
objc_sync_exit(weakSelf)
}
return observable
}
}
}
| mit | ec8a4a4d30253d8a88a07061c2ce6449 | 43.970149 | 349 | 0.592433 | 5.6742 | false | false | false | false |
tourani/GHIssue | OAuth2PodApp/Profile.swift | 1 | 895 | //
// Profile.swift
// OAuth2PodApp
//
// Created by Sanjay on 1/25/17.
//
import UIKit
class Profile: NSObject {
var avatar_url: String
var created_at: String
var email: String
var followers: Int
var following: Int
var company: String
var location: String
var login: String
var name: String
var public_repos: Int
init?(avatar_url: String, created_at: String, email: String, followers: Int, following: Int, company: String, location: String, login: String, name: String, public_repos: Int) {
self.avatar_url = avatar_url
self.created_at = created_at
self.email = email
self.followers = followers
self.following = following
self.company = company
self.location = location
self.login = login
self.name = name
self.public_repos = public_repos
}
}
| mit | dfb9daf3712b1a2204ebf208d68d3032 | 22.552632 | 181 | 0.622346 | 4.013453 | false | false | false | false |
shohei/firefox-ios | UITests/SearchTests.swift | 2 | 3114 | /* 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 WebKit
private let LabelPrompt = "Turn on search suggestions?"
private let HintSuggestionButton = "Searches for the suggestion"
class SearchTests: KIFTestCase {
func testOptInPrompt() {
var found: Bool
// Ensure that the prompt appears.
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterText("foobar", intoViewWithAccessibilityLabel: LabelAddressAndSearch)
found = tester().tryFindingViewWithAccessibilityLabel(LabelPrompt, error: nil)
XCTAssertTrue(found, "Prompt is shown")
// Ensure that no suggestions are visible before answering the prompt.
found = tester().tryFindingViewWithAccessibilityHint(HintSuggestionButton)
XCTAssertFalse(found, "No suggestion shown before prompt selection")
// Ensure that suggestions are visible after selecting Yes.
tester().tapViewWithAccessibilityLabel("Yes")
found = tester().tryFindingViewWithAccessibilityHint(HintSuggestionButton)
XCTAssertTrue(found, "Found suggestions after choosing Yes")
tester().tapViewWithAccessibilityLabel("Cancel")
// Return to the search screen, and make sure our choice was remembered.
found = tester().tryFindingViewWithAccessibilityLabel(LabelPrompt, error: nil)
XCTAssertFalse(found, "Prompt is not shown")
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterText("foobar", intoViewWithAccessibilityLabel: LabelAddressAndSearch)
found = tester().tryFindingViewWithAccessibilityHint(HintSuggestionButton)
XCTAssertTrue(found, "Search suggestions are still enabled")
tester().tapViewWithAccessibilityLabel("Cancel")
resetSuggestionsPrompt()
// Ensure that the prompt appears.
tester().tapViewWithAccessibilityIdentifier("url")
tester().clearTextFromAndThenEnterText("foobar", intoViewWithAccessibilityLabel: LabelAddressAndSearch)
found = tester().tryFindingViewWithAccessibilityLabel(LabelPrompt, error: nil)
XCTAssertTrue(found, "Prompt is shown")
// Ensure that no suggestions are visible before answering the prompt.
found = tester().tryFindingViewWithAccessibilityHint(HintSuggestionButton)
XCTAssertFalse(found, "No suggestion buttons are shown")
// Ensure that no suggestions are visible after selecting No.
tester().tapViewWithAccessibilityLabel("No")
found = tester().tryFindingViewWithAccessibilityHint(HintSuggestionButton)
XCTAssertFalse(found, "No suggestions after choosing No")
tester().tapViewWithAccessibilityLabel("Cancel")
resetSuggestionsPrompt()
}
private func resetSuggestionsPrompt() {
NSNotificationCenter.defaultCenter().postNotificationName("SearchEnginesPromptReset", object: nil)
}
}
| mpl-2.0 | f94d0f705a431832650871eab7f0a425 | 46.907692 | 111 | 0.735067 | 6.381148 | false | true | false | false |
wenghengcong/Coderpursue | BeeFun/Pods/SwiftyStoreKit/SwiftyStoreKit/SwiftyStoreKit.swift | 1 | 15893 | //
// SwiftyStoreKit.swift
// SwiftyStoreKit
//
// Copyright (c) 2015 Andrea Bizzotto ([email protected])
//
// 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 StoreKit
public class SwiftyStoreKit {
private let productsInfoController: ProductsInfoController
fileprivate let paymentQueueController: PaymentQueueController
fileprivate let receiptVerificator: InAppReceiptVerificator
init(productsInfoController: ProductsInfoController = ProductsInfoController(),
paymentQueueController: PaymentQueueController = PaymentQueueController(paymentQueue: SKPaymentQueue.default()),
receiptVerificator: InAppReceiptVerificator = InAppReceiptVerificator()) {
self.productsInfoController = productsInfoController
self.paymentQueueController = paymentQueueController
self.receiptVerificator = receiptVerificator
}
// MARK: private methods
fileprivate func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) {
return productsInfoController.retrieveProductsInfo(productIds, completion: completion)
}
fileprivate func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) {
retrieveProductsInfo(Set([productId])) { result -> Void in
if let product = result.retrievedProducts.first {
self.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
} else if let error = result.error {
completion(.error(error: SKError(_nsError: error as NSError)))
} else if let invalidProductId = result.invalidProductIDs.first {
let userInfo = [ NSLocalizedDescriptionKey: "Invalid product id: \(invalidProductId)" ]
let error = NSError(domain: SKErrorDomain, code: SKError.paymentInvalid.rawValue, userInfo: userInfo)
completion(.error(error: SKError(_nsError: error)))
} else {
let error = NSError(domain: SKErrorDomain, code: SKError.unknown.rawValue, userInfo: nil)
completion(.error(error: SKError(_nsError: error)))
}
}
}
fileprivate func purchase(product: SKProduct, quantity: Int, atomically: Bool, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) {
paymentQueueController.startPayment(Payment(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox) { result in
completion(self.processPurchaseResult(result))
})
}
fileprivate func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
paymentQueueController.restorePurchases(RestorePurchases(atomically: atomically, applicationUsername: applicationUsername) { results in
let results = self.processRestoreResults(results)
completion(results)
})
}
fileprivate func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
paymentQueueController.completeTransactions(CompleteTransactions(atomically: atomically, callback: completion))
}
fileprivate func finishTransaction(_ transaction: PaymentTransaction) {
paymentQueueController.finishTransaction(transaction)
}
private func processPurchaseResult(_ result: TransactionResult) -> PurchaseResult {
switch result {
case .purchased(let purchase):
return .success(purchase: purchase)
case .failed(let error):
return .error(error: error)
case .restored(let purchase):
return .error(error: storeInternalError(description: "Cannot restore product \(purchase.productId) from purchase path"))
}
}
private func processRestoreResults(_ results: [TransactionResult]) -> RestoreResults {
var restoredPurchases: [Purchase] = []
var restoreFailedPurchases: [(SKError, String?)] = []
for result in results {
switch result {
case .purchased(let purchase):
let error = storeInternalError(description: "Cannot purchase product \(purchase.productId) from restore purchases path")
restoreFailedPurchases.append((error, purchase.productId))
case .failed(let error):
restoreFailedPurchases.append((error, nil))
case .restored(let purchase):
restoredPurchases.append(purchase)
}
}
return RestoreResults(restoredPurchases: restoredPurchases, restoreFailedPurchases: restoreFailedPurchases)
}
private func storeInternalError(code: SKError.Code = SKError.unknown, description: String = "") -> SKError {
let error = NSError(domain: SKErrorDomain, code: code.rawValue, userInfo: [ NSLocalizedDescriptionKey: description ])
return SKError(_nsError: error)
}
}
extension SwiftyStoreKit {
// MARK: Singleton
fileprivate static let sharedInstance = SwiftyStoreKit()
// MARK: Public methods - Purchases
/**
* Return NO if this device is not able or allowed to make payments
*/
public class var canMakePayments: Bool {
return SKPaymentQueue.canMakePayments()
}
/**
* Retrieve products information
* - Parameter productIds: The set of product identifiers to retrieve corresponding products for
* - Parameter completion: handler for result
*/
public class func retrieveProductsInfo(_ productIds: Set<String>, completion: @escaping (RetrieveResults) -> Void) {
return sharedInstance.retrieveProductsInfo(productIds, completion: completion)
}
/**
* Purchase a product
* - Parameter productId: productId as specified in iTunes Connect
* - Parameter quantity: quantity of the product to be purchased
* - Parameter atomically: whether the product is purchased atomically (e.g. finishTransaction is called immediately)
* - Parameter applicationUsername: an opaque identifier for the user’s account on your system
* - Parameter completion: handler for result
*/
public class func purchaseProduct(_ productId: String, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping (PurchaseResult) -> Void) {
sharedInstance.purchaseProduct(productId, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
}
/**
* Purchase a product
* - Parameter product: product to be purchased
* - Parameter quantity: quantity of the product to be purchased
* - Parameter atomically: whether the product is purchased atomically (e.g. finishTransaction is called immediately)
* - Parameter applicationUsername: an opaque identifier for the user’s account on your system
* - Parameter completion: handler for result
*/
public class func purchaseProduct(_ product: SKProduct, quantity: Int = 1, atomically: Bool = true, applicationUsername: String = "", simulatesAskToBuyInSandbox: Bool = false, completion: @escaping ( PurchaseResult) -> Void) {
sharedInstance.purchase(product: product, quantity: quantity, atomically: atomically, applicationUsername: applicationUsername, simulatesAskToBuyInSandbox: simulatesAskToBuyInSandbox, completion: completion)
}
/**
* Restore purchases
* - Parameter atomically: whether the product is purchased atomically (e.g. finishTransaction is called immediately)
* - Parameter applicationUsername: an opaque identifier for the user’s account on your system
* - Parameter completion: handler for result
*/
public class func restorePurchases(atomically: Bool = true, applicationUsername: String = "", completion: @escaping (RestoreResults) -> Void) {
sharedInstance.restorePurchases(atomically: atomically, applicationUsername: applicationUsername, completion: completion)
}
/**
* Complete transactions
* - Parameter atomically: whether the product is purchased atomically (e.g. finishTransaction is called immediately)
* - Parameter completion: handler for result
*/
public class func completeTransactions(atomically: Bool = true, completion: @escaping ([Purchase]) -> Void) {
sharedInstance.completeTransactions(atomically: atomically, completion: completion)
}
/**
* Finish a transaction
* Once the content has been delivered, call this method to finish a transaction that was performed non-atomically
* - Parameter transaction: transaction to finish
*/
public class func finishTransaction(_ transaction: PaymentTransaction) {
sharedInstance.finishTransaction(transaction)
}
/**
* Register a handler for SKPaymentQueue.shouldAddStorePayment delegate method in iOS 11
*/
public static var shouldAddStorePaymentHandler: ShouldAddStorePaymentHandler? {
didSet {
sharedInstance.paymentQueueController.shouldAddStorePaymentHandler = shouldAddStorePaymentHandler
}
}
/**
* Register a handler for paymentQueue(_:updatedDownloads:)
*/
public static var updatedDownloadsHandler: UpdatedDownloadsHandler? {
didSet {
sharedInstance.paymentQueueController.updatedDownloadsHandler = updatedDownloadsHandler
}
}
public class func start(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.start(downloads)
}
public class func pause(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.pause(downloads)
}
public class func resume(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.resume(downloads)
}
public class func cancel(_ downloads: [SKDownload]) {
sharedInstance.paymentQueueController.cancel(downloads)
}
}
extension SwiftyStoreKit {
// MARK: Public methods - Receipt verification
/**
* Return receipt data from the application bundle. This is read from Bundle.main.appStoreReceiptURL
*/
public static var localReceiptData: Data? {
return sharedInstance.receiptVerificator.appStoreReceiptData
}
/**
* Verify application receipt
* - Parameter validator: receipt validator to use
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter completion: handler for result
*/
public class func verifyReceipt(using validator: ReceiptValidator, forceRefresh: Bool = false, completion: @escaping (VerifyReceiptResult) -> Void) {
sharedInstance.receiptVerificator.verifyReceipt(using: validator, forceRefresh: forceRefresh, completion: completion)
}
/**
* Fetch application receipt
* - Parameter forceRefresh: If true, refreshes the receipt even if one already exists.
* - Parameter completion: handler for result
*/
public class func fetchReceipt(forceRefresh: Bool, completion: @escaping (FetchReceiptResult) -> Void) {
sharedInstance.receiptVerificator.fetchReceipt(forceRefresh: forceRefresh, completion: completion)
}
/**
* Verify the purchase of a Consumable or NonConsumable product in a receipt
* - Parameter productId: the product id of the purchase to verify
* - Parameter inReceipt: the receipt to use for looking up the purchase
* - return: either notPurchased or purchased
*/
public class func verifyPurchase(productId: String, inReceipt receipt: ReceiptInfo) -> VerifyPurchaseResult {
return InAppReceipt.verifyPurchase(productId: productId, inReceipt: receipt)
}
/**
* Verify the validity of a subscription (auto-renewable, free or non-renewing) in a receipt.
*
* This method extracts all transactions matching the given productId and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date to determine its validity.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter productId: The product id of the subscription to verify.
* - Parameter receipt: The receipt to use for looking up the subscription.
* - Parameter validUntil: Date to check against the expiry date of the subscription. This is only used if a date is not found in the receipt.
* - return: Either .notPurchased or .purchased / .expired with the expiry date found in the receipt.
*/
public class func verifySubscription(ofType type: SubscriptionType, productId: String, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: [productId], inReceipt: receipt, validUntil: date)
}
/**
* Verify the validity of a set of subscriptions in a receipt.
*
* This method extracts all transactions matching the given productIds and sorts them by date in descending order. It then compares the first transaction expiry date against the receipt date, to determine its validity.
* - Note: You can use this method to check the validity of (mutually exclusive) subscriptions in a subscription group.
* - Remark: The type parameter determines how the expiration dates are calculated for all subscriptions. Make sure all productIds match the specified subscription type to avoid incorrect results.
* - Parameter type: .autoRenewable or .nonRenewing.
* - Parameter productIds: The product ids of the subscriptions to verify.
* - Parameter receipt: The receipt to use for looking up the subscriptions
* - Parameter validUntil: Date to check against the expiry date of the subscriptions. This is only used if a date is not found in the receipt.
* - return: Either .notPurchased or .purchased / .expired with the expiry date found in the receipt.
*/
public class func verifySubscriptions(ofType type: SubscriptionType = .autoRenewable, productIds: Set<String>, inReceipt receipt: ReceiptInfo, validUntil date: Date = Date()) -> VerifySubscriptionResult {
return InAppReceipt.verifySubscriptions(ofType: type, productIds: productIds, inReceipt: receipt, validUntil: date)
}
}
| mit | 78833c3b3511afb9ae2259e5f0a6e6f6 | 49.595541 | 230 | 0.718134 | 5.483949 | false | false | false | false |
gogunskiy/The-Name | NameMe/Classes/UserInterface/ViewControllers/NMMenuViewController/views/NMSearchViewBaseCell.swift | 1 | 726 | //
// NMSearchViewBaseCell
// NameMe
//
// Created by Vladimir Gogunsky on 1/9/15.
// Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved.
//
import UIKit
enum ActionType: Int {
case nameChanged = 1
case originChanged = 2
case groupTypeChanged = 3
case sortTypeChanged = 4
}
class NMSearchViewBaseCell : UITableViewCell {
var delegate : NMSearchViewDelegate!
var query: NMQuery!
func update(query: NMQuery) {
self.query = query
}
func updateValue() {
}
}
protocol NMSearchViewDelegate : NSObjectProtocol {
func dataHasBeenChanged(cell: NMSearchViewBaseCell, data: NSDictionary)
func performedCellAction(cell: NMSearchViewBaseCell)
} | mit | 1543897c357f640d7439ead0a2cfcc2b | 19.194444 | 75 | 0.687328 | 4.055866 | false | false | false | false |
shorlander/firefox-ios | Account/FxALoginStateMachine.swift | 8 | 9628 | /* 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 FxA
import Shared
import XCGLogger
import Deferred
// TODO: log to an FxA-only, persistent log file.
private let log = Logger.syncLogger
// TODO: fill this in!
private let KeyUnwrappingError = NSError(domain: "org.mozilla", code: 1, userInfo: nil)
protocol FxALoginClient {
func keyPair() -> Deferred<Maybe<KeyPair>>
func keys(_ keyFetchToken: Data) -> Deferred<Maybe<FxAKeysResponse>>
func sign(_ sessionToken: Data, publicKey: PublicKey) -> Deferred<Maybe<FxASignResponse>>
}
class FxALoginStateMachine {
let client: FxALoginClient
// The keys are used as a set, to prevent cycles in the state machine.
var stateLabelsSeen = [FxAStateLabel: Bool]()
init(client: FxALoginClient) {
self.client = client
}
func advance(fromState state: FxAState, now: Timestamp) -> Deferred<FxAState> {
stateLabelsSeen.updateValue(true, forKey: state.label)
return self.advanceOne(fromState: state, now: now).bind { (newState: FxAState) in
let labelAlreadySeen = self.stateLabelsSeen.updateValue(true, forKey: newState.label) != nil
if labelAlreadySeen {
// Last stop!
return Deferred(value: newState)
}
return self.advance(fromState: newState, now: now)
}
}
fileprivate func advanceOne(fromState state: FxAState, now: Timestamp) -> Deferred<FxAState> {
// For convenience. Without type annotation, Swift complains about types not being exact.
let separated: Deferred<FxAState> = Deferred(value: SeparatedState())
let doghouse: Deferred<FxAState> = Deferred(value: DoghouseState())
let same: Deferred<FxAState> = Deferred(value: state)
log.info("Advancing from state: \(state.label.rawValue)")
switch state.label {
case .married:
let state = state as! MarriedState
log.debug("Checking key pair freshness.")
if state.isKeyPairExpired(now) {
log.info("Key pair has expired; transitioning to CohabitingBeforeKeyPair.")
return advanceOne(fromState: state.withoutKeyPair(), now: now)
}
log.debug("Checking certificate freshness.")
if state.isCertificateExpired(now) {
log.info("Certificate has expired; transitioning to CohabitingAfterKeyPair.")
return advanceOne(fromState: state.withoutCertificate(), now: now)
}
log.info("Key pair and certificate are fresh; staying Married.")
return same
case .cohabitingBeforeKeyPair:
let state = state as! CohabitingBeforeKeyPairState
log.debug("Generating key pair.")
return self.client.keyPair().bind { result in
if let keyPair = result.successValue {
log.info("Generated key pair! Transitioning to CohabitingAfterKeyPair.")
let newState = CohabitingAfterKeyPairState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: keyPair, keyPairExpiresAt: now + OneMonthInMilliseconds)
return Deferred(value: newState)
} else {
log.error("Failed to generate key pair! Something is horribly wrong; transitioning to Separated in the hope that the error is transient.")
return separated
}
}
case .cohabitingAfterKeyPair:
let state = state as! CohabitingAfterKeyPairState
log.debug("Signing public key.")
return client.sign(state.sessionToken, publicKey: state.keyPair.publicKey).bind { result in
if let response = result.successValue {
log.info("Signed public key! Transitioning to Married.")
let newState = MarriedState(sessionToken: state.sessionToken,
kA: state.kA, kB: state.kB,
keyPair: state.keyPair, keyPairExpiresAt: state.keyPairExpiresAt,
certificate: response.certificate, certificateExpiresAt: now + OneDayInMilliseconds)
return Deferred(value: newState)
} else {
if let error = result.failureValue as? FxAClientError {
switch error {
case let .remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated.")
return separated
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
case let .local(localError) where localError.domain == NSURLErrorDomain:
log.warning("Local networking error: \(result.failureValue!). Assuming transient and not transitioning.")
return same
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .engagedBeforeVerified, .engagedAfterVerified:
let state = state as! ReadyForKeys
log.debug("Fetching keys.")
return client.keys(state.keyFetchToken).bind { result in
if let response = result.successValue {
if let kB = response.wrapkB.xoredWith(state.unwrapkB) {
log.info("Unwrapped keys response. Transition to CohabitingBeforeKeyPair.")
self.notifyAccountVerified()
let newState = CohabitingBeforeKeyPairState(sessionToken: state.sessionToken,
kA: response.kA, kB: kB)
return Deferred(value: newState)
} else {
log.error("Failed to unwrap keys response! Transitioning to Separated in order to fetch new initial datum.")
return separated
}
} else {
if let error = result.failureValue as? FxAClientError {
log.error("Error \(error.description) \(error.description)")
switch error {
case let .remote(remoteError):
if remoteError.isUpgradeRequired {
log.error("Upgrade required: \(error.description)! Transitioning to Doghouse.")
return doghouse
} else if remoteError.isInvalidAuthentication {
log.error("Invalid authentication: \(error.description)! Transitioning to Separated in order to fetch new initial datum.")
return separated
} else if remoteError.isUnverified {
log.warning("Account is not yet verified; not transitioning.")
return same
} else if remoteError.code < 200 || remoteError.code >= 300 {
log.error("Unsuccessful HTTP request: \(error.description)! Assuming error is transient and not transitioning.")
return same
} else {
log.error("Unknown error: \(error.description). Transitioning to Separated.")
return separated
}
case let .local(localError) where localError.domain == NSURLErrorDomain:
log.warning("Local networking error: \(result.failureValue!). Assuming transient and not transitioning.")
return same
default:
break
}
}
log.error("Unknown error: \(result.failureValue!). Transitioning to Separated.")
return separated
}
}
case .separated, .doghouse:
// We can't advance from the separated state (we need user input) or the doghouse (we need a client upgrade).
log.warning("User interaction required; not transitioning.")
return same
}
}
fileprivate func notifyAccountVerified() {
NotificationCenter.default.post(name: NotificationFirefoxAccountVerified, object: nil, userInfo: nil)
}
}
| mpl-2.0 | b8faea1639a726c132fc63db36dd43e0 | 51.901099 | 159 | 0.555983 | 5.810501 | false | false | false | false |
debugsquad/Hyperborea | Hyperborea/Model/Settings/MSettingsBackgroundItem.swift | 1 | 829 | import UIKit
class MSettingsBackgroundItem
{
private let letter:NSAttributedString
var positionY:CGFloat
let positionX:CGFloat
let width:CGFloat
let height:CGFloat
let speedY:CGFloat
init(
letter:NSAttributedString,
positionX:CGFloat,
positionY:CGFloat,
width:CGFloat,
height:CGFloat,
speedY:CGFloat)
{
self.letter = letter
self.positionX = positionX
self.positionY = positionY
self.width = width
self.height = height
self.speedY = speedY
}
//MARK: public
func draw(context:CGContext)
{
let rect:CGRect = CGRect(
x:positionX,
y:positionY,
width:width,
height:height)
letter.draw(in:rect)
}
}
| mit | 23d61325b4ebe4e894a0050341becb51 | 19.725 | 41 | 0.570567 | 4.737143 | false | false | false | false |
criticalmaps/criticalmaps-ios | CriticalMapsKit/Sources/ApiClient/LocationsAndChatDataService.swift | 1 | 1214 | import Foundation
import SharedModels
// MARK: Interface
/// A Service to send and fetch locations and chat messages from the Criticl Maps API
public struct LocationsAndChatDataService {
public typealias Body = SendLocationAndChatMessagesPostBody
public var getLocationsAndSendMessages: @Sendable (Body) async throws -> LocationAndChatMessages
public init(getLocationsAndSendMessages: @Sendable @escaping (Body) async throws -> LocationAndChatMessages) {
self.getLocationsAndSendMessages = getLocationsAndSendMessages
}
}
// MARK: Live
public extension LocationsAndChatDataService {
static func live(apiClient: APIClient = .live()) -> Self {
Self { body in
let request: Request = .locationsAndChats(body: try? body.encoded())
let (data, _) = try await apiClient.send(request)
return try data.decoded()
}
}
}
// MARK: Mocks and failing used for previews and tests
public extension LocationsAndChatDataService {
static let noop = Self(
getLocationsAndSendMessages: { _ in LocationAndChatMessages(locations: [:], chatMessages: [:]) }
)
static let failing = Self(
getLocationsAndSendMessages: { _ in
throw NSError(domain: "", code: 1)
}
)
}
| mit | 3be5e46c0d3cf278ed252ea916659e6a | 28.609756 | 112 | 0.733937 | 4.289753 | false | false | false | false |
Harekaze/Harekaze-iOS | Harekaze/ViewControllers/Introduction/FindServerTableViewController.swift | 1 | 4951 | /**
*
* FindServerTableViewController.swift
* Harekaze
* Created by Yuki MIZUNO on 2018/02/11.
*
* Copyright (c) 2016-2018, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import InAppSettingsKit
import SwiftyUserDefaults
import PKHUD
import APIKit
class FindServerTableViewController: ServerSettingTableViewController {
// MARK: - Private instance fileds
private var url: String = ""
private var pageViewController: NavigationPageViewController? {
return self.parent?.parent as? NavigationPageViewController
}
private func checkConnection() {
// Save values
ChinachuAPI.Config[.address] = url
HUD.show(.labeledRotatingImage(image: PKHUDAssets.progressCircularImage, title: nil, subtitle: "Connecting..."))
let start = DispatchTime.now()
ChinachuAPI.StatusRequest().send { result in
DispatchQueue.main.asyncAfter(deadline: start + 2) {
HUD.hide()
let errorMessage: String
switch result {
case .success(let data):
if data["connectedCount"] as? Int != nil {
self.pageViewController?.goSkipNext()
return
} else {
errorMessage = "Data parse error."
}
case .failure(let error):
switch error {
case .responseError(let responseError as ResponseError):
switch responseError {
case .unacceptableStatusCode(let statusCode):
switch statusCode {
case 401:
self.pageViewController?.goNext()
return
default:
errorMessage = ChinachuAPI.parseErrorMessage(error)
}
default:
errorMessage = ChinachuAPI.parseErrorMessage(error)
}
default:
errorMessage = ChinachuAPI.parseErrorMessage(error)
}
}
let errorDialog = AlertController("Connection failed", "\(errorMessage) Please check the URL and server.")
errorDialog.addAction(AlertButton(.default, title: "OK")) {}
self.pageViewController?.present(errorDialog, animated: false, completion: nil)
}
}
}
// MARK: - View deinitialization
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageViewController?.nextButtonAction = {
self.checkConnection()
}
}
// MARK: - Table view data source / delegate
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let label = UILabel()
label.textColor = .white
label.font = .boldSystemFont(ofSize: 20)
label.text = self.tableView(tableView, titleForHeaderInSection: section)?.uppercased()
return label
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.row == dataSource.count {
return
}
let service = dataSource[indexPath.row]
url = "\(service.type.contains("https") ? "https" : "http")://\(service.hostName!):\(service.port)"
checkConnection()
}
// MARK: - Text field delegate
override func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if let oldText = textField.text, let range = Range(range, in: oldText),
let pageViewController = self.parent?.parent as? NavigationPageViewController {
url = oldText.replacingCharacters(in: range, with: string)
let regex = "^((https|http)://)([\\w_\\.\\-]+)(:\\d{1,5})?(/[^/]+)*$"
let predicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [regex])
pageViewController.isNextButtonEnabled = predicate.evaluate(with: url)
}
return true
}
}
| bsd-3-clause | 304824c6fdcef4c8b9bfb32bad9190fd | 35.404412 | 135 | 0.725914 | 4.275475 | false | false | false | false |
the-blue-alliance/the-blue-alliance-ios | tba-unit-tests/View Controllers/Match/MatchViewControllerTests.swift | 1 | 2104 | import XCTest
@testable import MyTBAKit
@testable import TBAData
@testable import The_Blue_Alliance
class MatchViewControllerTests: TBATestCase {
var match: Match {
return matchViewController.match
}
var matchViewController: MatchViewController!
override func setUp() {
super.setUp()
let match = insertMatch()
matchViewController = MatchViewController(match: match, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
}
override func tearDown() {
matchViewController = nil
super.tearDown()
}
func test_title() {
XCTAssertEqual(matchViewController.navigationTitle, "Quals 1")
XCTAssertEqual(matchViewController.navigationSubtitle, "@ 2018ctsc")
}
func test_title_event() {
let event = insertDistrictEvent()
match.eventRaw = event
let vc = MatchViewController(match: match, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
XCTAssertEqual(vc.navigationTitle, "Quals 1")
XCTAssertEqual(vc.navigationSubtitle, "@ 2018 Kettering University #1 District")
}
func test_showsInfo() {
matchViewController.viewDidLoad()
XCTAssert(matchViewController.children.contains(where: { (viewController) -> Bool in
return viewController is MatchInfoViewController
}))
}
func test_showsBreakdown() {
matchViewController.viewDidLoad()
XCTAssert(matchViewController.children.contains(where: { (viewController) -> Bool in
return viewController is MatchBreakdownViewController
}))
}
func test_doesNotShowBreakdown() {
let match = insertMatch(eventKey: "2014miket_qm1")
let vc = MatchViewController(match: match, statusService: statusService, urlOpener: urlOpener, myTBA: myTBA, dependencies: dependencies)
XCTAssertFalse(vc.children.contains(where: { (viewController) -> Bool in
return viewController is MatchBreakdownViewController
}))
}
}
| mit | 4e306652daccfbf9fdaf6a5f422297ac | 31.875 | 157 | 0.69249 | 5.119221 | false | true | false | false |
marinehero/LeetCode-Solutions-in-Swift | Solutions/Solutions/Easy/Easy_007_Reverse_Integer.swift | 4 | 1606 | /*
https://oj.leetcode.com/problems/reverse-integer/
#7 Reverse Integer
Level: easy
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Have you thought about this?
Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!
If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
Inspired by @wshaoxuan at https://oj.leetcode.com/discuss/120/how-do-we-handle-the-overflow-case
*/
//Int.max 9,223,372,036,854,775,807
//Int.min -9,223,372,036,854,775,808
class Easy_007_Reverse_Integer {
// O (N)
class func reverse(x: Int) -> Int {
var neg = false
var i: Int = x
if x < 0 {
neg = true
i = -x
}
var res:UInt = 0
while i/10 > 0 {
res = res * 10 + UInt(i % 10)
i = i / 10
}
res = res * 10 + UInt(i % 10)
if neg == false && res > 9223372036854775807 {
return 0
} else if neg == true && res > 9223372036854775808 {
return 0
}
if neg {
return (-1) * Int(res)
} else {
return Int(res)
}
}
} | mit | 71540dcc07afaa602b83332916aff267 | 24.507937 | 170 | 0.605853 | 3.625282 | false | false | false | false |
TabletopAssistant/DiceKit | DiceKit/FrequencyDistributionIndex.swift | 1 | 1665 | //
// FrequencyDistributionIndex.swift
// DiceKit
//
// Created by Brentley Jones on 8/1/15.
// Copyright © 2015 Brentley Jones. All rights reserved.
//
public struct FrequencyDistributionIndex<Outcome: FrequencyDistributionOutcomeType>: ForwardIndexType {
typealias OrderedOutcomes = [Outcome]
let index: Int
let orderedOutcomes: OrderedOutcomes
static func startIndex(orderedOutcomes: OrderedOutcomes) -> FrequencyDistributionIndex {
return FrequencyDistributionIndex(index: 0, orderedOutcomes: orderedOutcomes)
}
static func endIndex(orderedOutcomes: OrderedOutcomes) -> FrequencyDistributionIndex {
return FrequencyDistributionIndex(index: orderedOutcomes.count, orderedOutcomes: orderedOutcomes)
}
init(index: Int, orderedOutcomes: OrderedOutcomes) {
self.index = index
self.orderedOutcomes = orderedOutcomes
}
var value: Outcome? {
guard index >= 0 && index < orderedOutcomes.count else {
return nil
}
return orderedOutcomes[index]
}
public func successor() -> FrequencyDistributionIndex {
let count = orderedOutcomes.count
guard index < count else {
return FrequencyDistributionIndex(index: count, orderedOutcomes: orderedOutcomes)
}
return FrequencyDistributionIndex(index: index + 1, orderedOutcomes: orderedOutcomes)
}
}
// MARK: - Equatable
public func == <V>(lhs: FrequencyDistributionIndex<V>, rhs: FrequencyDistributionIndex<V>) -> Bool {
return lhs.index == rhs.index && lhs.orderedOutcomes == rhs.orderedOutcomes
}
| apache-2.0 | adc6a3018378aae94785df5d1c919b3b | 31 | 105 | 0.688101 | 4.700565 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/Permissions/PermissionView.swift | 1 | 6730 | //
// PermissionView.swift
// EclipseSoundscapes
//
// Created by Arlindo Goncalves on 8/26/17.
//
// Copyright © 2017 Arlindo Goncalves.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see [http://www.gnu.org/licenses/].
//
// For Contact email: [email protected]
import UIKit
/// Inform the permission's have been accepted or skipped
protocol PermissionViewDelegate: class {
/// Send notice that permission view has finished
func didFinish()
}
class PermissionView: UIView {
weak var delegate: PermissionViewDelegate?
/// Tracker for Location Permission button touch
fileprivate var didPressLocation = false
/// Tracker for Notification Permission button touch
fileprivate var didPressNotification = false
/// Permissions to handle
var permissions : [PermissionType]!
var titleLabel : UILabel = {
var label = UILabel()
label.text = localizedString(key: "PermissionViewTitle")
label.textColor = .black
label.accessibilityTraits = .header
label.textAlignment = .center
label.font = UIFont.getDefautlFont(.bold, size: 20)
label.numberOfLines = 0
return label
}()
var iconImageView : UIImageView = {
var iv = UIImageView(image: #imageLiteral(resourceName: "EclipseSoundscapes-Eclipse"))
iv.contentMode = .scaleAspectFill
iv.backgroundColor = .clear
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
var laterLabel : UILabel = {
var label = UILabel()
label.text = localizedString(key: "PermissionViewLaterLabelTitle")
label.textColor = .black
label.textAlignment = .center
label.font = UIFont.getDefautlFont(.condensedMedium, size: 14)
return label
}()
lazy var laterButton : UIButton = {
var button = UIButton(type: .system)
button.translatesAutoresizingMaskIntoConstraints = false
button.addSqueeze()
button.backgroundColor = UIColor.black.withAlphaComponent(0.5)
button.titleLabel?.font = UIFont.getDefautlFont(.extraBold, size: (button.titleLabel?.font.pointSize)!)
button.setTitleColor(.white, for: .normal)
button.setTitle(localizedString(key: "PermissionViewLaterButtonTitle"), for: .normal)
button.addTarget(self, action: #selector(later), for: .touchUpInside)
button.accessibilityHint = localizedString(key: "PermissionViewLaterButtonHint")
return button
}()
var stackView: UIStackView = {
var sv = UIStackView()
sv.translatesAutoresizingMaskIntoConstraints = false
sv.alignment = .fill
sv.distribution = .fillProportionally
sv.axis = .vertical
sv.spacing = 10
return sv
}()
required init(for permissions: [PermissionType]) {
super.init(frame: .zero)
self.permissions = permissions
backgroundColor = UIColor.init(r: 227, g: 94, b: 5)
setupViews()
}
/// Setup and layout view's subviews
func setupViews() {
addSubview(titleLabel)
addSubview(iconImageView)
addSubview(stackView)
addSubview(laterLabel)
addSubview(laterButton)
titleLabel.anchorWithConstantsToTop(safeAreaLayoutGuide.topAnchor, left: leftAnchor, bottom: iconImageView.topAnchor, right: rightAnchor, topConstant: 20, leftConstant: 68, bottomConstant: 20, rightConstant: 68)
// ImageView
iconImageView.setSize(175, height: 175)
iconImageView.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
// StackView - Contains the Permission Buttons
stackView.anchor(nil, left: leftAnchor, bottom: nil, right: rightAnchor, topConstant: 0, leftConstant: 20, bottomConstant: 20, rightConstant: 20, widthConstant: 0, heightConstant: 0)
stackView.center(in: self)
// Stack buttons
for permissionType in permissions {
let permission: Permission
switch permissionType {
case .notification:
permission = NotificationPermission()
case .locationWhenInUse:
permission = LocationPermission()
}
let permissionBtn = PermissionButton(permission: permission)
permissionBtn.setSize(stackView.frame.width, height: 50)
permissionBtn.delegate = self
stackView.addArrangedSubview(permissionBtn)
}
// Later Label
laterLabel.anchor(nil, left: leftAnchor, bottom: laterButton.topAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 10, rightConstant: 0, widthConstant: 0, heightConstant: 30)
// Later Button
laterButton.leftAnchor.constraint(greaterThanOrEqualTo: leftAnchor, constant: 16).isActive = true
laterButton.rightAnchor.constraint(greaterThanOrEqualTo: rightAnchor, constant: -16).isActive = true
laterButton.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor, constant: -32).isActive = true
laterButton.centerXAnchor.constraint(equalTo: centerXAnchor).isActive = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
laterButton.layer.cornerRadius = laterButton.bounds.height/2
}
/// Tell the delegate that permission cell's job has been completed
@objc func later() {
delegate?.didFinish()
}
}
extension PermissionView: PermissionButtonDelegate {
func didPressPermission(for type: PermissionType) {
switch type {
case .notification:
if didPressNotification == false {
didPressNotification = true
}
case .locationWhenInUse:
if didPressLocation == false {
didPressLocation = true
}
}
if didPressNotification && didPressLocation {
delegate?.didFinish()
}
}
}
| gpl-3.0 | 20e760829d72611151260eeacc48d55a | 36.803371 | 219 | 0.664586 | 5.148432 | false | false | false | false |
szpnygo/firefox-ios | Sync/LoginPayload.swift | 15 | 4080 | /* 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 XCGLogger
private let log = XCGLogger.defaultInstance()
public class LoginPayload: CleartextPayloadJSON {
private static let OptionalStringFields = [
"formSubmitURL",
"httpRealm",
]
private static let OptionalNumericFields = [
"timeLastUsed",
"timeCreated",
"timePasswordChanged",
"timesUsed",
]
private static let RequiredStringFields = [
"hostname",
"username",
"password",
"usernameField",
"passwordField",
]
public class func fromJSON(json: JSON) -> LoginPayload? {
let p = LoginPayload(json)
if p.isValid() {
return p
}
return nil
}
override public func isValid() -> Bool {
if !super.isValid() {
return false
}
if self["deleted"].isBool {
return true
}
if !LoginPayload.RequiredStringFields.every({ self[$0].isString }) {
return false
}
if !LoginPayload.OptionalStringFields.every({ field in
let val = self[field]
// Yup, 404 is not found, so this means "string or nothing".
let valid = val.isString || val.isNull || val.asError?.code == 404
if !valid {
log.debug("Field \(field) is invalid: \(val)")
}
return valid
}) {
return false
}
if !LoginPayload.OptionalNumericFields.every({ field in
let val = self[field]
// Yup, 404 is not found, so this means "number or nothing".
// We only check for number because we're including timestamps as NSNumbers.
let valid = val.isNumber || val.isNull || val.asError?.code == 404
if !valid {
log.debug("Field \(field) is invalid: \(val)")
}
return valid
}) {
return false
}
return true
}
public var hostname: String {
return self["hostname"].asString!
}
public var username: String {
return self["username"].asString!
}
public var password: String {
return self["password"].asString!
}
public var usernameField: String {
return self["usernameField"].asString!
}
public var passwordField: String {
return self["passwordField"].asString!
}
public var formSubmitURL: String? {
return self["formSubmitURL"].asString
}
public var httpRealm: String? {
return self["httpRealm"].asString
}
private func timestamp(field: String) -> Timestamp? {
let json = self[field]
if let i = json.asInt64 where i > 0 {
return Timestamp(i)
}
return nil
}
public var timesUsed: Int? {
return self["timesUsed"].asInt
}
public var timeCreated: Timestamp? {
return self.timestamp("timeCreated")
}
public var timeLastUsed: Timestamp? {
return self.timestamp("timeLastUsed")
}
public var timePasswordChanged: Timestamp? {
return self.timestamp("timePasswordChanged")
}
override public func equalPayloads(obj: CleartextPayloadJSON) -> Bool {
if let p = obj as? LoginPayload {
if !super.equalPayloads(p) {
return false;
}
if p.deleted || self.deleted {
return self.deleted == p.deleted
}
// If either record is deleted, these other fields might be missing.
// But we just checked, so we're good to roll on.
return LoginPayload.RequiredStringFields.every({ field in
p[field].asString == self[field].asString
})
// TODO: optional fields.
}
return false
}
}
| mpl-2.0 | c7b7798b9a59f4da62a0d50f393a2bd2 | 25.666667 | 88 | 0.56299 | 4.927536 | false | false | false | false |
xsown/SectorProgressView | SectorProgressView/SectorProgressView.swift | 1 | 5365 | //
// SectorProgressView.swift
// SectorProgressView
//
// Created by Shi Xu on 15/12/24.
// Copyright © 2015 Shi Xu. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
class SectorProgressView: UIView {
var progress:Double = 0.0
var fillColor = UIColor(red: 0.0, green: 0, blue: 0, alpha: 0.5)
var circleBorderWidth:CGFloat = 2.0
var radius:CGFloat {
get {
return circleRadius
}
set {
circleRadius = min(newValue, bounds.size.width / 2)
}
}
var animationDuration:NSTimeInterval = 2.0
func setProgress(progress:Double, animated:Bool) {
if animated {
startProgress = self.progress
endProgress = progress
print("start:\(startProgress), end:\(endProgress)")
animationStopTime = animationDuration * abs(endProgress - startProgress)
if let displayLink = self.displayLink {
displayLink.invalidate()
}
let displayLink = CADisplayLink(target: self, selector: "updateProgress")
startTimestamp = CACurrentMediaTime()
displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self.displayLink = displayLink
}
else {
self.progress = progress
self.setNeedsDisplay()
}
}
private var degrees:Double {
return progress * 360.0
}
private lazy var circleRadius:CGFloat = self.bounds.size.height / 2 * 0.8
private var fanRadius:CGFloat {
return circleRadius - circleBorderWidth
}
private var viewCenter:CGPoint {
return CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
}
private var displayLink:CADisplayLink?
private var animationStopTime:CFTimeInterval = 0.0
private var startProgress = 0.0
private var endProgress = 0.0
private var startTimestamp:CFTimeInterval = 0.0
private var timeProgress:CFTimeInterval {
return displayLink!.timestamp - startTimestamp
}
func updateProgress() {
progress = startProgress + timeProgress / animationStopTime * (endProgress - startProgress)
if progress > startProgress && progress > endProgress {
progress = endProgress
}
else if progress < startProgress && progress < endProgress {
progress = endProgress
}
setNeedsDisplay()
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColor(context, CGColorGetComponents(fillColor.CGColor))
CGContextAddRect(context, bounds)
CGContextAddPath(context, createCirclePath())
CGContextAddPath(context, createFanPath())
CGContextEOFillPath(context)
if let displayLink = self.displayLink {
if timeProgress >= animationStopTime {
displayLink.invalidate()
self.displayLink = nil
}
}
}
private func radians(degrees:Double) -> Double {
return degrees * M_PI / 180.0
}
private func degrees(radians:Double) -> Double {
return radians * 180.0 / M_PI
}
private func createCirclePath() -> CGMutablePathRef {
let path = CGPathCreateMutable()
let startAngle = CGFloat(radians(0.0))
let endAngle = CGFloat(radians(360.0))
CGPathMoveToPoint(path, nil, viewCenter.x, viewCenter.y - circleRadius)
CGPathAddArc(path, nil, viewCenter.x, viewCenter.y, circleRadius, startAngle, endAngle, false)
return path
}
private func createFanPath() -> CGMutablePathRef {
let startAngle = CGFloat(radians(-90.0))
let endAngle = CGFloat(radians(degrees + 270.0))
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, viewCenter.x, 0)
CGPathAddArc(path, nil, viewCenter.x, viewCenter.y, fanRadius, startAngle, endAngle, false)
CGPathAddLineToPoint(path, nil, viewCenter.x, viewCenter.y)
CGPathAddLineToPoint(path, nil, viewCenter.x, 0)
return path
}
}
| mit | d2f9737bbff71b268e6f7b64d42ccac8 | 40.581395 | 464 | 0.664802 | 4.975881 | false | false | false | false |
MisterPear/CheckerboardView | Example/CheckerboardView/ViewController.swift | 1 | 1431 | //
// ViewController.swift
// CheckerboardView
//
// Created by Patryk Gruszka on 04/18/2017.
// Copyright (c) 2017 Patryk Gruszka. All rights reserved.
//
import UIKit
import CheckerboardView
class ViewController: UIViewController {
@IBOutlet weak var outletCheckerboardView: CheckerboardView!
override func viewDidLoad() {
super.viewDidLoad()
let middle = (UIScreen.main.bounds.size.width - 150) / 2
let realCheckerboardView = CheckerboardView(frame: CGRect(x: middle, y: 32, width: 150, height: 150), lines: 8, columns: 8)
view.addSubview(realCheckerboardView)
}
@IBAction func actionAddLine(_ sender: Any) {
outletCheckerboardView.lines += 1
}
@IBAction func actionAddColumn(_ sender: Any) {
outletCheckerboardView.columns += 1
}
@IBAction func actionRemoveLine(_ sender: Any) {
outletCheckerboardView.lines -= 1
}
@IBAction func actionRemoveColumn(_ sender: Any) {
outletCheckerboardView.columns -= 1
}
@IBAction func actionRandomColor(_ sender: Any) {
outletCheckerboardView.randomColor()
}
@IBAction func actionRandomFirstColor(_ sender: Any) {
outletCheckerboardView.randomFirstColor()
}
@IBAction func actionRandomSecondColor(_ sender: Any) {
outletCheckerboardView.randomSecondColor()
}
}
| mit | 88f49aa2b60e743c5a33fb9f8d0f07f3 | 25.018182 | 131 | 0.651992 | 4.336364 | false | false | false | false |
LeeMinglu/WeiBo_Swift3.0 | WeiBo_Swift3.0/WeiBo_Swift3.0/View/LSWeiboCell.swift | 1 | 3231 | //
// LSWeiboCell.swift
// WeiBo_Swift3.0
//
// Created by 李明禄 on 2016/11/28.
// Copyright © 2016年 SocererGroup. All rights reserved.
//
import UIKit
class LSWeiboCell: UITableViewCell {
var iconImageView: UIImageView!
var nameLabel: UILabel!
var vipView: UIImageView!
var picView: UIImageView!
var textView: UILabel!
let fontLbName = UIFont.systemFont(ofSize: 15)
let fontLbText = UIFont.systemFont(ofSize: 13)
//2.重写frame的方法
var weiBoFrame: LSWeiboFrame! {
didSet {
let weiBo = weiBoFrame.weiBo!
//设置frame
self.iconImageView.frame = weiBoFrame.iconFrame
self.nameLabel.frame = weiBoFrame.nameFrame
self.vipView.frame = weiBoFrame.vipFrame
self.textView.frame = weiBoFrame.textFrame!
self.picView.frame = weiBoFrame.picFrame!
//设置data
self.iconImageView.image = UIImage.init(named: weiBo.icon!)
self.nameLabel.text = weiBo.name!
self.textView.text = weiBo.text!
if weiBo.vip {
self.nameLabel!.textColor = UIColor.red
self.vipView.isHidden = false
}else {
self.nameLabel!.textColor = UIColor.blue
self.vipView.isHidden = true
}
if (weiBo.picture == nil) {
self.picView.isHidden = true
} else {
self.picView.image = UIImage.init(named: weiBo.picture!)
self.picView.isHidden = false
}
}
}
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
}
//MARK: 1.重写initWithStyle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
if !self.isEqual(nil) {
let icon = UIImageView.init()
self.iconImageView = icon
self.addSubview(iconImageView)
let name = UILabel.init()
name.sizeToFit()
name.adjustsFontSizeToFitWidth = true
nameLabel = name
name.font = fontLbName
self.addSubview(self.nameLabel)
let vipView = UIImageView.init(image: UIImage.init(named: "vip"))
self.vipView = vipView
self.addSubview(self.vipView)
let textView = UILabel.init()
textView.font = fontLbText
textView.sizeToFit()
textView.numberOfLines = 0
textView.adjustsFontSizeToFitWidth = true
self.textView = textView
self.addSubview(self.textView)
let picView = UIImageView()
self.picView = picView
self.addSubview(self.picView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 7d3e07af84d56c78e828c8573374ab38 | 29.769231 | 77 | 0.569063 | 4.804805 | false | false | false | false |
noxytrux/RescueKopter | RescueKopter/KPTGameViewController.swift | 1 | 18587 | //
// GameViewController.swift
// RescueKopter
//
// Created by Marcin Pędzimąż on 15.11.2014.
// Copyright (c) 2014 Marcin Pedzimaz. All rights reserved.
//
import UIKit
import Metal
import QuartzCore
#if os(tvOS)
import GameController
#else
import CoreMotion
#endif
let maxFramesToBuffer = 3
struct sunStructure {
var sunVector = Vector3()
var sunColor = Vector3()
}
struct matrixStructure {
var projMatrix = Matrix4x4()
var viewMatrix = Matrix4x4()
var normalMatrix = Matrix4x4()
}
class KPTGameViewController: UIViewController {
@IBOutlet weak var loadingLabel: UILabel!
let device = { MTLCreateSystemDefaultDevice()! }()
let metalLayer = { CAMetalLayer() }()
var commandQueue: MTLCommandQueue! = nil
var timer: CADisplayLink! = nil
var pipelineState: MTLRenderPipelineState! = nil
let inflightSemaphore = dispatch_semaphore_create(maxFramesToBuffer)
//logic stuff
internal var previousUpdateTime : CFTimeInterval = 0.0
internal var delta : CFTimeInterval = 0.0
internal var accumulator:CFTimeInterval = 0.0
internal let fixedDelta = 0.03
var defaultLibrary: MTLLibrary! = nil
//vector for viewMatrix
var eyeVec = Vector3(x: 0.0,y: 2,z: 3.0)
var dirVec = Vector3(x: 0.0,y: -0.23,z: -1.0)
var upVec = Vector3(x: 0, y: 1, z: 0)
var loadedModels = [KPTModel]()
//sun info
var sunPosition = Vector3(x: 5.316387,y: -2.408824,z: 0)
var orangeColor = Vector3(x: 1.0, y: 0.5, z: 0.0)
var yellowColor = Vector3(x: 1.0, y: 1.0, z: 0.8)
//MARK: Render states
var pipelineStates = [String : MTLRenderPipelineState]()
//MARK: uniform data
var sunBuffer: MTLBuffer! = nil
var cameraMatrix: Matrix4x4 = Matrix4x4()
var sunData = sunStructure()
var matrixData = matrixStructure()
var inverted = Matrix33()
var baseStiencilState: MTLDepthStencilState! = nil
var upRotation: Float = 0
var modelDirection: Float = 0
//MOTION
#if os(tvOS)
var gamePad:GCController? = nil
#else
let manager = CMMotionManager()
#endif
let queue = NSOperationQueue()
weak var kopter:KPTModel? = nil
weak var heightMap:KPTHeightMap? = nil
override func viewDidLoad() {
super.viewDidLoad()
metalLayer.device = device
metalLayer.pixelFormat = .BGRA8Unorm
metalLayer.framebufferOnly = true
self.resize()
view.layer.addSublayer(metalLayer)
view.opaque = true
view.backgroundColor = UIColor.whiteColor()
commandQueue = device.newCommandQueue()
commandQueue.label = "main command queue"
//load data here:
defaultLibrary = device.newDefaultLibrary()
KPTModelManager.sharedInstance
KPTTextureManager.sharedInstance
//generate shaders and descriptors
preparePipelineStates()
//set matrix
let aspect = Float32(view.frame.size.width/view.frame.size.height)
matrixData.projMatrix = matrix44MakePerspective(degToRad(60), aspect: aspect, nearZ: 0.01, farZ: 15000)
//set unifor buffers
sunBuffer = device.newBufferWithBytes(&sunData, length: sizeof(sunStructure), options: .CPUCacheModeDefaultCache)
#if os(tvOS)
//register for controller search
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("controllerDidConnect:"),
name: GCControllerDidConnectNotification,
object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("controllerDidDisconnect:"),
name: GCControllerDidDisconnectNotification,
object: nil)
if GCController.controllers().count > 0 {
self.gamePad = GCController.controllers().first
self.initializeGamePad()
}
else {
GCController.startWirelessControllerDiscoveryWithCompletionHandler {
//this is called in case of failure (searching stops)
print("Remote discovery ended")
if GCController.controllers().count == 0 {
//throw some error there is nothing we can control in our game
}
}
}
#else
if manager.deviceMotionAvailable {
manager.deviceMotionUpdateInterval = 0.01
manager.startDeviceMotionUpdatesToQueue(queue) {
(motion:CMDeviceMotion?, error:NSError?) -> Void in
if let motion = motion {
let attitude:CMAttitude = motion.attitude
self.upRotation = Float(atan2(Double(radToDeg(Float32(attitude.pitch))), Double(radToDeg(Float32(attitude.roll)))))
}
}
}
self.initializeGame()
#endif
}
func initializeGame() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
self.loadGameData()
dispatch_sync(dispatch_get_main_queue(), { () -> Void in
self.loadingLabel.hidden = true
self.view.backgroundColor = nil
self.timer = CADisplayLink(target: self, selector: Selector("renderLoop"))
self.timer.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
})
})
}
#if os(tvOS)
func controllerDidConnect(notification:NSNotification) {
print("controllerDidConnect: \(notification.object)")
//do not allow to connect more than 1
if let _ = self.gamePad {
return
}
self.gamePad = GCController.controllers().first
self.initializeGamePad()
}
func controllerDidDisconnect(notification:NSNotification) {
print("controllerDidDisconnect: \(notification.object)")
//stop game, infor about missing controller etc.
}
func initializeGamePad() {
//we are connected start motion monitoring and game
if let gamePad = self.gamePad {
print("found at index: \(gamePad.playerIndex) - device: (\(gamePad)")
guard let _ = gamePad.motion else {
print("Motion not supported")
return
}
if let profile = gamePad.microGamepad {
gamePad.motion!.valueChangedHandler = {[unowned self](motion) in
//TODO: Figure out is there any way to use gyro in Apple Remote
// let attitude = motion.attitude
//
// let roll = atan2(2*attitude.y*attitude.w - 2*attitude.x*attitude.z, 1 - 2*attitude.y*attitude.y - 2*attitude.z*attitude.z);
// let pitch = atan2(2*attitude.x*attitude.w - 2*attitude.y*attitude.z, 1 - 2*attitude.x*attitude.x - 2*attitude.z*attitude.z);
//
// self.upRotation = Float(atan2(Double(radToDeg(Float32(pitch))), Double(radToDeg(Float32(roll)))))
let gravity = motion.gravity
let upVector = Float32(abs(gravity.x))
let rotation = Float32(-gravity.y * 0.2) * (gravity.x > 0 ? 1 : -1)
self.upRotation = Float(atan2(radToDeg(rotation), radToDeg(upVector)))
}
profile.valueChangedHandler = { (gamepad, element) in
print("PROFILE UPDATE")
}
}
self.initializeGame()
}
}
#endif
func loadGameData() {
let skyboxSphere = KPTModelManager.sharedInstance.loadModel("sphere", device: device)
if let skyboxSphere = skyboxSphere {
skyboxSphere.modelScale = 5000
skyboxSphere.modelMatrix.t = Vector3()
skyboxSphere.modelMatrix.M.rotY(0)
//no back culling at all is skybox!
skyboxSphere.setCullModeForMesh(0, mode: .None)
skyboxSphere.setPipelineState(0, name: "skybox")
let skyboxTex = KPTTextureManager.sharedInstance.loadCubeTexture("skybox", device: device)
if let skyboxTex = skyboxTex {
skyboxSphere.setTexture(0, texture: skyboxTex)
}
loadedModels.append(skyboxSphere)
}
let helicopter = KPTModelManager.sharedInstance.loadModel("helicopter", device: device)
if let helicopter = helicopter {
helicopter.modelScale = 1.0
helicopter.modelMatrix.t = Vector3(x:0,y:34,z:-3)
var rotX = Matrix33()
rotX.rotX(Float(M_PI_2))
var rotZ = Matrix33()
rotZ.rotY(Float(M_PI))
helicopter.modelMatrix.M = rotX * rotZ
loadedModels.append(helicopter)
kopter = helicopter
}
let gameMap = KPTMapModel()
gameMap.load("heightmap", device: device)
heightMap = gameMap.heightMap
loadedModels.append(gameMap)
}
func preparePipelineStates() {
let desc = MTLDepthStencilDescriptor()
desc.depthWriteEnabled = true;
desc.depthCompareFunction = .LessEqual;
baseStiencilState = device.newDepthStencilStateWithDescriptor(desc)
//create all pipeline states for shaders
let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
var fragmentProgram: MTLFunction?
var vertexProgram: MTLFunction?
do {
//BASIC SHADER
fragmentProgram = defaultLibrary?.newFunctionWithName("basicRenderFragment")
vertexProgram = defaultLibrary?.newFunctionWithName("basicRenderVertex")
pipelineStateDescriptor.vertexFunction = vertexProgram
pipelineStateDescriptor.fragmentFunction = fragmentProgram
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm
let basicState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor)
pipelineStates["basic"] = basicState
} catch {
print("Failed to create pipeline state, error \(error)")
}
do {
//SKYBOX SHADER
fragmentProgram = defaultLibrary?.newFunctionWithName("skyboxFragment")
vertexProgram = defaultLibrary?.newFunctionWithName("skyboxVertex")
pipelineStateDescriptor.vertexFunction = vertexProgram
pipelineStateDescriptor.fragmentFunction = fragmentProgram
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .BGRA8Unorm
let basicState = try device.newRenderPipelineStateWithDescriptor(pipelineStateDescriptor)
pipelineStates["skybox"] = basicState
} catch {
print("Failed to create pipeline state, error \(error)")
}
}
#if os(iOS)
override func prefersStatusBarHidden() -> Bool {
return true
}
#endif
override func viewDidLayoutSubviews() {
self.resize()
}
func resize() {
if (view.window == nil) {
return
}
let window = view.window!
let nativeScale = window.screen.nativeScale
view.contentScaleFactor = nativeScale
metalLayer.frame = view.layer.frame
var drawableSize = view.bounds.size
drawableSize.width = drawableSize.width * CGFloat(view.contentScaleFactor)
drawableSize.height = drawableSize.height * CGFloat(view.contentScaleFactor)
metalLayer.drawableSize = drawableSize
}
deinit {
timer.invalidate()
}
func renderLoop() {
autoreleasepool {
self.render()
}
}
func render() {
dispatch_semaphore_wait(inflightSemaphore, DISPATCH_TIME_FOREVER)
self.update()
let commandBuffer = commandQueue.commandBuffer()
commandBuffer.label = "Frame command buffer"
if let drawable = metalLayer.nextDrawable() {
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = drawable.texture
renderPassDescriptor.colorAttachments[0].loadAction = .Clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
renderPassDescriptor.colorAttachments[0].storeAction = .Store
let renderEncoder = commandBuffer.renderCommandEncoderWithDescriptor(renderPassDescriptor)
renderEncoder.label = "render encoder"
renderEncoder.setFrontFacingWinding(.CounterClockwise)
renderEncoder.setDepthStencilState(baseStiencilState)
renderEncoder.setVertexBuffer(sunBuffer, offset: 0, atIndex: 2)
//game rendering here
var cameraViewMatrix = Matrix34(initialize: false)
cameraViewMatrix.setColumnMajor44(cameraMatrix)
for model in loadedModels {
//calcualte real model view matrix
let modelViewMatrix = cameraViewMatrix * (model.modelMatrix * model.modelScale)
var normalMatrix = Matrix33(other: modelViewMatrix.M)
if modelViewMatrix.M.getInverse(&inverted) == true {
normalMatrix.setTransposed(inverted)
}
//set updated buffer info
modelViewMatrix.getColumnMajor44(&matrixData.viewMatrix)
let normal4x4 = Matrix34(rot: normalMatrix, trans: Vector3(x: 0, y: 0, z: 0))
normal4x4.getColumnMajor44(&matrixData.normalMatrix)
//cannot modify single value
let matrices = UnsafeMutablePointer<matrixStructure>(model.matrixBuffer.contents())
matrices.memory = matrixData
renderEncoder.setVertexBuffer(model.matrixBuffer, offset: 0, atIndex: 1)
model.render(renderEncoder, states: pipelineStates, shadowPass: false)
}
renderEncoder.endEncoding()
commandBuffer.addCompletedHandler{ [weak self] commandBuffer in
if let strongSelf = self {
dispatch_semaphore_signal(strongSelf.inflightSemaphore)
}
return
}
commandBuffer.presentDrawable(drawable)
commandBuffer.commit()
}
}
func update() {
delta = timer.timestamp - self.previousUpdateTime
previousUpdateTime = timer.timestamp
if delta > 0.3 {
delta = 0.3
}
//update gyro:
let uprotationValue = min(max(upRotation, -0.7), 0.7)
var realUp = upVec
var rotationMat = Matrix33()
rotationMat.rotZ(uprotationValue)
rotationMat.multiply(upVec, dst: &realUp)
accumulator += delta
while (accumulator > fixedDelta) {
calculatePhysic()
accumulator -= fixedDelta
}
//update lookAt matrix
cameraMatrix = matrix44MakeLookAt(eyeVec, center: eyeVec+dirVec, up: realUp)
//udpate sun position and color
sunPosition.y += Float32(delta) * 0.05
sunPosition.x += Float32(delta) * 0.05
sunData.sunVector = Vector3(x: -cosf(sunPosition.x) * sinf(sunPosition.y),
y: -cosf(sunPosition.y),
z: -sinf(sunPosition.x) * sinf(sunPosition.y))
let sun_cosy = sunData.sunVector.y
let factor = 0.25 + sun_cosy * 0.75
sunData.sunColor = ((orangeColor * (1.0 - factor)) + (yellowColor * factor))
memcpy(sunBuffer.contents(), &sunData, Int(sizeof(sunStructure)))
}
func calculatePhysic() {
//update kopter logic
if let kopter = kopter {
let kopterRotation = min(max(upRotation, -0.4), 0.4)
modelDirection += kopterRotation * 0.5
var rotX = Matrix33()
rotX.rotX(Float(M_PI_2))
var rotY = Matrix33()
rotY.rotY(Float(M_PI))
var rotK1 = Matrix33()
rotK1.rotZ(modelDirection)
var rotK2 = Matrix33()
rotK2.rotY(kopterRotation)
kopter.modelMatrix.M = rotX * rotY * rotK1 * rotK2
//flying
let speed:Float = 9.0
let pos = Vector3(x: Float32(sin(modelDirection) * speed * Float(fixedDelta)), y: 0.0, z: Float32(cos(modelDirection) * speed * Float(fixedDelta)))
let dist = Vector3(x: Float32(sin(modelDirection) * speed), y: 0.0, z: Float32(cos(modelDirection) * speed))
eyeVec = kopter.modelMatrix.t + dist
eyeVec.y += 2
dirVec = eyeVec - kopter.modelMatrix.t
dirVec.normalize()
dirVec.setNegative()
dirVec.y = -0.23
kopter.modelMatrix.t -= pos
let px: Float32 = kopter.modelMatrix.t.x + 256.0
let pz: Float32 = kopter.modelMatrix.t.z + 256.0
kopter.modelMatrix.t.y = fabs(heightMap!.GetHeight(px/2.0, z: pz/2.0) / 8.0 ) + 10.0
}
}
} | mit | 3e824e18a88a1aabe2a635e86ca019cc | 31.153979 | 159 | 0.560913 | 4.913802 | false | false | false | false |
joshua7v/ResearchOL-iOS | ResearchOL/Class/More/Controller/ROLMoreController.swift | 1 | 1241 | //
// ROLMoreController.swift
// ResearchOL
//
// Created by Joshua on 15/4/12.
// Copyright (c) 2015年 SigmaStudio. All rights reserved.
//
import UIKit
class ROLMoreController: SESettingViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "设置"
self.setupGroup0()
self.setupGroup1()
}
// MARK: - setup
// MARK: group0 - contact us
func setupGroup0() {
var group = self.addGroup()
var contact = SESettingArrowItem(title: "联系方式", destVcClass: UITableViewController.classForCoder())
var bussiness = SESettingArrowItem(title: "我是企业 我要调查!", destVcClass: UITableViewController.classForCoder())
group.items = [contact, bussiness]
}
// MARK: group1 - about
func setupGroup1() {
var group = self.addGroup()
var rate = SESettingArrowItem(title: "评分", destVcClass: UITableViewController.classForCoder())
var version = SESettingLabelItem(title: "版本", text: "0.1.4")
var questions = SESettingArrowItem(title: "常见问题", destVcClass: UITableViewController.classForCoder())
group.items = [rate, version, questions]
}
}
| mit | 4482dc7efc38c289a766ee278c41e74e | 31.243243 | 115 | 0.649623 | 3.873377 | false | false | false | false |
psturm-swift/SwiftySignals | Tests/SwiftySignalsTests/DispatchTests.swift | 1 | 4038 | // Copyright (c) 2017 Patrick Sturm <[email protected]>
//
// 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 XCTest
@testable import SwiftySignals
class DispatchTests: XCTestCase {
override func setUp() {
}
override func tearDown() {
}
func testIfBlocksAreExecutedOnMainQueueOnSubscription() {
let observables = ObservableCollection()
let propertyProcessed = self.expectation(description: "Property processed")
let property = Property<Bool>(value: true)
property
.didSet
.then { _ in XCTAssertTrue(Thread.isMainThread) }
.map {
value -> Bool in
XCTAssertTrue(Thread.isMainThread)
return !value
}
.then { _ in propertyProcessed.fulfill() }
.append(to: observables)
self.waitForExpectations(timeout: 10, handler: nil)
}
func testIfBlocksAreExecutedOnMainQueueIfPropertyDidSet() {
let observables = ObservableCollection()
let propertyProcessed = self.expectation(description: "Property processed")
let property = Property<Bool>(value: true)
property
.didSet
.discard(first: 1)
.then { _ in XCTAssertTrue(Thread.isMainThread) }
.map {
value -> Bool in
XCTAssertTrue(Thread.isMainThread)
return !value
}
.then { _ in propertyProcessed.fulfill() }
.append(to: observables)
property.value = !property.value
self.waitForExpectations(timeout: 10, handler: nil)
}
func testIfBlocksAreExecutedNotOnMainThreadIfDispatchIsTurnedOff() {
let observables = ObservableCollection()
let propertyProcessed = self.expectation(description: "Property processed")
let signal = Signal<Bool>()
signal
.fired
.noDispatch()
.then { _ in XCTAssertTrue(!Thread.isMainThread) }
.map {
value -> Bool in
XCTAssertTrue(!Thread.isMainThread)
return !value
}
.then { _ in propertyProcessed.fulfill() }
.append(to: observables)
signal.fire(with: false)
self.waitForExpectations(timeout: 10, handler: nil)
}
static var allTests : [(String, (DispatchTests) -> () throws -> Void)] {
let unitTests : [(String, (DispatchTests) -> () throws -> Void)] = [
("testIfBlocksAreExecutedOnMainQueueOnSubscription", testIfBlocksAreExecutedOnMainQueueOnSubscription),
("testIfBlocksAreExecutedOnMainQueueIfPropertyDidSet", testIfBlocksAreExecutedOnMainQueueIfPropertyDidSet),
("testIfBlocksAreExecutedNotOnMainThreadIfDispatchIsTurnedOff", testIfBlocksAreExecutedNotOnMainThreadIfDispatchIsTurnedOff)
]
return unitTests
}
}
| mit | 515a6c5a328f5d1a3642cb8bfb351c7d | 38.203883 | 136 | 0.64314 | 5.143949 | false | true | false | false |
kyouko-taiga/LogicKit | Sources/LogicKit/Logger.swift | 1 | 2170 | public enum FontColor {
case red, green, yellow
}
public enum FontAttribute {
case bold
case dim
case foreground(FontColor)
case background(FontColor)
}
public protocol Logger {
func didBacktrack()
func willRealize(goal: Term)
func willAttempt(clause: Term)
}
public struct DefaultLogger: Logger {
public init(useFontAttributes: Bool = true) {
self.useFontAttributes = useFontAttributes
}
public let useFontAttributes: Bool
public func didBacktrack() {
log(message: "backtacking", fontAttributes: [.dim])
}
public func willRealize(goal: Term) {
log(message: "Attempting to realize ", terminator: "")
log(message: "\(goal)", fontAttributes: [.bold])
}
public func willAttempt(clause: Term) {
log(message: "using " , terminator: "", fontAttributes: [.dim])
log(message: "\(clause) ")
}
public func log(message: String, terminator: String, fontAttributes: [FontAttribute]) {
if useFontAttributes {
let attributes = fontAttributes.compactMap({
switch $0 {
case .bold:
return "\u{001B}[1m"
case .dim:
return "\u{001B}[2m"
case .foreground(let color):
return "\u{001B}[\(DefaultLogger.foreground[color] ?? "39m")"
case .background(let color):
return "\u{001B}[\(DefaultLogger.background[color] ?? "40m")"
}
}).joined(separator: "")
print("\(attributes)\(message)\u{001B}[0m", terminator: terminator)
} else {
print(message, terminator: terminator)
}
}
public func log(message: String) {
log(message: message, terminator: "\n", fontAttributes: [])
}
public func log(message: String, fontAttributes: [FontAttribute]) {
log(message: message, terminator: "\n", fontAttributes: fontAttributes)
}
public func log(message: String, terminator: String) {
log(message: message, terminator: terminator, fontAttributes: [])
}
static let foreground: [FontColor: String] = [
.red : "31m",
.green : "32m",
.yellow: "33m",
]
static let background: [FontColor: String] = [
.red : "41m",
.green : "42m",
.yellow: "43m",
]
}
| mit | 002434111b14d5f087890ad19a89dc1f | 23.111111 | 89 | 0.632719 | 3.840708 | false | false | false | false |
RxSwiftCommunity/RxSwiftExt | Tests/RxSwift/MapAtTests.swift | 2 | 1277 | //
// MapToKeyPath.swift
// RxSwiftExt
//
// Created by Michael Avila on 2/8/18.
// Copyright © 2018 RxSwift Community. All rights reserved.
//
import XCTest
import RxSwift
import RxSwiftExt
import RxTest
class MapAtTests: XCTestCase {
struct Person {
let name: String
}
let people: [Person] = [
Person(name: "Bart"),
Person(name: "Lisa"),
Person(name: "Maggie")
]
private var observer: TestableObserver<String>!
override func setUp() {
let scheduler = TestScheduler(initialClock: 0)
observer = scheduler.createObserver(String.self)
_ = Observable.from(people)
.mapAt(\.name)
.subscribe(observer)
scheduler.start()
}
func testResultSequenceHasSameNumberOfItemsAsSourceSequence() {
XCTAssertEqual(
observer.events.count - 1, // completed event
people.count
)
}
func testResultSequenceHasValuesAtProvidedKeypath() {
// test elements values and type
let correctValues = Recorded.events([
.next(0, "Bart"),
.next(0, "Lisa"),
.next(0, "Maggie"),
.completed(0)
])
XCTAssertEqual(observer.events, correctValues)
}
}
| mit | b7acb212c731358dd05bc53eb54300d9 | 21.385965 | 67 | 0.594044 | 4.354949 | false | true | false | false |
superman-coder/pakr | pakr/pakr/Preferences/AuthenPreferences.swift | 1 | 1418 | //
// AuthenPreferences.swift
// pakr
//
// Created by Huynh Quang Thao on 4/17/16.
// Copyright © 2016 Pakr. All rights reserved.
//
import Foundation
enum LoginMechanism: Int{
case NONE = 0
case FACEBOOK
case GOOGLE
}
let loginMechanismPref = "LoginMechanismPref"
let kUserDataKey = "UserData"
extension NSUserDefaults {
func getLoginMechanism() -> LoginMechanism {
let loginMechanism = self.integerForKey(loginMechanismPref)
return LoginMechanism(rawValue: loginMechanism)!
}
func setLoginMechanism(mechanism: LoginMechanism) {
self.setInteger(mechanism.rawValue, forKey: loginMechanismPref)
self.synchronize()
}
func saveCurrentUser(user:User?) {
if let user = user {
let data = try! NSJSONSerialization.dataWithJSONObject(user.toDictionary(), options: [])
self.setObject(data, forKey: kUserDataKey)
} else {
self.setObject(nil, forKey: kUserDataKey)
}
self.synchronize()
}
func currentUser() -> User? {
var user: User? = nil
let data = self.objectForKey(kUserDataKey) as? NSData
if let data = data {
let json = try! NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
user = User(dict: json)
}
user?.objectId = user?.userId
return user
}
} | apache-2.0 | bd16cb67df7bcc0c6d211038a11e599e | 25.754717 | 102 | 0.630205 | 4.36 | false | false | false | false |
OneBusAway/onebusaway-iphone | Carthage/Checkouts/SwiftEntryKit/Example/SwiftEntryKit/Playground/Cells/WidthSelectionTableViewCell.swift | 3 | 1647 | //
// WidthSelectionTableViewCell.swift
// SwiftEntryKit_Example
//
// Created by Daniel Huri on 4/25/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
class WidthSelectionTableViewCell: SelectionTableViewCell {
override func configure(attributesWrapper: EntryAttributeWrapper) {
super.configure(attributesWrapper: attributesWrapper)
titleValue = "Width"
descriptionValue = "Describes the entry's width inside the screen. It can be stretched to the margins, it can have an offset, can a constant or have a ratio to the screen"
insertSegments(by: ["Stretch", "20pts Offset", "90% Screen"])
selectSegment()
}
private func selectSegment() {
switch attributesWrapper.attributes.positionConstraints.size.width {
case .offset(value: let value):
if value == 0 {
segmentedControl.selectedSegmentIndex = 0
} else {
segmentedControl.selectedSegmentIndex = 1
}
case .ratio(value: _):
segmentedControl.selectedSegmentIndex = 2
default:
break
}
}
@objc override func segmentChanged() {
switch segmentedControl.selectedSegmentIndex {
case 0:
attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 0)
case 1:
attributesWrapper.attributes.positionConstraints.size.width = .offset(value: 20)
case 2:
attributesWrapper.attributes.positionConstraints.size.width = .ratio(value: 0.9)
default:
break
}
}
}
| apache-2.0 | fa256a432bc79b4192f7183ef2405c09 | 34.042553 | 179 | 0.64238 | 4.858407 | false | false | false | false |
tad-iizuka/swift-sdk | Tests/ToneAnalyzerV3Tests/ToneAnalyzerTests.swift | 2 | 7474 | /**
* Copyright IBM Corporation 2016
*
* 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 XCTest
import Foundation
import ToneAnalyzerV3
class ToneAnalyzerTests: XCTestCase {
private var toneAnalyzer: ToneAnalyzer!
private let timeout: TimeInterval = 5.0
static var allTests : [(String, (ToneAnalyzerTests) -> () throws -> Void)] {
return [
("testGetToneWithDefaultParameters", testGetToneWithDefaultParameters),
("testGetToneWithCustomParameters", testGetToneWithCustomParameters),
("testGetToneEmptyString", testGetToneEmptyString),
("testGetToneInvalidParameters", testGetToneInvalidParameters)
]
}
let text = "I know the times are difficult! Our sales have been disappointing for " +
"the past three quarters for our data analytics product suite. We have a " +
"competitive data analytics product suite in the industry. But we need " +
"to do our job selling it! "
// MARK: - Test Configuration
/** Set up for each test by instantiating the service. */
override func setUp() {
super.setUp()
continueAfterFailure = false
instantiateToneAnalyzer()
}
/** Instantiate Tone Analyzer. */
func instantiateToneAnalyzer() {
let username = Credentials.ToneAnalyzerUsername
let password = Credentials.ToneAnalyzerPassword
toneAnalyzer = ToneAnalyzer(username: username, password: password, version: "2016-05-10")
}
/** Fail false negatives. */
func failWithError(error: Error) {
XCTFail("Positive test failed with error: \(error)")
}
/** Fail false positives. */
func failWithResult<T>(result: T) {
XCTFail("Negative test returned a result.")
}
/** Wait for expectations. */
func waitForExpectations() {
waitForExpectations(timeout: timeout) { error in
XCTAssertNil(error, "Timeout")
}
}
// MARK: - Positive Tests
/** Analyze the tone of the given text using the default parameters. */
func testGetToneWithDefaultParameters() {
let description = "Analyze the tone of the given text using the default parameters."
let expectation = self.expectation(description: description)
toneAnalyzer.getTone(ofText: text, failure: failWithError) { toneAnalysis in
for emotionTone in toneAnalysis.documentTone[0].tones {
XCTAssertNotNil(emotionTone.name)
XCTAssertNotNil(emotionTone.id)
XCTAssert(emotionTone.score <= 1.0 && emotionTone.score >= 0.0)
}
for writingTone in toneAnalysis.documentTone[1].tones {
XCTAssertNotNil(writingTone.name)
XCTAssertNotNil(writingTone.id)
XCTAssert(writingTone.score <= 1.0 && writingTone.score >= 0.0)
}
for socialTone in toneAnalysis.documentTone[2].tones {
XCTAssertNotNil(socialTone.name)
XCTAssertNotNil(socialTone.id)
XCTAssert(socialTone.score <= 1.0 && socialTone.score >= 0.0)
}
guard let sentenceTones = toneAnalysis.sentencesTones else {
XCTFail("Sentence tones should not be nil.")
return
}
for sentence in sentenceTones {
XCTAssert(sentence.sentenceID >= 0)
XCTAssertNotEqual(sentence.text, "")
XCTAssert(sentence.inputFrom >= 0)
XCTAssert(sentence.inputTo > sentence.inputFrom)
for emotionTone in toneAnalysis.documentTone[0].tones {
XCTAssertNotNil(emotionTone.name)
XCTAssertNotNil(emotionTone.id)
XCTAssert(emotionTone.score <= 1.0 && emotionTone.score >= 0.0)
}
for writingTone in toneAnalysis.documentTone[1].tones {
XCTAssertNotNil(writingTone.name)
XCTAssertNotNil(writingTone.id)
XCTAssert(writingTone.score <= 1.0 && writingTone.score >= 0.0)
}
for socialTone in toneAnalysis.documentTone[2].tones {
XCTAssertNotNil(socialTone.name)
XCTAssertNotNil(socialTone.id)
XCTAssert(socialTone.score <= 1.0 && socialTone.score >= 0.0)
}
}
expectation.fulfill()
}
waitForExpectations()
}
/** Analyze the tone of the given text with custom parameters. */
func testGetToneWithCustomParameters() {
let description = "Analyze the tone of the given text using custom parameters."
let expectation = self.expectation(description: description)
let tones = ["emotion", "writing"]
toneAnalyzer.getTone(ofText: text, tones: tones, sentences: false, failure: failWithError) {
toneAnalysis in
for emotionTone in toneAnalysis.documentTone[0].tones {
XCTAssertNotNil(emotionTone.name)
XCTAssertNotNil(emotionTone.id)
XCTAssert(emotionTone.score <= 1.0 && emotionTone.score >= 0.0)
}
for writingTone in toneAnalysis.documentTone[1].tones {
XCTAssertNotNil(writingTone.name)
XCTAssertNotNil(writingTone.id)
XCTAssert(writingTone.score <= 1.0 && writingTone.score >= 0.0)
}
for tone in toneAnalysis.documentTone {
XCTAssert(tone.name != "Social Tone", "Social tone should not be included")
}
XCTAssertNil(toneAnalysis.sentencesTones)
expectation.fulfill()
}
waitForExpectations()
}
// MARK: - Negative Tests
func testGetToneEmptyString() {
let description = "Analyze the tone of an empty string."
let expectation = self.expectation(description: description)
let failure = { (error: Error) in
expectation.fulfill()
}
toneAnalyzer.getTone(ofText: "", failure: failure, success: failWithResult)
waitForExpectations()
}
func testGetToneInvalidParameters() {
let description = "Analyze the tone of the given text using invalid parameters."
let expectation = self.expectation(description: description)
let failure = { (error: Error) in
expectation.fulfill()
}
let tones = ["emotion", "this-tone-is-invalid"]
toneAnalyzer.getTone(ofText: text, tones: tones, failure: failure, success: failWithResult)
waitForExpectations()
}
}
| apache-2.0 | b0e665dd64c669173d9e019be0081a9e | 37.725389 | 100 | 0.597404 | 5.193885 | false | true | false | false |
groue/GRDB.swift | Tests/GRDBTests/TableRecordUpdateTests.swift | 1 | 28626 | import XCTest
import GRDB
private struct Player: Codable, PersistableRecord, FetchableRecord, Hashable {
var id: Int64
var name: String
var score: Int
var bonus: Int
static func createTable(_ db: Database) throws {
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("name", .text)
t.column("score", .integer)
t.column("bonus", .integer)
}
}
}
@available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *)
extension Player: Identifiable { }
private enum Columns: String, ColumnExpression {
case id, name, score, bonus
}
private extension QueryInterfaceRequest<Player> {
func incrementScore(_ db: Database) throws {
try updateAll(db, Columns.score += 1)
}
}
class TableRecordUpdateTests: GRDBTestCase {
func testRequestUpdateAll() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
try Player.updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try Player.filter(Columns.name == "Arthur").updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE \"name\" = 'Arthur'
""")
try Player.filter(key: 1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" = 1
""")
try Player.filter(keys: [1, 2]).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2)
""")
if #available(OSX 10.15, iOS 13.0, tvOS 13.0, watchOS 6, *) {
try Player.filter(id: 1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" = 1
""")
try Player.filter(ids: [1, 2]).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (1, 2)
""")
}
try Player.filter(sql: "id = 1").updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE id = 1
""")
try Player.filter(sql: "id = 1").filter(Columns.name == "Arthur").updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE (id = 1) AND (\"name\" = 'Arthur')
""")
try Player.select(Columns.name).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try Player.order(Columns.name).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") {
try Player.limit(1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 LIMIT 1
""")
try Player.order(Columns.name).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try Player.order(Columns.name).limit(1).updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 ORDER BY \"name\" LIMIT 1
""")
try Player.order(Columns.name).limit(1, offset: 2).reversed().updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 ORDER BY \"name\" DESC LIMIT 1 OFFSET 2
""")
try Player.limit(1, offset: 2).reversed().updateAll(db, assignment)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 LIMIT 1 OFFSET 2
""")
}
}
}
func testRequestUpdateAndFetchStatement() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
let assignment = Columns.score.set(to: 0)
let request = Player.all()
let statement = try request.updateAndFetchStatement(db, [assignment], selection: [AllColumns()])
XCTAssertEqual(statement.sql, "UPDATE \"player\" SET \"score\" = ? RETURNING *")
XCTAssertEqual(statement.arguments, [0])
XCTAssertEqual(statement.columnNames, ["id", "name", "score", "bonus"])
}
}
func testRequestUpdateAndFetchCursor() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let cursor = try request.updateAndFetchCursor(db, [Columns.score += 100])
let updatedPlayers = try Array(cursor).sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchAll() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let updatedPlayers = try request
.updateAndFetchAll(db, [Columns.score += 100])
.sorted(by: { $0.id < $1.id })
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testRequestUpdateAndFetchSet() throws {
#if GRDBCUSTOMSQLITE || GRDBCIPHER
guard sqlite3_libversion_number() >= 3035000 else {
throw XCTSkip("RETURNING clause is not available")
}
#else
guard #available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *) else {
throw XCTSkip("RETURNING clause is not available")
}
#endif
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player(id: 1, name: "Arthur", score: 10, bonus: 0).insert(db)
try Player(id: 2, name: "Barbara", score: 20, bonus: 10).insert(db)
try Player(id: 3, name: "Craig", score: 30, bonus: 20).insert(db)
let request = Player.filter(Columns.id != 2)
let updatedPlayers = try request.updateAndFetchSet(db, [Columns.score += 100])
XCTAssertEqual(updatedPlayers, [
Player(id: 1, name: "Arthur", score: 110, bonus: 0),
Player(id: 3, name: "Craig", score: 130, bonus: 20),
])
}
}
func testNilAssignment() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score.set(to: nil))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = NULL
""")
}
}
func testComplexAssignment() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score.set(to: Columns.score * (Columns.bonus + 1)))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * ("bonus" + 1)
""")
}
}
func testAssignmentSubtractAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score -= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - 1
""")
try Player.updateAll(db, Columns.score -= Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - "bonus"
""")
try Player.updateAll(db, Columns.score -= -Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - (-"bonus")
""")
try Player.updateAll(db, Columns.score -= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" - ("bonus" * 2)
""")
}
}
func testAssignmentAddAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score += 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + 1
""")
try Player.updateAll(db, Columns.score += Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + "bonus"
""")
try Player.updateAll(db, Columns.score += -Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + (-"bonus")
""")
try Player.updateAll(db, Columns.score += Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" + ("bonus" * 2)
""")
}
}
func testAssignmentMultiplyAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score *= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * 1
""")
try Player.updateAll(db, Columns.score *= Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * "bonus"
""")
try Player.updateAll(db, Columns.score *= -Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * (-"bonus")
""")
try Player.updateAll(db, Columns.score *= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" * ("bonus" * 2)
""")
}
}
func testAssignmentDivideAndAssign() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score /= 1)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / 1
""")
try Player.updateAll(db, Columns.score /= Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / "bonus"
""")
try Player.updateAll(db, Columns.score /= -Columns.bonus)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / (-"bonus")
""")
try Player.updateAll(db, Columns.score /= Columns.bonus * 2)
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = "score" / ("bonus" * 2)
""")
}
}
func testMultipleAssignments() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Columns.score.set(to: 0), Columns.bonus.set(to: 1))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0, "bonus" = 1
""")
try Player.updateAll(db, [Columns.score.set(to: 0), Columns.bonus.set(to: 1)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0, "bonus" = 1
""")
try Player.all().updateAll(db, Columns.score.set(to: 0), Columns.bonus.set(to: 1))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0, "bonus" = 1
""")
try Player.all().updateAll(db, [Columns.score.set(to: 0), Columns.bonus.set(to: 1)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0, "bonus" = 1
""")
}
}
func testUpdateAllWithoutAssignmentDoesNotAccessTheDatabase() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
sqlQueries.removeAll()
try XCTAssertEqual(Player.updateAll(db, []), 0)
try XCTAssertEqual(Player.all().updateAll(db, []), 0)
XCTAssert(sqlQueries.isEmpty)
}
}
func testUpdateAllReturnsNumberOfUpdatedRows() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try db.execute(sql: """
INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 2);
INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 1);
INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0);
INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 3);
""")
let assignment = Columns.score += 1
try XCTAssertEqual(Player.updateAll(db, assignment), 4)
try XCTAssertEqual(Player.filter(key: 1).updateAll(db, assignment), 1)
try XCTAssertEqual(Player.filter(key: 5).updateAll(db, assignment), 0)
try XCTAssertEqual(Player.filter(Columns.bonus > 1).updateAll(db, assignment), 2)
if try String.fetchCursor(db, sql: "PRAGMA COMPILE_OPTIONS").contains("ENABLE_UPDATE_DELETE_LIMIT") {
try XCTAssertEqual(Player.limit(1).updateAll(db, assignment), 1)
try XCTAssertEqual(Player.limit(2).updateAll(db, assignment), 2)
try XCTAssertEqual(Player.limit(2, offset: 3).updateAll(db, assignment), 1)
try XCTAssertEqual(Player.limit(10).updateAll(db, assignment), 4)
}
}
}
func testQueryInterfaceExtension() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try db.execute(sql: """
INSERT INTO player (id, name, score, bonus) VALUES (1, 'Arthur', 0, 0);
INSERT INTO player (id, name, score, bonus) VALUES (2, 'Barbara', 0, 0);
INSERT INTO player (id, name, score, bonus) VALUES (3, 'Craig', 0, 0);
INSERT INTO player (id, name, score, bonus) VALUES (4, 'Diane', 0, 0);
""")
try Player.all().incrementScore(db)
try XCTAssertEqual(Player.filter(Columns.score == 1).fetchCount(db), 4)
try Player.filter(key: 1).incrementScore(db)
try XCTAssertEqual(Player.fetchOne(db, key: 1)!.score, 2)
}
}
func testConflictPolicyAbort() throws {
struct AbortPlayer: PersistableRecord {
static let databaseTableName = "player"
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .abort)
func encode(to container: inout PersistenceContainer) { }
}
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try AbortPlayer.updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try AbortPlayer.updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try AbortPlayer.all().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try AbortPlayer.all().updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
}
}
func testConflictPolicyIgnore() throws {
struct IgnorePlayer: PersistableRecord {
static let databaseTableName = "player"
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore)
func encode(to container: inout PersistenceContainer) { }
}
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try IgnorePlayer.updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try IgnorePlayer.updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try IgnorePlayer.all().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try IgnorePlayer.all().updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
}
}
func testConflictPolicyIgnoreWithTable() throws {
struct IgnorePlayer: PersistableRecord {
static let databaseTableName = "player"
static let persistenceConflictPolicy = PersistenceConflictPolicy(insert: .abort, update: .ignore)
func encode(to container: inout PersistenceContainer) { }
}
let table = Table<IgnorePlayer>("player")
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try table.updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try table.updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try table.all().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try table.all().updateAll(db, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
}
}
func testConflictPolicyCustom() throws {
try makeDatabaseQueue().write { db in
try Player.createTable(db)
try Player.updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0
""")
try Player.updateAll(db, onConflict: .ignore, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try Player.updateAll(db, onConflict: .ignore, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try Player.all().updateAll(db, onConflict: .ignore, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
try Player.all().updateAll(db, onConflict: .ignore, [Column("score").set(to: 0)])
XCTAssertEqual(self.lastSQLQuery, """
UPDATE OR IGNORE "player" SET "score" = 0
""")
}
}
func testJoinedRequestUpdate() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
static let team = belongsTo(Team.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Team: MutablePersistableRecord {
static let players = hasMany(Player.self)
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "team") { t in
t.autoIncrementedPrimaryKey("id")
t.column("active", .boolean)
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("teamId", .integer).references("team")
t.column("score", .integer)
}
do {
try Player.including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON "team"."id" = "player"."teamId")
""")
}
do {
// Regression test for https://github.com/groue/GRDB.swift/issues/758
try Player.including(required: Player.team.filter(Column("active") == 1)).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "player"."id" \
FROM "player" \
JOIN "team" ON ("team"."id" = "player"."teamId") AND ("team"."active" = 1))
""")
}
do {
let alias = TableAlias(name: "p")
try Player.aliased(alias).including(required: Player.team).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "p"."id" \
FROM "player" "p" \
JOIN "team" ON "team"."id" = "p"."teamId")
""")
}
do {
try Team.having(Team.players.isEmpty).updateAll(db, Column("active").set(to: false))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0 WHERE "id" IN (\
SELECT "team"."id" \
FROM "team" \
LEFT JOIN "player" ON "player"."teamId" = "team"."id" \
GROUP BY "team"."id" \
HAVING COUNT(DISTINCT "player"."id") = 0)
""")
}
do {
try Team.including(all: Team.players).updateAll(db, Column("active").set(to: false))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "team" SET "active" = 0
""")
}
}
}
func testGroupedRequestUpdate() throws {
try makeDatabaseQueue().inDatabase { db in
struct Player: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
struct Passport: MutablePersistableRecord {
func encode(to container: inout PersistenceContainer) { preconditionFailure("should not be called") }
}
try db.create(table: "player") { t in
t.autoIncrementedPrimaryKey("id")
t.column("score", .integer)
}
try db.create(table: "passport") { t in
t.column("countryCode", .text).notNull()
t.column("citizenId", .integer).notNull()
t.column("active", .boolean)
t.primaryKey(["countryCode", "citizenId"])
}
do {
try Player.all().groupByPrimaryKey().updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "id")
""")
}
do {
try Player.all().group(Column.rowID).updateAll(db, Column("score").set(to: 0))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "player" SET "score" = 0 WHERE "id" IN (\
SELECT "id" \
FROM "player" \
GROUP BY "rowid")
""")
}
do {
try Passport.all().groupByPrimaryKey().updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
""")
}
do {
try Passport.all().group(Column.rowID).updateAll(db, Column("active").set(to: true))
XCTAssertEqual(self.lastSQLQuery, """
UPDATE "passport" SET "active" = 1 WHERE "rowid" IN (\
SELECT "rowid" \
FROM "passport" \
GROUP BY "rowid")
""")
}
}
}
}
| mit | 66591cb23ed2d9a1c991d095316e330a | 40.973607 | 131 | 0.509991 | 4.73157 | false | false | false | false |
yzpniceboy/KeychainAccess | Examples/Example-iOS/Example-iOS/InputViewController.swift | 8 | 1328 | //
// InputViewController.swift
// Example
//
// Created by kishikawa katsumi on 2014/12/26.
// Copyright (c) 2014 kishikawa katsumi. All rights reserved.
//
import UIKit
import KeychainAccess
class InputViewController: UITableViewController {
@IBOutlet weak var saveButton: UIBarButtonItem!
@IBOutlet weak var cancelButton: UIBarButtonItem!
@IBOutlet weak var usernameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var serviceField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 44.0
tableView.estimatedRowHeight = 44.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK:
@IBAction func cancelAction(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func saveAction(sender: UIBarButtonItem) {
let keychain = Keychain(service: serviceField.text)
keychain[usernameField.text] = passwordField.text
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func editingChanged(sender: UITextField) {
saveButton.enabled = !usernameField.text.isEmpty && !passwordField.text.isEmpty
}
}
| mit | cdb2e00dcfb82b2a5d9a2cf520084f54 | 26.102041 | 87 | 0.689759 | 5.207843 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Unit/Editing/View/MemberGroupView.swift | 1 | 8671 | //
// MemberEditableItemView.swift
// DereGuide
//
// Created by zzk on 2017/6/16.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SnapKit
class MemberEditableItemView: UIView {
var cardView: UnitSimulationCardView!
var overlayView: UIView!
var placeholderImageView: UIImageView!
var cardPlaceholder: UIView!
private(set) var isSelected: Bool = false
private var strokeColor: CGColor = UIColor.lightGray.cgColor {
didSet {
overlayView.layer.borderColor = isSelected ? strokeColor : UIColor.lightGray.cgColor
overlayView.layer.shadowColor = strokeColor
}
}
private func setSelected(_ selected: Bool) {
isSelected = selected
if selected {
overlayView.layer.shadowOpacity = 1
overlayView.layer.borderColor = strokeColor
overlayView.layer.shadowColor = strokeColor
overlayView.layer.borderWidth = 2
} else {
overlayView.layer.shadowOpacity = 0
overlayView.layer.borderColor = UIColor.lightGray.cgColor
overlayView.layer.borderWidth = 0
}
}
func setSelected(selected: Bool, animated: Bool) {
if animated {
overlayView.transform = CGAffineTransform(scaleX: 1.5, y: 1.5)
UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseOut, animations: {
self.overlayView.transform = .identity
self.setSelected(selected)
}, completion: nil)
} else {
setSelected(selected)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
overlayView = UIView()
addSubview(overlayView)
overlayView.snp.makeConstraints { (make) in
make.edges.equalToSuperview()
}
overlayView.layer.shadowOffset = CGSize.zero
setSelected(false)
cardView = UnitSimulationCardView()
cardView.icon.isUserInteractionEnabled = false
addSubview(cardView)
cardView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: 2, left: 4, bottom: 2, right: 4))
make.height.greaterThanOrEqualTo(cardView.snp.width).offset(29)
}
placeholderImageView = UIImageView(image: #imageLiteral(resourceName: "436-plus").withRenderingMode(.alwaysTemplate))
addSubview(placeholderImageView)
placeholderImageView.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.height.width.equalTo(self.snp.width).dividedBy(3)
}
placeholderImageView.tintColor = .lightGray
cardPlaceholder = UIView()
addSubview(cardPlaceholder)
cardPlaceholder.snp.makeConstraints { (make) in
make.width.equalToSuperview().offset(-8)
make.height.equalTo(cardPlaceholder.snp.width)
make.center.equalToSuperview()
}
cardPlaceholder.layer.masksToBounds = true
cardPlaceholder.layer.cornerRadius = 4
cardPlaceholder.layer.borderWidth = 1 / Screen.scale
cardPlaceholder.layer.borderColor = UIColor.border.cgColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(with member: Member) {
placeholderImageView.isHidden = true
cardPlaceholder.isHidden = true
if let color = member.card?.attColor.cgColor {
strokeColor = color
}
cardView.setup(with: member)
bringSubview(toFront: cardView)
}
}
protocol MemberGroupViewDelegate: class {
func memberGroupView(_ memberGroupView: MemberGroupView, didLongPressAt item: MemberEditableItemView)
func memberEditableView(_ memberGroupView: MemberGroupView, didDoubleTap item: MemberEditableItemView)
}
class MemberGroupView: UIView {
weak var delegate: MemberGroupViewDelegate?
var descLabel: UILabel!
var stackView: UIStackView!
var editableItemViews: [MemberEditableItemView]!
var centerLabel: UILabel!
var guestLabel: UILabel!
var currentIndex: Int = 0 {
didSet {
if oldValue != currentIndex {
editableItemViews[oldValue].setSelected(selected: false, animated: false)
editableItemViews[currentIndex].setSelected(selected: true, animated: true)
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
editableItemViews = [MemberEditableItemView]()
for _ in 0..<6 {
let view = MemberEditableItemView()
editableItemViews.append(view)
view.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPressGesture(_:)))
let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTapGesture(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
view.addGestureRecognizer(tap)
view.addGestureRecognizer(longPress)
}
editableItemViews[0].setSelected(selected: true, animated: false)
stackView = UIStackView(arrangedSubviews: editableItemViews)
stackView.spacing = 6
stackView.distribution = .fillEqually
stackView.alignment = .center
addSubview(stackView)
stackView.snp.remakeConstraints { (make) in
make.left.greaterThanOrEqualTo(10)
make.right.lessThanOrEqualTo(-10)
// make the view as wide as possible
make.right.equalTo(-10).priority(900)
make.left.equalTo(10).priority(900)
//
make.bottom.equalTo(-10)
make.width.lessThanOrEqualTo(104 * 6 + 30)
make.centerX.equalToSuperview()
}
centerLabel = UILabel()
centerLabel.text = NSLocalizedString("队长", comment: "")
centerLabel.font = UIFont.systemFont(ofSize: 12)
centerLabel.adjustsFontSizeToFitWidth = true
addSubview(centerLabel)
centerLabel.snp.makeConstraints { (make) in
make.top.equalTo(5)
make.centerX.equalTo(editableItemViews[0])
make.bottom.equalTo(stackView.snp.top).offset(-5)
make.width.lessThanOrEqualTo(editableItemViews[0].snp.width).offset(-4)
}
guestLabel = UILabel()
guestLabel.text = NSLocalizedString("好友", comment: "")
guestLabel.font = UIFont.systemFont(ofSize: 12)
guestLabel.adjustsFontSizeToFitWidth = true
addSubview(guestLabel)
guestLabel.snp.makeConstraints { (make) in
make.top.equalTo(centerLabel)
make.width.lessThanOrEqualTo(editableItemViews[5].snp.width).offset(-4)
make.centerX.equalTo(editableItemViews[5])
}
}
@objc func handleTapGesture(_ tap: UITapGestureRecognizer) {
if let view = tap.view as? MemberEditableItemView {
if let index = stackView.arrangedSubviews.index(of: view) {
currentIndex = index
}
}
}
@objc func handleLongPressGesture(_ longPress: UILongPressGestureRecognizer) {
if longPress.state == .began {
guard let view = longPress.view as? MemberEditableItemView else { return }
if let index = stackView.arrangedSubviews.index(of: view) {
currentIndex = index
}
delegate?.memberGroupView(self, didLongPressAt: view)
}
}
@objc func handleDoubleTapGesture(_ doubleTap: UITapGestureRecognizer) {
guard let view = doubleTap.view as? MemberEditableItemView else { return }
delegate?.memberEditableView(self, didDoubleTap: view)
}
func setup(with unit: Unit) {
for i in 0..<6 {
let member = unit[i]
setup(with: member, at: i)
}
}
func moveIndexToNext() {
var nextIndex = currentIndex + 1
if nextIndex == 6 {
nextIndex = 0
}
currentIndex = nextIndex
}
func setup(with member: Member, at index: Int) {
editableItemViews[index].setup(with: member)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 49e94ca397ecaf1eca8213871ebd593f | 34.785124 | 125 | 0.624942 | 5.151695 | false | false | false | false |
jopamer/swift | test/Serialization/Recovery/typedefs.swift | 1 | 17515 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module -enable-objc-interop %s | %FileCheck -check-prefix CHECK-VTABLE %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD > %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -DVERIFY %s -verify
// RUN: %target-swift-frontend -emit-silgen -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-SIL %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD %S/Inputs/typedefs-helper.swift -verify
#if TEST
import Typedefs
import Lib
// CHECK-SIL-LABEL: sil hidden @$S8typedefs11testSymbolsyyF
func testSymbols() {
// Check that the symbols are not using 'Bool'.
// CHECK-SIL: function_ref @$S3Lib1xs5Int32Vvau
_ = Lib.x
// CHECK-SIL: function_ref @$S3Lib9usesAssocs5Int32VSgvau
_ = Lib.usesAssoc
} // CHECK-SIL: end sil function '$S8typedefs11testSymbolsyyF'
// CHECK-IR-LABEL: define{{.*}} void @"$S8typedefs18testVTableBuilding4usery3Lib4UserC_tF
public func testVTableBuilding(user: User) {
// The important thing in this CHECK line is the "i64 30", which is the offset
// for the vtable slot for 'lastMethod()'. If the layout here
// changes, please check that offset is still correct.
// CHECK-IR-NOT: ret
// CHECK-IR: getelementptr inbounds void (%T3Lib4UserC*)*, void (%T3Lib4UserC*)** %{{[0-9]+}}, {{i64 30|i32 33}}
_ = user.lastMethod()
} // CHECK-IR: ret void
#if VERIFY
let _: String = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'String'}}
let _: Bool? = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'Bool?'}}
let _: Int32? = useAssoc(ImportedType.self)
let _: String = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'String'}}
let _: Bool? = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'Bool?'}}
let _: Int32? = useAssoc(AnotherType.self)
let _ = wrapped // expected-error {{use of unresolved identifier 'wrapped'}}
let _ = unwrapped // okay
_ = usesWrapped(nil) // expected-error {{use of unresolved identifier 'usesWrapped'}}
_ = usesUnwrapped(nil) // expected-error {{'nil' is not compatible with expected argument type 'Int32'}}
let _: WrappedAlias = nil // expected-error {{use of undeclared type 'WrappedAlias'}}
let _: UnwrappedAlias = nil // expected-error {{'nil' cannot initialize specified type 'UnwrappedAlias' (aka 'Int32')}} expected-note {{add '?'}}
let _: ConstrainedWrapped<Int> = nil // expected-error {{use of undeclared type 'ConstrainedWrapped'}}
let _: ConstrainedUnwrapped<Int> = nil // expected-error {{type 'Int' does not conform to protocol 'HasAssoc'}}
func testExtensions(wrapped: WrappedInt, unwrapped: UnwrappedInt) {
wrapped.wrappedMethod() // expected-error {{value of type 'WrappedInt' (aka 'Int32') has no member 'wrappedMethod'}}
unwrapped.unwrappedMethod() // expected-error {{value of type 'UnwrappedInt' has no member 'unwrappedMethod'}}
***wrapped // This one works because of the UnwrappedInt extension.
***unwrapped // expected-error {{cannot convert value of type 'UnwrappedInt' to expected argument type 'Int32'}}
let _: WrappedProto = wrapped // expected-error {{value of type 'WrappedInt' (aka 'Int32') does not conform to specified type 'WrappedProto'}}
let _: UnwrappedProto = unwrapped // expected-error {{value of type 'UnwrappedInt' does not conform to specified type 'UnwrappedProto'}}
}
public class UserDynamicSub: UserDynamic {
override init() {}
}
// FIXME: Bad error message; really it's that the convenience init hasn't been
// inherited.
_ = UserDynamicSub(conveniently: 0) // expected-error {{argument passed to call that takes no arguments}}
public class UserDynamicConvenienceSub: UserDynamicConvenience {
override init() {}
}
_ = UserDynamicConvenienceSub(conveniently: 0)
public class UserSub : User {} // expected-error {{cannot inherit from class 'User' because it has overridable members that could not be loaded}}
#endif // VERIFY
#else // TEST
import Typedefs
prefix operator ***
// CHECK-LABEL: class User {
// CHECK-RECOVERY-LABEL: class User {
open class User {
// CHECK: var unwrappedProp: UnwrappedInt?
// CHECK-RECOVERY: var unwrappedProp: Int32?
public var unwrappedProp: UnwrappedInt?
// CHECK: var wrappedProp: WrappedInt?
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
public var wrappedProp: WrappedInt?
// CHECK: func returnsUnwrappedMethod() -> UnwrappedInt
// CHECK-RECOVERY: func returnsUnwrappedMethod() -> Int32
public func returnsUnwrappedMethod() -> UnwrappedInt { fatalError() }
// CHECK: func returnsWrappedMethod() -> WrappedInt
// CHECK-RECOVERY: /* placeholder for returnsWrappedMethod() */
public func returnsWrappedMethod() -> WrappedInt { fatalError() }
// CHECK: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == UnwrappedInt
// CHECK-RECOVERY: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == Int32
public func constrainedUnwrapped<T: HasAssoc>(_: T) where T.Assoc == UnwrappedInt { fatalError() }
// CHECK: func constrainedWrapped<T>(_: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for constrainedWrapped(_:) */
public func constrainedWrapped<T: HasAssoc>(_: T) where T.Assoc == WrappedInt { fatalError() }
// CHECK: subscript(_: WrappedInt) -> () { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript(_: WrappedInt) -> () { return () }
// CHECK: subscript<T>(_: T) -> () where T : HasAssoc, T.Assoc == WrappedInt { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript<T: HasAssoc>(_: T) -> () where T.Assoc == WrappedInt { return () }
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
// CHECK: convenience init<T>(generic: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for init(generic:) */
public convenience init<T: HasAssoc>(generic: T) where T.Assoc == WrappedInt { self.init() }
// CHECK: required init(wrappedRequired: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt) {}
// CHECK: {{^}} init(wrappedRequiredInSub: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public init(wrappedRequiredInSub: WrappedInt) {}
// CHECK: dynamic init(wrappedDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedDynamic:) */
@objc public dynamic init(wrappedDynamic: WrappedInt) {}
// CHECK: dynamic required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
@objc public dynamic required init(wrappedRequiredDynamic: WrappedInt) {}
public func lastMethod() {}
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// This is mostly to check when changes are necessary for the CHECK-IR lines
// above.
// CHECK-VTABLE-LABEL: sil_vtable [serialized] User {
// (10 words of normal class metadata on 64-bit platforms, 13 on 32-bit)
// 10 CHECK-VTABLE-NEXT: #User.unwrappedProp!getter.1:
// 11 CHECK-VTABLE-NEXT: #User.unwrappedProp!setter.1:
// 12 CHECK-VTABLE-NEXT: #User.unwrappedProp!materializeForSet.1:
// 13 CHECK-VTABLE-NEXT: #User.wrappedProp!getter.1:
// 14 CHECK-VTABLE-NEXT: #User.wrappedProp!setter.1:
// 15 CHECK-VTABLE-NEXT: #User.wrappedProp!materializeForSet.1:
// 16 CHECK-VTABLE-NEXT: #User.returnsUnwrappedMethod!1:
// 17 CHECK-VTABLE-NEXT: #User.returnsWrappedMethod!1:
// 18 CHECK-VTABLE-NEXT: #User.constrainedUnwrapped!1:
// 19 CHECK-VTABLE-NEXT: #User.constrainedWrapped!1:
// 20 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 21 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 22 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 23 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 24 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 25 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 26 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 27 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 28 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 29 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 30 CHECK-VTABLE-NEXT: #User.lastMethod!1:
// CHECK-VTABLE: }
// CHECK-LABEL: class UserConvenience
// CHECK-RECOVERY-LABEL: class UserConvenience
open class UserConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamic
// CHECK-RECOVERY-LABEL: class UserDynamic
open class UserDynamic {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamicConvenience
// CHECK-RECOVERY-LABEL: class UserDynamicConvenience
open class UserDynamicConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserSub
// CHECK-RECOVERY-LABEL: class UserSub
open class UserSub : User {
// CHECK: init(wrapped: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public override init(wrapped: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequired: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredInSub: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public required override init(wrappedRequiredInSub: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
public required init(wrappedRequiredDynamic: WrappedInt) { super.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-DAG: let x: MysteryTypedef
// CHECK-RECOVERY-DAG: let x: Int32
public let x: MysteryTypedef = 0
public protocol HasAssoc {
associatedtype Assoc
}
extension ImportedType: HasAssoc {}
public struct AnotherType: HasAssoc {
public typealias Assoc = MysteryTypedef
}
public func useAssoc<T: HasAssoc>(_: T.Type) -> T.Assoc? { return nil }
// CHECK-DAG: let usesAssoc: ImportedType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc: Int32?
public let usesAssoc = useAssoc(ImportedType.self)
// CHECK-DAG: let usesAssoc2: AnotherType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc2: AnotherType.Assoc?
public let usesAssoc2 = useAssoc(AnotherType.self)
// CHECK-DAG: let wrapped: WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: let wrapped:
public let wrapped = WrappedInt(0)
// CHECK-DAG: let unwrapped: UnwrappedInt
// CHECK-RECOVERY-DAG: let unwrapped: Int32
public let unwrapped: UnwrappedInt = 0
// CHECK-DAG: let wrappedMetatype: WrappedInt.Type
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedMetatype:
public let wrappedMetatype = WrappedInt.self
// CHECK-DAG: let wrappedOptional: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedOptional:
public let wrappedOptional: WrappedInt? = nil
// CHECK-DAG: let wrappedIUO: WrappedInt!
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedIUO:
public let wrappedIUO: WrappedInt! = nil
// CHECK-DAG: let wrappedArray: [WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedArray:
public let wrappedArray: [WrappedInt] = []
// CHECK-DAG: let wrappedDictionary: [Int : WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedDictionary:
public let wrappedDictionary: [Int: WrappedInt] = [:]
// CHECK-DAG: let wrappedTuple: (WrappedInt, Int)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple:
public let wrappedTuple: (WrappedInt, Int)? = nil
// CHECK-DAG: let wrappedTuple2: (Int, WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple2:
public let wrappedTuple2: (Int, WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure: ((WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure:
public let wrappedClosure: ((WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosure2: (() -> WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure2:
public let wrappedClosure2: (() -> WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure3: ((Int, WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure3:
public let wrappedClosure3: ((Int, WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosureInout: ((inout WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosureInout:
public let wrappedClosureInout: ((inout WrappedInt) -> Void)? = nil
// CHECK-DAG: var wrappedFirst: WrappedInt?
// CHECK-DAG: var normalSecond: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFirst:
// CHECK-RECOVERY-DAG: var normalSecond: Int?
public var wrappedFirst: WrappedInt?, normalSecond: Int?
// CHECK-DAG: var normalFirst: Int?
// CHECK-DAG: var wrappedSecond: WrappedInt?
// CHECK-RECOVERY-DAG: var normalFirst: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedSecond:
public var normalFirst: Int?, wrappedSecond: WrappedInt?
// CHECK-DAG: var wrappedThird: WrappedInt?
// CHECK-DAG: var wrappedFourth: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedThird:
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFourth:
public var wrappedThird, wrappedFourth: WrappedInt?
// CHECK-DAG: func usesWrapped(_ wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: func usesWrapped(
public func usesWrapped(_ wrapped: WrappedInt) {}
// CHECK-DAG: func usesUnwrapped(_ unwrapped: UnwrappedInt)
// CHECK-RECOVERY-DAG: func usesUnwrapped(_ unwrapped: Int32)
public func usesUnwrapped(_ unwrapped: UnwrappedInt) {}
// CHECK-DAG: func returnsWrapped() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrapped(
public func returnsWrapped() -> WrappedInt { fatalError() }
// CHECK-DAG: func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedGeneric<
public func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt { fatalError() }
public protocol WrappedProto {}
public protocol UnwrappedProto {}
public typealias WrappedAlias = WrappedInt
public typealias UnwrappedAlias = UnwrappedInt
public typealias ConstrainedWrapped<T: HasAssoc> = T where T.Assoc == WrappedInt
public typealias ConstrainedUnwrapped<T: HasAssoc> = T where T.Assoc == UnwrappedInt
// CHECK-LABEL: extension Int32 : UnwrappedProto {
// CHECK-NEXT: func unwrappedMethod()
// CHECK-NEXT: prefix static func *** (x: UnwrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: extension Int32 : UnwrappedProto {
// CHECK-RECOVERY-NEXT: func unwrappedMethod()
// CHECK-RECOVERY-NEXT: prefix static func *** (x: Int32)
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension UnwrappedInt
extension UnwrappedInt: UnwrappedProto {
public func unwrappedMethod() {}
public static prefix func ***(x: UnwrappedInt) {}
}
// CHECK-LABEL: extension WrappedInt : WrappedProto {
// CHECK-NEXT: func wrappedMethod()
// CHECK-NEXT: prefix static func *** (x: WrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension WrappedInt
extension WrappedInt: WrappedProto {
public func wrappedMethod() {}
public static prefix func ***(x: WrappedInt) {}
}
#endif // TEST
| apache-2.0 | 5d78a579b5ce5955877811d521b6648f | 42.461538 | 240 | 0.72161 | 3.928892 | false | false | false | false |
lukevanin/OCRAI | CardScanner/Vertex.swift | 1 | 834 | //
// FragmentAnnotationVertex.swift
// CardScanner
//
// Created by Luke Van In on 2017/02/28.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import Foundation
import UIKit
import CoreData
private let entityName = "Vertex"
extension Vertex {
var point: CGPoint {
get {
return CGPoint(x: self.x, y: self.y)
}
set {
self.x = Double(newValue.x)
self.y = Double(newValue.y)
}
}
convenience init(x: Double, y: Double, context: NSManagedObjectContext) {
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
fatalError("Cannot initialize entity \(entityName)")
}
self.init(entity: entity, insertInto: context)
self.x = x
self.y = y
}
}
| mit | c59b5c6f9863d2ac1da4414038bc14ed | 22.8 | 100 | 0.59904 | 4.103448 | false | false | false | false |
osorioabel/my-location-app | My Locations/My Locations/Controllers/MapViewController.swift | 1 | 6004 | //
// MapViewController.swift
// My Locations
//
// Created by Abel Osorio on 2/17/16.
// Copyright © 2016 Abel Osorio. All rights reserved.
//
import UIKit
import CoreData
import MapKit
class MapViewController: UIViewController {
var managedObjectContext: NSManagedObjectContext! {
didSet {
NSNotificationCenter.defaultCenter().addObserverForName( NSManagedObjectContextObjectsDidChangeNotification,object: managedObjectContext,queue: NSOperationQueue.mainQueue()) {
notification in if self.isViewLoaded() {
self.updateLocations()
}
}
}
}
var locations = [Location]()
@IBOutlet weak var mapView: MKMapView!
// MARK: - LifeCycle
override func viewDidLoad() {
updateLocations()
if !locations.isEmpty{
showLocations()
}
}
func updateLocations() {
mapView.removeAnnotations(locations)
let entity = NSEntityDescription.entityForName("Location", inManagedObjectContext: managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entity
mapView.delegate = self
locations = try! managedObjectContext.executeFetchRequest( fetchRequest) as! [Location]
mapView.addAnnotations(locations)
}
// MARK: - Actions
@IBAction func showUser() {
let region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)
mapView.setRegion(mapView.regionThatFits(region), animated: true)
}
@IBAction func showLocations() {
let region = regionForAnnotations(locations)
mapView.setRegion(region, animated: true)
}
func regionForAnnotations(annotations: [MKAnnotation])-> MKCoordinateRegion {
var region: MKCoordinateRegion
switch annotations.count {
case 0:
region = MKCoordinateRegionMakeWithDistance(mapView.userLocation.coordinate, 1000, 1000)
case 1:
let annotation = annotations[annotations.count - 1]
region = MKCoordinateRegionMakeWithDistance(annotation.coordinate, 1000, 1000)
default:
var topLeftCoord = CLLocationCoordinate2D(latitude: -90,longitude: 180)
var bottomRightCoord = CLLocationCoordinate2D(latitude: 90,longitude: -180)
for annotation in annotations {
topLeftCoord.latitude = max(topLeftCoord.latitude,annotation.coordinate.latitude)
topLeftCoord.longitude = min(topLeftCoord.longitude,annotation.coordinate.longitude)
bottomRightCoord.latitude = min(bottomRightCoord.latitude,annotation.coordinate.latitude)
bottomRightCoord.longitude = max(bottomRightCoord.longitude,annotation.coordinate.longitude)
}
let finallatitude = topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) / 2
let finallongitude = topLeftCoord.longitude - (topLeftCoord.longitude - bottomRightCoord.longitude) / 2
let center = CLLocationCoordinate2D(latitude: finallatitude, longitude: finallongitude)
let extraSpace = 1.1
let span = MKCoordinateSpan(latitudeDelta: abs(topLeftCoord.latitude - bottomRightCoord.latitude) * extraSpace,longitudeDelta: abs(topLeftCoord.longitude - bottomRightCoord.longitude) * extraSpace)
region = MKCoordinateRegion(center: center, span: span)
}
return mapView.regionThatFits(region)
}
func showLocationDetails(sender: UIButton) {
performSegueWithIdentifier("EditLocation", sender: sender)
}
// MARK: - Navegation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditLocation" {
let navigationController = segue.destinationViewController as! UINavigationController
let controller = navigationController.topViewController as! LocationDetailsViewController
controller.managedObjectContext = managedObjectContext
let button = sender as! UIButton
let location = locations[button.tag]
controller.locationToEdit = location
}
}
}
// MARK: - NavigationDelegate
extension MapViewController: UINavigationBarDelegate {
func positionForBar(bar: UIBarPositioning) -> UIBarPosition {
return .TopAttached }
}
// MARK: - MapViewDelegate
extension MapViewController: MKMapViewDelegate {
func mapView(mapView: MKMapView,viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
guard annotation is Location else {
return nil
}
let identifier = "Location"
var annotationView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) as! MKPinAnnotationView!
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: annotation,reuseIdentifier: identifier)
annotationView.enabled = true
annotationView.canShowCallout = true
annotationView.animatesDrop = false
annotationView.tintColor = UIColor(white: 0.0, alpha: 0.5)
if #available(iOS 9.0, *) {
annotationView.pinTintColor = UIColor(red: 0.32, green: 0.82,blue: 0.4, alpha: 1)
} else {
// Fallback on earlier versions
}
let rightButton = UIButton(type: .DetailDisclosure)
rightButton.addTarget(self,action: Selector("showLocationDetails:"),forControlEvents: .TouchUpInside)
annotationView.rightCalloutAccessoryView = rightButton
} else {
annotationView.annotation = annotation
}
let button = annotationView.rightCalloutAccessoryView as! UIButton
if let index = locations.indexOf(annotation as! Location) {
button.tag = index
}
return annotationView
}
}
| mit | 9a5630a14aaacd0b4dc588dc3b43bfee | 34.311765 | 201 | 0.671498 | 5.605042 | false | false | false | false |
KagasiraBunJee/TryHard | TryHard/THVideoController.swift | 1 | 6233 | //
// THVideoController.swift
// TryHard
//
// Created by Sergey on 6/17/16.
// Copyright © 2016 Sergey Polishchuk. All rights reserved.
//
import UIKit
import AVFoundation
class THVideoController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var viewOverlay: UIView!
var videoDataOutput: AVCaptureVideoDataOutput!
var videoDataOutputQueue : dispatch_queue_t = dispatch_get_main_queue()
var previewLayer:AVCaptureVideoPreviewLayer!
var captureDevice : AVCaptureDevice!
let session = AVCaptureSession()
var currentBuffer:CVImageBuffer!
var currentImage = UIImage()
var layers:[CALayer] = [CALayer]()
var camera:THCameraManager!
override func viewDidLoad() {
super.viewDidLoad()
// initCamera()
camera = THCameraManager(parentView: imageView)
}
func initOpenCVCam() {
camera.setParentView(imageView)
}
func initCamera() {
let inputDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let captureInput:AVCaptureDeviceInput?
do {
captureInput = try AVCaptureDeviceInput(device: inputDevice)
} catch let error as NSError {
print(error)
return
}
let captureOut = AVCaptureVideoDataOutput()
captureOut.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
session.sessionPreset = AVCaptureSessionPresetMedium
if session.canAddInput(captureInput) {
session.addInput(captureInput)
}
if session.canAddOutput(captureOut) {
session.addOutput(captureOut)
let connection = captureOut.connectionWithMediaType(AVFoundation.AVMediaTypeVideo)
connection.videoOrientation = .Portrait
}
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.frame = CGRectMake(0, 0, self.imageView.frame.width, self.imageView.frame.height)
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
imageView.layer.insertSublayer(previewLayer, atIndex: 0)
while layers.count < 100 {
let layer = CALayer()
layer.borderColor = UIColor.redColor().CGColor
layer.borderWidth = 3.0
layer.frame = CGRectZero
layers.append(layer)
viewOverlay.layer.insertSublayer(layer, atIndex: 0)
}
// let layer = CALayer()
// layer.borderColor = UIColor.redColor().CGColor
// layer.borderWidth = 5.0
// layer.frame = CGRectMake(50, 50, 100, 100)
// viewOverlay.layer.insertSublayer(layer, atIndex: 0)
imageView.clipsToBounds = true
}
func convertSampleBufferToImage(buffer:CVImageBuffer) -> UIImage {
// let ciImage = CIImage(CVImageBuffer: buffer)
// let ctx = CIContext(options: nil)
// let imageRef = ctx.createCGImage(ciImage, fromRect: CGRectMake(0, 0, CGFloat(CVPixelBufferGetWidth(buffer)), CGFloat(CVPixelBufferGetHeight(buffer))))
// return UIImage(CIImage: ciImage)
// let srcPtr = Unmanaged.passUnretained(currentBuffer).toOpaque()
// let pixelBuffer:Unmanaged<CVImageBuffer>? = Unmanaged<CVImageBuffer>.fromOpaque(srcPtr)
//
// let cc = unsafeBitCast(pixelBuffer, UnsafeMutablePointer<Unmanaged<CVImageBuffer>?>.self)
CVPixelBufferLockBaseAddress(currentBuffer, UInt64(0))
let addr = CVPixelBufferGetBaseAddressOfPlane(currentBuffer, 0)
let width = CVPixelBufferGetWidth(currentBuffer)
let height = CVPixelBufferGetHeight(currentBuffer)
let image = THVideoHelper.inspectVideoWithAddress(addr, width: Int32(width), height: Int32(height))
CVPixelBufferUnlockBaseAddress(currentBuffer, UInt64(0))
return image
}
//MARK:- IBActions
@IBAction func startAction(sender: AnyObject) {
// previewLayer.frame = CGRectMake(0, 0, self.imageView.frame.width, self.imageView.frame.height)
// previewLayer.masksToBounds = true
//
// session.startRunning()
camera.startSession()
}
@IBAction func stopAction(sender: AnyObject) {
// session.stopRunning()
camera.stopSession()
}
@IBAction func detectAction(sender: AnyObject) {
session.stopRunning()
let vc = VCLoader<THHelpVC>.load(storyboardId: .VideoProcessing, inStoryboardID: "THHelpVC")
vc.image = currentImage
self.navigationController?.pushViewController(vc, animated: true)
}
//MARK:- AVCaptureVideoDataOutputSampleBufferDelegate
func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBuffer!, fromConnection connection: AVCaptureConnection!) {
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),{
let bounds = (THVideoHelper.createIplImageFromSampleBuffer(sampleBuffer) as! [NSValue]).map { (value) -> CGRect in
return value.CGRectValue()
}
dispatch_async(dispatch_get_main_queue(),{
for (index,frame) in bounds.enumerate() {
self.layers[index].frame = frame
}
})
})
// print(bounds)
//
// let uiimage = UIImage(CGImage: cgimage)
// let rects = uiimage.textBoundsV2()
// if rects.count > 0 {
// print("text found")
// }
// let ciImage = CIImage(CVImageBuffer: currentBuffer)
// let image1 = UIImage(CIImage: ciImage)
//
// let image = image1.copy() as! UIImage
//
// currentImage = image
//
// let rects = image.textBoundsV2()
// if rects.count > 0 {
// print("text found")
// }
}
}
| mit | 1badf4b94f70fd1f1ba5e5fc9f896bb8 | 31.8 | 160 | 0.616656 | 5.104013 | false | false | false | false |
noraesae/kawa | kawa/ShortcutViewController.swift | 1 | 1284 | import Cocoa
class ShortcutViewController: NSViewController, NSTableViewDataSource, NSTableViewDelegate {
func numberOfRows(in tableView: NSTableView) -> Int {
return InputSource.sources.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let inputSource = InputSource.sources[row]
switch tableColumn!.identifier.rawValue {
case "Keyboard":
return createKeyboardCellView(tableView, inputSource)
case "Shortcut":
return createShorcutCellView(tableView, inputSource)
default:
return nil
}
}
func createKeyboardCellView(_ tableView: NSTableView, _ inputSource: InputSource) -> NSTableCellView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "KeyboardCellView"), owner: self) as? NSTableCellView
cell!.textField?.stringValue = inputSource.name
cell!.imageView?.image = inputSource.icon
return cell
}
func createShorcutCellView(_ tableView: NSTableView, _ inputSource: InputSource) -> ShortcutCellView? {
let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "ShortcutCellView"), owner: self) as? ShortcutCellView
cell?.setInputSource(inputSource)
return cell
}
}
| mit | bdd85acbe4da7cb10740b47c69e49a2b | 37.909091 | 144 | 0.753115 | 5.055118 | false | false | false | false |
BanyaKrylov/Learn-Swift | Skill/Homework 14/Pods/RealmSwift/RealmSwift/RealmCollection.swift | 4 | 39692 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
/**
An iterator for a `RealmCollection` instance.
*/
public struct RLMIterator<Element: RealmCollectionValue>: IteratorProtocol {
private var generatorBase: NSFastEnumerationIterator
init(collection: RLMCollection) {
generatorBase = NSFastEnumerationIterator(collection)
}
/// Advance to the next element and return it, or `nil` if no next element exists.
public mutating func next() -> Element? {
let next = generatorBase.next()
if next is NSNull {
return Element._nilValue()
}
if let next = next as? Object? {
if next == nil {
return nil as Element?
}
return unsafeBitCast(next, to: Optional<Element>.self)
}
return dynamicBridgeCast(fromObjectiveC: next as Any)
}
}
/**
A `RealmCollectionChange` value encapsulates information about changes to collections
that are reported by Realm notifications.
The change information is available in two formats: a simple array of row
indices in the collection for each type of change, and an array of index paths
in a requested section suitable for passing directly to `UITableView`'s batch
update methods.
The arrays of indices in the `.update` case follow `UITableView`'s batching
conventions, and can be passed as-is to a table view's batch update functions after being converted to index paths.
For example, for a simple one-section table view, you can do the following:
```swift
self.notificationToken = results.observe { changes in
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self.tableView.reloadData()
break
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed, so apply them to the TableView
self.tableView.beginUpdates()
self.tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) },
with: .automatic)
self.tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) },
with: .automatic)
self.tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) },
with: .automatic)
self.tableView.endUpdates()
break
case .error(let err):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(err)")
break
}
}
```
*/
public enum RealmCollectionChange<CollectionType> {
/**
`.initial` indicates that the initial run of the query has completed (if
applicable), and the collection can now be used without performing any
blocking work.
*/
case initial(CollectionType)
/**
`.update` indicates that a write transaction has been committed which
either changed which objects are in the collection, and/or modified one
or more of the objects in the collection.
All three of the change arrays are always sorted in ascending order.
- parameter deletions: The indices in the previous version of the collection which were removed from this one.
- parameter insertions: The indices in the new collection which were added in this version.
- parameter modifications: The indices of the objects in the new collection which were modified in this version.
*/
case update(CollectionType, deletions: [Int], insertions: [Int], modifications: [Int])
/**
If an error occurs, notification blocks are called one time with a `.error`
result and an `NSError` containing details about the error. This can only
currently happen if opening the Realm on a background thread to calcuate
the change set fails. The callback will never be called again after it is
invoked with a .error value.
*/
case error(Error)
static func fromObjc(value: CollectionType, change: RLMCollectionChange?, error: Error?) -> RealmCollectionChange {
if let error = error {
return .error(error)
}
if let change = change {
return .update(value,
deletions: forceCast(change.deletions, to: [Int].self),
insertions: forceCast(change.insertions, to: [Int].self),
modifications: forceCast(change.modifications, to: [Int].self))
}
return .initial(value)
}
}
private func forceCast<A, U>(_ from: A, to type: U.Type) -> U {
return from as! U
}
/// A type which can be stored in a Realm List or Results.
///
/// Declaring additional types as conforming to this protocol will not make them
/// actually work. Most of the logic for how to store values in Realm is not
/// implemented in Swift and there is currently no extension mechanism for
/// supporting more types.
public protocol RealmCollectionValue: Equatable {
/// :nodoc:
static func _rlmArray() -> RLMArray<AnyObject>
/// :nodoc:
static func _nilValue() -> Self
}
extension RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .int, optional: false)
}
/// :nodoc:
public static func _nilValue() -> Self {
fatalError("unexpected NSNull for non-Optional type")
}
}
private func arrayType<T>(_ type: T.Type) -> RLMArray<AnyObject> {
switch type {
case is Int.Type, is Int8.Type, is Int16.Type, is Int32.Type, is Int64.Type:
return RLMArray(objectType: .int, optional: true)
case is Bool.Type: return RLMArray(objectType: .bool, optional: true)
case is Float.Type: return RLMArray(objectType: .float, optional: true)
case is Double.Type: return RLMArray(objectType: .double, optional: true)
case is String.Type: return RLMArray(objectType: .string, optional: true)
case is Data.Type: return RLMArray(objectType: .data, optional: true)
case is Date.Type: return RLMArray(objectType: .date, optional: true)
default: fatalError("Unsupported type for List: \(type)?")
}
}
extension Optional: RealmCollectionValue where Wrapped: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return arrayType(Wrapped.self)
}
/// :nodoc:
public static func _nilValue() -> Optional {
return nil
}
}
extension Int: RealmCollectionValue {}
extension Int8: RealmCollectionValue {}
extension Int16: RealmCollectionValue {}
extension Int32: RealmCollectionValue {}
extension Int64: RealmCollectionValue {}
extension Float: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .float, optional: false)
}
}
extension Double: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .double, optional: false)
}
}
extension Bool: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .bool, optional: false)
}
}
extension String: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .string, optional: false)
}
}
extension Date: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .date, optional: false)
}
}
extension Data: RealmCollectionValue {
/// :nodoc:
public static func _rlmArray() -> RLMArray<AnyObject> {
return RLMArray(objectType: .data, optional: false)
}
}
/// :nodoc:
public protocol _RealmCollectionEnumerator {
// swiftlint:disable:next identifier_name
func _asNSFastEnumerator() -> Any
}
/// :nodoc:
public protocol RealmCollectionBase: RandomAccessCollection, LazyCollectionProtocol, CustomStringConvertible, ThreadConfined where Element: RealmCollectionValue {
// This typealias was needed with Swift 3.1. It no longer is, but remains
// just in case someone was depending on it
typealias ElementType = Element
}
/**
A homogenous collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
*/
public protocol RealmCollection: RealmCollectionBase, _RealmCollectionEnumerator {
// Must also conform to `AssistedObjectiveCBridgeable`
// MARK: Properties
/// The Realm which manages the collection, or `nil` for unmanaged collections.
var realm: Realm? { get }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the `Realm` that manages the collection.
*/
var isInvalidated: Bool { get }
/// The number of objects in the collection.
var count: Int { get }
/// A human-readable description of the objects contained in the collection.
var description: String { get }
// MARK: Index Retrieval
/**
Returns the index of an object in the collection, or `nil` if the object is not present.
- parameter object: An object.
*/
func index(of object: Element) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicate: The predicate to use to filter the objects.
*/
func index(matching predicate: NSPredicate) -> Int?
/**
Returns the index of the first object matching the predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func index(matching predicateFormat: String, _ args: Any...) -> Int?
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element>
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate to use to filter the objects.
*/
func filter(_ predicate: NSPredicate) -> Results<Element>
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element>
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
*/
func sum<T: AddableType>(ofProperty property: String) -> T
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if
the collection is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func average(ofProperty property: String) -> Double?
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
func value(forKey key: String) -> Any?
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
func value(forKeyPath keyPath: String) -> Any?
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(_ value: Any?, forKey key: String)
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func observe(_ block: @escaping (RealmCollectionChange<Self>) -> Void) -> NotificationToken
/// :nodoc:
func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection<Element>>) -> Void) -> NotificationToken
}
/// :nodoc:
public protocol OptionalProtocol {
associatedtype Wrapped
/// :nodoc:
// swiftlint:disable:next identifier_name
func _rlmInferWrappedType() -> Wrapped
}
extension Optional: OptionalProtocol {
/// :nodoc:
// swiftlint:disable:next identifier_name
public func _rlmInferWrappedType() -> Wrapped { return self! }
}
public extension RealmCollection where Element: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Element? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Element? {
return max(ofProperty: "self")
}
}
public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Element.Wrapped? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Element.Wrapped? {
return max(ofProperty: "self")
}
}
public extension RealmCollection where Element: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Element {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average() -> Double? {
return average(ofProperty: "self")
}
}
public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Element.Wrapped {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average() -> Double? {
return average(ofProperty: "self")
}
}
public extension RealmCollection where Element: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Element> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
public extension RealmCollection where Element: OptionalProtocol, Element.Wrapped: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Element> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
private class _AnyRealmCollectionBase<T: RealmCollectionValue>: AssistedObjectiveCBridgeable {
typealias Wrapper = AnyRealmCollection<Element>
typealias Element = T
var realm: Realm? { fatalError() }
var isInvalidated: Bool { fatalError() }
var count: Int { fatalError() }
var description: String { fatalError() }
func index(of object: Element) -> Int? { fatalError() }
func index(matching predicate: NSPredicate) -> Int? { fatalError() }
func index(matching predicateFormat: String, _ args: Any...) -> Int? { fatalError() }
func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> { fatalError() }
func filter(_ predicate: NSPredicate) -> Results<Element> { fatalError() }
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> { fatalError() }
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element> where S.Iterator.Element == SortDescriptor {
fatalError()
}
func min<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
func max<T: MinMaxType>(ofProperty property: String) -> T? { fatalError() }
func sum<T: AddableType>(ofProperty property: String) -> T { fatalError() }
func average(ofProperty property: String) -> Double? { fatalError() }
subscript(position: Int) -> Element { fatalError() }
func makeIterator() -> RLMIterator<T> { fatalError() }
var startIndex: Int { fatalError() }
var endIndex: Int { fatalError() }
func value(forKey key: String) -> Any? { fatalError() }
func value(forKeyPath keyPath: String) -> Any? { fatalError() }
func setValue(_ value: Any?, forKey key: String) { fatalError() }
func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { fatalError() }
class func bridging(from objectiveCValue: Any, with metadata: Any?) -> Self { fatalError() }
var bridged: (objectiveCValue: Any, metadata: Any?) { fatalError() }
// swiftlint:disable:next identifier_name
func _asNSFastEnumerator() -> Any { fatalError() }
}
private final class _AnyRealmCollection<C: RealmCollection>: _AnyRealmCollectionBase<C.Element> {
let base: C
init(base: C) {
self.base = base
}
// MARK: Properties
override var realm: Realm? { return base.realm }
override var isInvalidated: Bool { return base.isInvalidated }
override var count: Int { return base.count }
override var description: String { return base.description }
// MARK: Index Retrieval
override func index(of object: C.Element) -> Int? { return base.index(of: object) }
override func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
override func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
}
// MARK: Filtering
override func filter(_ predicateFormat: String, _ args: Any...) -> Results<C.Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
}
override func filter(_ predicate: NSPredicate) -> Results<C.Element> { return base.filter(predicate) }
// MARK: Sorting
override func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<C.Element> {
return base.sorted(byKeyPath: keyPath, ascending: ascending)
}
override func sorted<S: Sequence>
(by sortDescriptors: S) -> Results<C.Element> where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
override func min<T: MinMaxType>(ofProperty property: String) -> T? {
return base.min(ofProperty: property)
}
override func max<T: MinMaxType>(ofProperty property: String) -> T? {
return base.max(ofProperty: property)
}
override func sum<T: AddableType>(ofProperty property: String) -> T {
return base.sum(ofProperty: property)
}
override func average(ofProperty property: String) -> Double? {
return base.average(ofProperty: property)
}
// MARK: Sequence Support
override subscript(position: Int) -> C.Element {
return base[position as! C.Index]
}
override func makeIterator() -> RLMIterator<Element> {
// FIXME: it should be possible to avoid this force-casting
return base.makeIterator() as! RLMIterator<Element>
}
/// :nodoc:
override func _asNSFastEnumerator() -> Any {
return base._asNSFastEnumerator()
}
// MARK: Collection Support
override var startIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.startIndex as! Int
}
override var endIndex: Int {
// FIXME: it should be possible to avoid this force-casting
return base.endIndex as! Int
}
// MARK: Key-Value Coding
override func value(forKey key: String) -> Any? { return base.value(forKey: key) }
override func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
override func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/// :nodoc:
override func _observe(_ block: @escaping (RealmCollectionChange<Wrapper>) -> Void)
-> NotificationToken { return base._observe(block) }
// MARK: AssistedObjectiveCBridgeable
override class func bridging(from objectiveCValue: Any, with metadata: Any?) -> _AnyRealmCollection {
return _AnyRealmCollection(
base: (C.self as! AssistedObjectiveCBridgeable.Type).bridging(from: objectiveCValue, with: metadata) as! C)
}
override var bridged: (objectiveCValue: Any, metadata: Any?) {
return (base as! AssistedObjectiveCBridgeable).bridged
}
}
/**
A type-erased `RealmCollection`.
Instances of `RealmCollection` forward operations to an opaque underlying collection having the same `Element` type.
*/
public struct AnyRealmCollection<Element: RealmCollectionValue>: RealmCollection {
/// The type of the objects contained within the collection.
public typealias ElementType = Element
public func index(after i: Int) -> Int { return i + 1 }
public func index(before i: Int) -> Int { return i - 1 }
/// The type of the objects contained in the collection.
fileprivate let base: _AnyRealmCollectionBase<Element>
fileprivate init(base: _AnyRealmCollectionBase<Element>) {
self.base = base
}
/// Creates an `AnyRealmCollection` wrapping `base`.
public init<C: RealmCollection>(_ base: C) where C.Element == Element {
self.base = _AnyRealmCollection(base: base)
}
// MARK: Properties
/// The Realm which manages the collection, or `nil` if the collection is unmanaged.
public var realm: Realm? { return base.realm }
/**
Indicates if the collection can no longer be accessed.
The collection can no longer be accessed if `invalidate()` is called on the containing `realm`.
*/
public var isInvalidated: Bool { return base.isInvalidated }
/// The number of objects in the collection.
public var count: Int { return base.count }
/// A human-readable description of the objects contained in the collection.
public var description: String { return base.description }
// MARK: Index Retrieval
/**
Returns the index of the given object, or `nil` if the object is not in the collection.
- parameter object: An object.
*/
public func index(of object: Element) -> Int? { return base.index(of: object) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicate: The predicate with which to filter the objects.
*/
public func index(matching predicate: NSPredicate) -> Int? { return base.index(matching: predicate) }
/**
Returns the index of the first object matching the given predicate, or `nil` if no objects match.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func index(matching predicateFormat: String, _ args: Any...) -> Int? {
return base.index(matching: NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
}
// MARK: Filtering
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicateFormat: A predicate format string, optionally followed by a variable number of arguments.
*/
public func filter(_ predicateFormat: String, _ args: Any...) -> Results<Element> {
return base.filter(NSPredicate(format: predicateFormat, argumentArray: unwrapOptionals(in: args)))
}
/**
Returns a `Results` containing all objects matching the given predicate in the collection.
- parameter predicate: The predicate with which to filter the objects.
- returns: A `Results` containing objects that match the given predicate.
*/
public func filter(_ predicate: NSPredicate) -> Results<Element> { return base.filter(predicate) }
// MARK: Sorting
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
public func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Element> {
return base.sorted(byKeyPath: keyPath, ascending: ascending)
}
/**
Returns a `Results` containing the objects in the collection, but sorted.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
- parameter sortDescriptors: A sequence of `SortDescriptor`s to sort by.
*/
public func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Element>
where S.Iterator.Element == SortDescriptor {
return base.sorted(by: sortDescriptors)
}
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func min<T: MinMaxType>(ofProperty property: String) -> T? {
return base.min(ofProperty: property)
}
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
public func max<T: MinMaxType>(ofProperty property: String) -> T? {
return base.max(ofProperty: property)
}
/**
Returns the sum of the values of a given property over all the objects in the collection.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
public func sum<T: AddableType>(ofProperty property: String) -> T { return base.sum(ofProperty: property) }
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if the collection is
empty.
- warning: Only the name of a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose average value should be calculated.
*/
public func average(ofProperty property: String) -> Double? { return base.average(ofProperty: property) }
// MARK: Sequence Support
/**
Returns the object at the given `index`.
- parameter index: The index.
*/
public subscript(position: Int) -> Element { return base[position] }
/// Returns a `RLMIterator` that yields successive elements in the collection.
public func makeIterator() -> RLMIterator<Element> { return base.makeIterator() }
/// :nodoc:
// swiftlint:disable:next identifier_name
public func _asNSFastEnumerator() -> Any { return base._asNSFastEnumerator() }
// MARK: Collection Support
/// The position of the first element in a non-empty collection.
/// Identical to endIndex in an empty collection.
public var startIndex: Int { return base.startIndex }
/// The collection's "past the end" position.
/// endIndex is not a valid argument to subscript, and is always reachable from startIndex by
/// zero or more applications of successor().
public var endIndex: Int { return base.endIndex }
// MARK: Key-Value Coding
/**
Returns an `Array` containing the results of invoking `valueForKey(_:)` with `key` on each of the collection's
objects.
- parameter key: The name of the property whose values are desired.
*/
public func value(forKey key: String) -> Any? { return base.value(forKey: key) }
/**
Returns an `Array` containing the results of invoking `valueForKeyPath(_:)` with `keyPath` on each of the
collection's objects.
- parameter keyPath: The key path to the property whose values are desired.
*/
public func value(forKeyPath keyPath: String) -> Any? { return base.value(forKeyPath: keyPath) }
/**
Invokes `setValue(_:forKey:)` on each of the collection's objects using the specified `value` and `key`.
- warning: This method may only be called during a write transaction.
- parameter value: The value to set the property to.
- parameter key: The name of the property whose value should be set on each object.
*/
public func setValue(_ value: Any?, forKey key: String) { base.setValue(value, forKey: key) }
// MARK: Notifications
/**
Registers a block to be called each time the collection changes.
The block will be asynchronously called with the initial results, and then called again after each write
transaction which changes either any of the objects in the collection, or which objects are in the collection.
The `change` parameter that is passed to the block reports, in the form of indices within the collection, which of
the objects were added, removed, or modified during each write transaction. See the `RealmCollectionChange`
documentation for more information on the change information supplied and an example of how to use it to update a
`UITableView`.
At the time when the block is called, the collection will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
Notifications are delivered via the standard run loop, and so can't be delivered while the run loop is blocked by
other activity. When notifications can't be delivered instantly, multiple notifications may be coalesced into a
single notification. This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let results = realm.objects(Dog.self)
print("dogs.count: \(dogs?.count)") // => 0
let token = dogs.observe { changes in
switch changes {
case .initial(let dogs):
// Will print "dogs.count: 1"
print("dogs.count: \(dogs.count)")
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
let dog = Dog()
dog.name = "Rex"
person.dogs.append(dog)
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
public func observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
-> NotificationToken { return base._observe(block) }
/// :nodoc:
public func _observe(_ block: @escaping (RealmCollectionChange<AnyRealmCollection>) -> Void)
-> NotificationToken { return base._observe(block) }
}
// MARK: AssistedObjectiveCBridgeable
private struct AnyRealmCollectionBridgingMetadata<T: RealmCollectionValue> {
var baseMetadata: Any?
var baseType: _AnyRealmCollectionBase<T>.Type
}
extension AnyRealmCollection: AssistedObjectiveCBridgeable {
static func bridging(from objectiveCValue: Any, with metadata: Any?) -> AnyRealmCollection {
guard let metadata = metadata as? AnyRealmCollectionBridgingMetadata<Element> else { preconditionFailure() }
return AnyRealmCollection(base: metadata.baseType.bridging(from: objectiveCValue, with: metadata.baseMetadata))
}
var bridged: (objectiveCValue: Any, metadata: Any?) {
return (
objectiveCValue: base.bridged.objectiveCValue,
metadata: AnyRealmCollectionBridgingMetadata(baseMetadata: base.bridged.metadata, baseType: type(of: base))
)
}
}
| apache-2.0 | 8e6d5d3ef304371eb48ef480cb7b9cf2 | 37.312741 | 162 | 0.680187 | 4.708422 | false | false | false | false |
cpuu/OTT | OTT/Group2ViewController.swift | 1 | 3047 | //
// Group2ViewController.swift
// BlueCap
//
// Created by 박재유 on 2016. 6. 1..
// Copyright © 2016년 Troy Stribling. All rights reserved.
//
import UIKit
class Group2ViewController: UIViewController {
@IBOutlet weak var txtName: UITextField!
@IBOutlet weak var txtMarks: UITextField!
var isEdit : Bool = false
var groupData : Group!
override func viewDidLoad() {
super.viewDidLoad()
if(isEdit)
{
txtName.text = groupData.GROUP_NM;
//txtMarks.text = groupData.GROUP_VALUE;
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: UIButton Action methods
@IBAction func btnBackClicked(sender: AnyObject)
{
self.navigationController?.popViewControllerAnimated(true)
}
@IBAction func btnSaveClicked(sender: AnyObject)
{
if(txtName.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter friend name.", delegate: nil)
}
else if(txtMarks.text == "")
{
Util.invokeAlertMethod("", strBody: "Please enter friend marks.", delegate: nil)
}
else
{
if(isEdit)
{
let groupData: Group = Group()
//groupData.RollNo = groupData.RollNo
groupData.GROUP_NM = txtName.text!
//groupData.GROUP_VALUE = txtMarks.text!
let isUpdated = ModelManager.getInstance().updateGroupData(groupData)
if isUpdated {
Util.invokeAlertMethod("", strBody: "Record updated successfully.", delegate: nil)
} else {
Util.invokeAlertMethod("", strBody: "Error in updating record.", delegate: nil)
}
}
else
{
let groupData: Group = Group()
groupData.GROUP_NM = txtName.text!
groupData.GROUP_ICON_FILE_NM = txtMarks.text!
let isInserted = ModelManager.getInstance().addGroupData(groupData)
if isInserted {
Util.invokeAlertMethod("", strBody: "Record Inserted successfully.", delegate: nil)
} else {
Util.invokeAlertMethod("", strBody: "Error in inserting record.", delegate: nil)
}
}
self.navigationController?.popViewControllerAnimated(true)
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | b30ebf12ece53f9dd0b7d3c6a4974c22 | 31.319149 | 107 | 0.569783 | 5.004942 | false | false | false | false |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/XCTEurofurenceModel/FakeKnowledgeService.swift | 1 | 1806 | import EurofurenceModel
import Foundation
public class FakeKnowledgeService: KnowledgeService {
public init() {
}
public func add(_ observer: KnowledgeServiceObserver) {
}
private var stubbedKnowledgeEntries = [KnowledgeEntryIdentifier: FakeKnowledgeEntry]()
public func fetchKnowledgeEntry(
for identifier: KnowledgeEntryIdentifier,
completionHandler: @escaping (KnowledgeEntry) -> Void
) {
completionHandler(stubbedKnowledgeEntry(for: identifier))
}
public func fetchImagesForKnowledgeEntry(
identifier: KnowledgeEntryIdentifier,
completionHandler: @escaping ([Data]) -> Void
) {
completionHandler(stubbedKnowledgeEntryImages(for: identifier))
}
private var stubbedGroups = [KnowledgeGroup]()
public func fetchKnowledgeGroup(
identifier: KnowledgeGroupIdentifier,
completionHandler: @escaping (KnowledgeGroup) -> Void
) {
stubbedGroups.first(where: { $0.identifier == identifier }).map(completionHandler)
}
}
extension FakeKnowledgeService {
public func stubbedKnowledgeEntry(for identifier: KnowledgeEntryIdentifier) -> FakeKnowledgeEntry {
if let entry = stubbedKnowledgeEntries[identifier] {
return entry
}
let randomEntry = FakeKnowledgeEntry.random
stub(randomEntry)
return randomEntry
}
public func stub(_ entry: FakeKnowledgeEntry) {
stubbedKnowledgeEntries[entry.identifier] = entry
}
public func stub(_ group: KnowledgeGroup) {
stubbedGroups.append(group)
}
public func stubbedKnowledgeEntryImages(for identifier: KnowledgeEntryIdentifier) -> [Data] {
return [identifier.rawValue.data(using: .utf8).unsafelyUnwrapped]
}
}
| mit | 7c498c5e169120dd017788e64c496479 | 27.21875 | 103 | 0.693245 | 5.522936 | false | false | false | false |
alsfox/ZYJModel | ZYJModel/TestModel.swift | 1 | 673 | //
// TestModel.swift
// ZYJModel
//
// Created by 张亚举 on 16/6/15.
// Copyright © 2016年 张亚举. All rights reserved.
//
import UIKit
class TestModel: ZYJModel {
var name = "张亚举"
var arr = NSArray()
var twoModel : TwoModel?
var thereModel : TwoModel?
var fourModel : TwoModel = TwoModel()
var modelArr : NSArray?
override func propertyForArray () -> NSDictionary?{
return ["arr" : "NSString",
"modelArr" : TwoModel.self
]
}
}
class TwoModel: ZYJModel {
var name = "张亚举磊"
var tesmo = "需要晨露"
}
| mit | 1394a210a7b75c4f325d8547ccac64a9 | 14.512195 | 55 | 0.531447 | 3.533333 | false | false | false | false |
stefanomondino/Raccoon | Example/Raccoon/ListViewModel.swift | 1 | 2228 | //
// ListViewModel.swift
// Raccoon
//
// Created by Stefano Mondino on 31/03/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Raccoon
import ReactiveCocoa
import Result
class ListViewModel: ViewModel {
var scheduler:Disposable?
var nextAction:Action<AnyObject, SegueParameters!, NoError>!
let searchString:MutableProperty<String?> = MutableProperty(nil)
override init () {
super.init()
self.reloadAction = Action({[unowned self] (string) -> SignalProducer<[[AnyObject]?], NSError> in
return RESTManager.sharedInstance
.searchWithString(string as? String)
.map({return [$0]})
})
self.searchString.value = "Raccoon"
var lastDisposable:Disposable?
self.searchString.producer.throttle(0.5, onScheduler:QueueScheduler.mainQueueScheduler).startWithNext {[unowned self] (string) in
print(string)
if (lastDisposable != nil) {lastDisposable!.dispose();}
lastDisposable = self.reloadAction?.apply(string).start()
}
self.nextAction = Action ({ [unowned self] (value:AnyObject) in
if value is NSIndexPath{
let indexPath = value as! NSIndexPath
let item = self.modelAtIndexPath(indexPath) as? Track
// print(item)
//let segueParameters = SegueParameters(segueIdentifier:"detailSegue",viewModel:DetailViewModel(trackDetail:item!))
let segueParameters = SegueParameters(segueIdentifier:"stackDetail",viewModel:DetailModel(trackDetail:item!))
return SignalProducer.init(value:segueParameters)
}
return SignalProducer.init(value:nil)
})
}
override func listIdentifiers() -> [String]! {
return ["ListCollectionViewCell"]
}
override func listIdentifierAtIndexPath(indexPath: NSIndexPath) -> String! {
return self.viewModelAtIndexPath(indexPath).listIdentifier()
}
override func listViewModelFromModel(model: AnyObject!) -> ViewModel! {
return ListCellViewModel(model: model as! Track)
}
}
| mit | bbba5fc1b506d5f5b6931e8ef3c351b0 | 35.508197 | 137 | 0.631792 | 4.970982 | false | false | false | false |
brentdax/swift | stdlib/public/core/Builtin.swift | 1 | 34377 | //===----------------------------------------------------------------------===//
//
// 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 SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@inlinable
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_sanityCheck(alignment > 0)
_sanityCheck(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@inlinable
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@inlinable
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_sanityCheck(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Use this function only to convert the instance passed as `x` to a
/// layout-compatible type when conversion through other means is not
/// possible. Common conversions supported by the Swift standard library
/// include the following:
///
/// - Value conversion from one integer type to another. Use the destination
/// type's initializer or the `numericCast(_:)` function.
/// - Bitwise conversion from one integer type to another. Use the destination
/// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer.
/// - Conversion from a pointer to an integer value with the bit pattern of the
/// pointer's address in memory, or vice versa. Use the `init(bitPattern:)`
/// initializer for the destination type.
/// - Casting an instance of a reference type. Use the casting operators (`as`,
/// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@inlinable // unsafe-performance
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"Can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// Returns `x` as its concrete type `U`.
///
/// This cast can be useful for dispatching to specializations of generic
/// functions.
///
/// - Requires: `x` has type `U`.
@_transparent
public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U {
_precondition(T.self == expectedType, "_identityCast to wrong type")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@usableFromInline @_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return !(lhs == rhs)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.RawPointer, rhs: Builtin.RawPointer
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether two types are identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the
/// same type; otherwise, `false`.
@inlinable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
switch (t0, t1) {
case (.none, .none): return true
case let (.some(ty0), .some(ty1)):
return Bool(Builtin.is_same_metatype(ty0, ty1))
default: return false
}
}
/// Returns a Boolean value indicating whether two types are not identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if
/// they represent different types; otherwise, `false`.
@inlinable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@usableFromInline @_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@usableFromInline @_transparent
internal func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@usableFromInline
@_silgen_name("_swift_isClassOrObjCExistentialType")
internal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@inlinable
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// Returns the given instance cast unconditionally to the specified type.
///
/// The instance passed as `x` must be an instance of type `T`.
///
/// Use this function instead of `unsafeBitcast(_:to:)` because this function
/// is more restrictive and still performs a check in debug builds. In -O
/// builds, no test is performed to ensure that `x` actually has the dynamic
/// type `T`.
///
/// - Warning: This function trades safety for performance. Use
/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always
/// evaluates to `true`, and only after `x as! T` has proven to be a
/// performance problem.
///
/// - Parameters:
/// - x: An instance to cast to type `T`.
/// - type: The type `T` to which `x` is cast.
/// - Returns: The instance `x`, cast to type `T`.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@_transparent
public func _unsafeUncheckedDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_sanityCheck(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
import SwiftShims
@inlinable
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<SwiftShims.HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@usableFromInline @_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
// Optimizer hint that the condition is true. The condition is unchecked.
// The builtin acts as an opaque instruction with side-effects.
@usableFromInline @_transparent
func _uncheckedUnsafeAssume(_ condition: Bool) {
_ = Builtin.assume_Int1(condition._value)
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@usableFromInline
@_silgen_name("_swift_objcClassUsesNativeSwiftReferenceCounting")
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@inlinable
@inline(__always)
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@usableFromInline
@_silgen_name("_swift_getSwiftClassInstanceExtents")
internal func getSwiftClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@usableFromInline
@_silgen_name("_swift_getObjCClassInstanceExtents")
internal func getObjCClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@inlinable
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(getObjCClassInstanceExtents(theClass).positive)
#else
return Int(getSwiftClassInstanceExtents(theClass).positive)
#endif
}
@inlinable
internal func _isValidAddress(_ address: UInt) -> Bool {
// TODO: define (and use) ABI max valid pointer value
return address >= _swift_abi_LeastValidPointerValue
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
// TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor
// calls
@inlinable
internal var _bridgeObjectTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) }
}
@inlinable
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_abi_ObjCReservedBitsMask) }
}
@inlinable
internal var _objectPointerSpareBits: UInt {
@inline(__always) get {
return UInt(_swift_abi_SwiftSpareBitsMask) & ~_bridgeObjectTaggedPointerBits
}
}
@inlinable
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get {
_sanityCheck(_swift_abi_ObjCReservedLowBits < 2,
"num bits now differs from num-shift-amount, new platform?")
return UInt(_swift_abi_ObjCReservedLowBits)
}
}
#if arch(i386) || arch(arm) || arch(powerpc64) || arch(powerpc64le) || arch(
s390x)
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
#else
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
#endif
/// Extract the raw bits of `x`.
@inlinable
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@inlinable
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: UInt) -> Bool {
return (x & _objCTaggedPointerBits) != 0
}
/// TODO: describe extras
@inlinable @inline(__always) public // FIXME
func _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool {
return _bitPattern(x) & _bridgeObjectTaggedPointerBits != 0
}
@inlinable @inline(__always) public // FIXME
func _isNativePointer(_ x: Builtin.BridgeObject) -> Bool {
return (
_bitPattern(x) & (_bridgeObjectTaggedPointerBits | _objectPointerIsObjCBit)
) == 0
}
@inlinable @inline(__always) public // FIXME
func _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool {
return !_isTaggedObject(x) && !_isNativePointer(x)
}
@inlinable
@inline(__always)
func _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt {
// Zero out the tag bits, and leave them all at the top.
_sanityCheck(_isTaggedObject(x), "not tagged!")
return (_bitPattern(x) & ~_bridgeObjectTaggedPointerBits)
>> _objectPointerLowSpareBitShift
}
// Values -> BridgeObject
@inline(__always)
@inlinable
public func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let object = Builtin.castToBridgeObject(x, 0._builtinWordValue)
_sanityCheck(_isNativePointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNonTaggedObjC x: AnyObject
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let object = _makeObjCBridgeObject(x)
_sanityCheck(_isNonTaggedObjCPointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject {
_sanityCheck(x & _bridgeObjectTaggedPointerBits != 0)
let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x)
_sanityCheck(_isTaggedObject(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject {
let shifted = x &<< _objectPointerLowSpareBitShift
_sanityCheck(x == (shifted &>> _objectPointerLowSpareBitShift),
"out-of-range: limited bit range requires some zero top bits")
_sanityCheck(shifted & _bridgeObjectTaggedPointerBits == 0,
"out-of-range: post-shift use of tag bits")
return _bridgeObject(fromTagged: shifted | _bridgeObjectTaggedPointerBits)
}
// BridgeObject -> Values
@inline(__always)
@inlinable
public func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject {
_sanityCheck(_isNativePointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
toNonTaggedObjC x: Builtin.BridgeObject
) -> AnyObject {
_sanityCheck(_isNonTaggedObjCPointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt {
_sanityCheck(_isTaggedObject(x))
let bits = _bitPattern(x)
_sanityCheck(bits & _bridgeObjectTaggedPointerBits != 0)
return bits
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt {
return _getNonTagBits(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNativeObject x: Builtin.NativeObject
) -> Builtin.BridgeObject {
return _bridgeObject(fromNative: _nativeObject(toNative: x))
}
//
// NativeObject
//
@inlinable
@inline(__always)
public func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject {
_sanityCheck(!_isObjCTaggedPointer(x))
let native = Builtin.unsafeCastToNativeObject(x)
// _sanityCheck(native == Builtin.castToNativeObject(x))
return native
}
@inlinable
@inline(__always)
public func _nativeObject(
fromBridge x: Builtin.BridgeObject
) -> Builtin.NativeObject {
return _nativeObject(fromNative: _bridgeObject(toNative: x))
}
@inlinable
@inline(__always)
public func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject {
return Builtin.castFromNativeObject(x)
}
// FIXME
extension ManagedBufferPointer {
// FIXME: String Guts
@inline(__always)
@inlinable
public init(_nativeObject buffer: Builtin.NativeObject) {
self._nativeBuffer = buffer
}
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@inlinable
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inlinable
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@inlinable
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_sanityCheck(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_sanityCheck(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_sanityCheck(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
public func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inlinable
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@usableFromInline @_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_sanityCheck(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is a bitwise takable. A bitwise takable type can
/// just be moved to a different address in memory.
@_transparent
public // @testable
func _isBitwiseTakable<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isbitwisetakable(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
/// Extract an object reference from an Any known to contain an object.
@inlinable
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_sanityCheck(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// Ideally we would do something like this:
//
// func open<T>(object: T) -> AnyObject {
// return unsafeBitCast(object, to: AnyObject.self)
// }
// return _openExistential(any, do: open)
//
// Unfortunately, class constrained protocol existentials conform to AnyObject
// but are not word-sized. As a result, we cannot currently perform the
// `unsafeBitCast` on them just yet. When they are word-sized, it would be
// possible to efficiently grab the object reference out of the inline
// storage.
return any as AnyObject
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inlinable
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// can be nested inside its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any` (the type
/// declared for the parameter) and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley : Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Finding the Dynamic Type in a Generic Context
/// =============================================
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function. As a result, `type(of:)` can only
/// produce the concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of `String.self` (the dynamic type inside the parameter).
///
/// func printGenericInfo<T>(_ value: T) {
/// let type = type(of: value)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let type = type(of: value as Any)
/// print("'\(value)' of type '\(type)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value for which to find the dynamic type.
/// - Returns: The dynamic type, which is a metatype instance.
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function;
/// nevertheless, it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve these errors, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed to `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameters:
/// - closure: A nonescaping closure value that is made escapable for the
/// duration of the execution of the `body` closure. If `body` has a
/// return value, that value is also used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - body: A closure that is executed immediately with an escapable copy of
/// `closure` as its argument.
/// - Returns: The return value, if any, of the `body` closure.
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
| apache-2.0 | fc8118157dbd8416b05e5925c221b030 | 34.877871 | 95 | 0.690146 | 4.06613 | false | false | false | false |
mansoor92/MaksabComponents | MaksabComponents/Classes/Localization/Localization.swift | 1 | 471 | //
// Localization.swift
// Pods
//
// Created by Incubasys on 04/08/2017.
//
//
import Foundation
class Localization {
static let budgetRide = "budgetRide"
static let howMuchYouAreWillingToPay = "howMuchYouAreWillingToPay"
static let priceUnit = "priceUnit"
static let mehramRide = "Mehram Ride"
static let noSmoking = "No Smoking"
static let creditCard = "Credit Card"
static let fourOrLessPassengers = "Four or less Passengers"
}
| mit | 9667f4632309872ed3fa3fcb3ba55140 | 22.55 | 70 | 0.70276 | 3.541353 | false | false | false | false |
felipecarreramo/BSImagePicker | Pod/Classes/Controller/BSImagePickerViewController.swift | 1 | 11141 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
import Photos
/**
BSImagePickerViewController.
Use settings or buttons to customize it to your needs.
*/
public final class BSImagePickerViewController : UINavigationController, BSImagePickerSettings {
fileprivate let settings = Settings()
fileprivate var doneBarButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
fileprivate var cancelBarButton: UIBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
fileprivate let albumTitleView: AlbumTitleView = bundle.loadNibNamed("AlbumTitleView", owner: nil, options: nil)!.first as! AlbumTitleView
fileprivate var dataSource: SelectableDataSource?
fileprivate let selections: [PHAsset]
static let bundle: Bundle = Bundle(path: Bundle(for: PhotosViewController.self).path(forResource: "BSImagePicker", ofType: "bundle")!)!
lazy var photosViewController: PhotosViewController = {
let dataSource: SelectableDataSource
if self.dataSource != nil {
dataSource = self.dataSource!
} else {
dataSource = BSImagePickerViewController.defaultDataSource()
}
let vc = PhotosViewController(dataSource: dataSource, settings: self.settings, selections: self.selections)
vc.doneBarButton = self.doneBarButton
vc.cancelBarButton = self.cancelBarButton
vc.albumTitleView = self.albumTitleView
return vc
}()
class func authorize(_ status: PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus(), fromViewController: UIViewController, completion: @escaping () -> Void) {
switch status {
case .authorized:
// We are authorized. Run block
completion()
case .notDetermined:
// Ask user for permission
PHPhotoLibrary.requestAuthorization({ (status) -> Void in
DispatchQueue.main.async(execute: { () -> Void in
self.authorize(status, fromViewController: fromViewController, completion: completion)
})
})
default: ()
DispatchQueue.main.async(execute: { () -> Void in
// Set up alert controller with some default strings. These should probably be overriden in application localizeable strings.
// If you don't enjoy my Swenglish that is ^^
let alertController = UIAlertController(title: NSLocalizedString("imagePickerNoCameraAccessTitle", value: "Can't access Photos", comment: "Alert view title"),
message: NSLocalizedString("imagePickerNoCameraAccessMessage", value: "You need to enable Photos access in application settings.", comment: "Alert view message"),
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: NSLocalizedString("imagePickerNoCameraAccessCancelButton", value: "Cancel", comment: "Cancel button title"), style: .cancel, handler:nil)
let settingsAction = UIAlertAction(title: NSLocalizedString("imagePickerNoCameraAccessSettingsButton", value: "Settings", comment: "Settings button title"), style: .default, handler: { (action) -> Void in
let url = URL(string: UIApplicationOpenSettingsURLString)
if let url = url , UIApplication.shared.canOpenURL(url) {
UIApplication.shared.openURL(url)
}
})
alertController.addAction(cancelAction)
alertController.addAction(settingsAction)
fromViewController.present(alertController, animated: true, completion: nil)
})
}
}
/**
Want it to show your own custom fetch results? Make sure the fetch results are of PHAssetCollections
:param: fetchResults PHFetchResult of PHAssetCollections
*/
public convenience init(fetchResults: [PHFetchResult<AnyObject>]) {
self.init(dataSource: FetchResultsDataSource(fetchResults: fetchResults))
}
/**
Do you have an asset collection you want to select from? Use this initializer!
:param: assetCollection The PHAssetCollection you want to select from
:param: selections Selected assets
*/
public convenience init(assetCollection: PHAssetCollection, selections: [PHAsset] = []) {
self.init(dataSource: AssetCollectionDataSource(assetCollection: assetCollection), selections: selections)
}
/**
Sets up an classic image picker with results from camera roll and albums
*/
public convenience init() {
self.init(dataSource: nil)
}
/**
You should probably use one of the convenience inits
:param: dataSource The data source for the albums
:param: selections Any PHAsset you want to seed the picker with as selected
*/
public required init(dataSource: SelectableDataSource?, selections: [PHAsset] = []) {
if let dataSource = dataSource {
self.dataSource = dataSource
}
self.selections = selections
super.init(nibName: nil, bundle: nil)
}
/**
https://www.youtube.com/watch?v=dQw4w9WgXcQ
*/
required public init?(coder aDecoder: NSCoder) {
dataSource = BSImagePickerViewController.defaultDataSource()
selections = []
super.init(coder: aDecoder)
}
/**
Load view. See apple documentation
*/
public override func loadView() {
super.loadView()
// TODO: Settings
view.backgroundColor = UIColor.white
// Make sure we really are authorized
if PHPhotoLibrary.authorizationStatus() == .authorized {
setViewControllers([photosViewController], animated: false)
}
}
fileprivate static func defaultDataSource() -> SelectableDataSource {
let fetchOptions = PHFetchOptions()
// Camera roll fetch result
let cameraRollResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: fetchOptions)
// Albums fetch result
let albumResult = PHAssetCollection.fetchAssetCollections(with: .album, subtype: .any, options: fetchOptions)
return FetchResultsDataSource(fetchResults: [cameraRollResult as! PHFetchResult<AnyObject>, albumResult as! PHFetchResult<AnyObject>])
}
// MARK: ImagePickerSettings proxy
/**
See BSImagePicketSettings for documentation
*/
public var maxNumberOfSelections: Int {
get {
return settings.maxNumberOfSelections
}
set {
settings.maxNumberOfSelections = newValue
}
}
/**
See BSImagePicketSettings for documentation
*/
public var selectionCharacter: Character? {
get {
return settings.selectionCharacter
}
set {
settings.selectionCharacter = newValue
}
}
/**
See BSImagePicketSettings for documentation
*/
public var selectionFillColor: UIColor {
get {
return settings.selectionFillColor
}
set {
settings.selectionFillColor = newValue
}
}
/**
See BSImagePicketSettings for documentation
*/
public var selectionStrokeColor: UIColor {
get {
return settings.selectionStrokeColor
}
set {
settings.selectionStrokeColor = newValue
}
}
/**
See BSImagePicketSettings for documentation
*/
public var selectionShadowColor: UIColor {
get {
return settings.selectionShadowColor
}
set {
settings.selectionShadowColor = newValue
}
}
/**
See BSImagePicketSettings for documentation
*/
public var selectionTextAttributes: [AnyHashable: Any] {
get {
return settings.selectionTextAttributes
}
set {
settings.selectionTextAttributes = newValue as [NSObject : AnyObject]
}
}
/**
See BSImagePicketSettings for documentation
*/
public var cellsPerRow: (_ verticalSize: UIUserInterfaceSizeClass, _ horizontalSize: UIUserInterfaceSizeClass) -> Int {
get {
return settings.cellsPerRow
}
set {
settings.cellsPerRow = newValue
}
}
// MARK: Buttons
/**
Cancel button
*/
public var cancelButton: UIBarButtonItem {
get {
return self.cancelBarButton
}
}
/**
Done button
*/
public var doneButton: UIBarButtonItem {
get {
return self.doneBarButton
}
}
/**
Album button
*/
public var albumButton: UIButton {
get {
return self.albumTitleView.albumButton
}
}
// MARK: Closures
var selectionClosure: ((_ asset: PHAsset) -> Void)? {
get {
return photosViewController.selectionClosure
}
set {
photosViewController.selectionClosure = newValue
}
}
var deselectionClosure: ((_ asset: PHAsset) -> Void)? {
get {
return photosViewController.deselectionClosure
}
set {
photosViewController.deselectionClosure = newValue
}
}
var cancelClosure: ((_ assets: [PHAsset]) -> Void)? {
get {
return photosViewController.cancelClosure
}
set {
photosViewController.cancelClosure = newValue
}
}
var finishClosure: ((_ assets: [PHAsset]) -> Void)? {
get {
return photosViewController.finishClosure
}
set {
photosViewController.finishClosure = newValue
}
}
}
| mit | a34d785e334164adbb711b433aa964b5 | 34.253165 | 220 | 0.635996 | 5.550573 | false | false | false | false |
jeffreybergier/WaterMe2 | WaterMe/WaterMe/ReminderVesselMain/ReminderVesselEdit/ReminderTableViewCell.swift | 1 | 4792 | //
// ReminderTableViewCell.swift
// WaterMe
//
// Created by Jeffrey Bergier on 6/18/17.
// Copyright © 2017 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe 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.
//
// WaterMe 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 WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import UIKit
class ReminderTableViewCell: UITableViewCell {
class var nib: UINib { return UINib(nibName: self.reuseID, bundle: Bundle(for: self.self)) }
static let reuseID = "ReminderTableViewCell"
@IBOutlet private weak var topLabel: UILabel?
@IBOutlet private weak var middleLabel: UILabel?
@IBOutlet private weak var bottomLabel: UILabel?
@IBOutlet private weak var emojiImageView: EmojiImageView?
@IBOutlet private weak var leadingConstraint: NSLayoutConstraint?
@IBOutlet private weak var trailingConstraint: NSLayoutConstraint?
@IBOutlet private weak var topConstraint: NSLayoutConstraint?
@IBOutlet private weak var bottomConstraint: NSLayoutConstraint?
fileprivate let formatter = DateComponentsFormatter.newReminderIntervalFormatter
func configure(with reminder: Reminder?) {
guard let reminder = reminder else { self.reset(); return; }
// do stuff that is the same for all cases
self.topLabel?.attributedText = NSAttributedString(string: reminder.kind.localizedShortString, font: .selectableTableViewCell)
let interval = NSAttributedString(string: self.formatter.string(forDayInterval: reminder.interval), font: .selectableTableViewCell)
let helper = NSAttributedString(string: ReminderVesselEditViewController.LocalizedString.rowLabelInterval,
font: .selectableTableViewCellHelper)
self.middleLabel?.attributedText = helper + interval
self.emojiImageView?.setKind(reminder.kind)
// do stuff that is case specific
switch reminder.kind {
case .water, .fertilize, .trim, .mist:
self.bottomLabel?.isHidden = true
case .move(let location):
let style: Font = location != nil ? .selectableTableViewCell : .selectableTableViewCellDisabled
let helper = NSAttributedString(string: ReminderVesselEditViewController.LocalizedString.rowLabelLocation,
font: .selectableTableViewCellHelper)
let location = NSAttributedString(string: location ?? ReminderVesselEditViewController.LocalizedString.rowValueLabelLocationNoValue, font: style)
self.bottomLabel?.attributedText = helper + location
case .other(let description):
let style: Font = description != nil ? .selectableTableViewCell : .selectableTableViewCellDisabled
let helper = NSAttributedString(string: ReminderVesselEditViewController.LocalizedString.rowLabelDescription,
font: .selectableTableViewCellHelper)
let description = NSAttributedString(string: description ?? ReminderVesselEditViewController.LocalizedString.rowValueLabelDescriptionNoValue,
font: style)
self.bottomLabel?.attributedText = helper + description
}
}
override func awakeFromNib() {
super.awakeFromNib()
self.emojiImageView?.backgroundColor = .clear
self.emojiImageView?.size = .small
self.emojiImageView?.ring = false
self.leadingConstraint?.constant = UITableViewCell.style_labelCellLeadingPadding
self.trailingConstraint?.constant = UITableViewCell.style_labelCellTrailingPadding
self.topConstraint?.constant = UITableViewCell.style_labelCellTopPadding
self.bottomConstraint?.constant = UITableViewCell.style_labelCellBottomPadding
self.reset()
}
private func reset() {
self.topLabel?.text = nil
self.middleLabel?.text = nil
self.bottomLabel?.text = nil
self.topLabel?.isHidden = false
self.middleLabel?.isHidden = false
self.bottomLabel?.isHidden = false
self.emojiImageView?.setKind(nil)
}
override func prepareForReuse() {
self.reset()
}
}
| gpl-3.0 | 760d6747ac1e6e2942eee25cd72c0308 | 45.970588 | 157 | 0.697558 | 5.276432 | false | false | false | false |
AlexRamey/mbird-iOS | Pods/CVCalendar/CVCalendar/CVCalendarMenuView.swift | 1 | 4963 | //
// CVCalendarMenuView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
public typealias WeekdaySymbolType = CVWeekdaySymbolType
public final class CVCalendarMenuView: UIView {
public var symbols = [String]()
public var symbolViews: [UILabel]?
public var firstWeekday: Weekday? = .sunday
public var dayOfWeekTextColor: UIColor? = .darkGray
public var dayofWeekBackgroundColor: UIColor? = .clear
public var dayOfWeekTextUppercase: Bool? = true
public var dayOfWeekFont: UIFont? = UIFont(name: "Avenir", size: 10)
public var weekdaySymbolType: WeekdaySymbolType? = .short
public var calendar: Calendar? = Calendar.current
@IBOutlet public weak var menuViewDelegate: AnyObject? {
set {
if let delegate = newValue as? MenuViewDelegate {
self.delegate = delegate
}
}
get {
return delegate
}
}
public weak var delegate: MenuViewDelegate? {
didSet {
setupAppearance()
setupWeekdaySymbols()
createDaySymbols()
}
}
public init() {
super.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setupAppearance() {
if let delegate = delegate {
firstWeekday~>delegate.firstWeekday?()
dayOfWeekTextColor~>delegate.dayOfWeekTextColor?()
dayofWeekBackgroundColor~>delegate.dayOfWeekBackGroundColor?()
dayOfWeekTextUppercase~>delegate.dayOfWeekTextUppercase?()
dayOfWeekFont~>delegate.dayOfWeekFont?()
weekdaySymbolType~>delegate.weekdaySymbolType?()
}
}
public func setupWeekdaySymbols() {
if var calendar = self.calendar {
(calendar as NSCalendar).components([NSCalendar.Unit.month, NSCalendar.Unit.day], from: Foundation.Date())
calendar.firstWeekday = firstWeekday!.rawValue
symbols = calendar.weekdaySymbols
}
}
public func createDaySymbols() {
// Change symbols with their places if needed.
let dateFormatter = DateFormatter()
dateFormatter.locale = calendar?.locale ?? Locale.current
var weekdays: NSArray
switch weekdaySymbolType! {
case .normal:
weekdays = dateFormatter.weekdaySymbols as NSArray
case .short:
weekdays = dateFormatter.shortWeekdaySymbols as NSArray
case .veryShort:
weekdays = dateFormatter.veryShortWeekdaySymbols as NSArray
}
let firstWeekdayIndex = firstWeekday!.rawValue - 1
if firstWeekdayIndex > 0 {
let copy = weekdays
weekdays = weekdays.subarray(
with: NSRange(location: firstWeekdayIndex, length: 7 - firstWeekdayIndex)) as NSArray
weekdays = weekdays.addingObjects(
from: copy.subarray(with: NSRange(location: 0, length: firstWeekdayIndex))) as NSArray
}
self.symbols = weekdays as! [String]
// Add symbols.
self.symbolViews = [UILabel]()
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<7 {
x = CGFloat(i) * width + space
let symbol = UILabel(frame: CGRect(x: x, y: y, width: width, height: height))
symbol.textAlignment = .center
symbol.text = self.symbols[i]
if dayOfWeekTextUppercase! {
symbol.text = (self.symbols[i]).uppercased()
}
let weekDay = Weekday(rawValue: (firstWeekday!.rawValue + i) % 7) ?? .saturday
symbol.font = dayOfWeekFont
symbol.textColor = self.delegate?.dayOfWeekTextColor?(by: weekDay)
?? dayOfWeekTextColor
symbol.backgroundColor = self.delegate?.dayOfWeekBackGroundColor?(by: weekDay)
?? dayofWeekBackgroundColor
self.symbolViews?.append(symbol)
self.addSubview(symbol)
}
}
public func commitMenuViewUpdate() {
setNeedsLayout()
layoutIfNeeded()
if let _ = delegate {
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<self.symbolViews!.count {
x = CGFloat(i) * width + space
let frame = CGRect(x: x, y: y, width: width, height: height)
let symbol = self.symbolViews![i]
symbol.frame = frame
}
}
}
}
| mit | 8f916a41123aceec82d9a315fe0173ad | 31.437908 | 118 | 0.596212 | 4.889655 | false | false | false | false |
audrl1010/EasyMakePhotoPicker | Example/EasyMakePhotoPicker/FacebookCameraCell.swift | 1 | 1716 | //
// FacebookCameraCell.swift
// EasyMakePhotoPicker
//
// Created by myung gi son on 2017. 7. 6..
// Copyright © 2017년 CocoaPods. All rights reserved.
//
import RxSwift
import Photos
import PhotosUI
import EasyMakePhotoPicker
class FacebookCameraCell: BaseCollectionViewCell, CameraCellable {
var cameraIcon: UIImage {
return #imageLiteral(resourceName: "camera")
}
var bgColor: UIColor {
return .white
}
var imageView = UIImageView().then {
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
imageView.image = centerAtRect(
image: cameraIcon,
rect: frame,
bgColor: bgColor)
}
fileprivate func centerAtRect(
image: UIImage?,
rect: CGRect,
bgColor: UIColor) -> UIImage? {
guard let image = image else { return nil }
UIGraphicsBeginImageContextWithOptions(rect.size, false, image.scale)
bgColor.setFill()
UIRectFill( CGRect(x: 0, y: 0, width: rect.size.width, height: rect.size.height))
image.draw(in:
CGRect(
x:rect.size.width/2 - image.size.width/2,
y:rect.size.height/2 - image.size.height/2,
width: image.size.width,
height: image.size.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
override func addSubviews() {
addSubview(imageView)
}
override func setupConstraints() {
imageView
.fs_leftAnchor(equalTo: leftAnchor)
.fs_topAnchor(equalTo: topAnchor)
.fs_rightAnchor(equalTo: rightAnchor)
.fs_bottomAnchor(equalTo: bottomAnchor)
.fs_endSetup()
}
}
| mit | 575e738ab4384881084900d071c708cc | 22.465753 | 85 | 0.669002 | 4.22963 | false | false | false | false |
aiaio/DesignStudioExpress | DesignStudioExpress/Views/TimerViewController.swift | 1 | 7449 | //
// TimerViewController.swift
// DesignStudioExpress
//
// Created by Kristijan Perusko on 12/3/15.
// Copyright © 2015 Alexander Interactive. All rights reserved.
//
import UIKit
import FXLabel
import MZTimerLabel
import DKCamera
import AVFoundation
class TimerViewController: UIViewControllerBase, MZTimerLabelDelegate {
@IBOutlet weak var challengeTitle: FXLabel!
@IBOutlet weak var activityTitle: UILabel!
@IBOutlet weak var activityDescription: FXLabel!
@IBOutlet weak var activityNotes: UILabel!
@IBOutlet weak var toggleButton: UIButtonLightBlue!
@IBOutlet weak var skipToNextActivity: FXLabel!
@IBOutlet weak var timer: MZTimerLabel!
enum NotificationIdentifier: String {
case AddMoreTimeToCurrentActivityNotification = "AddMoreTimeToCurrentActivity"
}
enum ViewControllerIdentifier: String {
case TimerViewController = "TimerViewController"
}
let vm = TimerViewModel()
var showPresenterNotes = true
let showNotesButtonLabel = "PRESENTER NOTES"
let showDescriptionButtonLabel = "BACK TO DESCRIPTION"
let cameraAccessErrorTitle = "Camera needs your permission!"
let cameraAccessErrorMessage = "Open iPhone Settings and tap on Design Studio Express. Allow app to access your camera."
override func viewDidLoad() {
super.viewDidLoad()
self.removeLastViewFromNavigation()
self.setUpTimerLabel()
self.addObservers()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
AppDelegate.designStudio.timerWillAppear()
self.populateFields()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
self.timer.start()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
self.timer.pause()
}
@IBAction func switchDescription(sender: AnyObject) {
self.toggleDescription()
}
@IBAction func skipToNextActivity(sender: AnyObject) {
self.vm.skipToNextActivity()
}
@IBAction func takePicture(sender: AnyObject) {
let authorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch authorizationStatus {
case .Authorized:
self.showCamera()
case .NotDetermined:
self.requestAccess()
default:
self.showWarningAlert()
}
}
private func showCamera() {
let camera = DKCamera()
camera.didCancelled = { () in
self.dismissViewControllerAnimated(true, completion: nil)
}
camera.didFinishCapturingImage = {(image: UIImage) in
self.vm.saveImage(image)
self.dismissViewControllerAnimated(true, completion: nil)
}
self.presentViewController(camera, animated: true, completion: nil)
}
private func requestAccess() {
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo) { (granted: Bool) -> Void in
if granted {
self.showCamera()
} else {
self.showWarningAlert()
}
}
}
private func showWarningAlert() {
let title = self.cameraAccessErrorTitle
let message = self.cameraAccessErrorMessage
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
// MARK: StyledNavigationBar
override func customizeNavBarStyle() {
super.customizeNavBarStyle()
DesignStudioElementStyles.transparentNavigationBar(self.navigationController!.navigationBar)
}
// MARK - MZTimerLabelDelegate
func timerLabel(timerLabel: MZTimerLabel!, countingTo time: NSTimeInterval, timertype timerType: MZTimerLabelType) {
if time < 60 {
timerLabel.timeLabel.textColor = DesignStudioStyles.primaryOrange
} else {
timerLabel.timeLabel.textColor = DesignStudioStyles.white
}
}
// MARK: - Custom
private func addObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshData:",
name: NotificationIdentifier.AddMoreTimeToCurrentActivityNotification.rawValue, object: nil)
}
func refreshData(notification: NSNotification) {
self.populateFields()
self.timer.start()
}
// remove
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func setUpTimerLabel() {
self.timer.delegate = self
self.timer.timerType = MZTimerLabelTypeTimer
self.timer.timeFormat = "mm:ss"
self.timer.timeLabel.textColor = DesignStudioStyles.white
}
private func populateFields () {
self.navigationItem.title = vm.designStudioTitle
self.challengeTitle.text = vm.challengeTitle
self.activityTitle.text = vm.activityTitle
self.activityDescription.text = vm.activityDescription
self.activityNotes.text = vm.activityNotes
self.timer.setCountDownTime(Double(vm.currentActivityRemainingDuration))
self.timer.reset()
self.skipToNextActivity.text = vm.nextButtonText
// hide/show toggle button for switching between description and presenter notes
self.toggleButton.hidden = !vm.activityNotesEnabled
}
// toggles between showing notes and description labels
private func toggleDescription() {
if showPresenterNotes {
// show activity notes
self.toggleButton.setTitle(self.showDescriptionButtonLabel, forState: .Normal)
self.activityNotes.hidden = false
self.activityDescription.hidden = true
self.showPresenterNotes = false
} else {
// show activity description
self.toggleButton.setTitle(self.showNotesButtonLabel, forState: .Normal)
self.activityNotes.hidden = true
self.activityDescription.hidden = false
self.showPresenterNotes = true
}
}
// to make back button always lead to the challenges screen
// remove all Timers and Upcoming challenge screens from the nav stack
private func removeLastViewFromNavigation() {
let endIndex = (self.navigationController?.viewControllers.endIndex ?? 0) - 1
if endIndex > 0 {
let previousVC = self.navigationController?.viewControllers[endIndex-1]
if previousVC is TimerViewController || previousVC is UpcomingChallengeViewController {
self.navigationController?.viewControllers.removeAtIndex(endIndex-1)
}
}
}
private func showNextTimerScreen() {
// segue to self
if let vc = self.storyboard?.instantiateViewControllerWithIdentifier(ViewControllerIdentifier.TimerViewController.rawValue) as? TimerViewController {
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
| mit | 64fed68cc403189a21e91f4a8b714b8b | 32.701357 | 157 | 0.660177 | 5.397101 | false | false | false | false |
makezwl/zhao | Nimble/Matchers/Equal.swift | 80 | 3211 | import Foundation
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable>(expectedValue: T?) -> NonNilMatcherFunc<T> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
let matches = actualExpression.evaluate() == expectedValue && expectedValue != nil
if expectedValue == nil || actualExpression.evaluate() == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return matches
}
}
/// A Nimble matcher that succeeds when the actual value is equal to the expected value.
/// Values can support equal by supporting the Equatable protocol.
///
/// @see beCloseTo if you want to match imprecise types (eg - floats, doubles).
public func equal<T: Equatable, C: Equatable>(expectedValue: [T: C]?) -> NonNilMatcherFunc<[T: C]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if expectedValue == nil || actualExpression.evaluate() == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualExpression.evaluate()!
}
}
/// A Nimble matcher that succeeds when the actual collection is equal to the expected collection.
/// Items must implement the Equatable protocol.
public func equal<T: Equatable>(expectedValue: [T]?) -> NonNilMatcherFunc<[T]> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "equal <\(stringify(expectedValue))>"
if expectedValue == nil || actualExpression.evaluate() == nil {
if expectedValue == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
}
return false
}
return expectedValue! == actualExpression.evaluate()!
}
}
public func ==<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<T>, rhs: T?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable>(lhs: Expectation<[T]>, rhs: [T]?) {
lhs.toNot(equal(rhs))
}
public func ==<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.to(equal(rhs))
}
public func !=<T: Equatable, C: Equatable>(lhs: Expectation<[T: C]>, rhs: [T: C]?) {
lhs.toNot(equal(rhs))
}
extension NMBObjCMatcher {
public class func equalMatcher(expected: NSObject) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage, location in
return equal(expected).matches(actualExpression, failureMessage: failureMessage)
}
}
}
| apache-2.0 | 87b86b274b9dc968dd5aabecf49d1c13 | 37.686747 | 100 | 0.651822 | 4.633478 | false | false | false | false |
jbourjeli/SwiftLabelPhoto | Photos++/PhotoDetailViewController.swift | 1 | 12428 | //
// PhotoDetailViewController.swift
// Photos++
//
// Created by Joseph Bourjeli on 9/9/16.
// Copyright © 2016 WorkSmarterComputing. All rights reserved.
//
import UIKit
import SwiftOverlays
class PhotoDetailViewController: UIViewController {
var photo: Photo!
var photoModelService: PhotoModelService!
@IBOutlet fileprivate weak var originalPhotoImageView: UIImageView!
@IBOutlet fileprivate weak var labelCollectionView: UICollectionView!
@IBOutlet fileprivate weak var addLabelButton: FAButton!
@IBOutlet fileprivate weak var commentButton: FAButton!
@IBOutlet fileprivate weak var deleteButton: FAButton!
@IBOutlet fileprivate weak var exportButton: FAButton!
@IBOutlet fileprivate weak var scrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
self.labelCollectionView.dataSource = self
self.labelCollectionView.delegate = self
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 5
layout.minimumLineSpacing = 5
self.labelCollectionView.collectionViewLayout = layout
self.originalPhotoImageView.contentMode = .scaleAspectFit
self.scrollView.minimumZoomScale=1.0;
self.scrollView.maximumZoomScale=3.0;
self.scrollView.contentSize=self.originalPhotoImageView.frame.size
self.scrollView.delegate = self
self.updateActionBar()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if self.originalPhotoImageView.image == nil {
//let _ = EZLoadingActivity.show("Loading ...", disableUI: true)
self.showWaitOverlayWithText("Fetching Image ...")
}
self.labelCollectionView.reloadData()
self.updateActionBar()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if self.originalPhotoImageView.image == nil {
photo.fetchOriginalImage { [unowned self] (image, error) in
if let error = error {
self.present(UIAlertController.alert(title: "Error fetching image",
message: "There was an error fetching the original image. Will display a lower resolution version \n [Error: \(error)]"),
animated: true, completion: nil)
}
//let _ = EZLoadingActivity.hide()
self.removeAllOverlays()
self.originalPhotoImageView.image = image
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - IBActions
@IBAction fileprivate func dismissAction(_ sender: AnyObject) {
if let photosViewController = self.storyboard?.instantiateViewController(withIdentifier: "PhotosViewController") as? PhotosViewController {
photosViewController.photosModelService = self.photoModelService
self.dismiss(animated: true, completion: nil)
/*UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveLinear, animations: {
self.view.alpha = 0
//self.view.frame = CGRectZero
photosViewController.view.alpha = 1
}, completion: { completed in
self.presentViewController(photosViewController, animated: false, completion: nil)
})*/
}
}
@IBAction func showLabelsAction(_ sender: AnyObject) {
if let navigationVC = self.storyboard?.instantiateViewController(withIdentifier: "ChooseLabelViewController") as? UINavigationController {
if let chooseLabelVC = navigationVC.viewControllers[0] as? ChooseLabelTableViewController {
chooseLabelVC.labelModelService = Service.labelModelService()
chooseLabelVC.delegate = self
navigationVC.modalPresentationStyle = .custom
navigationVC.transitioningDelegate = self
self.present(navigationVC, animated: true, completion: nil)
}
}
}
@IBAction func showCommentAction(_ sender: AnyObject) {
/*let alertController = UIAlertController(title: "Comments", message: "Have something to say about this photo?", preferredStyle: .alert)
alertController.addTextField(configurationHandler: { textField in
textField.clearButtonMode = .whileEditing
textField.placeholder = "Enter it here"
})
alertController.addAction(UIAlertAction(title: "Save", style: .default, handler: { [unowned alertController, unowned self] alertAction in
if let textField = alertController.textFields?.first {
if let text = textField.text {
self.photoModelService.photo(self.photo, addCommentWithText: text)
self.updateActionBar()
}
}
}))
//alertController.addAction(UIAlertAction(title: "Show Comments", style: .default, handler: {alertAction in }))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: {_ in }))
self.present(alertController, animated: true, completion: nil)*/
if let commentsViewControllerNav = self.storyboard?.instantiateViewController(withIdentifier: "CommentsViewControllerNav") as? UINavigationController {
if let commentsViewController = commentsViewControllerNav.viewControllers.first as? CommentsTableViewController {
commentsViewController.photo = self.photo
commentsViewController.photoModelService = self.photoModelService
commentsViewControllerNav.modalPresentationStyle = .custom
commentsViewControllerNav.transitioningDelegate = self
self.present(commentsViewControllerNav, animated: true, completion: nil)
}
}
}
@IBAction func deletePhotoAction(_ sender: AnyObject) {
if self.photo.isLink() {
self.photoModelService.unlink(photo: photo)
} else {
do {
try self.photoModelService.deletePhoto(photo)
} catch let error {
print("ERROR: Unable to delete photo because \(error)")
}
}
if let presentingVC = self.presentingViewController {
presentingVC.viewWillAppear(true)
presentingVC.dismiss(animated: true)
} else {
self.dismiss(animated: true)
}
}
@IBAction func exportPhotoAction(_ sender: AnyObject) {
self.blockUI(withMessage: "Fetching image ...")
self.photo.fetchOriginalImage { [unowned self] (image, error) in
self.unblockUI()
self.presentExportOptionsFor(image: image)
}
// TODO: - This custom function to save allows the option to create a new
// album and assign the image to the album. More flexible!!
/*self.photo.exportToPHAsset { [weak self] error in
DispatchQueue.main.sync {
self?.unblockUI()
}
}*/
}
// MARK: - Privates
fileprivate func updateActionBar() {
self.addLabelButton.backgroundColor = UIColor.primary()
self.addLabelButton.setTitle(FontAwesomeIcon.faTag.rawValue, for: .normal)
let commentTitle: FontAwesomeIcon!
if self.photo.numberOfComments() > 0 {
commentTitle = FontAwesomeIcon.faCommentsO
} else {
commentTitle = FontAwesomeIcon.faCommentO
}
self.commentButton.setFATitle(commentTitle, for: .normal)
self.commentButton.backgroundColor = UIColor.secondary()
self.commentButton.titleLabel?.textColor = UIColor.darkText
self.deleteButton.setTitleColor(UIColor.danger(), for: .normal)
self.deleteButton.setTitleShadowColor(UIColor.clear, for: .normal)
self.deleteButton.backgroundColor = UIColor.secondary()
if self.photo.isLink() {
self.deleteButton.setFATitle(FontAwesomeIcon.faMinusCircle, for: .normal)
} else {
self.deleteButton.setFATitle(FontAwesomeIcon.faTrashO, for: .normal)
}
self.exportButton.setTitleColor(UIColor.primary(), for: .normal)
self.exportButton.backgroundColor = UIColor.secondary()
self.exportButton.setTitleShadowColor(UIColor.clear, for: .normal)
self.exportButton.setFATitle(.faShare, for: .normal)
}
fileprivate func presentExportOptionsFor(image: UIImage) {
let activityViewController = UIActivityViewController(activityItems: [image], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
extension PhotoDetailViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photo.numberOfLabels()
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LabelCell", for: indexPath) as! LabelCollectionViewCell
cell.label = self.photoLabelAtIndexPath(indexPath)
cell.delegate = self
cell.backgroundColor = UIColor.lemonChiffon()
cell.layer.borderColor = UIColor.lightGray.cgColor
cell.layer.borderWidth = 1
cell.layer.cornerRadius = 0
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let label = self.photoLabelAtIndexPath(indexPath)
let labelString = (label.longName ?? label.description) as NSString
let labelBounds = labelString.boundingRect(with: collectionView.bounds.size, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [:], context: nil)
let sizeForItem = CGSize(width: labelBounds.width+10, height: labelBounds.height+10)
return sizeForItem
}
func collectionView(_ collectionView: UICollectionView, shouldShowMenuForItemAt indexPath: IndexPath) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, canPerformAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return true
}
func collectionView(_ collectionView: UICollectionView, performAction action: Selector, forItemAt indexPath: IndexPath, withSender sender: Any?) {
print("Perform action in \(sender)")
}
fileprivate func photoLabelAtIndexPath(_ indexPath: IndexPath) -> Label {
return self.photo.labelAtIndex(index: (indexPath as NSIndexPath).row)
}
}
extension PhotoDetailViewController: ChooseLabelTableViewControllerDelegate {
func didSelectLabel(_ label: Label) {
self.photoModelService.photo(self.photo, addLabel: label)
self.labelCollectionView.reloadData()
}
}
extension PhotoDetailViewController: LabelCollectionViewCellDelegate {
func removeLabel(_ label: Label) {
self.photoModelService.photo(self.photo, removeLabel: label)
self.labelCollectionView.reloadData()
}
}
extension PhotoDetailViewController: UIViewControllerTransitioningDelegate {
func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? {
return TransparentPresentationController(presentedViewController: presented, presenting: source)
//HalfScreenPresentationController(presentedViewController: presented, presenting: source, anchor: .Top)
}
}
extension PhotoDetailViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return self.originalPhotoImageView
}
}
| mit | 1f0f312488de699def4342413570f171 | 42.149306 | 178 | 0.661785 | 5.552726 | false | false | false | false |
pselle/macvimspeak | MacVimSpeak/KeyStrokes.swift | 1 | 1446 | //
// Grammar.swift
// MacVimSpeak
//
// Created by Pam Selle on 3/2/15.
// Copyright (c) 2015 The Webivore. All rights reserved.
//
import Foundation
import Dollar
// I'm not 100% sure what this is, but gotta have it!
let src = CGEventSourceCreate(CGEventSourceStateID(kCGEventSourceStateHIDSystemState)).takeRetainedValue()
func executeKeyCommands(keys: [KeySet]) {
println("===============ExecuteKeyCommands called")
for keySet in keys {
println("key set is", keySet)
executeMultiKey(keySet)
}
}
func executeMultiKey(keys: [UInt16]) {
println("pressing keys")
pressKeys(keys)
liftKeys(keys)
}
func pressKeys(keys:[UInt16]) {
if(keys[0] == 56) {
println("Down with shift")
let keyDown = CGEventCreateKeyboardEvent(src, keys[1], true).takeRetainedValue()
CGEventSetFlags(keyDown, CGEventFlags(kCGEventFlagMaskShift))
CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyDown)
} else {
for key in keys {
println("Down", key)
let keyDown = CGEventCreateKeyboardEvent(src, key, true).takeRetainedValue()
CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyDown)
}
}
}
func liftKeys(keys:[UInt16]) {
for key in keys {
println("Up", key)
let keyUp = CGEventCreateKeyboardEvent(src, key, false).takeRetainedValue()
CGEventPost(CGEventTapLocation(kCGHIDEventTap), keyUp)
}
}
| mit | c006f7a5602551034415827edec9e497 | 26.807692 | 106 | 0.664592 | 3.856 | false | false | false | false |
kzaher/RxSwift | RxSwift/Traits/Infallible/Infallible+Operators.swift | 1 | 28852 | //
// Infallible+Operators.swift
// RxSwift
//
// Created by Shai Mishali on 27/08/2020.
// Copyright © 2020 Krunoslav Zaher. All rights reserved.
//
// MARK: - Static allocation
#warning("Infallible still needs a full test suite")
extension InfallibleType {
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element) -> Infallible<Element> {
Infallible(.just(element))
}
/**
Returns an infallible sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting infallible sequence.
- parameter scheduler: Scheduler to send the single element on.
- returns: An infallible sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> Infallible<Element> {
Infallible(.just(element, scheduler: scheduler))
}
/**
Returns a non-terminating infallible sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence whose observers will never get called.
*/
public static func never() -> Infallible<Element> {
Infallible(.never())
}
/**
Returns an empty infallible sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An infallible sequence with no elements.
*/
public static func empty() -> Infallible<Element> {
Infallible(.empty())
}
/**
Returns an infallible sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> Infallible<Element>)
-> Infallible<Element> {
Infallible(.deferred { try observableFactory().asObservable() })
}
}
// MARK: - Filter
extension InfallibleType {
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (Element) -> Bool)
-> Infallible<Element> {
Infallible(asObservable().filter(predicate))
}
}
// MARK: - Map
extension InfallibleType {
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<Result>(_ transform: @escaping (Element) -> Result)
-> Infallible<Result> {
Infallible(asObservable().map(transform))
}
/**
Projects each element of an observable sequence into an optional form and filters all optional results.
- parameter transform: A transform function to apply to each source element and which returns an element or nil.
- returns: An observable sequence whose elements are the result of filtering the transform function for each element of the source.
*/
public func compactMap<Result>(_ transform: @escaping (Element) -> Result?)
-> Infallible<Result> {
Infallible(asObservable().compactMap(transform))
}
}
// MARK: - Distinct
extension InfallibleType where Element: Comparable {
/**
Returns an observable sequence that contains only distinct contiguous elements according to equality operator.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator, from the source sequence.
*/
public func distinctUntilChanged()
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged())
}
}
extension InfallibleType {
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `keySelector`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
public func distinctUntilChanged<Key: Equatable>(_ keySelector: @escaping (Element) throws -> Key)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged(keySelector, comparer: { $0 == $1 }))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the `comparer`.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on `comparer`, from the source sequence.
*/
public func distinctUntilChanged(_ comparer: @escaping (Element, Element) throws -> Bool)
-> Infallible<Element> {
Infallible(self.asObservable().distinctUntilChanged({ $0 }, comparer: comparer))
}
/**
Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- parameter keySelector: A function to compute the comparison key for each element.
- parameter comparer: Equality comparer for computed key values.
- returns: An observable sequence only containing the distinct contiguous elements, based on a computed key value and the comparer, from the source sequence.
*/
public func distinctUntilChanged<K>(_ keySelector: @escaping (Element) throws -> K, comparer: @escaping (K, K) throws -> Bool)
-> Infallible<Element> {
Infallible(asObservable().distinctUntilChanged(keySelector, comparer: comparer))
}
/**
Returns an observable sequence that contains only contiguous elements with distinct values in the provided key path on each object.
- seealso: [distinct operator on reactivex.io](http://reactivex.io/documentation/operators/distinct.html)
- returns: An observable sequence only containing the distinct contiguous elements, based on equality operator on the provided key path
*/
public func distinctUntilChanged<Property: Equatable>(at keyPath: KeyPath<Element, Property>) ->
Infallible<Element> {
Infallible(asObservable().distinctUntilChanged { $0[keyPath: keyPath] == $1[keyPath: keyPath] })
}
}
// MARK: - Throttle
extension InfallibleType {
/**
Ignores elements from an observable sequence which are followed by another element within a specified relative time duration, using the specified scheduler to run throttling timers.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func debounce(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().debounce(dueTime, scheduler: scheduler))
}
/**
Returns an Observable that emits the first and the latest item emitted by the source Observable during sequential time windows of a specified duration.
This operator makes sure that no two elements are emitted in less then dueTime.
- seealso: [debounce operator on reactivex.io](http://reactivex.io/documentation/operators/debounce.html)
- parameter dueTime: Throttling duration for each element.
- parameter latest: Should latest element received in a dueTime wide time window since last element emission be emitted.
- parameter scheduler: Scheduler to run the throttle timers on.
- returns: The throttled sequence.
*/
public func throttle(_ dueTime: RxTimeInterval, latest: Bool = true, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().throttle(dueTime, latest: latest, scheduler: scheduler))
}
}
// MARK: - FlatMap
extension InfallibleType {
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMap(selector))
}
/**
Projects each element of an observable sequence into a new sequence of observable sequences and then
transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
It is a combination of `map` + `switchLatest` operator
- seealso: [flatMapLatest operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source producing an
Observable of Observable sequences and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
public func flatMapLatest<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapLatest(selector))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
If element is received while there is some projected observable sequence being merged it will simply be ignored.
- seealso: [flatMapFirst operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to element that was observed while no observable is executing in parallel.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence that was received while no other sequence was being calculated.
*/
public func flatMapFirst<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().flatMapFirst(selector))
}
}
// MARK: - Concat
extension InfallibleType {
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat<Source: ObservableConvertibleType>(_ second: Source) -> Infallible<Element> where Source.Element == Element {
Infallible(Observable.concat([self.asObservable(), second.asObservable()]))
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Sequence: Swift.Sequence>(_ sequence: Sequence) -> Infallible<Element>
where Sequence.Element == Infallible<Element> {
Infallible(Observable.concat(sequence.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<Collection: Swift.Collection>(_ collection: Collection) -> Infallible<Element>
where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(collection.map { $0.asObservable() }))
}
/**
Concatenates all observable sequences in the given collection, as long as the previous observable sequence terminated successfully.
This operator has tail recursive optimizations that will prevent stack overflow.
Optimizations will be performed in cases equivalent to following:
[1, [2, [3, .....].concat()].concat].concat()
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: Infallible<Element> ...) -> Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Projects each element of an observable sequence to an observable sequence and concatenates the resulting observable sequences into one observable sequence.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
public func concatMap<Source: ObservableConvertibleType>(_ selector: @escaping (Element) -> Source)
-> Infallible<Source.Element> {
Infallible(asObservable().concatMap(selector))
}
}
// MARK: - Merge
extension InfallibleType {
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<Collection: Swift.Collection>(_ sources: Collection) -> Infallible<Element> where Collection.Element == Infallible<Element> {
Infallible(Observable.concat(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences from array into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: [Infallible<Element>]) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
/**
Merges elements from all infallible sequences into a single infallible sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of infallible sequences to merge.
- returns: The infallible sequence that merges the elements of the infallible sequences.
*/
public static func merge(_ sources: Infallible<Element>...) -> Infallible<Element> {
Infallible(Observable.merge(sources.map { $0.asObservable() }))
}
}
// MARK: - Do
extension Infallible {
/**
Invokes an action for each event in the infallible sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter afterNext: Action to invoke for each element after the observable has passed an onNext event along to its downstream.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter afterCompleted: Action to invoke after graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((Element) throws -> Void)? = nil, afterNext: ((Element) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, afterCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> Void)? = nil, onSubscribed: (() -> Void)? = nil, onDispose: (() -> Void)? = nil) -> Infallible<Element> {
Infallible(asObservable().do(onNext: onNext, afterNext: afterNext, onCompleted: onCompleted, afterCompleted: afterCompleted, onSubscribe: onSubscribe, onSubscribed: onSubscribed, onDispose: onDispose))
}
}
// MARK: - Scan
extension InfallibleType {
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(into seed: Seed, accumulator: @escaping (inout Seed, Element) -> Void)
-> Infallible<Seed> {
Infallible(asObservable().scan(into: seed, accumulator: accumulator))
}
/**
Applies an accumulator function over an observable sequence and returns each intermediate result. The specified seed value is used as the initial accumulator value.
For aggregation behavior with no intermediate results, see `reduce`.
- seealso: [scan operator on reactivex.io](http://reactivex.io/documentation/operators/scan.html)
- parameter seed: The initial accumulator value.
- parameter accumulator: An accumulator function to be invoked on each element.
- returns: An observable sequence containing the accumulated values.
*/
public func scan<Seed>(_ seed: Seed, accumulator: @escaping (Seed, Element) -> Seed)
-> Infallible<Seed> {
Infallible(asObservable().scan(seed, accumulator: accumulator))
}
}
// MARK: - Start with
extension InfallibleType {
/**
Prepends a value to an observable sequence.
- seealso: [startWith operator on reactivex.io](http://reactivex.io/documentation/operators/startwith.html)
- parameter element: Element to prepend to the specified sequence.
- returns: The source sequence prepended with the specified values.
*/
public func startWith(_ element: Element) -> Infallible<Element> {
Infallible(asObservable().startWith(element))
}
}
// MARK: - Take and Skip {
extension InfallibleType {
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: InfallibleType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other.asObservable()))
}
/**
Returns the elements from the source observable sequence until the other observable sequence produces an element.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter other: Observable sequence that terminates propagation of elements of the source sequence.
- returns: An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
public func take<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().take(until: other))
}
/**
Returns elements from an observable sequence until the specified condition is true.
- seealso: [takeUntil operator on reactivex.io](http://reactivex.io/documentation/operators/takeuntil.html)
- parameter predicate: A function to test each element for a condition.
- parameter behavior: Whether or not to include the last element matching the predicate. Defaults to `exclusive`.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test passes.
*/
public func take(until predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(until: predicate, behavior: behavior))
}
/**
Returns elements from an observable sequence as long as a specified condition is true.
- seealso: [takeWhile operator on reactivex.io](http://reactivex.io/documentation/operators/takewhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
public func take(while predicate: @escaping (Element) throws -> Bool,
behavior: TakeBehavior = .exclusive)
-> Infallible<Element> {
Infallible(asObservable().take(while: predicate, behavior: behavior))
}
/**
Returns a specified number of contiguous elements from the start of an observable sequence.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter count: The number of elements to return.
- returns: An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
public func take(_ count: Int) -> Infallible<Element> {
Infallible(asObservable().take(count))
}
/**
Takes elements for the specified duration from the start of the infallible source sequence, using the specified scheduler to run timers.
- seealso: [take operator on reactivex.io](http://reactivex.io/documentation/operators/take.html)
- parameter duration: Duration for taking elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An infallible sequence with the elements taken during the specified duration from the start of the source sequence.
*/
public func take(for duration: RxTimeInterval, scheduler: SchedulerType)
-> Infallible<Element> {
Infallible(asObservable().take(for: duration, scheduler: scheduler))
}
/**
Bypasses elements in an infallible sequence as long as a specified condition is true and then returns the remaining elements.
- seealso: [skipWhile operator on reactivex.io](http://reactivex.io/documentation/operators/skipwhile.html)
- parameter predicate: A function to test each element for a condition.
- returns: An infallible sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
public func skip(while predicate: @escaping (Element) throws -> Bool) -> Infallible<Element> {
Infallible(asObservable().skip(while: predicate))
}
/**
Returns the elements from the source infallible sequence that are emitted after the other infallible sequence produces an element.
- seealso: [skipUntil operator on reactivex.io](http://reactivex.io/documentation/operators/skipuntil.html)
- parameter other: Infallible sequence that starts propagation of elements of the source sequence.
- returns: An infallible sequence containing the elements of the source sequence that are emitted after the other sequence emits an item.
*/
public func skip<Source: ObservableType>(until other: Source)
-> Infallible<Element> {
Infallible(asObservable().skip(until: other))
}
}
// MARK: - Share
extension InfallibleType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Infallible<Element> {
Infallible(asObservable().share(replay: replay, scope: scope))
}
}
| mit | 99a521cf19123ac0ff6df521a9ff0739 | 46.608911 | 320 | 0.7241 | 5.11724 | false | false | false | false |
mozilla-mobile/firefox-ios | Tests/SharedTests/NSURLExtensionsTests.swift | 2 | 19548 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import XCTest
@testable import Shared
class NSURLExtensionsTests: XCTestCase {
func testRemovesHTTPFromURL() {
let url = URL(string: "http://google.com")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "google.com")
} else {
XCTFail("Actual url is nil")
}
}
func testRemovesHTTPAndTrailingSlashFromURL() {
let url = URL(string: "http://google.com/")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "google.com")
} else {
XCTFail("Actual url is nil")
}
}
func testRemovesHTTPButNotTrailingSlashFromURL() {
let url = URL(string: "http://google.com/foo/")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "google.com/foo/")
} else {
XCTFail("Actual url is nil")
}
}
func testKeepsHTTPSInURL() {
let url = URL(string: "https://google.com")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "https://google.com")
} else {
XCTFail("Actual url is nil")
}
}
func testKeepsHTTPSAndRemovesTrailingSlashInURL() {
let url = URL(string: "https://google.com/")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "https://google.com")
} else {
XCTFail("Actual url is nil")
}
}
func testKeepsHTTPSAndTrailingSlashInURL() {
let url = URL(string: "https://google.com/foo/")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "https://google.com/foo/")
} else {
XCTFail("Actual url is nil")
}
}
func testKeepsAboutSchemeInURL() {
let url = URL(string: "about:home")
if let actual = url?.absoluteDisplayString {
XCTAssertEqual(actual, "about:home")
} else {
XCTFail("Actual url is nil")
}
}
// MARK: Public Suffix
func testNormalBaseDomainWithSingleSubdomain() {
// TLD Entry: co.uk
let url = "http://a.bbc.co.uk".asURL!
let expected = url.publicSuffix!
XCTAssertEqual("co.uk", expected)
}
func testCanadaComputers() {
let url = "http://m.canadacomputers.com".asURL!
let actual = url.baseDomain!
XCTAssertEqual("canadacomputers.com", actual)
}
func testMultipleSuffixesInsideURL() {
let url = "http://com:[email protected]".asURL!
let actual = url.baseDomain!
XCTAssertEqual("canadacomputers.co.uk", actual)
}
func testNormalBaseDomainWithManySubdomains() {
// TLD Entry: co.uk
let url = "http://a.b.c.d.bbc.co.uk".asURL!
let expected = url.publicSuffix!
XCTAssertEqual("co.uk", expected)
}
func testWildCardDomainWithSingleSubdomain() {
// TLD Entry: *.kawasaki.jp
let url = "http://a.kawasaki.jp".asURL!
let expected = url.publicSuffix!
XCTAssertEqual("a.kawasaki.jp", expected)
}
func testWildCardDomainWithManySubdomains() {
// TLD Entry: *.kawasaki.jp
let url = "http://a.b.c.d.kawasaki.jp".asURL!
let expected = url.publicSuffix!
XCTAssertEqual("d.kawasaki.jp", expected)
}
func testExceptionDomain() {
// TLD Entry: !city.kawasaki.jp
let url = "http://city.kawasaki.jp".asURL!
let expected = url.publicSuffix!
XCTAssertEqual("kawasaki.jp", expected)
}
// MARK: Base Domain
func testNormalBaseSubdomain() {
// TLD Entry: co.uk
let url = "http://bbc.co.uk".asURL!
let expected = url.baseDomain!
XCTAssertEqual("bbc.co.uk", expected)
}
func testNormalBaseSubdomainWithAdditionalSubdomain() {
// TLD Entry: co.uk
let url = "http://a.bbc.co.uk".asURL!
let expected = url.baseDomain!
XCTAssertEqual("bbc.co.uk", expected)
}
func testBaseDomainForWildcardDomain() {
// TLD Entry: *.kawasaki.jp
let url = "http://a.b.kawasaki.jp".asURL!
let expected = url.baseDomain!
XCTAssertEqual("a.b.kawasaki.jp", expected)
}
func testBaseDomainForWildcardDomainWithAdditionalSubdomain() {
// TLD Entry: *.kawasaki.jp
let url = "http://a.b.c.kawasaki.jp".asURL!
let expected = url.baseDomain!
XCTAssertEqual("b.c.kawasaki.jp", expected)
}
func testBaseDomainForExceptionDomain() {
// TLD Entry: !city.kawasaki.jp
let url = "http://city.kawasaki.jp".asURL!
let expected = url.baseDomain!
XCTAssertEqual("city.kawasaki.jp", expected)
}
func testBaseDomainForExceptionDomainWithAdditionalSubdomain() {
// TLD Entry: !city.kawasaki.jp
let url = "http://a.city.kawasaki.jp".asURL!
let expected = url.baseDomain!
XCTAssertEqual("city.kawasaki.jp", expected)
}
func testBugzillaURLDomain() {
let url = "https://bugzilla.mozilla.org/enter_bug.cgi?format=guided#h=dupes|Data%20%26%20BI%20Services%20Team|"
let nsURL = url.asURL
XCTAssertNotNil(nsURL, "URL parses.")
let host = nsURL!.normalizedHost
XCTAssertEqual(host!, "bugzilla.mozilla.org")
XCTAssertEqual(nsURL!.fragment!, "h=dupes%7CData%20%26%20BI%20Services%20Team%7C")
}
func testIPv6Domain() {
let url = "http://[::1]/foo/bar".asURL!
XCTAssertTrue(url.isIPv6)
XCTAssertNil(url.baseDomain)
XCTAssertEqual(url.normalizedHost!, "[::1]")
}
private func checkUrls(goodurls: [String], badurls: [String], checker: (InternalURL) -> Bool) {
goodurls.forEach {
var result = false
if let url = InternalURL(URL(string: $0)!) { result = checker(url) }
XCTAssertTrue(result)
}
badurls.forEach {
var result = false
if let url = InternalURL(URL(string: $0)!) { result = checker(url) }
XCTAssertFalse(result)
}
}
func testisAboutHomeURL() {
let goodurls = [
"\(InternalURL.baseUrl)/sessionrestore?url=\(InternalURL.baseUrl)/about/home%23panel%3D1",
"\(InternalURL.baseUrl)/about/home#panel=0"
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"http://localhost:\(AppInfo.webserverPort)/errors/error.html?url=http%3A//mozilla.com",
"http://localhost:\(AppInfo.webserverPort)/errors/error.html?url=http%3A//mozilla.com/about/home/%23panel%3D1",
]
checkUrls(goodurls: goodurls, badurls: badurls, checker: { url in
return url.isAboutHomeURL
})
}
func testisAboutURL() {
let goodurls = [
"\(InternalURL.baseUrl)/about/home#panel=0",
"\(InternalURL.baseUrl)/about/license"
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"http://localhost:\(AppInfo.webserverPort)/errors/error.html?url=http%3A//mozilla.com",
"http://localhost:\(AppInfo.webserverPort)/errors/error.html?url=http%3A//mozilla.com/about/home/%23panel%3D1",
]
checkUrls(goodurls: goodurls, badurls: badurls, checker: { url in
return url.isAboutURL
})
}
func testisErrorPage() {
let goodurls = [
"\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A//mozilla.com",
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"http://localhost:1234/about/home/#panel=0"
]
checkUrls(goodurls: goodurls, badurls: badurls, checker: { url in
return url.isErrorPage
})
}
func testoriginalURLFromErrorURL() {
let goodurls = [
("\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A//mozilla.com", URL(string: "http://mozilla.com")),
("\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A//localhost%3A\(AppInfo.webserverPort)/about/home/%23panel%3D1",
URL(string: "http://localhost:\(AppInfo.webserverPort)/about/home/#panel=1")),
]
goodurls.forEach {
var result = false
if let url = InternalURL(URL(string: $0.0)!) { result = (url.originalURLFromErrorPage == $0.1) }
XCTAssertTrue(result)
}
}
func testisReaderModeURL() {
let goodurls = [
"http://localhost:\(AppInfo.webserverPort)/reader-mode/page",
"http://localhost:\(AppInfo.webserverPort)/reader-mode/page?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2FMain%5FPage",
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"http://localhost:1234/about/home/#panel=0"
]
checkUrls(goodurls: goodurls, badurls: badurls) { url in
return url.url.isReaderModeURL
}
}
func testisSyncedReaderModeURL() {
let goodurls = [
"about:reader?url=",
"about:reader?url=http://example.com",
"about:reader?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2FMain%5FPage"
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"about:reader",
"http://about:reader?url=http://example.com"
]
goodurls.forEach { XCTAssertTrue(URL(string: $0)!.isSyncedReaderModeURL, $0) }
badurls.forEach { XCTAssertFalse(URL(string: $0)!.isSyncedReaderModeURL, $0) }
}
func testdecodeReaderModeURL() {
let goodurls = [
("http://localhost:\(AppInfo.webserverPort)/reader-mode/page?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2FMain%5FPage&uuidkey=AAAAA",
URL(string: "https://en.m.wikipedia.org/wiki/Main_Page")),
("about:reader?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2FMain%5FPage&uuidkey=AAAAA",
URL(string: "https://en.m.wikipedia.org/wiki/Main_Page")),
("about:reader?url=http%3A%2F%2Fexample%2Ecom%3Furl%3Dparam%26key%3Dvalue&uuidkey=AAAAA",
URL(string: "http://example.com?url=param&key=value"))
]
let badurls = [
"http://google.com",
"http://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"http://localhost:1234/about/home/#panel=0",
"http://localhost:\(AppInfo.webserverPort)/reader-mode/page",
"about:reader?url="
]
goodurls.forEach { XCTAssertEqual(URL(string: $0.0)!.decodeReaderModeURL, $0.1) }
badurls.forEach { XCTAssertNil(URL(string: $0)!.decodeReaderModeURL, $0) } }
func testencodeReaderModeURL() {
let ReaderURL = "http://localhost:\(AppInfo.webserverPort)/reader-mode/page"
let goodurls = [
("https://en.m.wikipedia.org/wiki/Main_Page",
URL(string: "http://localhost:\(AppInfo.webserverPort)/reader-mode/page?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2FMain%5FPage"))
]
goodurls.forEach { XCTAssertEqual(URL(string: $0.0)!.encodeReaderModeURL(ReaderURL), $0.1) }
}
func testhavingRemovedAuthorisationComponents() {
let goodurls = [
("https://Aladdin:[email protected]/index.html", "https://www.example.com/index.html"),
("https://www.example.com/noauth", "https://www.example.com/noauth")
]
goodurls.forEach { XCTAssertEqual(URL(string: $0.0)!.havingRemovedAuthorisationComponents().absoluteString, $0.1) }
}
func testschemeIsValid() {
let goodurls = [
"http://localhost:\(AppInfo.webserverPort)/reader-mode/page",
"https://google.com",
"tel:6044044004"
]
let badurls = [
"blah://google.com",
"hax://localhost:\(AppInfo.webserverPort)/sessionrestore.html",
"leet://codes.com"
]
goodurls.forEach { XCTAssertTrue(URL(string: $0)!.schemeIsValid, $0) }
badurls.forEach { XCTAssertFalse(URL(string: $0)!.schemeIsValid, $0) }
}
func testisWebPage() {
let goodurls = [
"http://localhost:\(AppInfo.webserverPort)/reader-mode/page",
"https://127.0.0.1:\(AppInfo.webserverPort)/sessionrestore.html",
"data://:\(AppInfo.webserverPort)/sessionrestore.html"
]
let badurls = [
"about://google.com",
"tel:6044044004",
"hax://localhost:\(AppInfo.webserverPort)/about"
]
goodurls.forEach { XCTAssertTrue(URL(string: $0)!.isWebPage(), $0) }
badurls.forEach { XCTAssertFalse(URL(string: $0)!.isWebPage(), $0) }
}
func testdomainURL() {
let urls = [
("https://www.example.com/index.html", "https://example.com/"),
("https://mail.example.com/index.html", "https://mail.example.com/"),
("https://mail.example.co.uk/index.html", "https://mail.example.co.uk/"),
]
urls.forEach { XCTAssertEqual(URL(string: $0.0)!.domainURL.absoluteString, $0.1) }
}
func testdisplayURL() {
let goodurls = [
("http://localhost:\(AppInfo.webserverPort)/reader-mode/page?url=https%3A%2F%2Fen%2Em%2Ewikipedia%2Eorg%2Fwiki%2F",
"https://en.m.wikipedia.org/wiki/"),
("\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A//mozilla.com",
"http://mozilla.com"),
("\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A//mozilla.com",
"http://mozilla.com"),
("\(InternalURL.baseUrl)/\(InternalURL.Path.errorpage)?url=http%3A%2F%2Flocalhost%3A\(AppInfo.webserverPort)%2Freader-mode%2Fpage%3Furl%3Dhttps%253A%252F%252Fen%252Em%252Ewikipedia%252Eorg%252Fwiki%252F",
"https://en.m.wikipedia.org/wiki/"),
("https://mail.example.co.uk/index.html",
"https://mail.example.co.uk/index.html"),
]
let badurls = [
"http://localhost:\(AppInfo.webserverPort)/errors/error.html?url=http%3A//localhost%3A\(AppInfo.webserverPort)/about/home/%23panel%3D1",
"http://localhost:\(AppInfo.webserverPort)/errors/error.html",
]
goodurls.forEach { XCTAssertEqual(URL(string: $0.0)!.displayURL?.absoluteString, $0.1) }
badurls.forEach { XCTAssertNil(URL(string: $0)!.displayURL) }
}
func testnormalizedHostAndPath() {
let goodurls = [
("https://www.example.com/index.html", "example.com/index.html"),
("https://mail.example.com/index.html", "mail.example.com/index.html"),
("https://mail.example.co.uk/index.html", "mail.example.co.uk/index.html"),
("https://m.example.co.uk/index.html", "example.co.uk/index.html")
]
let badurls = [
"http:///errors/error.html",
"http://:\(AppInfo.webserverPort)/about/home",
]
goodurls.forEach { XCTAssertEqual(URL(string: $0.0)!.normalizedHostAndPath, $0.1) }
badurls.forEach { XCTAssertNil(URL(string: $0)!.normalizedHostAndPath) }
}
func testShortDisplayString() {
let urls = [
("https://www.example.com/index.html", "example"),
("https://m.foo.com/bar/baz?noo=abc#123", "foo"),
("https://user:[email protected]/bar/baz?noo=abc#123", "foo"),
("https://accounts.foo.com/bar/baz?noo=abc#123", "accounts.foo"),
("https://accounts.what.foo.co.za/bar/baz?noo=abc#123", "accounts.what.foo"),
]
urls.forEach { XCTAssertEqual(URL(string: $0.0)!.shortDisplayString, $0.1) }
}
func testorigin() {
let urls = [
("https://www.example.com/index.html", "https://www.example.com"),
("https://user:[email protected]/bar/baz?noo=abc#123", "https://m.foo.com"),
]
let badurls = [
"data://google.com"
]
urls.forEach { XCTAssertEqual(URL(string: $0.0)!.origin, $0.1) }
badurls.forEach { XCTAssertNil(URL(string: $0)!.origin) }
}
func testhostPort() {
let urls = [
("https://www.example.com", "www.example.com"),
("https://user:[email protected]", "www.example.com"),
("http://localhost:6000/blah", "localhost:6000")
]
let badurls = [
"blah",
"http://"
]
urls.forEach { XCTAssertEqual(URL(string: $0.0)!.hostPort, $0.1) }
badurls.forEach { XCTAssertNil(URL(string: $0)!.hostPort) }
}
func testgetQuery() {
let url = URL(string: "http://example.com/path?a=1&b=2&c=3")!
let params = ["a": "1", "b": "2", "c": "3"]
let urlParams = url.getQuery()
params.forEach { XCTAssertEqual(urlParams[$0], $1, "The values in params should be the same in urlParams") }
}
func testwithQueryParams() {
let url = URL(string: "http://example.com/path")!
let params = ["a": "1", "b": "2", "c": "3"]
let newURL = url.withQueryParams(params.map { URLQueryItem(name: $0, value: $1) })
// make sure the new url has all the right params.
let newURLParams = newURL.getQuery()
params.forEach { XCTAssertEqual(newURLParams[$0], $1, "The values in params should be the same in newURLParams") }
}
func testWithQueryParam() {
let urlA = URL(string: "http://foo.com/bar/")!
let urlB = URL(string: "http://bar.com/noo")!
let urlC = urlA.withQueryParam("ppp", value: "123")
let urlD = urlB.withQueryParam("qqq", value: "123")
let urlE = urlC.withQueryParam("rrr", value: "aaa")
XCTAssertEqual("http://foo.com/bar/?ppp=123", urlC.absoluteString)
XCTAssertEqual("http://bar.com/noo?qqq=123", urlD.absoluteString)
XCTAssertEqual("http://foo.com/bar/?ppp=123&rrr=aaa", urlE.absoluteString)
}
func testHidingFromDataDetectors() {
guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else {
XCTFail()
return
}
let urls = ["https://example.com", "example.com", "http://example.com"]
for u in urls {
let url = URL(string: u)!
let original = url.absoluteDisplayString
let matches = detector.matches(in: original, options: [], range: NSRange(location: 0, length: original.count))
guard !matches.isEmpty else {
print("\(url) doesn't match as a URL")
continue
}
let modified = url.absoluteDisplayExternalString
XCTAssertNotEqual(original, modified)
let newMatches = detector.matches(in: modified, options: [], range: NSRange(location: 0, length: modified.count))
XCTAssertEqual(0, newMatches.count, "\(modified) is not a valid URL")
}
}
}
| mpl-2.0 | c0656b8f025b7e7301048d3091c7da9d | 37.556213 | 216 | 0.590956 | 3.743393 | false | true | false | false |
tbkka/swift-protobuf | Tests/SwiftProtobufTests/Test_MessageSet.swift | 6 | 8384 | // Tests/SwiftProtobufTests/Test_MessageSet.swift - Test MessageSet behaviors
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Test all behaviors around the message option message_set_wire_format.
///
// -----------------------------------------------------------------------------
import Foundation
import XCTest
@testable import SwiftProtobuf
extension ProtobufUnittest_RawMessageSet.Item {
fileprivate init(typeID: Int, message: Data) {
self.init()
self.typeID = Int32(typeID)
self.message = message
}
}
class Test_MessageSet: XCTestCase {
// wireformat_unittest.cc: TEST(WireFormatTest, SerializeMessageSet)
func testSerialize() throws {
let msg = Proto2WireformatUnittest_TestMessageSet.with {
$0.ProtobufUnittest_TestMessageSetExtension1_messageSetExtension.i = 123
$0.ProtobufUnittest_TestMessageSetExtension2_messageSetExtension.str = "foo"
}
let serialized: Data
do {
serialized = try msg.serializedData()
} catch let e {
XCTFail("Failed to serialize: \(e)")
return
}
// Read it back in with the RawMessageSet to validate it.
let raw: ProtobufUnittest_RawMessageSet
do {
raw = try ProtobufUnittest_RawMessageSet(serializedData: serialized)
} catch let e {
XCTFail("Failed to parse: \(e)")
return
}
XCTAssertTrue(raw.unknownFields.data.isEmpty)
XCTAssertEqual(raw.item.count, 2)
XCTAssertEqual(Int(raw.item[0].typeID),
ProtobufUnittest_TestMessageSetExtension1.Extensions.message_set_extension.fieldNumber)
XCTAssertEqual(Int(raw.item[1].typeID),
ProtobufUnittest_TestMessageSetExtension2.Extensions.message_set_extension.fieldNumber)
let extMsg1 = try ProtobufUnittest_TestMessageSetExtension1(serializedData: raw.item[0].message)
XCTAssertEqual(extMsg1.i, 123)
XCTAssertTrue(extMsg1.unknownFields.data.isEmpty)
let extMsg2 = try ProtobufUnittest_TestMessageSetExtension2(serializedData: raw.item[1].message)
XCTAssertEqual(extMsg2.str, "foo")
XCTAssertTrue(extMsg2.unknownFields.data.isEmpty)
}
// wireformat_unittest.cc: TEST(WireFormatTest, ParseMessageSet)
func testParse() throws {
let msg1 = ProtobufUnittest_TestMessageSetExtension1.with { $0.i = 123 }
let msg2 = ProtobufUnittest_TestMessageSetExtension2.with { $0.str = "foo" }
var raw = ProtobufUnittest_RawMessageSet()
raw.item = [
// Two known extensions.
ProtobufUnittest_RawMessageSet.Item(
typeID: ProtobufUnittest_TestMessageSetExtension1.Extensions.message_set_extension.fieldNumber,
message: try msg1.serializedData()),
ProtobufUnittest_RawMessageSet.Item(
typeID: ProtobufUnittest_TestMessageSetExtension2.Extensions.message_set_extension.fieldNumber,
message: try msg2.serializedData()),
// One unknown extension.
ProtobufUnittest_RawMessageSet.Item(typeID: 7, message: Data([1, 2, 3]))
]
// Add some unknown data into one of the groups to ensure it gets stripped when parsing.
raw.item[1].unknownFields.append(protobufData: Data([40, 2])) // Field 5, varint of 2
let serialized: Data
do {
serialized = try raw.serializedData()
} catch let e {
XCTFail("Failed to serialize: \(e)")
return
}
let msg: Proto2WireformatUnittest_TestMessageSet
do {
msg = try Proto2WireformatUnittest_TestMessageSet(
serializedData: serialized,
extensions: ProtobufUnittest_UnittestMset_Extensions)
} catch let e {
XCTFail("Failed to parse: \(e)")
return
}
// Ensure the extensions showed up, but with nothing extra.
XCTAssertEqual(
msg.ProtobufUnittest_TestMessageSetExtension1_messageSetExtension.i, 123)
XCTAssertTrue(
msg.ProtobufUnittest_TestMessageSetExtension1_messageSetExtension.unknownFields.data.isEmpty)
XCTAssertEqual(
msg.ProtobufUnittest_TestMessageSetExtension2_messageSetExtension.str, "foo")
XCTAssertTrue(
msg.ProtobufUnittest_TestMessageSetExtension2_messageSetExtension.unknownFields.data.isEmpty)
// Ensure the unknown shows up as a group.
let expectedUnknowns = Data([
11, // Start group
16, 7, // typeID = 7
26, 3, 1, 2, 3, // message data = 3 bytes: 1, 2, 3
12 // End Group
])
XCTAssertEqual(msg.unknownFields.data, expectedUnknowns)
var validator = ExtensionValidator()
validator.expectedMessages = [
(ProtobufUnittest_TestMessageSetExtension1.Extensions.message_set_extension.fieldNumber, false),
(ProtobufUnittest_TestMessageSetExtension2.Extensions.message_set_extension.fieldNumber, false),
]
validator.expectedUnknowns = [ expectedUnknowns ]
validator.validate(message: msg)
}
static let canonicalTextFormat: String = (
"message_set {\n" +
" [protobuf_unittest.TestMessageSetExtension1] {\n" +
" i: 23\n" +
" }\n" +
" [protobuf_unittest.TestMessageSetExtension2] {\n" +
" str: \"foo\"\n" +
" }\n" +
"}\n"
)
// text_format_unittest.cc: TEST_F(TextFormatMessageSetTest, Serialize)
func testTextFormat_Serialize() {
let msg = ProtobufUnittest_TestMessageSetContainer.with {
$0.messageSet.ProtobufUnittest_TestMessageSetExtension1_messageSetExtension.i = 23
$0.messageSet.ProtobufUnittest_TestMessageSetExtension2_messageSetExtension.str = "foo"
}
XCTAssertEqual(msg.textFormatString(), Test_MessageSet.canonicalTextFormat)
}
// text_format_unittest.cc: TEST_F(TextFormatMessageSetTest, Deserialize)
func testTextFormat_Parse() {
let msg: ProtobufUnittest_TestMessageSetContainer
do {
msg = try ProtobufUnittest_TestMessageSetContainer(
textFormatString: Test_MessageSet.canonicalTextFormat,
extensions: ProtobufUnittest_UnittestMset_Extensions)
} catch let e {
XCTFail("Shouldn't have failed: \(e)")
return
}
XCTAssertEqual(
msg.messageSet.ProtobufUnittest_TestMessageSetExtension1_messageSetExtension.i, 23)
XCTAssertEqual(
msg.messageSet.ProtobufUnittest_TestMessageSetExtension2_messageSetExtension.str, "foo")
// Ensure nothing else showed up.
XCTAssertTrue(msg.unknownFields.data.isEmpty)
XCTAssertTrue(msg.messageSet.unknownFields.data.isEmpty)
var validator = ExtensionValidator()
validator.expectedMessages = [
(1, true), // protobuf_unittest.TestMessageSetContainer.message_set (where the extensions are)
(ProtobufUnittest_TestMessageSetExtension1.Extensions.message_set_extension.fieldNumber, false),
(ProtobufUnittest_TestMessageSetExtension2.Extensions.message_set_extension.fieldNumber, false),
]
validator.validate(message: msg)
}
fileprivate struct ExtensionValidator: PBTestVisitor {
// Values are field number and if we should recurse.
var expectedMessages = [(Int, Bool)]()
var expectedUnknowns = [Data]()
mutating func validate<M: Message>(message: M) {
do {
try message.traverse(visitor: &self)
} catch let e {
XCTFail("Error while traversing: \(e)")
}
XCTAssertTrue(expectedMessages.isEmpty,
"Expected more messages: \(expectedMessages)")
XCTAssertTrue(expectedUnknowns.isEmpty,
"Expected more unknowns: \(expectedUnknowns)")
}
mutating func visitSingularMessageField<M: Message>(value: M, fieldNumber: Int) throws {
guard !expectedMessages.isEmpty else {
XCTFail("Unexpected Message: \(fieldNumber) = \(value)")
return
}
let (expected, shouldRecurse) = expectedMessages.removeFirst()
XCTAssertEqual(fieldNumber, expected)
if shouldRecurse && expected == fieldNumber {
try value.traverse(visitor: &self)
}
}
mutating func visitUnknown(bytes: Data) throws {
guard !expectedUnknowns.isEmpty else {
XCTFail("Unexpected Unknown: \(bytes)")
return
}
let expected = expectedUnknowns.removeFirst()
XCTAssertEqual(bytes, expected)
}
}
}
| apache-2.0 | 9478e901855966068d0fc0cbde5dc344 | 36.262222 | 106 | 0.692032 | 4.534343 | false | true | false | false |
kesun421/firefox-ios | Client/Utils/FaviconFetcher.swift | 1 | 13904 | /* 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 Storage
import Shared
import Alamofire
import XCGLogger
import Deferred
import SDWebImage
import Fuzi
import SwiftyJSON
private let log = Logger.browserLogger
private let queue = DispatchQueue(label: "FaviconFetcher", attributes: DispatchQueue.Attributes.concurrent)
class FaviconFetcherErrorType: MaybeErrorType {
let description: String
init(description: String) {
self.description = description
}
}
/* A helper class to find the favicon associated with a URL.
* This will load the page and parse any icons it finds out of it.
* If that fails, it will attempt to find a favicon.ico in the root host domain.
*/
open class FaviconFetcher: NSObject, XMLParserDelegate {
open static var userAgent: String = ""
static let ExpirationTime = TimeInterval(60*60*24*7) // Only check for icons once a week
fileprivate static var characterToFaviconCache = [String: UIImage]()
static var defaultFavicon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
static var colors: [String: UIColor] = [:] //An in-Memory data store that stores background colors domains. Stored using url.baseDomain.
// Sites can be accessed via their baseDomain.
static var defaultIcons: [String: (color: UIColor, url: String)] = {
return FaviconFetcher.getDefaultIcons()
}()
static let multiRegionDomains = ["craigslist", "google", "amazon"]
class func getDefaultIconForURL(url: URL) -> (color: UIColor, url: String)? {
// Problem: Sites like amazon exist with .ca/.de and many other tlds.
// Solution: They are stored in the default icons list as "amazon" instead of "amazon.com" this allows us to have favicons for every tld."
// Here, If the site is in the multiRegionDomain array look it up via its second level domain (amazon) instead of its baseDomain (amazon.com)
let hostName = url.hostSLD
if multiRegionDomains.contains(hostName), let icon = defaultIcons[hostName] {
return icon
}
if let name = url.baseDomain, let icon = defaultIcons[name] {
return icon
}
return nil
}
class func getForURL(_ url: URL, profile: Profile) -> Deferred<Maybe<[Favicon]>> {
let f = FaviconFetcher()
return f.loadFavicons(url, profile: profile)
}
fileprivate func loadFavicons(_ url: URL, profile: Profile, oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> {
if isIgnoredURL(url) {
return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons."))
}
let deferred = Deferred<Maybe<[Favicon]>>()
var oldIcons: [Favicon] = oldIcons
queue.async { _ in
self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in
var deferreds = [Deferred<Maybe<Favicon>>]()
if let icons = result.successValue {
deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) }
}
return all(deferreds)
}).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in
for result in results {
if let icon = result.successValue {
oldIcons.append(icon)
}
}
oldIcons = oldIcons.sorted {
return $0.width! > $1.width!
}
return deferMaybe(oldIcons)
}).upon({ (result: Maybe<[Favicon]>) in
deferred.fill(result)
return
})
}
return deferred
}
lazy fileprivate var alamofire: SessionManager = {
let configuration = URLSessionConfiguration.default
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = userAgent
configuration.httpAdditionalHeaders = defaultHeaders
configuration.timeoutIntervalForRequest = 5
return SessionManager(configuration: configuration)
}()
fileprivate func fetchDataForURL(_ url: URL) -> Deferred<Maybe<Data>> {
let deferred = Deferred<Maybe<Data>>()
alamofire.request(url).response { response in
// Don't cancel requests just because our Manager is deallocated.
withExtendedLifetime(self.alamofire) {
if response.error == nil {
if let data = response.data {
deferred.fill(Maybe(success: data))
return
}
}
let errorDescription = (response.error as NSError?)?.description ?? "No content."
deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: errorDescription)))
}
}
return deferred
}
///Users/fpatel/Documents/firefox-ios/Client/Utils/FaviconFetcher.swift:117:77: Cannot convert value of type 'String' to expected argument type 'String.Index' (aka 'String.CharacterView.Index')
// Loads and parses an html document and tries to find any known favicon-type tags for the page
fileprivate func parseHTMLForFavicons(_ url: URL) -> Deferred<Maybe<[Favicon]>> {
return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in
var icons = [Favicon]()
guard let data = result.successValue, result.isSuccess,
let root = try? HTMLDocument(data: data as Data) else {
return deferMaybe([])
}
var reloadUrl: URL? = nil
for meta in root.xpath("//head/meta") {
if let refresh = meta["http-equiv"], refresh == "Refresh",
let content = meta["content"],
let index = content.range(of: "URL="),
let url = NSURL(string: content.substring(from: index.upperBound)) {
reloadUrl = url as URL
}
}
if let url = reloadUrl {
return self.parseHTMLForFavicons(url)
}
var bestType = IconType.noneFound
for link in root.xpath("//head//link[contains(@rel, 'icon')]") {
var iconType: IconType? = nil
if let rel = link["rel"] {
switch rel {
case "shortcut icon":
iconType = .icon
case "icon":
iconType = .icon
case "apple-touch-icon":
iconType = .appleIcon
case "apple-touch-icon-precomposed":
iconType = .appleIconPrecomposed
default:
iconType = nil
}
}
guard let href = link["href"], iconType != nil else {
continue //Skip the rest of the loop. But don't stop the loop
}
if href.endsWith(".ico") {
iconType = .guess
}
if let type = iconType, !bestType.isPreferredTo(type), let iconUrl = NSURL(string: href, relativeTo: url as URL), let absoluteString = iconUrl.absoluteString {
let icon = Favicon(url: absoluteString, date: NSDate() as Date, type: type)
// If we already have a list of Favicons going already, then add it…
if type == bestType {
icons.append(icon)
} else {
// otherwise, this is the first in a new best yet type.
icons = [icon]
bestType = type
}
}
// If we haven't got any options icons, then use the default at the root of the domain.
if let url = NSURL(string: "/favicon.ico", relativeTo: url as URL), icons.isEmpty, let absoluteString = url.absoluteString {
let icon = Favicon(url: absoluteString, date: NSDate() as Date, type: .guess)
icons = [icon]
}
}
return deferMaybe(icons)
})
}
func getFavicon(_ siteUrl: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> {
let deferred = Deferred<Maybe<Favicon>>()
let url = icon.url
let manager = SDWebImageManager.shared()
let site = Site(url: siteUrl.absoluteString, title: "")
var fav = Favicon(url: url, type: icon.type)
if let url = url.asURL {
var fetch: SDWebImageOperation?
fetch = manager.loadImage(with: url,
options: .lowPriority,
progress: { (receivedSize, expectedSize, _) in
if receivedSize > FaviconManager.maximumFaviconSize || expectedSize > FaviconManager.maximumFaviconSize {
fetch?.cancel()
}
},
completed: { (img, _, _, _, _, url) in
guard let url = url else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
fav = Favicon(url: url.absoluteString, type: icon.type)
if let img = img {
fav.width = Int(img.size.width)
fav.height = Int(img.size.height)
profile.favicons.addFavicon(fav, forSite: site)
} else {
fav.width = 0
fav.height = 0
}
deferred.fill(Maybe(success: fav))
})
} else {
return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)"))
}
return deferred
}
// Returns a single Favicon UIImage for a given URL
class func fetchFavImageForURL(forURL url: URL, profile: Profile) -> Deferred<Maybe<UIImage>> {
let deferred = Deferred<Maybe<UIImage>>()
FaviconFetcher.getForURL(url.domainURL, profile: profile).uponQueue(DispatchQueue.main) { result in
var iconURL: URL?
if let favicons = result.successValue, favicons.count > 0, let faviconImageURL = favicons.first?.url.asURL {
iconURL = faviconImageURL
} else {
return deferred.fill(Maybe(failure: FaviconError()))
}
SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
if let image = image {
deferred.fill(Maybe(success: image))
} else {
deferred.fill(Maybe(failure: FaviconError()))
}
}
}
return deferred
}
// Returns the default favicon for a site based on the first letter of the site's domain
class func getDefaultFavicon(_ url: URL) -> UIImage {
guard let character = url.baseDomain?.characters.first else {
return defaultFavicon
}
let faviconLetter = String(character).uppercased()
if let cachedFavicon = characterToFaviconCache[faviconLetter] {
return cachedFavicon
}
var faviconImage = UIImage()
let faviconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: TwoLineCellUX.ImageSize, height: TwoLineCellUX.ImageSize))
faviconLabel.text = faviconLetter
faviconLabel.textAlignment = .center
faviconLabel.font = UIFont.systemFont(ofSize: 18, weight: UIFontWeightMedium)
faviconLabel.textColor = UIColor.white
UIGraphicsBeginImageContextWithOptions(faviconLabel.bounds.size, false, 0.0)
faviconLabel.layer.render(in: UIGraphicsGetCurrentContext()!)
faviconImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
characterToFaviconCache[faviconLetter] = faviconImage
return faviconImage
}
// Returns a color based on the url's hash
class func getDefaultColor(_ url: URL) -> UIColor {
guard let hash = url.baseDomain?.hashValue else {
return UIColor.gray
}
let index = abs(hash) % (UIConstants.DefaultColorStrings.count - 1)
let colorHex = UIConstants.DefaultColorStrings[index]
return UIColor(colorString: colorHex)
}
// Default favicons and background colors provided via mozilla/tippy-top-sites
class func getDefaultIcons() -> [String: (color: UIColor, url: String)] {
let filePath = Bundle.main.path(forResource: "top_sites", ofType: "json")
let file = try! Data(contentsOf: URL(fileURLWithPath: filePath!))
let json = JSON(file)
var icons: [String: (color: UIColor, url: String)] = [:]
json.forEach({
guard let url = $0.1["domain"].string, let color = $0.1["background_color"].string, var path = $0.1["image_url"].string else {
return
}
path = path.replacingOccurrences(of: ".png", with: "")
let filePath = Bundle.main.path(forResource: "TopSites/" + path, ofType: "png")
if let filePath = filePath {
if color == "#fff" || color == "#FFF" {
icons[url] = (UIColor.clear, filePath)
} else {
icons[url] = (UIColor(colorString: color.replacingOccurrences(of: "#", with: "")), filePath)
}
}
})
return icons
}
}
| mpl-2.0 | f8cab3114e5183768ab3ebc925369de9 | 42.173913 | 193 | 0.570997 | 5.042437 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/Support/FAQDetailViewController.swift | 1 | 1622 | //
// FAQDetailViewController.swift
// Habitica
//
// Created by Phillip Thelen on 13.08.20.
// Copyright © 2020 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
import Down
class FAQDetailViewController: BaseUIViewController {
var index: Int = -1
@IBOutlet weak var answerTextView: MarkdownTextView!
@IBOutlet weak var questionLabel: UILabel!
private let contentRepository = ContentRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
var faqTitle: String?
var faqText: String?
override func viewDidLoad() {
super.viewDidLoad()
topHeaderCoordinator?.hideHeader = true
answerTextView.contentInset = UIEdgeInsets.zero
answerTextView.textContainerInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
if let title = faqTitle {
questionLabel.text = title
}
if let text = faqText {
answerTextView.setMarkdownString(text)
}
if index >= 0 {
disposable.inner.add(contentRepository.getFAQEntry(index: index).on(value: {[weak self]entry in
self?.questionLabel.text = entry.question
self?.answerTextView.setMarkdownString(entry.answer, highlightUsernames: false)
}).start())
}
}
override func applyTheme(theme: Theme) {
super.applyTheme(theme: theme)
questionLabel.textColor = theme.primaryTextColor
answerTextView.backgroundColor = theme.contentBackgroundColor
}
}
| gpl-3.0 | 44de4c1e2367b7bb11d9e1bfa4b7fa47 | 29.584906 | 107 | 0.658853 | 4.88253 | false | false | false | false |
digitrick/LocalizedStringSwift | LocalizedStringSwift/LocalizableString.swift | 1 | 1843 | //
// Localizable.swift
//
// Created by Kenta Nakae on 11/17/16.
// Copyright © 2016 digitrick. All rights reserved.
//
import Foundation
/// default language: System or English
public let defaultLanguageIdentifier = Bundle.main.preferredLocalizations.first ?? "en"
/// default table name: Localizable.strings
public let defaultTableName = "Localizable"
/// defaultBundle: main bundle
public let defaultBundle = Bundle.main
/// LocalizableString Protocol
public protocol LocalizableString {
/// localize string
///
/// - Parameters:
/// - key: key
/// - language: language identifier
/// - tableName: table name
/// - bundle: bundle
/// - comment: comment
/// - Returns: localized string
func localized(key: String, language: String, tableName: String?, bundle: Bundle, comment: String) -> String
}
// MARK: - LocalizableString Protocol Default Extension
public extension LocalizableString {
public func localized(key: String, language: String = defaultLanguageIdentifier, tableName: String? = defaultTableName, bundle: Bundle = defaultBundle, comment: String = "") -> String {
var targetBundlePath = bundle.path(forResource: language, ofType: "lproj") ?? defaultBundle.bundlePath
var targetBundle = Bundle(path: targetBundlePath) ?? defaultBundle
let localizedString = NSLocalizedString(key, tableName: tableName, bundle: targetBundle, value: key, comment: comment)
if localizedString == key {
targetBundlePath = bundle.path(forResource: "Base", ofType: "lproj") ?? defaultBundle.bundlePath
targetBundle = Bundle(path: targetBundlePath) ?? defaultBundle
}
return NSLocalizedString(key, tableName: tableName, bundle: targetBundle, value: key, comment: comment)
}
}
| mit | a4d916cbe598410ce857fe2c1136b6bc | 35.84 | 189 | 0.687839 | 4.75969 | false | false | false | false |
zmeyc/GRDB.swift | Tests/GRDBTests/RecordInitializersTests.swift | 1 | 4281 | import XCTest
#if USING_SQLCIPHER
import GRDBCipher
#elseif USING_CUSTOMSQLITE
import GRDBCustomSQLite
#else
import GRDB
#endif
// Tests about how minimal can class go regarding their initializers
// What happens for a class without property, without any initializer?
class EmptyRecordWithoutInitializer : Record {
// nothing is required
}
// What happens if we add a mutable property, still without any initializer?
// A compiler error: class 'RecordWithoutInitializer' has no initializers
//
// class RecordWithoutInitializer : Record {
// let name: String?
// }
// What happens with a mutable property, and init(row: Row)?
class RecordWithMutablePropertyAndRowInitializer : Record {
var name: String?
required init(row: Row) {
super.init(row: row) // super.init(row: row) is required
self.name = "toto" // property can be set before or after super.init
}
}
// What happens with a mutable property, and init()?
class RecordWithMutablePropertyAndEmptyInitializer : Record {
var name: String?
override init() {
super.init() // super.init() is required
self.name = "toto" // property can be set before or after super.init
}
required init(row: Row) { // init(row) is required
super.init(row: row) // super.init(row: row) is required
}
}
// What happens with a mutable property, and a custom initializer()?
class RecordWithMutablePropertyAndCustomInitializer : Record {
var name: String?
init(name: String? = nil) {
self.name = name
super.init() // super.init() is required
}
required init(row: Row) { // init(row) is required
super.init(row: row) // super.init(row: row) is required
}
}
// What happens with an immutable property?
class RecordWithImmutableProperty : Record {
let initializedFromRow: Bool
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must bet set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
}
}
// What happens with an immutable property and init()?
class RecordWithPedigree : Record {
let initializedFromRow: Bool
override init() {
initializedFromRow = false // property must bet set before super.init(row: row)
super.init() // super.init() is required
}
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must bet set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
}
}
// What happens with an immutable property and a custom initializer()?
class RecordWithImmutablePropertyAndCustomInitializer : Record {
let initializedFromRow: Bool
init(name: String? = nil) {
initializedFromRow = false // property must bet set before super.init(row: row)
super.init() // super.init() is required
}
required init(row: Row) { // An initializer is required, and the minimum is init(row)
initializedFromRow = true // property must bet set before super.init(row: row)
super.init(row: row) // super.init(row: row) is required
}
}
class RecordInitializersTests : GRDBTestCase {
func testFetchedRecordAreInitializedFromRow() throws {
// Here we test that Record.init(row: Row) can be overriden independently from Record.init().
// People must be able to perform some initialization work when fetching records from the database.
XCTAssertFalse(RecordWithPedigree().initializedFromRow)
let dbQueue = try makeDatabaseQueue()
try dbQueue.inDatabase { db in
try db.execute("CREATE TABLE pedigrees (foo INTEGER)")
try db.execute("INSERT INTO pedigrees (foo) VALUES (NULL)")
let pedigree = try RecordWithPedigree.fetchOne(db, "SELECT * FROM pedigrees")!
XCTAssertTrue(pedigree.initializedFromRow) // very important
}
}
}
| mit | 998f5804b7baf5f462babde572f150e6 | 34.675 | 107 | 0.644943 | 4.381781 | false | false | false | false |
uasys/swift | test/SILGen/pointer_conversion.swift | 3 | 28107 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | %FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func sideEffect1() -> Int { return 1 }
func sideEffect2() -> Int { return 2 }
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(_ x: UnsafePointer<Int>) {}
func takesOptConstPointer(_ x: UnsafePointer<Int>?, and: Int) {}
func takesOptOptConstPointer(_ x: UnsafePointer<Int>??, and: Int) {}
func takesMutablePointer(_ x: UnsafeMutablePointer<Int>, and: Int) {}
func takesConstPointer(_ x: UnsafePointer<Int>, and: Int) {}
func takesMutableVoidPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstVoidPointer(_ x: UnsafeRawPointer) {}
func takesMutableRawPointer(_ x: UnsafeMutableRawPointer) {}
func takesConstRawPointer(_ x: UnsafeRawPointer) {}
func takesOptConstRawPointer(_ x: UnsafeRawPointer?, and: Int) {}
func takesOptOptConstRawPointer(_ x: UnsafeRawPointer??, and: Int) {}
// CHECK-LABEL: sil hidden @_T018pointer_conversion0A9ToPointerySpySiG_SPySiGSvtF
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>, [[MRP:%.*]] : $UnsafeMutableRawPointer):
func pointerToPointer(_ mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>, _ mrp: UnsafeMutableRawPointer) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesMutableVoidPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesMutableRawPointer(mp)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]
takesConstPointer(mp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(mp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstPointer(cp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: apply [[TAKES_CONST_POINTER]]([[CP]])
takesConstVoidPointer(cp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
takesConstRawPointer(cp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafePointer<Int>, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
takesConstRawPointer(mrp)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s017_convertPointerToB8Argument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer, UnsafeRawPointer>
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion14arrayToPointeryyF
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutablePointer<Int> on [[OWNER]]
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiGF
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: apply [[TAKES_CONST_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesMutableRawPointer(&ints)
// CHECK: [[TAKES_MUTABLE_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointerySvF :
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_T0s37_convertMutableArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_MUTABLE]]<Int, UnsafeMutableRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeMutableRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_MUTABLE_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(ints)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySVF :
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstPointer(ints, and: sideEffect1())
// CHECK: [[TAKES_OPT_CONST_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF :
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: apply [[TAKES_OPT_CONST_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion15stringToPointerySSF
func stringToPointer(_ s: String) {
takesConstVoidPointer(s)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_T018pointer_conversion21takesConstVoidPointerySV{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesConstRawPointer(s)
// CHECK: [[TAKES_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion20takesConstRawPointerySV{{[_0-9a-zA-Z]*}}F
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: apply [[TAKES_CONST_RAW_POINTER]]([[DEPENDENT]])
// CHECK: destroy_value [[OWNER]]
takesOptConstRawPointer(s, and: sideEffect1())
// CHECK: [[TAKES_OPT_CONST_RAW_POINTER:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF :
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: [[OWNER:%.*]] = apply [[CONVERT_STRING]]<UnsafeRawPointer>([[POINTER_BUF:%[0-9]*]],
// CHECK: [[POINTER:%.*]] = load [trivial] [[POINTER_BUF]]
// CHECK: [[DEPENDENT:%.*]] = mark_dependence [[POINTER]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEPENDENT]]
// CHECK: apply [[TAKES_OPT_CONST_RAW_POINTER]]([[OPTPTR]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion14inoutToPointeryyF
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box ${ var Int }
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
takesMutableRawPointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
takesMutableRawPointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion22takesMutableRawPointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivg
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutableRawPointer>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_T018pointer_conversion14inoutToPointeryyF10logicalIntL_Sivs
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(_ x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(_ x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(_ x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @_T018pointer_conversion19classInoutToPointeryyF
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box ${ var C }
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @_T018pointer_conversion19takesPlusOnePointer{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_T018pointer_conversion20takesPlusZeroPointerys026AutoreleasingUnsafeMutableF0VyAA1CCGF
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load_borrow [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [trivial] [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s30_convertInOutToPointerArgument{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [trivial] [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: [[OWNED_OUT_COPY:%.*]] = copy_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT_COPY]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @_T018pointer_conversion18ObjCMethodBridgingC0A4Args{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(_ x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @_T018pointer_conversion22functionInoutToPointeryyF
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned () -> () }
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_owned (@in ()) -> @out ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
// rdar://problem/31781386
// CHECK-LABEL: sil hidden @_T018pointer_conversion20inoutPointerOrderingyyF
func inoutPointerOrdering() {
// CHECK: [[ARRAY_BOX:%.*]] = alloc_box ${ var Array<Int> }
// CHECK: [[ARRAY:%.*]] = project_box [[ARRAY_BOX]] :
// CHECK: store {{.*}} to [init] [[ARRAY]]
var array = [Int]()
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_T018pointer_conversion19takesMutablePointerySpySiG_Si3andtF
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: apply [[TAKES_MUTABLE]]({{.*}}, [[RESULT2]])
// CHECK: strong_unpin
// CHECK: end_access [[ACCESS]]
takesMutablePointer(&array[sideEffect1()], and: sideEffect2())
// CHECK: [[TAKES_CONST:%.*]] = function_ref @_T018pointer_conversion17takesConstPointerySPySiG_Si3andtF
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[SIDE2:%.*]] = function_ref @_T018pointer_conversion11sideEffect2SiyF
// CHECK: [[RESULT2:%.*]] = apply [[SIDE2]]()
// CHECK: [[ACCESS:%.*]] = begin_access [read] [unknown] [[ARRAY]] : $*Array<Int>
// CHECK: apply [[TAKES_CONST]]({{.*}}, [[RESULT2]])
// CHECK: end_access [[ACCESS]]
takesConstPointer(&array[sideEffect1()], and: sideEffect2())
}
// rdar://problem/31542269
// CHECK-LABEL: sil hidden @_T018pointer_conversion20optArrayToOptPointerySaySiGSg5array_tF
func optArrayToOptPointer(array: [Int]?) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion20takesOptConstPointerySPySiGSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion013optOptArrayTodD7PointerySaySiGSgSg5array_tF
func optOptArrayToOptOptPointer(array: [Int]??) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD12ConstPointerySPySiGSgSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s35_convertConstArrayToPointerArgumentyXlSg_q_tSayxGs01_E0R_r0_lF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafePointer<Int>
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<Int, UnsafePointer<Int>>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafePointer<Int> on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafePointer<Int>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafePointer<Int>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafePointer<Int>> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafePointer<Int>>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafePointer<Int>>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafePointer<Int>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafePointer<Int>>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafePointer<Int>>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafePointer<Int>>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstPointer(array, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion21optStringToOptPointerySSSg6string_tF
func optStringToOptPointer(string: String?) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion23takesOptConstRawPointerySVSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptConstRawPointer(string, and: sideEffect1())
}
// CHECK-LABEL: sil hidden @_T018pointer_conversion014optOptStringTodD7PointerySSSgSg6string_tF
func optOptStringToOptOptPointer(string: String??) {
// CHECK: [[TAKES:%.*]] = function_ref @_T018pointer_conversion08takesOptD15ConstRawPointerySVSgSg_Si3andtF
// CHECK: [[BORROW:%.*]] = begin_borrow %0
// CHECK: [[COPY:%.*]] = copy_value [[BORROW]]
// CHECK: [[SIDE1:%.*]] = function_ref @_T018pointer_conversion11sideEffect1SiyF
// CHECK: [[RESULT1:%.*]] = apply [[SIDE1]]()
// CHECK: [[T0:%.*]] = select_enum [[COPY]]
// FIXME: this should really go somewhere that will make nil, not some(nil)
// CHECK: cond_br [[T0]], [[SOME_BB:bb[0-9]+]], [[NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_BB]]:
// CHECK: [[SOME_VALUE:%.*]] = unchecked_enum_data [[COPY]]
// CHECK: [[T0:%.*]] = select_enum [[SOME_VALUE]]
// CHECK: cond_br [[T0]], [[SOME_SOME_BB:bb[0-9]+]], [[SOME_NONE_BB:bb[0-9]+]]
// CHECK: [[SOME_NONE_BB]]:
// CHECK: destroy_value [[SOME_VALUE]]
// CHECK: br [[SOME_NONE_BB2:bb[0-9]+]]
// CHECK: [[SOME_SOME_BB]]:
// CHECK: [[SOME_SOME_VALUE:%.*]] = unchecked_enum_data [[SOME_VALUE]]
// CHECK: [[CONVERT:%.*]] = function_ref @_T0s40_convertConstStringToUTF8PointerArgumentyXlSg_xtSSs01_F0RzlF
// CHECK: [[TEMP:%.*]] = alloc_stack $UnsafeRawPointer
// CHECK: [[OWNER:%.*]] = apply [[CONVERT]]<UnsafeRawPointer>([[TEMP:%.*]], [[SOME_SOME_VALUE]])
// CHECK: [[PTR:%.*]] = load [trivial] [[TEMP]]
// CHECK: [[DEP:%.*]] = mark_dependence [[PTR]] : $UnsafeRawPointer on [[OWNER]]
// CHECK: [[OPTPTR:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.some!enumelt.1, [[DEP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: br [[SOME_SOME_CONT_BB:bb[0-9]+]]([[OPTPTR]] : $Optional<UnsafeRawPointer>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_SOME_CONT_BB]]([[OPTPTR:%.*]] : $Optional<UnsafeRawPointer>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTDEP:%.*]] = mark_dependence [[OPTPTR]] : $Optional<UnsafeRawPointer> on [[OWNER]]
// CHECK: [[OPTOPTPTR:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.some!enumelt.1, [[OPTDEP]]
// CHECK: br [[SOME_CONT_BB:bb[0-9]+]]([[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER]] : $Optional<AnyObject>)
// CHECK: [[SOME_CONT_BB]]([[OPTOPTPTR:%.*]] : $Optional<Optional<UnsafeRawPointer>>, [[OWNER:%.*]] : $Optional<AnyObject>):
// CHECK: [[OPTOPTDEP:%.*]] = mark_dependence [[OPTOPTPTR]] : $Optional<Optional<UnsafeRawPointer>> on [[OWNER]]
// CHECK: apply [[TAKES]]([[OPTOPTDEP]], [[RESULT1]])
// CHECK: destroy_value [[OWNER]]
// CHECK: end_borrow [[BORROW]]
// CHECK: destroy_value %0
// CHECK: [[SOME_NONE_BB2]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<UnsafeRawPointer>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_SOME_CONT_BB]]([[NO_VALUE]] : $Optional<UnsafeRawPointer>, [[NO_OWNER]] : $Optional<AnyObject>)
// CHECK: [[NONE_BB]]:
// CHECK: [[NO_VALUE:%.*]] = enum $Optional<Optional<UnsafeRawPointer>>, #Optional.none
// CHECK: [[NO_OWNER:%.*]] = enum $Optional<AnyObject>, #Optional.none
// CHECK: br [[SOME_CONT_BB]]([[NO_VALUE]] : $Optional<Optional<UnsafeRawPointer>>, [[NO_OWNER]] : $Optional<AnyObject>)
takesOptOptConstRawPointer(string, and: sideEffect1())
}
| apache-2.0 | 9799f4f356713479297661ebf6e2243f | 59.706263 | 260 | 0.644395 | 3.667885 | false | false | false | false |
nathawes/swift | test/InterfaceHash/added_private_struct_property-type-fingerprints.swift | 6 | 2445 | // REQUIRES: shell
// Also uses awk:
// XFAIL OS=windows
// When adding a private protocol method, the interface hash should stay the same
// The per-type fingerprint should change
// RUN: %empty-directory(%t)
// RUN: %{python} %utils/split_file.py -o %t %s
// RUN: cp %t/{a,x}.swift
// RUN: %target-swift-frontend -typecheck -enable-type-fingerprints -primary-file %t/x.swift -emit-reference-dependencies-path %t/x.swiftdeps -module-name main
// RUN: %S/../Inputs/process_fine_grained_swiftdeps_with_fingerprints.sh %swift-dependency-tool %t/x.swiftdeps %t/a-processed.swiftdeps
// RUN: cp %t/{b,x}.swift
// RUN: %target-swift-frontend -typecheck -enable-type-fingerprints -primary-file %t/x.swift -emit-reference-dependencies-path %t/x.swiftdeps -module-name main
// RUN: %S/../Inputs/process_fine_grained_swiftdeps_with_fingerprints.sh %swift-dependency-tool %t/x.swiftdeps %t/b-processed.swiftdeps
// RUN: not diff %t/{a,b}-processed.swiftdeps >%t/diffs
// BEGIN a.swift
private struct S {
func f2() -> Int {
return 0
}
var y: Int = 0
}
// BEGIN b.swift
private struct S {
func f2() -> Int {
return 0
}
var x: Int = 0
var y: Int = 0
}
// RUN: %FileCheck %s <%t/diffs -check-prefix=CHECK-SAME-INTERFACE-HASH
// RUN: %FileCheck %s <%t/diffs -check-prefix=CHECK-DIFFERENT-TYPE-FINGERPRINT
// CHECK-SAME-INTERFACE-HASH-NOT: sourceFileProvides
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < topLevel implementation '' S true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < topLevel interface '' S true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > topLevel implementation '' S true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > topLevel interface '' S true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < nominal implementation 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < nominal interface 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > nominal implementation 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > nominal interface 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < potentialMember implementation 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: < potentialMember interface 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > potentialMember implementation 4main1S{{[^ ]+}} '' true
// CHECK-DIFFERENT-TYPE-FINGERPRINT-DAG: > potentialMember interface 4main1S{{[^ ]+}} '' true
| apache-2.0 | 95dde3d6c72d3b3023b4000dc46b0491 | 42.660714 | 159 | 0.701431 | 3.468085 | false | false | false | false |
feighter09/Cloud9 | Pods/Bond/Bond/Bond+UIBarItem.swift | 4 | 3157 | //
// Bond+UIBarItem.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
private var enabledDynamicHandleUIBarItem: UInt8 = 0;
private var titleDynamicHandleUIBarItem: UInt8 = 0;
private var imageDynamicHandleUIBarItem: UInt8 = 0;
extension UIBarItem: Bondable {
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleUIBarItem) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled)
let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleUIBarItem, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynTitle: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &titleDynamicHandleUIBarItem) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.title ?? "")
let bond = Bond<String>() { [weak self] v in if let s = self { s.title = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &titleDynamicHandleUIBarItem, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynImage: Dynamic<UIImage?> {
if let d: AnyObject = objc_getAssociatedObject(self, &imageDynamicHandleUIBarItem) {
return (d as? Dynamic<UIImage?>)!
} else {
let d = InternalDynamic<UIImage?>(self.image)
let bond = Bond<UIImage?>() { [weak self] img in if let s = self { s.image = img } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &imageDynamicHandleUIBarItem, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var designatedBond: Bond<Bool> {
return self.dynEnabled.valueBond
}
}
| lgpl-3.0 | 6d120cc6aae4d8cc9ddbf7b2953a4a72 | 39.474359 | 129 | 0.702882 | 4.12141 | false | false | false | false |
coolmacmaniac/swift-ios | DesignPatterns/DesignPatterns/AbstractFactory/DPOctal.swift | 1 | 988 | //
// DPOctal.swift
// DesignPatterns
//
// Created by Sourabh on 28/06/17.
// Copyright © 2017 Home. All rights reserved.
//
import Foundation
/**
Specifies the type for a number that has to be coverted to octal format
*/
struct DPOctal: DPBaseNumber {
/// To hold the decimal input value
private var value: Int
public static func getNumber(value: Int) -> DPBaseNumber {
return DPOctal(value: value)
}
public func convertBase() -> String {
// find the octal equivalent
let octVal = String(value, radix: DPNumberBase.octal.rawValue)
// calculate the padded length if the length is not a multiple of 3
var padding = Int(ceil(Double(octVal.characters.count) / 3))
padding = padding * 3 - octVal.characters.count
// pad the beginning with zeros, with one added zero for octal indication
var result = String(repeating: "0", count: padding + 1)
// append the actual converted value
result = result.appending(octVal)
return result
}
}
| gpl-3.0 | 83ed5d24613ebd5cfe1e65ae0c85980f | 23.073171 | 75 | 0.700101 | 3.5 | false | false | false | false |
gnachman/iTerm2 | iTermFileProvider/Paginator.swift | 2 | 3610 | //
// Paginator.swift
// FileProvider
//
// Created by George Nachman on 6/8/22.
//
import Foundation
import FileProvider
import FileProviderService
struct Paginator {
private let path: String
private let sorting: FileSorting?
private var service: RemoteService
private(set) var page: Page
private let pageSize: Int?
// A better data type for NSFileProviderPage
enum Page: CustomDebugStringConvertible {
case first(FileSorting)
case later(Data)
case finished
var hasMore: Bool {
switch self {
case .first(_), .later(_):
return true
case .finished:
return false
}
}
var data: Data? {
switch self {
case .first(_), .finished:
return nil
case .later(let data):
return data
}
}
var fileProviderPage: NSFileProviderPage? {
switch self {
case .first(.byName):
return NSFileProviderPage(NSFileProviderPage.initialPageSortedByName as Data)
case .first(.byDate):
return NSFileProviderPage(NSFileProviderPage.initialPageSortedByDate as Data)
case .later(let data):
return NSFileProviderPage(rawValue: data)
case .finished:
return nil
}
}
init(page: NSFileProviderPage) {
switch page.rawValue as NSData {
case NSFileProviderPage.initialPageSortedByName:
self = .first(.byName)
case NSFileProviderPage.initialPageSortedByDate:
self = .first(.byDate)
default:
self = .later(page.rawValue as Data)
}
}
var debugDescription: String {
switch self {
case .first(.byName):
return "firstByName"
case .first(.byDate):
return "firstByDate"
case .later(let data):
return "later(\(data.stringOrHex))"
case .finished:
return "finished"
}
}
var description: String {
return debugDescription
}
}
init(service: RemoteService,
path: String,
page: NSFileProviderPage,
pageSize: Int?) {
self.service = service
self.path = path
self.pageSize = pageSize
self.sorting = page.remoteServiceFileSorting
self.page = Page(page: page)
}
mutating func get() async throws -> [RemoteFile] {
precondition(hasMore)
return try await logging("Paginator.get") {
log("Request from service: path=\(path), page=\(page.debugDescription), sorting=\(String(describing: sorting)), pageSize=\(String(describing: pageSize)))")
let result = try await service.list(at: path,
fromPage: page.data,
sort: sorting ?? .byName,
pageSize: pageSize)
log("result is \(result)")
if let data = result.nextPage {
log("set page to .later")
page = .later(data)
} else {
log("set page to .finished")
page = .finished
}
return result.files
}
}
var hasMore: Bool {
log("Paginator: hasMore returning \(page.hasMore)")
return page.hasMore
}
}
| gpl-2.0 | 9478554eefa4f932f9b4ac93f0f7b68c | 28.834711 | 167 | 0.518283 | 5.277778 | false | false | false | false |
SteveKueng/SplashBuddy | SplashBuddy/Controller/Regexes.swift | 1 | 1488 | //
// Regexes.swift
// CasperWait
//
// Created by François on 10/02/16.
// Copyright © 2016 François Levaux. All rights reserved.
//
import Foundation
/**
Initialize Regexes
- returns: A Dictionary of status: regex
*/
func initRegex() -> Dictionary<Software.SoftwareStatus, NSRegularExpression?> {
let re_options = NSRegularExpression.Options.anchorsMatchLines
// Installing
let re_installing: NSRegularExpression?
do {
try re_installing = NSRegularExpression(
pattern: "(?<=Installing )([a-zA-Z0-9._ ]*) ",
options: re_options
)
} catch {
re_installing = nil
}
// Failure
let re_failure: NSRegularExpression?
do {
try re_failure = NSRegularExpression(
pattern: "(?<=Install of )([a-zA-Z0-9._ ]*)-([a-zA-Z0-9._]*): FAILED",
options: re_options
)
} catch {
re_failure = nil
}
// Success
let re_success: NSRegularExpression?
do {
try re_success = NSRegularExpression(
pattern: "(?<=Install of )([a-zA-Z0-9._ ]*)-([a-zA-Z0-9._]*): SUCCESSFUL$",
options: re_options
)
} catch {
re_success = nil
}
return [
.success: re_success,
.failed: re_failure,
.installing: re_installing
]
}
| apache-2.0 | 11431e6763614f54ad2e21ccfea067ad | 17.333333 | 87 | 0.506397 | 4.279539 | false | false | false | false |
alloyapple/Goose | Sources/Goose/Product.swift | 1 | 4735 | //
// Created by color on 12/25/17.
//
import Foundation
/**
Returns an iterator-sequence for the Cartesian product of the sequences.
```
let values = product([1, 2, 3], [4, 5, 6, 7], [8, 9])
// [1, 4, 8], [1, 4, 9], [1, 5, 8], [1, 5, 9], [1, 6, 8], ... [3, 7, 9]
```
- Parameter sequences: The sequences from which to compute the product.
- Returns: An iterator-sequence for the Cartesian product of the sequences.
*/
public func product<S: Sequence>(_ sequences: S...) -> CartesianProduct<S> {
return CartesianProduct(sequences)
}
/**
Returns an iterator-sequence for the Cartesian product of the sequence repeated with itself a number of times.
```
let values = product([1, 2, 3], repeated: 2)
// Equivalent to product([1, 2, 3], [1, 2, 3])
```
- Parameters:
- sequence: The sequence from which to compute the product.
- repeated: The number of times to repeat the sequence with itself in computing the product.
- Returns: An iterator-sequence for the Cartesian product of the sequence repeated with itself a number of times.
*/
public func product<S: Sequence>(_ sequence: S, repeated: Int) -> CartesianProduct<S> {
let sequences = Array(repeating: sequence, count: repeated)
return CartesianProduct(sequences)
}
/**
Returns an iterator-sequence for the Cartesian product of two sequences containing elements of different types.
```
let values = mixedProduct(["a", "b"], [1, 2, 3])
// ("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)
```
- Parameters:
- firstSequence: The first of the two sequences used in computing the product.
- secondSequence: The second of the two sequences used in computing the product.
- Returns: An iterator-sequence for the Cartesian product of two sequences containing elements of different types.
*/
public func mixedProduct<S1: Sequence, S2: Sequence>(_ firstSequence: S1, _ secondSequence: S2) -> MixedTypeCartesianProduct<S1, S2> {
// If this function is named `product`, "ambiguous reference to `product`" error can occur
return MixedTypeCartesianProduct(firstSequence, secondSequence)
}
/// An iterator-sequence for the Cartesian product of multiple sequences of the same type.
/// See `product(_:)`.
public struct CartesianProduct<S: Sequence>: IteratorProtocol, Sequence {
private let sequences: [S]
private var iterators: [S.Iterator]
private var currentValues: [S.Iterator.Element] = []
fileprivate init(_ sequences: [S]) {
self.sequences = sequences
self.iterators = sequences.map { $0.makeIterator() }
}
public mutating func next() -> [S.Iterator.Element]? {
guard !currentValues.isEmpty else {
var firstValues: [S.Iterator.Element] = []
for index in iterators.indices {
guard let value = iterators[index].next() else {
return nil
}
firstValues.append(value)
}
currentValues = firstValues
return firstValues
}
for index in currentValues.indices.reversed() {
if let value = iterators[index].next() {
currentValues[index] = value
return currentValues
}
guard index != 0 else {
return nil
}
iterators[index] = sequences[index].makeIterator()
currentValues[index] = iterators[index].next()!
}
return currentValues
}
}
/// An iterator-sequence for the Cartesian product of two sequences of different types.
/// See `mixedProduct(_:_:)`.
public struct MixedTypeCartesianProduct<S1: Sequence, S2: Sequence>: IteratorProtocol, Sequence {
private let secondSequence: S2
private var firstIterator: S1.Iterator
private var secondIterator: S2.Iterator
private var currentFirstElement: S1.Iterator.Element?
fileprivate init(_ firstSequence: S1, _ secondSequence: S2) {
self.secondSequence = secondSequence
self.firstIterator = firstSequence.makeIterator()
self.secondIterator = secondSequence.makeIterator()
self.currentFirstElement = firstIterator.next()
}
public mutating func next() -> (S1.Iterator.Element, S2.Iterator.Element)? {
// Avoid stack overflow
guard secondSequence.underestimatedCount > 0 else {
return nil
}
guard let firstElement = currentFirstElement else {
return nil
}
guard let secondElement = secondIterator.next() else {
currentFirstElement = firstIterator.next()
secondIterator = secondSequence.makeIterator()
return next()
}
return (firstElement, secondElement)
}
} | bsd-3-clause | 712163850fa40ae1027bdb86a187f270 | 34.343284 | 134 | 0.64773 | 4.332113 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Persistence/Migrations/DatabaseMigration.swift | 2 | 2791 | //
// DatabaseMigration.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 30/03/2019.
// Copyright © 2019 Will Baumann. All rights reserved.
//
import Foundation
import FMDB
let DB_VERSION_UUID = 19
protocol DatabaseMigration {
var version: Int { get }
func migrate(_ database: Database) -> Bool
}
class DatabaseMigrator: NSObject {
lazy var feedbackComposer: FeedbackComposer = FeedbackComposer()
private static var allMigrations: [DatabaseMigration] = {
return [
DatabaseCreateAtVersion11(),
DatabaseUpgradeToVersion12(),
DatabaseUpgradeToVersion13(),
DatabaseUpgradeToVersion14(),
DatabaseUpgradeToVersion15(),
DatabaseUpgradeToVersion16(),
DatabaseUpgradeToVersion17(),
DatabaseUpgradeToVersion18(),
DatabaseUpgradeToVersion19()
]
}()
@objc func migrate(database: Database) -> Bool {
let dbPath = database.pathToDatabase
let copyName = "migration_failed.db"
let copyPath = dbPath.asNSString.deletingLastPathComponent.asNSString.appendingPathComponent(copyName)
_ = FileManager.forceCopy(from: dbPath, to: copyPath)
let migrationResult = run(migrations: DatabaseMigrator.allMigrations, database: database)
if !migrationResult {
database.close()
try? FileManager().removeItem(atPath: dbPath)
_ = FileManager.forceCopy(from: copyPath, to: dbPath)
processFailedMigration(databasePath: copyPath)
} else {
processSuccessMigration()
}
try? FileManager().removeItem(atPath: copyPath)
return migrationResult
}
func run(migrations: [DatabaseMigration], database: Database) -> Bool {
let tick = TickTock.tick()
var currentVersion = database.databaseVersion()
Logger.debug("Current version: \(currentVersion)")
for migration in migrations {
if currentVersion >= migration.version {
Logger.error("DB at version \(currentVersion), will skip migration to \(migration.version)")
continue
}
Logger.info("Migrate to version \(migration.version)")
if !migration.migrate(database) {
Logger.error("Failed on migration \(migration.version)")
return false
}
currentVersion = migration.version
database.setDatabaseVersion(currentVersion)
}
Logger.debug("Migration time \(tick.tock())")
return true
}
}
extension DatabaseMigrator {
@objc static var UUIDVersion: Int = 19
}
| agpl-3.0 | 1a55218d3c594ca60f0b54110d3e7bdd | 30.704545 | 110 | 0.611111 | 5.264151 | false | false | false | false |
mozilla-mobile/firefox-ios | Storage/ReadingList.swift | 2 | 2190 | // 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
func ReadingListNow() -> Timestamp {
return Timestamp(Date.timeIntervalSinceReferenceDate * 1000.0)
}
let ReadingListDefaultUnread: Bool = true
let ReadingListDefaultArchived: Bool = false
let ReadingListDefaultFavorite: Bool = false
public protocol ReadingList {
func getAvailableRecords() -> Deferred<Maybe<[ReadingListItem]>>
func getAvailableRecords(completion: @escaping ([ReadingListItem]) -> Void)
func deleteRecord(_ record: ReadingListItem, completion: ((Bool) -> Void)?)
@discardableResult func createRecordWithURL(_ url: String, title: String, addedBy: String) -> Deferred<Maybe<ReadingListItem>>
func getRecordWithURL(_ url: String) -> Deferred<Maybe<ReadingListItem>>
@discardableResult func updateRecord(_ record: ReadingListItem, unread: Bool) -> Deferred<Maybe<ReadingListItem>>
}
public struct ReadingListItem: Equatable {
public let id: Int
public let lastModified: Timestamp
public let url: String
public let title: String
public let addedBy: String
public let unread: Bool
public let archived: Bool
public let favorite: Bool
/// Initializer for when a record is loaded from a database row
public init(id: Int, lastModified: Timestamp, url: String, title: String, addedBy: String, unread: Bool = true, archived: Bool = false, favorite: Bool = false) {
self.id = id
self.lastModified = lastModified
self.url = url
self.title = title
self.addedBy = addedBy
self.unread = unread
self.archived = archived
self.favorite = favorite
}
}
public func == (lhs: ReadingListItem, rhs: ReadingListItem) -> Bool {
return lhs.id == rhs.id
&& lhs.lastModified == rhs.lastModified
&& lhs.url == rhs.url
&& lhs.title == rhs.title
&& lhs.addedBy == rhs.addedBy
&& lhs.unread == rhs.unread
&& lhs.archived == rhs.archived
&& lhs.favorite == rhs.favorite
}
| mpl-2.0 | 75291dc883717330ddad1b219b0ee91c | 37.421053 | 165 | 0.690868 | 4.543568 | false | false | false | false |
benlangmuir/swift | test/expr/closure/closures.swift | 2 | 37761 | // RUN: %target-typecheck-verify-swift -disable-availability-checking
var func6 : (_ fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(_ f: (Int, Int) -> Int, _ n: Int = 0) {}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{53-53= _ in}}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0
// expected-error@-1 {{cannot convert value of type 'Double' to closure result type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int = { 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{27-27=()}} // expected-note {{Remove '=' to make 'closure7' a computed property}}{{20-22=}}
var capturedVariable = 1
var closure8 = { [capturedVariable] in
capturedVariable += 1 // expected-error {{left side of mutating operator isn't mutable: 'capturedVariable' is an immutable capture}}
}
func funcdecl1(_ a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(_ a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(_ a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6({$0 + $1}) // Closure with two named anonymous arguments
func6({($0) + $1}) // Closure with sequence expr inferred type
func6({($0) + $0}) // // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
var testfunc : ((), Int) -> Int // expected-note {{'testfunc' declared here}}
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
// expected-error@-1 {{cannot convert value of type '(Int) -> Int' to expected argument type '()'}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11) // expected-warning {{expression shuffles the elements of this tuple; this behavior is deprecated}}
funcdecl1(123, 444)
// Calls.
4() // expected-error {{cannot call value of non-function type 'Int'}}{{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6({ a, b -> Int in a+b})
// Return type inference.
func6({ a,b in a+b })
// Infer incompatible type.
func6({a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{17-22=Int}} // Pattern doesn't need to name arguments.
func6({ _,_ in 4 })
func6({a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6({(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, Int) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(_ x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(_ p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(_ a: Any) -> Int { return 1 }
assert(f0(1) == 1)
// TODO(diagnostics): Bad diagnostic - should be `circular reference`
var selfRef = { selfRef() }
// expected-error@-1 {{unable to infer closure type in the current context}}
// TODO: should be an error `circular reference` but it's diagnosed via overlapped requests
var nestedSelfRef = {
var recursive = { nestedSelfRef() }
// expected-warning@-1 {{variable 'recursive' was never mutated; consider changing to 'let' constant}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
func f(_: String) {}
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{26-28=z}}
var a4 = { (z: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'z'?}} {{7-9=z}} expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
}
var a5 = { (_: [Int], w: [Int]) in
f($0.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
f($1.count) // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments; did you mean 'w'?}} {{7-9=w}}
}
}
func doStuff(_ fn : @escaping () -> Int) {}
func doVoidStuff(_ fn : @escaping () -> ()) {}
func doVoidStuffNonEscaping(_ fn: () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base or an explicit capture.
doVoidStuff({ self.x += 1 })
doVoidStuff({ [self] in x += 1 })
doVoidStuff({ [self = self] in x += 1 })
doVoidStuff({ [unowned self] in x += 1 })
doVoidStuff({ [unowned(unsafe) self] in x += 1 })
doVoidStuff({ [unowned self = self] in x += 1 })
doStuff({ [self] in x+1 })
doStuff({ [self = self] in x+1 })
doStuff({ self.x+1 })
doStuff({ [unowned self] in x+1 })
doStuff({ [unowned(unsafe) self] in x+1 })
doStuff({ [unowned self = self] in x+1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff({ doStuff({ x+1 })}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{28-28= [self] in}} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{19-19=self.}}
doVoidStuff({ _ = "\(x)"}) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff({ [y = self] in x += 1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{33-33=self.}}
doStuff({ [y = self] in x+1 }) // expected-warning {{capture 'y' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in x += 1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in x+1 }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in x += 1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in x+1 }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}}
// Methods follow the same rules as properties, uses of 'self' without capturing must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}} expected-note{{reference 'self.' explicitly}} {{15-15=self.}}
doVoidStuff { _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}}
doVoidStuff { () -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{35-35=self.}}
doVoidStuff { [y = self] in _ = method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{20-20=self, }} expected-note{{reference 'self.' explicitly}} {{37-37=self.}}
doStuff({ [y = self] in method() }) // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{29-29=self.}}
doVoidStuff({ [weak self] in _ = method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [weak self] in method() }) // expected-note {{weak capture of 'self' here does not enable implicit 'self'}} expected-warning {{variable 'self' was written to, but never read}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff({ [self = self.x] in _ = method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doStuff({ [self = self.x] in method() }) // expected-note {{variable other than 'self' captured here under the name 'self' does not enable implicit 'self'}} expected-warning {{capture 'self' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}}
doVoidStuff { _ = self.method() }
doVoidStuff { [self] in _ = method() }
doVoidStuff { [self = self] in _ = method() }
doVoidStuff({ [unowned self] in _ = method() })
doVoidStuff({ [unowned(unsafe) self] in _ = method() })
doVoidStuff({ [unowned self = self] in _ = method() })
doStuff { self.method() }
doStuff { [self] in method() }
doStuff({ [self = self] in method() })
doStuff({ [unowned self] in method() })
doStuff({ [unowned(unsafe) self] in method() })
doStuff({ [unowned self = self] in method() })
// When there's no space between the opening brace and the first expression, insert it
doStuff {method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in }} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
doVoidStuff {_ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doVoidStuff {() -> () in _ = method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self]}} expected-note{{reference 'self.' explicitly}} {{34-34=self.}}
// With an empty capture list, insertion should be suggested without a comma
doStuff { [] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{21-21=self.}}
doStuff { [ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
doStuff { [ /* This space intentionally left blank. */ ] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}} expected-note{{reference 'self.' explicitly}} {{65-65=self.}}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self}}
doStuff { [ // Nothing in this capture list!
]
in
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{9-9=self.}}
}
// An inserted capture list should be on the same line as the opening brace, immediately following it.
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+2 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
// Note: Trailing whitespace on the following line is intentional and should not be removed!
doStuff {
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff { // We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// expected-note@+1 {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{14-14= [self] in}}
doStuff {// We have stuff to do.
method() // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{7-7=self.}}
}
// String interpolation should offer the diagnosis and fix-its at the expected locations
doVoidStuff { _ = "\(method())" } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
doVoidStuff { _ = "\(x+1)" } // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{26-26=self.}} expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}} {{18-18= [self] in}}
// If we already have a capture list, self should be added to the list
let y = 1
doStuff { [y] in method() } // expected-warning {{capture 'y' was never used}} expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }} expected-note{{reference 'self.' explicitly}} {{22-22=self.}}
doStuff { [ // expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
y // expected-warning {{capture 'y' was never used}}
] in method() } // expected-error {{call to method 'method' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{reference 'self.' explicitly}} {{14-14=self.}}
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{23-23= [self] in }} expected-note{{reference 'self.' explicitly}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
// If the implicit self is of value type, no diagnostic should be produced.
struct ImplicitSelfAllowedInStruct {
var x = 42
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ x += 1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
enum ImplicitSelfAllowedInEnum {
case foo
var x: Int { 42 }
mutating func method() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method() })
doVoidStuff({ _ = method() })
}
func method2() -> Int {
doStuff({ x+1 })
doVoidStuff({ _ = x+1 })
doStuff({ method2() })
doVoidStuff({ _ = method2() })
}
}
class SomeClass {
var field : SomeClass?
var `class` : SomeClass?
var `in`: Int = 0
func foo() -> Int {}
}
func testCaptureBehavior(_ ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{invalid redeclaration of 'v1'}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() }
// expected-error@-1{{fields may only be captured by assigning to a specific name}}{{21-21=field = }}
// expected-error@-2{{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}}
// expected-note@-3{{reference 'self.' explicitly}} {{36-36=self.}}
// expected-note@-4{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
doStuff { [self.field] in field!.foo() }
// expected-error@-1{{fields may only be captured by assigning to a specific name}}{{16-16=field = }}
// expected-error@-2{{reference to property 'field' in closure requires explicit use of 'self' to make capture semantics explicit}}
// expected-note@-3{{reference 'self.' explicitly}} {{31-31=self.}}
// expected-note@-4{{capture 'self' explicitly to enable implicit 'self' in this closure}} {{16-16=self, }}
doStuff { [self.field!.foo()] in 32 }
//expected-error@-1{{fields may only be captured by assigning to a specific name}}
doStuff { [self.class] in self.class!.foo() }
//expected-error@-1{{fields may only be captured by assigning to a specific name}}{{16-16=`class` = }}
doStuff { [self.`in`] in `in` }
//expected-note@-1{{capture 'self' explicitly to enable implicit 'self' in this closure}}
//expected-error@-2{{fields may only be captured by assigning to a specific name}}{{16-16=`in` = }}
//expected-error@-3{{reference to property 'in' in closure requires explicit use of 'self' to make capture semantics explicit}}
//expected-note@-4{{reference 'self.' explicitly}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 { // expected-warning {{variable 'a' was never used; consider replacing with '_' or removing it}}
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{top-level statement cannot begin with a closure expression}}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> (Int) -> Int {
return { x in
class A {
let d : Int = 0
}
return 0
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(_ f: () -> ()) {}
var i: Int = 1
// expected-warning @+1 {{expression of type 'Int' is unused}}
takesVoidFunc({i})
// expected-warning @+1 {{expression of type 'Int' is unused}}
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = {
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(_ fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(_ fp : ((Int) -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(_ count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(_ a: () -> T) {}
func genericTwo<T>(_ a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{cannot find type 'Undeclared' in scope}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0
var height = 0
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{cannot find type 'asdf' in scope}}
[UInt8](repeating: 0, count: width*height)
}
}
// <rdar://problem/25993258>
// Don't crash if we infer a closure argument to have a tuple type containing inouts.
func r25993258_helper(_ fn: (inout Int, Int) -> ()) {}
func r25993258a() {
r25993258_helper { x in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
func r25993258b() {
r25993258_helper { _ in () } // expected-error {{contextual closure type '(inout Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}}
}
// We have to map the captured var type into the right generic environment.
class GenericClass<T> {}
func lvalueCapture<T>(c: GenericClass<T>) {
var cc = c
weak var wc = c
func innerGeneric<U>(_: U) {
_ = cc
_ = wc
cc = wc!
}
}
// Don't expose @lvalue-ness in diagnostics.
let closure = {
var helper = true // expected-warning {{variable 'helper' was never mutated; consider changing to 'let' constant}}
return helper
}
// https://github.com/apple/swift/issues/52253
do {
func f(_: @escaping @convention(block) () -> Void) {}
func id<T>(_: T) -> T {}
let qux: () -> Void
f(qux)
f(id(qux)) // expected-error {{conflicting arguments to generic parameter 'T' ('() -> Void' vs. '@convention(block) () -> Void')}}
func forceUnwrap<T>(_: T?) -> T {}
let qux1: (() -> Void)?
f(qux1!)
f(forceUnwrap(qux1))
}
// rdar://problem/65155671 - crash referencing parameter of outer closure
func rdar65155671(x: Int) {
{ a in
_ = { [a] in a }
}(x)
}
// https://github.com/apple/swift/issues/45774
do {
func f<T, U>(_: (@escaping (@escaping (T) -> U) -> ((T) -> U))) -> ((T) -> U) {}
class C {
init() {
// expected-warning@+1{{capture 'self' was never used}}
let _ = f { fn in { [unowned self, fn] x in x != 1000 ? fn(x + 1) : "success" } }(0)
}
}
}
// https://github.com/apple/swift/issues/56501
// Apply the explicit 'self' rule even if it refers to a capture, if
// we're inside a nested closure.
class C_56501 {
func operation() {}
func test1() {
doVoidStuff { [self] in
operation()
}
}
func test2() {
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
func test3() {
doVoidStuff { [self] in
doVoidStuff { [self] in
operation()
}
}
}
func test4() {
doVoidStuff { [self] in
doVoidStuff {
self.operation()
}
}
}
func test5() {
doVoidStuff { [self] in
doVoidStuffNonEscaping {
operation()
}
}
}
func test6() {
doVoidStuff { [self] in
doVoidStuff { [self] in
doVoidStuff {
// expected-warning@+3 {{call to method 'operation' in closure requires explicit use of 'self'}}
// expected-note@-2 {{capture 'self' explicitly to enable implicit 'self' in this closure}}
// expected-note@+1 {{reference 'self.' explicitly}}
operation()
}
}
}
}
}
// https://github.com/apple/swift/issues/57029
do {
func call<T>(_ : Int, _ f: () -> (T, Int)) -> (T, Int) {}
func f() -> (Int, Int) {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
((), 0)
}
}
func f_Optional() -> (Int, Int)? {
call(1) { // expected-error {{cannot convert return expression of type '((), Int)' to return type '(Int, Int)'}}
((), 0)
}
}
}
// https://github.com/apple/swift/issues/55680
func callit<T>(_ f: () -> T) -> T {
f()
}
func callitArgs<T>(_ : Int, _ f: () -> T) -> T {
f()
}
func callitArgsFn<T>(_ : Int, _ f: () -> () -> T) -> T {
f()()
}
func callitGenericArg<T>(_ a: T, _ f: () -> T) -> T {
f()
}
func callitTuple<T>(_ : Int, _ f: () -> (T, Int)) -> T {
f().0
}
func callitVariadic<T>(_ fs: () -> T...) -> T {
fs.first!()
}
func test_55680_Tuple() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitTuple(1) { // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
(print("hello"), 0)
}
}
func test_55680() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callit { // expected-note@:10{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func test_55680_Args() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgs(1) { // expected-note@:17{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
}
}
func test_55680_ArgsFn() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitArgsFn(1) { // expected-note@:19{{generic parameter 'T' inferred as '()' from closure return expression}}
{ print("hello") }
}
}
func test_55680_MultiExpr() -> Int {
callit {
print("hello")
return print("hello") // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
}
}
func test_55680_GenericArg() -> Int {
// Generic argument is inferred as Int from first argument literal, so no conflict in this case.
callitGenericArg(1) {
print("hello") // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
}
}
func test_55680_Variadic() -> Int {
// expected-error@+2{{conflicting arguments to generic parameter 'T' ('()' vs. 'Int')}}
// expected-note@+1:3{{generic parameter 'T' inferred as 'Int' from context}}
callitVariadic({ // expected-note@:18{{generic parameter 'T' inferred as '()' from closure return expression}}
print("hello")
})
}
func test_55680_Variadic_Twos() -> Int {
// expected-error@+1{{cannot convert return expression of type '()' to return type 'Int'}}
callitVariadic({
print("hello")
}, {
print("hello")
})
}
// rdar://82545600: this should just be a warning until Swift 6
public class TestImplicitCaptureOfExplicitCaptureOfSelfInEscapingClosure {
var property = false
private init() {
doVoidStuff { [unowned self] in
doVoidStuff {}
doVoidStuff { // expected-note {{capture 'self' explicitly to enable implicit 'self' in this closure}}
doVoidStuff {}
property = false // expected-warning {{reference to property 'property' in closure requires explicit use of 'self' to make capture semantics explicit}} expected-note {{reference 'self.' explicitly}}
}
}
}
}
// https://github.com/apple/swift/issues/59716
["foo"].map { s in
if s == "1" { return } // expected-error{{cannot convert value of type '()' to closure result type 'Bool'}}
return s.isEmpty
}.filter { $0 }
["foo"].map { s in
if s == "1" { return } // expected-error{{cannot convert value of type '()' to closure result type 'Bool'}}
if s == "2" { return }
if s == "3" { return }
return s.isEmpty
}.filter { $0 }
["foo"].map { s in
if s == "1" { return () } // expected-error{{cannot convert value of type '()' to closure result type 'Bool'}}
return s.isEmpty
}.filter { $0 }
func producer<T>(_ f: (String) -> T) -> T {}
func f59716() -> some BinaryInteger { // expected-note{{required by opaque return type of global function 'f59716()'}}
// expected-note@+1{{only concrete types such as structs, enums and classes can conform to protocols}}
return producer { s in // expected-error{{type '()' cannot conform to 'BinaryInteger'}}
if s == "1" { return }
return s.count // expected-error{{cannot convert value of type 'Int' to closure result type '()'}}
}
}
func f59716_1() -> some BinaryInteger {
return producer { s in
if s == "1" { return 1 }
return s.count
}
}
// https://github.com/apple/swift/issues/60781
func f60781<T>(_ x: T) -> T { x }
func f60781<T>(_ x: T, _ y: T) -> T { x }
func test60781() -> Int {
f60781({ 1 }) // expected-error{{conflicting arguments to generic parameter 'T' ('Int' vs. '() -> Int')}}
}
func test60781_MultiArg() -> Int {
f60781({ 1 }, { 1 }) // expected-error{{conflicting arguments to generic parameter 'T' ('Int' vs. '() -> Int')}}
}
| apache-2.0 | a4f3769d5352e20fc6ecc3b1c94f886a | 47.411538 | 382 | 0.647997 | 3.69952 | false | false | false | false |
malaonline/iOS | mala-ios/View/LiveCourseDetail/LiveCourseDetailTableView.swift | 1 | 4052 | //
// LiveCourseDetailTableView.swift
// mala-ios
//
// Created by 王新宇 on 16/10/20.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
class LiveCourseDetailTableView: UITableView, UITableViewDelegate, UITableViewDataSource {
let LiveCourseDetailCellReuseId = [
0: "LiveCourseDetailClassCellReuseId", // 班级名称
1: "LiveCourseDetailServiceCellReuseId", // 课程服务
2: "LiveCourseDetailDescCellReuseId", // 课程介绍
3: "LiveCourseDetailLecturerCellReuseId", // 直播名师
4: "LiveCourseAssistantCellReuseId", // 助教
]
let LiveCourseDetailCellTitle = [
1: "班级名称",
2: "课程服务",
3: "课程介绍",
4: "直播名师",
5: "联系助教",
]
// MARK: - Property
/// 教师详情模型
var model: LiveClassModel? {
didSet {
self.reloadData()
}
}
// MARK: - Instance Method
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
configration()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func configration() {
delegate = self
dataSource = self
backgroundColor = UIColor(named: .themeLightBlue)
estimatedRowHeight = 400
separatorStyle = .none
register(LiveCourseDetailClassCell.self, forCellReuseIdentifier: LiveCourseDetailCellReuseId[0]!)
register(LiveCourseDetailServiceCell.self, forCellReuseIdentifier: LiveCourseDetailCellReuseId[1]!)
register(LiveCourseDetailDescCell.self, forCellReuseIdentifier: LiveCourseDetailCellReuseId[2]!)
register(LiveCourseDetailLecturerCell.self, forCellReuseIdentifier: LiveCourseDetailCellReuseId[3]!)
register(LiveCourseDetailAssistantCell.self, forCellReuseIdentifier: LiveCourseDetailCellReuseId[4]!)
}
// MARK: - Delegate
func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return section == 0 ? 12 : 6
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 6
}
// MARK: - DataSource
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return LiveCourseDetailCellReuseId.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseCell = tableView.dequeueReusableCell(withIdentifier: LiveCourseDetailCellReuseId[indexPath.section]!, for: indexPath)
(reuseCell as! MalaBaseLiveCourseCell).title = LiveCourseDetailCellTitle[indexPath.section+1]
switch indexPath.section {
case 0:
let cell = reuseCell as! LiveCourseDetailClassCell
cell.model = model
return cell
case 1:
let cell = reuseCell as! LiveCourseDetailServiceCell
return cell
case 2:
let cell = reuseCell as! LiveCourseDetailDescCell
cell.model = model
return cell
case 3:
let cell = reuseCell as! LiveCourseDetailLecturerCell
cell.model = model
return cell
case 4:
let cell = reuseCell as! LiveCourseDetailAssistantCell
cell.model = model
return cell
default:
break
}
return reuseCell
}
deinit {
println("LiveCourseDetail TableView deinit")
}
}
| mit | d8c3d673e7ac9cb51f5eb45d20cd2d30 | 30.388889 | 134 | 0.615929 | 4.974843 | false | false | false | false |
CharlinFeng/Reflect | Reflect/JsonConvert.swift | 1 | 823 | //
// JsonConvert.swift
// Reflect
//
// Created by Charlin on 16/6/6.
// Copyright © 2016年 冯成林. All rights reserved.
//
import Foundation
let jsonStr = "{\"name\":null,\"age\":32}"
class CoachModel: Reflect {
var name: String?
var age: NSNumber?
static func parse(){
let d = jsonStr.data(using: String.Encoding.utf8)
do{
// id obj=[NSJSONSerialization JSONObjectWithData:correctStringData options:NSJSONReadingAllowFragments error:&error];
let dict = try? JSONSerialization.jsonObject(with: d!, options: JSONSerialization.ReadingOptions.allowFragments)
let m = CoachModel.parse(dict: dict as! NSDictionary)
} catch {
}
}
}
| mit | 9db812ec90e40019e43081c9bb1af5f3 | 21 | 129 | 0.571253 | 4.59887 | false | false | false | false |
malaonline/iOS | mala-ios/Controller/Course/CourseTableViewController.swift | 1 | 11671 | //
// CourseTableViewController.swift
// mala-ios
//
// Created by 王新宇 on 16/6/14.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
import DZNEmptyDataSet
private let CourseTableViewSectionHeaderViewReuseId = "CourseTableViewSectionHeaderViewReuseId"
private let CourseTableViewCellReuseId = "CourseTableViewCellReuseId"
public class CourseTableViewController: StatefulViewController, UITableViewDataSource, UITableViewDelegate {
static let shared = CourseTableViewController()
// MARK: - Property
/// 上课时间表数据模型
var model: [[[StudentCourseModel]]]? {
didSet {
DispatchQueue.main.async {
if self.model?.count == 0 {
self.goTopButton.isHidden = true
}else if self.model?.count != oldValue?.count {
self.goTopButton.isHidden = false
self.tableView.reloadData()
self.scrollToToday()
}
}
}
}
/// 距当前时间最近的一节未上课程下标
var recentlyCourseIndexPath: IndexPath?
/// 当前显示年月(用于TitleView显示)
var currentDate: TimeInterval? {
didSet {
if currentDate != oldValue {
titleLabel.text = getDateTimeString(currentDate ?? 0, format: "yyyy年M月")
titleLabel.sizeToFit()
}
}
}
private lazy var featureView: MAFeatureView = {
let view = MAFeatureView()
view.button.addTarget(self, action: #selector(CourseTableViewController.featureViewButtonDidTap), for: .touchUpInside)
return view
}()
override var currentState: StatefulViewState {
didSet {
if currentState != oldValue {
self.tableView.reloadEmptyDataSet()
}
}
}
// MARK: - Components
/// "跳转最近的未上课程"按钮
private lazy var goTopButton: UIButton = {
let button = UIButton()
button.setBackgroundImage(UIImage(asset: .goTop), for: UIControlState())
button.addTarget(self, action: #selector(CourseTableViewController.scrollToToday), for: .touchUpInside)
button.isHidden = true
return button
}()
lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .grouped)
return tableView
}()
/// 保存按钮
private lazy var saveButton: UIButton = {
let saveButton = UIButton(
title: L10n.today,
titleColor: UIColor(named: .ThemeBlue),
target: self,
action: #selector(CourseTableViewController.scrollToToday)
)
saveButton.setTitleColor(UIColor(named: .Disabled), for: .disabled)
return saveButton
}()
/// 导航栏TitleView
private lazy var titleLabel: UILabel = {
let label = UILabel(
text: L10n.schedule,
textColor: UIColor.white
)
label.font = FontFamily.PingFangSC.Regular.font(16)
return label
}()
// MARK: - Life Cycle
override open func viewDidLoad() {
super.viewDidLoad()
configure()
setupUserInterface()
}
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadStudentCourseTable()
if MalaUserDefaults.isLogined && model?.count > 0 {
featureView.state = .sign
}else {
goTopButton.isHidden = true
featureView.state = .login
}
}
override open func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
sendScreenTrack(SAMyCourseViewName)
}
// MARK: - Private Method
private func configure() {
// tableView
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.backgroundColor = UIColor.white
// dataSet
tableView.emptyDataSetSource = self
tableView.emptyDataSetDelegate = self
// register
tableView.register(CourseTableViewCell.self, forCellReuseIdentifier: CourseTableViewCellReuseId)
tableView.register(CourseTableViewSectionHeader.self, forHeaderFooterViewReuseIdentifier: CourseTableViewSectionHeaderViewReuseId)
}
private func setupUserInterface() {
// Style
navigationItem.titleView = UIView()
navigationItem.titleView?.addSubview(titleLabel)
view.backgroundColor = UIColor.white
// SubViews
switchToSchedule()
view.addSubview(goTopButton)
// AutoLayout
goTopButton.snp.makeConstraints { (maker) -> Void in
maker.right.equalTo(view).offset(-20)
maker.bottom.equalTo(view).offset(-64)
maker.width.equalTo(58)
maker.height.equalTo(58)
}
if let titleView = navigationItem.titleView {
titleLabel.snp.makeConstraints { (maker) -> Void in
maker.center.equalTo(titleView)
}
}
}
private func switchToSchedule() {
guard tableView.superview == nil else { return }
if let _ = featureView.superview { featureView.removeFromSuperview() }
view.insertSubview(tableView, belowSubview: goTopButton)
tableView.snp.makeConstraints { (maker) -> Void in
maker.center.equalTo(view)
maker.size.equalTo(view)
}
}
private func switchToFeature() {
guard featureView.superview == nil else { return }
if let _ = tableView.superview { tableView.removeFromSuperview() }
view.insertSubview(featureView, belowSubview: goTopButton)
featureView.snp.makeConstraints { (maker) -> Void in
maker.center.equalTo(view)
maker.size.equalTo(view)
}
}
/// 获取学生可用时间表
fileprivate func loadStudentCourseTable() {
// 用户登录后请求数据,否则显示默认页面
if !MalaUserDefaults.isLogined {
switchToFeature()
return
}
guard currentState != .loading else { return }
model = nil
recentlyCourseIndexPath = nil
currentState = .loading
/// 获取学生课程信息
MAProvider.getStudentSchedule(failureHandler: { error in
println(error)
self.currentState = .error
}) { schedule in
self.currentState = .content
guard !schedule.isEmpty else {
self.switchToFeature()
return
}
// 解析学生上课时间表
self.switchToSchedule()
let result = parseStudentCourseTable(schedule)
self.recentlyCourseIndexPath = result.recently
self.model = result.model
}
}
// MARK: - DataSource
public func numberOfSections(in tableView: UITableView) -> Int {
return model?.count ?? 0
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return model?[section].count ?? 0
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: CourseTableViewCellReuseId, for: indexPath) as! CourseTableViewCell
cell.model = model?[indexPath.section][indexPath.row]
return cell
}
// MARK: - Delegate
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: CourseTableViewSectionHeaderViewReuseId) as! CourseTableViewSectionHeader
headerView.timeInterval = model?[section][0][0].end
return headerView
}
public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 实时调整当前第一个显示的Cell日期为导航栏标题日期
if let date = (tableView.visibleCells.first as? CourseTableViewCell)?.model?[0].end {
currentDate = date
}else {
currentDate = Date().timeIntervalSince1970
}
// 当最近一节课程划出屏幕时,显示“回到最近课程”按钮
if indexPath == recentlyCourseIndexPath {
goTopButton.isHidden = true
}
}
public func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// 当最近一节课程划出屏幕时,显示“回到最近课程”按钮
if indexPath == recentlyCourseIndexPath {
goTopButton.isHidden = false
}
}
public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 140
}
public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return 20
}
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let height = Int(MalaConfig.singleCourseCellHeight()+1)
return CGFloat((model?[indexPath.section][indexPath.row].count ?? 0) * height)
}
public func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
return false
}
// MARK: - Event Response
/// 滚动到近日首个未上课程
@objc private func scrollToToday() {
guard let recent = self.recentlyCourseIndexPath else { return }
DispatchQueue.main.async {
self.tableView.scrollToRow(at: recent, at: .top, animated: true)
}
}
/// 特性视图按钮点击事件
@objc private func featureViewButtonDidTap() {
if MalaUserDefaults.isLogined {
switchToFindTeacher()
}else {
switchToLoginView()
}
}
/// 跳转到挑选老师页面
@objc fileprivate func switchToFindTeacher() {
MainViewController.shared.selectedIndex = 0
}
/// 跳转到登陆页面
@objc fileprivate func switchToLoginView() {
let loginView = LoginViewController()
loginView.popAction = loadStudentCourseTable
self.present(
UINavigationController(rootViewController: loginView),
animated: true,
completion: { () -> Void in
// 用户登录后请求数据,否则显示默认页面
if MalaUserDefaults.isLogined {
self.switchToSchedule()
}
})
}
}
extension CourseTableViewController {
public func emptyDataSet(_ scrollView: UIScrollView!, didTap button: UIButton!) {
switch currentState {
case .notLoggedIn: switchToLoginView()
case .empty: switchToFindTeacher()
case .error: loadStudentCourseTable()
default: break
}
}
public func emptyDataSet(_ scrollView: UIScrollView!, didTap view: UIView!) {
switch currentState {
case .notLoggedIn: switchToLoginView()
case .empty: switchToFindTeacher()
case .error: loadStudentCourseTable()
default: break
}
}
}
| mit | 9d86a7d14e035cdcd0d4e1f2d37a4fc5 | 32.651652 | 156 | 0.610833 | 5.156926 | false | false | false | false |
nakau1/NerobluCore | NerobluCore/NBReflection.swift | 1 | 2611 | // =============================================================================
// NerobluCore
// Copyright (C) NeroBlu. All rights reserved.
// =============================================================================
import UIKit
// MARK: - NBReflection -
/// クラスについての処理を行うクラス
public class NBReflection {
private let target: Any?
/// イニシャライザ
/// - parameter target: 対象
public init(_ target: Any?) {
self.target = target
}
/// パッケージ名を含めないクラス名を返却する
public var shortClassName: String {
return self.className(false)
}
/// パッケージ名を含めたクラス名を返却する
public var fullClassName: String {
return self.className(true)
}
/// パッケージ名を返却する
public var packageName: String? {
let full = self.fullClassName
let short = self.shortClassName
if full == short {
return nil
}
guard let range = full.rangeOfString(".\(short)") else {
return nil
}
return full.substringToIndex(range.startIndex)
}
private func className(full: Bool) -> String {
if let target = self.target {
if let cls = target as? AnyClass {
return self.classNameByClass(cls, full)
} else if let obj = target as? AnyObject {
return self.classNameByClass(obj.dynamicType, full)
} else {
return self.classNameByClass(nil, full)
}
}
else {
return "nil"
}
}
private func classNameByClass(cls: AnyClass?, _ full: Bool) -> String {
let unknown = "unknown"
guard let cls = cls else {
return unknown
}
let fullName = NSStringFromClass(cls)
if full { return fullName }
guard let name = fullName.componentsSeparatedByString(".").last else {
return unknown
}
return name
}
}
// MARK: - NSObject拡張 -
public extension NSObject {
/// パッケージ名を含めないクラス名を返却する
public var shortClassName: String { return NBReflection(self).shortClassName }
/// パッケージ名を含めたクラス名を返却する
public var fullClassName: String { return NBReflection(self).fullClassName }
/// パッケージ名を返却する
public var packageName: String? { return NBReflection(self).packageName }
}
| apache-2.0 | f1a7a0bbce8be0e0c393a55150fcd684 | 26.406977 | 82 | 0.537123 | 4.285455 | false | false | false | false |
imzyf/99-projects-of-swift | 017-self-sizing-table-view-cells/017-self-sizing-table-view-cells/views/ArtistTableViewCell.swift | 1 | 757 | //
// ArtistTableViewCell.swift
// 017-self-sizing-table-view-cells
//
// Created by moma on 2017/11/10.
// Copyright © 2017年 yifans. All rights reserved.
//
import UIKit
class ArtistTableViewCell: UITableViewCell {
@IBOutlet weak var bioLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var artistImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
self.nameLabel.textColor = UIColor.white
self.nameLabel.backgroundColor = UIColor(red: 1, green: 152 / 255, blue: 0, alpha: 1)
self.nameLabel.layer.cornerRadius = 3
self.nameLabel.clipsToBounds = true
self.bioLabel.textColor = UIColor(white: 114/255, alpha: 1)
}
}
| mit | 9c477cf9b1827c8bf38863f516449046 | 28 | 93 | 0.669761 | 4.032086 | false | false | false | false |
graphcool-examples/react-apollo-auth0-example | quickstart-with-apollo/Instagram/Carthage/Checkouts/apollo-ios/Sources/ApolloStore.swift | 1 | 2757 | func rootKey<Operation: GraphQLOperation>(forOperation operation: Operation) -> CacheKey {
switch operation {
case is GraphQLQuery:
return "QUERY_ROOT"
case is GraphQLMutation:
return "MUTATION_ROOT"
default:
preconditionFailure("Unknown operation type")
}
}
protocol ApolloStoreSubscriber: class {
func store(_ store: ApolloStore, didChangeKeys changedKeys: Set<CacheKey>, context: UnsafeMutableRawPointer?)
}
/// The `ApolloStore` class acts as a local cache for normalized GraphQL results.
public final class ApolloStore {
private let queue: DispatchQueue
private var records: RecordSet
private var subscribers: [ApolloStoreSubscriber] = []
init(records: RecordSet = RecordSet()) {
self.records = records
queue = DispatchQueue(label: "com.apollographql.ApolloStore", attributes: .concurrent)
}
func publish(records: RecordSet, context: UnsafeMutableRawPointer?) {
queue.async(flags: .barrier) {
let changedKeys = self.records.merge(records: records)
for subscriber in self.subscribers {
subscriber.store(self, didChangeKeys: changedKeys, context: context)
}
}
}
func subscribe(_ subscriber: ApolloStoreSubscriber) {
queue.async(flags: .barrier) {
self.subscribers.append(subscriber)
}
}
func unsubscribe(_ subscriber: ApolloStoreSubscriber) {
queue.async(flags: .barrier) {
self.subscribers = self.subscribers.filter({ $0 !== subscriber })
}
}
func load<Query: GraphQLQuery>(query: Query, cacheKeyForObject: CacheKeyForObject?, resultHandler: @escaping OperationResultHandler<Query>) {
queue.async {
do {
let rootKey = Apollo.rootKey(forOperation: query)
let rootObject = self.records[rootKey]?.fields
let reader = GraphQLResultReader(variables: query.variables) { field, object, info in
let value = (object ?? rootObject)?[field.cacheKey]
return self.complete(value: value)
}
let normalizer = GraphQLResultNormalizer(rootKey: rootKey)
normalizer.cacheKeyForObject = cacheKeyForObject
reader.delegate = normalizer
let data = try Query.Data(reader: reader)
let dependentKeys = normalizer.dependentKeys
resultHandler(GraphQLResult(data: data, errors: nil, dependentKeys: dependentKeys), nil)
} catch {
resultHandler(nil, error)
}
}
}
private func complete(value: JSONValue?) -> JSONValue? {
if let reference = value as? Reference {
return self.records[reference.key]?.fields
} else if let array = value as? Array<JSONValue> {
return array.map(complete)
} else {
return value
}
}
}
| mit | 1cf6a03efcc05b3cb89559ad286f6d15 | 31.435294 | 143 | 0.674646 | 4.625839 | false | false | false | false |
Adlai-Holler/Atomic | Atomic/Lock.swift | 1 | 1137 | //
// Lock.swift
// Atomic
//
// Created by Adlai Holler on 1/31/16.
// Copyright © 2016 Adlai Holler. All rights reserved.
//
import Darwin
final public class Lock {
internal var _lock = pthread_mutex_t()
/// Initializes the variable with the given initial value.
public init() {
let result = pthread_mutex_init(&_lock, nil)
assert(result == 0, "Failed to init mutex in \(self)")
}
public func lock() {
let result = pthread_mutex_lock(&_lock)
assert(result == 0, "Failed to lock mutex in \(self)")
}
public func tryLock() -> Int32 {
return pthread_mutex_trylock(&_lock)
}
public func unlock() {
let result = pthread_mutex_unlock(&_lock)
assert(result == 0, "Failed to unlock mutex in \(self)")
}
deinit {
let result = pthread_mutex_destroy(&_lock)
assert(result == 0, "Failed to destroy mutex in \(self)")
}
}
extension Lock {
public func withCriticalScope<Result>(@noescape body: () throws -> Result) rethrows -> Result {
lock()
defer { unlock() }
return try body()
}
} | mit | 53ad348e11fb81de6118fc4d847d133e | 23.191489 | 99 | 0.590669 | 3.958188 | false | false | false | false |
904388172/-TV | DouYuTV/DouYuTV/Classes/Tools/Externsion/UIBarButton-Externsion.swift | 1 | 1544 | //
// UIBarButton-Externsion.swift
// DouYuTV
//
// Created by GS on 2017/10/19.
// Copyright © 2017年 Demo. All rights reserved.
//
import UIKit
//扩展
extension UIBarButtonItem {
/*
//扩展类方法
class func createItem(imageName: String, highImageName: String, size: CGSize) -> UIBarButtonItem {
let btn = UIButton(type: UIButtonType.custom)
btn.setImage(UIImage(named: imageName), for: UIControlState.normal)
btn.setImage(UIImage(named: highImageName), for: UIControlState.highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size: size)
return UIBarButtonItem(customView: btn)
}
*/
//一般扩展都是扩展成构造函数,很少扩展成类方法
//便利构造函数:1> convenience开头 2> 在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName: String, highImageName: String = "", size: CGSize = CGSize.zero) {
//创建UIButton
let btn = UIButton(type: UIButtonType.custom)
//设置button的图片
btn.setImage(UIImage(named: imageName), for: UIControlState.normal)
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: UIControlState.highlighted)
}
//设置button的尺寸
if size == CGSize.zero {
btn.sizeToFit()
} else {
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
//创建uibarbuttonItem
self.init(customView: btn)
}
}
| mit | c6fe21a5560c1dc5b9179fa17c0801f3 | 30 | 103 | 0.633692 | 4.090909 | false | false | false | false |
siddug/headout-video-discovery | headout/headout/Utilities/Constants.swift | 1 | 983 | //
// Constants.swift
// headout
//
// Created by varun jindal on 18/02/17.
// Copyright © 2017 headout. All rights reserved.
//
import Foundation
import UIKit
struct VideoConstants {
static let bufferSize = 5.0
}
struct LabelConstants {
static let characterSpacing: CGFloat = 7
static let paraSpacing: CGFloat = 15
}
struct UIConstants {
static let centerDiffForReplayButtons: CGFloat = 30
static let topSpaceForWishButton: CGFloat = 30
static let rightSpaceForWishButton: CGFloat = 21
static let leftSpaceForHamburger = UIConstants.rightSpaceForWishButton
static let wishListMovementInterval = 0.2
static let offsetForTopConstraint: CGFloat = 20
}
struct SideBarConstants {
static let imageArray = [Images.skip, Images.wishlist]
static let colorArray = [Color.sideBarBg, Color.sideBarBg]
static let animationDuration: CGFloat = 0.2
static let width: CGFloat = 180
static let itemBackgroundColor = Color.sideBarBg
}
| mit | 020447988cf3e58a0591084148f5d4ae | 26.277778 | 74 | 0.742363 | 4.074689 | false | false | false | false |
pigigaldi/Pock | Pock/UI/DebugConsole/Controllers/DebugConsoleViewController/DebugConsoleViewController.swift | 1 | 5105 | //
// DebugConsoleViewController.swift
// Pock
//
// Created by Pierluigi Galdi on 26/06/21.
//
import Cocoa
class DebugConsoleViewController: NSViewController {
// MARK: Core
private lazy var lock = NSRecursiveLock()
// MARK: UI Elements
@IBOutlet private weak var textView: NSTextViewWithShortcuts!
@IBOutlet private weak var floatingWindowButton: NSButton!
@IBOutlet private weak var showOnLaunchCheckbox: NSButton!
@IBOutlet private weak var filterTextField: NSFilterTextField!
@IBOutlet private weak var autoScrollButton: NSButton!
@IBOutlet private weak var clearButton: NSButton!
// MARK: Data
private lazy var filterQuery: String = "" {
didSet {
updateTextViewWithData("")
}
}
private var logsData: [String] = []
// MARK: Variables
private var isFloatingWindow: Bool {
get {
return view.window?.level == .mainMenu
}
set {
view.window?.level = newValue ? .mainMenu : .normal
floatingWindowButton.contentTintColor = newValue ? .controlAccentColor : .white
}
}
private var isAutoScrollEnabled: Bool = true {
didSet {
if isAutoScrollEnabled {
textView.scrollToEndOfDocument(self)
}
autoScrollButton.contentTintColor = isAutoScrollEnabled ? .controlAccentColor : .white
}
}
// MARK: Overrides
override var title: String? {
get {
return "Pock • Debug Console"
}
set {
view.window?.title = newValue ?? ""
}
}
deinit {
Roger.debug("** deinit **")
}
override func viewDidLoad() {
super.viewDidLoad()
startListeningForConsoleEvents()
}
override func viewWillAppear() {
super.viewWillAppear()
configureUIElements()
}
private func configureUIElements() {
view.wantsLayer = true
view.layer?.backgroundColor = NSColor(red: 41/255, green: 42/255, blue: 47/255, alpha: 1).cgColor
// TextView
textView.textContainerInset.height = 4
textView.isEditable = false
textView.backgroundColor = .clear
textView.font = NSFont(name: "Menlo", size: 12)
textView.textColor = .white
// Action buttons
showOnLaunchCheckbox.state = Preferences[.showDebugConsoleOnLaunch] ? .on : .off
floatingWindowButton.contentTintColor = isFloatingWindow ? .controlAccentColor : .white
autoScrollButton.contentTintColor = isAutoScrollEnabled ? .systemBlue : .white
// Tooltips
floatingWindowButton.toolTip = "debug.console.floating-window".localized
autoScrollButton.toolTip = "debug.console.scroll-automatically".localized
clearButton.toolTip = "debug.console.clear-console".localized
}
private func updateTextViewWithData(_ data: String) {
lock.lock()
defer {
lock.unlock()
}
// split per line
logsData.append(data)
let shouldScroll = isAutoScrollEnabled && textView.visibleRect.maxY == textView.bounds.maxY
let stringValue: String
if !filterQuery.isEmpty {
let filtered = logsData.filter({ $0.lowercased().contains(filterQuery.lowercased()) })
filterTextField.setNumberOfOccurrencies(filtered.count)
stringValue = filtered.joined()
} else {
filterTextField.setNumberOfOccurrencies(0)
stringValue = logsData.joined()
}
textView.string = stringValue
if shouldScroll {
textView.scrollToEndOfDocument(self)
}
}
private func startListeningForConsoleEvents() {
Roger.listenForSTDOUTEvents { [weak self] incomingLogs in
self?.updateTextViewWithData(incomingLogs)
}
Roger.listenForSTDERREvents { [weak self] incomingLogs in
self?.updateTextViewWithData(incomingLogs)
}
}
// MARK: IB Actions
@IBAction private func didSelectAction(_ sender: Any?) {
guard let control = sender as? NSControl else {
return
}
switch control {
case floatingWindowButton:
isFloatingWindow = !isFloatingWindow
case showOnLaunchCheckbox:
Preferences[.showDebugConsoleOnLaunch] = showOnLaunchCheckbox.state == .on
case filterTextField.textField:
filterQuery = filterTextField.textField.stringValue
case filterTextField.clearButton:
filterTextField.textField.stringValue = ""
filterQuery = ""
view.window?.makeFirstResponder(nil)
case autoScrollButton:
isAutoScrollEnabled = !isAutoScrollEnabled
case clearButton:
logsData.removeAll()
updateTextViewWithData("")
default:
return
}
}
}
| mit | ee4721dc60904511ab400d90be469972 | 29.740964 | 105 | 0.605722 | 5.25 | false | false | false | false |
CoolCodeFactory/Antidote | AntidoteArchitectureExample/UserContainerViewController.swift | 1 | 2203 | //
// UserContainerViewController.swift
// AntidoteArchitectureExample
//
// Created by Dima on 20/09/16.
// Copyright © 2016 Dmitry Utmanov. All rights reserved.
//
import UIKit
class UserContainerViewController: UIViewController {
@IBOutlet weak var usersContainerView: UIView!
@IBOutlet weak var userContainerView: UIView!
var usersViewControllerBuilder: () -> (UsersTableViewControllerProtocol) = {
closureFatalError()
}
var userViewControllerBuilder: (String) -> (UserViewController) = { _ in
closureFatalError()
}
func updateUserViewController(_ name: String) {
if let userViewController = userViewController {
let newUserViewController = userViewControllerBuilder(name)
exchangeContentController(fromContentController: userViewController, toContentController: newUserViewController, inView: userContainerView, animated: true)
self.userViewController = newUserViewController
} else {
userViewController = userViewControllerBuilder(name)
displayContentController(userViewController!, inView: userContainerView, animated: true)
}
}
weak var usersViewControllerProtocol: UsersTableViewControllerProtocol?
weak var userViewController: UserViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
usersViewControllerProtocol = usersViewControllerBuilder()
displayContentController(usersViewControllerProtocol!.viewController()!, inView: usersContainerView, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f923c9332364faace4b79450a5106364 | 33.952381 | 167 | 0.70663 | 5.779528 | false | false | false | false |
HTWDD/htwcampus | HTWDD/Components/Schedule/Models/ScheduleDataSource.swift | 1 | 7777 | //
// ScheduleDataSource.swift
// HTWDD
//
// Created by Benjamin Herzog on 03/03/2017.
// Copyright © 2017 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
protocol ScheduleDataSourceDelegate: class {
func scheduleDataSourceHasFinishedLoading()
func scheduleDataSourceHasUpdated()
}
class ScheduleDataSource: CollectionViewDataSource {
struct Configuration {
let context: HasSchedule
var auth: ScheduleService.Auth?
var shouldFilterEmptySections: Bool
var addFreeDays: Bool
var splitFreeDaysInDays: Bool
init(context: HasSchedule, auth: ScheduleService.Auth?, shouldFilterEmptySections: Bool, addFreeDays: Bool, splitFreeDaysInDays: Bool) {
self.context = context
self.auth = auth
self.shouldFilterEmptySections = shouldFilterEmptySections
self.addFreeDays = addFreeDays
self.splitFreeDaysInDays = splitFreeDaysInDays
}
}
var auth: ScheduleService.Auth? {
didSet {
guard self.auth != nil else {
self.data = []
self.semesterInformation = nil
self.semesterInformations = []
self.lectures = [:]
self.invalidate()
return
}
self.load()
}
}
private(set) var lectures = [Day: [AppLecture]]()
private var semesterInformations = [SemesterInformation]() {
didSet {
self.semesterInformation = SemesterInformation.information(date: Date(), input: self.semesterInformations)
}
}
private(set) var semesterInformation: SemesterInformation?
struct Data {
let day: Day
let date: Date
let lectures: [AppLecture]
let freeDays: [Event]
}
private var data = [Data]() {
didSet {
self.delegate?.scheduleDataSourceHasUpdated()
}
}
private let disposeBag = DisposeBag()
private let service: ScheduleService
private let filterEmptySections: Bool
private let splitFreeDaysInDays: Bool
weak var delegate: ScheduleDataSourceDelegate?
private(set) var indexPathOfToday: IndexPath?
private let loadingCount = Variable(0)
lazy var loading = self.loadingCount
.asObservable()
.map({ $0 > 0 })
.observeOn(MainScheduler.instance)
init(configuration: Configuration) {
self.service = configuration.context.scheduleService
self.auth = configuration.auth
self.filterEmptySections = configuration.shouldFilterEmptySections
self.splitFreeDaysInDays = configuration.splitFreeDaysInDays
}
func load() {
self.loadingCount.value += 1
guard let auth = self.auth else {
Log.info("Can't load schedule if no authentication is provided. Abort…")
self.loadingCount.value -= 1
return
}
self.service.load(parameters: auth)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { [weak self] information in
self?.lectures = information.lectures
self?.semesterInformations = information.semesters
self?.invalidate()
self?.delegate?.scheduleDataSourceHasFinishedLoading()
self?.loadingCount.value -= 1
}, onError: { [weak self] _ in
self?.loadingCount.value -= 1
}).disposed(by: self.disposeBag)
}
override func invalidate() {
self.data = self.calculate()
super.invalidate()
}
func lecture(at indexPath: IndexPath) -> AppLecture? {
return self.data[safe: indexPath.section]?.lectures[safe: indexPath.row]
}
func freeDay(at indexPath: IndexPath) -> Event? {
return self.data[safe: indexPath.section]?.freeDays[safe: indexPath.row]
}
func dayInformation(indexPath: IndexPath) -> (day: Day, date: Date) {
let dataPart = self.data[indexPath.section]
return (dataPart.day, dataPart.date)
}
private func calculate() -> [Data] {
guard let semesterInformation = self.semesterInformation, !self.lectures.isEmpty else {
return []
}
let originDate = semesterInformation.period.begin.date
let sections = 0..<semesterInformation.period.lengthInDays
let originDay = originDate.weekday
let startWeek = originDate.weekNumber
var all: [Data] = sections.map { section in
let date = originDate.byAdding(days: TimeInterval(section))
let day = date.weekday
// Check if date of section exists in semester information
guard semesterInformation.lecturesContains(date: date) else {
// If not, check if date of section is today
if date.sameDayAs(other: Date()) {
// If so, try to create a `Event` "Holiday" object
if let eventDate = EventDate(date: date) {
let freeDays = [Event(name: Loca.Schedule.holiday, period: EventPeriod(begin: eventDate, end: eventDate))]
return Data(day: day, date: date, lectures: [], freeDays: freeDays)
}
}
// Otherwise return an empty `Data` object
return Data(day: day, date: date, lectures: [], freeDays: [])
}
// Check if `date` is marked as a free day
if let freeDay = semesterInformation.freeDayContains(date: date) {
if self.splitFreeDaysInDays {
return Data(day: day, date: date, lectures: [], freeDays: [freeDay])
} else if freeDay.period.begin.date.sameDayAs(other: date) {
return Data(day: day, date: date, lectures: [], freeDays: [freeDay])
} else {
return Data(day: day, date: date, lectures: [], freeDays: [])
}
}
let weekNumber = originDay.weekNumber(starting: startWeek, addingDays: section)
let l = (self.lectures[originDay.dayByAdding(days: section)] ?? []).filter { lecture in
let weekEvenOddValidation = lecture.lecture.week.validate(weekNumber: weekNumber)
let weekOnlyValidation = lecture.lecture.weeks?.contains(weekNumber) ?? true
return weekEvenOddValidation && weekOnlyValidation
}.sorted { l1, l2 in
return l1.lecture.begin < l2.lecture.begin
}
let freeDays: [Event]
if l.isEmpty && date.sameDayAs(other: Date()) {
if let eventDate = EventDate(date: Date()) {
freeDays = [Event(name: Loca.Schedule.freeDay, period: EventPeriod(begin: eventDate, end: eventDate))]
} else {
freeDays = []
}
} else {
freeDays = []
}
return Data(day: day, date: date, lectures: l.filter { !$0.hidden }, freeDays: freeDays)
}
if self.filterEmptySections {
all = all.filter { $0.date.sameDayAs(other: Date()) || !$0.lectures.isEmpty || !$0.freeDays.isEmpty }
}
self.indexPathOfToday = all
.index(where: { $0.date.sameDayAs(other: Date()) })
.map({ IndexPath(item: 0, section: $0) })
return all
}
// MARK: CollectionViewDataSource methods
override func item(at index: IndexPath) -> Identifiable? {
return self.lecture(at: index) ?? self.freeDay(at: index)
}
override func numberOfSections() -> Int {
return self.data.count
}
override func numberOfItems(in section: Int) -> Int {
return self.data[safe: section].map { max($0.lectures.count, $0.freeDays.count) } ?? 0
}
}
| mit | 35f29915b662e1f99fe65cd2b06b3aeb | 34.824885 | 144 | 0.600592 | 4.457569 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.