repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/iOS/CanvasCropView.swift | 1 | 20221 | //
// CanvasCropView.swift
// SwiftGL
//
// Created by jerry on 2015/8/18.
// Copyright © 2015年 Jerry Chan. All rights reserved.
//
import UIKit
let square:Bool = false
let IMAGE_MIN_HEIGHT:CGFloat = 100;
let IMAGE_MIN_WIDTH:CGFloat = 100;
func SquareCGRectAtCenter(_ centerX:CGFloat, centerY:CGFloat, size:CGFloat)->CGRect {
let x = centerX - size / 2.0;
let y = centerY - size / 2.0;
return CGRect(x: x, y: y, width: size, height: size);
}
struct DragPoint {
var dragStart: CGPoint
var topLeftCenter: CGPoint
var bottomLeftCenter: CGPoint
var bottomRightCenter: CGPoint
var topRightCenter: CGPoint
var clearAreaCenter: CGPoint
}
class CanvasCropView: UIView{
var shadeView:ShadeView!
var cropAreaView:UIView!
var controlPointSize:CGFloat = 5
var topLeftPoint:ControlPointView!
var bottomLeftPoint:ControlPointView!
var bottomRightPoint:ControlPointView!
var topRightPoint:ControlPointView!
var pointsArray:[ControlPointView]!
var dragViewOne:UIView!
var dragPoint:DragPoint!
var imageFrameInView:CGRect!
override init(frame: CGRect) {
super.init(frame: frame)
initView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func initView()
{
let centerInView:CGPoint = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
let initialClearAreaSize = self.frame.size.width / 10;
topLeftPoint = ControlPointView(frame: SquareCGRectAtCenter(centerInView.x - initialClearAreaSize, centerY: centerInView.y - initialClearAreaSize, size:controlPointSize))
bottomLeftPoint = ControlPointView(frame: SquareCGRectAtCenter(centerInView.x - initialClearAreaSize, centerY: centerInView.y + initialClearAreaSize, size:controlPointSize))
bottomRightPoint = ControlPointView(frame: SquareCGRectAtCenter(centerInView.x + initialClearAreaSize, centerY: centerInView.y + initialClearAreaSize, size:controlPointSize))
topRightPoint = ControlPointView(frame: SquareCGRectAtCenter(centerInView.x + initialClearAreaSize, centerY: centerInView.y - initialClearAreaSize, size:controlPointSize))
shadeView = ShadeView(frame: self.bounds)
let cropArea = clearAreaFromControlPoints()
cropAreaView = UIView(frame: cropArea)
cropAreaView.backgroundColor = UIColor.clear
self.addSubview(shadeView)
self.addSubview(cropAreaView)
self.addSubview(topRightPoint)
self.addSubview(bottomRightPoint)
self.addSubview(topLeftPoint)
self.addSubview(bottomLeftPoint)
imageFrameInView = CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height)
pointsArray = [topLeftPoint,bottomLeftPoint,bottomRightPoint,topRightPoint]
shadeView.setCropArea(cropArea)
initGesture()
}
func initGesture()
{
let dragRecognizer: UIPanGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(CanvasCropView.handleDrag(_:)))
self.forBaselineLayout().addGestureRecognizer(dragRecognizer)
}
func setCropAreaInView(_ area: CGRect) {
let topLeft: CGPoint = area.origin
let bottomLeft: CGPoint = CGPoint(x: topLeft.x, y: topLeft.y + area.size.height)
let bottomRight: CGPoint = CGPoint(x: bottomLeft.x + area.size.width, y: bottomLeft.y)
let topRight: CGPoint = CGPoint(x: topLeft.x + area.size.width, y: topLeft.y)
topLeftPoint.center = topLeft
bottomLeftPoint.center = bottomLeft
bottomRightPoint.center = bottomRight
topRightPoint.center = topRight
let cropArea: CGRect = clearAreaFromControlPoints()
cropAreaView = UIView(frame: cropArea)
cropAreaView.isOpaque = false
cropAreaView.backgroundColor = UIColor.clear
shadeView.cropArea = area
self.setNeedsDisplay()
}
func clearAreaFromControlPoints() -> CGRect {
let width: CGFloat = topRightPoint.center.x - topLeftPoint.center.x
let height: CGFloat = bottomRightPoint.center.y - topRightPoint.center.y
let hole: CGRect = CGRect(x: topLeftPoint.center.x, y: topLeftPoint.center.y, width: width, height: height)
return hole
}
func controllableAreaFromControlPoints() -> CGRect {
let width: CGFloat = topRightPoint.center.x - topLeftPoint.center.x - controlPointSize
let height: CGFloat = bottomRightPoint.center.y - topRightPoint.center.y - controlPointSize
let hole: CGRect = CGRect(x: topLeftPoint.center.x + controlPointSize / 2, y: topLeftPoint.center.y + controlPointSize / 2, width: width, height: height)
return hole
}
func boundingBoxForTopLeft(_ topLeft: CGPoint, bottomLeft: CGPoint, bottomRight: CGPoint, topRight: CGPoint) {
var box: CGRect = CGRect(x: topLeft.x - controlPointSize / 2, y: topLeft.y - controlPointSize / 2, width: topRight.x - topLeft.x + controlPointSize, height: bottomRight.y - topRight.y + controlPointSize)
if !square {
box = imageFrameInView.intersection(box)
}
if imageFrameInView.contains(box) {
bottomLeftPoint.center = CGPoint(x: box.origin.x + controlPointSize / 2, y: box.origin.y + box.size.height - controlPointSize / 2)
bottomRightPoint.center = CGPoint(x: box.origin.x + box.size.width - controlPointSize / 2, y: box.origin.y + box.size.height - controlPointSize / 2)
topLeftPoint.center = CGPoint(x: box.origin.x + controlPointSize / 2, y: box.origin.y + controlPointSize / 2)
topRightPoint.center = CGPoint(x: box.origin.x + box.size.width - controlPointSize / 2, y: box.origin.y + controlPointSize / 2)
}
}
func checkHit(_ point: CGPoint) -> UIView {
var view: UIView = cropAreaView
for i in 0 ..< pointsArray.count {
let a = pow((point.x - view.center.x), 2)
let b = pow((point.y - view.center.y), 2)
let c = pow((point.x - pointsArray[i].center.x), 2)
let d = pow((point.y - pointsArray[i].center.y), 2)
if sqrt(a + b) > sqrt(c+d) {
view = pointsArray[i]
}
}
return view
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let frame: CGRect = cropAreaView.frame.insetBy(dx: -30, dy: -30)
return frame.contains(point) ? cropAreaView : nil
}
func handleDrag(_ recognizer: UIPanGestureRecognizer) {
switch(recognizer.state)
{
case UIGestureRecognizerState.began:
self.prepSingleTouchPan(recognizer)
return
case UIGestureRecognizerState.changed:
self.beginCropBoxTransformForPoint(recognizer.location(in: self), atView: dragViewOne)
case UIGestureRecognizerState.ended:
return
default:
return
}
}
func prepSingleTouchPan(_ recognizer: UIPanGestureRecognizer) {
dragViewOne = self.checkHit(recognizer.location(in: self))
dragPoint = DragPoint(dragStart: recognizer.location(in: self), topLeftCenter: topLeftPoint.center, bottomLeftCenter: bottomLeftPoint.center, bottomRightCenter: bottomRightPoint.center, topRightCenter: topRightPoint.center, clearAreaCenter: cropAreaView.center)
}
func deriveDisplacementFromDragLocation(_ dragLocation: CGPoint, draggedPoint: CGPoint, oppositePoint: CGPoint) -> CGSize {
let dX: CGFloat = dragLocation.x - dragPoint.dragStart.x
let dY: CGFloat = dragLocation.y - dragPoint.dragStart.y
let tempDraggedPoint: CGPoint = CGPoint(x: draggedPoint.x + dX, y: draggedPoint.y + dY)
let width: CGFloat = (tempDraggedPoint.x - oppositePoint.x)
let height: CGFloat = (tempDraggedPoint.y - oppositePoint.y)
let size: CGFloat = fabs(width) >= fabs(height) ? width : height
let xDir: CGFloat = draggedPoint.x <= oppositePoint.x ? 1 : -1
let yDir: CGFloat = draggedPoint.y <= oppositePoint.y ? 1 : -1
var newX: CGFloat = 0
var newY: CGFloat = 0
if xDir >= 0 {
if square {
newX = oppositePoint.x - fabs(size)
}
else {
newX = oppositePoint.x - fabs(width)
}
}
else {
if square {
newX = oppositePoint.x + fabs(size)
}
else {
newX = oppositePoint.x + fabs(width)
}
}
if yDir >= 0 {
if square {
newY = oppositePoint.y - fabs(size)
}
else {
newY = oppositePoint.y - fabs(height)
}
}
else {
if square {
newY = oppositePoint.y + fabs(size)
}
else {
newY = oppositePoint.y + fabs(height)
}
}
let displacement: CGSize = CGSize(width: newX - draggedPoint.x, height: newY - draggedPoint.y)
return displacement
}
func beginCropBoxTransformForPoint(_ location: CGPoint, atView view: UIView) {
switch(view)
{
case topLeftPoint:
self.handleDragTopLeft(location)
case bottomLeftPoint:
self.handleDragBottomLeft(location)
case bottomRightPoint:
self.handleDragBottomRight(location)
case topRightPoint:
self.handleDragTopRight(location)
case cropAreaView:
self.handleDragClearArea(location)
default:
return
}
var clearArea: CGRect = self.clearAreaFromControlPoints()
cropAreaView.frame = clearArea
clearArea.origin.y = clearArea.origin.y - imageFrameInView.origin.y
clearArea.origin.x = clearArea.origin.x - imageFrameInView.origin.x
self.shadeView.setCropArea(clearArea)
}
var imageScale:CGFloat = 1
func handleDragTopLeft(_ dragLocation: CGPoint) {
let disp: CGSize = self.deriveDisplacementFromDragLocation(dragLocation, draggedPoint: dragPoint.topLeftCenter, oppositePoint: dragPoint.bottomRightCenter)
var topLeft: CGPoint = CGPoint(x: dragPoint.topLeftCenter.x + disp.width, y: dragPoint.topLeftCenter.y + disp.height)
var topRight: CGPoint = CGPoint(x: dragPoint.topRightCenter.x, y: dragPoint.topLeftCenter.y + disp.height)
var bottomLeft: CGPoint = CGPoint(x: dragPoint.bottomLeftCenter.x + disp.width, y: dragPoint.bottomLeftCenter.y)
var width: CGFloat = topRight.x - topLeft.x
var height: CGFloat = bottomLeft.y - topLeft.y
width = width * imageScale
height = height * imageScale
let cropArea: CGRect = self.clearAreaFromControlPoints()
if width >= IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
topLeft.y = cropArea.origin.y + (((cropArea.size.height * self.imageScale) - IMAGE_MIN_HEIGHT) / self.imageScale)
topRight.y = topLeft.y
}
else {
if width < IMAGE_MIN_WIDTH && height >= IMAGE_MIN_HEIGHT {
topLeft.x = cropArea.origin.x + (((cropArea.size.width * self.imageScale) - IMAGE_MIN_WIDTH) / self.imageScale)
bottomLeft.x = topLeft.x
}
else {
if width < IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
topLeft.x = cropArea.origin.x + (((cropArea.size.width * self.imageScale) - IMAGE_MIN_WIDTH) / self.imageScale)
topLeft.y = cropArea.origin.y + (((cropArea.size.height * self.imageScale) - IMAGE_MIN_HEIGHT) / self.imageScale)
topRight.y = topLeft.y
bottomLeft.x = topLeft.x
}
}
}
self.boundingBoxForTopLeft(topLeft, bottomLeft: bottomLeft, bottomRight: dragPoint.bottomRightCenter, topRight: topRight)
}
func handleDragBottomLeft(_ dragLocation: CGPoint) {
let disp: CGSize = self.deriveDisplacementFromDragLocation(dragLocation, draggedPoint: dragPoint.bottomLeftCenter, oppositePoint: dragPoint.topRightCenter)
var bottomLeft: CGPoint = CGPoint(x: dragPoint.bottomLeftCenter.x + disp.width, y: dragPoint.bottomLeftCenter.y + disp.height)
var topLeft: CGPoint = CGPoint(x: dragPoint.topLeftCenter.x + disp.width, y: dragPoint.topLeftCenter.y)
var bottomRight: CGPoint = CGPoint(x: dragPoint.bottomRightCenter.x, y: dragPoint.bottomRightCenter.y + disp.height)
var width: CGFloat = bottomRight.x - bottomLeft.x
var height: CGFloat = bottomLeft.y - topLeft.y
width = width * self.imageScale
height = height * self.imageScale
let cropArea: CGRect = self.clearAreaFromControlPoints()
if width >= IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
bottomLeft.y = cropArea.origin.y + (IMAGE_MIN_HEIGHT / self.imageScale)
bottomRight.y = bottomLeft.y
}
else {
if width < IMAGE_MIN_WIDTH && height >= IMAGE_MIN_HEIGHT {
bottomLeft.x = cropArea.origin.x + (((cropArea.size.width * self.imageScale) - IMAGE_MIN_WIDTH) / self.imageScale)
topLeft.x = bottomLeft.x
}
else {
if width < IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
bottomLeft.x = cropArea.origin.x + (((cropArea.size.width * self.imageScale) - IMAGE_MIN_WIDTH) / self.imageScale)
bottomLeft.y = cropArea.origin.y + (IMAGE_MIN_HEIGHT / self.imageScale)
topLeft.x = bottomLeft.x
bottomRight.y = bottomLeft.y
}
}
}
self.boundingBoxForTopLeft(topLeft, bottomLeft: bottomLeft, bottomRight: bottomRight, topRight: dragPoint.topRightCenter)
}
func handleDragBottomRight(_ dragLocation: CGPoint) {
let disp: CGSize = self.deriveDisplacementFromDragLocation(dragLocation, draggedPoint: dragPoint.bottomRightCenter, oppositePoint: dragPoint.topLeftCenter)
var bottomRight: CGPoint = CGPoint(x: dragPoint.bottomRightCenter.x + disp.width, y: dragPoint.bottomRightCenter.y + disp.height)
var topRight: CGPoint = CGPoint(x: dragPoint.topRightCenter.x + disp.width, y: dragPoint.topRightCenter.y)
var bottomLeft: CGPoint = CGPoint(x: dragPoint.bottomLeftCenter.x, y: dragPoint.bottomLeftCenter.y + disp.height)
var width: CGFloat = bottomRight.x - bottomLeft.x
var height: CGFloat = bottomRight.y - topRight.y
width = width * self.imageScale
height = height * self.imageScale
let cropArea: CGRect = self.clearAreaFromControlPoints()
if width >= IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
bottomRight.y = cropArea.origin.y + (IMAGE_MIN_HEIGHT / self.imageScale)
bottomLeft.y = bottomRight.y
}
else {
if width < IMAGE_MIN_WIDTH && height >= IMAGE_MIN_HEIGHT {
bottomRight.x = cropArea.origin.x + (IMAGE_MIN_WIDTH / self.imageScale)
topRight.x = bottomRight.x
}
else {
if width < IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
bottomRight.x = cropArea.origin.x + (IMAGE_MIN_WIDTH / self.imageScale)
bottomRight.y = cropArea.origin.y + (IMAGE_MIN_HEIGHT / self.imageScale)
topRight.x = bottomRight.x
bottomLeft.y = bottomRight.y
}
}
}
self.boundingBoxForTopLeft(dragPoint.topLeftCenter, bottomLeft: bottomLeft, bottomRight: bottomRight, topRight: topRight)
}
func handleDragTopRight(_ dragLocation: CGPoint) {
let disp: CGSize = self.deriveDisplacementFromDragLocation(dragLocation, draggedPoint: dragPoint.topRightCenter, oppositePoint: dragPoint.bottomLeftCenter)
var topRight: CGPoint = CGPoint(x: dragPoint.topRightCenter.x + disp.width, y: dragPoint.topRightCenter.y + disp.height)
var topLeft: CGPoint = CGPoint(x: dragPoint.topLeftCenter.x, y: dragPoint.topLeftCenter.y + disp.height)
var bottomRight: CGPoint = CGPoint(x: dragPoint.bottomRightCenter.x + disp.width, y: dragPoint.bottomRightCenter.y)
var width: CGFloat = topRight.x - topLeft.x
var height: CGFloat = bottomRight.y - topRight.y
width = width * self.imageScale
height = height * self.imageScale
let cropArea: CGRect = self.clearAreaFromControlPoints()
if width >= IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
topRight.y = cropArea.origin.y + (((cropArea.size.height * self.imageScale) - IMAGE_MIN_HEIGHT) / self.imageScale)
topLeft.y = topRight.y
}
else {
if width < IMAGE_MIN_WIDTH && height >= IMAGE_MIN_HEIGHT {
topRight.x = cropArea.origin.x + (IMAGE_MIN_WIDTH / self.imageScale)
bottomRight.x = topRight.x
}
else {
if width < IMAGE_MIN_WIDTH && height < IMAGE_MIN_HEIGHT {
topRight.x = cropArea.origin.x + (IMAGE_MIN_WIDTH / self.imageScale)
topRight.y = cropArea.origin.y + (((cropArea.size.height * self.imageScale) - IMAGE_MIN_HEIGHT) / self.imageScale)
topLeft.y = topRight.y
bottomRight.x = topRight.x
}
}
}
self.boundingBoxForTopLeft(topLeft, bottomLeft: dragPoint.bottomLeftCenter, bottomRight: bottomRight, topRight: topRight)
}
func handleDragClearArea(_ dragLocation: CGPoint) {
let dX: CGFloat = dragLocation.x - dragPoint.dragStart.x
let dY: CGFloat = dragLocation.y - dragPoint.dragStart.y
var newTopLeft: CGPoint = CGPoint(x: dragPoint.topLeftCenter.x + dX, y: dragPoint.topLeftCenter.y + dY)
var newBottomLeft: CGPoint = CGPoint(x: dragPoint.bottomLeftCenter.x + dX, y: dragPoint.bottomLeftCenter.y + dY)
var newBottomRight: CGPoint = CGPoint(x: dragPoint.bottomRightCenter.x + dX, y: dragPoint.bottomRightCenter.y + dY)
var newTopRight: CGPoint = CGPoint(x: dragPoint.topRightCenter.x + dX, y: dragPoint.topRightCenter.y + dY)
let clearAreaWidth: CGFloat = dragPoint.topRightCenter.x - dragPoint.topLeftCenter.x
let clearAreaHeight: CGFloat = dragPoint.bottomLeftCenter.y - dragPoint.topLeftCenter.y
let halfControlPointSize: CGFloat = controlPointSize / 2
let minX: CGFloat = imageFrameInView.origin.x + halfControlPointSize
let maxX: CGFloat = imageFrameInView.origin.x + imageFrameInView.size.width - halfControlPointSize
let minY: CGFloat = imageFrameInView.origin.y + halfControlPointSize
let maxY: CGFloat = imageFrameInView.origin.y + imageFrameInView.size.height - halfControlPointSize
if newTopLeft.x < minX {
newTopLeft.x = minX
newBottomLeft.x = minX
newTopRight.x = newTopLeft.x + clearAreaWidth
newBottomRight.x = newTopRight.x
}
if newTopLeft.y < minY {
newTopLeft.y = minY
newTopRight.y = minY
newBottomLeft.y = newTopLeft.y + clearAreaHeight
newBottomRight.y = newBottomLeft.y
}
if newBottomRight.x > maxX {
newBottomRight.x = maxX
newTopRight.x = maxX
newTopLeft.x = newBottomRight.x - clearAreaWidth
newBottomLeft.x = newTopLeft.x
}
if newBottomRight.y > maxY {
newBottomRight.y = maxY
newBottomLeft.y = maxY
newTopRight.y = newBottomRight.y - clearAreaHeight
newTopLeft.y = newTopRight.y
}
topLeftPoint.center = newTopLeft
bottomLeftPoint.center = newBottomLeft
bottomRightPoint.center = newBottomRight
topRightPoint.center = newTopRight
}
}
| mit | c64c0aa14c3280478f126bb10170ac0c | 45.800926 | 269 | 0.635473 | 4.70843 | false | false | false | false |
y-takagi/ActiveRecord | ActiveRecord/Source/ActiveRecord/Validations.swift | 1 | 1454 | public protocol Validations {
func runValidateCallbacks()
func validates_presence_of(_ attribute: String)
func validates_uniqueness_of(_ attribute: String)
func validates_format_of(_ attribute: String, format: String)
}
extension ActiveRecord: Validations {
public func isValid() -> Bool {
errors.removeAll()
return runValidations() && validateRelations()
}
public func validates_presence_of(_ attribute: String) {
switch self.value(forKey: attribute) {
case let value as String:
if value.isEmpty {
errors[attribute] = "is empty."
}
case .none:
errors[attribute] = "is nil."
default:
break
}
}
public func validates_uniqueness_of(_ attribute: String) {}
public func validates_format_of(_ attribute: String, format: String) {
guard let value = self.value(forKey: attribute) as? String else { return }
if !NSPredicate(format: "SELF MATCHES %@", format).evaluate(with: value) {
errors[attribute] = "Doesn't match to format: \(format)"
}
}
private func runValidations() -> Bool {
runValidateCallbacks()
return errors.isEmpty
}
private func validateRelations() -> Bool {
return objectSchema.properties.filter { $0.objectClassName != nil
}.map {
if let rel = value(forKey: $0.name) as? Relationable {
return rel.isValid()
} else {
return true
}
}.reduce(true, { $0 && $1 })
}
}
| mit | 6aa71e3446945ee88fbb4a73573f6294 | 27.509804 | 78 | 0.642366 | 4.130682 | false | false | false | false |
mrketchup/cooldown | Core/DateComponentsFormatter+Cooldown.swift | 1 | 1386 | //
// Copyright © 2018 Matt Jones. All rights reserved.
//
// This file is part of Cooldown.
//
// Cooldown 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.
//
// Cooldown 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 Cooldown. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
public extension DateComponentsFormatter {
static let cooldownFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.hour, .minute, .second]
formatter.maximumUnitCount = 2
return formatter
}()
static let notificationFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .brief
formatter.allowedUnits = [.hour, .minute, .second]
formatter.maximumUnitCount = 2
return formatter
}()
}
| gpl-3.0 | 122f703a0c3ca7ea5879af633331ee3a | 33.625 | 71 | 0.704693 | 4.893993 | false | false | false | false |
Minitour/WWDC-Collaborators | Macintosh.playground/Sources/Interface/Boot/MacintoshFaceView.swift | 1 | 4020 | import Foundation
import UIKit
public class MacintoshFaceView: UIView {
open class func getFacePathFor(rect: CGRect)->UIBezierPath{
let path = UIBezierPath()
path.append(MacintoshFaceView.getHeadPath(rect))
path.append(MacintoshFaceView.getMouthPath(rect))
path.append(MacintoshFaceView.getLeftEyePath(rect))
path.append(MacintoshFaceView.getRightEyePath(rect))
path.append(MacintoshFaceView.getNosePath(rect))
return path
}
override public func draw(_ rect: CGRect) {
UIColor.black.set()
UIColor.clear.setFill()
MacintoshFaceView.getHeadPath(rect).stroke()
MacintoshFaceView.getMouthPath(rect).stroke()
MacintoshFaceView.getLeftEyePath(rect).stroke()
MacintoshFaceView.getRightEyePath(rect).stroke()
MacintoshFaceView.getNosePath(rect).stroke()
}
class func getHeadPath(_ rect: CGRect)->UIBezierPath{
let height = rect.height
let width = rect.width
let spacingAspectRatio: CGFloat = 0.125
let heightAspectRatio: CGFloat = 0.75
let rect = CGRect(x: 0, y: height * spacingAspectRatio, width: width, height: height * heightAspectRatio)
let path = UIBezierPath(rect: rect)
return path
}
class func getMouthPath(_ rect: CGRect)->UIBezierPath{
let height = rect.height
let width = rect.width
let headHeight = rect.height * 0.75
let spaceHorizontal = width * 0.125
let spaceVertical = height * 0.2 * 0.5
let startPoint = CGPoint(x: spaceHorizontal, y: headHeight - spaceVertical)
let endPoint = CGPoint(x: width - spaceHorizontal, y: headHeight - spaceVertical)
let controlPoint1 = CGPoint(x: startPoint.x + width / 3, y: startPoint.y + spaceVertical)
let controlPoint2 = CGPoint(x: endPoint.x - width / 3, y: startPoint.y + spaceVertical)
let path = UIBezierPath()
path.move(to: startPoint)
path.addCurve(to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2)
path.lineWidth = 3.0
return path
}
class func getLeftEyePath(_ rect: CGRect)->UIBezierPath{
let height = rect.height
let width = rect.width
let spaceHorizontal = width * 0.3
let eyeHeight = height * 0.1
let start = CGPoint(x: spaceHorizontal , y: height * 0.3)
let end = CGPoint(x: start.x, y: start.y + eyeHeight)
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
path.lineWidth = 3.0
return path
}
class func getRightEyePath(_ rect: CGRect)->UIBezierPath{
let height = rect.height
let width = rect.width
let spaceHorizontal = width * 0.3
let eyeHeight = height * 0.1
let start = CGPoint(x: width - spaceHorizontal , y: height * 0.3)
let end = CGPoint(x: start.x, y: start.y + eyeHeight)
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
path.lineWidth = 3.0
return path
}
class func getNosePath(_ rect: CGRect)->UIBezierPath{
let width = rect.width
let headHeight = rect.height * 0.75
let pt1 = CGPoint(x: rect.midX + width * 0.1, y: 0)
let pt2 = CGPoint(x: rect.midX - width * 0.05, y: headHeight - width * 0.125 * 1.5)
let pt3 = CGPoint(x: rect.midX + width * 0.05, y: pt2.y)
let pt4 = CGPoint(x: pt1.x, y: rect.maxY)
let ctrl1 = CGPoint(x: pt2.x, y: abs(pt1.y - pt2.y)/2)
let ctrl2 = CGPoint(x: rect.midX , y: headHeight)
let path = UIBezierPath()
path.move(to: pt1)
path.addQuadCurve(to: pt2, controlPoint: ctrl1)
path.addLine(to: pt2)
path.addLine(to: pt3)
path.addQuadCurve(to: pt4, controlPoint: ctrl2)
path.addLine(to: pt4)
path.lineWidth = 3.0
return path
}
}
| mit | ed7f09635ab644cd71bf339434040bc1 | 36.570093 | 113 | 0.613184 | 4.048338 | false | false | false | false |
mohshin-shah/MSTabBarController | MSTabBarController/MSTabAnimator.swift | 1 | 3506 | //
// MSTabAnimator.swift
//
//
// Created by Mohshin Shah on 06/11/2016.
// Copyright © 2016 Mohshin Shah. All rights reserved.
//
import Foundation
import UIKit
///Default animation duration
let kAnimationDuration: TimeInterval = 0.1
public class MSTabAnimator: UIPercentDrivenInteractiveTransition, UIViewControllerAnimatedTransitioning {
//Check whether it is animating
var isAnimating = false
//Check whether it is presenting
var isPresenting = true
//---------------------------------------
// MARK: - UIViewControllerAnimatedTransitioning
//---------------------------------------
public func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return kAnimationDuration
}
public func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)
let toViewController = transitionContext.viewController(forKey: .to)
let endFrame = transitionContext.containerView.bounds
//Check if presenting
if (self.isPresenting) {
transitionContext.containerView.insertSubview((toViewController?.view)!, belowSubview: (fromViewController?.view)!)
var startFrame = endFrame
startFrame.origin.x += transitionContext.containerView.bounds.width
toViewController?.view.frame = startFrame
var endFrameFromView = endFrame
endFrameFromView.origin.x -= transitionContext.containerView.bounds.width
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0.0, options: .curveLinear, animations: {
toViewController?.view.frame = endFrame
fromViewController?.view.frame = endFrameFromView
}, completion: { (finished) in
let didComplete = !transitionContext.transitionWasCancelled
transitionContext .completeTransition(didComplete)
})
} else {
transitionContext.containerView.insertSubview((toViewController?.view)!, aboveSubview: (fromViewController?.view)!)
var startFrameToView = endFrame
startFrameToView.origin.x -= transitionContext.containerView.bounds.width
toViewController?.view.frame = startFrameToView
var endFrameFromView = endFrame
endFrameFromView.origin.x += transitionContext.containerView.bounds.width
UIView.animate(withDuration: self.transitionDuration(using: transitionContext), delay: 0.0, options: .curveLinear, animations: {
fromViewController?.view.frame = endFrameFromView
toViewController?.view.frame = endFrame
}, completion: { (finished) in
let didComplete = !transitionContext.transitionWasCancelled
transitionContext .completeTransition(didComplete)
})
}
//Setting animation flag true
isAnimating = true
}
public func animationEnded(_ transitionCompleted: Bool) {
//Setting animation flag to false
isAnimating = false
}
}
| mit | afed496d6e3190a41224440f92924c78 | 35.894737 | 140 | 0.617404 | 6.845703 | false | false | false | false |
apple/swift | test/IRGen/simple_partial_apply_or_not.swift | 13 | 1260 | // RUN: %target-swift-emit-ir -module-name test %s | %FileCheck %s
// RUN: %target-run-simple-swift %s | %FileCheck %s --check-prefix=CHECK-EXEC
// REQUIRES: executable_test
@propertyWrapper
struct State<T> {
private class Reference {
var value: T
init(value: T) { self.value = value }
}
private let ref: Reference
init(wrappedValue: T) {
ref = Reference(value: wrappedValue)
}
var wrappedValue: T {
get { ref.value }
nonmutating set { ref.value = newValue }
}
}
struct S {
@State var value: Int = 1
init() {
value = 10 // CRASH
}
}
print("Hello!")
let s = S()
print(s)
// We need to call a partial apply thunk instead of directly calling the method
// because the ABI of closure requires swiftself in the context parameter but
// the method of this self type (struct S) does not.
// CHECK: define {{.*}}swiftcc %T4test5StateV9Reference33_C903A018FCE7355FD30EF8324850EB90LLCySi_G* @"$s4test1SVACycfC"()
// CHECK: call swiftcc void {{.*}}"$s4test1SV5valueSivsTA
// CHECK: ret %T4test5StateV9Reference33_C903A018FCE7355FD30EF8324850EB90LLCySi_G
// This used to crash.
// CHECK-EXEC: Hello!
// CHECK-EXEC: S(_value: main.State<Swift.Int>(ref: main.State<Swift.Int>.(unknown context at {{.*}}).Reference))
| apache-2.0 | 35fd9012aacf3fbcc86e7089883f424a | 25.25 | 121 | 0.688095 | 3.189873 | false | true | false | false |
zs40x/FirstRxSwiftTest | RxSwiftPlayground.playground/Contents.swift | 1 | 2523 | //: Playground - noun: a place where people can play
import UIKit
import RxSwift
enum Errors: Error {
case anError
}
func print<T: CustomStringConvertible>(label: String, event: Event<T>) {
print(label, event.element ?? event.error ?? event)
}
let disposeBag = DisposeBag()
//# Simple observable example
let observeable = Observable<Int>.range(start: 1, count: 10)
observeable.subscribe(
onNext: { element in
print(element)
},
onError: { error in
print("Error: \(error)")
},
onCompleted: {
print("Completed")
},
onDisposed: {
print("Disposed")
}
).addDisposableTo(disposeBag)
//# Simple subject example
let subject = PublishSubject<String>()
subject.subscribe(
onNext: { string in
print(string)
},
onError: { error in
print("Error: \(error)")
},
onDisposed: {
print("String subject disposed")
}
).addDisposableTo(disposeBag)
subject.on(.next("Hello world from a string subject"))
subject.on(.next("sdf"))
subject.on(.error(Errors.anError))
//# Simple BehaviorSubject
let behaviorSubject = BehaviorSubject(value: "Initial value")
// receiveives the initial value, because behaviorSubjects emit the latest value onSubscription
behaviorSubject.subscribe {
print(label: "1)", event: $0)
}.addDisposableTo(disposeBag)
// 1) and 2) will receive tis value, but 2) will receive only this message
behaviorSubject.on(.next("next value"))
behaviorSubject.subscribe {
print(label: "2)", event: $0)
}.addDisposableTo(disposeBag)
//# Simple ReplaySubject
let replaySubject = ReplaySubject<String>.create(bufferSize: 2)
replaySubject.on(.next("Initial replay subject value"))
replaySubject.on(.next("second value"))
replaySubject.subscribe {
print(label: "Replay 1)", event: $0)
}.addDisposableTo(disposeBag)
replaySubject.on(.next("Third value"))
replaySubject.subscribe { // does not receive the first, because the bufferSize is 1
print(label: "Replay 2)", event: $0)
}.addDisposableTo(disposeBag)
//# Variable example
let aVariable = Variable("Initial value")
aVariable.value = "another value"
aVariable.asObservable()
.subscribe {
print(label: "Var a)", event: $0)
}.addDisposableTo(disposeBag)
aVariable.value = "hey ho"
// Variables can emmit only values - no erros or completed events
// Filter
Observable.of(1,2,3,4,5,6)
.filter { integer in
integer % 2 == 0
}
.subscribe(onNext: {
print($0)
}).addDisposableTo(disposeBag) | mit | 6df24c372825f8ce009a2ebfb3989f24 | 25.020619 | 95 | 0.683314 | 3.966981 | false | false | false | false |
baydet/Cingulata | CingulataTests/ApiClient.swift | 1 | 2919 | //
// ApiClient.swift
// Cingulata
//
// Created by Alexandr Evsyuchenya on 11/16/15.
// Copyright © 2015 Alexander Evsyuchenya. All rights reserved.
//
import Foundation
import Cingulata
import Alamofire
import Pichi
func testDataMapping<M: Map>(inout data: TestData, map: M) {
data.stringKey <-> map["key"]
data.string2Key <-> map["key2"]
}
struct TestData: Mappable {
var stringKey: String = ""
var string2Key: String? = nil
init() {
}
init<T:Map>(_ map: T) {
}
}
struct NestedData: Mappable {
var stringKey: String = ""
init() {
}
init<T:Map>(_ map: T) {
}
}
enum Endpoint: RequestBuilder {
case NotFound
case Data(object: TestData)
case GetNestedData
var URL: NSURL {
let path: String!
switch self {
case .NotFound:
path = "status/404"
case .Data:
path = "https://httpbin.org/response-headers"
case .GetNestedData:
path = "https://httpbin.org/get"
}
return NSURL(string: path, relativeToURL: NSURL(string: "https://httpbin.org"))!
}
var httpMethod: Cingulata.Method {
switch self {
default:
return .GET
}
}
var parameters: [String : AnyObject]? {
switch self {
case .Data(_):
return ["key2" : "value2"]
default:
return nil
}
}
var requestMapping: RequestObjectMapping? {
switch self {
case .Data(let data):
return RequestObjectMapping(key: nil, sourceObject: data, transform: RequestDictionaryMapping<TestData>(mapFunction: testDataMapping))
default:
return nil
}
}
var requestBuilder: NSURLRequestBuilder {
return defaultRequestBuilder
}
var responseMapping: [ResponseObjectMapping]? {
switch self {
case .Data:
return [ResponseObjectMapping(code: HTTPStatusCode.Success, key: nil, transform: ResponseDictionaryMapping<TestData>(mapFunction: testDataMapping))]
default:
return nil
}
}
}
func defaultRequestBuilder(parameters: [String:AnyObject]?, HTTPMethod: String, URL: NSURL) throws -> NSURLRequest {
return try encode(parameters, HTTPMethod: HTTPMethod, URL: URL, encodingType: .URL)
}
private func encode(parameters: [String:AnyObject]?, HTTPMethod: String, URL: NSURL, encodingType: ParameterEncoding) throws -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = HTTPMethod
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameterEncoding = encodingType.encode(mutableURLRequest, parameters: parameters)
if let error = parameterEncoding.1 {
throw error
}
return parameterEncoding.0
}
| apache-2.0 | fbc5752b31b3cedf6898ddffb56fbf96 | 24.823009 | 160 | 0.619945 | 4.4414 | false | true | false | false |
edosedgar/xs-pkg | SWIFT/trie/main.swift | 1 | 5346 | /* |==========================|
* |Trie implemention on Swift|
* |==========================|
*/
/*
* One node of trie
*/
class trie_node_t<data_t:Hashable> {
var data : data_t?
var is_last : Bool
var children : [data_t : trie_node_t]
var used : Bool
init(elem : data_t?) {
data = elem
is_last = false
children = [data_t : trie_node_t]()
used = false
}
}
/*
* General class
*/
class trie_t<data_t:Hashable> {
let head : trie_node_t<data_t>
/*
* Init
*/
init(data: [[data_t]]) {
//Create main trie_node_t
head = trie_node_t<data_t>(elem : nil)
//Let's parse input data
for first in data {
expand(data : first)
print("Added: \(first)")
}
}
/*
* Add new element
*/
func expand(data: [data_t]) {
var current_level : trie_node_t<data_t> = head
var count = 0
for letter in data {
if let next_stage = current_level.children[letter] {
current_level = next_stage
current_level.is_last = count == (data.count - 1)
} else {
current_level.children[letter] =
trie_node_t<data_t>(elem : letter)
current_level.children[letter]!.is_last =
count == (data.count - 1)
current_level = current_level.children[letter]!
}
count = count + 1
}
}
/*
* Search in trie
*/
func prefix_search(data: [data_t]) -> [[data_t]]? {
var current_level : trie_node_t<data_t> = head
var common_node : trie_node_t<data_t>?
var results : [[data_t]]? = [[data_t]]()
//Let's find the deepest common node
for letter in data {
if let next_stage = current_level.children[letter] {
current_level = next_stage
} else {
break
}
if letter == data.last {
common_node = current_level
}
}
//In case of absence of any matches
guard let temp_node = common_node else {
return nil
}
//Let's build answers
while let element = resolve_all(node: common_node,
cur_data: data) {
results?.append(element)
}
clear_service_flag(node: head)
return results
}
/*
* Service function
*/
private func resolve_all(node: trie_node_t<data_t>?,
cur_data: [data_t]) -> [data_t]? {
var loc_data : [data_t] = cur_data
for (character, c_node) in node!.children {
loc_data = cur_data
if c_node.is_last && !c_node.used {
c_node.used = true
loc_data.append(character)
return loc_data
}
loc_data.append(character)
if let ret = resolve_all(node: c_node,
cur_data: loc_data) {
return ret
} else {
continue
}
}
if node!.is_last && !node!.used {
node!.used = true
return loc_data
}
return nil
}
/*
* Service function
*/
private func clear_service_flag(node: trie_node_t<data_t>) {
for (_, c_node) in node.children {
c_node.used = false
clear_service_flag(node: c_node)
}
return
}
}
/*
* Main code
*/
var key = "te"
let instance = trie_t<Character>(data: [Array("three".characters), Array("tea".characters),
Array("tiny".characters), Array("telescope".characters),
Array("bird".characters)])
var completion = instance.prefix_search(data: Array(key.characters))
print("\nKey: \"\(key)\"")
if let result = completion {
for each in result {
print("Found match:\(each)")
}
} else {
print("No result")
}
key = "t"
completion = instance.prefix_search(data: Array(key.characters))
print("\nKey: \"\(key)\"")
if let result = completion {
for each in result {
print("Found match:\(each)")
}
} else {
print("No result")
}
| gpl-2.0 | f0bfdae72da1db18c4d0ce63f22f65f9 | 32.622642 | 96 | 0.384961 | 4.891125 | false | false | false | false |
xiabob/ZhiHuDaily | ZhiHuDaily/ZhiHuDaily/Views/CommonViews/ScrollNumberLabel.swift | 1 | 9460 | //
// ScrollNumberLabel.swift
// ZhiHuDaily
//
// Created by xiabob on 17/3/23.
// Copyright © 2017年 xiabob. All rights reserved.
//
import UIKit
class ScrollNumberLabel: UIView {
private(set) var number: UInt = 0
var font = UIFont.systemFont(ofSize: 14) {
didSet {
for label in numberLabels {
label.font = font
}
}
}
var textColor = UIColor.black {
didSet {
for label in numberLabels {
label.textColor = textColor
}
}
}
fileprivate var numbers: [UInt] = []
fileprivate var numberLabels: [CyclicNumberLabel] = []
fileprivate lazy var containerView: UIView = {
let view = UIView(frame: CGRect.zero)
view.backgroundColor = .clear
return view
}()
init(frame: CGRect, originNumber: UInt) {
super.init(frame: frame)
clipsToBounds = true
number = originNumber
addSubview(containerView)
initNumberLabels()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func initNumberLabels() {
numbers = getNumbersArray(from: number)
let width = "9".widthWithConstrainedHeight(font.lineHeight, font: font)
numberLabels = numbers.map { (value) -> CyclicNumberLabel in
let label = CyclicNumberLabel(frame: CGRect(x: 0, y: 0, width: width, height: self.xb_height))
label.font = self.font
label.textColor = self.textColor
label.change(toNewNumber: "\(value)", by: .add, isAnimation: false)
return label
}
containerView.xb_width = ceil(CGFloat(numberLabels.count) * width)
containerView.xb_height = xb_height
containerView.center = CGPoint(x: xb_width/2, y: xb_height/2)
var index = 0
while index < numberLabels.count {
let label = numberLabels[index]
label.xb_left = CGFloat(index) * label.xb_width
containerView.addSubview(label)
index += 1
}
}
fileprivate func resetNumberLabels(newValue: UInt) {
for label in numberLabels {
label.removeFromSuperview()
}
numberLabels.removeAll()
let newNumbers = getNumbersArray(from: newValue)
let numberCount = newNumbers.count
var index: Int = 0
let width = "9".widthWithConstrainedHeight(font.lineHeight, font: font)
while index < numberCount {
let label = CyclicNumberLabel(frame: CGRect(x: CGFloat(index) * width, y: 0, width: width, height: xb_height))
label.font = self.font
label.textColor = self.textColor
label.change(toNewNumber: "\(newNumbers[index])", by: .add, isAnimation: false)
index += 1
numberLabels.append(label)
containerView.addSubview(label)
}
containerView.xb_width = ceil(CGFloat(numberLabels.count) * width)
containerView.xb_height = xb_height
containerView.center = CGPoint(x: xb_width/2, y: xb_height/2)
}
fileprivate func getNewContainerView(from newValue: UInt) -> UIView {
let containerView = UIView()
let newNumbers = getNumbersArray(from: newValue)
let numberCount = newNumbers.count
var index: Int = 0
let width = "9".widthWithConstrainedHeight(font.lineHeight, font: font)
while index < numberCount {
let label = CyclicNumberLabel(frame: CGRect(x: CGFloat(index) * width, y: 0, width: width, height: xb_height))
label.font = self.font
label.textColor = self.textColor
label.change(toNewNumber: "\(newNumbers[index])", by: .add, isAnimation: false)
index += 1
containerView.addSubview(label)
}
containerView.xb_width = ceil(CGFloat(newNumbers.count) * width)
containerView.xb_height = xb_height
containerView.center = CGPoint(x: xb_width/2, y: xb_height/2)
return containerView
}
fileprivate func setNumberLabels(to newNumbers: [UInt], type: CyclicNumberLabelType) {
var index = 0
while index < newNumbers.count {
let label = numberLabels[index]
label.change(toNewNumber: "\(newNumbers[index])", by: type)
index += 1
}
}
fileprivate func getNumbersArray(from number: UInt) -> [UInt] {
let numberString = NSString(format: "%d", number)
var numberArray: [UInt] = Array(repeating: 0, count: numberString.length)
var index = 0
while index < numberArray.count {
numberArray[index] = UInt(numberString.substring(with: NSRange(location: index, length: 1))) ?? 0
index += 1
}
return numberArray
}
func change(toNewNumber value: UInt) {
if number == value {return}
let oldValue = number
let oldNumbersCount = numbers.count
number = value
numbers = getNumbersArray(from: value)
let newNumbersCount = numbers.count
if newNumbersCount == oldNumbersCount {
let type = oldValue < value ? CyclicNumberLabelType.add : CyclicNumberLabelType.reduce
setNumberLabels(to: numbers, type: type)
} else {
let type = newNumbersCount > oldNumbersCount ? CyclicNumberLabelType.add : CyclicNumberLabelType.reduce
containerView.isHidden = true
resetNumberLabels(newValue: number)
var multiplier: CGFloat = 0
if type == .add {
multiplier = 1
} else {
multiplier = -1
}
let oldContainer = getNewContainerView(from: oldValue)
oldContainer.xb_top = 0
addSubview(oldContainer)
let newContainer = getNewContainerView(from: value)
newContainer.xb_top = multiplier * xb_height
addSubview(newContainer)
UIView.animate(withDuration: 0.25, animations: {
oldContainer.xb_top = -multiplier * self.xb_height
newContainer.xb_top = 0
}, completion: { (finished) in
oldContainer.removeFromSuperview()
newContainer.removeFromSuperview()
self.containerView.isHidden = false
})
}
}
}
fileprivate enum CyclicNumberLabelType {
case add, reduce
}
fileprivate class CyclicNumberLabel: UIView {
var font = UIFont.systemFont(ofSize: 14) {
didSet {
topLabel.font = font
centerLabel.font = font
bottomLabel.font = font
}
}
var textColor = UIColor.black {
didSet {
topLabel.textColor = textColor
centerLabel.textColor = textColor
bottomLabel.textColor = textColor
}
}
fileprivate lazy var topLabel: UILabel = self.createLabel()
fileprivate lazy var centerLabel: UILabel = self.createLabel()
fileprivate lazy var bottomLabel: UILabel = self.createLabel()
fileprivate lazy var containerView: UIView = { [unowned self] in
let view = UIView(frame: CGRect(x: 0,
y: -self.xb_height,
width: self.xb_width,
height: self.xb_height*3))
view.backgroundColor = .clear
return view
}()
override init(frame: CGRect) {
super.init(frame: frame)
clipsToBounds = true
configViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func configViews() {
addSubview(containerView)
topLabel.xb_top = 0
containerView.addSubview(topLabel)
centerLabel.xb_top = xb_height
containerView.addSubview(centerLabel)
bottomLabel.xb_top = xb_height * 2
containerView.addSubview(bottomLabel)
}
fileprivate func createLabel() -> UILabel {
let label = UILabel(frame: bounds)
label.font = font
label.textColor = textColor
label.textAlignment = .center
return label
}
func change(toNewNumber value: String, by type: CyclicNumberLabelType, isAnimation: Bool = true) {
if centerLabel.text == "\(value)" {return}
if !isAnimation {return self.centerLabel.text = value}
if type == .add {
bottomLabel.text = value
UIView.animate(withDuration: 0.25, animations: {
self.containerView.xb_top = -2*self.xb_height
}, completion: { (finished) in
self.centerLabel.text = value
self.containerView.xb_top = -self.xb_height
})
} else {
topLabel.text = value
UIView.animate(withDuration: 0.25, animations: {
self.containerView.xb_top = 0
}, completion: { (finished) in
self.centerLabel.text = value
self.containerView.xb_top = -self.xb_height
})
}
}
}
| mit | 23362355702f8796e8087085df9ce71c | 33.389091 | 122 | 0.572486 | 4.920395 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Controllers/Chat/ChannelInfoViewController.swift | 1 | 7036 | //
// ChannelInfoViewController.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 09/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
class ChannelInfoViewController: BaseViewController {
var tableViewData: [[Any]] = [] {
didSet {
tableView?.reloadData()
}
}
var subscription: Subscription? {
didSet {
guard let subscription = self.subscription else { return }
let channelInfoData = [
ChannelInfoDetailCellData(title: localized("chat.info.item.members"), detail: ""),
ChannelInfoDetailCellData(title: localized("chat.info.item.pinned"), detail: ""),
ChannelInfoDetailCellData(title: localized("chat.info.item.starred"), detail: "")
]
if subscription.type == .directMessage {
tableViewData = [[
ChannelInfoUserCellData(user: subscription.directMessageUser)
], channelInfoData]
} else {
let topic = subscription.roomTopic?.characters.count ?? 0 == 0 ? localized("chat.info.item.no_topic") : subscription.roomTopic
let description = subscription.roomDescription?.characters.count ?? 0 == 0 ? localized("chat.info.item.no_description") : subscription.roomDescription
tableViewData = [[
ChannelInfoBasicCellData(title: "#\(subscription.name)"),
ChannelInfoDescriptionCellData(
title: localized("chat.info.item.topic"),
description: topic
),
ChannelInfoDescriptionCellData(
title: localized("chat.info.item.description"),
description: description
)
], channelInfoData]
}
}
}
@IBOutlet weak var tableView: UITableView!
weak var buttonFavorite: UIBarButtonItem?
override func viewDidLoad() {
super.viewDidLoad()
title = localized("chat.info.title")
if let auth = AuthManager.isAuthenticated() {
if auth.settings?.favoriteRooms ?? false {
let defaultImage = UIImage(named: "Star")?.imageWithTint(UIColor.RCGray()).withRenderingMode(.alwaysOriginal)
let buttonFavorite = UIBarButtonItem(image: defaultImage, style: .plain, target: self, action: #selector(buttonFavoriteDidPressed))
navigationItem.rightBarButtonItem = buttonFavorite
self.buttonFavorite = buttonFavorite
updateButtonFavoriteImage()
}
}
}
func updateButtonFavoriteImage(_ force: Bool = false, value: Bool = false) {
guard let buttonFavorite = self.buttonFavorite else { return }
let favorite = force ? value : subscription?.favorite ?? false
var image: UIImage?
if favorite {
image = UIImage(named: "Star-Filled")?.imageWithTint(UIColor.RCFavoriteMark())
} else {
image = UIImage(named: "Star")?.imageWithTint(UIColor.RCGray())
}
buttonFavorite.image = image?.withRenderingMode(.alwaysOriginal)
}
// MARK: IBAction
func buttonFavoriteDidPressed(_ sender: Any) {
guard let subscription = self.subscription else { return }
SubscriptionManager.toggleFavorite(subscription) { [unowned self] (response) in
if response.isError() {
subscription.updateFavorite(!subscription.favorite)
}
self.updateButtonFavoriteImage()
}
self.subscription?.updateFavorite(!subscription.favorite)
updateButtonFavoriteImage()
}
@IBAction func buttonCloseDidPressed(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
// MARK: UITableViewDelegate
extension ChannelInfoViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let data = tableViewData[indexPath.section][indexPath.row]
if let data = data as? ChannelInfoBasicCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoBasicCell.identifier) as? ChannelInfoBasicCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoDetailCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoDetailCell.identifier) as? ChannelInfoDetailCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoUserCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoUserCell.identifier) as? ChannelInfoUserCell {
cell.data = data
return cell
}
}
if let data = data as? ChannelInfoDescriptionCellData {
if let cell = tableView.dequeueReusableCell(withIdentifier: ChannelInfoDescriptionCell.identifier) as? ChannelInfoDescriptionCell {
cell.data = data
return cell
}
}
return UITableViewCell()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let data = tableViewData[indexPath.section][indexPath.row]
if data as? ChannelInfoBasicCellData != nil {
return CGFloat(ChannelInfoBasicCell.defaultHeight)
}
if data as? ChannelInfoDetailCellData != nil {
return CGFloat(ChannelInfoDetailCell.defaultHeight)
}
if data as? ChannelInfoUserCellData != nil {
return CGFloat(ChannelInfoUserCell.defaultHeight)
}
if data as? ChannelInfoDescriptionCellData != nil {
return CGFloat(ChannelInfoDescriptionCell.defaultHeight)
}
return CGFloat(0)
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let data = tableViewData[indexPath.section][indexPath.row]
if data as? ChannelInfoDetailCellData != nil {
let alert = UIAlertController(title: "Ops!", message: "We're still working on this feature, stay tunned!", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
if let selectedIndex = tableView.indexPathForSelectedRow {
tableView.deselectRow(at: selectedIndex, animated: true)
}
}
}
}
// MARK: UITableViewDataSource
extension ChannelInfoViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return tableViewData.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableViewData[section].count
}
}
| mit | 050f1ac542ce57024166f759f7beb2b8 | 35.076923 | 166 | 0.622886 | 5.583333 | false | false | false | false |
RobinChao/Monkey | Monkey/Monkey.swift | 1 | 2500 |
import Foundation
final public class Monkey {
//json object to model
public class func model<T: NSObject>(json: AnyObject?, clz: T.Type) -> T?{
let model = T()
if let _ = json{
if json is NSDictionary{
model.setProperty(json)
return model
}else{
debugPrint("error: reflect model need a dictionary json")
}
}
return nil
}
public class func model<T: NSObject>(data: NSData?, clz: T.Type) -> T?{
let model = T()
if let _ = data{
do{
let json: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if json is NSDictionary{
model.setProperty(json)
return model
}else{
debugPrint("error: reflect model need a dictionary json")
}
}catch{
debugPrint("Serializat json error, \(error)")
}
}
return nil
}
public class func modelArray<T: NSObject>(json: AnyObject?, clz: T.Type) -> [T]?{
var modelArray = [T]()
if let _ = json{
if json is NSArray {
for jsonObj in json as! NSArray{
let model = T()
model.setProperty(jsonObj)
modelArray.append(model)
}
return modelArray
} else {
debugPrint("error: reflect model need a array json")
}
}
return nil
}
public static func modelArray<T: NSObject>(data: NSData?, clz: T.Type) -> [T]? {
var modelArray = [T]()
if let _ = data {
do {
let json: AnyObject! = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if json is NSArray {
for jsonObj in json as! NSArray {
let model = T()
model.setProperty(jsonObj)
modelArray.append(model)
}
return modelArray
} else {
debugPrint("error: reflect model need a array json")
}
} catch {
debugPrint("Serializat json error, \(error)")
}
}
return nil
}
} | mit | 4c7aedae84586ca178173f0dbb9be25d | 31.480519 | 137 | 0.4728 | 5.411255 | false | false | false | false |
davefoxy/SwiftBomb | SwiftBomb/Classes/Resources/Shared/ImageURLs.swift | 1 | 1714 | //
// ImageURLs.swift
// SwiftBomb
//
// Created by David Fox on 16/04/2016.
// Copyright © 2016 David Fox. All rights reserved.
//
import Foundation
/**
A container to hold all the possible URLs for an image hosted on Giant Bomb.
*/
public struct ImageURLs {
/// URL to the icon-sized version of the image.
public let icon: URL?
/// URL to the medium-sized version of the image.
public let medium: URL?
/// URL to the screen-sized version of the image.
public let screen: URL?
/// URL to the small-sized version of the image.
public let small: URL?
/// URL to the supersized version of the image.
public let supersize: URL?
/// URL to the thumbnail version of the image.
public let thumb: URL?
/// URL to the tiny-sized version of the image.
public let tiny: URL?
/// Optional array of tags the image has on the wiki.
public let tags: [String]?
init(json: [String: AnyObject]) {
icon = (json["icon_url"] as? String)?.safeGBImageURL() as URL?
medium = (json["medium_url"] as? String)?.safeGBImageURL() as URL?
screen = (json["screen_url"] as? String)?.safeGBImageURL() as URL?
small = (json["small_url"] as? String)?.safeGBImageURL() as URL?
supersize = (json["super_url"] as? String)?.safeGBImageURL() as URL?
thumb = (json["thumb_url"] as? String)?.safeGBImageURL() as URL?
tiny = (json["tiny_url"] as? String)?.safeGBImageURL() as URL?
if let tagsString = json["tags"] as? String {
tags = tagsString.components(separatedBy: ", ")
} else {
tags = [String]()
}
}
}
| mit | 33a540deca14e352944116e95f0e3618 | 29.589286 | 77 | 0.598949 | 4.040094 | false | false | false | false |
xwu/swift | test/stdlib/StringCreate.swift | 1 | 5138 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
defer { runAllTests() }
var StringCreateTests = TestSuite("StringCreateTests")
enum SimpleString: String, CaseIterable {
case smallASCII = "abcdefg"
case smallUnicode = "abéÏ𓀀"
case largeASCII = "012345678901234567890"
case largeUnicode = "abéÏ012345678901234567890𓀀"
case emoji = "😀😃🤢🤮👩🏿🎤🧛🏻♂️🧛🏻♂️👩👩👦👦"
case empty = ""
}
extension String {
var utf32: [UInt32] { return unicodeScalars.map { $0.value } }
}
StringCreateTests.test("String(decoding:as:)") {
func validateDecodingAs(_ str: String) {
// Non-contiguous (maybe) storage
expectEqual(str, String(decoding: str.utf8, as: UTF8.self))
expectEqual(str, String(decoding: str.utf16, as: UTF16.self))
expectEqual(str, String(decoding: str.utf32, as: UTF32.self))
// Contiguous storage
expectEqual(str, String(decoding: Array(str.utf8), as: UTF8.self))
expectEqual(str, String(decoding: Array(str.utf16), as: UTF16.self))
expectEqual(str, String(decoding: Array(str.utf32), as: UTF32.self))
}
for simpleString in SimpleString.allCases {
validateDecodingAs(simpleString.rawValue)
}
// Corner-case: UBP with null pointer (https://bugs.swift.org/browse/SR-9869)
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF8.self))
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF16.self))
expectEqual(
"", String(decoding: UnsafeBufferPointer(_empty: ()), as: UTF32.self))
}
if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
StringCreateTests.test("String(unsafeUninitializedCapacity:initializingUTF8With:)") {
for simpleString in SimpleString.allCases {
let expected = simpleString.rawValue
let expectedUTF8 = expected.utf8
let actual = String(unsafeUninitializedCapacity: expectedUTF8.count) {
_ = $0.initialize(from: expectedUTF8)
return expectedUTF8.count
}
expectEqual(expected, actual)
}
let validUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3, 0xA9]
let invalidUTF8: [UInt8] = [0x43, 0x61, 0x66, 0xC3]
let longerValidUTF8: [UInt8] = [0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x21, 0x43, 0x61, 0x66, 0xC3, 0xA9]
let longerInvalidUTF8: [UInt8] = [0x21, 0x21, 0x43, 0x61, 0x66, 0xC3, 0x43, 0x61, 0x66, 0xC3, 0x43, 0x61, 0x66, 0xC3]
func test(bufferSize: Int, input: [UInt8], expected: String) {
let strs = (0..<100).map { _ in
String(unsafeUninitializedCapacity: bufferSize) { buffer in
_ = buffer.initialize(from: input)
return input.count
}
}
for str in strs {
expectEqual(expected, str)
}
}
test(bufferSize: validUTF8.count, input: validUTF8, expected: "Café")
test(bufferSize: invalidUTF8.count, input: invalidUTF8, expected: "Caf�")
// Force non-smol strings by using a larger capacity
test(bufferSize: 16, input: validUTF8, expected: "Café")
test(bufferSize: 16, input: invalidUTF8, expected: "Caf�")
test(bufferSize: longerValidUTF8.count, input: longerValidUTF8, expected: "!!!!!!!!!!Café")
test(bufferSize: longerInvalidUTF8.count, input: longerInvalidUTF8, expected: "!!Caf�Caf�Caf�")
test(bufferSize: 16, input: longerValidUTF8, expected: "!!!!!!!!!!Café")
test(bufferSize: 16, input: longerInvalidUTF8, expected: "!!Caf�Caf�Caf�")
let empty = String(unsafeUninitializedCapacity: 16) { _ in
// Can't initialize the buffer (e.g. the capacity is too small).
return 0
}
expectTrue(empty.isEmpty)
}
}
if #available(macOS 10.16, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
StringCreateTests.test("Small string unsafeUninitializedCapacity") {
let str1 = "42"
let str2 = String(42)
expectEqual(str1, str2)
let str3 = String(unsafeUninitializedCapacity: 2) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
return 2
}
expectEqual(str1, str3)
// Write into uninitialized space.
let str4 = String(unsafeUninitializedCapacity: 3) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
$0[2] = UInt8(ascii: "X")
// Deinitialize memory used for scratch space before returning.
($0.baseAddress! + 2).deinitialize(count: 1)
return 2
}
expectEqual(str1, str4)
let str5 = String(unsafeUninitializedCapacity: 3) {
$0[1] = UInt8(ascii: "4")
$0[2] = UInt8(ascii: "2")
// Move the initialized UTF-8 code units to the start of the buffer,
// leaving the non-overlapping source memory uninitialized.
$0.baseAddress!.moveInitialize(from: $0.baseAddress! + 1, count: 2)
return 2
}
expectEqual(str1, str5)
// Ensure reasonable behavior despite a deliberate API contract violation.
let str6 = String(unsafeUninitializedCapacity: 3) {
$0[0] = UInt8(ascii: "4")
$0[1] = UInt8(ascii: "2")
$0[2] = UInt8(ascii: "X")
return 2
}
expectEqual(str1, str6)
}
}
| apache-2.0 | dc821e7273f7873fa5b494f4bc43b4d4 | 35.543478 | 125 | 0.654967 | 3.437628 | false | true | false | false |
ahoppen/swift | test/Generics/function_defs.swift | 6 | 11136 | // RUN: %target-typecheck-verify-swift -warn-redundant-requirements
//===----------------------------------------------------------------------===//
// Type-check function definitions
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Basic type checking
//===----------------------------------------------------------------------===//
protocol EqualComparable {
func isEqual(_ other: Self) -> Bool
}
func doCompare<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) -> Bool {
var b1 = t1.isEqual(t2)
if b1 {
return true
}
return t1.isEqual(u) // expected-error {{cannot convert value of type 'U' to expected argument type 'T'}}
}
protocol MethodLessComparable {
func isLess(_ other: Self) -> Bool
}
func min<T : MethodLessComparable>(_ x: T, y: T) -> T {
if (y.isLess(x)) { return y }
return x
}
//===----------------------------------------------------------------------===//
// Interaction with existential types
//===----------------------------------------------------------------------===//
func existential<T : EqualComparable, U : EqualComparable>(_ t1: T, t2: T, u: U) {
var eqComp : any EqualComparable = t1
eqComp = u
if t1.isEqual(eqComp) {} // expected-error{{cannot convert value of type 'any EqualComparable' to expected argument type 'T'}}
if eqComp.isEqual(t2) {}
// expected-error@-1 {{member 'isEqual' cannot be used on value of type 'any EqualComparable'; consider using a generic constraint instead}}
}
protocol OtherEqualComparable {
func isEqual(_ other: Self) -> Bool
}
func otherExistential<T : EqualComparable>(_ t1: T) {
var otherEqComp : OtherEqualComparable = t1 // expected-error{{value of type 'T' does not conform to specified type 'OtherEqualComparable'}}
otherEqComp = t1 // expected-error{{cannot assign value of type 'T' to type 'any OtherEqualComparable'}}
_ = otherEqComp
var otherEqComp2 : any OtherEqualComparable // Ok
otherEqComp2 = t1 // expected-error{{cannot assign value of type 'T' to type 'any OtherEqualComparable'}}
_ = otherEqComp2
_ = t1 as any EqualComparable & OtherEqualComparable // expected-error{{cannot convert value of type 'T' to type 'any EqualComparable & OtherEqualComparable' in coercion}}
}
//===----------------------------------------------------------------------===//
// Overloading
//===----------------------------------------------------------------------===//
protocol Overload {
associatedtype A
associatedtype B
func getA() -> A
func getB() -> B
func f1(_: A) -> A // expected-note {{candidate expects value of type 'OtherOvl.A' for parameter #1}}
func f1(_: B) -> B // expected-note {{candidate expects value of type 'OtherOvl.B' for parameter #1}}
func f2(_: Int) -> A // expected-note{{found this candidate}}
func f2(_: Int) -> B // expected-note{{found this candidate}}
func f3(_: Int) -> Int // expected-note {{found candidate with type '(Int) -> Int'}}
func f3(_: Float) -> Float // expected-note {{found candidate with type '(Float) -> Float'}}
func f3(_: Self) -> Self // expected-note {{found candidate with type '(OtherOvl) -> OtherOvl'}}
var prop : Self { get }
}
func testOverload<Ovl : Overload, OtherOvl : Overload>(_ ovl: Ovl, ovl2: Ovl,
other: OtherOvl) {
var a = ovl.getA()
var b = ovl.getB()
// Overloading based on arguments
_ = ovl.f1(a)
a = ovl.f1(a)
_ = ovl.f1(b)
b = ovl.f1(b)
// Overloading based on return type
a = ovl.f2(17)
b = ovl.f2(17)
ovl.f2(17) // expected-error{{ambiguous use of 'f2'}}
// Check associated types from different objects/different types.
a = ovl2.f2(17)
a = ovl2.f1(a)
other.f1(a) // expected-error{{no exact matches in call to instance method 'f1'}}
// Overloading based on context
var f3i : (Int) -> Int = ovl.f3
var f3f : (Float) -> Float = ovl.f3
var f3ovl_1 : (Ovl) -> Ovl = ovl.f3
var f3ovl_2 : (Ovl) -> Ovl = ovl2.f3
var f3ovl_3 : (Ovl) -> Ovl = other.f3 // expected-error{{no 'f3' candidates produce the expected contextual result type '(Ovl) -> Ovl'}}
var f3i_unbound : (Ovl) -> (Int) -> Int = Ovl.f3
var f3f_unbound : (Ovl) -> (Float) -> Float = Ovl.f3
var f3f_unbound2 : (OtherOvl) -> (Float) -> Float = OtherOvl.f3
var f3ovl_unbound_1 : (Ovl) -> (Ovl) -> Ovl = Ovl.f3
var f3ovl_unbound_2 : (OtherOvl) -> (OtherOvl) -> OtherOvl = OtherOvl.f3
}
//===----------------------------------------------------------------------===//
// Subscripting
//===----------------------------------------------------------------------===//
protocol Subscriptable {
associatedtype Index
associatedtype Value
func getIndex() -> Index
func getValue() -> Value
subscript (index : Index) -> Value { get set } // expected-note {{found this candidate}}
}
protocol IntSubscriptable {
associatedtype ElementType
func getElement() -> ElementType
subscript (index : Int) -> ElementType { get } // expected-note {{found this candidate}}
}
func subscripting<T : Subscriptable & IntSubscriptable>(_ t: T) {
var index = t.getIndex()
var value = t.getValue()
var element = t.getElement()
value = t[index]
t[index] = value // expected-error{{cannot assign through subscript: 't' is a 'let' constant}}
element = t[17]
t[42] = element // expected-error{{cannot assign through subscript: subscript is get-only}}
t[value] = 17 // expected-error{{no exact matches in call to subscript}}
}
//===----------------------------------------------------------------------===//
// Static functions
//===----------------------------------------------------------------------===//
protocol StaticEq {
static func isEqual(_ x: Self, y: Self) -> Bool
}
func staticEqCheck<T : StaticEq, U : StaticEq>(_ t: T, u: U) {
if t.isEqual(t, t) { return } // expected-error{{static member 'isEqual' cannot be used on instance of type 'T'}} // expected-error {{missing argument label 'y:' in call}}
if T.isEqual(t, y: t) { return }
if U.isEqual(u, y: u) { return }
T.isEqual(t, y: u) // expected-error{{cannot convert value of type 'U' to expected argument type 'T'}}
}
//===----------------------------------------------------------------------===//
// Operators
//===----------------------------------------------------------------------===//
protocol Ordered {
static func <(lhs: Self, rhs: Self) -> Bool
}
func testOrdered<T : Ordered>(_ x: T, y: Int) {
if y < 100 || 500 < y { return }
if x < x { return }
}
//===----------------------------------------------------------------------===//
// Requires clauses
//===----------------------------------------------------------------------===//
func conformanceViaRequires<T>(_ t1: T, t2: T) -> Bool
where T : EqualComparable, T : MethodLessComparable {
let b1 = t1.isEqual(t2)
if b1 || t1.isLess(t2) {
return true
}
}
protocol GeneratesAnElement {
associatedtype Element : EqualComparable
func makeIterator() -> Element
}
protocol AcceptsAnElement {
associatedtype Element : MethodLessComparable
func accept(_ e : Element)
}
func impliedSameType<T : GeneratesAnElement>(_ t: T)
where T : AcceptsAnElement {
t.accept(t.makeIterator())
let e = t.makeIterator(), e2 = t.makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
protocol GeneratesAssoc1 {
associatedtype Assoc1 : EqualComparable
func get() -> Assoc1
}
protocol GeneratesAssoc2 {
associatedtype Assoc2 : MethodLessComparable
func get() -> Assoc2
}
func simpleSameType<T : GeneratesAssoc1, U : GeneratesAssoc2>
(_ t: T, u: U) -> Bool
where T.Assoc1 == U.Assoc2 {
return t.get().isEqual(u.get()) || u.get().isLess(t.get())
}
protocol GeneratesMetaAssoc1 {
associatedtype MetaAssoc1 : GeneratesAnElement
func get() -> MetaAssoc1
}
protocol GeneratesMetaAssoc2 {
associatedtype MetaAssoc2 : AcceptsAnElement
func get() -> MetaAssoc2
}
func recursiveSameType
<T : GeneratesMetaAssoc1, U : GeneratesMetaAssoc2, V : GeneratesAssoc1>
(_ t: T, u: U, v: V)
where T.MetaAssoc1 == V.Assoc1, V.Assoc1 == U.MetaAssoc2
{
t.get().accept(t.get().makeIterator())
let e = t.get().makeIterator(), e2 = t.get().makeIterator()
if e.isEqual(e2) || e.isLess(e2) {
return
}
}
// <rdar://problem/13985164>
protocol P1 {
associatedtype Element
}
protocol P2 {
associatedtype AssocP1 : P1
func getAssocP1() -> AssocP1
}
func beginsWith2<E0: P1, E1: P1>(_ e0: E0, _ e1: E1) -> Bool
where E0.Element == E1.Element,
E0.Element : EqualComparable
{
}
func beginsWith3<S0: P2, S1: P2>(_ seq1: S0, _ seq2: S1) -> Bool
where S0.AssocP1.Element == S1.AssocP1.Element,
S1.AssocP1.Element : EqualComparable {
return beginsWith2(seq1.getAssocP1(), seq2.getAssocP1())
}
// FIXME: Test same-type constraints that try to equate things we
// don't want to equate, e.g., T == U.
//===----------------------------------------------------------------------===//
// Bogus requirements
//===----------------------------------------------------------------------===//
func nonTypeReq<T>(_: T) where T : Wibble {} // expected-error{{cannot find type 'Wibble' in scope}}
func badProtocolReq<T>(_: T) where T : Int {} // expected-error{{type 'T' constrained to non-protocol, non-class type 'Int'}}
func nonTypeSameType<T>(_: T) where T == Wibble {} // expected-error{{cannot find type 'Wibble' in scope}}
func nonTypeSameType2<T>(_: T) where Wibble == T {} // expected-error{{cannot find type 'Wibble' in scope}}
func sameTypeEq<T>(_: T) where T = T {} // expected-error{{use '==' for same-type requirements rather than '='}} {{34-35===}}
// expected-warning@-1{{redundant same-type constraint 'T' == 'T'}}
func badTypeConformance1<T>(_: T) where Int : EqualComparable {} // expected-error{{type 'Int' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance2<T>(_: T) where T.Blarg : EqualComparable { } // expected-error{{'Blarg' is not a member type of type 'T'}}
func badTypeConformance3<T>(_: T) where (T) -> () : EqualComparable { }
// expected-error@-1{{type '(T) -> ()' in conformance requirement does not refer to a generic parameter or associated type}}
func badTypeConformance4<T>(_: T) where @escaping (inout T) throws -> () : EqualComparable { }
// expected-error@-1 {{@escaping attribute may only be used in function parameter position}}
func badTypeConformance5<T>(_: T) where T & Sequence : EqualComparable { }
// expected-error@-1 {{non-protocol, non-class type 'T' cannot be used within a protocol-constrained type}}
func badTypeConformance6<T>(_: T) where [T] : Collection { }
// expected-warning@-1{{redundant conformance constraint '[T]' : 'Collection'}}
func badTypeConformance7<T, U>(_: T, _: U) where T? : U { }
// expected-error@-1{{type 'T?' constrained to non-protocol, non-class type 'U'}}
func badSameType<T, U : GeneratesAnElement, V>(_ : T, _ : U)
where T == U.Element, U.Element == V {}
// expected-warning@-2{{same-type requirement makes generic parameters 'V' and 'T' equivalent}}
| apache-2.0 | 0cc4bb93153578a2135ad6ede908fed0 | 35.631579 | 180 | 0.581268 | 3.960171 | false | false | false | false |
nifty-swift/Nifty | Sources/cross.swift | 2 | 1660 | /**************************************************************************************************
* cross.swift
*
* This file defines vector cross product functionality.
*
* Author: Philip Erickson
* Creation Date: 29 Dec 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.
*
* Copyright 2016 Philip Erickson
**************************************************************************************************/
/// Compute the cross product of two vectors.
///
/// - Parameters:
/// - a: first vector
/// - b: second vector
/// - Returns: cross product of given vectors
public func cross(_ a: Vector<Double>, _ b: Vector<Double>) -> Vector<Double>
{
precondition(a.count == 3 && b.count == 3, "The cross product requires A and B be of length 3")
let s1 = a[1]*b[2] - a[2]*b[1]
let s2 = a[2]*b[0] - a[0]*b[2]
let s3 = a[0]*b[1] - a[1]*b[0]
var name: String? = nil
var showName: Bool? = nil
if let nameA = a.name, let nameB = b.name
{
name = "cross\(nameA, nameB)"
showName = a.showName && b.showName
}
return Vector([s1, s2, s3], name: name, showName: showName)
}
| apache-2.0 | 64c7a80b98fdde30e30205f948f20529 | 35.086957 | 101 | 0.571084 | 3.869464 | false | false | false | false |
ahoppen/swift | test/attr/attr_objc.swift | 3 | 125631 | // RUN: %empty-directory(%t)
// RUN: %{python} %S/Inputs/access-note-gen.py %s %t/attr_objc_access_note.swift %t/attr_objc_access_note.accessnotes
// Test with @objc attrs, without access notes
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t/attr_objc.ast
// Test without @objc attrs, with access notes
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %t/attr_objc_access_note.swift
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %t/attr_objc_access_note.swift -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc_access_note.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %t/attr_objc_access_note.swift < %t/attr_objc_access_note.ast
// Test with both @objc attrs and access notes
// RUN: %target-swift-frontend -disable-objc-attr-requires-foundation-module -typecheck -verify -verify-ignore-unknown %s -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference
// RUN: %target-swift-ide-test -skip-deinit=false -print-ast-typechecked -source-filename %s -access-notes-path %t/attr_objc_access_note.accessnotes -function-definitions=true -prefer-type-repr=false -print-implicit-attrs=true -explode-pattern-binding-decls=true -disable-objc-attr-requires-foundation-module -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference | %FileCheck %s
// RUN: not %target-swift-frontend -typecheck -dump-ast -disable-objc-attr-requires-foundation-module %s -access-notes-path %t/attr_objc_access_note.accessnotes -swift-version 4 -enable-source-import -I %S/Inputs -enable-swift3-objc-inference > %t/attr_objc_2.ast
// RUN: %FileCheck -check-prefix CHECK-DUMP %s < %t/attr_objc_2.ast
// REQUIRES: objc_interop
// HOW TO WORK ON THIS TEST
//
// This file is primarily used to test '@objc' in source files, but it is also
// processed to produce test files for access notes, which can annotate
// declarations with '@objc' based on a sidecar file. This processing produces
// a source file with most of the '@objc' annotations removed, plus an access
// note file which adds back the removed '@objc' annotations. The three files
// are then tested in various combinations.
//
// The processing step uses the following special commands, which must appear
// at the beginning of a line comment to be recognized:
//
// * `access-note-adjust @±offset` (where the offset is optional) modifies the
// rest of the line comment to:
//
// 1. Change expected errors to expected remarks
// 2. Adjust the line offsets of all expected diagnostics by the offset
// 3. Change the phrase "marked @objc" to "marked @objc by an access note"
// 4. Change all expected fix-its to "{{none}}"
//
// * `access-note-move @±offset {{name}}` (where the offset is optional) can
// only appear immediately after an `@objc` or `@objc(someName)` attribute.
// It removes the attribute from the source code, adds a corresponding
// access note for `name` to the access note file, and does the same
// processing to the rest of the line as access-note-adjust. Note that in this
// case, the offset is @+1, not @+0, unless something else is specified.
//
// Note that, in some cases, we need additional access notes to be added that
// don't directly correspond to any attribute in the source code (usually
// because one @objc attribute covers several declarations). When this happens,
// we write a commented-out @objc attribute and use the `access-note-move`
// command.
import Foundation
class PlainClass {}
struct PlainStruct {}
enum PlainEnum {}
protocol PlainProtocol {} // expected-note {{protocol 'PlainProtocol' declared here}}
enum ErrorEnum : Error {
case failed
}
@objc // access-note-move{{Class_ObjC1}}
class Class_ObjC1 {}
protocol Protocol_Class1 : class {} // expected-note {{protocol 'Protocol_Class1' declared here}}
protocol Protocol_Class2 : class {}
@objc // access-note-move{{Protocol_ObjC1}}
protocol Protocol_ObjC1 {}
@objc // access-note-move{{Protocol_ObjC2}}
protocol Protocol_ObjC2 {}
//===--- Subjects of @objc attribute.
@objc // expected-error{{'@objc' can only be applied to an extension of a class}}{{1-7=}}
extension PlainStruct { }
class FáncyName {}
@objc(FancyName)
extension FáncyName {}
@objc // bad-access-note-move{{subject_globalVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_globalVar: Int
var subject_getterSetter: Int {
@objc // bad-access-note-move{{getter:subject_getterSetter()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
get {
return 0
}
@objc // bad-access-note-move{{setter:subject_getterSetter()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
set {
}
}
var subject_global_observingAccessorsVar1: Int = 0 {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
willSet {
}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
didSet {
}
}
class subject_getterSetter1 {
var instanceVar1: Int {
@objc // bad-access-note-move{{getter:subject_getterSetter1.instanceVar1()}} expected-error {{'@objc' getter for non-'@objc' property}} {{5-11=}}
get {
return 0
}
}
var instanceVar2: Int {
get {
return 0
}
@objc // bad-access-note-move{{setter:subject_getterSetter1.instanceVar2()}} expected-error {{'@objc' setter for non-'@objc' property}} {{5-11=}}
set {
}
}
var instanceVar3: Int {
@objc // bad-access-note-move{{getter:subject_getterSetter1.instanceVar3()}} expected-error {{'@objc' getter for non-'@objc' property}} {{5-11=}}
get {
return 0
}
@objc // bad-access-note-move{{setter:subject_getterSetter1.instanceVar3()}} expected-error {{'@objc' setter for non-'@objc' property}} {{5-11=}}
set {
}
}
var observingAccessorsVar1: Int = 0 {
@objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}}
willSet {
}
@objc // expected-error {{observing accessors are not allowed to be marked @objc}} {{5-11=}}
didSet {
}
}
}
class subject_staticVar1 {
@objc // access-note-move{{subject_staticVar1.staticVar1}}
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
@objc // access-note-move{{subject_staticVar1.staticVar2}}
class var staticVar2: Int { return 42 }
}
@objc // bad-access-note-move{{subject_freeFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}}
func subject_freeFunc() {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_localVar: Int
// expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_nestedFreeFunc() {
}
}
@objc // bad-access-note-move{{subject_genericFunc(t:)}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{1-7=}}
func subject_genericFunc<T>(t: T) {
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_localVar: Int
// expected-warning@-1 {{variable 'subject_localVar' was never used; consider replacing with '_' or removing it}}
@objc // expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
func subject_funcParam(a: @objc Int) { // expected-error {{attribute can only be applied to declarations, not types}} {{1-1=@objc }} {{27-33=}}
}
@objc // bad-access-note-move{{subject_struct}} expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_struct {
@objc // bad-access-note-move{{subject_struct.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_instanceVar: Int
@objc // bad-access-note-move{{subject_struct.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // bad-access-note-move{{subject_struct.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
@objc // bad-access-note-move{{subject_genericStruct}} expected-error {{'@objc' attribute cannot be applied to this declaration}} {{1-7=}}
struct subject_genericStruct<T> {
@objc // bad-access-note-move{{subject_genericStruct.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
var subject_instanceVar: Int
@objc // bad-access-note-move{{subject_genericStruct.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // bad-access-note-move{{subject_genericStruct.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
@objc // access-note-move{{subject_class1}}
class subject_class1 { // no-error
@objc // access-note-move{{subject_class1.subject_instanceVar}}
var subject_instanceVar: Int // no-error
@objc // access-note-move{{subject_class1.init()}}
init() {} // no-error
@objc // access-note-move{{subject_class1.subject_instanceFunc()}}
func subject_instanceFunc() {} // no-error
}
@objc // access-note-move{{subject_class2}}
class subject_class2 : Protocol_Class1, PlainProtocol { // no-error
}
@objc // bad-access-note-move{{subject_genericClass}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass<T> {
@objc // access-note-move{{subject_genericClass.subject_instanceVar}}
var subject_instanceVar: Int // no-error
@objc // access-note-move{{subject_genericClass.init()}}
init() {} // no-error
@objc // access-note-move{{subject_genericClass.subject_instanceFunc()}}
func subject_instanceFunc() {} // no_error
}
@objc // bad-access-note-move{{subject_genericClass2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class subject_genericClass2<T> : Class_ObjC1 {
@objc // access-note-move{{subject_genericClass2.subject_instanceVar}}
var subject_instanceVar: Int // no-error
@objc // access-note-move{{subject_genericClass2.init(foo:)}}
init(foo: Int) {} // no-error
@objc // access-note-move{{subject_genericClass2.subject_instanceFunc()}}
func subject_instanceFunc() {} // no_error
}
extension subject_genericClass where T : Hashable {
@objc // bad-access-note-move{{subject_genericClass.prop}}
var prop: Int { return 0 } // access-note-adjust{{@objc}} expected-error{{members of constrained extensions cannot be declared @objc}}
}
extension subject_genericClass {
@objc // bad-access-note-move{{subject_genericClass.extProp}}
var extProp: Int { return 0 } // access-note-adjust{{@objc}} expected-error{{extensions of generic classes cannot contain '@objc' members}}
@objc // bad-access-note-move{{subject_genericClass.extFoo()}}
func extFoo() {} // access-note-adjust{{@objc}} expected-error{{extensions of generic classes cannot contain '@objc' members}}
}
@objc // access-note-move{{subject_enum}}
enum subject_enum: Int {
@objc // bad-access-note-move{{subject_enum.subject_enumElement1}} expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement1
@objc(subject_enumElement2) // access-note-move{{subject_enum.subject_enumElement2}}
case subject_enumElement2
// Fake for access notes: @objc(subject_enumElement3) // bad-access-note-move@+2{{subject_enum.subject_enumElement4}}
@objc(subject_enumElement3) // bad-access-note-move{{subject_enum.subject_enumElement3}} expected-error {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}}{{3-31=}}
case subject_enumElement3, subject_enumElement4
// Because of the fake access-note-move above, we expect to see extra diagnostics when we run this test with both explicit @objc attributes *and* access notes:
// expected-remark@-2 * {{'@objc' enum case declaration defines multiple enum cases with the same Objective-C name}} expected-note@-2 *{{attribute 'objc' was added by access note for fancy tests}}
// Fake for access notes: @objc // bad-access-note-move@+2{{subject_enum.subject_enumElement6}}
@objc // bad-access-note-move{{subject_enum.subject_enumElement5}} expected-error {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} {{3-9=}}
case subject_enumElement5, subject_enumElement6
// Because of the fake access-note-move above, we expect to see extra diagnostics when we run this test with both explicit @objc attributes *and* access notes:
// expected-remark@-2 * {{attribute has no effect; cases within an '@objc' enum are already exposed to Objective-C}} expected-note@-2 *{{attribute 'objc' was added by access note for fancy tests}}
@nonobjc // expected-error {{'@nonobjc' attribute cannot be applied to this declaration}}
case subject_enumElement7
@objc // bad-access-note-move{{subject_enum.init()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
init() {}
@objc // bad-access-note-move{{subject_enum.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}} {{3-9=}}
func subject_instanceFunc() {}
}
enum subject_enum2 {
@objc(subject_enum2Element1) // bad-access-note-move{{subject_enum2.subject_enumElement1}} expected-error{{'@objc' enum case is not allowed outside of an '@objc' enum}}{{3-32=}}
case subject_enumElement1
}
@objc // access-note-move{{subject_protocol1}}
protocol subject_protocol1 {
@objc // access-note-move{{subject_protocol1.subject_instanceVar}}
var subject_instanceVar: Int { get }
@objc // access-note-move{{subject_protocol1.subject_instanceFunc()}}
func subject_instanceFunc()
}
@objc // access-note-move{{subject_protocol2}} // no-error
protocol subject_protocol2 {}
// CHECK-LABEL: @objc protocol subject_protocol2 {
@objc // access-note-move{{subject_protocol3}} // no-error
protocol subject_protocol3 {}
// CHECK-LABEL: @objc protocol subject_protocol3 {
@objc // access-note-move{{subject_protocol4}}
protocol subject_protocol4 : PlainProtocol {} // expected-error {{@objc protocol 'subject_protocol4' cannot refine non-@objc protocol 'PlainProtocol'}}
@objc // access-note-move{{subject_protocol5}}
protocol subject_protocol5 : Protocol_Class1 {} // expected-error {{@objc protocol 'subject_protocol5' cannot refine non-@objc protocol 'Protocol_Class1'}}
@objc // access-note-move{{subject_protocol6}}
protocol subject_protocol6 : Protocol_ObjC1 {}
protocol subject_containerProtocol1 {
@objc // bad-access-note-move{{subject_containerProtocol1.subject_instanceVar}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var subject_instanceVar: Int { get }
@objc // bad-access-note-move{{subject_containerProtocol1.subject_instanceFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
func subject_instanceFunc()
@objc // bad-access-note-move{{subject_containerProtocol1.subject_staticFunc()}} expected-error {{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
static func subject_staticFunc()
}
@objc // access-note-move{{subject_containerObjCProtocol1}}
protocol subject_containerObjCProtocol1 {
func func_FunctionReturn1() -> PlainStruct
// expected-error@-1 {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_FunctionParam1(a: PlainStruct)
// expected-error@-1 {{method cannot be a member of an @objc protocol because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
func func_Variadic(_: AnyObject...)
// expected-error @-1{{method cannot be a member of an @objc protocol because it has a variadic parameter}}
// expected-note @-2{{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
subscript(a: PlainStruct) -> Int { get }
// expected-error@-1 {{subscript cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
var varNonObjC1: PlainStruct { get }
// expected-error@-1 {{property cannot be a member of an @objc protocol because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// expected-note@-3 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
@objc // access-note-move{{subject_containerObjCProtocol2}}
protocol subject_containerObjCProtocol2 {
init(a: Int)
// expected-note@-1 {{'init' previously declared here}}
@objc // FIXME: Access notes can't distinguish between init(a:) overloads
init(a: Double)
// expected-warning@-1 {{initializer 'init(a:)' with Objective-C selector 'initWithA:' conflicts with previous declaration with the same Objective-C selector; this is an error in Swift 6}}
func func1() -> Int
@objc // access-note-move{{subject_containerObjCProtocol2.func1_()}}
func func1_() -> Int
var instanceVar1: Int { get set }
@objc // access-note-move{{subject_containerObjCProtocol2.instanceVar1_}}
var instanceVar1_: Int { get set }
subscript(i: Int) -> Int { get set }
@objc // FIXME: Access notes can't distinguish between subscript(_:) overloads
subscript(i: String) -> Int { get set}
}
protocol nonObjCProtocol {
@objc // bad-access-note-move{{nonObjCProtocol.objcRequirement()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
func objcRequirement()
}
func concreteContext1() {
@objc
class subject_inConcreteContext {}
}
class ConcreteContext2 {
@objc // access-note-move{{ConcreteContext2.subject_inConcreteContext}}
class subject_inConcreteContext {}
}
class ConcreteContext3 {
func dynamicSelf1() -> Self { return self }
@objc // access-note-move{{ConcreteContext3.dynamicSelf1_()}}
func dynamicSelf1_() -> Self { return self }
@objc // bad-access-note-move{{ConcreteContext3.genericParams()}}
func genericParams<T: NSObject>() -> [T] { return [] } // access-note-adjust{{@objc}} expected-error{{instance method cannot be marked @objc because it has generic parameters}}
@objc // bad-access-note-move{{ConcreteContext3.returnObjCProtocolMetatype()}}
func returnObjCProtocolMetatype() -> NSCoding.Protocol { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias AnotherNSCoding = NSCoding
typealias MetaNSCoding1 = NSCoding.Protocol
typealias MetaNSCoding2 = AnotherNSCoding.Protocol
@objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype1()}}
func returnObjCAliasProtocolMetatype1() -> AnotherNSCoding.Protocol { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype2()}}
func returnObjCAliasProtocolMetatype2() -> MetaNSCoding1 { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ConcreteContext3.returnObjCAliasProtocolMetatype3()}}
func returnObjCAliasProtocolMetatype3() -> MetaNSCoding2 { return NSCoding.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias Composition = NSCopying & NSCoding
@objc // bad-access-note-move{{ConcreteContext3.returnCompositionMetatype1()}}
func returnCompositionMetatype1() -> Composition.Protocol { return Composition.self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ConcreteContext3.returnCompositionMetatype2()}}
func returnCompositionMetatype2() -> (NSCopying & NSCoding).Protocol { return (NSCopying & NSCoding).self } // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
typealias NSCodingExistential = NSCoding.Type
@objc // bad-access-note-move{{ConcreteContext3.inoutFunc(a:)}}
func inoutFunc(a: inout Int) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because inout parameters cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ConcreteContext3.metatypeOfExistentialMetatypePram1(a:)}}
func metatypeOfExistentialMetatypePram1(a: NSCodingExistential.Protocol) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ConcreteContext3.metatypeOfExistentialMetatypePram2(a:)}}
func metatypeOfExistentialMetatypePram2(a: NSCoding.Type.Protocol) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
}
func genericContext1<T>(_: T) {
@objc // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {} // expected-error {{type 'subject_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc // expected-error {{generic subclasses of '@objc' classes cannot have an explicit '@objc'}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {} // expected-error {{type 'subject_inGenericContext2' cannot be nested in generic function 'genericContext1'}}
class subject_constructor_inGenericContext { // expected-error {{type 'subject_constructor_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
init() {} // no-error
}
class subject_var_inGenericContext { // expected-error {{type 'subject_var_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
var subject_instanceVar: Int = 0 // no-error
}
class subject_func_inGenericContext { // expected-error {{type 'subject_func_inGenericContext' cannot be nested in generic function 'genericContext1'}}
@objc
func f() {} // no-error
}
}
class GenericContext2<T> {
@objc // bad-access-note-move{{GenericContext2.subject_inGenericContext}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext {}
@objc // bad-access-note-move{{GenericContext2.subject_inGenericContext2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{3-9=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc // access-note-move{{GenericContext2.f()}}
func f() {} // no-error
}
class GenericContext3<T> {
class MoreNested {
@objc // bad-access-note-move{{GenericContext3.MoreNested.subject_inGenericContext}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext {}
@objc // bad-access-note-move{{GenericContext3.MoreNested.subject_inGenericContext2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{5-11=}}
class subject_inGenericContext2 : Class_ObjC1 {}
@objc // access-note-move{{GenericContext3.MoreNested.f()}}
func f() {} // no-error
}
}
class GenericContext4<T> {
@objc // bad-access-note-move{{GenericContext4.foo()}}
func foo() where T: Hashable { } // access-note-adjust{{@objc}} expected-error {{instance method cannot be marked @objc because it has a 'where' clause}}
}
@objc // bad-access-note-move{{ConcreteSubclassOfGeneric}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric {
@objc // access-note-move{{ConcreteSubclassOfGeneric.foo()}}
func foo() {} // okay
}
@objc // bad-access-note-move{{ConcreteSubclassOfGeneric2}} expected-error{{generic subclasses of '@objc' classes cannot have an explicit '@objc' because they are not directly visible from Objective-C}} {{1-7=}}
class ConcreteSubclassOfGeneric2 : subject_genericClass2<Int> {}
extension ConcreteSubclassOfGeneric2 {
@objc // access-note-move{{ConcreteSubclassOfGeneric2.foo()}}
func foo() {} // okay
}
@objc(CustomNameForSubclassOfGeneric) // access-note-move{{ConcreteSubclassOfGeneric3}} no-error
class ConcreteSubclassOfGeneric3 : GenericContext3<Int> {}
extension ConcreteSubclassOfGeneric3 {
@objc // access-note-move{{ConcreteSubclassOfGeneric3.foo()}}
func foo() {} // okay
}
class subject_subscriptIndexed1 {
@objc // access-note-move{{subject_subscriptIndexed1.subscript(_:)}}
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed2 {
@objc // access-note-move{{subject_subscriptIndexed2.subscript(_:)}}
subscript(a: Int8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptIndexed3 {
@objc // access-note-move{{subject_subscriptIndexed3.subscript(_:)}}
subscript(a: UInt8) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed1 {
@objc // access-note-move{{subject_subscriptKeyed1.subscript(_:)}}
subscript(a: String) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed2 {
@objc // access-note-move{{subject_subscriptKeyed2.subscript(_:)}}
subscript(a: Class_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed3 {
@objc // access-note-move{{subject_subscriptKeyed3.subscript(_:)}}
subscript(a: Class_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed4 {
@objc // access-note-move{{subject_subscriptKeyed4.subscript(_:)}}
subscript(a: Protocol_ObjC1) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed5 {
@objc // access-note-move{{subject_subscriptKeyed5.subscript(_:)}}
subscript(a: Protocol_ObjC1.Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed6 {
@objc // access-note-move{{subject_subscriptKeyed6.subscript(_:)}}
subscript(a: Protocol_ObjC1 & Protocol_ObjC2) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptKeyed7 {
@objc // access-note-move{{subject_subscriptKeyed7.subscript(_:)}}
subscript(a: (Protocol_ObjC1 & Protocol_ObjC2).Type) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptBridgedFloat {
@objc // access-note-move{{subject_subscriptBridgedFloat.subscript(_:)}}
subscript(a: Float32) -> Int {
get { return 0 }
}
}
class subject_subscriptGeneric<T> {
@objc // access-note-move{{subject_subscriptGeneric.subscript(_:)}}
subscript(a: Int) -> Int { // no-error
get { return 0 }
}
}
class subject_subscriptInvalid1 {
@objc // bad-access-note-move{{subject_subscriptInvalid1.subscript(_:)}}
class subscript(_ i: Int) -> AnyObject? { // access-note-adjust{{@objc}} expected-error {{class subscript cannot be marked @objc}}
return nil
}
}
class subject_subscriptInvalid2 {
@objc // bad-access-note-move{{subject_subscriptInvalid2.subscript(_:)}}
subscript(a: PlainClass) -> Int {
// access-note-adjust{{@objc}} expected-error@-1 {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid3 {
@objc // bad-access-note-move{{subject_subscriptInvalid3.subscript(_:)}}
subscript(a: PlainClass.Type) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid4 {
@objc // bad-access-note-move{{subject_subscriptInvalid4.subscript(_:)}}
subscript(a: PlainStruct) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid5 {
@objc // bad-access-note-move{{subject_subscriptInvalid5.subscript(_:)}}
subscript(a: PlainEnum) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{enums cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid6 {
@objc // bad-access-note-move{{subject_subscriptInvalid6.subscript(_:)}}
subscript(a: PlainProtocol) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid7 {
@objc // bad-access-note-move{{subject_subscriptInvalid7.subscript(_:)}}
subscript(a: Protocol_Class1) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_subscriptInvalid8 {
@objc // bad-access-note-move{{subject_subscriptInvalid8.subscript(_:)}}
subscript(a: Protocol_Class1 & Protocol_Class2) -> Int { // access-note-adjust{{@objc}} expected-error {{subscript cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
get { return 0 }
}
}
class subject_propertyInvalid1 {
@objc // bad-access-note-move{{subject_propertyInvalid1.plainStruct}}
let plainStruct = PlainStruct() // access-note-adjust{{@objc}} expected-error {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-1{{Swift structs cannot be represented in Objective-C}}
}
//===--- Tests for @objc inference.
@objc // access-note-move{{infer_instanceFunc1}}
class infer_instanceFunc1 {
// CHECK-LABEL: @objc class infer_instanceFunc1 {
func func1() {}
// CHECK-LABEL: @objc func func1() {
@objc // access-note-move{{infer_instanceFunc1.func1_()}}
func func1_() {} // no-error
func func2(a: Int) {}
// CHECK-LABEL: @objc func func2(a: Int) {
@objc // access-note-move{{infer_instanceFunc1.func2_(a:)}}
func func2_(a: Int) {} // no-error
func func3(a: Int) -> Int {}
// CHECK-LABEL: @objc func func3(a: Int) -> Int {
@objc // access-note-move{{infer_instanceFunc1.func3_(a:)}}
func func3_(a: Int) -> Int {} // no-error
func func4(a: Int, b: Double) {}
// CHECK-LABEL: @objc func func4(a: Int, b: Double) {
@objc // access-note-move{{infer_instanceFunc1.func4_(a:b:)}}
func func4_(a: Int, b: Double) {} // no-error
func func5(a: String) {}
// CHECK-LABEL: @objc func func5(a: String) {
@objc // access-note-move{{infer_instanceFunc1.func5_(a:)}}
func func5_(a: String) {} // no-error
func func6() -> String {}
// CHECK-LABEL: @objc func func6() -> String {
@objc // access-note-move{{infer_instanceFunc1.func6_()}}
func func6_() -> String {} // no-error
func func7(a: PlainClass) {}
// CHECK-LABEL: {{^}} func func7(a: PlainClass) {
@objc // bad-access-note-move{{infer_instanceFunc1.func7_(a:)}}
func func7_(a: PlainClass) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func7m(a: PlainClass.Type) {}
// CHECK-LABEL: {{^}} func func7m(a: PlainClass.Type) {
@objc // bad-access-note-move{{infer_instanceFunc1.func7m_(a:)}}
func func7m_(a: PlainClass.Type) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
func func8() -> PlainClass {}
// CHECK-LABEL: {{^}} func func8() -> PlainClass {
@objc // bad-access-note-move{{infer_instanceFunc1.func8_()}}
func func8_() -> PlainClass {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
func func8m() -> PlainClass.Type {}
// CHECK-LABEL: {{^}} func func8m() -> PlainClass.Type {
@objc // bad-access-note-move{{infer_instanceFunc1.func8m_()}}
func func8m_() -> PlainClass.Type {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
func func9(a: PlainStruct) {}
// CHECK-LABEL: {{^}} func func9(a: PlainStruct) {
@objc // bad-access-note-move{{infer_instanceFunc1.func9_(a:)}}
func func9_(a: PlainStruct) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func10() -> PlainStruct {}
// CHECK-LABEL: {{^}} func func10() -> PlainStruct {
@objc // bad-access-note-move{{infer_instanceFunc1.func10_()}}
func func10_() -> PlainStruct {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
func func11(a: PlainEnum) {}
// CHECK-LABEL: {{^}} func func11(a: PlainEnum) {
@objc // bad-access-note-move{{infer_instanceFunc1.func11_(a:)}}
func func11_(a: PlainEnum) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
func func12(a: PlainProtocol) {}
// CHECK-LABEL: {{^}} func func12(a: PlainProtocol) {
@objc // bad-access-note-move{{infer_instanceFunc1.func12_(a:)}}
func func12_(a: PlainProtocol) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
func func13(a: Class_ObjC1) {}
// CHECK-LABEL: @objc func func13(a: Class_ObjC1) {
@objc // access-note-move{{infer_instanceFunc1.func13_(a:)}}
func func13_(a: Class_ObjC1) {} // no-error
func func14(a: Protocol_Class1) {}
// CHECK-LABEL: {{^}} func func14(a: Protocol_Class1) {
@objc // bad-access-note-move{{infer_instanceFunc1.func14_(a:)}}
func func14_(a: Protocol_Class1) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
func func15(a: Protocol_ObjC1) {}
// CHECK-LABEL: @objc func func15(a: Protocol_ObjC1) {
@objc // access-note-move{{infer_instanceFunc1.func15_(a:)}}
func func15_(a: Protocol_ObjC1) {} // no-error
func func16(a: AnyObject) {}
// CHECK-LABEL: @objc func func16(a: AnyObject) {
@objc // access-note-move{{infer_instanceFunc1.func16_(a:)}}
func func16_(a: AnyObject) {} // no-error
func func17(a: @escaping () -> ()) {}
// CHECK-LABEL: {{^}} @objc func func17(a: @escaping () -> ()) {
@objc // access-note-move{{infer_instanceFunc1.func17_(a:)}}
func func17_(a: @escaping () -> ()) {}
func func18(a: @escaping (Int) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func18(a: @escaping (Int) -> (), b: Int)
@objc // access-note-move{{infer_instanceFunc1.func18_(a:b:)}}
func func18_(a: @escaping (Int) -> (), b: Int) {}
func func19(a: @escaping (String) -> (), b: Int) {}
// CHECK-LABEL: {{^}} @objc func func19(a: @escaping (String) -> (), b: Int) {
@objc // access-note-move{{infer_instanceFunc1.func19_(a:b:)}}
func func19_(a: @escaping (String) -> (), b: Int) {}
func func_FunctionReturn1() -> () -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn1() -> () -> () {
@objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn1_()}}
func func_FunctionReturn1_() -> () -> () {}
func func_FunctionReturn2() -> (Int) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn2() -> (Int) -> () {
@objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn2_()}}
func func_FunctionReturn2_() -> (Int) -> () {}
func func_FunctionReturn3() -> () -> Int {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn3() -> () -> Int {
@objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn3_()}}
func func_FunctionReturn3_() -> () -> Int {}
func func_FunctionReturn4() -> (String) -> () {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn4() -> (String) -> () {
@objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn4_()}}
func func_FunctionReturn4_() -> (String) -> () {}
func func_FunctionReturn5() -> () -> String {}
// CHECK-LABEL: {{^}} @objc func func_FunctionReturn5() -> () -> String {
@objc // access-note-move{{infer_instanceFunc1.func_FunctionReturn5_()}}
func func_FunctionReturn5_() -> () -> String {}
func func_ZeroParams1() {}
// CHECK-LABEL: @objc func func_ZeroParams1() {
@objc // access-note-move{{infer_instanceFunc1.func_ZeroParams1a()}}
func func_ZeroParams1a() {} // no-error
func func_OneParam1(a: Int) {}
// CHECK-LABEL: @objc func func_OneParam1(a: Int) {
@objc // access-note-move{{infer_instanceFunc1.func_OneParam1a(a:)}}
func func_OneParam1a(a: Int) {} // no-error
func func_TupleStyle1(a: Int, b: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle1(a: Int, b: Int) {
@objc // access-note-move{{infer_instanceFunc1.func_TupleStyle1a(a:b:)}}
func func_TupleStyle1a(a: Int, b: Int) {}
func func_TupleStyle2(a: Int, b: Int, c: Int) {}
// CHECK-LABEL: {{^}} @objc func func_TupleStyle2(a: Int, b: Int, c: Int) {
@objc // access-note-move{{infer_instanceFunc1.func_TupleStyle2a(a:b:c:)}}
func func_TupleStyle2a(a: Int, b: Int, c: Int) {}
// Check that we produce diagnostics for every parameter and return type.
@objc // bad-access-note-move{{infer_instanceFunc1.func_MultipleDiags(a:b:)}}
func func_MultipleDiags(a: PlainStruct, b: PlainEnum) -> Any {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter 1 cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// access-note-adjust{{@objc}} expected-error@-3 {{method cannot be marked @objc because the type of the parameter 2 cannot be represented in Objective-C}}
// expected-note@-4 {{non-'@objc' enums cannot be represented in Objective-C}}
// Produces an extra: expected-note@-5 * {{attribute 'objc' was added by access note for fancy tests}}
@objc // access-note-move{{infer_instanceFunc1.func_UnnamedParam1(_:)}}
func func_UnnamedParam1(_: Int) {} // no-error
@objc // bad-access-note-move{{infer_instanceFunc1.func_UnnamedParam2(_:)}}
func func_UnnamedParam2(_: PlainStruct) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
@objc // access-note-move{{infer_instanceFunc1.func_varParam1(a:)}}
func func_varParam1(a: AnyObject) {
var a = a
let b = a; a = b
}
func func_varParam2(a: AnyObject) {
var a = a
let b = a; a = b
}
// CHECK-LABEL: @objc func func_varParam2(a: AnyObject) {
}
@objc // access-note-move{{infer_constructor1}}
class infer_constructor1 {
// CHECK-LABEL: @objc class infer_constructor1
init() {}
// CHECK: @objc init()
init(a: Int) {}
// CHECK: @objc init(a: Int)
init(a: PlainStruct) {}
// CHECK: {{^}} init(a: PlainStruct)
init(malice: ()) {}
// CHECK: @objc init(malice: ())
init(forMurder _: ()) {}
// CHECK: @objc init(forMurder _: ())
}
@objc // access-note-move{{infer_destructor1}}
class infer_destructor1 {
// CHECK-LABEL: @objc class infer_destructor1
deinit {}
// CHECK: @objc deinit
}
// @!objc
class infer_destructor2 {
// CHECK-LABEL: {{^}}class infer_destructor2
deinit {}
// CHECK: @objc deinit
}
@objc // access-note-move{{infer_instanceVar1}}
class infer_instanceVar1 {
// CHECK-LABEL: @objc class infer_instanceVar1 {
init() {}
var instanceVar1: Int
// CHECK: @objc var instanceVar1: Int
var (instanceVar2, instanceVar3): (Int, PlainProtocol)
// CHECK: @objc var instanceVar2: Int
// CHECK: {{^}} var instanceVar3: PlainProtocol
@objc // bad-access-note-move{{infer_instanceVar1.instanceVar1_}}
var (instanceVar1_, instanceVar2_): (Int, PlainProtocol)
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
// Fake for access notes: @objc // access-note-move@-3{{infer_instanceVar1.instanceVar2_}}
var instanceVar4: Int {
// CHECK: @objc var instanceVar4: Int {
get {}
// CHECK-NEXT: @objc get {}
}
var instanceVar5: Int {
// CHECK: @objc var instanceVar5: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
@objc // access-note-move{{infer_instanceVar1.instanceVar5_}}
var instanceVar5_: Int {
// CHECK: @objc var instanceVar5_: Int {
get {}
// CHECK-NEXT: @objc get {}
set {}
// CHECK-NEXT: @objc set {}
}
var observingAccessorsVar1: Int {
// CHECK: @_hasStorage @objc var observingAccessorsVar1: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get {
// CHECK-NEXT: return
// CHECK-NEXT: }
didSet {}
// CHECK-NEXT: {{^}} @objc set {
}
@objc // access-note-move{{infer_instanceVar1.observingAccessorsVar1_}}
var observingAccessorsVar1_: Int {
// CHECK: {{^}} @objc @_hasStorage var observingAccessorsVar1_: Int {
willSet {}
// CHECK-NEXT: {{^}} @objc get {
// CHECK-NEXT: return
// CHECK-NEXT: }
didSet {}
// CHECK-NEXT: {{^}} @objc set {
}
var var_Int: Int
// CHECK-LABEL: @objc var var_Int: Int
var var_Bool: Bool
// CHECK-LABEL: @objc var var_Bool: Bool
var var_CBool: CBool
// CHECK-LABEL: @objc var var_CBool: CBool
var var_String: String
// CHECK-LABEL: @objc var var_String: String
var var_Float: Float
var var_Double: Double
// CHECK-LABEL: @objc var var_Float: Float
// CHECK-LABEL: @objc var var_Double: Double
var var_Char: Unicode.Scalar
// CHECK-LABEL: @objc var var_Char: Unicode.Scalar
//===--- Tuples.
var var_tuple1: ()
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple1: ()
@objc // bad-access-note-move{{infer_instanceVar1.var_tuple1_}}
var var_tuple1_: ()
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple2: Void
// CHECK-LABEL: {{^}} @_hasInitialValue var var_tuple2: Void
@objc // bad-access-note-move{{infer_instanceVar1.var_tuple2_}}
var var_tuple2_: Void
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{empty tuple type cannot be represented in Objective-C}}
var var_tuple3: (Int)
// CHECK-LABEL: @objc var var_tuple3: (Int)
@objc // access-note-move{{infer_instanceVar1.var_tuple3_}}
var var_tuple3_: (Int) // no-error
var var_tuple4: (Int, Int)
// CHECK-LABEL: {{^}} var var_tuple4: (Int, Int)
@objc // bad-access-note-move{{infer_instanceVar1.var_tuple4_}}
var var_tuple4_: (Int, Int)
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{tuples cannot be represented in Objective-C}}
//===--- Stdlib integer types.
var var_Int8: Int8
var var_Int16: Int16
var var_Int32: Int32
var var_Int64: Int64
// CHECK-LABEL: @objc var var_Int8: Int8
// CHECK-LABEL: @objc var var_Int16: Int16
// CHECK-LABEL: @objc var var_Int32: Int32
// CHECK-LABEL: @objc var var_Int64: Int64
var var_UInt8: UInt8
var var_UInt16: UInt16
var var_UInt32: UInt32
var var_UInt64: UInt64
// CHECK-LABEL: @objc var var_UInt8: UInt8
// CHECK-LABEL: @objc var var_UInt16: UInt16
// CHECK-LABEL: @objc var var_UInt32: UInt32
// CHECK-LABEL: @objc var var_UInt64: UInt64
var var_OpaquePointer: OpaquePointer
// CHECK-LABEL: @objc var var_OpaquePointer: OpaquePointer
var var_PlainClass: PlainClass
// CHECK-LABEL: {{^}} var var_PlainClass: PlainClass
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainClass_}}
var var_PlainClass_: PlainClass
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{classes not annotated with @objc cannot be represented in Objective-C}}
var var_PlainStruct: PlainStruct
// CHECK-LABEL: {{^}} var var_PlainStruct: PlainStruct
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainStruct_}}
var var_PlainStruct_: PlainStruct
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
var var_PlainEnum: PlainEnum
// CHECK-LABEL: {{^}} var var_PlainEnum: PlainEnum
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainEnum_}}
var var_PlainEnum_: PlainEnum
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{non-'@objc' enums cannot be represented in Objective-C}}
var var_PlainProtocol: PlainProtocol
// CHECK-LABEL: {{^}} var var_PlainProtocol: PlainProtocol
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainProtocol_}}
var var_PlainProtocol_: PlainProtocol
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_ClassObjC: Class_ObjC1
// CHECK-LABEL: @objc var var_ClassObjC: Class_ObjC1
@objc // access-note-move{{infer_instanceVar1.var_ClassObjC_}}
var var_ClassObjC_: Class_ObjC1 // no-error
var var_ProtocolClass: Protocol_Class1
// CHECK-LABEL: {{^}} var var_ProtocolClass: Protocol_Class1
@objc // bad-access-note-move{{infer_instanceVar1.var_ProtocolClass_}}
var var_ProtocolClass_: Protocol_Class1
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_ProtocolObjC: Protocol_ObjC1
// CHECK-LABEL: @objc var var_ProtocolObjC: Protocol_ObjC1
@objc // access-note-move{{infer_instanceVar1.var_ProtocolObjC_}}
var var_ProtocolObjC_: Protocol_ObjC1 // no-error
var var_PlainClassMetatype: PlainClass.Type
// CHECK-LABEL: {{^}} var var_PlainClassMetatype: PlainClass.Type
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainClassMetatype_}}
var var_PlainClassMetatype_: PlainClass.Type
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainStructMetatype: PlainStruct.Type
// CHECK-LABEL: {{^}} var var_PlainStructMetatype: PlainStruct.Type
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainStructMetatype_}}
var var_PlainStructMetatype_: PlainStruct.Type
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainEnumMetatype: PlainEnum.Type
// CHECK-LABEL: {{^}} var var_PlainEnumMetatype: PlainEnum.Type
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainEnumMetatype_}}
var var_PlainEnumMetatype_: PlainEnum.Type
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_PlainExistentialMetatype: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_PlainExistentialMetatype: PlainProtocol.Type
@objc // bad-access-note-move{{infer_instanceVar1.var_PlainExistentialMetatype_}}
var var_PlainExistentialMetatype_: PlainProtocol.Type
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ClassObjCMetatype: Class_ObjC1.Type
// CHECK-LABEL: @objc var var_ClassObjCMetatype: Class_ObjC1.Type
@objc // access-note-move{{infer_instanceVar1.var_ClassObjCMetatype_}}
var var_ClassObjCMetatype_: Class_ObjC1.Type // no-error
var var_ProtocolClassMetatype: Protocol_Class1.Type
// CHECK-LABEL: {{^}} var var_ProtocolClassMetatype: Protocol_Class1.Type
@objc // bad-access-note-move{{infer_instanceVar1.var_ProtocolClassMetatype_}}
var var_ProtocolClassMetatype_: Protocol_Class1.Type
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype1: Protocol_ObjC1.Type
@objc // access-note-move{{infer_instanceVar1.var_ProtocolObjCMetatype1_}}
var var_ProtocolObjCMetatype1_: Protocol_ObjC1.Type // no-error
var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
// CHECK-LABEL: @objc var var_ProtocolObjCMetatype2: Protocol_ObjC2.Type
@objc // access-note-move{{infer_instanceVar1.var_ProtocolObjCMetatype2_}}
var var_ProtocolObjCMetatype2_: Protocol_ObjC2.Type // no-error
var var_AnyObject1: AnyObject
var var_AnyObject2: AnyObject.Type
// CHECK-LABEL: @objc var var_AnyObject1: AnyObject
// CHECK-LABEL: @objc var var_AnyObject2: AnyObject.Type
var var_Existential0: Any
// CHECK-LABEL: @objc var var_Existential0: Any
@objc // access-note-move{{infer_instanceVar1.var_Existential0_}}
var var_Existential0_: Any
var var_Existential1: PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential1: PlainProtocol
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential1_}}
var var_Existential1_: PlainProtocol
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential2: PlainProtocol & PlainProtocol
// CHECK-LABEL: {{^}} var var_Existential2: PlainProtocol
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential2_}}
var var_Existential2_: PlainProtocol & PlainProtocol
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential3: PlainProtocol & Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential3: PlainProtocol & Protocol_Class1
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential3_}}
var var_Existential3_: PlainProtocol & Protocol_Class1
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential4: PlainProtocol & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential4: PlainProtocol & Protocol_ObjC1
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential4_}}
var var_Existential4_: PlainProtocol & Protocol_ObjC1
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'PlainProtocol' cannot be represented in Objective-C}}
var var_Existential5: Protocol_Class1
// CHECK-LABEL: {{^}} var var_Existential5: Protocol_Class1
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential5_}}
var var_Existential5_: Protocol_Class1
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential6: Protocol_Class1 & Protocol_Class2
// CHECK-LABEL: {{^}} var var_Existential6: Protocol_Class1 & Protocol_Class2
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential6_}}
var var_Existential6_: Protocol_Class1 & Protocol_Class2
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential7: Protocol_Class1 & Protocol_ObjC1
// CHECK-LABEL: {{^}} var var_Existential7: Protocol_Class1 & Protocol_ObjC1
@objc // bad-access-note-move{{infer_instanceVar1.var_Existential7_}}
var var_Existential7_: Protocol_Class1 & Protocol_ObjC1
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{protocol-constrained type containing protocol 'Protocol_Class1' cannot be represented in Objective-C}}
var var_Existential8: Protocol_ObjC1
// CHECK-LABEL: @objc var var_Existential8: Protocol_ObjC1
@objc // access-note-move{{infer_instanceVar1.var_Existential8_}}
var var_Existential8_: Protocol_ObjC1 // no-error
var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc var var_Existential9: Protocol_ObjC1 & Protocol_ObjC2
@objc // access-note-move{{infer_instanceVar1.var_Existential9_}}
var var_Existential9_: Protocol_ObjC1 & Protocol_ObjC2 // no-error
var var_ExistentialMetatype0: Any.Type
var var_ExistentialMetatype1: PlainProtocol.Type
var var_ExistentialMetatype2: (PlainProtocol & PlainProtocol).Type
var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
var var_ExistentialMetatype5: (Protocol_Class1).Type
var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
var var_ExistentialMetatype8: Protocol_ObjC1.Type
var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype0: Any.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype1: PlainProtocol.Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype2: (PlainProtocol).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype3: (PlainProtocol & Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype4: (PlainProtocol & Protocol_ObjC1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype5: (Protocol_Class1).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype6: (Protocol_Class1 & Protocol_Class2).Type
// CHECK-LABEL: {{^}} var var_ExistentialMetatype7: (Protocol_Class1 & Protocol_ObjC1).Type
// CHECK-LABEL: @objc var var_ExistentialMetatype8: Protocol_ObjC1.Type
// CHECK-LABEL: @objc var var_ExistentialMetatype9: (Protocol_ObjC1 & Protocol_ObjC2).Type
var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer1: UnsafeMutablePointer<Int>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer2: UnsafeMutablePointer<Bool>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer3: UnsafeMutablePointer<CBool>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer4: UnsafeMutablePointer<String>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer5: UnsafeMutablePointer<Float>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer6: UnsafeMutablePointer<Double>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer7: UnsafeMutablePointer<OpaquePointer>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer8: UnsafeMutablePointer<PlainClass>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer9: UnsafeMutablePointer<PlainStruct>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer10: UnsafeMutablePointer<PlainEnum>
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer11: UnsafeMutablePointer<PlainProtocol>
// CHECK-LABEL: @objc var var_UnsafeMutablePointer12: UnsafeMutablePointer<AnyObject>
// CHECK-LABEL: var var_UnsafeMutablePointer13: UnsafeMutablePointer<AnyObject.Type>
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer100: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} @objc var var_UnsafeMutablePointer101: UnsafeMutableRawPointer
// CHECK-LABEL: {{^}} var var_UnsafeMutablePointer102: UnsafeMutablePointer<(Int, Int)>
var var_Optional1: Class_ObjC1?
var var_Optional2: Protocol_ObjC1?
var var_Optional3: Class_ObjC1.Type?
var var_Optional4: Protocol_ObjC1.Type?
var var_Optional5: AnyObject?
var var_Optional6: AnyObject.Type?
var var_Optional7: String?
var var_Optional8: Protocol_ObjC1?
var var_Optional9: Protocol_ObjC1.Type?
var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
var var_Optional12: OpaquePointer?
var var_Optional13: UnsafeMutablePointer<Int>?
var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional1: Class_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional2: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional3: Class_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional4: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional5: AnyObject?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional6: AnyObject.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional7: String?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional8: Protocol_ObjC1?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional9: Protocol_ObjC1.Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional10: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional11: (Protocol_ObjC1 & Protocol_ObjC2).Type?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional12: OpaquePointer?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional13: UnsafeMutablePointer<Int>?
// CHECK-LABEL: @objc @_hasInitialValue var var_Optional14: UnsafeMutablePointer<Class_ObjC1>?
var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
var var_ImplicitlyUnwrappedOptional5: AnyObject!
var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
var var_ImplicitlyUnwrappedOptional7: String!
var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional1: Class_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional2: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional3: Class_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional4: Protocol_ObjC1.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional5: AnyObject!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional6: AnyObject.Type!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional7: String!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional8: Protocol_ObjC1!
// CHECK-LABEL: @objc @_hasInitialValue var var_ImplicitlyUnwrappedOptional9: (Protocol_ObjC1 & Protocol_ObjC2)!
var var_Optional_fail1: PlainClass?
var var_Optional_fail2: PlainClass.Type?
var var_Optional_fail3: PlainClass!
var var_Optional_fail4: PlainStruct?
var var_Optional_fail5: PlainStruct.Type?
var var_Optional_fail6: PlainEnum?
var var_Optional_fail7: PlainEnum.Type?
var var_Optional_fail8: PlainProtocol?
var var_Optional_fail10: PlainProtocol?
var var_Optional_fail11: (PlainProtocol & Protocol_ObjC1)?
var var_Optional_fail12: Int?
var var_Optional_fail13: Bool?
var var_Optional_fail14: CBool?
var var_Optional_fail20: AnyObject??
var var_Optional_fail21: AnyObject.Type??
var var_Optional_fail22: ComparisonResult? // a non-bridged imported value type
var var_Optional_fail23: NSRange? // a bridged struct imported from C
// CHECK-NOT: @objc{{.*}}Optional_fail
// CHECK-LABEL: @objc var var_CFunctionPointer_1: @convention(c) () -> ()
var var_CFunctionPointer_1: @convention(c) () -> ()
// CHECK-LABEL: @objc var var_CFunctionPointer_invalid_1: Int
var var_CFunctionPointer_invalid_1: @convention(c) Int // expected-error {{@convention attribute only applies to function types}}
// CHECK-LABEL: {{^}} var var_CFunctionPointer_invalid_2: <<error type>>
var var_CFunctionPointer_invalid_2: @convention(c) (PlainStruct) -> Int // expected-error {{'(PlainStruct) -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
// <rdar://problem/20918869> Confusing diagnostic for @convention(c) throws
var var_CFunctionPointer_invalid_3 : @convention(c) (Int) throws -> Int // expected-error {{'(Int) throws -> Int' is not representable in Objective-C, so it cannot be used with '@convention(c)'}}
weak var var_Weak1: Class_ObjC1?
weak var var_Weak2: Protocol_ObjC1?
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//weak var var_Weak3: Class_ObjC1.Type?
//weak var var_Weak4: Protocol_ObjC1.Type?
weak var var_Weak5: AnyObject?
//weak var var_Weak6: AnyObject.Type?
weak var var_Weak7: Protocol_ObjC1?
weak var var_Weak8: (Protocol_ObjC1 & Protocol_ObjC2)?
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak1: @sil_weak Class_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak2: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak5: @sil_weak AnyObject
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak7: @sil_weak Protocol_ObjC1
// CHECK-LABEL: @objc @_hasInitialValue weak var var_Weak8: @sil_weak (Protocol_ObjC1 & Protocol_ObjC2)?
weak var var_Weak_fail1: PlainClass?
weak var var_Weak_bad2: PlainStruct?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
weak var var_Weak_bad3: PlainEnum?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
weak var var_Weak_bad4: String?
// expected-error@-1 {{'weak' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Weak_fail
unowned var var_Unowned1: Class_ObjC1
unowned var var_Unowned2: Protocol_ObjC1
// <rdar://problem/16473062> weak and unowned variables of metatypes are rejected
//unowned var var_Unowned3: Class_ObjC1.Type
//unowned var var_Unowned4: Protocol_ObjC1.Type
unowned var var_Unowned5: AnyObject
//unowned var var_Unowned6: AnyObject.Type
unowned var var_Unowned7: Protocol_ObjC1
unowned var var_Unowned8: Protocol_ObjC1 & Protocol_ObjC2
// CHECK-LABEL: @objc unowned var var_Unowned1: @sil_unowned Class_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned2: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned5: @sil_unowned AnyObject
// CHECK-LABEL: @objc unowned var var_Unowned7: @sil_unowned Protocol_ObjC1
// CHECK-LABEL: @objc unowned var var_Unowned8: @sil_unowned Protocol_ObjC1 & Protocol_ObjC2
unowned var var_Unowned_fail1: PlainClass
unowned var var_Unowned_bad2: PlainStruct
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainStruct'}}
unowned var var_Unowned_bad3: PlainEnum
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'PlainEnum'}}
unowned var var_Unowned_bad4: String
// expected-error@-1 {{'unowned' may only be applied to class and class-bound protocol types, not 'String'}}
// CHECK-NOT: @objc{{.*}}Unowned_fail
var var_FunctionType1: () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType1: () -> ()
var var_FunctionType2: (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType2: (Int) -> ()
var var_FunctionType3: (Int) -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionType3: (Int) -> Int
var var_FunctionType4: (Int, Double) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType4: (Int, Double) -> ()
var var_FunctionType5: (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType5: (String) -> ()
var var_FunctionType6: () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionType6: () -> String
var var_FunctionType7: (PlainClass) -> ()
// CHECK-NOT: @objc var var_FunctionType7: (PlainClass) -> ()
var var_FunctionType8: () -> PlainClass
// CHECK-NOT: @objc var var_FunctionType8: () -> PlainClass
var var_FunctionType9: (PlainStruct) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType9: (PlainStruct) -> ()
var var_FunctionType10: () -> PlainStruct
// CHECK-LABEL: {{^}} var var_FunctionType10: () -> PlainStruct
var var_FunctionType11: (PlainEnum) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType11: (PlainEnum) -> ()
var var_FunctionType12: (PlainProtocol) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType12: (PlainProtocol) -> ()
var var_FunctionType13: (Class_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType13: (Class_ObjC1) -> ()
var var_FunctionType14: (Protocol_Class1) -> ()
// CHECK-LABEL: {{^}} var var_FunctionType14: (Protocol_Class1) -> ()
var var_FunctionType15: (Protocol_ObjC1) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType15: (Protocol_ObjC1) -> ()
var var_FunctionType16: (AnyObject) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType16: (AnyObject) -> ()
var var_FunctionType17: (() -> ()) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType17: (() -> ()) -> ()
var var_FunctionType18: ((Int) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType18: ((Int) -> (), Int) -> ()
var var_FunctionType19: ((String) -> (), Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionType19: ((String) -> (), Int) -> ()
var var_FunctionTypeReturn1: () -> () -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn1: () -> () -> ()
@objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn1_}}
var var_FunctionTypeReturn1_: () -> () -> () // no-error
var var_FunctionTypeReturn2: () -> (Int) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn2: () -> (Int) -> ()
@objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn2_}}
var var_FunctionTypeReturn2_: () -> (Int) -> () // no-error
var var_FunctionTypeReturn3: () -> () -> Int
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn3: () -> () -> Int
@objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn3_}}
var var_FunctionTypeReturn3_: () -> () -> Int // no-error
var var_FunctionTypeReturn4: () -> (String) -> ()
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn4: () -> (String) -> ()
@objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn4_}}
var var_FunctionTypeReturn4_: () -> (String) -> () // no-error
var var_FunctionTypeReturn5: () -> () -> String
// CHECK-LABEL: {{^}} @objc var var_FunctionTypeReturn5: () -> () -> String
@objc // access-note-move{{infer_instanceVar1.var_FunctionTypeReturn5_}}
var var_FunctionTypeReturn5_: () -> () -> String // no-error
var var_BlockFunctionType1: @convention(block) () -> ()
// CHECK-LABEL: @objc var var_BlockFunctionType1: @convention(block) () -> ()
@objc // access-note-move{{infer_instanceVar1.var_BlockFunctionType1_}}
var var_BlockFunctionType1_: @convention(block) () -> () // no-error
var var_ArrayType1: [AnyObject]
// CHECK-LABEL: {{^}} @objc var var_ArrayType1: [AnyObject]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType1_}}
var var_ArrayType1_: [AnyObject] // no-error
var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType2: [@convention(block) (AnyObject) -> AnyObject]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType2_}}
var var_ArrayType2_: [@convention(block) (AnyObject) -> AnyObject] // no-error
var var_ArrayType3: [PlainStruct]
// CHECK-LABEL: {{^}} var var_ArrayType3: [PlainStruct]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType3_}}
var var_ArrayType3_: [PlainStruct]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType4: [(AnyObject) -> AnyObject] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType4: [(AnyObject) -> AnyObject]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType4_}}
var var_ArrayType4_: [(AnyObject) -> AnyObject]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType5: [Protocol_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType5: [Protocol_ObjC1]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType5_}}
var var_ArrayType5_: [Protocol_ObjC1] // no-error
var var_ArrayType6: [Class_ObjC1]
// CHECK-LABEL: {{^}} @objc var var_ArrayType6: [Class_ObjC1]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType6_}}
var var_ArrayType6_: [Class_ObjC1] // no-error
var var_ArrayType7: [PlainClass]
// CHECK-LABEL: {{^}} var var_ArrayType7: [PlainClass]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType7_}}
var var_ArrayType7_: [PlainClass]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType8: [PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType8: [PlainProtocol]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType8_}}
var var_ArrayType8_: [PlainProtocol]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType9: [Protocol_ObjC1 & PlainProtocol]
// CHECK-LABEL: {{^}} var var_ArrayType9: [PlainProtocol & Protocol_ObjC1]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType9_}}
var var_ArrayType9_: [Protocol_ObjC1 & PlainProtocol]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
// CHECK-LABEL: {{^}} @objc var var_ArrayType10: [Protocol_ObjC1 & Protocol_ObjC2]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType10_}}
var var_ArrayType10_: [Protocol_ObjC1 & Protocol_ObjC2]
// no-error
var var_ArrayType11: [Any]
// CHECK-LABEL: @objc var var_ArrayType11: [Any]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType11_}}
var var_ArrayType11_: [Any]
var var_ArrayType13: [Any?]
// CHECK-LABEL: {{^}} var var_ArrayType13: [Any?]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType13_}}
var var_ArrayType13_: [Any?]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType15: [AnyObject?]
// CHECK-LABEL: {{^}} var var_ArrayType15: [AnyObject?]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType15_}}
var var_ArrayType15_: [AnyObject?]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
var var_ArrayType16: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} @objc var var_ArrayType16: {{\[}}[@convention(block) (AnyObject) -> AnyObject]]
@objc // access-note-move{{infer_instanceVar1.var_ArrayType16_}}
var var_ArrayType16_: [[@convention(block) (AnyObject) -> AnyObject]] // no-error
var var_ArrayType17: [[(AnyObject) -> AnyObject]] // no-error
// CHECK-LABEL: {{^}} var var_ArrayType17: {{\[}}[(AnyObject) -> AnyObject]]
@objc // bad-access-note-move{{infer_instanceVar1.var_ArrayType17_}}
var var_ArrayType17_: [[(AnyObject) -> AnyObject]]
// access-note-adjust{{@objc}} expected-error @-1{{property cannot be marked @objc because its type cannot be represented in Objective-C}}
}
@objc // access-note-move{{ObjCBase}}
class ObjCBase {}
class infer_instanceVar2<
GP_Unconstrained,
GP_PlainClass : PlainClass,
GP_PlainProtocol : PlainProtocol,
GP_Class_ObjC : Class_ObjC1,
GP_Protocol_Class : Protocol_Class1,
GP_Protocol_ObjC : Protocol_ObjC1> : ObjCBase {
// CHECK-LABEL: class infer_instanceVar2<{{.*}}> : ObjCBase where {{.*}} {
override init() {}
var var_GP_Unconstrained: GP_Unconstrained
// CHECK-LABEL: {{^}} var var_GP_Unconstrained: GP_Unconstrained
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_Unconstrained_}}
var var_GP_Unconstrained_: GP_Unconstrained
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainClass: GP_PlainClass
// CHECK-LABEL: {{^}} var var_GP_PlainClass: GP_PlainClass
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_PlainClass_}}
var var_GP_PlainClass_: GP_PlainClass
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_PlainProtocol: GP_PlainProtocol
// CHECK-LABEL: {{^}} var var_GP_PlainProtocol: GP_PlainProtocol
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_PlainProtocol_}}
var var_GP_PlainProtocol_: GP_PlainProtocol
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Class_ObjC: GP_Class_ObjC
// CHECK-LABEL: {{^}} var var_GP_Class_ObjC: GP_Class_ObjC
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_Class_ObjC_}}
var var_GP_Class_ObjC_: GP_Class_ObjC
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_Class: GP_Protocol_Class
// CHECK-LABEL: {{^}} var var_GP_Protocol_Class: GP_Protocol_Class
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_Protocol_Class_}}
var var_GP_Protocol_Class_: GP_Protocol_Class
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
var var_GP_Protocol_ObjC: GP_Protocol_ObjC
// CHECK-LABEL: {{^}} var var_GP_Protocol_ObjC: GP_Protocol_ObjC
@objc // bad-access-note-move{{infer_instanceVar2.var_GP_Protocol_ObjCa}}
var var_GP_Protocol_ObjCa: GP_Protocol_ObjC
// access-note-adjust{{@objc}} expected-error@-1 {{property cannot be marked @objc because its type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
func func_GP_Unconstrained(a: GP_Unconstrained) {}
// CHECK-LABEL: {{^}} func func_GP_Unconstrained(a: GP_Unconstrained) {
@objc // bad-access-note-move{{infer_instanceVar2.func_GP_Unconstrained_(a:)}}
func func_GP_Unconstrained_(a: GP_Unconstrained) {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc // bad-access-note-move{{infer_instanceVar2.func_GP_Unconstrained_()}}
func func_GP_Unconstrained_() -> GP_Unconstrained {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
@objc // bad-access-note-move{{infer_instanceVar2.func_GP_Class_ObjC__()}}
func func_GP_Class_ObjC__() -> GP_Class_ObjC {}
// access-note-adjust{{@objc}} expected-error@-1 {{method cannot be marked @objc because its result type cannot be represented in Objective-C}}
// expected-note@-2 {{generic type parameters cannot be represented in Objective-C}}
}
class infer_instanceVar3 : Class_ObjC1 {
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_instanceVar3 : Class_ObjC1 {
var v1: Int = 0
// CHECK-LABEL: @objc @_hasInitialValue var v1: Int
}
@objc // access-note-move{{infer_instanceVar4}}
protocol infer_instanceVar4 {
// CHECK-LABEL: @objc protocol infer_instanceVar4 {
var v1: Int { get }
// CHECK-LABEL: @objc var v1: Int { get }
}
// @!objc
class infer_instanceVar5 {
// CHECK-LABEL: {{^}}class infer_instanceVar5 {
@objc // access-note-move{{infer_instanceVar5.instanceVar1}}
var instanceVar1: Int {
// CHECK: @objc var instanceVar1: Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc // access-note-move{{infer_staticVar1}}
class infer_staticVar1 {
// CHECK-LABEL: @objc class infer_staticVar1 {
class var staticVar1: Int = 42 // expected-error {{class stored properties not supported}}
// CHECK: @objc @_hasInitialValue class var staticVar1: Int
}
// @!objc
class infer_subscript1 {
// CHECK-LABEL: class infer_subscript1
@objc // access-note-move{{infer_subscript1.subscript(_:)}}
subscript(i: Int) -> Int {
// CHECK: @objc subscript(i: Int) -> Int
get {}
// CHECK: @objc get {}
set {}
// CHECK: @objc set {}
}
}
@objc // access-note-move{{infer_throughConformanceProto1}}
protocol infer_throughConformanceProto1 {
// CHECK-LABEL: @objc protocol infer_throughConformanceProto1 {
func funcObjC1()
var varObjC1: Int { get }
var varObjC2: Int { get set }
// CHECK: @objc func funcObjC1()
// CHECK: @objc var varObjC1: Int { get }
// CHECK: @objc var varObjC2: Int { get set }
}
class infer_class1 : PlainClass {}
// CHECK-LABEL: {{^}}@_inheritsConvenienceInitializers class infer_class1 : PlainClass {
class infer_class2 : Class_ObjC1 {}
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class2 : Class_ObjC1 {
class infer_class3 : infer_class2 {}
// CHECK-LABEL: @objc @_inheritsConvenienceInitializers class infer_class3 : infer_class2 {
class infer_class4 : Protocol_Class1 {}
// CHECK-LABEL: {{^}}class infer_class4 : Protocol_Class1 {
class infer_class5 : Protocol_ObjC1 {}
// CHECK-LABEL: {{^}}class infer_class5 : Protocol_ObjC1 {
//
// If a protocol conforms to an @objc protocol, this does not infer @objc on
// the protocol itself, or on the newly introduced requirements. Only the
// inherited @objc requirements get @objc.
//
// Same rule applies to classes.
//
protocol infer_protocol1 {
// CHECK-LABEL: {{^}}protocol infer_protocol1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol2 : Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol2 : Protocol_Class1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol3 : Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol3 : Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
// CHECK-LABEL: {{^}}protocol infer_protocol4 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
protocol infer_protocol5 : Protocol_ObjC1, Protocol_Class1 {
// CHECK-LABEL: {{^}}protocol infer_protocol5 : Protocol_Class1, Protocol_ObjC1 {
func nonObjC1()
// CHECK: {{^}} func nonObjC1()
}
class C {
// Don't crash.
@objc func foo(x: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}}
@IBAction func myAction(sender: Undeclared) {} // expected-error {{cannot find type 'Undeclared' in scope}}
@IBSegueAction func myAction(coder: Undeclared, sender: Undeclared) -> Undeclared {fatalError()} // expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}} expected-error {{cannot find type 'Undeclared' in scope}}
}
//===---
//===--- @IBOutlet implies @objc
//===---
class HasIBOutlet {
// CHECK-LABEL: {{^}}class HasIBOutlet {
init() {}
@IBOutlet weak var goodOutlet: Class_ObjC1!
// CHECK-LABEL: {{^}} @objc @IBOutlet @_hasInitialValue weak var goodOutlet: @sil_weak Class_ObjC1!
@IBOutlet var badOutlet: PlainStruct
// expected-error@-1 {{@IBOutlet property cannot have non-object type 'PlainStruct'}} {{3-13=}}
// expected-error@-2 {{@IBOutlet property has non-optional type 'PlainStruct'}}
// expected-note@-3 {{add '?' to form the optional type 'PlainStruct?'}}
// expected-note@-4 {{add '!' to form an implicitly unwrapped optional}}
// CHECK-LABEL: {{^}} @IBOutlet var badOutlet: PlainStruct
}
//===---
//===--- @IBAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBAction {
class HasIBAction {
@IBAction func goodAction(_ sender: AnyObject?) { }
// CHECK: {{^}} @objc @IBAction @MainActor func goodAction(_ sender: AnyObject?) {
@IBAction func badAction(_ sender: PlainStruct?) { }
// expected-error@-1{{method cannot be marked @IBAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @IBSegueAction implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBSegueAction {
class HasIBSegueAction {
@IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject {fatalError()}
// CHECK: {{^}} @objc @IBSegueAction func goodSegueAction(_ coder: AnyObject) -> AnyObject {
@IBSegueAction func badSegueAction(_ coder: PlainStruct?) -> Int? {fatalError()}
// expected-error@-1{{method cannot be marked @IBSegueAction because the type of the parameter cannot be represented in Objective-C}}
}
//===---
//===--- @IBInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasIBInspectable {
class HasIBInspectable {
@IBInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @IBInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @GKInspectable implies @objc
//===---
// CHECK-LABEL: {{^}}class HasGKInspectable {
class HasGKInspectable {
@GKInspectable var goodProperty: AnyObject?
// CHECK: {{^}} @objc @GKInspectable @_hasInitialValue var goodProperty: AnyObject?
}
//===---
//===--- @NSManaged implies @objc
//===---
class HasNSManaged {
// CHECK-LABEL: {{^}}class HasNSManaged {
init() {}
@NSManaged
var goodManaged: Class_ObjC1
// CHECK-LABEL: {{^}} @objc @NSManaged dynamic var goodManaged: Class_ObjC1 {
// CHECK-NEXT: {{^}} @objc get
// CHECK-NEXT: {{^}} @objc set
// CHECK-NEXT: {{^}} }
@NSManaged
var badManaged: PlainStruct
// expected-error@-1 {{property cannot be marked @NSManaged because its type cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @NSManaged dynamic var badManaged: PlainStruct {
// CHECK-NEXT: {{^}} get
// CHECK-NEXT: {{^}} set
// CHECK-NEXT: {{^}} }
}
//===---
//===--- Pointer argument types
//===---
@objc // access-note-move{{TakesCPointers}}
class TakesCPointers {
// CHECK-LABEL: {{^}}@objc class TakesCPointers {
func constUnsafeMutablePointer(p: UnsafePointer<Int>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointer(p: UnsafePointer<Int>) {
func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToAnyObject(p: UnsafePointer<AnyObject>) {
func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {}
// CHECK-LABEL: @objc func constUnsafeMutablePointerToClass(p: UnsafePointer<TakesCPointers>) {
func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {}
// CHECK-LABEL: @objc func mutableUnsafeMutablePointer(p: UnsafeMutablePointer<Int>) {
func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableStrongUnsafeMutablePointerToAnyObject(p: UnsafeMutablePointer<AnyObject>) {
func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {}
// CHECK-LABEL: {{^}} @objc func mutableAutoreleasingUnsafeMutablePointerToAnyObject(p: AutoreleasingUnsafeMutablePointer<AnyObject>) {
}
// @objc with nullary names
@objc(NSObjC2) // access-note-move{{Class_ObjC2}}
class Class_ObjC2 {
// CHECK-LABEL: @objc(NSObjC2) class Class_ObjC2
@objc(initWithMalice) // access-note-move{{Class_ObjC2.init(foo:)}}
init(foo: ()) { }
@objc(initWithIntent) // access-note-move{{Class_ObjC2.init(bar:)}}
init(bar _: ()) { }
@objc(initForMurder) // access-note-move{{Class_ObjC2.init()}}
init() { }
@objc(isFoo) // access-note-move{{Class_ObjC2.foo()}}
func foo() -> Bool {}
// CHECK-LABEL: @objc(isFoo) func foo() -> Bool {
}
@objc() // expected-error {{expected name within parentheses of @objc attribute}}
class Class_ObjC3 {
}
// @objc with selector names
extension PlainClass {
// CHECK-LABEL: @objc(setFoo:) dynamic func
@objc(setFoo:) // access-note-move{{PlainClass.foo(b:)}}
func foo(b: Bool) { }
// CHECK-LABEL: @objc(setWithRed:green:blue:alpha:) dynamic func set
@objc(setWithRed:green:blue:alpha:) // access-note-move{{PlainClass.set(_:green:blue:alpha:)}}
func set(_: Float, green: Float, blue: Float, alpha: Float) { }
// CHECK-LABEL: @objc(createWithRed:green:blue:alpha:) dynamic class func createWith
@objc(createWithRed:green blue:alpha)
class func createWithRed(_: Float, green: Float, blue: Float, alpha: Float) { }
// expected-error@-2{{missing ':' after selector piece in @objc attribute}}{{28-28=:}}
// expected-error@-3{{missing ':' after selector piece in @objc attribute}}{{39-39=:}}
// CHECK-LABEL: @objc(::) dynamic func badlyNamed
@objc(::) // access-note-move{{PlainClass.badlyNamed(_:y:)}}
func badlyNamed(_: Int, y: Int) {}
}
@objc(Class:) // bad-access-note-move{{BadClass1}} expected-error{{'@objc' class must have a simple name}}{{12-13=}}
class BadClass1 { }
@objc(Protocol:) // bad-access-note-move{{BadProto1}} expected-error{{'@objc' protocol must have a simple name}}{{15-16=}}
protocol BadProto1 { }
@objc(Enum:) // bad-access-note-move{{BadEnum1}} expected-error{{'@objc' enum must have a simple name}}{{11-12=}}
enum BadEnum1: Int { case X }
@objc // access-note-move{{BadEnum2}}
enum BadEnum2: Int {
@objc(X:) // bad-access-note-move{{BadEnum2.X}} expected-error{{'@objc' enum case must have a simple name}}{{10-11=}}
case X
}
class BadClass2 {
@objc(realDealloc) // expected-error{{'@objc' deinitializer cannot have a name}}
deinit { }
@objc(badprop:foo:wibble:) // bad-access-note-move{{BadClass2.badprop}} expected-error{{'@objc' property must have a simple name}}{{16-28=}}
var badprop: Int = 5
@objc(foo) // bad-access-note-move{{BadClass2.subscript(_:)}} expected-error{{'@objc' subscript cannot have a name; did you mean to put the name on the getter or setter?}}
subscript (i: Int) -> Int {
get {
return i
}
}
@objc(foo) // bad-access-note-move{{BadClass2.noArgNamesOneParam(x:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam(x: Int) { }
@objc(foo) // bad-access-note-move{{BadClass2.noArgNamesOneParam2(_:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter}}
func noArgNamesOneParam2(_: Int) { }
@objc(foo) // bad-access-note-move{{BadClass2.noArgNamesTwoParams(_:y:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters}}
func noArgNamesTwoParams(_: Int, y: Int) { }
@objc(foo:) // bad-access-note-move{{BadClass2.oneArgNameTwoParams(_:y:)}} expected-error{{'@objc' method name provides one argument name, but method has 2 parameters}}
func oneArgNameTwoParams(_: Int, y: Int) { }
@objc(foo:) // bad-access-note-move{{BadClass2.oneArgNameNoParams()}} expected-error{{'@objc' method name provides one argument name, but method has 0 parameters}}
func oneArgNameNoParams() { }
@objc(foo:) // bad-access-note-move{{BadClass2.init()}} expected-error{{'@objc' initializer name provides one argument name, but initializer has 0 parameters}}
init() { }
var _prop = 5
@objc // access-note-move{{BadClass2.prop}}
var prop: Int {
@objc(property) // access-note-move{{getter:BadClass2.prop()}}
get { return _prop }
@objc(setProperty:) // access-note-move{{setter:BadClass2.prop()}}
set { _prop = newValue }
}
var prop2: Int {
@objc(property) // bad-access-note-move{{getter:BadClass2.prop2()}} expected-error{{'@objc' getter for non-'@objc' property}} {{5-21=}}
get { return _prop }
@objc(setProperty:) // bad-access-note-move{{setter:BadClass2.prop2()}} expected-error{{'@objc' setter for non-'@objc' property}} {{5-25=}}
set { _prop = newValue }
}
var prop3: Int {
@objc(setProperty:) // expected-error{{observing accessors are not allowed to be marked @objc}} {{5-25=}}
didSet { }
}
}
// FIXME: This could be part of BadClass except that access notes can't
// distinguish between overloads of `subscript(_:)`.
class GoodClass {
@objc // access-note-move{{GoodClass.subscript(_:)}}
subscript (c: Class_ObjC1) -> Class_ObjC1 {
@objc(getAtClass:) // access-note-move{{getter:GoodClass.subscript(_:)}}
get {
return c
}
@objc(setAtClass:class:) // access-note-move{{setter:GoodClass.subscript(_:)}}
set {
}
}
}
// Swift overrides that aren't also @objc overrides.
class Super {
@objc(renamedFoo) // access-note-move{{Super.foo}}
var foo: Int { get { return 3 } } // expected-note 2{{overridden declaration is here}}
@objc // access-note-move{{Super.process(i:)}}
func process(i: Int) -> Int { } // expected-note {{overriding '@objc' method 'process(i:)' here}}
}
class Sub1 : Super {
@objc(foo) // bad-access-note-move{{Sub1.foo}} expected-error{{Objective-C property has a different name from the property it overrides ('foo' vs. 'renamedFoo')}}{{9-12=renamedFoo}}
override var foo: Int { get { return 5 } }
override func process(i: Int?) -> Int { } // expected-error{{method cannot be an @objc override because the type of the parameter cannot be represented in Objective-C}}
}
class Sub2 : Super {
@objc // bad-access-note-move{{Sub2.foo}} -- @objc is already implied by overriding an @objc attribute, so access notes shouldn't emit a remark
override var foo: Int { get { return 5 } }
}
class Sub3 : Super {
override var foo: Int { get { return 5 } }
}
class Sub4 : Super {
@objc(renamedFoo) // access-note-move{{Sub4.foo}}
override var foo: Int { get { return 5 } }
}
class Sub5 : Super {
@objc(wrongFoo) // bad-access-note-move{{Sub5.foo}} expected-error{{Objective-C property has a different name from the property it overrides ('wrongFoo' vs. 'renamedFoo')}} {{9-17=renamedFoo}}
override var foo: Int { get { return 5 } }
}
enum NotObjCEnum { case X }
struct NotObjCStruct {}
// Closure arguments can only be @objc if their parameters and returns are.
// CHECK-LABEL: @objc class ClosureArguments
@objc // access-note-move{{ClosureArguments}}
class ClosureArguments {
// CHECK: @objc func foo
@objc // access-note-move{{ClosureArguments.foo(f:)}}
func foo(f: (Int) -> ()) {}
// CHECK: @objc func bar
@objc // bad-access-note-move{{ClosureArguments.bar(f:)}}
func bar(f: (NotObjCEnum) -> NotObjCStruct) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func bas
@objc // bad-access-note-move{{ClosureArguments.bas(f:)}}
func bas(f: (NotObjCEnum) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zim
@objc // bad-access-note-move{{ClosureArguments.zim(f:)}}
func zim(f: () -> NotObjCStruct) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func zang
@objc // bad-access-note-move{{ClosureArguments.zang(f:)}}
func zang(f: (NotObjCEnum, NotObjCStruct) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
@objc // bad-access-note-move{{ClosureArguments.zangZang(f:)}}
func zangZang(f: (Int...) -> ()) {} // access-note-adjust{{@objc}} expected-error{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}} expected-note{{function types cannot be represented in Objective-C unless their parameters and returns can be}}
// CHECK: @objc func fooImplicit
func fooImplicit(f: (Int) -> ()) {}
// CHECK: {{^}} func barImplicit
func barImplicit(f: (NotObjCEnum) -> NotObjCStruct) {}
// CHECK: {{^}} func basImplicit
func basImplicit(f: (NotObjCEnum) -> ()) {}
// CHECK: {{^}} func zimImplicit
func zimImplicit(f: () -> NotObjCStruct) {}
// CHECK: {{^}} func zangImplicit
func zangImplicit(f: (NotObjCEnum, NotObjCStruct) -> ()) {}
// CHECK: {{^}} func zangZangImplicit
func zangZangImplicit(f: (Int...) -> ()) {}
}
typealias GoodBlock = @convention(block) (Int) -> ()
typealias BadBlock = @convention(block) (NotObjCEnum) -> () // expected-error{{'(NotObjCEnum) -> ()' is not representable in Objective-C, so it cannot be used with '@convention(block)'}}
@objc // access-note-move{{AccessControl}}
class AccessControl {
// CHECK: @objc func foo
func foo() {}
// CHECK: {{^}} private func bar
private func bar() {}
// CHECK: @objc private func baz
@objc // access-note-move{{AccessControl.baz()}}
private func baz() {}
}
//===--- Ban @objc +load methods
class Load1 {
// Okay: not @objc
class func load() { }
class func alloc() {}
class func allocWithZone(_: Int) {}
class func initialize() {}
}
@objc // access-note-move{{Load2}}
class Load2 {
class func load() { } // expected-error {{method 'load()' defines Objective-C class method 'load', which is not permitted by Swift}}
class func alloc() {} // expected-error {{method 'alloc()' defines Objective-C class method 'alloc', which is not permitted by Swift}}
class func allocWithZone(_: Int) {} // expected-error {{method 'allocWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
class func initialize() {} // expected-error {{method 'initialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
@objc // access-note-move{{Load3}}
class Load3 {
class var load: Load3 {
get { return Load3() } // expected-error {{getter for 'load' defines Objective-C class method 'load', which is not permitted by Swift}}
set { }
}
@objc(alloc) // access-note-move{{Load3.prop}}
class var prop: Int { return 0 } // expected-error {{getter for 'prop' defines Objective-C class method 'alloc', which is not permitted by Swift}}
@objc(allocWithZone:) // access-note-move{{Load3.fooWithZone(_:)}}
class func fooWithZone(_: Int) {} // expected-error {{method 'fooWithZone' defines Objective-C class method 'allocWithZone:', which is not permitted by Swift}}
@objc(initialize) // access-note-move{{Load3.barnitialize()}}
class func barnitialize() {} // expected-error {{method 'barnitialize()' defines Objective-C class method 'initialize', which is not permitted by Swift}}
}
// Members of protocol extensions cannot be @objc
extension PlainProtocol {
@objc // bad-access-note-move{{PlainProtocol.property}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var property: Int { return 5 }
@objc // bad-access-note-move{{PlainProtocol.subscript(_:)}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() }
@objc // bad-access-note-move{{PlainProtocol.fun()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
func fun() { }
}
extension Protocol_ObjC1 {
@objc // bad-access-note-move{{Protocol_ObjC1.property}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
var property: Int { return 5 }
@objc // bad-access-note-move{{Protocol_ObjC1.subscript(_:)}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
subscript(x: Int) -> Class_ObjC1 { return Class_ObjC1() }
@objc // bad-access-note-move{{Protocol_ObjC1.fun()}} expected-error{{@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes}}
func fun() { }
}
extension Protocol_ObjC1 {
// Don't infer @objc for extensions of @objc protocols.
// CHECK: {{^}} var propertyOK: Int
var propertyOK: Int { return 5 }
}
//===---
//===--- Error handling
//===---
class ClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
@objc // access-note-move{{ClassThrows1.methodReturnsVoid()}}
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
@objc // access-note-move{{ClassThrows1.methodReturnsObjCClass()}}
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
@objc // access-note-move{{ClassThrows1.methodReturnsBridged()}}
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
@objc // access-note-move{{ClassThrows1.methodReturnsArray()}}
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: @objc init(degrees: Double) throws
@objc // access-note-move{{ClassThrows1.init(degrees:)}}
init(degrees: Double) throws { }
// Errors
@objc // bad-access-note-move{{ClassThrows1.methodReturnsOptionalObjCClass()}}
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of optional type 'Class_ObjC1?'; 'nil' indicates failure to Objective-C}}
@objc // bad-access-note-move{{ClassThrows1.methodReturnsOptionalArray()}}
func methodReturnsOptionalArray() throws -> [String]? { return nil } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of optional type '[String]?'; 'nil' indicates failure to Objective-C}}
@objc // bad-access-note-move{{ClassThrows1.methodReturnsInt()}}
func methodReturnsInt() throws -> Int { return 0 } // access-note-adjust{{@objc}} expected-error{{throwing method cannot be marked @objc because it returns a value of type 'Int'; return 'Void' or a type that bridges to an Objective-C class}}
@objc // bad-access-note-move{{ClassThrows1.methodAcceptsThrowingFunc(fn:)}}
func methodAcceptsThrowingFunc(fn: (String) throws -> Int) { }
// access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{throwing function types cannot be represented in Objective-C}}
@objc // bad-access-note-move{{ClassThrows1.init(radians:)}}
init?(radians: Double) throws { } // access-note-adjust{{@objc}} expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc // bad-access-note-move{{ClassThrows1.init(string:)}}
init!(string: String) throws { } // access-note-adjust{{@objc}} expected-error{{a failable and throwing initializer cannot be marked @objc because 'nil' indicates failure to Objective-C}}
@objc // bad-access-note-move{{ClassThrows1.fooWithErrorEnum1(x:)}}
func fooWithErrorEnum1(x: ErrorEnum) {}
// access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{non-'@objc' enums cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorEnum2(x: ErrorEnum)
func fooWithErrorEnum2(x: ErrorEnum) {}
@objc // bad-access-note-move{{ClassThrows1.fooWithErrorProtocolComposition1(x:)}}
func fooWithErrorProtocolComposition1(x: Error & Protocol_ObjC1) { }
// access-note-adjust{{@objc}} expected-error@-1{{method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2{{protocol-constrained type containing 'Error' cannot be represented in Objective-C}}
// CHECK: {{^}} func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1)
func fooWithErrorProtocolComposition2(x: Error & Protocol_ObjC1) { }
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"ImplicitClassThrows1"
@objc // access-note-move{{ImplicitClassThrows1}}
class ImplicitClassThrows1 {
// CHECK: @objc func methodReturnsVoid() throws
// CHECK-DUMP: func_decl{{.*}}"methodReturnsVoid()"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodReturnsVoid() throws { }
// CHECK: @objc func methodReturnsObjCClass() throws -> Class_ObjC1
// CHECK-DUMP: func_decl{{.*}}"methodReturnsObjCClass()" {{.*}}foreign_error=NilResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
func methodReturnsObjCClass() throws -> Class_ObjC1 {
return Class_ObjC1()
}
// CHECK: @objc func methodReturnsBridged() throws -> String
func methodReturnsBridged() throws -> String { return String() }
// CHECK: @objc func methodReturnsArray() throws -> [String]
func methodReturnsArray() throws -> [String] { return [String]() }
// CHECK: {{^}} func methodReturnsOptionalObjCClass() throws -> Class_ObjC1?
func methodReturnsOptionalObjCClass() throws -> Class_ObjC1? { return nil }
// CHECK: @objc func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int)
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int, fn3: @escaping (Int) -> Int) throws { }
// CHECK: @objc init(degrees: Double) throws
// CHECK-DUMP: constructor_decl{{.*}}"init(degrees:)"{{.*}}foreign_error=NilResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>
init(degrees: Double) throws { }
// CHECK: {{^}} func methodReturnsBridgedValueType() throws -> NSRange
func methodReturnsBridgedValueType() throws -> NSRange { return NSRange() }
@objc // bad-access-note-move{{ImplicitClassThrows1.methodReturnsBridgedValueType2()}}
func methodReturnsBridgedValueType2() throws -> NSRange {
return NSRange()
}
// access-note-adjust{{@objc}} expected-error@-3{{throwing method cannot be marked @objc because it returns a value of type 'NSRange' (aka '_NSRange'); return 'Void' or a type that bridges to an Objective-C class}}
// CHECK: {{^}} @objc func methodReturnsError() throws -> Error
func methodReturnsError() throws -> Error { return ErrorEnum.failed }
// CHECK: @objc func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int)
func methodReturnStaticBridged() throws -> ((Int) -> (Int) -> Int) {
func add(x: Int) -> (Int) -> Int {
return { x + $0 }
}
}
}
// CHECK-DUMP-LABEL: class_decl{{.*}}"SubclassImplicitClassThrows1"
@objc // access-note-move{{SubclassImplicitClassThrows1}}
class SubclassImplicitClassThrows1 : ImplicitClassThrows1 {
// CHECK: @objc override func methodWithTrailingClosures(_ s: String, fn1: @escaping ((Int) -> Int), fn2: @escaping ((Int) -> Int), fn3: @escaping ((Int) -> Int))
// CHECK-DUMP: func_decl{{.*}}"methodWithTrailingClosures(_:fn1:fn2:fn3:)"{{.*}}foreign_error=ZeroResult,unowned,param=1,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func methodWithTrailingClosures(_ s: String, fn1: (@escaping (Int) -> Int), fn2: (@escaping (Int) -> Int), fn3: (@escaping (Int) -> Int)) throws { }
}
class ThrowsRedecl1 {
@objc // access-note-move{{ThrowsRedecl1.method1(_:error:)}}
func method1(_ x: Int, error: Class_ObjC1) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.method1(_:)}}
func method1(_ x: Int) throws { } // access-note-adjust{{@objc}} expected-error {{method 'method1' with Objective-C selector 'method1:error:' conflicts with method 'method1(_:error:)' with the same Objective-C selector}}
@objc // access-note-move{{ThrowsRedecl1.method2AndReturnError(_:)}}
func method2AndReturnError(_ x: Int) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.method2()}}
func method2() throws { } // access-note-adjust{{@objc}} expected-error {{method 'method2()' with Objective-C selector 'method2AndReturnError:' conflicts with method 'method2AndReturnError' with the same Objective-C selector}}
@objc // access-note-move{{ThrowsRedecl1.method3(_:error:closure:)}}
func method3(_ x: Int, error: Int, closure: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.method3(_:closure:)}}
func method3(_ x: Int, closure: (Int) -> Int) throws { } // access-note-adjust{{@objc}} expected-error {{method 'method3(_:closure:)' with Objective-C selector 'method3:error:closure:' conflicts with method 'method3(_:error:closure:)' with the same Objective-C selector}}
@objc(initAndReturnError:) // access-note-move{{ThrowsRedecl1.initMethod1(error:)}}
func initMethod1(error: Int) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.init()}}
init() throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init()' with Objective-C selector 'initAndReturnError:' conflicts with method 'initMethod1(error:)' with the same Objective-C selector}}
@objc(initWithString:error:) // access-note-move{{ThrowsRedecl1.initMethod2(string:error:)}}
func initMethod2(string: String, error: Int) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.init(string:)}}
init(string: String) throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init(string:)' with Objective-C selector 'initWithString:error:' conflicts with method 'initMethod2(string:error:)' with the same Objective-C selector}}
@objc(initAndReturnError:fn:) // access-note-move{{ThrowsRedecl1.initMethod3(error:fn:)}}
func initMethod3(error: Int, fn: @escaping (Int) -> Int) { } // expected-note{{declared here}}
@objc // bad-access-note-move{{ThrowsRedecl1.init(fn:)}}
init(fn: (Int) -> Int) throws { } // access-note-adjust{{@objc}} expected-error {{initializer 'init(fn:)' with Objective-C selector 'initAndReturnError:fn:' conflicts with method 'initMethod3(error:fn:)' with the same Objective-C selector}}
}
class ThrowsObjCName {
@objc(method4:closure:error:) // access-note-move{{ThrowsObjCName.method4(x:closure:)}}
func method4(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method5AndReturnError:x:closure:) // access-note-move{{ThrowsObjCName.method5(x:closure:)}}
func method5(x: Int, closure: @escaping (Int) -> Int) throws { }
@objc(method6) // bad-access-note-move{{ThrowsObjCName.method6()}} expected-error{{'@objc' method name provides names for 0 arguments, but method has one parameter (the error parameter)}}
func method6() throws { }
@objc(method7) // bad-access-note-move{{ThrowsObjCName.method7(x:)}} expected-error{{'@objc' method name provides names for 0 arguments, but method has 2 parameters (including the error parameter)}}
func method7(x: Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method8:fn1:error:fn2:) // access-note-move{{ThrowsObjCName.method8(_:fn1:fn2:)}}
func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
@objc(method9AndReturnError:s:fn1:fn2:) // access-note-move{{ThrowsObjCName.method9(_:fn1:fn2:)}}
func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
class SubclassThrowsObjCName : ThrowsObjCName {
// CHECK-DUMP: func_decl{{.*}}"method8(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=2,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method8(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
// CHECK-DUMP: func_decl{{.*}}"method9(_:fn1:fn2:)"{{.*}}foreign_error=ZeroResult,unowned,param=0,paramtype=Optional<AutoreleasingUnsafeMutablePointer<Optional<NSError>>>,resulttype=ObjCBool
override func method9(_ s: String, fn1: (@escaping (Int) -> Int), fn2: @escaping (Int) -> Int) throws { }
}
@objc // access-note-move{{ProtocolThrowsObjCName}}
protocol ProtocolThrowsObjCName {
@objc // Access notes don't allow the `optional` keyword, that's fine, honestly.
optional func doThing(_ x: String) throws -> String // expected-note{{requirement 'doThing' declared here}}
}
class ConformsToProtocolThrowsObjCName1 : ProtocolThrowsObjCName {
@objc // bad-access-note-move{{ConformsToProtocolThrowsObjCName1.doThing(_:)}} -- @objc inherited, so no remarks
func doThing(_ x: String) throws -> String { return x } // okay
}
class ConformsToProtocolThrowsObjCName2 : ProtocolThrowsObjCName {
@objc // access-note-move{{ConformsToProtocolThrowsObjCName2.doThing(_:)}}
func doThing(_ x: Int) throws -> String { return "" }
// expected-warning@-1{{instance method 'doThing' nearly matches optional requirement 'doThing' of protocol 'ProtocolThrowsObjCName'}}
// expected-note@-2{{move 'doThing' to an extension to silence this warning}}
// expected-note@-3{{make 'doThing' private to silence this warning}}{{3-3=private }}
// expected-note@-4{{candidate has non-matching type '(Int) throws -> String'}}
}
@objc // access-note-move{{DictionaryTest}}
class DictionaryTest {
// CHECK-LABEL: @objc func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>)
func func_dictionary1a(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
// CHECK-LABEL: @objc func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>)
@objc // access-note-move{{DictionaryTest.func_dictionary1b(x:)}}
func func_dictionary1b(x: Dictionary<ObjC_Class1, ObjC_Class1>) { }
func func_dictionary2a(x: Dictionary<String, Int>) { }
@objc // access-note-move{{DictionaryTest.func_dictionary2b(x:)}}
func func_dictionary2b(x: Dictionary<String, Int>) { }
}
@objc
extension PlainClass {
// CHECK-LABEL: @objc final func objc_ext_objc_okay(_: Int) {
final func objc_ext_objc_okay(_: Int) { }
final func objc_ext_objc_not_okay(_: PlainStruct) { }
// expected-error@-1{{method cannot be in an @objc extension of a class (without @nonobjc) because the type of the parameter cannot be represented in Objective-C}}
// expected-note@-2 {{Swift structs cannot be represented in Objective-C}}
// CHECK-LABEL: {{^}} @nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) {
@nonobjc final func objc_ext_objc_explicit_nonobjc(_: PlainStruct) { }
}
@objc // access-note-move{{ObjC_Class1}}
class ObjC_Class1 : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(lhs: ObjC_Class1, rhs: ObjC_Class1) -> Bool {
return true
}
// CHECK-LABEL: @objc class OperatorInClass
@objc // access-note-move{{OperatorInClass}}
class OperatorInClass {
// CHECK: {{^}} static func == (lhs: OperatorInClass, rhs: OperatorInClass) -> Bool
static func ==(lhs: OperatorInClass, rhs: OperatorInClass) -> Bool {
return true
}
// CHECK: {{^}} @objc static func + (lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass
@objc
static func +(lhs: OperatorInClass, rhs: OperatorInClass) -> OperatorInClass { // expected-error {{operator methods cannot be declared @objc}}
return lhs
}
} // CHECK: {{^}$}}
@objc // access-note-move{{OperatorInProtocol}}
protocol OperatorInProtocol {
static func +(lhs: Self, rhs: Self) -> Self // expected-error {{@objc protocols must not have operator requirements}}
}
class AdoptsOperatorInProtocol : OperatorInProtocol {
static func +(lhs: AdoptsOperatorInProtocol, rhs: AdoptsOperatorInProtocol) -> Self {}
// expected-error@-1 {{operator methods cannot be declared @objc}}
}
//===--- @objc inference for witnesses
@objc // access-note-move{{InferFromProtocol}}
protocol InferFromProtocol {
@objc(inferFromProtoMethod1:)
optional func method1(value: Int)
}
// Infer when in the same declaration context.
// CHECK-LABEL: ClassInfersFromProtocol1
class ClassInfersFromProtocol1 : InferFromProtocol{
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
// Infer when in a different declaration context of the same class.
// CHECK-LABEL: ClassInfersFromProtocol2a
class ClassInfersFromProtocol2a {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
extension ClassInfersFromProtocol2a : InferFromProtocol { }
// Infer when in a different declaration context of the same class.
class ClassInfersFromProtocol2b : InferFromProtocol { }
// CHECK-LABEL: ClassInfersFromProtocol2b
extension ClassInfersFromProtocol2b {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
// Don't infer when there is a signature mismatch.
// CHECK-LABEL: ClassInfersFromProtocol3
class ClassInfersFromProtocol3 : InferFromProtocol {
}
extension ClassInfersFromProtocol3 {
// CHECK: {{^}} func method1(value: String)
func method1(value: String) { }
}
// Inference for subclasses.
class SuperclassImplementsProtocol : InferFromProtocol { }
class SubclassInfersFromProtocol1 : SuperclassImplementsProtocol {
// CHECK: {{^}} @objc func method1(value: Int)
func method1(value: Int) { }
}
class SubclassInfersFromProtocol2 : SuperclassImplementsProtocol {
}
extension SubclassInfersFromProtocol2 {
// CHECK: {{^}} @objc dynamic func method1(value: Int)
func method1(value: Int) { }
}
@objc // access-note-move{{NeverReturningMethod}}
class NeverReturningMethod {
@objc // access-note-move{{NeverReturningMethod.doesNotReturn()}}
func doesNotReturn() -> Never {}
}
// SR-5025
class User: NSObject {
}
@objc
extension User {
var name: String {
get {
return "No name"
}
set {
// Nothing
}
}
var other: String {
unsafeAddress { // expected-error {{addressors are not allowed to be marked @objc}}
}
}
}
// 'dynamic' methods cannot be @inlinable.
class BadClass {
@objc // access-note-move{{BadClass.badMethod1()}}
@inlinable dynamic func badMethod1() {}
// expected-error@-1 {{'@inlinable' attribute cannot be applied to 'dynamic' declarations}}
}
@objc // access-note-move{{ObjCProtocolWithWeakProperty}}
protocol ObjCProtocolWithWeakProperty {
weak var weakProp: AnyObject? { get set } // okay
}
@objc // access-note-move{{ObjCProtocolWithUnownedProperty}}
protocol ObjCProtocolWithUnownedProperty {
unowned var unownedProp: AnyObject { get set } // okay
}
// rdar://problem/46699152: errors about read/modify accessors being implicitly
// marked @objc.
@objc // access-note-move{{MyObjCClass}}
class MyObjCClass: NSObject {}
@objc
extension MyObjCClass {
@objc // access-note-move{{MyObjCClass.objCVarInObjCExtension}}
static var objCVarInObjCExtension: Bool {
get {
return true
}
set {}
}
// CHECK: {{^}} @objc private dynamic func stillExposedToObjCDespiteBeingPrivate()
private func stillExposedToObjCDespiteBeingPrivate() {}
}
@objc
private extension MyObjCClass {
// CHECK: {{^}} @objc dynamic func alsoExposedToObjCDespiteBeingPrivate()
func alsoExposedToObjCDespiteBeingPrivate() {}
}
@objcMembers class VeryObjCClass: NSObject {
// CHECK: {{^}} private func notExposedToObjC()
private func notExposedToObjC() {}
}
// SR-9035
class SR_9035_C {}
@objc // access-note-move{{SR_9035_P}}
protocol SR_9035_P {
func throwingMethod1() throws -> Unmanaged<CFArray> // Ok
func throwingMethod2() throws -> Unmanaged<SR_9035_C> // expected-error {{method cannot be a member of an @objc protocol because its result type cannot be represented in Objective-C}}
// expected-note@-1 {{inferring '@objc' because the declaration is a member of an '@objc' protocol}}
}
// SR-12801: Make sure we reject an @objc generic subscript.
class SR12801 {
@objc // bad-access-note-move{{SR12801.subscript(_:)}}
subscript<T>(foo : [T]) -> Int { return 0 }
// access-note-adjust{{@objc}} expected-error@-1 {{subscript cannot be marked @objc because it has generic parameters}}
}
// @_backDeploy
public class BackDeployClass {
@available(macOS 11.0, *)
@_backDeploy(before: macOS 12.0)
@objc // expected-error {{'@objc' cannot be applied to a back deployed instance method}}
final public func objcMethod() {}
}
| apache-2.0 | ad0d94d493f48a3b70c450720a0842e5 | 46.086582 | 462 | 0.712442 | 3.840747 | false | false | false | false |
Lietmotiv/Swift4096 | swift-2048/NumberTileGame.swift | 1 | 7680 | //
// NumberTileGame.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
/// A view controller representing the swift-2048 game. It serves mostly to tie a GameModel and a GameboardView
/// together. Data flow works as follows: user input reaches the view controller and is forwarded to the model. Move
/// orders calculated by the model are returned to the view controller and forwarded to the gameboard view, which
/// performs any animations to update its state.
class NumberTileGameViewController : UIViewController, GameModelProtocol {
// How many tiles in both directions the gameboard contains
var dimension: Int
// The value of the winning tile
var threshold: Int
var board: GameboardView?
var model: GameModel?
var scoreView: ScoreViewProtocol?
// Width of the gameboard
let boardWidth: CGFloat = 560.0
// How much padding to place between the tiles
let thinPadding: CGFloat = 12.0
let thickPadding: CGFloat = 24.0
// Amount of space to place between the different component views (gameboard, score view, etc)
let viewPadding: CGFloat = 20.0
// Amount that the vertical alignment of the component views should differ from if they were centered
let verticalViewOffset: CGFloat = 0.0
init(dimension d: Int, threshold t: Int) {
dimension = d > 2 ? d : 2
threshold = t > 8 ? t : 8
super.init(nibName: nil, bundle: nil)
model = GameModel(dimension: dimension, threshold: threshold, delegate: self)
view.backgroundColor = UIColor.blackColor()
setupSwipeControls()
}
func setupSwipeControls() {
let upSwipe = UISwipeGestureRecognizer(target: self, action: Selector("upCommand"))
upSwipe.numberOfTouchesRequired = 1
upSwipe.direction = .Up
view.addGestureRecognizer(upSwipe)
let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("downCommand"))
downSwipe.numberOfTouchesRequired = 1
downSwipe.direction = .Down
view.addGestureRecognizer(downSwipe)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("leftCommand"))
leftSwipe.numberOfTouchesRequired = 1
leftSwipe.direction = .Left
view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("rightCommand"))
rightSwipe.numberOfTouchesRequired = 1
rightSwipe.direction = .Right
view.addGestureRecognizer(rightSwipe)
}
// View Controller
override func viewDidLoad() {
super.viewDidLoad()
setupGame()
}
func reset() {
assert(board != nil && model != nil)
let b = board!
let m = model!
b.reset()
m.reset()
m.insertTileAtRandomLocation(8)
m.insertTileAtRandomLocation(8)
}
func setupGame() {
let vcHeight = view.bounds.size.height
let vcWidth = view.bounds.size.width
// This nested function provides the x-position for a component view
func xPositionToCenterView(v: UIView) -> CGFloat {
let viewWidth = v.bounds.size.width
let tentativeX = 0.5*(vcWidth - viewWidth)
return tentativeX >= 0 ? tentativeX : 0
}
// This nested function provides the y-position for a component view
func yPositionForViewAtPosition(order: Int, views: [UIView]) -> CGFloat {
assert(views.count > 0)
assert(order >= 0 && order < views.count)
let viewHeight = views[order].bounds.size.height
let totalHeight = CGFloat(views.count - 1)*viewPadding + views.map({ $0.bounds.size.height }).reduce(verticalViewOffset, { $0 + $1 })
let viewsTop = 0.5*(vcHeight - totalHeight) >= 0 ? 0.5*(vcHeight - totalHeight) : 0
// Not sure how to slice an array yet
var acc: CGFloat = 0
for i in 0..<order {
acc += viewPadding + views[i].bounds.size.height
}
return viewsTop + acc
}
// Create the score view
let scoreView = ScoreView(backgroundColor: UIColor.blackColor(),
textColor: UIColor.whiteColor(),
font: UIFont(name: "HelveticaNeue-Bold", size: 20.0),
radius: 6)
scoreView.score = 0
// Create the gameboard
let padding: CGFloat = dimension > 5 ? thinPadding : thickPadding
let v1 = boardWidth - padding*(CGFloat(dimension + 1))
let width: CGFloat = CGFloat(floorf(CFloat(v1)))/CGFloat(dimension)
let gameboard = GameboardView(dimension: dimension,
tileWidth: width,
tilePadding: padding,
cornerRadius: 6,
backgroundColor: UIColor.blackColor(),
foregroundColor: UIColor.darkGrayColor())
// Set up the frames
let views = [scoreView, gameboard]
var f = scoreView.frame
f.origin.x = xPositionToCenterView(scoreView)
f.origin.y = yPositionForViewAtPosition(0, views)
scoreView.frame = f
f = gameboard.frame
f.origin.x = xPositionToCenterView(gameboard)
f.origin.y = yPositionForViewAtPosition(1, views)
gameboard.frame = f
// Add to game state
view.addSubview(gameboard)
board = gameboard
view.addSubview(scoreView)
self.scoreView = scoreView
assert(model != nil)
let m = model!
m.insertTileAtRandomLocation(8)
m.insertTileAtRandomLocation(8)
}
// Misc
func followUp() {
assert(model != nil)
let m = model!
let (userWon, winningCoords) = m.userHasWon()
if userWon {
// TODO: alert delegate we won
let alertView = UIAlertView()
alertView.title = "Victory"
alertView.message = "You won!"
alertView.addButtonWithTitle("Cancel")
alertView.show()
// TODO: At this point we should stall the game until the user taps 'New Game' (which hasn't been implemented yet)
return
}
// Now, insert more tiles
let randomVal = Int(arc4random_uniform(10))
m.insertTileAtRandomLocation(randomVal == 1 ? 16 : 8)
// At this point, the user may lose
if m.userHasLost() {
// TODO: alert delegate we lost
NSLog("You lost...")
let alertView = UIAlertView()
alertView.title = "Defeat"
alertView.message = "You lost..."
alertView.addButtonWithTitle("Cancel")
alertView.show()
}
}
// Commands
func upCommand() {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Up,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
func downCommand() {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Down,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
func leftCommand() {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Left,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
func rightCommand() {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Right,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
// Protocol
func scoreChanged(score: Int) {
if (!scoreView) {
return
}
let s = scoreView!
s.scoreChanged(newScore: score)
}
func moveOneTile(from: (Int, Int), to: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.moveOneTile(from, to: to, value: value)
}
func moveTwoTiles(from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.moveTwoTiles(from, to: to, value: value)
}
func insertTile(location: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.insertTile(location, value: value)
}
}
| mit | df2689e43acfa0d8b4b43adb524b9d40 | 28.65251 | 139 | 0.654688 | 4.111349 | false | false | false | false |
Jnosh/swift | test/SILGen/complete_object_init.swift | 11 | 1975 | // RUN: %target-swift-frontend %s -emit-silgen | %FileCheck %s
struct X { }
class A {
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick A.Type) -> @owned A
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type):
// CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A
// CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A
// CHECK: return [[RESULT]] : $A
// CHECK-LABEL: sil hidden @_T020complete_object_init1AC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned A) -> @owned A
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var A }
// CHECK: [[UNINIT_SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var A }
// CHECK: [[PB:%.*]] = project_box [[UNINIT_SELF]]
// CHECK: store [[SELF_PARAM]] to [init] [[PB]] : $*A
// CHECK: [[SELFP:%[0-9]+]] = load [take] [[PB]] : $*A
// CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : (A.Type) -> (X) -> A, $@convention(method) (X, @owned A) -> @owned A
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_T020complete_object_init1XV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(method) (@thin X.Type) -> X
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A
// CHECK: store [[INIT_RESULT]] to [init] [[PB]] : $*A
// CHECK: [[RESULT:%[0-9]+]] = load [copy] [[PB]] : $*A
// CHECK: destroy_value [[UNINIT_SELF]] : ${ var A }
// CHECK: return [[RESULT]] : $A
convenience init() {
self.init(x: X())
}
init(x: X) { }
}
| apache-2.0 | def8ef2a3fc5eb221c9c08647fc1b3ec | 55.428571 | 152 | 0.54481 | 2.739251 | false | false | false | false |
yanif/circator | MetabolicCompassKit/IOSHealthManager.swift | 1 | 15097 | //
// HealthManager.swift
// MetabolicCompass
//
// Created by Yanif Ahmad on 9/27/15.
// Copyright © 2015 Yanif Ahmad, Tom Woolf. All rights reserved.
//
import Darwin
import HealthKit
import WatchConnectivity
import Async
import SwiftyBeaver
import SwiftDate
import MCCircadianQueries
// Constants.
public let HMDidUpdateRecentSamplesNotification = "HMDidUpdateRecentSamplesNotification"
public let HMDidUpdatedChartsData = "HMDidUpdatedChartsData"
public class IOSHealthManager: NSObject, WCSessionDelegate {
public static let sharedManager = IOSHealthManager()
var observerQueries: [HKQuery] = []
private override init() {
super.init()
connectWatch()
}
public func reset() {
MCHealthManager.sharedManager.reset()
self.updateWatchContext()
}
// MARK: - Apple Watch
func connectWatch() {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}
func updateWatchContext() {
// This release currently removed watch support
guard WCSession.isSupported() && WCSession.defaultSession().watchAppInstalled else {
return
}
do {
let sampleFormatter = SampleFormatter()
let applicationContext = MCHealthManager.sharedManager.mostRecentSamples.map {
(sampleType, results) -> [String: String] in
return [
"sampleTypeIdentifier": sampleType.identifier,
"displaySampleType": sampleType.displayText!,
"value": sampleFormatter.stringFromSamples(results)
]
}
try WCSession.defaultSession().updateApplicationContext(["context": applicationContext])
} catch {
log.error(error)
}
}
// MARK: - Push-based HealthKit data access.
private func fetchAnchoredSamplesOfType(type: HKSampleType, predicate: NSPredicate?, anchor: HKQueryAnchor?,
maxResults: Int, callContinuously: Bool, completion: HMAnchorSamplesBlock)
{
let hkAnchor = anchor ?? noAnchor
let onAnchorQueryResults: HMAnchorQueryBlock = {
(query, addedObjects, deletedObjects, newAnchor, nsError) -> Void in
completion(added: addedObjects ?? [], deleted: deletedObjects ?? [], newAnchor: newAnchor, error: nsError)
}
let anchoredQuery = HKAnchoredObjectQuery(type: type, predicate: predicate, anchor: hkAnchor, limit: Int(maxResults), resultsHandler: onAnchorQueryResults)
if callContinuously {
anchoredQuery.updateHandler = onAnchorQueryResults
}
MCHealthManager.sharedManager.healthKitStore.executeQuery(anchoredQuery)
}
public func startBackgroundObserverForType(type: HKSampleType, maxResultsPerQuery: Int = Int(HKObjectQueryNoLimit),
getAnchorCallback: HKSampleType -> (Bool, HKQueryAnchor?, NSPredicate?),
anchorQueryCallback: HMAnchorSamplesCBlock) -> Void
{
let onBackgroundStarted = {(success: Bool, nsError: NSError?) -> Void in
guard success else {
log.error(nsError)
return
}
let obsQuery = HKObserverQuery(sampleType: type, predicate: nil) {
query, completion, obsError in
guard obsError == nil else {
log.error(obsError)
return
}
// Run the anchor query as a background task, to support interactive queries for UI
// components that run at higher priority.
Async.background {
let tname = type.displayText ?? type.identifier
let (needsOldestSamples, anchor, predicate) = getAnchorCallback(type)
if needsOldestSamples {
Async.background(after: 0.5) {
log.verbose("Registering bulk ingestion availability for: \(tname)")
MCHealthManager.sharedManager.getOldestSampleDateForType(type) { date in
if let minDate = date {
log.info("Lower bound date for \(type.displayText ?? type.identifier): \(minDate)")
UserManager.sharedManager.setHistoricalRangeMinForType(type.identifier, min: minDate, sync: true)
}
}
}
}
self.fetchAnchoredSamplesOfType(type, predicate: predicate, anchor: anchor, maxResults: maxResultsPerQuery, callContinuously: false) {
(added, deleted, newAnchor, error) -> Void in
if added.count > 0 || deleted.count > 0 {
let asCircadian = type.identifier == HKWorkoutTypeIdentifier || type.identifier == HKCategoryTypeIdentifierSleepAnalysis
MCHealthManager.sharedManager.invalidateCacheForUpdates(type, added: asCircadian ? added : nil)
}
anchorQueryCallback(added: added, deleted: deleted, newAnchor: newAnchor, error: error, completion: completion)
}
}
}
self.observerQueries.append(obsQuery)
MCHealthManager.sharedManager.healthKitStore.executeQuery(obsQuery)
}
MCHealthManager.sharedManager.healthKitStore.enableBackgroundDeliveryForType(type, frequency: HKUpdateFrequency.Immediate, withCompletion: onBackgroundStarted)
}
public func stopAllBackgroundObservers(completion: (Bool, NSError?) -> Void) {
MCHealthManager.sharedManager.healthKitStore.disableAllBackgroundDeliveryWithCompletion { (success, error) in
if !(success && error == nil) { log.error(error) }
else {
self.observerQueries.forEach { MCHealthManager.sharedManager.healthKitStore.stopQuery($0) }
self.observerQueries.removeAll()
}
completion(success, error)
}
}
// MARK: - Chart data access
public func collectDataForCharts() {
log.verbose("Clearing HMAggregateCache expired objects")
MCHealthManager.sharedManager.aggregateCache.removeExpiredObjects()
MCHealthManager.sharedManager.circadianCache.removeExpiredObjects()
let periods: [HealthManagerStatisticsRangeType] = [
HealthManagerStatisticsRangeType.Week
, HealthManagerStatisticsRangeType.Month
, HealthManagerStatisticsRangeType.Year
]
let group = dispatch_group_create()
for sampleType in PreviewManager.manageChartsSampleTypes {
let type = sampleType.identifier == HKCorrelationTypeIdentifierBloodPressure ? HKQuantityTypeIdentifierBloodPressureSystolic : sampleType.identifier
let keyPrefix = type
for period in periods {
log.verbose("Collecting chart data for \(keyPrefix) \(period)")
dispatch_group_enter(group)
// We should get max and min values. because for this type we are using scatter chart
if type == HKQuantityTypeIdentifierHeartRate || type == HKQuantityTypeIdentifierUVExposure {
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(keyPrefix, sampleType: sampleType, period: period) {
if $2 != nil { log.error($2) }
dispatch_group_leave(group)
}
} else if type == HKQuantityTypeIdentifierBloodPressureSystolic {
// We should also get data for HKQuantityTypeIdentifierBloodPressureDiastolic
let diastolicKeyPrefix = HKQuantityTypeIdentifierBloodPressureDiastolic
let bloodPressureGroup = dispatch_group_create()
dispatch_group_enter(bloodPressureGroup)
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(keyPrefix, sampleType: HKObjectType.quantityTypeForIdentifier(type)!, period: period) {
if $2 != nil { log.error($2) }
dispatch_group_leave(bloodPressureGroup)
}
let diastolicType = HKQuantityTypeIdentifierBloodPressureDiastolic
dispatch_group_enter(bloodPressureGroup)
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(diastolicKeyPrefix, sampleType: HKObjectType.quantityTypeForIdentifier(diastolicType)!, period: period) {
if $2 != nil { log.error($2) }
dispatch_group_leave(bloodPressureGroup)
}
dispatch_group_notify(bloodPressureGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
dispatch_group_leave(group) //leave main group
}
} else {
MCHealthManager.sharedManager.getDailyStatisticsOfTypeForPeriod(keyPrefix, sampleType: sampleType, period: period, aggOp: .DiscreteAverage) {
if $1 != nil { log.error($1) }
dispatch_group_leave(group) //leave main group
}
}
}
}
// After completion, notify that we finished collecting statistics for all types
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
NSNotificationCenter.defaultCenter().postNotificationName(HMDidUpdatedChartsData, object: nil)
}
}
public func getChartDataForQuantity(sampleType: HKSampleType, inPeriod period: HealthManagerStatisticsRangeType, completion: AnyObject -> Void) {
let type = sampleType.identifier == HKCorrelationTypeIdentifierBloodPressure ? HKQuantityTypeIdentifierBloodPressureSystolic : sampleType.identifier
let keyPrefix = type
var key : String
var asMinMax = false
var asBP = false
let finalize : (MCAggregateSample) -> MCSample = {
var agg = $0; agg.final(); return agg as MCSample
}
let finalizeAgg : (HKStatisticsOptions, MCAggregateSample) -> MCSample = {
var agg = $1; agg.finalAggregate($0); return agg as MCSample
}
if type == HKQuantityTypeIdentifierHeartRate ||
type == HKQuantityTypeIdentifierUVExposure ||
type == HKQuantityTypeIdentifierBloodPressureSystolic
{
key = MCHealthManager.sharedManager.getPeriodCacheKey(keyPrefix, aggOp: [.DiscreteMin, .DiscreteMax], period: period)
asMinMax = true
asBP = type == HKQuantityTypeIdentifierBloodPressureSystolic
} else {
key = MCHealthManager.sharedManager.getPeriodCacheKey(keyPrefix, aggOp: .DiscreteAverage, period: period)
}
if let aggArray = MCHealthManager.sharedManager.aggregateCache[key] {
log.verbose("Cache hit for \(key) (size \(aggArray.aggregates.count))")
} else {
log.verbose("Cache miss for \(key)")
}
if asMinMax {
if asBP {
let diastolicKeyPrefix = HKQuantityTypeIdentifierBloodPressureDiastolic
let diastolicType = HKQuantityTypeIdentifierBloodPressureDiastolic
let bloodPressureGroup = dispatch_group_create()
dispatch_group_enter(bloodPressureGroup)
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(keyPrefix, sampleType: HKObjectType.quantityTypeForIdentifier(type)!, period: period) {
if $2 != nil { log.error($2) }
dispatch_group_leave(bloodPressureGroup)
}
dispatch_group_enter(bloodPressureGroup)
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(diastolicKeyPrefix, sampleType: HKObjectType.quantityTypeForIdentifier(diastolicType)!, period: period) {
if $2 != nil { log.error($2) }
dispatch_group_leave(bloodPressureGroup)
}
dispatch_group_notify(bloodPressureGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let diastolicKey = MCHealthManager.sharedManager.getPeriodCacheKey(diastolicKeyPrefix, aggOp: [.DiscreteMin, .DiscreteMax], period: period)
if let systolicAggArray = MCHealthManager.sharedManager.aggregateCache[key],
diastolicAggArray = MCHealthManager.sharedManager.aggregateCache[diastolicKey]
{
completion([systolicAggArray.aggregates.map { return finalizeAgg(.DiscreteMax, $0).numeralValue! },
systolicAggArray.aggregates.map { return finalizeAgg(.DiscreteMin, $0).numeralValue! },
diastolicAggArray.aggregates.map { return finalizeAgg(.DiscreteMax, $0).numeralValue! },
diastolicAggArray.aggregates.map { return finalizeAgg(.DiscreteMin, $0).numeralValue! }])
} else {
completion([])
}
}
} else {
MCHealthManager.sharedManager.getMinMaxOfTypeForPeriod(keyPrefix, sampleType: sampleType, period: period) { (_, _, error) in
guard error == nil || MCHealthManager.sharedManager.aggregateCache[key] != nil else {
completion([])
return
}
if let aggArray = MCHealthManager.sharedManager.aggregateCache[key] {
let mins = aggArray.aggregates.map { return finalizeAgg(.DiscreteMin, $0).numeralValue! }
let maxs = aggArray.aggregates.map { return finalizeAgg(.DiscreteMax, $0).numeralValue! }
completion([maxs, mins])
}
}
}
} else {
MCHealthManager.sharedManager.getDailyStatisticsOfTypeForPeriod(keyPrefix, sampleType: sampleType, period: period, aggOp: .DiscreteAverage) { (_, error) in
guard error == nil || MCHealthManager.sharedManager.aggregateCache[key] != nil else {
completion([])
return
}
if let aggArray = MCHealthManager.sharedManager.aggregateCache[key] {
completion(aggArray.aggregates.map { return finalize($0).numeralValue! })
}
}
}
}
//MARK: Working with cache
public func cleanCache() {
log.verbose("Clearing HMAggregateCache")
MCHealthManager.sharedManager.aggregateCache.removeAllObjects()
}
}
| apache-2.0 | f6c705ed32690f89c673975829aa555d | 46.621451 | 180 | 0.607578 | 5.876216 | false | false | false | false |
plenprojectcompany/plen-Scenography_iOS | PLENConnect/Connect/Views/PlenMotionView/PlenMotionView.swift | 1 | 2562 | //
// PlenMotionView.swift
// Scenography
//
// Created by PLEN Project on 2016/03/08.
// Copyright © 2016年 PLEN Project. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
import MaterialKit
@IBDesignable
class PlenMotionView: UIView {
// MARK: - IBOutlets
@IBOutlet weak var iconView: MKButton!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
// MARK: Variables
let rx_motion = Variable(PlenMotion.None)
var motion: PlenMotion {
get {return rx_motion.value}
set(value) { rx_motion.value = value }
}
fileprivate let disposeBag = DisposeBag()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
_ = UIViewUtil.loadXib(self)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_ = UIViewUtil.loadXib(self)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
initIconLayer(iconView.layer)
initBindings()
}
// MARK: - IBAction
@IBAction func iconViewTouched(_ sender: AnyObject) {
let plenCommand = Constants.PlenCommand.self
let plenConnection = PlenConnection.defaultInstance()
plenConnection.writeValue(plenCommand.playMotion(motion.id))
plenConnection.writeValue(Constants.PlenCommand.stopMotion)
}
// MARK: - Methods
fileprivate func initBindings() {
// icon
rx_motion.asObservable()
.map {$0.iconPath}
.distinctUntilChanged()
.subscribe(onNext: { [weak self] in
self?.iconView.setImage(UIImage(named: $0), for: .normal)
}, onError: nil, onCompleted: nil, onDisposed: nil)
.addDisposableTo(disposeBag)
// id
rx_motion.asObservable()
.map {String(format: "%02X", $0.id)}
.bindTo(idLabel.rx.text)
.addDisposableTo(disposeBag)
// name
rx_motion.asObservable()
.map {NSLocalizedString($0.name, comment: "")}
.bindTo(nameLabel.rx.text)
.addDisposableTo(disposeBag)
}
fileprivate func initIconLayer(_ layer: CALayer) {
layer.rasterizationScale = UIScreen.main.scale
layer.shadowRadius = 1.0
layer.shadowOpacity = 0.5
layer.shadowOffset = CGSize(width: 0, height: 1)
layer.shouldRasterize = true
}
}
| mit | 5f9901df813d1470ae8ac9fdabae7264 | 26.815217 | 73 | 0.603361 | 4.419689 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-push | Pods/BMSCore/Source/BMSClient.swift | 1 | 8132 | /*
* Copyright 2016 IBM Corp.
* 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.
*/
// MARK: - Swift 3
#if swift(>=3.0)
/**
A singleton that serves as the entry point to Bluemix client-server communication.
*/
public class BMSClient {
// MARK: - Constants
/**
The region where your Bluemix service is hosted.
*/
public struct Region {
/**
The southern United States Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let usSouth = ".ng.bluemix.net"
/**
The United Kingdom Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let unitedKingdom = ".eu-gb.bluemix.net"
/**
The Sydney Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let sydney = ".au-syd.bluemix.net"
/**
The Germany Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let germany = ".eu-de.bluemix.net"
/**
The Washington Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let usEast = ".us-east.bluemix.net"
/**
The Tokyo Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let jpTok = ".jp-tok.bluemix.net"
}
// MARK: - Properties
/// The singleton that is used for all `BMSClient` activity.
public static let sharedInstance = BMSClient()
/// Specifies the base Bluemix application backend URL.
public private(set) var bluemixAppRoute: String?
/// Specifies the region where the Bluemix service is hosted.
public private(set) var bluemixRegion: String?
/// Specifies the Bluemix application backend identifier.
public private(set) var bluemixAppGUID: String?
/// Specifies the allowed timeout (in seconds) for all `Request` network requests.
public var requestTimeout: Double = 20.0
// MARK: - Properties (internal)
// Handles the authentication process for network requests.
public var authorizationManager: AuthorizationManager
// MARK: - Initializer
/**
The required intializer for the `BMSClient` class.
Call this method on `BMSClient.sharedInstance`.
- Note: The `backendAppRoute` and `backendAppGUID` parameters are not required; they are only used for making network requests to the Bluemix server using the `Request` class.
- parameter backendAppRoute: (Optional) The base URL for the authorization server.
- parameter backendAppGUID: (Optional) The GUID of the Bluemix application.
- parameter bluemixRegion: The region where your Bluemix application is hosted. Use one of the `BMSClient.Region` constants.
*/
public func initialize(bluemixAppRoute: String? = nil, bluemixAppGUID: String? = nil, bluemixRegion: String...) {
self.bluemixAppRoute = bluemixAppRoute
self.bluemixAppGUID = bluemixAppGUID
self.bluemixRegion = bluemixRegion[0]
}
// Prevent users from using BMSClient() initializer - They must use BMSClient.sharedInstance
private init() {
self.authorizationManager = BaseAuthorizationManager()
}
}
/**************************************************************************************************/
#else
// MARK: - Swift 2
/**
A singleton that serves as the entry point to Bluemix client-server communication.
*/
public class BMSClient {
// MARK: - Constants
/**
The region where your Bluemix service is hosted.
*/
public struct Region {
/**
The southern United States Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let usSouth = ".ng.bluemix.net"
/**
The United Kingdom Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let unitedKingdom = ".eu-gb.bluemix.net"
/**
The Sydney Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let sydney = ".au-syd.bluemix.net"
/**
The Germany Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let germany = ".eu-de.bluemix.net"
/**
The Washington Bluemix region.
- note: Use this in the `BMSClient.initialize(bluemixAppRoute:bluemixAppGUID:bluemixRegion:)` method.
*/
public static let usEast = ".us-east.bluemix.net"
}
// MARK: - Properties
/// The singleton that is used for all `BMSClient` activity.
public static let sharedInstance = BMSClient()
/// Specifies the base Bluemix application backend URL.
public private(set) var bluemixAppRoute: String?
/// Specifies the region where the Bluemix service is hosted.
public private(set) var bluemixRegion: String?
/// Specifies the Bluemix application backend identifier.
public private(set) var bluemixAppGUID: String?
/// Specifies the allowed timeout (in seconds) for all `Request` network requests.
public var requestTimeout: Double = 20.0
// MARK: - Properties (internal)
// Handles the authentication process for network requests.
public var authorizationManager: AuthorizationManager
// MARK: - Initializer
/**
The required intializer for the `BMSClient` class.
Call this method on `BMSClient.sharedInstance`.
- Note: The `backendAppRoute` and `backendAppGUID` parameters are not required; they are only used for making network requests to the Bluemix server using the `Request` class.
- parameter backendAppRoute: (Optional) The base URL for the authorization server.
- parameter backendAppGUID: (Optional) The GUID of the Bluemix application.
- parameter bluemixRegion: The region where your Bluemix application is hosted. Use one of the `BMSClient.Region` constants.
*/
public func initialize(bluemixAppRoute bluemixAppRoute: String? = nil, bluemixAppGUID: String? = nil, bluemixRegion: String...) {
self.bluemixAppRoute = bluemixAppRoute
self.bluemixAppGUID = bluemixAppGUID
self.bluemixRegion = bluemixRegion[0]
}
// Prevent users from using BMSClient() initializer - They must use BMSClient.sharedInstance
private init() {
self.authorizationManager = BaseAuthorizationManager()
}
}
#endif
| apache-2.0 | f4ceb6b124e792ce9b90bacca89c8457 | 30.281853 | 183 | 0.631696 | 5.213642 | false | false | false | false |
danielsaidi/iExtra | iExtraTests/Operations/SerialOperationCoordinatorTests.swift | 1 | 3532 | //
// SerialOperationCoordinatorTests.swift
// iExtra
//
// Created by Daniel Saidi on 2019-01-26.
// Copyright © 2019 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import iExtra
class SerialOperationCoordinatorTests: QuickSpec {
override func spec() {
var coordinator: SerialOperationCoordinator!
var counter: TestCounter!
beforeEach {
coordinator = SerialOperationCoordinator()
counter = TestCounter()
}
it("completes once for empty sequence") {
var count = 0
coordinator.perform([]) { _ in count += 1 }
expect(count).to(equal(1))
}
it("completes once for non-empty sequence") {
var count = 0
let operation1 = TestOperation(counter: counter, performCompletion: true)
let operation2 = TestOperation(counter: counter, performCompletion: true)
let operations = [operation1, operation2]
coordinator.perform(operations) { _ in count += 1 }
expect(count).to(equal(1))
}
it("performs operation on each item") {
let operation1 = TestOperation(counter: counter, performCompletion: true)
let operation2 = TestOperation(counter: counter, performCompletion: true)
let operations = [operation1, operation2]
coordinator.perform(operations) { _ in }
expect(counter.count).to(equal(2))
}
it("performs operation until one operation does not complete") {
let operation1 = TestOperation(counter: counter, performCompletion: false)
let operation2 = TestOperation(counter: counter, performCompletion: true)
let operations = [operation1, operation2]
coordinator.perform(operations) { _ in }
expect(counter.count).to(equal(1))
}
it("does not complete if one operation does not complete") {
var count = 0
let operation1 = TestOperation(counter: counter, performCompletion: true)
let operation2 = TestOperation(counter: counter, performCompletion: false)
let operations = [operation1, operation2]
coordinator.perform(operations) { _ in count += 1 }
expect(count).to(equal(0))
}
it("completes with returned errors") {
let error = NSError(domain: "foo", code: 1, userInfo: nil )
let operation1 = TestOperation(counter: counter, performCompletion: true)
let operation2 = TestOperation(counter: counter, performCompletion: true)
let operations = [operation1, operation2]
operation2.error = error
var errors = [Error?]()
coordinator.perform(operations) { res in errors = res }
expect(errors.count).to(equal(1))
expect(errors[0]).to(be(error))
}
}
}
private class TestCounter {
var count: Int = 0
}
private class TestOperation: iExtra.Operation {
init(counter: TestCounter, performCompletion: Bool) {
self.counter = counter
self.performCompletion = performCompletion
}
var error: Error?
private var counter: TestCounter
private var performCompletion: Bool
func perform(completion: @escaping OperationCompletion) {
counter.count += 1
guard performCompletion else { return }
completion(error)
}
}
| mit | 4be47f466a19aefd270b8e950e7923d3 | 33.960396 | 86 | 0.60691 | 5.008511 | false | true | false | false |
qiuncheng/study-for-swift | learn-rx-swift/Pods/RxSwift/RxSwift/Observables/Implementations/Dematerialize.swift | 14 | 1280 | //
// Dematerialize.swift
// RxSwift
//
// Created by Jamie Pinkham on 3/13/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
fileprivate final class DematerializeSink<Element: EventConvertible, O: ObserverType>: Sink<O>, ObserverType where O.E == Element.ElementType {
fileprivate func on(_ event: Event<Element>) {
switch event {
case .next(let element):
forwardOn(element.event)
if element.event.isStopEvent {
dispose()
}
case .completed:
forwardOn(.completed)
dispose()
case .error(let error):
forwardOn(.error(error))
dispose()
}
}
}
final class Dematerialize<Element: EventConvertible>: Producer<Element.ElementType> {
private let _source: Observable<Element>
init(source: Observable<Element>) {
_source = source
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element.ElementType {
let sink = DematerializeSink<Element, O>(observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | 94eb64eba006f5bfedd727e210d349fe | 31.794872 | 157 | 0.625489 | 4.551601 | false | false | false | false |
apple/swift | test/stdlib/freestanding_diags_stdlib.swift | 2 | 7565 | // RUN: %target-typecheck-verify-swift -concurrency-model=task-to-thread
// REQUIRES: freestanding
import _Concurrency
@MainActor(unsafe) // expected-error{{not permitted within task-to-thread concurrency model}}
func chowMein() async {
}
@MainActor // expected-error{{not permitted within task-to-thread concurrency model}}
class ChowMein {}
@available(SwiftStdlib 5.1, *)
func foo() async throws {
Task<Void, Never> {} // expected-error{{Unavailable in task-to-thread concurrency model}}
Task<Void, Error> {} // expected-error{{Unavailable in task-to-thread concurrency model}}
Task<Void, Never>.detached {} // expected-error{{Unavailable in task-to-thread concurrency model}}
Task<Void, Error>.detached {} // expected-error{{Unavailable in task-to-thread concurrency model}}
Task<Void, Error>.runDetached {} // expected-error{{Unavailable in task-to-thread concurrency model}}
detach { () async -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
detach { () async throws -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
async { () async -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
async { () async throws -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
asyncDetached { () async -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
asyncDetached { () async throws -> () in } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = MainActor.self // expected-error{{Unavailable in task-to-thread concurrency model}}
await Task.sleep(1 as UInt64) // expected-error{{Unavailable in task-to-thread concurrency model}}
try await Task.sleep(nanoseconds: 1 as UInt64) // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = AsyncStream<Int>.self // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = AsyncThrowingStream<Int, Error>.self // expected-error{{Unavailable in task-to-thread concurrency model}}
func withTaskGroup(_ tg: inout TaskGroup<Int>) async throws {
tg.addTask(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.addTask { return 1 } // ok
_ = tg.addTaskUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.addTaskUnlessCancelled { return 1 } // ok
_ = await tg.add(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = await tg.add { return 1 } // expected-warning{{'add(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
tg.spawn(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.spawn { return 1 } // expected-warning{{'spawn(operation:)' is deprecated: renamed to 'addTask(operation:)'}}
// expected-note@-1{{use 'addTask(operation:)' instead}}
_ = tg.spawnUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.spawnUnlessCancelled { return 1 } // expected-warning{{'spawnUnlessCancelled(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
tg.async(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.async { return 1 } // expected-warning{{'async(operation:)' is deprecated: renamed to 'addTask(operation:)'}}
// expected-note@-1{{use 'addTask(operation:)' instead}}
_ = tg.asyncUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.asyncUnlessCancelled { return 1 } // expected-warning{{'asyncUnlessCancelled(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
}
func withThrowingTaskGroup(_ tg: inout ThrowingTaskGroup<Int, Error>) async throws {
tg.addTask(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.addTask { return 1 } // ok
_ = tg.addTaskUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.addTaskUnlessCancelled { return 1 } // ok
_ = await tg.add(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = await tg.add { return 1 } // expected-warning{{'add(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
tg.spawn(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.spawn { return 1 } // expected-warning{{'spawn(operation:)' is deprecated: renamed to 'addTask(operation:)'}}
// expected-note@-1{{use 'addTask(operation:)' instead}}
_ = tg.spawnUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.spawnUnlessCancelled { return 1 } // expected-warning{{'spawnUnlessCancelled(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
tg.async(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
tg.async { return 1 } // expected-warning{{'async(operation:)' is deprecated: renamed to 'addTask(operation:)'}}
// expected-note@-1{{use 'addTask(operation:)' instead}}
_ = tg.asyncUnlessCancelled(priority: .low) { return 1 } // expected-error{{Unavailable in task-to-thread concurrency model}}
_ = tg.asyncUnlessCancelled { return 1 } // expected-warning{{'asyncUnlessCancelled(operation:)' is deprecated: renamed to 'addTaskUnlessCancelled(operation:)'}}
// expected-note@-1{{use 'addTaskUnlessCancelled(operation:)' instead}}
}
}
@available(SwiftStdlib 5.7, *)
func bar() async {
func withContinuousClock(_ clock: ContinuousClock) async throws { try await clock.sleep(until: { fatalError() }()) } // expected-error{{Unavailable in task-to-thread concurrency model}}
func withSuspendingClock(_ clock: SuspendingClock) async throws { try await clock.sleep(until: { fatalError() }()) } // expected-error{{Unavailable in task-to-thread concurrency model}}
func withClock<C : Clock>(
until deadline: C.Instant,
tolerance: C.Instant.Duration? = nil,
clock: C
) async throws {
try await Task.sleep(until: deadline, tolerance: tolerance, clock: clock) // expected-error{{Unavailable in task-to-thread concurrency model}}
}
func withDuration(_ duration: Duration) async throws { try await Task.sleep(for: duration) } // expected-error{{Unavailable in task-to-thread concurrency model}}
}
func foo2(
body: @MainActor @Sendable () throws -> () // expected-error{{annotating a type with a global actor 'MainActor' is not permitted within task-to-thread concurrency model}}
) {}
| apache-2.0 | 87482ce9f3851a7cccc6805a0cdda3a2 | 79.478723 | 187 | 0.685393 | 4.408508 | false | false | false | false |
haitran2011/Rocket.Chat.iOS | Rocket.Chat/Controllers/Auth/RegisterUsernameViewController.swift | 1 | 3926 | //
// RegisterUsernameViewController.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 04/03/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
import SwiftyJSON
final class RegisterUsernameViewController: BaseViewController {
internal var requesting = false
var serverPublicSettings: AuthSettings?
@IBOutlet weak var viewFields: UIView! {
didSet {
viewFields.layer.cornerRadius = 4
viewFields.layer.borderColor = UIColor.RCLightGray().cgColor
viewFields.layer.borderWidth = 0.5
}
}
@IBOutlet weak var visibleViewBottomConstraint: NSLayoutConstraint!
@IBOutlet weak var textFieldUsername: UITextField!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
startLoading()
AuthManager.usernameSuggestion { [weak self] (response) in
self?.stopLoading()
if !response.isError() {
self?.textFieldUsername.text = response.result["result"].string ?? ""
}
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow(_:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillHide(_:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil
)
textFieldUsername.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
NotificationCenter.default.removeObserver(self)
}
func startLoading() {
textFieldUsername.alpha = 0.5
requesting = true
activityIndicator.startAnimating()
textFieldUsername.resignFirstResponder()
}
func stopLoading() {
textFieldUsername.alpha = 1
requesting = false
activityIndicator.stopAnimating()
}
// MARK: Keyboard Handlers
override func keyboardWillShow(_ notification: Notification) {
if let keyboardSize = ((notification as NSNotification).userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
visibleViewBottomConstraint.constant = keyboardSize.height
}
}
override func keyboardWillHide(_ notification: Notification) {
visibleViewBottomConstraint.constant = 0
}
// MARK: Request username
fileprivate func requestUsername() {
startLoading()
AuthManager.setUsername(textFieldUsername.text ?? "") { [weak self] (response) in
self?.stopLoading()
if response.isError() {
if let error = response.result["error"].dictionary {
let alert = UIAlertController(
title: localized("error.socket.default_error_title"),
message: error["message"]?.string ?? localized("error.socket.default_error_message"),
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
} else {
self?.dismiss(animated: true, completion: nil)
}
}
}
}
extension RegisterUsernameViewController: UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return !requesting
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
requestUsername()
return true
}
}
| mit | 85d061e35f00dd0e1a10f2be8e6ea540 | 29.426357 | 134 | 0.625987 | 5.631277 | false | false | false | false |
caiodias/CleanerSkeeker | CleanerSeeker/CleanerSeeker/JobHistoryCell.swift | 1 | 615 | //
// JobHistoryCell.swift
// CleanerSeeker
//
// Created by Caio Dias on 2017-03-28.
// Copyright © 2017 Caio Dias. All rights reserved.
//
import UIKit
class JobHistoryCell: UITableViewCell {
@IBOutlet weak private var dateLabel: UILabel!
@IBOutlet weak private var titleLabel: UILabel!
private let dateFormatter = DateFormatter()
func fillElements(job: JobOpportunity) {
self.dateFormatter.dateStyle = .short
self.dateFormatter.timeStyle = .none
self.dateLabel.text = dateFormatter.string(from: job.jobWorkDate)
self.titleLabel.text = job.address
}
}
| mit | bdb1aa77ea7cc8968f870a5393d6ba54 | 25.695652 | 73 | 0.701954 | 4.093333 | false | false | false | false |
toineheuvelmans/Metron | source/Demo/GridView.swift | 1 | 7297 | //
// GridView.swift
// Metron
//
// Copyright © 2017 Toine Heuvelmans. All rights reserved.
//
// NOTE: This GridView is only for demonstration purposes,
// and is not at all optimised in any way. Feel free to use
// it in your code, but don't expect too much of it.
//
import UIKit
import Metron
class GridView: UIView {
weak var drawableSource: DrawableSource?
var displayCenter: CGPoint = .zero
var scale: CGFloat = 1.0 / 15.0
var gridColor: UIColor = UIColor(white: 1.0, alpha: 0.5)
/// The effective grid frame that is displayed
var displayFrame: CGRect {
let displaySize = scale * frame.size
let halfSize = 0.5 * displaySize
let displayOrigin = CGPoint(x: -halfSize.width + displayCenter.x,
y: -halfSize.height + displayCenter.y)
return CGRect(origin: displayOrigin, size: displaySize)
}
/// Converts a point in screen coordinates to a point on the grid
func convert(_ point: CGPoint) -> CGPoint {
let dpf = displayFrame
return CGPoint(x: dpf.minX + (point.x * scale), y: dpf.minY + ((frame.size.height - point.y) * scale))
}
override func awakeFromNib() {
super.awakeFromNib()
let pan = UIPanGestureRecognizer(target: self, action: #selector(updateTranslation(_:)))
pan.maximumNumberOfTouches = 1
pan.delegate = self
addGestureRecognizer(pan)
let pinch = UIPinchGestureRecognizer(target: self, action: #selector(updateScale(_:)))
pinch.delegate = self
addGestureRecognizer(pinch)
backgroundColor = #colorLiteral(red: 0.05882352941, green: 0.2588235294, blue: 0.5764705882, alpha: 1)
}
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else { return }
ctx.saveGState()
ctx.concatenate(CGAffineTransform(a: 1, b: 0, c: 0, d: -1, tx: 0, ty: frame.height))
let displayFrame = self.displayFrame
ctx.scaleBy(x: 1.0 / scale, y: 1.0 / scale)
ctx.translateBy(x: -displayFrame.origin.x, y: -displayFrame.origin.y)
ctx.setLineWidth(2.0 * scale)
ctx.move(to: CGPoint(x: displayFrame.minX, y: 0.0))
ctx.addLine(to: CGPoint(x: displayFrame.maxX, y: 0.0))
ctx.move(to: CGPoint(x: 0.0, y: displayFrame.minY))
ctx.addLine(to: CGPoint(x: 0.0, y: displayFrame.maxY))
ctx.setStrokeColor(gridColor.withAlphaComponent(0.3).cgColor)
ctx.drawPath(using: .stroke)
let lineWidth = 1.0 * scale
ctx.setLineWidth(lineWidth)
ctx.saveGState()
ctx.setLineDash(phase: lineWidth, lengths: [lineWidth, lineWidth])
let s = pow(10.0, ceil(log10(scale)) + 1)
let minX = floor(displayFrame.minX / s) * s
let maxX = ceil(displayFrame.maxX / s) * s
for x in stride(from: minX, to: maxX, by: s) {
ctx.move(to: CGPoint(x: CGFloat(x), y: displayFrame.minY))
ctx.addLine(to: CGPoint(x: CGFloat(x), y: displayFrame.maxY))
}
let minY = floor(displayFrame.minY / s) * s
let maxY = ceil(displayFrame.maxY / s) * s
for y in stride(from: minY, to: maxY, by: s) {
ctx.move(to: CGPoint(x: displayFrame.minX, y: CGFloat(y)))
ctx.addLine(to: CGPoint(x: displayFrame.maxX, y: CGFloat(y)))
}
ctx.drawPath(using: .stroke)
ctx.restoreGState()
// ctx.saveGState()
// ctx.setLineWidth(lineWidth)
// ctx.setLineDash(phase: 0, lengths: [2.0 * lineWidth, 2.0 * lineWidth])
//
// let subGridStrength = (0.9 - ((10 * scale) / s)) * 0.3
//
// for x in stride(from: minX, to: maxX, by: s / 10.0) {
// ctx.move(to: CGPoint(x: CGFloat(x), y: displayFrame.minY))
// ctx.addLine(to: CGPoint(x: CGFloat(x), y: displayFrame.maxY))
// }
// for y in stride(from: minY, to: maxY, by: s / 10.0) {
// ctx.move(to: CGPoint(x: displayFrame.minX, y: CGFloat(y)))
// ctx.addLine(to: CGPoint(x: displayFrame.maxX, y: CGFloat(y)))
// }
//
// ctx.setStrokeColor(gridColor.withAlphaComponent(subGridStrength * subGridStrength).cgColor)
//
// ctx.drawPath(using: .stroke)
// ctx.restoreGState()
let hasSelectedDrawable = drawableSource?.drawables.first { $0.selected } != nil
if hasSelectedDrawable {
// fill
ctx.saveGState()
drawableSource?.drawables.compactMap { $0.selected ? $0.shape.path : nil }.forEach { ctx.addPath($0) }
ctx.clip()
let shift = s
for y in stride(from: minY, to: maxY, by: s / 10.0) {
ctx.move(to: CGPoint(x: displayFrame.minX, y: CGFloat(y) - shift))
ctx.addLine(to: CGPoint(x: displayFrame.maxX, y: CGFloat(y) + shift))
}
ctx.setLineWidth(1.0 * lineWidth)
ctx.setStrokeColor(gridColor.withAlphaComponent(0.5).cgColor)
ctx.drawPath(using: .stroke)
ctx.restoreGState()
}
// lines
ctx.saveGState()
drawableSource?.drawables.compactMap { $0.shape.path }.forEach { ctx.addPath($0) }
ctx.setLineWidth(3.0 * lineWidth)
ctx.setStrokeColor(gridColor.withAlphaComponent(1.0).cgColor)
ctx.drawPath(using: .stroke)
ctx.restoreGState()
ctx.restoreGState()
}
// MARK: - Pan / Pinch
@objc func updateTranslation(_ panGestureRecognizer: UIPanGestureRecognizer) {
switch panGestureRecognizer.state {
case .changed:
if isUserInteractionEnabled {
let t = panGestureRecognizer.translation(in: self)
displayCenter = displayCenter - (scale * CGVector(dx: t.x, dy: -t.y))
panGestureRecognizer.setTranslation(.zero, in: self)
setNeedsDisplay()
}
default: break
}
}
@objc func updateScale(_ pinchGestureRecognizer: UIPinchGestureRecognizer) {
switch pinchGestureRecognizer.state {
case .changed:
if isUserInteractionEnabled {
guard pinchGestureRecognizer.numberOfTouches > 1 else { return }
let touch1 = pinchGestureRecognizer.location(ofTouch: 0, in: self)
let touch2 = pinchGestureRecognizer.location(ofTouch: 1, in: self)
let focus = touch1 + (0.5 * (touch2 - touch1))
let offset = (focus - center) * scale
let shiftedOffset = offset / pinchGestureRecognizer.scale
var dif = shiftedOffset - offset
dif.dy = -dif.dy
displayCenter = (displayCenter - dif)
scale = scale / pinchGestureRecognizer.scale
pinchGestureRecognizer.scale = 1.0
setNeedsDisplay()
}
default: break
}
}
}
extension GridView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gestureRecognizers = gestureRecognizers else { return false }
return gestureRecognizers.contains(otherGestureRecognizer)
}
}
| mit | bf70d76ba8ec5113c970a6d14bb8dc75 | 36.415385 | 157 | 0.60403 | 4.166762 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit | Sources/BSWInterfaceKit/DataSource/CollectionViewDataSource.swift | 1 | 17550 | //
// Created by Pierluigi Cifani on 28/04/16.
// Copyright © 2018 TheLeftBit SL. All rights reserved.
//
#if canImport(UIKit)
import UIKit
import BSWFoundation
public class CollectionViewDataSource<Cell:ViewModelReusable & UICollectionViewCell>: NSObject, UICollectionViewDataSource {
public private(set) var data: [Cell.VM]
public weak var collectionView: UICollectionView!
public var emptyConfiguration: ErrorView.Configuration?
private var emptyView: UIView?
private var offsetObserver: NSKeyValueObservation?
private var isRequestingNextPage: Bool = false
private var scrollDirection: UICollectionView.ScrollDirection {
guard let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else {
return .vertical
}
return flowLayout.scrollDirection
}
public init(data: [Cell.VM] = [],
collectionView: UICollectionView,
emptyConfiguration: ErrorView.Configuration? = nil) {
self.data = data
self.collectionView = collectionView
self.emptyConfiguration = emptyConfiguration
super.init()
collectionView.registerReusableCell(Cell.self)
collectionView.dataSource = self
}
deinit {
emptyView?.removeFromSuperview()
}
@available(tvOS, unavailable)
public var pullToRefreshSupport: CollectionViewPullToRefreshSupport<Cell.VM>? {
didSet {
guard let pullToRefreshSupport = self.pullToRefreshSupport else {
self.collectionView.refreshControl = nil
return
}
let refreshControl = UIRefreshControl()
refreshControl.tintColor = pullToRefreshSupport.tintColor
refreshControl.addTarget(self, action: #selector(handlePullToRefresh), for: .valueChanged)
self.collectionView.refreshControl = refreshControl
}
}
public var supplementaryViewSupport: CollectionViewSupplementaryViewSupport? {
didSet {
defer {
collectionView.reloadData()
}
guard let supplementaryViewSupport = self.supplementaryViewSupport else {
return
}
collectionView.register(
supplementaryViewSupport.supplementaryViewClass,
forSupplementaryViewOfKind: supplementaryViewSupport.kind.toUIKit(),
withReuseIdentifier: Constants.SupplementaryViewReuseID
)
}
}
public var reorderSupport: CollectionViewReorderSupport<Cell.VM>? {
didSet {
guard let _ = self.reorderSupport else { return }
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(a345678907654(gesture:)))
self.collectionView.addGestureRecognizer(longPressGesture)
}
}
public var infiniteScrollSupport: CollectionViewInfiniteScrollSupport<Cell.VM>? {
didSet {
defer {
collectionView.reloadData()
}
guard let infiniteScrollSupport = self.infiniteScrollSupport else {
offsetObserver = nil
if let columnLayout = self.collectionView.collectionViewLayout as? ColumnFlowLayout {
columnLayout.showsFooter = false
}
return
}
// To ease adoption, we're adding here some callbacks neccesaries
// to make the layout query the dataSource for the footer
if let columnLayout = self.collectionView.collectionViewLayout as? ColumnFlowLayout {
columnLayout.showsFooter = true
columnLayout.footerFactory = { _ in
return infiniteScrollSupport.footerViewClass.init()
}
}
collectionView.register(
infiniteScrollSupport.footerViewClass,
forSupplementaryViewOfKind: UICollectionView.SupplementaryViewKind.footer.toUIKit(),
withReuseIdentifier: Constants.InfinitePagingReuseID
)
offsetObserver = self.collectionView.observe(\.contentOffset, changeHandler: { [weak self] (cv, change) in
guard let self = self else { return }
switch self.scrollDirection {
case .vertical:
let offsetY = cv.contentOffset.y
let contentHeight = cv.contentSize.height
guard offsetY > 0, contentHeight > 0 else { return }
if offsetY > contentHeight - cv.frame.size.height {
self.requestNextInfiniteScrollPage()
}
case .horizontal:
let offsetX = cv.contentOffset.x
let contentWidth = cv.contentSize.width
guard offsetX > 0, contentWidth > 0 else { return }
if offsetX > contentWidth - cv.frame.size.width {
self.requestNextInfiniteScrollPage()
}
@unknown default:
fatalError()
}
})
}
}
public func updateDataWithoutReloadingCollectionView(_ data: [Cell.VM]) {
self.data = data
}
public func updateData(_ data: [Cell.VM]) {
self.data = data
collectionView.reloadData()
}
public func performEditActions(_ actions: [CollectionViewEditActionKind<Cell.VM>], completion: @escaping VoidHandler = {}) {
guard actions.count > 0 else {
completion()
return
}
collectionView.performBatchUpdates({
actions.forEach {
switch $0 {
case .remove(let fromIndexPath):
data.remove(at: fromIndexPath.item)
collectionView.deleteItems(at: [fromIndexPath])
case .insert(let item, let indexPath):
data.insert(item, at: indexPath.item)
collectionView.insertItems(at: [indexPath])
case .move(let from, let to):
data.moveItem(fromIndex: from.item, toIndex: to.item)
collectionView.moveItem(at: from, to: to)
case .reload(let model, let indexPath):
data[indexPath.item] = model
collectionView.reloadItems(at: [indexPath])
}
}
}, completion: { _ in
completion()
})
}
//MARK:- UICollectionViewDataSource
@objc public func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
defer { addEmptyView() }
return self.data.count
}
@objc public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: Cell = collectionView.dequeueReusableCell(indexPath: indexPath)
let model = data[indexPath.item]
cell.configureFor(viewModel: model)
return cell
}
@objc public func collectionView(_ collectionView: UICollectionView, canMoveItemAt indexPath: IndexPath) -> Bool {
guard let reorderSupport = self.reorderSupport else { return false }
return reorderSupport.canMoveItemAtIndexPath(indexPath)
}
@objc public func collectionView(_ collectionView: UICollectionView, moveItemAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
guard let commitMoveHandler = reorderSupport?.didMoveItemHandler else { return }
let movedItem = data[destinationIndexPath.item]
data.moveItem(fromIndex: sourceIndexPath.item, toIndex: destinationIndexPath.item)
commitMoveHandler(sourceIndexPath, destinationIndexPath, movedItem)
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let infiniteScrollSupport = self.infiniteScrollSupport, kind == UICollectionView.elementKindSectionFooter {
let supplementaryView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: Constants.InfinitePagingReuseID,
for: indexPath
)
let footer = supplementaryView as! CollectionViewInfiniteFooter
infiniteScrollSupport.configureFooter(footer)
return supplementaryView
} else if let supplementaryViewSupport = self.supplementaryViewSupport {
let supplementaryView = collectionView.dequeueReusableSupplementaryView(
ofKind: supplementaryViewSupport.kind.toUIKit(),
withReuseIdentifier: Constants.SupplementaryViewReuseID,
for: indexPath
)
supplementaryViewSupport.configureHeader(supplementaryView)
supplementaryView.isHidden = (data.count == 0) && supplementaryViewSupport.shouldHideOnEmptyDataSet
return supplementaryView
} else {
fatalError()
}
}
//MARK:- Private
private func requestNextInfiniteScrollPage() {
guard !isRequestingNextPage, let infiniteScrollSupport = self.infiniteScrollSupport else { return }
isRequestingNextPage = true
infiniteScrollSupport.fetchHandler { [weak self] result in
guard let `self` = self else { return }
let actions: [CollectionViewEditActionKind<Cell.VM>] = {
guard let newData = result.newDataAvailable else { return [] }
let dataCount = self.data.count
var newIndex = 0
return newData.map {
defer { newIndex += 1 }
return .insert(item: $0, atIndexPath: IndexPath(item: dataCount + newIndex, section: 0))
}
}()
self.performEditActions(actions) {
self.isRequestingNextPage = false
// No more paging
if !result.shouldKeepPaging {
self.infiniteScrollSupport = nil
}
}
}
}
private func addEmptyView() {
guard let emptyConfiguration = self.emptyConfiguration else {
return
}
self.emptyView?.removeFromSuperview()
if data.count == 0 {
emptyView = emptyConfiguration.viewRepresentation()
} else {
emptyView = nil
}
guard let emptyView = self.emptyView, let collectionView = self.collectionView else { return }
emptyView.translatesAutoresizingMaskIntoConstraints = false
let superView: UIView = {
if let hostView = collectionView.superview {
hostView.insertSubview(emptyView, aboveSubview: collectionView)
return hostView
} else {
collectionView.addSubview(emptyView)
return collectionView
}
}()
let spacing = Constants.Spacing
NSLayoutConstraint.activate([
emptyView.centerXAnchor.constraint(equalTo: superView.centerXAnchor),
emptyView.centerYAnchor.constraint(equalTo: superView.centerYAnchor),
emptyView.leadingAnchor.constraint(greaterThanOrEqualTo: superView.leadingAnchor, constant: spacing),
emptyView.trailingAnchor.constraint(greaterThanOrEqualTo: superView.trailingAnchor, constant: -spacing)
])
}
//MARK: IBAction
@available(tvOS, unavailable)
@objc func handlePullToRefresh() {
guard let pullToRefreshSupport = self.pullToRefreshSupport else { return }
pullToRefreshSupport.handler({ [weak self] behavior in
guard let `self` = self else { return }
self.collectionView.refreshControl?.endRefreshing()
switch behavior {
case .insertOnTop(let newModels):
self.collectionView.performBatchUpdates({
self.data.insert(contentsOf: newModels, at: 0)
let newIndexPaths = newModels.enumerated().map({ (idx, element) -> IndexPath in
return IndexPath(item: idx, section: 0)
})
self.collectionView.insertItems(at: newIndexPaths)
}, completion: nil)
case .replace(let newModels):
self.data = newModels
self.collectionView.reloadData()
case .noNewContent:
break
}
})
}
/// This used to be called `handleLongPress:` but Apple is being idiotic
/// More info: https://i.imgur.com/eX4JQL2.jpg
@objc private func a345678907654(gesture: UILongPressGestureRecognizer) {
guard let collectionView = self.collectionView else { return }
switch(gesture.state) {
case .began:
guard let selectedIndexPath = collectionView.indexPathForItem(at: gesture.location(in: collectionView)) else {
break
}
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
}
//MARK: - Edit Support
public enum CollectionViewEditActionKind<Model> {
case insert(item: Model, atIndexPath: IndexPath)
case remove(fromIndexPath: IndexPath)
case move(fromIndexPath: IndexPath, toIndexPath: IndexPath)
case reload(item: Model, indexPath: IndexPath)
}
//MARK: - Reorder Support
public struct CollectionViewReorderSupport<Model> {
public typealias DidMoveItemHandler = ((_ from: IndexPath, _ to: IndexPath, _ movedItem: Model) -> Void)
public typealias CanMoveItemHandler = ((IndexPath) -> Bool)
public let canMoveItemAtIndexPath: CanMoveItemHandler
public let didMoveItemHandler: DidMoveItemHandler
public init(canMoveItemAtIndexPath: @escaping CanMoveItemHandler, didMoveItemAtIndexPath: @escaping DidMoveItemHandler) {
self.canMoveItemAtIndexPath = canMoveItemAtIndexPath
self.didMoveItemHandler = didMoveItemAtIndexPath
}
}
//MARK: - Pull to Refresh Support
@available(tvOS, unavailable)
public struct CollectionViewPullToRefreshSupport<Model> {
public enum Behavior {
case replace([Model])
case insertOnTop([Model])
case noNewContent
}
public typealias Handler = (@escaping (Behavior) -> ()) -> ()
public let tintColor: UIColor?
public let handler: Handler
public init(tintColor: UIColor? = nil, handler: @escaping Handler) {
self.handler = handler
self.tintColor = tintColor
}
}
//MARK: - SupplementaryViewSupport
public struct CollectionViewSupplementaryViewSupport {
public typealias ConfigureHeader = (UICollectionReusableView) -> ()
public let kind: UICollectionView.SupplementaryViewKind
public let configureHeader: ConfigureHeader
public let shouldHideOnEmptyDataSet: Bool
public let supplementaryViewClass: UICollectionReusableView.Type
public init(supplementaryViewClass: UICollectionReusableView.Type, kind: UICollectionView.SupplementaryViewKind, shouldHideOnEmptyDataSet: Bool = false, configureHeader: @escaping ConfigureHeader) {
self.supplementaryViewClass = supplementaryViewClass
self.kind = kind
self.shouldHideOnEmptyDataSet = shouldHideOnEmptyDataSet
self.configureHeader = configureHeader
}
}
//MARK: - Infinite Scroll support
public protocol CollectionViewInfiniteFooter: UICollectionReusableView {
func startAnimating()
}
public struct CollectionViewInfiniteScrollSupport<Model> {
public struct FetchResult {
public let newDataAvailable: [Model]?
public let shouldKeepPaging: Bool
public init(newDataAvailable: [Model]?, shouldKeepPaging: Bool) {
self.newDataAvailable = newDataAvailable
self.shouldKeepPaging = shouldKeepPaging
}
}
public typealias ConfigureFooter = (CollectionViewInfiniteFooter) -> ()
public typealias FetchHandler = (@escaping (FetchResult) -> ()) -> ()
public let footerViewClass: UICollectionReusableView.Type
public let configureFooter: ConfigureFooter
public let fetchHandler: FetchHandler
public init(
footerViewClass: UICollectionReusableView.Type = InfiniteLoadingCollectionViewFooter.self,
configureFooter: @escaping ConfigureFooter = { $0.startAnimating() },
fetchHandler: @escaping FetchHandler) {
self.footerViewClass = footerViewClass
self.configureFooter = configureFooter
self.fetchHandler = fetchHandler
}
}
private enum Constants {
static let SupplementaryViewReuseID = "SupplementaryViewReuseID"
static let InfinitePagingReuseID = "InfinitePagingReuseID"
static let Spacing: CGFloat = 20
}
#endif
| mit | ebabc55005f306ad0a7fe141e58f8c72 | 38.974943 | 202 | 0.634737 | 6.026442 | false | true | false | false |
IngmarStein/swift | test/Constraints/existential_metatypes.swift | 4 | 2719 | // RUN: %target-parse-verify-swift
protocol P {}
protocol Q {}
protocol PP: P {}
var qp: Q.Protocol
var pp: P.Protocol = qp // expected-error{{cannot convert value of type 'Q.Protocol' to specified type 'P.Protocol'}}
var qt: Q.Type
qt = qp // expected-error{{cannot assign value of type 'Q.Protocol' to type 'Q.Type'}}
qp = qt // expected-error{{cannot assign value of type 'Q.Type' to type 'Q.Protocol'}}
var pt: P.Type = qt // expected-error{{cannot convert value of type 'Q.Type' to specified type 'P.Type'}}
pt = pp // expected-error{{cannot assign value of type 'P.Protocol' to type 'P.Type'}}
pp = pt // expected-error{{cannot assign value of type 'P.Type' to type 'P.Protocol'}}
var pqt: (P & Q).Type
pt = pqt
qt = pqt
var pqp: (P & Q).Protocol
pp = pqp // expected-error{{cannot assign value of type '(P & Q).Protocol' to type 'P.Protocol'}}
qp = pqp // expected-error{{cannot assign value of type '(P & Q).Protocol' to type 'Q.Protocol'}}
var ppp: PP.Protocol
pp = ppp // expected-error{{cannot assign value of type 'PP.Protocol' to type 'P.Protocol'}}
var ppt: PP.Type
pt = ppt
var at: Any.Type
at = pt
var ap: Any.Protocol
ap = pp // expected-error{{cannot assign value of type 'P.Protocol' to type 'Any.Protocol'}}
ap = pt // expected-error{{cannot assign value of type 'P.Type' to type 'Any.Protocol'}}
// Meta-metatypes
protocol Toaster {}
class WashingMachine : Toaster {}
class Dryer : WashingMachine {}
class HairDryer {}
let a: Toaster.Type.Protocol = Toaster.Type.self
let b: Any.Type.Type = Toaster.Type.self
let c: Any.Type.Protocol = Toaster.Type.self // expected-error {{cannot convert value of type 'Toaster.Type.Protocol' to specified type 'Any.Type.Protocol'}}
let d: Toaster.Type.Type = WashingMachine.Type.self
let e: Any.Type.Type = WashingMachine.Type.self
let f: Toaster.Type.Type = Dryer.Type.self
let g: Toaster.Type.Type = HairDryer.Type.self // expected-error {{cannot convert value of type 'HairDryer.Type.Type' to specified type 'Toaster.Type.Type'}}
let h: WashingMachine.Type.Type = Dryer.Type.self // expected-error {{cannot convert value of type 'Dryer.Type.Type' to specified type 'WashingMachine.Type.Type'}}
func generic<T : WashingMachine>(_ t: T.Type) {
let _: Toaster.Type.Type = type(of: t)
}
// rdar://problem/20780797
protocol P2 {
init(x: Int)
var elements: [P2] {get}
}
extension P2 {
init() { self.init(x: 5) }
}
func testP2(_ pt: P2.Type) {
pt.init().elements // expected-warning {{expression of type '[P2]' is unused}}
}
// rdar://problem/21597711
protocol P3 {
func withP3(_ fn: (P3) -> ())
}
class Something {
func takeP3(_ p: P3) { }
}
func testP3(_ p: P3, something: Something) {
p.withP3(Something.takeP3(something))
}
| apache-2.0 | 94937bbd729491d1cf6d80ac30e1b52d | 30.252874 | 163 | 0.692534 | 3.103881 | false | false | false | false |
morgz/SwiftGoal | Carthage/Checkouts/Nimble/NimbleTests/AsynchronousTest.swift | 4 | 5417 | import XCTest
import Nimble
class AsyncTest: XCTestCase {
let errorToThrow = NSError(domain: NSInternalInconsistencyException, code: 42, userInfo: nil)
private func doThrowError() throws -> Int {
throw errorToThrow
}
func testToEventuallyPositiveMatches() {
var value = 0
deferToMainQueue { value = 1 }
expect { value }.toEventually(equal(1))
deferToMainQueue { value = 0 }
expect { value }.toEventuallyNot(equal(1))
}
func testToEventuallyNegativeMatches() {
let value = 0
failsWithErrorMessage("expected to eventually not equal <0>, got <0>") {
expect { value }.toEventuallyNot(equal(0))
}
failsWithErrorMessage("expected to eventually equal <1>, got <0>") {
expect { value }.toEventually(equal(1))
}
failsWithErrorMessage("expected to eventually equal <1>, got an unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.toEventually(equal(1))
}
failsWithErrorMessage("expected to eventually not equal <0>, got an unexpected error thrown: <\(errorToThrow)>") {
expect { try self.doThrowError() }.toEventuallyNot(equal(0))
}
}
func testWaitUntilPositiveMatches() {
waitUntil { done in
done()
}
waitUntil { done in
deferToMainQueue {
done()
}
}
}
func testWaitUntilTimesOutIfNotCalled() {
failsWithErrorMessage("Waited more than 1.0 second") {
waitUntil(timeout: 1) { done in return }
}
}
func testWaitUntilTimesOutWhenExceedingItsTime() {
var waiting = true
failsWithErrorMessage("Waited more than 0.01 seconds") {
waitUntil(timeout: 0.01) { done in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
NSThread.sleepForTimeInterval(0.1)
done()
waiting = false
}
}
}
// "clear" runloop to ensure this test doesn't poison other tests
repeat {
NSRunLoop.mainRunLoop().runUntilDate(NSDate().dateByAddingTimeInterval(0.2))
} while(waiting)
}
func testWaitUntilNegativeMatches() {
failsWithErrorMessage("expected to equal <2>, got <1>") {
waitUntil { done in
NSThread.sleepForTimeInterval(0.1)
expect(1).to(equal(2))
done()
}
}
}
func testWaitUntilDetectsStalledMainThreadActivity() {
let msg = "-waitUntil() timed out but was unable to run the timeout handler because the main thread is unresponsive (0.5 seconds is allow after the wait times out). Conditions that may cause this include processing blocking IO on the main thread, calls to sleep(), deadlocks, and synchronous IPC. Nimble forcefully stopped run loop which may cause future failures in test run."
failsWithErrorMessage(msg) {
waitUntil(timeout: 1) { done in
NSThread.sleepForTimeInterval(5.0)
done()
}
}
}
func testCombiningAsyncWaitUntilAndToEventuallyIsNotAllowed() {
let referenceLine = __LINE__ + 9
var msg = "Unexpected exception raised: Nested async expectations are not allowed "
msg += "to avoid creating flaky tests."
msg += "\n\n"
msg += "The call to\n\t"
msg += "expect(...).toEventually(...) at \(__FILE__):\(referenceLine + 7)\n"
msg += "triggered this exception because\n\t"
msg += "waitUntil(...) at \(__FILE__):\(referenceLine + 1)\n"
msg += "is currently managing the main run loop."
failsWithErrorMessage(msg) { // reference line
waitUntil(timeout: 2.0) { done in
var protected: Int = 0
dispatch_async(dispatch_get_main_queue()) {
protected = 1
}
expect(protected).toEventually(equal(1))
done()
}
}
}
func testWaitUntilErrorsIfDoneIsCalledMultipleTimes() {
waitUntil { done in
deferToMainQueue {
done()
}
}
waitUntil { done in
deferToMainQueue {
done()
expect {
done()
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
}
}
}
func testWaitUntilMustBeInMainThread() {
var executedAsyncBlock: Bool = false
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
expect {
waitUntil { done in done() }
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
executedAsyncBlock = true
}
expect(executedAsyncBlock).toEventually(beTruthy())
}
func testToEventuallyMustBeInMainThread() {
var executedAsyncBlock: Bool = false
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
expect {
expect(1).toEventually(equal(2))
}.to(raiseException(named: "InvalidNimbleAPIUsage"))
executedAsyncBlock = true
}
expect(executedAsyncBlock).toEventually(beTruthy())
}
}
| mit | a466bc1c87144a6b5b556817dd82ec48 | 34.638158 | 385 | 0.577072 | 5.159048 | false | true | false | false |
gtranchedone/NFYU | NFYU/AppDelegate.swift | 1 | 1502 | //
// AppDelegate.swift
// NFYU
//
// Created by Gianluca Tranchedone on 01/11/2015.
// Copyright © 2015 Gianluca Tranchedone. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var apiClient: APIClient = APIClient(requestSerializer: OpenWeatherAPIClientRequestSerializer(),
responseSerializer: OpenWeatherAPIClientResponseSerializer())
var userDefaults: UserDefaults = Foundation.UserDefaults.standard
var locationManager: UserLocationManager = SystemUserLocationManager()
var currentLocale: Locale = Locale.autoupdatingCurrent
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
updateRootViewController()
updateDefaultSettings()
return true
}
private func updateDefaultSettings() {
let measurementSystem = (currentLocale as NSLocale).object(forKey: NSLocale.Key.measurementSystem) as! String
userDefaults.useFahrenheitDegrees = (measurementSystem == "U.S.") // this is what iOS gives us
}
private func updateRootViewController() {
let viewController = window?.rootViewController as? WeatherViewController
viewController?.locationManager = locationManager
viewController?.userDefaults = userDefaults
viewController?.apiClient = apiClient
}
}
| mit | 73264eff0047fbd55455fc6b53c708d9 | 36.525 | 144 | 0.722851 | 6.151639 | false | false | false | false |
rymir/ConfidoIOS | ConfidoIOSTests/KeyPairTests.swift | 1 | 6846 | //
// KeyPairTests.swift
// ExpendSecurity
//
// Created by Rudolph van Graan on 19/08/2015.
//
import UIKit
import XCTest
import ConfidoIOS
class KeyPairTests: BaseTests {
func testGenerateNamedKeyPair() {
do {
clearKeychainItems(.Key)
var items = try Keychain.keyChainItems(SecurityClass.Key)
XCTAssertEqual(items.count,0)
let keypairDescriptor = PermanentKeychainKeyPairDescriptor(accessible: Accessible.WhenUnlockedThisDeviceOnly,
privateKeyAccessControl: nil, publicKeyAccessControl: nil,
keyType: .RSA, keySize: 1024, keyLabel: "AAA", keyAppTag: "BBB", keyAppLabel: "CCC")
var keyPair : KeychainKeyPair?
keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTAssertNotNil(keyPair)
items = try Keychain.keyChainItems(.Key)
XCTAssertEqual(items.count,2)
let keyDescriptor = KeychainKeyDescriptor(keyLabel: "AAA")
var keyItem: KeychainItem?
keyItem = try Keychain.fetchItem(matchingDescriptor: keyDescriptor)
XCTAssertNotNil(keyItem)
XCTAssertEqual(keyPair!.privateKey.keyType, KeyType.RSA)
XCTAssertEqual(keyPair!.publicKey.keyType, KeyType.RSA)
XCTAssertEqual(keyPair!.privateKey.keySize, 1024)
XCTAssertEqual(keyPair!.publicKey.keySize, 1024)
XCTAssertNotNil(keyPair!.privateKey.itemLabel)
XCTAssertEqual(keyPair!.privateKey.itemLabel!, "AAA")
XCTAssertNotNil(keyPair!.privateKey.keyAppTag)
XCTAssertEqual(keyPair!.privateKey.keyAppTag!, "BBB")
XCTAssertNotNil(keyPair!.privateKey.keyAppLabelString)
XCTAssertEqual(keyPair!.privateKey.keyAppLabelString!, "CCC")
XCTAssertEqual(keyPair!.publicKey.itemAccessGroup, "")
XCTAssertEqual(keyPair!.publicKey.itemAccessible, Accessible.WhenUnlockedThisDeviceOnly)
let publicKeyData = keyPair!.publicKey.keyData
XCTAssertNotNil(publicKeyData)
XCTAssertEqual(publicKeyData!.length,140)
} catch let error as NSError {
XCTFail("Unexpected Exception \(error)")
}
}
func testGenerateNamedKeyPairNoKeyLabel() {
do {
clearKeychainItems(.Key)
var items = try Keychain.keyChainItems(SecurityClass.Key)
XCTAssertEqual(items.count,0)
let keypairDescriptor = PermanentKeychainKeyPairDescriptor(
accessible: Accessible.AlwaysThisDeviceOnly,
privateKeyAccessControl: nil, publicKeyAccessControl: nil,
keyType: .RSA, keySize: 1024, keyLabel: "AAA")
var keyPair : KeychainKeyPair?
keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTAssertNotNil(keyPair)
items = try Keychain.keyChainItems(.Key)
XCTAssertEqual(items.count,2)
let keyDescriptor = KeychainKeyDescriptor(keyLabel: "AAA")
var keyItem: KeychainItem?
keyItem = try Keychain.fetchItem(matchingDescriptor: keyDescriptor)
XCTAssertNotNil(keyItem)
XCTAssertEqual(keyPair!.privateKey.keyType, KeyType.RSA)
XCTAssertEqual(keyPair!.publicKey.keyType, KeyType.RSA)
XCTAssertEqual(keyPair!.privateKey.keySize, 1024)
XCTAssertEqual(keyPair!.publicKey.keySize, 1024)
XCTAssertNotNil(keyPair!.privateKey.itemLabel)
XCTAssertEqual(keyPair!.privateKey.itemLabel!, "AAA")
XCTAssertNotNil(keyPair!.privateKey.keyAppTag)
XCTAssertEqual(keyPair!.privateKey.keyAppTag!, "")
XCTAssertNotNil(keyPair!.privateKey.keyAppLabelData)
//The keyAppLabel is equal to the hash of the public key by default
let publicKeyData = keyPair!.publicKey.keyData
XCTAssertNotNil(publicKeyData)
XCTAssertEqual(publicKeyData!.length,140)
} catch let error as NSError {
XCTFail("Unexpected Exception \(error)")
}
}
func testGenerateUnnamedKeyPair() {
do {
clearKeychainItems(.Key)
var items = try Keychain.keyChainItems(SecurityClass.Key)
XCTAssertEqual(items.count,0)
let keypairDescriptor = TemporaryKeychainKeyPairDescriptor(keyType: .RSA, keySize: 1024)
let keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTAssertNotNil(keyPair)
items = try Keychain.keyChainItems(.Key)
// Temporary keys are not stored in the keychain
XCTAssertEqual(items.count,0)
XCTAssertEqual(keyPair.privateKey.keySize, 1024)
XCTAssertEqual(keyPair.publicKey.keySize, 1024)
// There is no way to extract the data of a key for non-permanent keys
let publicKeyData = keyPair.publicKey.keyData
XCTAssertNil(publicKeyData)
} catch let error as NSError {
XCTFail("Unexpected Exception \(error)")
}
}
func testDuplicateKeyPairMatching() {
do {
clearKeychainItems(.Key)
var items = try Keychain.keyChainItems(SecurityClass.Key)
XCTAssertEqual(items.count,0)
var keypairDescriptor = PermanentKeychainKeyPairDescriptor(
accessible: Accessible.AlwaysThisDeviceOnly,
privateKeyAccessControl: nil, publicKeyAccessControl: nil,
keyType: .RSA, keySize: 1024, keyLabel: "A1", keyAppTag: "BBB", keyAppLabel: "CCC")
var keyPair : KeychainKeyPair? = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTAssertNotNil(keyPair)
items = try Keychain.keyChainItems(.Key)
XCTAssertEqual(items.count,2)
// Test that labels make the keypair unique
do {
keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTFail("Expected DuplicateItemError")
} catch KeychainStatus.DuplicateItemError {
// keySize, keyLabel, keyAppTag, keyAppLabel all the same --> DuplicateItemError
}
// different keySize
keypairDescriptor = PermanentKeychainKeyPairDescriptor(
accessible: Accessible.AlwaysThisDeviceOnly,
privateKeyAccessControl: nil, publicKeyAccessControl: nil,
keyType: .RSA, keySize: 2048, keyLabel: "A1", keyAppTag: "BBB", keyAppLabel: "CCC")
keyPair = try KeychainKeyPair.generateKeyPair(keypairDescriptor)
XCTAssertNotNil(keyPair)
} catch let error {
XCTFail("Unexpected Exception \(error)")
}
}
}
| mit | ae4aed6af25a2671f203ebb421b68dea | 35.222222 | 121 | 0.642857 | 5.743289 | false | false | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/Database.swift | 1 | 4905 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
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 appli-
-cable 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.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Structure representing a database reference.
@author Ferran Vila Conesa
@since v2.0
@version 1.0
*/
public class Database : APIBean {
/**
Indicates if database was created or needs to be created as Compressed.
*/
var compress : Bool?
/**
Database Name (name of the .db local file).
*/
var name : String?
/**
Default constructor
@since v2.0
*/
public override init() {
super.init()
}
/**
Default constructor. The compress param is setted to false.
@param name Name of the table.
@since v2.0
*/
public init(name: String) {
super.init()
self.name = name
}
/**
Constructor using fields.
@param name Name of the DatabaseTable.
@param compress Compression enabled.
@since v2.0
*/
public init(name: String, compress: Bool) {
super.init()
self.name = name
self.compress = compress
}
/**
Returns if the table is compressed
@return Compression enabled
@since v2.0
*/
public func getCompress() -> Bool? {
return self.compress
}
/**
Sets if the table is compressed or not.
@param compress Compression enabled
@since v2.0
*/
public func setCompress(compress: Bool) {
self.compress = compress
}
/**
Returns the name.
@return The name of the table.
@since v2.0
*/
public func getName() -> String? {
return self.name
}
/**
Sets the name of the table.
@param name The name of the table.
@since v2.0
*/
public func setName(name: String) {
self.name = name
}
/**
JSON Serialization and deserialization support.
*/
public struct Serializer {
public static func fromJSON(json : String) -> Database {
let data:NSData = json.dataUsingEncoding(NSUTF8StringEncoding)!
let dict = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
return fromDictionary(dict!)
}
static func fromDictionary(dict : NSDictionary) -> Database {
let resultObject : Database = Database()
if let value : AnyObject = dict.objectForKey("compress") {
if "\(value)" as NSString != "<null>" {
resultObject.compress = (value as! Bool)
}
}
if let value : AnyObject = dict.objectForKey("name") {
if "\(value)" as NSString != "<null>" {
resultObject.name = (value as! String)
}
}
return resultObject
}
public static func toJSON(object: Database) -> String {
let jsonString : NSMutableString = NSMutableString()
// Start Object to JSON
jsonString.appendString("{ ")
// Fields.
object.compress != nil ? jsonString.appendString("\"compress\": \(object.compress!), ") : jsonString.appendString("\"compress\": null, ")
object.name != nil ? jsonString.appendString("\"name\": \"\(JSONUtil.escapeString(object.name!))\"") : jsonString.appendString("\"name\": null")
// End Object to JSON
jsonString.appendString(" }")
return jsonString as String
}
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | fbf0b86797ff99f66c9771f48c1c64d4 | 27.017143 | 156 | 0.561289 | 4.903 | false | false | false | false |
wwq0327/iOS8Example | iOSFontList/iOSFontList/MasterViewModel.swift | 1 | 1180 | //
// MasterViewModel.swift
// iOSFontList
//
// Created by wyatt on 15/6/10.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
class MasterViewModel {
var familyNames: [String]
var fonts = [String: [String]]()
init() {
let unsortedFamilyNames = UIFont.familyNames() as! [String]
familyNames = sorted(unsortedFamilyNames)
let sorter = FontSorter()
for familyName in familyNames {
let unsortedFamilyNames = UIFont.fontNamesForFamilyName(familyName) as! [String]
fonts[familyName] = sorter.sortFontNames(unsortedFamilyNames)
}
}
func numberOfSections() -> Int {
return count(familyNames)
}
func numberOfRowsInSection(section: Int) -> Int {
// 取出相应字体的key
let key = familyNames[section]
// 取出值
let array = fonts[key]!
return count(array)
}
func titleAtIndexPath(indexPath: NSIndexPath) -> String {
let key = familyNames[indexPath.section]
let array = fonts[key]
let fontName = array![indexPath.row]
return fontName
}
}
| apache-2.0 | bfa8f80d1b1ad02e8efd2b80908b2013 | 25.318182 | 92 | 0.611399 | 4.577075 | false | false | false | false |
ajjnix/Remember | Remember/CALayer+Animation.swift | 1 | 1066 | import UIKit
extension CALayer {
typealias AnimationStarted = (CAAnimation) -> ()
typealias AnimationStopped = (CAAnimation, Bool) -> ()
func add(_ animation: CAAnimation,
forKey key: String? = nil,
onStart: @escaping AnimationStarted = nothing,
onStop: @escaping AnimationStopped = nothing) {
animation.delegate = ClosureAnimationDelegate(start: onStart, stop: onStop)
add(animation, forKey: key)
}
}
private final class ClosureAnimationDelegate: NSObject {
fileprivate let start: CALayer.AnimationStarted
fileprivate let stop: CALayer.AnimationStopped
init(start: @escaping CALayer.AnimationStarted, stop: @escaping CALayer.AnimationStopped) {
self.start = start
self.stop = stop
super.init()
}
}
extension ClosureAnimationDelegate: CAAnimationDelegate {
func animationDidStart(_ anim: CAAnimation) {
start(anim)
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
stop(anim, flag)
}
}
| mit | 3a27433c40f40c34b236ba080d718a3c | 28.611111 | 95 | 0.665103 | 4.86758 | false | false | false | false |
CKOTech/checkoutkit-ios | CheckoutKit/CheckoutKit/ResponseError.swift | 1 | 1733 | //
// ResponseError.swift
// CheckoutKit
//
// Created by Manon Henrioux on 13/08/2015.
// Copyright (c) 2015 Checkout.com. All rights reserved.
//
import Foundation
/** Class used to represent a error returned by the server after a request has failed. It contains all the information relative to this error/failure. */
open class ResponseError<T: Serializable> {
open var errorCode: String
open var message: String
open var errors: [String]
/**
Default constructor used by Gson to build the response automatically based on JSON data
@param errorCode String containing the error code if an error occurred
@param message String containing the message describing the error
@param errors Array of String containing more information on the errors that occurred
*/
public init(errorCode: String, message: String, errors: [String]) {
self.errorCode = errorCode;
self.message = message;
self.errors = errors;
}
/**
Convenience constructor
@param data: Dictionary [String: AnyObject] containing a JSON representation of a ResponseError instance
*/
public required init?(data: [String: AnyObject]) {
if let code = data["errorCode"] as? String, let msg = data["message"] as? String {
self.errorCode = code
self.message = msg
if let errorsData = data["errors"] as? [String] {
self.errors = errorsData
} else {
self.errors = []
}
} else {
self.errorCode = ""
self.message = ""
self.errors = []
return nil
}
}
}
| mit | 9606e7606180f87beb53ac7296b03309 | 26.507937 | 153 | 0.604732 | 4.827298 | false | false | false | false |
hsavit1/stampicon | StampIcon/main.swift | 1 | 1367 | //
// main.swift
// StampIcon
//
// Created by Jory Stiefel on 9/12/15.
// Copyright © 2015 Jory Stiefel. All rights reserved.
//
import Cocoa
func generateConfigFromArguments() -> StampConfig {
var config = StampConfig()
if Process.arguments.count == 1 {
print("stampicon by Jory Stiefel")
print("Usage: stampicon iconfile.png --text \"stamp text\" --output outputfile.png\n")
exit(0)
}
for idx in 1..<Process.arguments.count {
let argument = Process.arguments[idx]
if idx == 1 {
config.inputFile = argument
continue
}
switch argument {
case "--text":
config.text = Process.arguments[idx+1]
case "--output":
config.outputFile = Process.arguments[idx+1]
case "--font":
config.fontName = Process.arguments[idx+1]
case "--textcolor":
config.textColor = NSColor(rgba: Process.arguments[idx+1])
case "--badgecolor":
config.badgeColor = NSColor(rgba: Process.arguments[idx+1])
default:
continue
}
}
return config
}
var config = generateConfigFromArguments()
let stamper = Stamper(config: config)
stamper.processStamp();
| mit | 6f0c7e6d8eb026eeb65dd058abd45324 | 21.766667 | 94 | 0.54612 | 4.406452 | false | true | false | false |
swift102016team5/mefocus | MeFocus/MeFocus/AutoCompleteGoal.swift | 1 | 1657 | //
// AutoCompleteGoal.swift
// MeFocus
//
// Created by Hao on 11/20/16.
// Copyright © 2016 Group5. All rights reserved.
//
import UIKit
import AutoCompleteTextField
protocol AutoCompleteGoalDelegate {
func onResignFirstResponder(suggestion:Suggestion)
func onResignFirstResponder(goal:String)
}
class AutoCompleteGoal: AutoCompleteTextField {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var autoCompleteGoalDelegate:AutoCompleteGoalDelegate?
override open func resignFirstResponder() -> Bool {
let responder = super.resignFirstResponder()
if let delegate = autoCompleteGoalDelegate {
let goal:String = text ?? ""
if let suggestion = SuggestionsManager.findByGoal(goal: goal){
delegate.onResignFirstResponder(suggestion: suggestion)
return responder
}
delegate.onResignFirstResponder(goal: goal)
}
return responder
}
}
extension AutoCompleteGoal:AutoCompleteTextFieldDataSource {
func autoCompleteTextFieldDataSource(_ autoCompleteTextField: AutoCompleteTextField) -> [String] {
let suggestions = SuggestionsManager.all
return suggestions.map({
(suggestion:Suggestion) in
if let name = suggestion.goal {
return name
}
return ""
})
}
}
| mit | de2540c023f8a8125d63d9d6285c9c1a | 24.090909 | 102 | 0.618961 | 5.557047 | false | false | false | false |
dathtcheapgo/Jira-Demo | Driver/MVC/Register/Model/CGActiveParam.swift | 1 | 2154 | //
// CGActiveParam.swift
//
// Created by Đinh Anh Huy on 10/31/16
// Copyright (c) . All rights reserved.
//
import Foundation
import ObjectMapper
public class CGActiveParam: Mappable {
// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kCGRegisterParamTypeKey: String = "type"
internal let kCGRegisterParamActivationKey: String = "activation"
internal let kCGRegisterParamMobileKey: String = "mobile"
internal let kCGRegisterParamCountryCodeKey: String = "country_code"
// MARK: Properties
public var type: String?
public var activation: CGActivation?
public var mobile: String?
public var countryCode: String?
// MARK: ObjectMapper Initalizers
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
init() { }
public required init?(map: Map){
activation = CGActivation()
}
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
public func mapping(map: Map) {
type <- map[kCGRegisterParamTypeKey]
activation <- map[kCGRegisterParamActivationKey]
mobile <- map[kCGRegisterParamMobileKey]
countryCode <- map[kCGRegisterParamCountryCodeKey]
}
}
extension CGActiveParam {
public class CGActivation: Mappable {
// MARK: Declaration for string constants to be used to decode and also serialize.
internal let kCGActivationCodeKey: String = "code"
// MARK: Properties
public var code: Int?
init() {
}
// MARK: ObjectMapper Initalizers
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
public required init?(map: Map){
}
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
public func mapping(map: Map) {
code <- map[kCGActivationCodeKey]
}
}
}
| mit | ca4aaeb8a26e3756816b128aff04c94c | 25.256098 | 90 | 0.639108 | 4.773836 | false | false | false | false |
lastobelus/eidolon | KioskTests/Bid Fulfillment/ConfirmYourBidViewControllerTests.swift | 6 | 1356 | import Quick
import Nimble
import Nimble_Snapshots
import ReactiveCocoa
@testable
import Kiosk
class ConfirmYourBidViewControllerTests: QuickSpec {
override func spec() {
var subject: ConfirmYourBidViewController!
var nav: FulfillmentNavigationController!
beforeEach {
subject = ConfirmYourBidViewController.instantiateFromStoryboard(fulfillmentStoryboard).wrapInFulfillmentNav() as! ConfirmYourBidViewController
nav = FulfillmentNavigationController(rootViewController:subject)
}
pending("looks right by default") {
subject.loadViewProgrammatically()
expect(subject) == snapshot("default")
}
it("shows keypad buttons") {
let keypadSubject = RACSubject()
subject.numberSignal = keypadSubject
subject.loadViewProgrammatically()
keypadSubject.sendNext("3")
expect(subject.numberAmountTextField.text) == "3"
}
pending("changes enter button to enabled") {
let keypadSubject = RACSubject()
subject.numberSignal = keypadSubject
subject.loadViewProgrammatically()
expect(subject.enterButton.enabled) == false
keypadSubject.sendNext(3)
expect(subject.enterButton.enabled) == true
}
}
}
| mit | 42f4bdc20ddf8a95a2aa3bcf690c9183 | 29.133333 | 155 | 0.65708 | 6.108108 | false | false | false | false |
quintonwall/SObjectKit | Example/SObjectKit/AppDelegate.swift | 1 | 2887 | //
// AppDelegate.swift
// SObjectKit
//
// Created by quintonwall on 12/01/2016.
// Copyright (c) 2016 quintonwall. All rights reserved.
//
import UIKit
import SwiftlySalesforce
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, LoginDelegate {
var window: UIWindow?
//You will need to create your own connected app by following the instructions here:
// https://help.salesforce.com/articleView?id=connected_app_create.htm
let consumerKey = "ADD-YOUR-CONSUMER-KEY-HERE"
//eg: sobjectkit://success
let redirectURL = URL(string: "sobjectkit://success")!
//eg: na30.lightning.force.com
let hostname = "naXX.lightning.force.com"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
configureSalesforce(consumerKey: consumerKey, redirectURL: redirectURL)
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
handleRedirectURL(url: url)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 1f3bdaad1a43b96d6ad248542c6bb0b6 | 44.825397 | 285 | 0.737097 | 5.239564 | false | false | false | false |
mlavergn/swiftutil | Sources/app.swift | 1 | 2225 | /// App struct with package or bundle related helpers
///
/// - author: Marc Lavergne <[email protected]>
/// - copyright: 2017 Marc Lavergne. All rights reserved.
/// - license: MIT
import Foundation
#if os(iOS) || os(tvOS)
import UIKit
#endif
// MARK: - App struct
public struct App {
/// Application bundle identifier
public static var bundleId: String {
if let ident = Bundle.main.bundleIdentifier {
return ident
} else {
return "com.example.NoBundle"
}
}
/// Application bundle version
public static var bundleVersion: String {
if let version = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as? String {
return version
} else {
return "0"
}
}
/// Set a key value pair in the application plist
///
/// - Parameters:
/// - value: value as an Any
/// - key: plist key as a String
public static func setPlistKey(value: String, key: Any) {
if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
Log.debug(path)
if let plist = NSMutableDictionary.init(contentsOfFile: path) {
plist[key] = value
plist.write(toFile: path, atomically: true)
}
}
}
/// Change the app icon to the named plist icon, use nil for default icon
/// http://stackoverflow.com/questions/43097604/alternate-icon-in-ios-10-3
/// You MUST ask the user prior to changing the icon
private static func updateIcon(name: String?) {
#if os(iOS) || os(tvOS)
if #available(iOS 10.3, *) {
if UIApplication.shared.supportsAlternateIcons {
UIApplication.shared.setAlternateIconName(name) { (err: Error?) in
if err != nil {
Log.error(err!)
}
}
}
}
#endif
}
/// Bool with true if the application running in a sandbox, otherwise false
public static var isSandboxed: Bool {
let dir = NSHomeDirectory()
if let bundleName: String = Bundle.main.bundleIdentifier {
if dir.contains("/containers/" + bundleName) {
return true
}
}
return false
}
/// Bool with true if the application running in a simulator, otherwise false
public static var isSimulator: Bool {
let cwdPath = FileManager.default.currentDirectoryPath
if cwdPath.contains("/CoreSimulator/") {
return true
}
return false
}
}
| mit | e09b5ec2c94242305d80fabd4dc8621b | 25.488095 | 103 | 0.684944 | 3.52057 | false | false | false | false |
DRybochkin/Spika.swift | Spika/Utils/CSEmitJsonCreator.swift | 1 | 1555 | //
// EmitJsonCreator.h
// Prototype
//
// Created by Dmitry Rybochkin on 25.02.17.
// Copyright (c) 2015 Clover Studio. All rights reserved.
//
import Foundation
class CSEmitJsonCreator: NSObject {
class func createEmitSendMessage(_ message: CSMessageModel!, andUser user: CSUserModel!, andMessage messageTxt: String, andFile file: CSFileModel!, andLocation locationModel: CSLocationModel!) -> [AnyHashable: Any] {
var params = [AnyHashable: Any]()
params[paramRoomID] = user.roomID
params[paramUserID] = user.userID
params[paramType] = message.type
params[paramLocalID] = message.localID
params[paramMessage] = messageTxt
if (file != nil) {
var fileDict = [AnyHashable: Any]()
let fileInside: [AnyHashable: Any] = [paramId: file.file.id, paramName: file.file.name, paramSize: file.file.size, paramMimeType: file.file.mimeType]
fileDict[paramFile] = fileInside
if (file.thumb != nil) {
let thumbInside: [AnyHashable: Any] = [paramId: file.thumb.id, paramName: file.thumb.name, paramSize: file.thumb.size, paramMimeType: file.thumb.mimeType]
fileDict[paramThumb] = thumbInside
}
params[paramFile] = fileDict
}
if (locationModel != nil) {
let locationDict: [AnyHashable: Any] = [paramLat: NSNumber(value: locationModel.lat), paramLng: NSNumber(value: locationModel.lng)]
params[paramLocation] = locationDict
}
return params
}
}
| mit | d660cd19b67bc82b7414e9dc71b57ed3 | 46.121212 | 220 | 0.648875 | 4.070681 | false | false | false | false |
Nicholas-Swift/VaporServer | Sources/App/Controllers/UsersController.swift | 1 | 2472 | //
// UserController.swift
// VaporServer
//
// Created by Nicholas Swift on 4/9/17.
//
//
import Foundation
import Vapor
import HTTP
import Turnstile
import TurnstileCrypto
import TurnstileWeb
import JWT
class UsersController {
// MARK: Authentication
func create(request: Request) throws -> ResponseRepresentable {
// Get our credentials
guard let password = request.data["password"]?.string else {
throw Abort.custom(status: Status.badRequest, message: "Missing password")
}
let credentials = PasswordCredentials(password: password)
// Try to register the user
do {
let newUser = try User.register(credentials: credentials)
credentials.username = try newUser.makeNode()["username"]!.string!
try request.auth.login(credentials)
// Get the current signed-in user's ID
guard let user = try? request.user(), let userId = user.id?.int else {
throw Abort.custom(status: .unauthorized, message: "Please re authenticate")
}
// Gernare our token with the User ID
let payload = Node([ExpirationTimeClaim(Seconds(Authentication.Length)), SubjectClaim("\(userId)")])
let jwt = try JWT(payload: payload, signer: HS256(key: Authentication.AccessTokenSigningKey.makeBytes()))
return try JSON(node: ["success": true, "user": request.user().makeNode(), "token": jwt.createToken()])
} catch let e as TurnstileError {
throw Abort.custom(status: Status.badRequest, message: e.description)
}
}
// me
func me(request: Request) throws -> ResponseRepresentable {
return try JSON(node: request.user().makeNode())
}
}
// MARK: - User Request Extension
extension Request {
// Helper method to get the current user
func user() throws -> User {
guard let user = try auth.user() as? User else {
throw UnsupportedCredentialsError()
}
return user
}
// Base URL returns the hostname, scheme, and port in a URL string form. (?idk)
var baseURL: String {
return uri.scheme + "://" + uri.host + (uri.port == nil ? "" : ":\(uri.port!)")
}
// Exposes the Turnstile subject, as Vapor has a facade on it. (?idk)
var subject: Subject {
return storage["subject"] as! Subject
}
}
| mit | 7bfb8caba0fea1ed5dad35b8363d4279 | 31.526316 | 117 | 0.608414 | 4.681818 | false | false | false | false |
humeng12/DouYuZB | DouYuZB/Pods/Alamofire/Source/SessionDelegate.swift | 1 | 34183 | //
// SessionDelegate.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for handling all delegate callbacks for the underlying session.
@available(iOS 9.0, *)
open class SessionDelegate: NSObject {
// MARK: URLSessionDelegate Overrides
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didBecomeInvalidWithError:)`.
open var sessionDidBecomeInvalidWithError: ((URLSession, Error?) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)`.
open var sessionDidReceiveChallenge: ((URLSession, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionDelegate method `urlSession(_:didReceive:completionHandler:)` and requires the caller to call the `completionHandler`.
open var sessionDidReceiveChallengeWithCompletion: ((URLSession, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDelegate method `urlSessionDidFinishEvents(forBackgroundURLSession:)`.
open var sessionDidFinishEventsForBackgroundURLSession: ((URLSession) -> Void)?
// MARK: URLSessionTaskDelegate Overrides
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)`.
open var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskWillPerformHTTPRedirectionWithCompletion: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest, (URLRequest?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)`.
open var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:didReceive:completionHandler:)` and
/// requires the caller to call the `completionHandler`.
open var taskDidReceiveChallengeWithCompletion: ((URLSession, URLSessionTask, URLAuthenticationChallenge, (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)`.
open var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
/// Overrides all behavior for URLSessionTaskDelegate method `urlSession(_:task:needNewBodyStream:)` and
/// requires the caller to call the `completionHandler`.
open var taskNeedNewBodyStreamWithCompletion: ((URLSession, URLSessionTask, (InputStream?) -> Void) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:)`.
open var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionTaskDelegate method `urlSession(_:task:didCompleteWithError:)`.
open var taskDidComplete: ((URLSession, URLSessionTask, Error?) -> Void)?
// MARK: URLSessionDataDelegate Overrides
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)`.
open var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskDidReceiveResponseWithCompletion: ((URLSession, URLSessionDataTask, URLResponse, (URLSession.ResponseDisposition) -> Void) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didBecome:)`.
open var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:didReceive:)`.
open var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
/// Overrides default behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)`.
open var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
/// Overrides all behavior for URLSessionDataDelegate method `urlSession(_:dataTask:willCacheResponse:completionHandler:)` and
/// requires caller to call the `completionHandler`.
open var dataTaskWillCacheResponseWithCompletion: ((URLSession, URLSessionDataTask, CachedURLResponse, (CachedURLResponse?) -> Void) -> Void)?
// MARK: URLSessionDownloadDelegate Overrides
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didFinishDownloadingTo:)`.
open var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:)`.
open var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for URLSessionDownloadDelegate method `urlSession(_:downloadTask:didResumeAtOffset:expectedTotalBytes:)`.
open var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: URLSessionStreamDelegate Overrides
#if !os(watchOS)
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:readClosedFor:)`.
open var streamTaskReadClosed: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:writeClosedFor:)`.
open var streamTaskWriteClosed: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:betterRouteDiscoveredFor:)`.
open var streamTaskBetterRouteDiscovered: ((URLSession, URLSessionStreamTask) -> Void)?
/// Overrides default behavior for URLSessionStreamDelegate method `urlSession(_:streamTask:didBecome:outputStream:)`.
open var streamTaskDidBecomeInputAndOutputStreams: ((URLSession, URLSessionStreamTask, InputStream, OutputStream) -> Void)?
#endif
// MARK: Properties
var retrier: RequestRetrier?
weak var sessionManager: SessionManager?
private var requests: [Int: Request] = [:]
private let lock = NSLock()
/// Access the task delegate for the specified task in a thread-safe manner.
open subscript(task: URLSessionTask) -> Request? {
get {
lock.lock() ; defer { lock.unlock() }
return requests[task.taskIdentifier]
}
set {
lock.lock() ; defer { lock.unlock() }
requests[task.taskIdentifier] = newValue
}
}
// MARK: Lifecycle
/// Initializes the `SessionDelegate` instance.
///
/// - returns: The new `SessionDelegate` instance.
public override init() {
super.init()
}
// MARK: NSObject Overrides
/// Returns a `Bool` indicating whether the `SessionDelegate` implements or inherits a method that can respond
/// to a specified message.
///
/// - parameter selector: A selector that identifies a message.
///
/// - returns: `true` if the receiver implements or inherits a method that can respond to selector, otherwise `false`.
open override func responds(to selector: Selector) -> Bool {
#if !os(macOS)
if selector == #selector(URLSessionDelegate.urlSessionDidFinishEvents(forBackgroundURLSession:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
#if !os(watchOS)
switch selector {
case #selector(URLSessionStreamDelegate.urlSession(_:readClosedFor:)):
return streamTaskReadClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:writeClosedFor:)):
return streamTaskWriteClosed != nil
case #selector(URLSessionStreamDelegate.urlSession(_:betterRouteDiscoveredFor:)):
return streamTaskBetterRouteDiscovered != nil
case #selector(URLSessionStreamDelegate.urlSession(_:streamTask:didBecome:outputStream:)):
return streamTaskDidBecomeInputAndOutputStreams != nil
default:
break
}
#endif
switch selector {
case #selector(URLSessionDelegate.urlSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(URLSessionDelegate.urlSession(_:didReceive:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(URLSessionTaskDelegate.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(URLSessionDataDelegate.urlSession(_:dataTask:didReceive:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return type(of: self).instancesRespond(to: selector)
}
}
}
// MARK: - URLSessionDelegate
@available(iOS 9.0, *)
extension SessionDelegate: URLSessionDelegate {
/// Tells the delegate that the session has been invalidated.
///
/// - parameter session: The session object that was invalidated.
/// - parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
open func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/// Requests credentials from the delegate in response to a session-level authentication request from the
/// remote server.
///
/// - parameter session: The session containing the task that requested authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if
let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
#if !os(macOS)
/// Tells the delegate that all messages enqueued for a session have been delivered.
///
/// - parameter session: The session that no longer has any outstanding requests.
open func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
#endif
}
// MARK: - URLSessionTaskDelegate
@available(iOS 9.0, *)
extension SessionDelegate: URLSessionTaskDelegate {
/// Tells the delegate that the remote server requested an HTTP redirect.
///
/// - parameter session: The session containing the task whose request resulted in a redirect.
/// - parameter task: The task whose request resulted in a redirect.
/// - parameter response: An object containing the server’s response to the original request.
/// - parameter request: A URL request object filled out with the new location.
/// - parameter completionHandler: A closure that your handler should call with either the value of the request
/// parameter, a modified URL request object, or NULL to refuse the redirect and
/// return the body of the redirect response.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/// Requests credentials from the delegate in response to an authentication request from the remote server.
///
/// - parameter session: The session containing the task whose request requires authentication.
/// - parameter task: The task whose request requires authentication.
/// - parameter challenge: An object that contains the request for authentication.
/// - parameter completionHandler: A handler that your delegate method must call providing the disposition
/// and credential.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task]?.delegate {
delegate.urlSession(
session,
task: task,
didReceive: challenge,
completionHandler: completionHandler
)
} else {
urlSession(session, didReceive: challenge, completionHandler: completionHandler)
}
}
/// Tells the delegate when a task requires a new request body stream to send to the remote server.
///
/// - parameter session: The session containing the task that needs a new body stream.
/// - parameter task: The task that needs a new body stream.
/// - parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task]?.delegate {
delegate.urlSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/// Periodically informs the delegate of the progress of sending body content to the server.
///
/// - parameter session: The session containing the data task.
/// - parameter task: The data task.
/// - parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
/// - parameter totalBytesSent: The total number of bytes sent so far.
/// - parameter totalBytesExpectedToSend: The expected length of the body data.
open func urlSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task]?.delegate as? UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
#if !os(watchOS)
/// Tells the delegate that the session finished collecting metrics for the task.
///
/// - parameter session: The session collecting the metrics.
/// - parameter task: The task whose metrics have been collected.
/// - parameter metrics: The collected metrics.
@available(iOS 10.0, macOS 10.12, tvOS 10.0, *)
@objc(URLSession:task:didFinishCollectingMetrics:)
open func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
self[task]?.delegate.metrics = metrics
}
#endif
/// Tells the delegate that the task finished transferring data.
///
/// - parameter session: The session containing the task whose request finished transferring data.
/// - parameter task: The task whose request finished transferring data.
/// - parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
open func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
/// Executed after it is determined that the request is not going to be retried
let completeTask: (URLSession, URLSessionTask, Error?) -> Void = { [weak self] session, task, error in
guard let strongSelf = self else { return }
if let taskDidComplete = strongSelf.taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = strongSelf[task]?.delegate {
delegate.urlSession(session, task: task, didCompleteWithError: error)
}
NotificationCenter.default.post(
name: Notification.Name.Task.DidComplete,
object: strongSelf,
userInfo: [Notification.Key.Task: task]
)
strongSelf[task] = nil
}
guard let request = self[task], let sessionManager = sessionManager else {
completeTask(session, task, error)
return
}
// Run all validations on the request before checking if an error occurred
request.validations.forEach { $0() }
// Determine whether an error has occurred
var error: Error? = error
if let taskDelegate = self[task]?.delegate, taskDelegate.error != nil {
error = taskDelegate.error
}
/// If an error occurred and the retrier is set, asynchronously ask the retrier if the request
/// should be retried. Otherwise, complete the task by notifying the task delegate.
if let retrier = retrier, let error = error {
retrier.should(sessionManager, retry: request, with: error) { [weak self] shouldRetry, delay in
guard shouldRetry else { completeTask(session, task, error) ; return }
DispatchQueue.utility.after(delay) { [weak self] in
guard let strongSelf = self else { return }
let retrySucceeded = strongSelf.sessionManager?.retry(request) ?? false
if retrySucceeded, let task = request.task {
strongSelf[task] = request
return
} else {
completeTask(session, task, error)
}
}
}
} else {
completeTask(session, task, error)
}
}
}
// MARK: - URLSessionDataDelegate
@available(iOS 9.0, *)
extension SessionDelegate: URLSessionDataDelegate {
/// Tells the delegate that the data task received the initial reply (headers) from the server.
///
/// - parameter session: The session containing the data task that received an initial reply.
/// - parameter dataTask: The data task that received an initial reply.
/// - parameter response: A URL response object populated with headers.
/// - parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
/// constant to indicate whether the transfer should continue as a data task or
/// should become a download task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: URLSession.ResponseDisposition = .allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/// Tells the delegate that the data task was changed to a download task.
///
/// - parameter session: The session containing the task that was replaced by a download task.
/// - parameter dataTask: The data task that was replaced by a download task.
/// - parameter downloadTask: The new download task that replaced the data task.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
self[downloadTask]?.delegate = DownloadTaskDelegate(task: downloadTask)
}
}
/// Tells the delegate that the data task has received some of the expected data.
///
/// - parameter session: The session containing the data task that provided data.
/// - parameter dataTask: The data task that provided data.
/// - parameter data: A data object containing the transferred data.
open func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(session, dataTask: dataTask, didReceive: data)
}
}
/// Asks the delegate whether the data (or upload) task should store the response in the cache.
///
/// - parameter session: The session containing the data (or upload) task.
/// - parameter dataTask: The data (or upload) task.
/// - parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
/// caching policy and the values of certain received headers, such as the Pragma
/// and Cache-Control headers.
/// - parameter completionHandler: A block that your handler must call, providing either the original proposed
/// response, a modified version of that response, or NULL to prevent caching the
/// response. If your delegate implements this method, it must call this completion
/// handler; otherwise, your app leaks memory.
open func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask]?.delegate as? DataTaskDelegate {
delegate.urlSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
}
// MARK: - URLSessionDownloadDelegate
@available(iOS 9.0, *)
extension SessionDelegate: URLSessionDownloadDelegate {
/// Tells the delegate that a download task has finished downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that finished.
/// - parameter location: A file URL for the temporary file. Because the file is temporary, you must either
/// open the file for reading or move it to a permanent location in your app’s sandbox
/// container directory before returning from this delegate method.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(session, downloadTask: downloadTask, didFinishDownloadingTo: location)
}
}
/// Periodically informs the delegate about the download’s progress.
///
/// - parameter session: The session containing the download task.
/// - parameter downloadTask: The download task.
/// - parameter bytesWritten: The number of bytes transferred since the last time this delegate
/// method was called.
/// - parameter totalBytesWritten: The total number of bytes transferred so far.
/// - parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
/// header. If this header was not provided, the value is
/// `NSURLSessionTransferSizeUnknown`.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/// Tells the delegate that the download task has resumed downloading.
///
/// - parameter session: The session containing the download task that finished.
/// - parameter downloadTask: The download task that resumed. See explanation in the discussion.
/// - parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
/// existing content, then this value is zero. Otherwise, this value is an
/// integer representing the number of bytes on disk that do not need to be
/// retrieved again.
/// - parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
/// If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
open func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask]?.delegate as? DownloadTaskDelegate {
delegate.urlSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
}
// MARK: - URLSessionStreamDelegate
#if !os(watchOS)
@available(iOS 9.0, *)
extension SessionDelegate: URLSessionStreamDelegate {
/// Tells the delegate that the read side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, readClosedFor streamTask: URLSessionStreamTask) {
streamTaskReadClosed?(session, streamTask)
}
/// Tells the delegate that the write side of the connection has been closed.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, writeClosedFor streamTask: URLSessionStreamTask) {
streamTaskWriteClosed?(session, streamTask)
}
/// Tells the delegate that the system has determined that a better route to the host is available.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
open func urlSession(_ session: URLSession, betterRouteDiscoveredFor streamTask: URLSessionStreamTask) {
streamTaskBetterRouteDiscovered?(session, streamTask)
}
/// Tells the delegate that the stream task has been completed and provides the unopened stream objects.
///
/// - parameter session: The session.
/// - parameter streamTask: The stream task.
/// - parameter inputStream: The new input stream.
/// - parameter outputStream: The new output stream.
open func urlSession(
_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: OutputStream)
{
streamTaskDidBecomeInputAndOutputStreams?(session, streamTask, inputStream, outputStream)
}
}
#endif
| mit | 38ca7213e530a58db4ef7205f1037c0e | 48.74818 | 182 | 0.678731 | 6.189243 | false | false | false | false |
kylebrowning/waterwheel.swift | waterwheelDemo/waterwheelDemo-iOS/waterwheelDemo-iOS/LoginViewController.swift | 1 | 2182 | //
// ViewController.swift
// waterwheelDemo
//
// Created by Kyle Browning on 8/16/16.
// Copyright © 2016 Acquia. All rights reserved.
//
import UIKit
import waterwheel
// NO such module error? run `carthage update`
class LoginViewController: UIViewController {
@IBOutlet weak var authButton: waterwheelAuthButton!
override func viewDidLoad() {
super.viewDidLoad()
// Lets build our default waterwheelLoginViewController.
let vc = waterwheelLoginViewController()
// Lets add some default username and passwords so that we can demo login/logout
vc.usernameField.text = "waterwheelDemo"
vc.passwordField.text = "waterwheelDemo!"
// Lets add our function that will be run when the request is completed.
vc.loginRequestCompleted = { (success, error) in
if (success) {
// Do something related to a successfull login
print("successfull login")
self.dismiss(animated: true, completion: nil)
} else {
print (error!)
}
}
// Define our logout action
vc.logoutRequestCompleted = { (success, error) in
if (success) {
print("successfull logout")
// Do something related to a successfull logout
self.dismiss(animated: true, completion: nil)
} else {
print (error!)
}
}
// Define our cancel button action
vc.cancelButtonHit = {
self.dismiss(animated: true, completion: nil)
}
// Do any additional setup after loading the view, typically from a nib.
authButton.didPressLogin = {
// Lets Present our Login View Controller since this closure is for the loginButton press
self.present(vc, animated: true, completion: nil)
}
authButton.didPressLogout = { (success, error) in
print("logged out")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 2009ffb6a15ff8d8c0ea05b3084f42a5 | 29.291667 | 101 | 0.598808 | 4.956818 | false | false | false | false |
TinyCrayon/TinyCrayon-iOS-SDK | TCMask/HairBrushTool.swift | 1 | 3807 | //
// HairBrushTool.swift
// TinyCrayon
//
// Created by Xin Zeng on 6/22/16.
//
//
import UIKit
import TCCore
class HairBrushTool : Tool {
var imgSize: CGSize!
var canvasView: CanvasView!
var regionRect = CGRect()
var previousAlpha = [UInt8]()
var activeRegion = [UInt8]()
var regionContext: CGContext!
var sessionPoints = [(CGPoint, CGPoint, CGFloat)]()
init(maskView: MaskView, toolManager: ToolManager) {
super.init(type: TCMaskTool.hairBrush, maskView: maskView, toolManager: toolManager)
self.imgSize = maskView.image.size
previousAlpha = [UInt8](repeating: 0, count: maskView.opacity.count)
TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count)
activeRegion = [UInt8](repeating: UInt8(GM_UNINIT), count: maskView.opacity.count)
regionContext = CGContext(data: &activeRegion, width: Int(imgSize.width), height: Int(imgSize.height), bitsPerComponent: 8, bytesPerRow: Int(imgSize.width), space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.alphaOnly.rawValue)!
regionContext.setLineCap(CGLineCap.round)
regionContext.setLineJoin(CGLineJoin.round)
regionContext.setShouldAntialias(false)
// CGContextDrawImage draws image upside down
// http://stackoverflow.com/questions/506622/cgcontextdrawimage-draws-image-upside-down-when-passed-uiimage-cgimage
regionContext.translateBy(x: 0, y: imgSize.height)
regionContext.scaleBy(x: 1.0, y: -1.0)
}
override func refresh() {
maskView.refresh()
}
override func invert() {
TCCore.invertAlpha(&maskView.opacity, count: maskView.opacity.count)
TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count)
refresh()
}
override func touchBegan(_ location: CGPoint) {
notifyWillBeginProcessing()
}
override func touchMoved(_ previousLocation: CGPoint, _ location: CGPoint) {
let scaleFactor = maskView.scaleFactor
let scrollView = maskView.scrollView!
let params = delegate.getToolParams()
let p1 = previousLocation * scaleFactor
let p2 = location * scaleFactor
let lineWidth = min(60, CGFloat(params.hairBrushBrushSize) * scaleFactor / scrollView.zoomScale)
let color = UIColor(white: 0, alpha: CGFloat(GM_UNKNOWN) / 255.0)
let rect = CGContextDrawLine(regionContext, p1: p1, p2: p2, lineWidth: lineWidth, color: color.cgColor)
let paintColor = UIColor(white: 0, alpha: CGFloat(params.add ? GM_FGD : GM_BGD) / 255.0)
_ = CGContextDrawLine(regionContext, p1: p1, p2: p2, lineWidth: lineWidth / 2, color: paintColor.cgColor)
if (TCCore.imageFiltering(self.maskView.imageData, size: imgSize, alpha: &maskView.opacity, region: activeRegion, rect: rect, add: params.add)) {
let mattingImage = TCCore.image(fromAlpha: maskView.opacity, size: imgSize, rect: rect)!
maskView.drawImgToCache(mattingImage, rect: rect)
sessionPoints.append((p1, p2, lineWidth))
}
let uninitColor = UIColor(white: 0, alpha: CGFloat(GM_UNINIT) / 255.0)
CGContextFillRect(regionContext, rect: rect, color: uninitColor.cgColor)
}
override func touchEnded(_ previousLocation: CGPoint, _ location: CGPoint) {
self.sessionPoints.removeAll()
self.notifyDidEndProcessing()
}
override func notifyDidEndProcessing() {
toolManager.pushLogOfHairBrush(previousAlpha: previousAlpha, currentAlpha: maskView.opacity)
TCCore.arrayCopy(&previousAlpha, src: maskView.opacity, count: previousAlpha.count)
super.notifyDidEndProcessing()
}
}
| mit | 9551f27d21394968235fe2678184505b | 42.261364 | 253 | 0.679538 | 4.306561 | false | false | false | false |
iamshezad/SHTransition | Example/Example/AppDelegate.swift | 1 | 4610 | //
// AppDelegate.swift
// Example
//
// Created by Focaloid Technologies on 22/08/17.
// Copyright © 2017 Focaloid Technologies. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Example")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | fd85afd31ef46b37152da44ec2ee85f8 | 48.55914 | 285 | 0.686917 | 5.863868 | false | false | false | false |
wftllc/hahastream | Haha Stream/HahaService/Models/Game.swift | 1 | 3489 | import Foundation
class Game: NSObject, FromDictable {
let MaximumTimeIntervalToBeConsideredActive:TimeInterval = -4*60*60;
public var uuid: String;
public var title: String;
private var ready: Bool;
private var isReady: Bool { get {
return ready || readyDate <= Date()
}}
private var ended: Bool
public var startDate: Date;
public var readyDate: Date;
public var free: Bool;
public var homeTeam: Team;
public var awayTeam: Team;
public var sport: Sport;
public var isActive: Bool {
return isReady && startDate.timeIntervalSinceNow > MaximumTimeIntervalToBeConsideredActive
}
public var isUpcoming: Bool {
return startDate.timeIntervalSinceNow > 0;
}
public var startTimeString: String {
return Game.timeFormatter.string(from: startDate)
}
static var dateFormatter: ISO8601DateFormatter = {
let df = ISO8601DateFormatter();
df.formatOptions = [.withFullDate, .withTime, .withDashSeparatorInDate, .withColonSeparatorInTime]
return df;
}()
static var timeFormatter: DateFormatter = {
let df = DateFormatter();
df.locale = Locale.autoupdatingCurrent
df.timeStyle = .short
df.dateStyle = .none
return df;
}()
static func fromDictionary(_ dict:[String: Any]?) throws -> Self {
guard let dict = dict else { throw FromDictableError.keyError(key: "<root>") }
let uuid: String = try dict.value("uuid")
let ready: Bool = (try? dict.value("live")) ?? false
let ended: Bool = try dict.value("ended")
let title: String = try dict.value("title")
let sportDict: [String: Any] = try dict.value("sport")
let sport = try Sport.fromDictionary(sportDict)
let startDateString: String = try dict.value("start_in_gmt")
guard let date = self.dateFormatter.date(from: startDateString) else {
throw FromDictableError.otherError(reason: "couldn't parse start_in_gmt")
}
let readyDateString: String = try dict.value("ready_at")
guard let readyDate = self.dateFormatter.date(from: readyDateString) else {
throw FromDictableError.otherError(reason: "couldn't parse ready_at")
}
let homeTeam: Team = try Team.fromDictionary(dict.value("home_team"))
let awayTeam: Team = try Team.fromDictionary(dict.value("away_team"))
return self.init(uuid: uuid,
sport: sport,
title: title,
ready: ready,
ended: ended,
startDate: date,
readyDate: readyDate,
free: false,
homeTeam: homeTeam,
awayTeam: awayTeam
);
}
required init(uuid: String,
sport: Sport,
title: String,
ready: Bool,
ended: Bool,
startDate: Date,
readyDate: Date,
free: Bool,
homeTeam: Team,
awayTeam: Team
) {
self.uuid = uuid;
self.sport = sport
self.homeTeam = homeTeam;
self.awayTeam = awayTeam;
self.free = free;
self.ready = ready;
self.ended = ended
self.title = title;
self.startDate = startDate;
self.readyDate = readyDate;
}
override var description : String {
return "\(title)";
}
public var singleImageURL: URL? {
return URL(string: "https://logos.hehestreams.xyz/image/vue_channels/\(self.uuid).png")
}
public var playActionURL: URL? {
//TODO: url escape
return URL(string: "hahastream://play/game/\(self.sport.name)/\(self.uuid)")
}
public var displayActionURL: URL? {
return URL(string: "hahastream://open/game/\(self.sport.name)/\(self.uuid)")
}
}
| mit | 2189974cd63c35f640348deb250aa5a3 | 26.690476 | 100 | 0.664947 | 3.676502 | false | false | false | false |
dreamsxin/swift | test/DebugInfo/bbentry-location.swift | 4 | 1065 | // REQUIRES: OS=ios
// REQUIRES: objc_interop
// RUN: %target-swift-frontend -emit-ir -g %s -o - | FileCheck %s
import UIKit
@available(iOS, introduced: 8.0)
class ActionViewController
{
var imageView: UIImageView!
func viewDidLoad(_ inputItems: [AnyObject]) {
for item: AnyObject in inputItems {
let inputItem = item as! NSExtensionItem
for provider: AnyObject in inputItem.attachments! {
let itemProvider = provider as! NSItemProvider
// CHECK: load {{.*}}selector
// CHECK:; <label>{{.*}} ; preds = %{{[0-9]+}}
// CHECK: @rt_swift_allocObject({{.*}}, !dbg ![[DBG:[0-9]+]]
// Test that the location is reset at the entry of a new basic block.
// CHECK: ![[DBG]] = {{.*}}line: 0
if itemProvider.hasItemConformingToTypeIdentifier("") {
weak var weakImageView = self.imageView
itemProvider.loadItem(forTypeIdentifier: "", options: nil,
completionHandler: { (image, error) in
if let imageView = weakImageView {
}
})
}
}
}
}
}
| apache-2.0 | 72ada6faf4ff436144f366ddbc1e9c1c | 33.354839 | 77 | 0.605634 | 4.364754 | false | false | false | false |
storehouse/Advance | Sources/Advance/Animator.swift | 1 | 6483 | import Foundation
/// Manages the application of animations to a value.
///
/// ```
/// let view = UIView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
///
/// let sizeAnimator = Animator(initialValue: view.bounds.size)
/// sizeAnimator.onChange = { view.bounds.size = $0 }
///
/// /// Spring physics will move the view's size to the new value.
/// sizeAnimator.spring(to: CGSize(width: 300, height: 300))
///
/// /// Some time in the future...
///
/// /// The value will keep the same velocity that it had from the preceeding
/// /// animation, and a decay function will slowly bring movement to a stop.
/// sizeAnimator.decay(drag: 2.0)
/// ```
///
public final class Animator<Value: VectorConvertible> {
/// Called every time the animator's `value` changes.
public var onChange: ((Value) -> Void)? = nil {
didSet {
dispatchPrecondition(condition: .onQueue(.main))
}
}
private let displayLink = DisplayLink()
private var state: State {
didSet {
dispatchPrecondition(condition: .onQueue(.main))
displayLink.isPaused = state.isAtRest
if state.value.animatableData != oldValue.value.animatableData {
onChange?(state.value)
}
}
}
/// Initializes a new animator with the given value.
public init(initialValue: Value) {
dispatchPrecondition(condition: .onQueue(.main))
state = .atRest(value: initialValue)
displayLink.onFrame = { [weak self] (frame) in
self?.advance(by: frame.duration)
}
}
private func advance(by time: Double) {
dispatchPrecondition(condition: .onQueue(.main))
state.advance(by: time)
}
/// assigning to this value will remove any running animation.
public var value: Value {
get {
dispatchPrecondition(condition: .onQueue(.main))
return state.value
}
set {
dispatchPrecondition(condition: .onQueue(.main))
state = .atRest(value: newValue)
}
}
/// The current velocity of the animator.
public var velocity: Value {
dispatchPrecondition(condition: .onQueue(.main))
return state.velocity
}
/// Animates the property using the given animation.
public func animate(to finalValue: Value, duration: Double, timingFunction: TimingFunction = .swiftOut) {
dispatchPrecondition(condition: .onQueue(.main))
state.animate(to: finalValue, duration: duration, timingFunction: timingFunction)
}
/// Animates the property using the given simulation function, imparting the specified initial velocity into the simulation.
public func simulate<T>(using function: T, initialVelocity: T.Value) where T: SimulationFunction, T.Value == Value {
dispatchPrecondition(condition: .onQueue(.main))
state.simulate(using: function, initialVelocity: initialVelocity)
}
/// Animates the property using the given simulation function.
public func simulate<T>(using function: T) where T: SimulationFunction, T.Value == Value {
dispatchPrecondition(condition: .onQueue(.main))
state.simulate(using: function)
}
/// Removes any active animation, freezing the animator at the current value.
public func cancelRunningAnimation() {
dispatchPrecondition(condition: .onQueue(.main))
state = .atRest(value: state.value)
}
}
extension Animator {
fileprivate enum State {
case atRest(value: Value)
case animating(animation: Animation<Value>)
case simulating(simulation: Simulation<Value>)
mutating func advance(by time: Double) {
switch self {
case .atRest: break
case .animating(var animation):
animation.advance(by: time)
if animation.isFinished {
self = .atRest(value: animation.value)
} else {
self = .animating(animation: animation)
}
case .simulating(var simulation):
simulation.advance(by: time)
if simulation.hasConverged {
self = .atRest(value: simulation.value)
} else {
self = .simulating(simulation: simulation)
}
}
}
var isAtRest: Bool {
switch self {
case .atRest: return true
case .animating: return false
case .simulating: return false
}
}
var value: Value {
switch self {
case .atRest(let value): return value
case .animating(let animation): return animation.value
case .simulating(let simulation): return simulation.value
}
}
var velocity: Value {
switch self {
case .atRest(let value):
var result = value
result.animatableData = .zero
return result
case .animating(let animation): return animation.velocity
case .simulating(let simulation): return simulation.velocity
}
}
mutating func animate(to finalValue: Value, duration: Double, timingFunction: TimingFunction) {
let animation = Animation(
from: self.value,
to: finalValue,
duration: duration,
timingFunction: timingFunction)
self = .animating(animation: animation)
}
mutating func simulate<T>(using function: T, initialVelocity: Value) where T: SimulationFunction, T.Value == Value {
let simulation = Simulation(
function: function,
initialValue: self.value,
initialVelocity: initialVelocity)
self = .simulating(simulation: simulation)
}
mutating func simulate<T>(using function: T) where T: SimulationFunction, T.Value == Value {
switch self {
case .atRest, .animating:
self.simulate(using: function, initialVelocity: self.velocity)
case .simulating(var simulation):
simulation.use(function: function)
self = .simulating(simulation: simulation)
}
}
}
}
| bsd-2-clause | d6d0f46ba1c5d71e6f79fad99d797264 | 34.233696 | 128 | 0.58476 | 5.080721 | false | false | false | false |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift100Tips/Swift100Tips/InitNilController.swift | 1 | 2364 | //
// InitNilController.swift
// Swift100Tips
//
// Created by 沈兆良 on 16/5/27.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class InitNilController: UIViewController {
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.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension Int {
init?(fromString: String) {
self = 0
var digit = fromString.characters.count - 1
for c in fromString.characters {
var number = 0
if let n = Int(String(c)) {
number = n
} else {
switch c {
case "一": number = 1
case "二": number = 2
case "三": number = 3
case "四": number = 4
case "五": number = 5
case "六": number = 6
case "七": number = 7
case "八": number = 8
case "九": number = 9
case "零": number = 0
default: return nil
}
}
self = self + number * Int(pow(10, Double(digit)))
digit = digit - 1
}
}
}
let number1 = Int(fromString: "12")
// {Some 12}
let number2 = Int(fromString: "三二五")
// {Some 325}
let number3 = Int(fromString: "七9八")
// {Some 798}
let number4 = Int(fromString: "吃了么")
// nil
let number5 = Int(fromString: "1a4n")
// nil
//为了简化 API 和安全,Apple 已经被标记为不可用了并无法编译。而对应地,可能返回 nil 的 init 方法都加上了 ? 标记:
//convenience init?(string URLString: String)
//在新版本的 Swift 中,对于可能初始化失败的情况,我们应该始终使用可返回 nil 的初始化方法,而不是类型工厂方法。 | mit | f1c9434a419bc99963e807507999cf02 | 23.860465 | 106 | 0.559663 | 3.972119 | false | false | false | false |
parkera/swift-corelibs-foundation | Foundation/NSTextCheckingResult.swift | 1 | 4824 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/* NSTextCheckingType in this project is limited to regular expressions. */
extension NSTextCheckingResult {
public struct CheckingType : OptionSet {
public let rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
public static let RegularExpression = CheckingType(rawValue: 1 << 10) // regular expression matches
}
}
open class NSTextCheckingResult: NSObject, NSCopying, NSCoding {
public override init() {
if type(of: self) == NSTextCheckingResult.self {
NSRequiresConcreteImplementation()
}
}
open class func regularExpressionCheckingResultWithRanges(_ ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) -> NSTextCheckingResult {
return _NSRegularExpressionNSTextCheckingResultResult(ranges: ranges, count: count, regularExpression: regularExpression)
}
public required init?(coder aDecoder: NSCoder) {
if type(of: self) == NSTextCheckingResult.self {
NSRequiresConcreteImplementation()
}
}
open func encode(with aCoder: NSCoder) {
NSRequiresConcreteImplementation()
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
/* Mandatory properties, used with all types of results. */
open var resultType: CheckingType { NSRequiresConcreteImplementation() }
open var range: NSRange { return range(at: 0) }
/* A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups). The range at index 0 always matches the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1. */
open func range(at idx: Int) -> NSRange { NSRequiresConcreteImplementation() }
@available(macOS 10.13, iOS 11.0, watchOS 4.0, tvOS 11.0, *)
open func range(withName: String) -> NSRange { NSRequiresConcreteImplementation() }
open var regularExpression: NSRegularExpression? { return nil }
open var numberOfRanges: Int { return 1 }
}
internal class _NSRegularExpressionNSTextCheckingResultResult : NSTextCheckingResult {
var _ranges = [NSRange]()
let _regularExpression: NSRegularExpression
init(ranges: NSRangePointer, count: Int, regularExpression: NSRegularExpression) {
_regularExpression = regularExpression
super.init()
let notFound = NSRange(location: NSNotFound,length: 0)
for i in 0..<count {
ranges[i].location == kCFNotFound ? _ranges.append(notFound) : _ranges.append(ranges[i])
}
}
internal required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
internal override func encode(with aCoder: NSCoder) {
NSUnimplemented()
}
override var resultType: CheckingType { return .RegularExpression }
override func range(at idx: Int) -> NSRange { return _ranges[idx] }
override func range(withName name: String) -> NSRange {
let idx = _regularExpression._captureGroupNumber(withName: name)
if idx != kCFNotFound, idx < numberOfRanges {
return range(at: idx)
}
return NSRange(location: NSNotFound, length: 0)
}
override var numberOfRanges: Int { return _ranges.count }
override var regularExpression: NSRegularExpression? { return _regularExpression }
}
extension NSTextCheckingResult {
public func adjustingRanges(offset: Int) -> NSTextCheckingResult {
let count = self.numberOfRanges
var newRanges = [NSRange]()
for idx in 0..<count {
let currentRange = self.range(at: idx)
if (currentRange.location == NSNotFound) {
newRanges.append(currentRange)
} else if ((offset > 0 && NSNotFound - currentRange.location <= offset) || (offset < 0 && currentRange.location < -offset)) {
NSInvalidArgument(" \(offset) invalid offset for range {\(currentRange.location), \(currentRange.length)}")
} else {
newRanges.append(NSRange(location: currentRange.location + offset,length: currentRange.length))
}
}
let result = NSTextCheckingResult.regularExpressionCheckingResultWithRanges(&newRanges, count: count, regularExpression: self.regularExpression!)
return result
}
}
| apache-2.0 | dfe97e7f67ad073616ea1f23a0ea3698 | 39.881356 | 271 | 0.679312 | 5.083246 | false | false | false | false |
tnantoka/GameplayKitSandbox | GameplayKitSandbox/HouseWetState.swift | 1 | 814 | //
// HouseWetState.swift
// GameplayKitSandbox
//
// Created by Tatsuya Tobioka on 2015/09/22.
// Copyright © 2015年 tnantoka. All rights reserved.
//
import UIKit
import GameplayKit
class HouseWetState: HouseState {
var remainingTime: TimeInterval = 0
override func isValidNextState(_ stateClass: AnyClass) -> Bool {
return stateClass == HouseDryState.self
}
override func didEnter(from previousState: GKState?) {
if let component = entity.component(ofType: BurnableComponent.self) {
component.useWetAppearance()
remainingTime = 3.0
}
}
override func update(deltaTime seconds: TimeInterval) {
remainingTime -= seconds
if remainingTime < 0 {
stateMachine?.enter(HouseDryState.self)
}
}
}
| mit | f8b49c875a66d865873e7b86d969d2fc | 22.852941 | 77 | 0.65598 | 4.55618 | false | false | false | false |
Mashape/httpsnippet | test/fixtures/output/swift/nsurlsession/https.swift | 2 | 574 | import Foundation
let request = NSMutableURLRequest(url: NSURL(string: "https://mockbin.com/har")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
| mit | 1aaf334c62f59234f07d1629ac3ae1e2 | 30.888889 | 116 | 0.632404 | 4.592 | false | false | false | false |
Vadim-Yelagin/DataSourceExample | DataSourceExample/Helpers/RandomData.swift | 1 | 1174 | //
// RandomData.swift
// DataSourceExample
//
// Created by Vadim Yelagin on 16/07/15.
// Copyright (c) 2015 Fueled. All rights reserved.
//
import Foundation
import DataSource
import UIKit
func random(_ x: Int) -> Int {
return Int(arc4random_uniform(UInt32(x)))
}
struct RandomData {
static func spell(_ number: Int) -> String {
let nf = NumberFormatter()
nf.numberStyle = .spellOut
nf.formattingContext = .standalone
return nf.string(from: NSNumber(value: number as Int))!
}
static func title(_ value: Int = 1000) -> String {
return self.spell(random(value))
}
static func items(_ count: Int = 5, value: Int = 1000) -> [ExampleItem] {
let n = 1 + random(count)
return (0 ..< n).map { _ in
ExampleItem(self.title(value))
}
}
static func section() -> DataSourceSection<ExampleItem> {
let title = self.title()
return DataSourceSection(items: self.items(),
supplementaryItems: [UICollectionView.elementKindSectionHeader: title])
}
static func dataSource() -> StaticDataSource<ExampleItem> {
let n = 1 + random(5)
let sections = (0 ..< n).map { _ in
self.section()
}
return StaticDataSource(sections: sections)
}
}
| mit | dea36ae3215e674b9703e78cce076658 | 22.019608 | 74 | 0.678876 | 3.354286 | false | false | false | false |
Raizlabs/RIGImageGallery | RIGImageGalleryDemo/View Controller/ViewController.swift | 1 | 6965 | //
// ViewController.swift
// RigPhotoViewerDemo
//
// Created by Michael Skiba on 2/8/16.
// Copyright © 2016 Raizlabs. All rights reserved.
//
import UIKit
import RIGImageGallery
class ViewController: UIViewController {
fileprivate let imageSession = URLSession(configuration: .default)
override func loadView() {
view = UIView()
view.backgroundColor = .white
navigationItem.title = NSLocalizedString("RIG Image Gallery", comment: "Main screen title")
let remoteGalleryButton = UIButton(type: .system)
remoteGalleryButton.addTarget(self, action: #selector(ViewController.showOnlineGallery(_:)), for: .touchUpInside)
remoteGalleryButton.setTitle(NSLocalizedString("Show Online Gallery", comment: "Show gallery button title"), for: .normal)
let localGalleryButton = UIButton(type: .system)
localGalleryButton.setTitle(NSLocalizedString("Show Local Gallery", comment: "Show Local Gallery"), for: .normal)
localGalleryButton.addTarget(self, action: #selector(ViewController.showLocalGallery(_:)), for: .touchUpInside)
let stackView = UIStackView(arrangedSubviews: [remoteGalleryButton, localGalleryButton])
stackView.alignment = .center
stackView.axis = .vertical
stackView.isLayoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
stackView.distribution = .fill
stackView.spacing = 10
view.addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
let constraints: [NSLayoutConstraint] = [
stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
stackView.bottomAnchor.constraint(lessThanOrEqualTo: bottomLayoutGuide.topAnchor),
stackView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor),
]
NSLayoutConstraint.activate(constraints)
}
}
private extension ViewController {
@objc func showOnlineGallery(_ sender: UIButton) {
let photoViewController = prepareRemoteGallery()
photoViewController.dismissHandler = dismissPhotoViewer
photoViewController.actionButtonHandler = actionButtonHandler
photoViewController.actionButton = UIBarButtonItem(barButtonSystemItem: .action, target: nil, action: nil)
photoViewController.traitCollectionChangeHandler = traitCollectionChangeHandler
photoViewController.countUpdateHandler = updateCount
let navigationController = navBarWrappedViewController(photoViewController)
present(navigationController, animated: true, completion: nil)
}
@objc func showLocalGallery(_ sender: UIButton) {
let photoViewController = prepareLocalGallery()
photoViewController.dismissHandler = dismissPhotoViewer
photoViewController.actionButtonHandler = actionButtonHandler
photoViewController.actionButton = UIBarButtonItem(barButtonSystemItem: .action, target: nil, action: nil)
photoViewController.traitCollectionChangeHandler = traitCollectionChangeHandler
photoViewController.countUpdateHandler = updateCount
let navigationController = navBarWrappedViewController(photoViewController)
present(navigationController, animated: true, completion: nil)
}
}
private extension ViewController {
func dismissPhotoViewer(_ :RIGImageGalleryViewController) {
dismiss(animated: true, completion: nil)
}
func actionButtonHandler(_: RIGImageGalleryViewController, galleryItem: RIGImageGalleryItem) {
}
func updateCount(_ gallery: RIGImageGalleryViewController, position: Int, total: Int) {
gallery.countLabel.text = "\(position + 1) of \(total)"
}
func traitCollectionChangeHandler(_ photoView: RIGImageGalleryViewController) {
let isPhone = UITraitCollection(userInterfaceIdiom: .phone)
let isCompact = UITraitCollection(verticalSizeClass: .compact)
let allTraits = UITraitCollection(traitsFrom: [isPhone, isCompact])
photoView.doneButton = photoView.traitCollection.containsTraits(in: allTraits) ? nil : UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: nil)
}
}
private extension ViewController {
static let urls: [URL] = [
"https://placehold.it/1920x1080",
"https://placehold.it/1080x1920",
"https://placehold.it/350x150",
"https://placehold.it/150x350",
].flatMap(URL.init(string:))
func prepareRemoteGallery() -> RIGImageGalleryViewController {
let urls = type(of: self).urls
let rigItems: [RIGImageGalleryItem] = urls.map { url in
RIGImageGalleryItem(placeholderImage: #imageLiteral(resourceName: "placeholder"),
title: url.pathComponents.last ?? "",
isLoading: true)
}
let rigController = RIGImageGalleryViewController(images: rigItems)
for (index, URL) in urls.enumerated() {
let completion = rigController.handleImageLoadAtIndex(index)
let request = imageSession.dataTask(with: URLRequest(url: URL),
completionHandler: completion)
request.resume()
}
rigController.setCurrentImage(2, animated: false)
return rigController
}
func prepareLocalGallery() -> RIGImageGalleryViewController {
let items: [UIImage] = ["1", "2", "3", "4", "5", "6"].flatMap(UIImage.init(named:))
let rigItems: [RIGImageGalleryItem] = items.map { item in
RIGImageGalleryItem(image: item)
}
let rigController = RIGImageGalleryViewController(images: rigItems)
return rigController
}
func navBarWrappedViewController(_ viewController: UIViewController) -> UINavigationController {
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.navigationBar.barStyle = .blackTranslucent
navigationController.navigationBar.tintColor = .white
navigationController.toolbar.barStyle = .blackTranslucent
navigationController.toolbar.tintColor = .white
return navigationController
}
}
private extension RIGImageGalleryViewController {
// swiftlint:disable:next large_tuple
func handleImageLoadAtIndex(_ index: Int) -> ((Data?, URLResponse?, Error?) -> Void) {
return { [weak self] (data: Data?, response: URLResponse?, error: Error?) in
guard let image = data.flatMap(UIImage.init), error == nil else {
if let error = error {
print(error)
}
return
}
self?.images[index].isLoading = false
self?.images[index].image = image
}
}
}
| mit | 8b4ba0f9f47286353ad5935ae40f4c82 | 40.452381 | 164 | 0.692705 | 5.531374 | false | false | false | false |
KeepGoing2016/WMJWeiBo | WMJWeiBo/WMJWeiBo/Classes/Home/WMJSQCodeCreateViewController.swift | 1 | 2251 | //
// WMJSQCodeCreateViewController.swift
// WMJWeiBo
//
// Created by lumf on 16/7/4.
// Copyright © 2016年 WMJ. All rights reserved.
//
import UIKit
class WMJSQCodeCreateViewController: UIViewController {
@IBOutlet weak var codeImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// 1.创建滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
// 2.还原滤镜默认属性
filter?.setDefaults()
// 3.设置需要生成二维码的数据到滤镜中
// OC中要求设置的是一个二进制数据
filter?.setValue("微博".dataUsingEncoding(NSUTF8StringEncoding), forKeyPath: "InputMessage")
// 4.从滤镜从取出生成好的二维码图片
guard let ciImage = filter?.outputImage else
{
return
}
// codeImage.image = UIImage(CIImage: ciImage)
codeImage.image = createNonInterpolatedUIImageFormCIImage(ciImage, size: 500)
}
/**
生成高清二维码
- parameter image: 需要生成原始图片
- parameter size: 生成的二维码的宽高
*/
private func createNonInterpolatedUIImageFormCIImage(image: CIImage, size: CGFloat) -> UIImage {
let extent: CGRect = CGRectIntegral(image.extent)
let scale: CGFloat = min(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent))
// 1.创建bitmap;
let width = CGRectGetWidth(extent) * scale
let height = CGRectGetHeight(extent) * scale
let cs: CGColorSpaceRef = CGColorSpaceCreateDeviceGray()!
let bitmapRef = CGBitmapContextCreate(nil, Int(width), Int(height), 8, 0, cs, 0)!
let context = CIContext(options: nil)
let bitmapImage: CGImageRef = context.createCGImage(image, fromRect: extent)
CGContextSetInterpolationQuality(bitmapRef, CGInterpolationQuality.None)
CGContextScaleCTM(bitmapRef, scale, scale);
CGContextDrawImage(bitmapRef, extent, bitmapImage);
// 2.保存bitmap到图片
let scaledImage: CGImageRef = CGBitmapContextCreateImage(bitmapRef)!
return UIImage(CGImage: scaledImage)
}
}
| mit | 3be6019c6e6636da55703287bbd55f64 | 30.815385 | 100 | 0.64265 | 4.710706 | false | false | false | false |
sffernando/SwiftLearning | SwiftStudyChangeFont/SwiftStudyChangeFont/ViewController.swift | 1 | 3501 | //
// ViewController.swift
// SwiftStudyChangeFont
//
// Created by koudai on 2016/11/27.
// Copyright © 2016年 fernando. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// MARK: propeties and vars
var data = ["30 Days Swift", "这些字体特别适合打「奋斗」和「理想」", "谢谢「造字工房」,本案例不涉及商业使用", "使用到造字工房劲黑体,致黑体,童心体", " See you next Project", "微博 @Allen朝辉",
"测试测试测试测试测试测试",
"123",
"Alex",
"@@@@@@","learning form 30 Days Swift by Allen","especially thanks to Allen"]
var fontNames = ["MFTongXin_Noncommercial-Regular", "MFJinHei_Noncommercial-Regular", "MFZhiHei_Noncommercial-Regular", "edundot", "Gaspar Regular"]
var changeFontBtn: UIButton!
var testTableView: UITableView!
var fontOfIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.title = "Custom fonts"
self.view.backgroundColor = UIColor.init(white: 0, alpha: 0.8)
testTableView = UITableView.init(frame: CGRect.init(origin: CGPoint.init(x: 0, y: 20), size: CGSize.init(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 220)), style: .plain)
testTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
testTableView.delegate = self
testTableView.dataSource = self
self.view.addSubview(testTableView);
testTableView.reloadData();
changeFontBtn = UIButton.init(type: .custom)
changeFontBtn.layer.cornerRadius = 50
changeFontBtn.clipsToBounds = true
changeFontBtn.frame = CGRect.init(x: (UIScreen.main.bounds.width - 100)/2, y: UIScreen.main.bounds.height - 150, width: 100, height: 100)
changeFontBtn.backgroundColor = UIColor.yellow
changeFontBtn.setTitle("变体", for: .normal)
changeFontBtn.addTarget(self, action: #selector(changeFontAction(sender:)), for: .touchUpInside)
changeFontBtn.setTitleColor(UIColor.black, for: .normal)
self.view.addSubview(changeFontBtn)
}
func changeFontAction(sender: UIButton) {
fontOfIndex += 1;
if fontOfIndex >= fontNames.count {
fontOfIndex = 0
}
testTableView.reloadData()
}
// MARK:UITableViewDelegate, UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = data[indexPath.row]
cell.textLabel?.textColor = UIColor.green
cell.textLabel?.font = UIFont.init(name: fontNames[fontOfIndex], size: 25)
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 29db876dec5b349671adf646b70cfeed | 37.976744 | 207 | 0.659308 | 4.375979 | false | true | false | false |
zyhndesign/DesignCourse | DesignCourse/DesignCourse/views/HomeItemView.swift | 1 | 1779 | //
// HomeItemView.swift
// DesignCourse
//
// Created by lotusprize on 15/10/8.
// Copyright © 2015年 geekTeam. All rights reserved.
//
import UIKit
import Haneke
class HomeItemView: UIView {
var imageUrl:String
var title:String
var time:String
let cache = Shared.imageCache
init(frame: CGRect,imageUrl:String, title:String, time:String) {
self.imageUrl = imageUrl
self.title = title
self.time = time
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let imageLayer:CALayer = CALayer.init()
imageLayer.frame = CGRectMake(0, 0, 188, 106)
imageLayer.contentsGravity = kCAGravityResize
let URL = NSURL(string: imageUrl)!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
cache.fetch(fetcher: fetcher).onSuccess { image in
imageLayer.contents = image.CGImage
}
self.layer.addSublayer(imageLayer)
let titleLayer:CATextLayer = CATextLayer.init()
titleLayer.frame = CGRectMake(5, 106, 180, 25)
titleLayer.string = title
titleLayer.foregroundColor = UIColor(red: 42/255.0, green: 58/255.0, blue: 97/255.0, alpha: 1).CGColor
titleLayer.fontSize = 20.0
self.layer.addSublayer(titleLayer)
let timeLayer:CATextLayer = CATextLayer.init()
timeLayer.frame = CGRectMake(5, 136, 180, 16)
timeLayer.string = time
timeLayer.fontSize = 14.0
timeLayer.foregroundColor = UIColor(red: 247/255.0, green: 182/255.0, blue: 0, alpha: 1).CGColor
self.layer.addSublayer(timeLayer)
}
}
| apache-2.0 | ec04effc0a12ccfeed55138ab12b32aa | 30.157895 | 110 | 0.631757 | 4.228571 | false | false | false | false |
nahive/location-spoofer | source/location-spoofer/SettingsViewController.swift | 1 | 2082 | //
// SettingsViewController.swift
// location-spoofer
//
// Created by Szymon Maślanka on 15/07/2016.
// Copyright © 2016 Szymon Maslanka. All rights reserved.
//
import Cocoa
enum TrackingSpeed: Double {
case walking = 2.0
case cycling = 6.0
case driving = 15.0
static func fromSegment(segment: Int) -> TrackingSpeed {
switch segment {
case 0:
return .walking
case 1:
return .cycling
case 2:
return .driving
default:
return .walking
}
}
}
protocol SettingsViewControllerDelegate: class {
func settingsViewController(controller: SettingsViewController, stickToRoadsEnabled enabled: Bool)
func settingsViewController(controller: SettingsViewController, trackingSpeedChanged speed: TrackingSpeed)
}
class SettingsViewController: NSViewController, NSPopoverDelegate {
weak var delegate: SettingsViewControllerDelegate?
@IBOutlet weak var stickToRoadsButton: NSButtonCell!
@IBOutlet weak var speedSegmentedControl: NSSegmentedControl!
private let popover = NSPopover()
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override init?(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
setup()
}
private func setup(){
popover.contentViewController = self
}
func show(sender: NSView) {
popover.show(relativeTo: sender.bounds, of: sender, preferredEdge: NSRectEdge.maxY)
}
func hide(sender: NSView){
popover.performClose(sender)
}
func toggle(sender: NSView) {
popover.isShown ? hide(sender: sender) : show(sender: sender)
}
@IBAction func stickToRoadButtonClicked(sender: NSButton) {
delegate?.settingsViewController(controller: self, stickToRoadsEnabled: sender.state == NSOnState)
}
@IBAction func trackingSpeedSegmentedControlClicked(_ sender: NSSegmentedControl) {
delegate?.settingsViewController(controller: self, trackingSpeedChanged: TrackingSpeed.fromSegment(segment: sender.selectedSegment))
}
}
| unlicense | f6eb47caab08621c64f4a1660aed680a | 25.666667 | 136 | 0.728365 | 4.571429 | false | false | false | false |
akaralar/siesta | Source/Siesta/Request/ProgressTracker.swift | 3 | 1843 | //
// ProgressTracker.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal class ProgressTracker
{
var progress: Double
{ return progressComputation.fractionDone }
var callbacks = CallbackGroup<Double>()
private var networking: RequestNetworking?
private var lastProgressBroadcast: Double?
private var progressComputation: RequestProgressComputation
private var progressUpdateTimer: Timer?
init(isGet: Bool)
{
progressComputation = RequestProgressComputation(isGet: isGet)
}
func start(_ networking: RequestNetworking, reportingInterval: TimeInterval)
{
precondition(self.networking == nil, "already started")
self.networking = networking
progressUpdateTimer =
CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent(),
reportingInterval, 0, 0)
{ [weak self] _ in self?.updateProgress() }
CFRunLoopAddTimer(CFRunLoopGetCurrent(), progressUpdateTimer, CFRunLoopMode.commonModes)
}
deinit
{
progressUpdateTimer?.invalidate()
}
private func updateProgress()
{
guard let networking = networking else
{ return }
progressComputation.update(from: networking.transferMetrics)
let progress = self.progress
if lastProgressBroadcast != progress
{
lastProgressBroadcast = progress
callbacks.notify(progress)
}
}
func complete()
{
progressUpdateTimer?.invalidate()
progressComputation.complete()
callbacks.notifyOfCompletion(1)
}
}
| mit | 7246bc8e54f6466708838b39a2521f68 | 25.695652 | 96 | 0.62975 | 5.810726 | false | false | false | false |
mathewa6/Practise | PathShare.playground/Sources/GPXVC.swift | 1 | 3498 | import UIKit
import MapKit
public class GPXViewController: UIViewController, MKMapViewDelegate {
public var mapView: MKMapView!
public let testCoordinates: [CLLocationCoordinate2D] = {
let x = CLLocationCoordinate2D(latitude: 42.734406033781006,
longitude: -84.48360716924071)
let y = CLLocationCoordinate2D(latitude: 42.73487430061096,
longitude: -84.48363977484405)
let z = CLLocationCoordinate2D(latitude: 42.73553624632179,
longitude: -84.48381680063903)
return [x, y, z]
}()
public override func viewDidLoad() {
super.viewDidLoad()
let frame: CGRect = CGRect(x: 0.0,
y: 0.0,
width: 375.0,
height: 375.0)
let mainView: UIView = UIView(frame: frame)
self.mapView = MKMapView(frame: frame)
self.mapView.delegate = self
self.mapView.showsBuildings = false
self.mapView.showsPointsOfInterest = false
mainView.addSubview(self.mapView)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(mapTapped(_:)))
self.mapView.addGestureRecognizer(tap)
self.view = mainView
self.view.backgroundColor = .white
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let mapCenterCoordinate: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 42.725680140945656, longitude: -84.477848661018569)
let mapCamera: MKMapCamera = MKMapCamera(lookingAtCenter: mapCenterCoordinate,
fromDistance: 9000.0,
pitch: 0,
heading: 0)
let newMapCamera: MKMapCamera = MKMapCamera(lookingAtCenter: mapCenterCoordinate,
fromDistance: 6000.0,
pitch: 0,
heading: 0)
self.mapView.camera = mapCamera
UIView.animate(withDuration: 3.0, delay: 3.0, options: [.allowUserInteraction, .curveEaseInOut], animations: { self.mapView.camera = newMapCamera }, completion: nil)
let over = DXLPointsOverlay(withLocations: testCoordinates)
// self.mapView.add(DBGTileOverlay())
self.mapView.add(over)
}
func mapTapped(_ gesture: UITapGestureRecognizer) {
let touchPoint: CGPoint = gesture.location(in: self.mapView)
let touchCoordinate: CLLocationCoordinate2D = self.mapView.convert(touchPoint,
toCoordinateFrom: self.mapView)
print(touchCoordinate)
print(self.mapView.camera.altitude)
}
public func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
if overlay.isKind(of: DXLPointsOverlay.self) {
return DXLPointsRenderer(overlay: overlay)
}
return DXLDebugTileOverlayRenderer(overlay: overlay)
}
}
| mit | 86896b501311e08653a49b0797858501 | 39.674419 | 173 | 0.541166 | 5.491366 | false | false | false | false |
drewcrawford/XcodeServerSDK | XcodeServerSDK/API Routes/XcodeServer+Bot.swift | 2 | 7444 | //
// XcodeServer+Bot.swift
// XcodeServerSDK
//
// Created by Mateusz Zając on 01.07.2015.
// Copyright © 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
// MARK: - XcodeSever API Routes for Bot management
extension XcodeServer {
// MARK: Bot management
/**
Creates a new Bot from the passed in information. First validates Bot's Blueprint to make sure
that the credentials are sufficient to access the repository and that the communication between
the client and XCS will work fine. This might take a couple of seconds, depending on your proximity
to your XCS.
- parameter botOrder: Bot object which is wished to be created.
- parameter response: Response from the XCS.
*/
public final func createBot(botOrder: Bot, completion: (response: CreateBotResponse) -> ()) {
//first validate Blueprint
let blueprint = botOrder.configuration.sourceControlBlueprint
self.verifyGitCredentialsFromBlueprint(blueprint) { (response) -> () in
switch response {
case .Error(let error):
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
case .SSHFingerprintFailedToVerify(let fingerprint, _):
blueprint.certificateFingerprint = fingerprint
completion(response: XcodeServer.CreateBotResponse.BlueprintNeedsFixing(fixedBlueprint: blueprint))
return
case .Success(_, _): break
}
//blueprint verified, continue creating our new bot
//next, we need to fetch all the available platforms and pull out the one intended for this bot. (TODO: this could probably be sped up by smart caching)
self.getPlatforms({ (platforms, error) -> () in
if let error = error {
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
}
//we have platforms, find the one in the bot config and replace it
self.replacePlaceholderPlatformInBot(botOrder, platforms: platforms!)
//cool, let's do it.
self.createBotNoValidation(botOrder, completion: completion)
})
}
}
/**
XCS API call for getting all available bots.
- parameter bots: Optional array of available bots.
- parameter error: Optional error.
*/
public final func getBots(completion: (bots: [Bot]?, error: NSError?) -> ()) {
self.sendRequestWithMethod(.GET, endpoint: .Bots, params: nil, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(bots: nil, error: error)
return
}
if let body = (body as? NSDictionary)?["results"] as? NSArray {
let bots: [Bot] = XcodeServerArray(body)
completion(bots: bots, error: nil)
} else {
completion(bots: nil, error: Error.withInfo("Wrong data returned: \(body)"))
}
}
}
/**
XCS API call for getting specific bot.
- parameter botTinyId: ID of bot about to be received.
- parameter bot: Optional Bot object.
- parameter error: Optional error.
*/
public final func getBot(botTinyId: String, completion: (bot: Bot?, error: NSError?) -> ()) {
let params = [
"bot": botTinyId
]
self.sendRequestWithMethod(.GET, endpoint: .Bots, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(bot: nil, error: error)
return
}
if let body = body as? NSDictionary {
let bot = Bot(json: body)
completion(bot: bot, error: nil)
} else {
completion(bot: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
/**
XCS API call for deleting bot on specified revision.
- parameter botId: Bot's ID.
- parameter revision: Revision which should be deleted.
- parameter success: Operation result indicator.
- parameter error: Optional error.
*/
public final func deleteBot(botId: String, revision: String, completion: (success: Bool, error: NSError?) -> ()) {
let params = [
"rev": revision,
"bot": botId
]
self.sendRequestWithMethod(.DELETE, endpoint: .Bots, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(success: false, error: error)
return
}
if let response = response {
if response.statusCode == 204 {
completion(success: true, error: nil)
} else {
completion(success: false, error: Error.withInfo("Wrong status code: \(response.statusCode)"))
}
} else {
completion(success: false, error: Error.withInfo("Nil response"))
}
}
}
// MARK: Helpers
/**
Enum for handling Bot creation response.
- Success: Bot has been created successfully.
- BlueprintNeedsFixing: Source Control needs fixing.
- Error: Couldn't create Bot.
*/
public enum CreateBotResponse {
case Success(bot: Bot)
case BlueprintNeedsFixing(fixedBlueprint: SourceControlBlueprint)
case Error(error: ErrorType)
}
private func replacePlaceholderPlatformInBot(bot: Bot, platforms: [DevicePlatform]) {
if let filter = bot.configuration.deviceSpecification.filters.first {
let intendedPlatform = filter.platform
if let platform = platforms.findFirst({ $0.type == intendedPlatform.type }) {
//replace
filter.platform = platform
} else {
fatalError("Couldn't find intended platform in list of platforms: \(platforms)!")
}
} else {
fatalError("Couldn't find device filter!")
}
}
private func createBotNoValidation(botOrder: Bot, completion: (response: CreateBotResponse) -> ()) {
let body: NSDictionary = botOrder.dictionarify()
self.sendRequestWithMethod(.POST, endpoint: .Bots, params: nil, query: nil, body: body) { (response, body, error) -> () in
if let error = error {
completion(response: XcodeServer.CreateBotResponse.Error(error: error))
return
}
guard let dictBody = body as? NSDictionary else {
let e = Error.withInfo("Wrong body \(body)")
completion(response: XcodeServer.CreateBotResponse.Error(error: e))
return
}
let bot = Bot(json: dictBody)
completion(response: XcodeServer.CreateBotResponse.Success(bot: bot))
}
}
}
| mit | 226920c45551be6fe8875e8db620e7e1 | 36.024876 | 164 | 0.557108 | 5.09726 | false | false | false | false |
LYM-mg/MGDS_Swift | MGDS_Swift/MGDS_Swift/Class/Music/Tools/MGAVPlayerTool.swift | 1 | 2540 | //
// MGAVPlayerTool.swift
// MGDS_Swift
//
// Created by i-Techsys.com on 17/3/3.
// Copyright © 2017年 i-Techsys. All rights reserved.
//
import UIKit
import AVKit
class MGAVPlayerTool: NSObject {
fileprivate lazy var player: AVPlayer = AVPlayer()
deinit {
self.player.currentItem?.removeObserver(self, forKeyPath: "sattus")
}
}
extension MGAVPlayerTool {
func playMusicWith(urlStr: String) -> AVPlayer? {
guard let url = URL(string: urlStr) else { return nil }
//创建需要播放的AVPlayerItem
let item = AVPlayerItem(url: url)
//替换当前音乐资源
self.player.replaceCurrentItem(with: item)
/*
typedef NS_ENUM(NSInteger, AVPlayerItemStatus) {
AVPlayerItemStatusUnknown,//未知状态
AVPlayerItemStatusReadyToPlay,//准备播放
AVPlayerItemStatusFailed//加载失败
};*/
self.player.currentItem?.addObserver(self, forKeyPath: "status", options: .new, context: nil)
//KVO监听音乐缓冲状态
self.player.currentItem?.addObserver(self, forKeyPath: "loadedTimeRanges", options: .new, context: nil)
return self.player
}
override func addObserver(_ observer: NSObject, forKeyPath keyPath: String, options: NSKeyValueObservingOptions = [], context: UnsafeMutableRawPointer?) {
//注意这里查看的是self.player.status属性
if keyPath == "status" {
switch (self.player.status) {
case AVPlayerStatus.unknown:
debugPrint("未知转态")
case AVPlayerStatus.readyToPlay:
debugPrint("准备播放")
case AVPlayerStatus.failed:
debugPrint("加载失")
}
}
if keyPath == "loadedTimeRanges" {
// self.loadTimeProgress.progress = scale
// let timeRanges = (self.player.currentItem?.loadedTimeRanges)!
// //本次缓冲的时间范围
// let timeRange: CMTimeRange = timeRanges.first.cmTimeRange
// //缓冲总长度
// let totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
// //音乐的总时间
// let duration = CMTimeGetSeconds((self.player.currentItem?.duration)!);
// //计算缓冲百分比例
// let scale = totalLoadTime/duration;
//更新缓冲进度条
// self.loadTimeProgress.progress = scale;
}
}
}
| mit | a20557b1c251ae7caf38d3487f80d261 | 32.169014 | 158 | 0.610191 | 4.520154 | false | false | false | false |
icoderRo/SMAnimation | SMDemo/iOS-MVX/MVVM/TableView/MVVMVM.swift | 2 | 1165 | //
// MVVMVM.swift
// iOS-MVX
//
// Created by simon on 2017/3/2.
// Copyright © 2017年 simon. All rights reserved.
//
import UIKit
class MVVMVM: NSObject {
var reloadData:(() -> Void)?
lazy var models = [MVVMModel]()
}
extension MVVMVM {
func setCell(_ cell: UITableViewCell, _ index: Int) {
if cell.isKind(of: MVVMCell.self) {
let cell = cell as! MVVMCell
let model = models[index]
cell.setName(model.name, index: index)
cell.clickNameClosure = {[weak self] index in
let model = self?.models[index]
model?.name = "test test.."
self?.reloadData?()
}
}
}
}
extension MVVMVM {
func loadData() {
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
for i in 0..<20 {
let model = MVVMModel()
model.name = "simon" + "\(i)"
self.models.append(model)
}
self.reloadData?()
}
}
}
| mit | 058422b276bf092ca3e8c1281dd13a20 | 20.127273 | 62 | 0.450947 | 4.435115 | false | false | false | false |
wayfair/brickkit-ios | Source/ViewControllers/BrickViewController.swift | 1 | 8204 | //
// BrickViewController.swift
// BrickApp
//
// Created by Ruben Cagnie on 5/25/16.
// Copyright © 2016 Wayfair. All rights reserved.
//
import UIKit
/**
Conform to this delegate on your preview view controller in order to enable UIKit Pop.
*/
public protocol BrickViewControllerPreviewing: class {
var sourceBrick: Brick { get set }
}
/// A BrickViewController is a UIViewController that contains a BrickCollectionView
open class BrickViewController: UIViewController, UICollectionViewDelegate {
// MARK: - Public members
open var layout: BrickFlowLayout {
guard let flowlayout = collectionViewLayout as? BrickFlowLayout else {
fatalError("collectionViewLayout is not BrickFlowLayout, is \(type(of: collectionViewLayout))")
}
return flowlayout
}
open var collectionViewLayout: UICollectionViewLayout {
return brickCollectionView.collectionViewLayout
}
open var collectionView: UICollectionView?
open var brickCollectionView: BrickCollectionView {
guard let collectionView = self.collectionView as? BrickCollectionView else {
fatalError("collectionView is not BrickCollectionView, is \(type(of: self.collectionView))")
}
return collectionView
}
/// Previewing context, retained for unregistration in the event of a capability change
open internal(set) var previewingContext: UIViewControllerPreviewing?
#if os(iOS)
// MARK: - Internal members
/// Refresh control, if added
open internal(set) var refreshControl: UIRefreshControl?
/// Refresh action, if added
open internal(set) var refreshAction: ((_ refreshControl: UIRefreshControl) -> Void)?
#endif
// MARK: - Initializers
public init() {
super.init(nibName: nil, bundle: nil)
}
public override init(nibName: String?, bundle: Bundle?) {
super.init(nibName: nibName, bundle: bundle)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - UIViewController overrides
open override func viewDidLoad() {
super.viewDidLoad()
initializeComponents()
if let registrationDataSource = self as? BrickRegistrationDataSource {
registrationDataSource.registerBricks()
}
}
/// Registration/unregistration happens here because the user can disable force touch in their system settings
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
handleTraitCollectionChange(traitCollection, previousTraitCollection)
}
// MARK: - Private Methods
fileprivate func initializeComponents() {
autoreleasepool { // This would result in not releasing the BrickCollectionView even when its being set to nil
let collectionView = BrickCollectionView(frame: self.view.bounds, collectionViewLayout: BrickFlowLayout())
collectionView.backgroundColor = UIColor.clear
collectionView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.view.addSubview(collectionView)
self.collectionView = collectionView
self.collectionView?.delegate = self
}
}
/// On tvOS, this method accomplishes nothing, despite UIViewControllerPreviewing and its delegate protocol being available
func handleTraitCollectionChange(_ traitCollection: UITraitCollection, _ previousTraitCollection: UITraitCollection?) {
if previewingContext == nil && traitCollection.forceTouchCapability == .available {
// We use brickCollectionView as the sourceView for the previewingContext, otherwise the coordinates returned
// in UIViewControllerPreviewing#previewingContext(_:, viewControllerForLocation:) are not in the right system
previewingContext = registerForPreviewing(with: self, sourceView: brickCollectionView)
} else if let previewingContext = previewingContext,
previousTraitCollection?.forceTouchCapability == .available {
unregisterForPreviewing(withContext: previewingContext)
self.previewingContext = nil
}
}
// MARK: - Convenience methods
open func setSection(_ section: BrickSection) {
brickCollectionView.setSection(section)
}
open func registerBrickClass(_ brickClass: Brick.Type, nib: UINib? = nil) {
brickCollectionView.registerBrickClass(brickClass, nib: nib)
}
open func registerNib(_ nib: UINib, forBrickWithIdentifier identifier: String) {
brickCollectionView.registerNib(nib, forBrickWithIdentifier: identifier)
}
open func reloadBricksWithIdentifiers(_ identifiers: [String], shouldReloadCell: Bool = false, completion: ((Bool) -> Void)? = nil) {
brickCollectionView.reloadBricksWithIdentifiers(identifiers, shouldReloadCell: shouldReloadCell, completion: completion)
}
open func invalidateLayout() {
brickCollectionView.invalidateBricks()
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension BrickViewController: UIViewControllerPreviewingDelegate {
open func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = brickCollectionView.indexPathForItem(at: location) else {
return nil
}
let brick = brickCollectionView.brick(at: indexPath)
return brick.previewingDelegate?.previewViewController(for: brick)
}
open func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
guard let previewViewController = viewControllerToCommit as? BrickViewControllerPreviewing else {
return
}
previewViewController.sourceBrick.previewingDelegate?.commit(viewController: viewControllerToCommit)
}
}
#if os(iOS)
// MARK: - UIRefreshControl
extension BrickViewController {
/// Add a refresh control to the BrickViewController
///
/// - parameter refreshControl: refreshControl
/// - parameter action: action
public func addRefreshControl(_ refreshControl: UIRefreshControl, action:@escaping ((_ refreshControl: UIRefreshControl) -> Void)) {
self.refreshControl = refreshControl
self.refreshAction = action
self.refreshControl!.addTarget(self, action: #selector(refreshControlAction), for: .valueChanged)
self.brickCollectionView.addSubview(self.refreshControl!)
}
/// This method needs to be called then ever you are do refreshing so it can be brought back to the the top
public func resetRefreshControl() {
if refreshControl?.isRefreshing == true {
refreshControl?.layer.zPosition = (brickCollectionView.backgroundView?.layer.zPosition ?? 0) + 1
}
}
@objc internal func refreshControlAction() {
refreshControl?.layer.zPosition = (brickCollectionView.backgroundView?.layer.zPosition ?? 0) - 1
if let refreshControl = self.refreshControl {
self.refreshAction?(refreshControl)
}
}
}
#endif
#if os(tvOS)
extension BrickViewController {
open func collectionViewShouldUpdateFocusIn(context: UICollectionViewFocusUpdateContext) -> Bool {
guard let nextIndex = context.nextFocusedIndexPath else {
return false
}
if let lastIndex = context.previouslyFocusedIndexPath, let cell = brickCollectionView.cellForItem(at: lastIndex) as? FocusableBrickCell {
if !cell.willUnfocus() {
return false
}
}
if let cell = brickCollectionView.cellForItem(at: nextIndex) as? FocusableBrickCell {
return cell.willFocus()
}
return false
}
public func collectionView(collectionView: UICollectionView, canFocusItemAtIndexPath indexPath: IndexPath) -> Bool {
let cell = brickCollectionView.cellForItem(at: indexPath) as? BrickCell
return cell is FocusableBrickCell && cell?.allowsFocus == true
}
}
#endif
| apache-2.0 | 00e1566d07dc881e3739db834d983f8f | 37.511737 | 148 | 0.703279 | 5.838434 | false | false | false | false |
ejeinc/MetalScope | Sources/ScreenModel.swift | 1 | 3946 | //
// ScreenModel.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/01/23.
// Copyright © 2017 eje Inc. All rights reserved.
//
import UIKit
public enum ScreenModel {
case iPhone4
case iPhone5
case iPhone6
case iPhone6Plus
case custom(parameters: ScreenParametersProtocol)
public static let iPhone4S = ScreenModel.iPhone4
public static let iPhone5s = ScreenModel.iPhone5
public static let iPhone5c = ScreenModel.iPhone5
public static let iPhoneSE = ScreenModel.iPhone5
public static let iPhone6s = ScreenModel.iPhone6
public static let iPhone6sPlus = ScreenModel.iPhone6Plus
public static let iPhone7 = ScreenModel.iPhone6
public static let iPhone7Plus = ScreenModel.iPhone6Plus
public static let iPodTouch = ScreenModel.iPhone5
public static var `default`: ScreenModel {
return ScreenModel.current ?? .iPhone5
}
public static var current: ScreenModel? {
return ScreenModel(modelIdentifier: currentModelIdentifier) ?? ScreenModel(screen: .main)
}
private static var currentModelIdentifier: String {
var size: size_t = 0
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine: [CChar] = Array(repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
private init?(modelIdentifier identifier: String) {
func match(_ identifier: String, _ prefixes: [String]) -> Bool {
return prefixes.filter({ identifier.hasPrefix($0) }).count > 0
}
if match(identifier, ["iPhone3"]) {
self = .iPhone4
} else if match(identifier, ["iPhone4"]) {
self = .iPhone4S
} else if match(identifier, ["iPhone5"]) {
self = .iPhone5
} else if match(identifier, ["iPhone6"]) {
self = .iPhone5s
} else if match(identifier, ["iPhone8,4"]) {
self = .iPhoneSE
} else if match(identifier, ["iPhone7,2"]) {
self = .iPhone6
} else if match(identifier, ["iPhone8,1"]) {
self = .iPhone6s
} else if match(identifier, ["iPhone9,1", "iPhone9,3"]) {
self = .iPhone7
} else if match(identifier, ["iPhone7,1"]) {
self = .iPhone6Plus
} else if match(identifier, ["iPhone8,2"]) {
self = .iPhone6sPlus
} else if match(identifier, ["iPhone9,2", "iPhone9,4"]) {
self = .iPhone7Plus
} else if match(identifier, ["iPod7,1"]) {
self = .iPodTouch
} else {
return nil
}
}
private init?(screen: UIScreen) {
switch screen.fixedCoordinateSpace.bounds.size {
case CGSize(width: 320, height: 480):
self = .iPhone4
case CGSize(width: 320, height: 568):
self = .iPhone5
case CGSize(width: 375, height: 667):
self = .iPhone6
case CGSize(width: 414, height: 768):
self = .iPhone6Plus
default:
return nil
}
}
}
extension ScreenModel: ScreenParametersProtocol {
private var parameters: ScreenParameters {
switch self {
case .iPhone4:
return ScreenParameters(width: 0.075, height: 0.050, border: 0.0045)
case .iPhone5:
return ScreenParameters(width: 0.089, height: 0.050, border: 0.0045)
case .iPhone6:
return ScreenParameters(width: 0.104, height: 0.058, border: 0.005)
case .iPhone6Plus:
return ScreenParameters(width: 0.112, height: 0.068, border: 0.005)
case .custom(let parameters):
return ScreenParameters(parameters)
}
}
public var width: Float {
return parameters.width
}
public var height: Float {
return parameters.height
}
public var border: Float {
return parameters.border
}
}
| mit | fed386bc31105f816fcbd48170c4973d | 31.603306 | 97 | 0.601774 | 4.219251 | false | false | false | false |
appintheair/documents-ocr-ios | DocumentsOCR/Classes/Helpers/Utils.swift | 1 | 4550 | //
// Utils.swift
// PassportOCR
//
// Created by Михаил on 15.09.16.
// Copyright © 2016 empatika. All rights reserved.
//
import Foundation
import TesseractOCR
import PodAsset
open class Utils {
fileprivate static let bundle = PodAsset.bundle(forPod: "DocumentsOCR")!
static let passportPattern: String! = Utils.stringFromTxtFile("passportPattern", inBundle: bundle)
fileprivate static let tesseract = createTesseract()
open static func stringFromTxtFile(_ fileName: String, inBundle bundle: Bundle = Bundle.main) -> String? {
let filePath = bundle.path(forResource: fileName, ofType: "txt")
let contentData = FileManager.default.contents(atPath: filePath!)
return NSString(data: contentData!, encoding: String.Encoding.utf8.rawValue) as? String
}
static func mrCodeFrom(image: UIImage, tesseractDelegate: G8TesseractDelegate? = nil) -> String? {
tesseract.delegate = tesseractDelegate!
tesseract.image = image.recognitionImage
tesseract.recognize()
if let recognizedText = tesseract.recognizedText {
NSLog("Utils : mrCodeFrom : Recognized: \(recognizedText)")
let text = recognizedText.replacingOccurrences(of: " ", with: "")
let regex = try? NSRegularExpression(pattern: passportPattern, options: [])
let range = NSRange(location: 0, length: text.count)
if let result = regex!.firstMatch(in: text, options: [], range: range) {
let code = (text as NSString).substring(with: result.range)
return fixFirstRowIn(code: code)
}
}
return nil
}
fileprivate static func fixFirstRowIn(code: String) -> String {
let pattern = "(?<FirstLine>(?<Passport>[A-Z0-9])(?<PassportType>.)(?<IssuingCountry>[A-Z0-9]{3})(?<PassportOwner>(?<Surname>[A-Z0-9]+)<<(?<GivenName>(?:[A-Z0-9]+<)+)){1})"
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: code.count)
let result = regex!.matches(in: code, options: [], range: range)
var resultFirstRow = (code as NSString).substring(with: result[0].range)
while resultFirstRow.count != 44 {resultFirstRow.append("<")}
let secondRow = code.split(separator: "\n", maxSplits: 2, omittingEmptySubsequences: true)[1]
return "\(resultFirstRow)\n\(String(secondRow))\n"
}
fileprivate static func createTesseract() -> G8Tesseract {
let trainDataPath = bundle.path(forResource: "eng", ofType: "traineddata")
let cacheURL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
let tessdataURL = cacheURL.appendingPathComponent("tesseract", isDirectory: true).appendingPathComponent("tessdata", isDirectory: true)
let destinationURL = tessdataURL.appendingPathComponent("eng.traineddata")
if !FileManager.default.fileExists(atPath: destinationURL.path) {
createTessdataFrom(trainDataPath!, toDirectoryURL: tessdataURL, withDestinationURL: destinationURL)
}
print("Utils : createTesseract : Cache path = \(cacheURL.path)")
print("Utils : createTesseract : Tess data path = \(tessdataURL.path)")
print("Utils : createTesseract : Destination path = \(destinationURL.path)")
let tesseract = G8Tesseract(
language: "eng",
configDictionary: [:],
configFileNames: [],
cachesRelatedDataPath: "tesseract/tessdata",
engineMode: .tesseractOnly)
var whiteList = DOConstants.alphabet.uppercased()
whiteList.append("<>1234567890")
tesseract?.charWhitelist = whiteList
tesseract?.setVariableValue("FALSE", forKey: "x_ht_quality_check")
return tesseract!
}
fileprivate static func createTessdataFrom(
_ filePath: String,
toDirectoryURL tessdataURL: URL,
withDestinationURL destinationURL: URL) {
do {
let fileManager = FileManager.default
try fileManager.createDirectory(atPath: tessdataURL.path, withIntermediateDirectories: true, attributes: nil)
try fileManager.copyItem(atPath: filePath, toPath: destinationURL.path)
}
catch let error as NSError {
assertionFailure("There is no tessdata directory in cache (TesseractOCR traineddata)."
+ "\(error.localizedDescription)")
}
}
}
| mit | 6e5e05469284e355e1a1c515bc53dd48 | 46.821053 | 180 | 0.652432 | 4.698035 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit | SwiftKit/extension/UIColor+extension.swift | 1 | 2211 | //
// UIColor+extension.swift
// swift4.2Demo
//
// Created by baiqiang on 2018/10/6.
// Copyright © 2018年 baiqiang. All rights reserved.
//
import UIKit
private let main_color = UIColor("308ee3")
private let text_color = UIColor("444444")
private let line_color = UIColor("f7f7f7")
extension UIColor {
public convenience init(_ hexString:String) {
let colorStr = hexString.replacingOccurrences(of: "", with: "#")
let scan = Scanner(string: colorStr)
var rgbValue:UInt32 = 0;
scan.scanHexInt32(&rgbValue)
let red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0;
let green = CGFloat((rgbValue & 0xFF00) >> 8) / 255.0;
let blue = CGFloat(rgbValue & 0xFF) / 255.0;
self.init(r: red, g: green, b: blue)
}
/// r,g,b (0 ~ 1)
public convenience init(r:CGFloat, g:CGFloat, b:CGFloat) {
self.init(red: r , green: g , blue: b , alpha: 1)
}
class var randomColor: UIColor {
get {
let red = CGFloat(arc4random() % 256) / 255.0;
let green = CGFloat(arc4random() % 256) / 255.0;
let blue = CGFloat(arc4random() % 256) / 255.0;
return UIColor(r: red, g: green, b: blue);
}
}
class var mainColor: UIColor {
get {
return main_color
}
}
class var textColor: UIColor {
get {
return text_color
}
}
class var lineColor: UIColor {
get {
return line_color
}
}
var rgbRed: CGFloat {
get {
return self.rgbaArray()[0]
}
}
var rgbGreen: CGFloat {
get {
return self.rgbaArray()[1]
}
}
var rgbBlue: CGFloat {
get {
return self.rgbaArray()[2]
}
}
var alpha: CGFloat {
get {
return self.rgbaArray()[3]
}
}
public func rgbaArray() -> Array<CGFloat> {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return [r,g,b,a]
}
}
| apache-2.0 | 7bbd27371136b16288962b370f2861ff | 22.242105 | 72 | 0.509058 | 3.742373 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/Message/Ephemeral/ZMMessageDestructionTimer.swift | 1 | 5778 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
let MessageDeletionTimerKey = "MessageDeletionTimer"
let MessageObfuscationTimerKey = "MessageObfuscationTimer"
private let log = ZMSLog(tag: "ephemeral")
public extension NSManagedObjectContext {
@objc var zm_messageDeletionTimer: ZMMessageDestructionTimer? {
precondition(zm_isUserInterfaceContext, "MessageDeletionTimerKey should be started only on the uiContext")
return userInfo[MessageDeletionTimerKey] as? ZMMessageDestructionTimer
}
@objc var zm_messageObfuscationTimer: ZMMessageDestructionTimer? {
precondition(zm_isSyncContext, "MessageObfuscationTimer should be started only on the syncContext")
return userInfo[MessageObfuscationTimerKey] as? ZMMessageDestructionTimer
}
@objc func zm_createMessageObfuscationTimer() {
precondition(zm_isSyncContext, "MessageObfuscationTimer should be started only on the syncContext")
guard userInfo[MessageObfuscationTimerKey] == nil else {
log.debug("Obfuscation timer already exists, skipping")
return
}
userInfo[MessageObfuscationTimerKey] = ZMMessageDestructionTimer(managedObjectContext: self)
log.debug("creating obfuscation timer")
}
@objc func zm_createMessageDeletionTimer() {
precondition(zm_isUserInterfaceContext, "MessageDeletionTimer should be started only on the uiContext")
guard userInfo[MessageDeletionTimerKey] == nil else {
log.debug("Deletion timer already exists, skipping")
return
}
userInfo[MessageDeletionTimerKey] = ZMMessageDestructionTimer(managedObjectContext: self)
log.debug("creating deletion timer")
}
/// Tears down zm_messageObfuscationTimer and zm_messageDeletionTimer
/// Call inside a performGroupedBlock(AndWait) when calling it from another context
@objc func zm_teardownMessageObfuscationTimer() {
precondition(zm_isSyncContext, "MessageObfuscationTimer is located on the syncContext")
if let timer = userInfo[MessageObfuscationTimerKey] as? ZMMessageDestructionTimer {
timer.tearDown()
userInfo.removeObject(forKey: MessageObfuscationTimerKey)
log.debug("tearing down obfuscation timer")
}
}
/// Tears down zm_messageDeletionTimer
/// Call inside a performGroupedBlock(AndWait) when calling it from another context
@objc func zm_teardownMessageDeletionTimer() {
precondition(zm_isUserInterfaceContext, "MessageDeletionTimerKey is located on the uiContext")
if let timer = userInfo[MessageDeletionTimerKey] as? ZMMessageDestructionTimer {
timer.tearDown()
userInfo.removeObject(forKey: MessageDeletionTimerKey)
log.debug("tearing down deletion timer")
}
}
}
enum MessageDestructionType: String {
static let UserInfoKey = "destructionType"
case obfuscation, deletion
}
@objcMembers public class ZMMessageDestructionTimer: ZMMessageTimer {
internal var isTesting: Bool = false
override init(managedObjectContext: NSManagedObjectContext!) {
super.init(managedObjectContext: managedObjectContext)
timerCompletionBlock = { [weak self] (message, userInfo) in
guard let strongSelf = self, let message = message, !message.isZombieObject else {
return log.debug("not forwarding timer, nil message or zombie")
}
strongSelf.messageTimerDidFire(message: message, userInfo: userInfo)
}
}
func messageTimerDidFire(message: ZMMessage, userInfo: [AnyHashable: Any]?) {
guard let userInfo = userInfo as? [String: Any],
let type = userInfo[MessageDestructionType.UserInfoKey] as? String
else { return }
log.debug("message timer did fire for \(message.nonce?.transportString() ?? ""), \(type)")
switch MessageDestructionType(rawValue: type) {
case .some(.obfuscation):
message.obfuscate()
case .some(.deletion):
message.deleteEphemeral()
default:
return
}
moc.saveOrRollback()
}
public func startObfuscationTimer(message: ZMMessage, timeout: TimeInterval) {
log.debug("starting obfuscation timer for \(message.nonce?.transportString() ?? "") timeout in \(timeout)")
let fireDate = Date().addingTimeInterval(timeout)
start(forMessageIfNeeded: message,
fire: fireDate,
userInfo: [MessageDestructionType.UserInfoKey: MessageDestructionType.obfuscation.rawValue])
}
public func startDeletionTimer(message: ZMMessage, timeout: TimeInterval) -> TimeInterval {
log.debug("starting deletion timer for \(message.nonce?.transportString() ?? "") timeout in \(timeout)")
let fireDate = Date().addingTimeInterval(timeout)
start(forMessageIfNeeded: message,
fire: fireDate,
userInfo: [MessageDestructionType.UserInfoKey: MessageDestructionType.deletion.rawValue])
return timeout
}
}
| gpl-3.0 | dcd5bc34f5d9705cd67e49075537f533 | 39.978723 | 115 | 0.704915 | 5.415183 | false | false | false | false |
vasarhelyia/SwiftySheetsDemo | SwiftySheetsDemo/AppDelegate.swift | 1 | 1882 | //
// AppDelegate.swift
// SwiftySheetsDemo
//
// Created by Agnes Vasarhelyi on 03/07/16.
// Copyright © 2016 Agnes Vasarhelyi. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
do {
let stylesheet = NSBundle.mainBundle().pathForResource("label", ofType: "style")
let context = try SwiftyParser.sharedInstance.parseFile(stylesheet!)
StyleProcessor.processContext(context)
} catch {
print("An error ocurred: \(error)")
}
return true
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| mit | d6d2783941d90180ebe34fbd136ff4d8 | 38.1875 | 219 | 0.787879 | 5.516129 | false | false | false | false |
feliperuzg/CleanExample | CleanExample/Core/Network/NetworkConfiguration/NetworkConfiguration.swift | 1 | 2045 | //
// NetworkConfiguration.swift
// CleanExample
//
// Created by Felipe Ruz on 12-12-17.
// Copyright © 2017 Felipe Ruz. All rights reserved.
//
import Foundation
class NetworkConfiguration: NSObject {
private var configurationDictionary: [String: AnyObject]?
var networkConfigurationList = NetworkConstants.networkConfigurationList
override init() {
super.init()
prepare()
}
func prepare() {
prepareConfigurationDictionary()
}
/// Will read Configuration.plist and assing it to configurationDictionary property
private func prepareConfigurationDictionary() {
let bundle = Bundle(for: NetworkConfiguration.self)
var format = PropertyListSerialization.PropertyListFormat.xml
if
let plistPath = bundle.path(
forResource: networkConfigurationList,
ofType: NetworkConstants.fileExtension
),
let plistData = FileManager.default.contents(atPath: plistPath),
let dict = try? PropertyListSerialization.propertyList(
from: plistData,
options: .mutableContainersAndLeaves,
format: &format
) as? [String: AnyObject] {
configurationDictionary = dict
} else {
configurationDictionary = nil
}
}
private func endpointFor(domain: Domain, endpoint: String) -> String? {
guard
let configurationDict = configurationDictionary,
let dict = configurationDict[domain.rawValue] as? [String: AnyObject],
let baseURL = dict[NetworkConstants.baseURL] as? String,
let endpointsDict = dict[NetworkConstants.endpointKey] as? [String: String],
let endpointURL = endpointsDict[endpoint]
else { return nil }
return "\(baseURL)/\(endpointURL)"
}
func authenticationURL(for endpoint: Endpoint.Authentication) -> String? {
return endpointFor(domain: Domain.auth, endpoint: endpoint.rawValue)
}
}
| mit | eb103ad50a33849c99b3b548e5e57050 | 33.644068 | 88 | 0.646282 | 5.421751 | false | true | false | false |
jkolb/Unamper | Unamper/String+UnescapeEntities.swift | 2 | 3852 | // Copyright (c) 2016 Justin Kolb - http://franticapparatus.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
public extension String {
public func unescapeEntities(entities: [String:String] = EntitySet.XMLSpecialC0ControlAndBasicLatinEntities, longestName: Int = 8) -> String {
enum State {
case Looking
case Started
case Extract
}
let ampersand = UnicodeScalar(0x0026)
let semicolon = UnicodeScalar(0x003B)
let scalars = self.unicodeScalars
var state = State.Looking
var unescaped = String()
unescaped.reserveCapacity(scalars.count)
var name = String()
name.reserveCapacity(longestName)
for scalar in scalars {
switch state {
case .Looking:
if scalar == ampersand {
state = .Started
} else {
unescaped.append(scalar)
}
case .Started:
if scalar == ampersand {
unescaped.append(ampersand)
} else if scalar == semicolon {
unescaped.append(ampersand)
unescaped.append(semicolon)
state = .Looking
} else {
name.append(scalar)
state = .Extract
}
case .Extract:
if scalar == ampersand {
unescaped.append(ampersand)
unescaped.appendContentsOf(name)
name.removeAll(keepCapacity: true)
state = .Started
} else if scalar == semicolon {
if let entity = entities[name] {
unescaped.appendContentsOf(entity)
} else {
unescaped.append(ampersand)
unescaped.appendContentsOf(name)
unescaped.append(semicolon)
}
name.removeAll(keepCapacity: true)
state = .Looking
} else if name.unicodeScalars.count >= longestName {
unescaped.append(ampersand)
unescaped.appendContentsOf(name)
unescaped.append(scalar)
name.removeAll(keepCapacity: true)
state = .Looking
} else {
name.append(scalar)
}
}
}
switch state {
case .Looking:
break
case .Started:
unescaped.append(ampersand)
case .Extract:
unescaped.append(ampersand)
unescaped.appendContentsOf(name)
}
return unescaped
}
}
| mit | 35c9786e9e475911569a7e64b30228c6 | 39.125 | 146 | 0.55893 | 5.590711 | false | false | false | false |
bobbymay/HouseAds | Ads/Ad Files/TopBanner.swift | 1 | 4060 | import UIKit
class TopBanner: NSObject {
static var created = false
static var showing = false
static var height: CGFloat = 0.0
private lazy var bannerID: UInt32 = 0
private lazy var appStore = AppStore()
static var timer = Timer()
override init() {
super.init()
let size = UIScreen.main.traitCollection.userInterfaceIdiom == .pad ? CGSize(width: 728, height: 90) : CGSize(width: 320, height: 50)
let banner = UIButton(frame: CGRect(x: 0, y: -size.height, width: size.width, height: size.height))
TopBanner.created = true
banner.tag = 5000
banner.addTarget(self, action: #selector(self.tapped), for: .touchUpInside)
UIApplication.shared.delegate?.window??.rootViewController?.view.addSubview(banner)
if setImage() { TopBanner.timer = Timer.scheduledTimer(timeInterval: 60.0, target: self, selector: #selector(setImage), userInfo: nil, repeats: true) }
show()
}
/// Show in-house banner
func show() {
if let banner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) {
TopBanner.showing = true
TopBanner.height = banner.frame.size.height
banner.frame = CGRect.center(x: Screen.width/2, y: banner.frame.size.height/2 + Screen.statusBarHeight, width: banner.frame.size.width, height: banner.frame.size.height)
if BannerWall.showing { BannerWall.resize() }
}
}
/// Hide in-house banner
func hide() {
if let banner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) {
banner.frame = CGRect.center( x: Screen.width/2, y: -banner.frame.size.height, width: banner.frame.size.width, height: banner.frame.size.height)
TopBanner.showing = false
TopBanner.height = 0
}
}
/// Chooses a random image, verifies it, sets image and ID
@objc func setImage() -> Bool {
let mb = UserDefaults.standard.dictionary(forKey: "MyBanners")!
guard let doc = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false) else { return false }
// get random banner and ID
var found = false
for _ in mb { // randomly sets banner
let index = Int(arc4random_uniform(UInt32(mb.count)))
let name = Array(mb.keys)[index]
let id = Array(mb.values)[index] as! NSString
if id.contains(String(bannerID)) { continue } // same banner that was showing
// make sure banner exists, sets image and ID
if FileManager().fileExists(atPath: doc.appendingPathComponent(name).path) {
let banner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) as! UIButton
banner.setBackgroundImage(UIImage(contentsOfFile: URL(fileURLWithPath: doc.absoluteString).appendingPathComponent(name).path), for: .normal)
bannerID = UInt32(id as String)!
found = true
break
}
}
// if nothing is found randomly, use brute force to find a banner, this is just a safety check, should be unnecessary.
if !found {
for (app, ids) in mb {
if FileManager().fileExists(atPath: doc.appendingPathComponent(app).path) {
// set banner
let banner = UIApplication.shared.delegate?.window??.rootViewController?.view.viewWithTag(5000) as! UIButton
banner.setBackgroundImage(UIImage(contentsOfFile: URL(fileURLWithPath: (doc.absoluteString)).appendingPathComponent(app).path), for: .normal)
// set ID
var id = ids as! NSString
if id.contains("_") { // could be iPhone or iPad
let t = id.components(separatedBy: "_")
id = UIScreen.main.traitCollection.userInterfaceIdiom == .phone ? t[0] as NSString : t[1] as NSString
}
bannerID = UInt32(id as String)!
break
}
}
}
return true
}
/// Opens app store
@objc func tapped(sender: UIButton) {
appStore.open(bannerID)
}
/// Removes top banner
static func removed() {
timer.invalidate() // stops setImage from being called, and allows banner to be removed from memory, the timer keeps the object around so the action method (tapped) can be called
TopBanner.created = false
TopBanner.showing = false
TopBanner.height = 0
}
}
| mit | e510fc7315b2913b5d0116fb0434811d | 38.417476 | 180 | 0.711823 | 3.694268 | false | false | false | false |
fluidsonic/JetPack | Xcode/Tests/Extensions/Foundation/NSMutableAttributedString.swift | 1 | 2597 | import XCTest
import Foundation
import JetPack
class NSMutableAttributedString_Tests: XCTestCase {
private let testKey1 = NSAttributedString.Key("a")
private let testKey2 = NSAttributedString.Key("b")
fileprivate func attributedString(_ string: String, attributes: [(range: CountableClosedRange<Int>, name: NSAttributedString.Key, value: Any)]) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: string)
for attribute in attributes {
let range = NSRange(location: attribute.range.lowerBound, length: attribute.range.upperBound - attribute.range.lowerBound + 1)
attributedString.addAttribute(attribute.name, value: attribute.value, range: range)
}
return attributedString
}
func testAppendString() {
do {
let expectedString = attributedString("rednothing", attributes: [(range: 0 ... 2, name: .foregroundColor, value: UIColor.red)])
let string = attributedString("red", attributes: [(range: 0 ... 2, name: .foregroundColor, value: UIColor.red)])
string.append("nothing")
XCTAssertEqual(string, expectedString)
}
do {
let expectedString = attributedString("redred", attributes: [(range: 0 ... 5, name: .foregroundColor, value: UIColor.red)])
let string = attributedString("red", attributes: [(range: 0 ... 2, name: .foregroundColor, value: UIColor.red)])
string.append("red", maintainingPrecedingAttributes: true)
XCTAssertEqual(string, expectedString)
}
do {
let expectedString = attributedString("redcustom", attributes: [
(range: 0 ... 2, name: .foregroundColor, value: UIColor.red),
(range: 3 ... 8, name: testKey1, value: testKey1.rawValue),
(range: 3 ... 8, name: testKey2, value: testKey2.rawValue)
])
let string = attributedString("red", attributes: [(range: 0 ... 2, name: .foregroundColor, value: UIColor.red)])
string.append("custom", attributes: [
testKey1: testKey1.rawValue,
testKey2: testKey2.rawValue
])
XCTAssertEqual(string, expectedString)
}
do {
let expectedString = attributedString("redcustom", attributes: [
(range: 0 ... 8, name: .foregroundColor, value: UIColor.red),
(range: 3 ... 8, name: testKey1, value: testKey1.rawValue),
(range: 3 ... 8, name: testKey2, value: testKey2.rawValue)
])
let string = attributedString("red", attributes: [(range: 0 ... 2, name: .foregroundColor, value: UIColor.red)])
string.append("custom", attributes: [
testKey1: testKey1.rawValue,
testKey2: testKey2.rawValue
], maintainingPrecedingAttributes: true)
XCTAssertEqual(string, expectedString)
}
}
}
| mit | 3b5b1f248f2621e401832e3849b15c67 | 35.577465 | 175 | 0.709665 | 3.964885 | false | true | false | false |
Neft-io/neft | packages/neft-storage/native/ios/StorageExtension.swift | 1 | 2017 | import JavaScriptCore
extension Extension.Storage {
static let app = App.getApp()
static func register() {
app.client.addCustomFunction("NeftStorage/get") {
(args: [Any?]) in
let uid = args[0] as? String ?? ""
let key = args[1] as? String ?? ""
resolve(uid, key) {
(url: URL) throws in
return try String(contentsOf: url)
}
}
app.client.addCustomFunction("NeftStorage/set") {
(args: [Any?]) in
let uid = args[0] as? String ?? ""
let key = args[1] as? String ?? ""
let value = args[2] as? String ?? ""
resolve(uid, key) {
(url: URL) throws in
try value.write(to: url, atomically: true, encoding: .utf8)
return nil
}
}
app.client.addCustomFunction("NeftStorage/remove") {
(args: [Any?]) in
let uid = args[0] as? String ?? ""
let key = args[1] as? String ?? ""
resolve(uid, key) {
(url: URL) throws in
try FileManager.default.removeItem(at: url)
return nil
}
}
}
private static func resolve(_ id: String, _ path: String, _ completion: @escaping (URL) throws -> String?) {
var responseArgs: [Any?]? = nil
thread({
let dir = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
var result: String? = nil
do {
result = try completion(dir!.appendingPathComponent("neft_storage_" + path))
} catch {
responseArgs = [id, error.localizedDescription, nil]
return
}
responseArgs = [id, nil, result]
}) {
let client = App.getApp().client
client?.pushEvent("NeftStorage/response", args: responseArgs)
}
}
}
| apache-2.0 | f672801a2ba9b4f88546e6c2b701de5c | 33.775862 | 131 | 0.495786 | 4.375271 | false | false | false | false |
RxSwiftCommunity/RxSwiftExt | Playground/RxSwiftExtPlayground.playground/Pages/retryWithBehavior.xcplaygroundpage/Contents.swift | 3 | 3189 | /*:
> # IMPORTANT: To use `RxSwiftExtPlayground.playground`, please:
1. Make sure you have [Carthage](https://github.com/Carthage/Carthage) installed
1. Fetch Carthage dependencies from shell: `carthage bootstrap --platform ios`
1. Build scheme `RxSwiftExtPlayground` scheme for a simulator target
1. Choose `View > Show Debug Area`
*/
//: [Previous](@previous)
import Foundation
import RxSwift
import RxSwiftExt
private enum SampleErrors : Error {
case fatalError
}
let sampleObservable = Observable<String>.create { observer in
observer.onNext("First")
observer.onNext("Second")
observer.onError(SampleErrors.fatalError)
observer.onCompleted()
return Disposables.create()
}
let delayScheduler = SerialDispatchQueueScheduler(qos: .utility)
example("Immediate retry") {
// after receiving error will immediate retry
_ = sampleObservable.retry(.immediate(maxCount: 3))
.subscribe(onNext: { event in
print("Receive event: \(event)")
}, onError: { error in
print("Receive error \(error)")
})
}
example("Immediate retry with custom predicate") {
// in this case we provide custom predicate, that will evaluate error and decide, should we retry or not
_ = sampleObservable.retry(.immediate(maxCount: 3), scheduler: delayScheduler) { error in
// error checks here
// in this example we simply say, that retry not allowed
return false
}
.subscribe(onNext: { event in
print("Receive event: \(event)")
}, onError: { error in
print("Receive error \(error)")
})
}
example("Delayed retry") {
// after error, observable will be retried after 1.0 second delay
_ = sampleObservable.retry(.delayed(maxCount: 3, time: 1.0), scheduler: delayScheduler)
.subscribe(onNext: { event in
print("Receive event: \(event)")
}, onError: { error in
print("Receive error: \(error)")
})
}
// sleep in order to wait until previous example finishes
Thread.sleep(forTimeInterval: 2.5)
example("Exponential delay") {
// in case of an error initial delay will be 1 second,
// every next delay will be doubled
// delay formula is: initial * pow(1 + multiplier, Double(currentRepetition - 1)), so multiplier 1.0 means, delay will doubled
_ = sampleObservable.retry(.exponentialDelayed(maxCount: 3, initial: 1.0, multiplier: 1.0), scheduler: delayScheduler)
.subscribe(onNext: { event in
print("Receive event: \(event)")
}, onError: { error in
print("Receive error: \(error)")
})
}
// sleep in order to wait until previous example finishes
Thread.sleep(forTimeInterval: 4.0)
example("Delay with calculator") {
// custom delay calculator
// will be invoked to calculate delay for particular repetition
// will be invoked in the beginning of repetition, not when error occurred
let customCalculator: (UInt) -> Double = { attempt in
switch attempt {
case 1: return 0.5
case 2: return 1.5
default: return 2.0
}
}
_ = sampleObservable.retry(.customTimerDelayed(maxCount: 3, delayCalculator: customCalculator), scheduler: delayScheduler)
.subscribe(onNext: { event in
print("Receive event: \(event)")
}, onError: { error in
print("Receive error: \(error)")
})
}
playgroundShouldContinueIndefinitely()
//: [Next](@next)
| mit | a1e21204557f244bf9b41cd48a28d33e | 29.961165 | 127 | 0.720288 | 3.837545 | false | false | false | false |
globelabs/globe-connect-swift | Sources/Payment.swift | 1 | 3888 | import Foundation
public struct Payment {
let accessToken: String
let appId: String
let appSecret: String
public typealias SuccessHandler = (JSON) -> Void
public typealias ErrorHandler = (_ error: Error) -> Void
public init(
appId: String,
appSecret: String,
accessToken: String? = nil
) {
self.appId = appId
self.appSecret = appSecret
self.accessToken = accessToken!
}
public func sendPaymentRequest(
amount: Float,
description: String,
endUserId: String,
referenceCode: String,
transactionOperationStatus: String,
success: SuccessHandler? = nil,
failure: ErrorHandler? = nil
) {
// set the url
let url = "https://devapi.globelabs.com.ph/payment/v1/transactions/amount?access_token=\(self.accessToken)"
// TODO: make sure that amount has 2 decimal places
let data: [String: Any] = [
"amount" : String(format: "%.2f", amount),
"description" : description,
"endUserId" : endUserId,
"referenceCode" : referenceCode,
"transactionOperationStatus" : transactionOperationStatus
]
// set the header
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
// let's convert the payload to JSON
do {
// convert it!
let jsonData = try JSONSerialization.data(
withJSONObject: data,
options: JSONSerialization.WritingOptions.prettyPrinted
)
// it is now in json so we need it to be a string so we can send it
if let jsonPayload = String(data: jsonData, encoding: String.Encoding.utf8) {
Request().post(
url: url,
payload: jsonPayload,
headers: headers,
callback: { data, _, _ in
DispatchQueue.global(qos: .utility).async {
do {
let jsonResult = try JSON.parse(jsonData: data!)
DispatchQueue.main.async {
success?(jsonResult)
}
} catch {
DispatchQueue.main.async {
failure?(error)
}
}
}
}
)
}
} catch let error as NSError {
// oops, error in converting it to JSON
failure?(error)
}
}
public func getLastReferenceCode(
success: SuccessHandler? = nil,
failure: ErrorHandler? = nil
) -> Void {
// set the url
let url = "https://devapi.globelabs.com.ph/payment/v1/transactions/getLastRefCode?app_id=\(self.appId)&app_secret=\(self.appSecret)"
// set the header
let headers = [
"Content-Type" : "application/json; charset=utf-8"
]
// send the request
Request().get(
url: url,
headers: headers,
callback: { data, _, _ in
DispatchQueue.global(qos: .utility).async {
do {
let jsonResult = try JSON.parse(jsonData: data!)
DispatchQueue.main.async {
success?(jsonResult)
}
} catch {
DispatchQueue.main.async {
failure?(error)
}
}
}
}
)
}
}
| mit | 5e88e85793a6686a0d1ec4f531c17cda | 32.517241 | 140 | 0.459619 | 5.445378 | false | false | false | false |
prolificinteractive/Optik | Example/Optik/ViewController.swift | 1 | 2740 | //
// ViewController.swift
// Optik
//
// Created by Htin Linn on 05/14/2016.
// Copyright (c) 2016 Prolific Interactive. All rights reserved.
//
import UIKit
import Optik
internal final class ViewController: UIViewController {
// MARK: - Private properties
@IBOutlet fileprivate weak var localImagesButton: UIButton!
fileprivate var currentLocalImageIndex = 0 {
didSet {
localImagesButton.setImage(localImages[currentLocalImageIndex], for: .normal)
}
}
private let localImages: [UIImage] = [
UIImage(named: "cats.jpg")!,
UIImage(named: "super_blood_moon.jpg")!,
UIImage(named: "life.jpg")!,
UIImage(named: "whiteboard.jpg")!
]
// MARK: - Override functions
override func viewDidLoad() {
super.viewDidLoad()
setupDesign()
}
// MARK: - Private functions
private func setupDesign() {
localImagesButton.imageView?.layer.cornerRadius = 5
localImagesButton.imageView?.contentMode = .scaleAspectFill
}
@IBAction private func presentLocalImageViewer(_ sender: UIButton) {
let viewController = Optik.imageViewer(withImages: localImages,
initialImageDisplayIndex: currentLocalImageIndex,
delegate: self)
present(viewController, animated: true, completion: nil)
}
@IBAction private func presentRemoteImageViewer(_ sender: UIButton) {
guard
let url1 = URL(string: "https://upload.wikimedia.org/wikipedia/commons/6/6a/Caesio_teres_in_Fiji_by_Nick_Hobgood.jpg"),
let url2 = URL(string: "https://upload.wikimedia.org/wikipedia/commons/9/9b/Croissant%2C_cross_section.jpg"),
let url3 = URL(string: "https://upload.wikimedia.org/wikipedia/en/9/9d/Link_%28Hyrule_Historia%29.png"),
let url4 = URL(string: "https://upload.wikimedia.org/wikipedia/en/3/34/RickAstleyNeverGonnaGiveYouUp7InchSingleCover.jpg") else {
return
}
let urls = [url1, url2, url3, url4]
let imageDownloader = AlamofireImageDownloader()
let viewController = Optik.imageViewer(withURLs: urls, imageDownloader: imageDownloader)
present(viewController, animated: true, completion: nil)
}
}
// MARK: - Protocol conformance
// MARK: ImageViewerDelegate
extension ViewController: ImageViewerDelegate {
func transitionImageView(for index: Int) -> UIImageView {
return localImagesButton.imageView!
}
func imageViewerDidDisplayImage(at index: Int) {
currentLocalImageIndex = index
}
}
| mit | 9fa0e2636aad9cf299c48ab2b1f4a0db | 31.235294 | 141 | 0.635036 | 4.491803 | false | false | false | false |
xebia-france/XebiaSkiExtension | XebiaSki WatchKit Extension/DetailInterfaceController.swift | 1 | 1717 | //
// DetailInterfaceController.swift
// XebiaSki
//
// Created by Simone Civetta on 02/12/14.
// Copyright (c) 2014 Xebia IT Architechts. All rights reserved.
//
import WatchKit
import XebiaSkiFramework
class DetailInterfaceController: WKInterfaceController {
@IBOutlet weak var nameLabel: WKInterfaceLabel!
@IBOutlet weak var temperatureLabel: WKInterfaceLabel!
@IBOutlet weak var photoImageView: WKInterfaceImage!
@IBOutlet weak var dateLabel: WKInterfaceDate!
private var photoDownloadManager: PhotoDownloadManager?
private var skiResort: SkiResort?
override func awakeWithContext(context: AnyObject!) {
super.awakeWithContext(context)
if let skiResort = context as? SkiResort {
self.skiResort = skiResort
self.nameLabel.setText(skiResort.name)
self.temperatureLabel.setText(String(skiResort.temperature) + "°C ")
self.photoDownloadManager = PhotoDownloadManager(photoURL: skiResort.photoURL)
}
}
override func willActivate() {
if let skiResort = self.skiResort? {
self.photoDownloadManager?.retrievePhoto({ (image) -> () in
self.photoImageView.setImage(image)
})
setTitle(skiResort.name)
}
}
func savePreference() {
if let skiResort = self.skiResort? {
let archivedResort = NSKeyedArchiver.archivedDataWithRootObject(skiResort)
NSUserDefaults.standardUserDefaults().setObject(archivedResort, forKey: "selection")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
@IBAction func setAsDefault() {
savePreference()
}
}
| apache-2.0 | 33003c4872a9ead3f41e6c6747f2070f | 31.377358 | 96 | 0.670163 | 5.247706 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-x | Source/KeychainStorage/KeychainQueryOptions.swift | 2 | 2556 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder 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 AUTHOR ''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 AUTHOR 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.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
@objc(VSSKeychainQueryOptions) public class KeychainQueryOptions: NSObject {
#if os(macOS)
/// Trusted applications
@objc public var trustedApplications: [String] = []
#else
// swiftlint:disable line_length
/// Access group. See https://developer.apple.com/reference/security/ksecattraccessgroup
@objc public var accessGroup: String? = nil
/// Accessibility.
/// See https://developer.apple.com/documentation/security/keychain_services/keychain_items/restricting_keychain_item_accessibility
@objc public var accessibility: String = kSecAttrAccessibleAfterFirstUnlock as String
// swiftlint:enable line_length
#endif
#if os(macOS) || os(iOS)
/// Use biometric protection
@objc public var biometricallyProtected = false
/// User promt for UI
@objc public var biometricPromt: String = "Access your password on the keychain"
#endif
}
| bsd-3-clause | d97426c000cae34c6115221e299edf4a | 39.571429 | 135 | 0.742958 | 4.515901 | false | false | false | false |
apple/swift-corelibs-foundation | Darwin/Foundation-swiftoverlay-Tests/StdlibUnittest checkHashable.swift | 1 | 6468 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// FIXME: This should be in a separate package:
// rdar://57247249 Port StdlibUnittest's collection test suite to XCTest
import XCTest
/// Produce an integer hash value for `value` by feeding it to a dedicated
/// `Hasher`. This is always done by calling the `hash(into:)` method.
/// If a non-nil `seed` is given, it is used to perturb the hasher state;
/// this is useful for resolving accidental hash collisions.
private func hash<H: Hashable>(_ value: H, seed: Int? = nil) -> Int {
var hasher = Hasher()
if let seed = seed {
hasher.combine(seed)
}
hasher.combine(value)
return hasher.finalize()
}
/// Test that the elements of `groups` consist of instances that satisfy the
/// semantic requirements of `Hashable`, with each group defining a distinct
/// equivalence class under `==`.
public func checkHashableGroups<Groups: Collection>(
_ groups: Groups,
_ message: @autoclosure () -> String = "",
allowIncompleteHashing: Bool = false,
file: StaticString = #file, line: UInt = #line
) where Groups.Element: Collection, Groups.Element.Element: Hashable {
let instances = groups.flatMap { $0 }
// groupIndices[i] is the index of the element in groups that contains
// instances[i].
let groupIndices =
zip(0..., groups).flatMap { i, group in group.map { _ in i } }
func equalityOracle(_ lhs: Int, _ rhs: Int) -> Bool {
return groupIndices[lhs] == groupIndices[rhs]
}
checkHashable(
instances,
equalityOracle: equalityOracle,
hashEqualityOracle: equalityOracle,
allowBrokenTransitivity: false,
allowIncompleteHashing: allowIncompleteHashing,
file: file, line: line)
}
/// Test that the elements of `instances` satisfy the semantic requirements of
/// `Hashable`, using `equalityOracle` to generate equality and hashing
/// expectations from pairs of positions in `instances`.
public func checkHashable<Instances: Collection>(
_ instances: Instances,
equalityOracle: (Instances.Index, Instances.Index) -> Bool,
allowBrokenTransitivity: Bool = false,
allowIncompleteHashing: Bool = false,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) where Instances.Element: Hashable {
checkHashable(
instances,
equalityOracle: equalityOracle,
hashEqualityOracle: equalityOracle,
allowBrokenTransitivity: allowBrokenTransitivity,
allowIncompleteHashing: allowIncompleteHashing,
file: file, line: line)
}
/// Test that the elements of `instances` satisfy the semantic
/// requirements of `Hashable`, using `equalityOracle` to generate
/// equality expectations from pairs of positions in `instances`,
/// and `hashEqualityOracle` to do the same for hashing.
public func checkHashable<Instances: Collection>(
_ instances: Instances,
equalityOracle: (Instances.Index, Instances.Index) -> Bool,
hashEqualityOracle: (Instances.Index, Instances.Index) -> Bool,
allowBrokenTransitivity: Bool = false,
allowIncompleteHashing: Bool = false,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) where
Instances.Element: Hashable {
checkEquatable(
instances,
oracle: equalityOracle,
allowBrokenTransitivity: allowBrokenTransitivity,
message(),
file: file, line: line)
for i in instances.indices {
let x = instances[i]
for j in instances.indices {
let y = instances[j]
let predicted = hashEqualityOracle(i, j)
XCTAssertEqual(
predicted, hashEqualityOracle(j, i),
"bad hash oracle: broken symmetry between indices \(i), \(j)",
file: file, line: line)
if x == y {
XCTAssertTrue(
predicted,
"""
bad hash oracle: equality must imply hash equality
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
}
if predicted {
XCTAssertEqual(
hash(x), hash(y),
"""
hash(into:) expected to match, found to differ
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
XCTAssertEqual(
x.hashValue, y.hashValue,
"""
hashValue expected to match, found to differ
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
XCTAssertEqual(
x._rawHashValue(seed: 0), y._rawHashValue(seed: 0),
"""
_rawHashValue(seed:) expected to match, found to differ
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
} else if !allowIncompleteHashing {
// Try a few different seeds; at least one of them should discriminate
// between the hashes. It is extremely unlikely this check will fail
// all ten attempts, unless the type's hash encoding is not unique,
// or unless the hash equality oracle is wrong.
XCTAssertTrue(
(0..<10).contains { hash(x, seed: $0) != hash(y, seed: $0) },
"""
hash(into:) expected to differ, found to match
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
XCTAssertTrue(
(0..<10).contains { i in
x._rawHashValue(seed: i) != y._rawHashValue(seed: i)
},
"""
_rawHashValue(seed:) expected to differ, found to match
lhs (at index \(i)): \(x)
rhs (at index \(j)): \(y)
""",
file: file, line: line)
}
}
}
}
public func checkHashable<T : Hashable>(
expectedEqual: Bool, _ lhs: T, _ rhs: T,
_ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line
) {
checkHashable(
[lhs, rhs], equalityOracle: { expectedEqual || $0 == $1 }, message(),
file: file, line: line)
}
| apache-2.0 | 244d5485f3b395dafd38a175dc48ed89 | 35.337079 | 80 | 0.614255 | 4.424077 | false | false | false | false |
sztoth/PodcastChapters | PodcastChapters/UI/Views/ChapterCell/ChapterViewItem.swift | 1 | 956 | //
// ChapterViewItem.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 10. 25..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import Cocoa
class ChapterViewItem: NSCollectionViewItem {
var text: String {
get { return chapterView.text }
set { chapterView.text = newValue }
}
var highlighted: Bool {
get { return chapterView.highlighted }
set { chapterView.highlighted = newValue }
}
fileprivate var chapterView: ChapterViewItemView {
return view as! ChapterViewItemView
}
override func loadView() {
let customView: ChapterViewItemView = ChapterViewItemView.pch_loadFromNib()!
view = customView
}
override func prepareForReuse() {
super.prepareForReuse()
highlighted = false
}
override func viewDidLoad() {
super.viewDidLoad()
chapterView.setup()
highlighted = false
}
}
| mit | fe2ab30cafb37486b082d549b68584a6 | 21.738095 | 84 | 0.640838 | 5 | false | false | false | false |
spark/photon-tinker-ios | Photon-Tinker/Mesh/Common/Gen3SetupFlowRunner.swift | 1 | 16777 | //
// Created by Raimundas Sakalauskas on 2019-03-21.
// Copyright (c) 2019 Particle. All rights reserved.
//
//
// Created by Raimundas Sakalauskas on 2019-03-01.
// Copyright (c) 2019 Particle. All rights reserved.
//
import Foundation
import CoreBluetooth
class Gen3SetupFlowRunner : Gen3SetupBluetoothConnectionManagerDelegate, Gen3SetupStepDelegate {
internal var context: Gen3SetupContext
internal var currentFlow: [Gen3SetupStep]?
internal var currentStepIdx: Int = 0
internal var currentStep: Gen3SetupStep? {
if let currentFlow = currentFlow {
return currentFlow[currentStepIdx]
}
return nil
}
init(delegate: Gen3SetupFlowRunnerDelegate, context: Gen3SetupContext? = nil) {
if (context == nil) {
self.context = Gen3SetupContext()
self.context.bluetoothManager = Gen3SetupBluetoothConnectionManager(delegate: self)
} else {
self.context = context!
}
self.context.delegate = delegate
self.context.stepDelegate = self
}
//MARK: public interface
func pauseSetup() {
context.paused = true
}
func continueSetup() {
if (context.paused) {
context.paused = false
self.runCurrentStep()
}
}
func cancelSetup() {
context.canceled = true
context.bluetoothManager.stopScan()
context.bluetoothManager.dropAllConnections()
}
internal func finishSetup() {
context.canceled = true
context.bluetoothManager.stopScan()
context.bluetoothManager.dropAllConnections()
}
//this is for internal use only, because it requires a lot of internal knowledge to use and is nearly impossible to expose to external developers
internal func rewindTo(step: Gen3SetupStep.Type, runStep: Bool = true) -> Gen3SetupFlowError? {
currentStep!.rewindFrom()
guard let currentFlow = self.currentFlow else {
return .IllegalOperation
}
for i in 0 ..< currentFlow.count {
if (currentFlow[i].isKind(of: step)) {
if (i >= self.currentStepIdx) {
//trying to "rewind" forward
return .IllegalOperation
}
self.currentStepIdx = i
self.log("returning to step: \(self.currentStepIdx)")
self.currentStep!.rewindTo(context: self.context)
if (runStep) {
self.runCurrentStep()
}
return nil
}
}
return .IllegalOperation
}
func retryLastAction() {
self.log("Retrying action: \(self.currentStep!)")
self.currentStep!.retry()
}
internal func log(_ message: String) {
ParticleLogger.logInfo("Gen3SetupFlowRunner", format: message, withParameters: getVaList([]))
}
internal func fail(withReason reason: Gen3SetupFlowError, severity: Gen3SetupErrorSeverity = .Error, nsError: Error? = nil) {
if context.canceled == false {
if (severity == .Fatal) {
self.cancelSetup()
}
self.log("error: \(reason.description), nsError: \(nsError?.localizedDescription as Optional)")
context.delegate.gen3SetupError(self.currentStep!, error: reason, severity: severity, nsError: nsError)
}
}
internal func runCurrentStep() {
if (context.canceled) {
return
}
guard let currentFlow = self.currentFlow else {
return
}
//if we reached the end of current flow
if (currentStepIdx == currentFlow.count) {
self.switchFlow()
}
log("stepComplete\n\n" +
"--------------------------------------------------------------------------------------------\n" +
"currentStepIdx = \(currentStepIdx), currentStep = \(currentStep)")
self.currentStep?.reset()
self.currentStep?.run(context: self.context)
}
internal func switchFlow() {
fatalError("not implemented")
}
//MARK: Delegate responses
func setTargetDeviceInfo(dataMatrix: Gen3SetupDataMatrix) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetTargetDeviceInfo.self else {
return .IllegalOperation
}
return (currentStep as? StepGetTargetDeviceInfo)?.setTargetDeviceInfo(dataMatrix: dataMatrix)
}
func setTargetUseEthernet(useEthernet: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureCorrectEthernetFeatureStatus.self else {
return .IllegalOperation
}
return (currentStep as? StepEnsureCorrectEthernetFeatureStatus)?.setTargetUseEthernet(useEthernet: useEthernet)
}
func setTargetSimStatus(simActive: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureCorrectSimState.self else {
return .IllegalOperation
}
return (currentStep as? StepEnsureCorrectSimState)?.setTargetSimStatus(simActive: simActive)
}
func setSimDataLimit(dataLimit: Int) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepSetSimDataLimit.self else {
return .IllegalOperation
}
return (currentStep as? StepSetSimDataLimit)?.setSimDataLimit(dataLimit: dataLimit)
}
func setTargetPerformFirmwareUpdate(update: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureLatestFirmware.self else {
return .IllegalOperation
}
return (currentStep as? StepEnsureLatestFirmware)?.setTargetPerformFirmwareUpdate(update: update)
}
func setTargetDeviceLeaveNetwork(leave: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureNotOnMeshNetwork.self else {
return .IllegalOperation
}
return (currentStep as? StepEnsureNotOnMeshNetwork)?.setTargetDeviceLeaveNetwork(leave: leave)
}
func setSwitchToControlPanel(switchToCP: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepOfferToSwitchToControlPanel.self else {
return .IllegalOperation
}
return (currentStep as? StepOfferToSwitchToControlPanel)?.setSwitchToControlPanel(switchToCP: switchToCP)
}
func setSelectStandAloneOrMeshSetup(meshSetup: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepOfferSetupStandAloneOrWithNetwork.self else {
return .IllegalOperation
}
return (currentStep as? StepOfferSetupStandAloneOrWithNetwork)?.setSelectStandAloneOrMeshSetup(meshSetup: meshSetup)
}
func setOptionalSelectedNetwork(selectedNetworkExtPanID: String?) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepOfferSelectOrCreateNetwork.self else {
return .IllegalOperation
}
return (currentStep as? StepOfferSelectOrCreateNetwork)?.setOptionalSelectedNetwork(selectedNetworkExtPanID: selectedNetworkExtPanID)
}
func setInfoDone() -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepShowInfo.self else {
return .IllegalOperation
}
return (currentStep as? StepShowInfo)?.setInfoDone()
}
func setDeviceName(name: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) {
guard let currentStep = currentStep, type(of: currentStep) == StepGetNewDeviceName.self else {
onComplete(.IllegalOperation)
return
}
(currentStep as? StepGetNewDeviceName)?.setDeviceName(name: name, onComplete: onComplete)
}
func setAddOneMoreDevice(addOneMoreDevice: Bool) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepOfferToAddOneMoreDevice.self else {
return .IllegalOperation
}
return nil
}
func setNewNetworkName(name: String) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetNewNetworkName.self else {
return .IllegalOperation
}
return (currentStep as? StepGetNewNetworkName)?.setNewNetworkName(name: name)
}
func setNewNetworkPassword(password: String) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetNewNetworkPassword.self else {
return .IllegalOperation
}
return (currentStep as? StepGetNewNetworkPassword)?.setNewNetworkPassword(password: password)
}
func setSelectedWifiNetworkPassword(_ password: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureCorrectSelectedWifiNetworkPassword.self else {
onComplete(.IllegalOperation)
return
}
(currentStep as? StepEnsureCorrectSelectedWifiNetworkPassword)?.setSelectedWifiNetworkPassword(password, onComplete: onComplete)
}
func setSelectedWifiNetwork(selectedNetwork: Gen3SetupNewWifiNetworkInfo) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetUserWifiNetworkSelection.self else {
return .IllegalOperation
}
return (currentStep as? StepGetUserWifiNetworkSelection)?.setSelectedWifiNetwork(selectedNetwork: selectedNetwork)
}
func setSelectedNetwork(selectedNetworkExtPanID: String) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetUserNetworkSelection.self else {
return .IllegalOperation
}
return (currentStep as? StepGetUserNetworkSelection)?.setSelectedNetwork(selectedNetworkExtPanID: selectedNetworkExtPanID)
}
func setCommissionerDeviceInfo(dataMatrix: Gen3SetupDataMatrix) -> Gen3SetupFlowError? {
guard let currentStep = currentStep, type(of: currentStep) == StepGetCommissionerDeviceInfo.self else {
return .IllegalOperation
}
return (currentStep as? StepGetCommissionerDeviceInfo)?.setCommissionerDeviceInfo(dataMatrix: dataMatrix)
}
func setSelectedNetworkPassword(_ password: String, onComplete:@escaping (Gen3SetupFlowError?) -> ()) {
guard let currentStep = currentStep, type(of: currentStep) == StepEnsureCorrectSelectedNetworkPassword.self else {
onComplete(.IllegalOperation)
return
}
(currentStep as? StepEnsureCorrectSelectedNetworkPassword)?.setSelectedNetworkPassword(password, onComplete: onComplete)
}
func rescanNetworks() -> Gen3SetupFlowError? {
guard let currentStep = currentStep else {
return .IllegalOperation
}
if (type(of: currentStep) == StepOfferSelectOrCreateNetwork.self) {
(currentStep as! StepOfferSelectOrCreateNetwork).scanNetworks()
} else if (type(of: currentStep) == StepGetUserNetworkSelection.self) {
(currentStep as! StepGetUserNetworkSelection).scanNetworks()
} else if (type(of: currentStep) == StepGetUserWifiNetworkSelection.self) {
(currentStep as! StepGetUserWifiNetworkSelection).scanWifiNetworks()
} else {
return .IllegalOperation
}
return nil
}
//MARK: BluetoothConnectionManagerDelegate
internal func bluetoothConnectionManagerStateChanged(sender: Gen3SetupBluetoothConnectionManager, state: Gen3SetupBluetoothConnectionManagerState) {
if (context.canceled) {
return
}
self.log("bluetoothConnectionManagerStateChanged = \(state)")
if (context.bluetoothManager.state == .Ready) {
context.bluetoothReady = true
} else if (context.bluetoothManager.state == .Disabled) {
context.bluetoothReady = false
//if we are waiting for the reply = trigger timeout
if let targetDeviceTransceiver = context.targetDevice.transceiver {
targetDeviceTransceiver.triggerTimeout()
}
//if we are waiting for the reply = trigger timeout
if let commissionerDeviceTransceiver = context.commissionerDevice?.transceiver {
commissionerDeviceTransceiver.triggerTimeout()
}
}
}
internal func bluetoothConnectionManagerError(sender: Gen3SetupBluetoothConnectionManager, error: BluetoothConnectionManagerError, severity: Gen3SetupErrorSeverity) {
if (context.canceled) {
return
}
log("bluetoothConnectionManagerError = \(error), severity = \(severity)")
if let currentStep = currentStep, !currentStep.handleBluetoothConnectionManagerError(error) {
self.fail(withReason: .BluetoothError, severity: .Fatal)
}
}
internal func bluetoothConnectionManagerConnectionCreated(sender: Gen3SetupBluetoothConnectionManager, connection: Gen3SetupBluetoothConnection) {
if (context.canceled) {
return
}
log("bluetoothConnectionManagerConnectionCreated = \(connection)")
if let currentStep = currentStep, !currentStep.handleBluetoothConnectionManagerConnectionCreated(connection) {
//do nothing
}
}
internal func bluetoothConnectionManagerPeripheralDiscovered(sender: Gen3SetupBluetoothConnectionManager, peripheral: CBPeripheral) {
if (context.canceled) {
return
}
log("bluetoothConnectionManagerPeripheralDiscovered = \(peripheral)")
if let currentStep = currentStep, !currentStep.handleBluetoothConnectionManagerPeripheralDiscovered(peripheral) {
//do nothing
}
}
internal func bluetoothConnectionManagerConnectionBecameReady(sender: Gen3SetupBluetoothConnectionManager, connection: Gen3SetupBluetoothConnection) {
if (context.canceled) {
return
}
log("bluetoothConnectionManagerConnectionBecameReady = \(connection)")
if let currentStep = currentStep, !currentStep.handleBluetoothConnectionManagerConnectionBecameReady(connection) {
//do nothing
}
}
internal func bluetoothConnectionManagerConnectionDropped(sender: Gen3SetupBluetoothConnectionManager, connection: Gen3SetupBluetoothConnection) {
if (context.canceled) {
return
}
log("bluetoothConnectionManagerConnectionDropped = \(connection)")
if (connection == context.targetDevice.transceiver?.connection || connection == context.commissionerDevice?.transceiver?.connection) {
if (connection == context.targetDevice.transceiver?.connection) {
context.targetDevice.transceiver = nil
}
if (connection == context.commissionerDevice?.transceiver?.connection) {
context.commissionerDevice?.transceiver = nil
}
if let currentStep = currentStep, !currentStep.handleBluetoothConnectionManagerConnectionDropped(connection) {
self.fail(withReason: .BluetoothConnectionDropped, severity: .Fatal)
}
}
//if some other connection was dropped - we dont care
}
//MARK: Gen3SetupStepDelegate
internal func rewindTo(_ sender: Gen3SetupStep, step: Gen3SetupStep.Type, runStep: Bool = true) -> Gen3SetupStep {
if let error = self.rewindTo(step: step, runStep: runStep) {
fatalError("flow tried to perform illegal back")
} else {
return self.currentStep!
}
}
internal func fail(_ sender: Gen3SetupStep, withReason reason: Gen3SetupFlowError, severity: Gen3SetupErrorSeverity, nsError: Error?) {
self.fail(withReason: reason, severity: severity, nsError: nsError)
}
internal func stepCompleted(_ sender: Gen3SetupStep) {
if (context.canceled) {
return
}
if type(of: sender) != type(of: currentStep!) {
self.log("Flow order is broken :(. Current command: \(self.currentStep!), Parameter command: \(sender)")
self.log("Stack:\n\(Thread.callStackSymbols.joined(separator: "\n"))")
self.fail(withReason: .CriticalFlowError, severity: .Fatal)
}
self.currentStepIdx += 1
if (context.paused) {
return
}
self.runCurrentStep()
}
}
| apache-2.0 | 3d81d3811bbecf1d5dd3923a50422c73 | 35.872527 | 170 | 0.665018 | 5.399743 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Healthcare | iOS/Healthcare/Views/MILRatingCollectionView.swift | 1 | 8356 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2014, 2015. All Rights Reserved.
*/
import UIKit
import QuartzCore
/**
Reusable CollectionView that acts as a horizontal scrolling number picker
*/
class MILRatingCollectionView: UICollectionView, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate {
var dummyBackgroundView: UIView!
var circularView: UIView!
var selectedIndexPath: NSIndexPath?
var ratingCellID = "ratingCell"
var centerIsSet = false
private var currentNumberRange: NSRange = NSMakeRange(0, 10)
/// The range of the collectionView, location is the starting number, length is the number of elements
var numberRange: NSRange {
set(value) {
currentNumberRange = value
selectedIndexPath = NSIndexPath(forRow: (currentNumberRange.length - currentNumberRange.location)/2, inSection: 0)
}
get {
return currentNumberRange
}
}
/// Private delegate so callbacks in this class will be called before any child class
private var actualDelegate: UICollectionViewDelegate?
/// Private datasource so callbacks in this class will be called before any child class
private var actualDataSource: UICollectionViewDataSource?
/// custom delegate property accessible to external classes
var preDelegate: UICollectionViewDelegate? {
set(newValue) {
self.actualDelegate = newValue
//super.delegate = self
}
get {
return self.actualDelegate
}
}
/// custom datasource property accessible to external classes
var preDataSource: UICollectionViewDataSource? {
set(newValue) {
self.actualDataSource = newValue
//super.dataSource = self
}
get {
return self.actualDataSource
}
}
// Init method called programmaticly
convenience init(frame: CGRect) {
self.init(frame: frame)
initView()
}
// Init method called from storyboard
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initView()
}
/**
MILRatingCollectionView set up method, initializes background and collectionView properties.
*/
func initView() {
super.delegate = self
super.dataSource = self
self.collectionViewLayout = UICollectionViewFlowLayoutCenterItem(viewWidth: UIScreen.mainScreen().bounds.size.width)
self.showsHorizontalScrollIndicator = false
self.registerClass(RatingCollectionViewCell.self, forCellWithReuseIdentifier: ratingCellID)
// create ciruclarview and fix in the middle of the collectionView background
circularView = UIView(frame: CGRectMake(0, 0, 100, 100))
circularView.backgroundColor = UIColor.readyAppRed()
self.setRoundedViewToDiameter(circularView, diameter: circularView.frame.size.height)
dummyBackgroundView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height))
dummyBackgroundView.addSubview(circularView)
self.backgroundView = dummyBackgroundView
setUpAutoLayoutConstraints()
}
// MARK: CollectionView delegate and datasource
// number of items based on number range set by developer
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return currentNumberRange.length
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var cell: RatingCollectionViewCell?
// if preDataSource not set by developer, create cell like normal
if let ds = preDataSource {
cell = ds.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as? RatingCollectionViewCell
} else {
cell = collectionView.dequeueReusableCellWithReuseIdentifier(ratingCellID, forIndexPath: indexPath) as? RatingCollectionViewCell
}
cell!.numberLabel.text = "\(indexPath.row + currentNumberRange.location)" // offset to start at 1
// sets an initial highlighted cell, only true once
if !centerIsSet && indexPath == selectedIndexPath {
cell!.setAsHighlightedCell()
centerIsSet = true
}
return cell!
}
/**
Method to round corners enough to make a circle based on diameter.
- parameter view: UIView to circlefy
- parameter diameter: the desired diameter of your view
*/
func setRoundedViewToDiameter(view: UIView, diameter: CGFloat) {
let saveCenter = view.center
let newFrame = CGRectMake(view.frame.origin.x, view.frame.origin.y, diameter, diameter)
view.frame = newFrame
view.layer.cornerRadius = diameter / 2.0
view.center = saveCenter
}
// MARK ScrollView delegate methods
/**
Method replicating the functionality of indexPathForItemAtPoint(), which was not working with the custom flow layout
- parameter point: center point to find most centered cell
- returns: UICollectionViewLayoutAttributes of the centered cell
*/
func grabCellAttributesAtPoint(point: CGPoint) -> UICollectionViewLayoutAttributes? {
let visible = self.indexPathsForVisibleItems()
for paths in visible {
let layoutAttributes = self.layoutAttributesForItemAtIndexPath(paths )
// true when center point is within a cell's frame
if CGRectContainsPoint(layoutAttributes!.frame, point) {
return layoutAttributes!
}
}
return nil
}
/**
Method that recognizes center cell and highlights it while leaving other cells normal
- parameter scrollView: scrollView built into the UICollectionView
*/
func scrollViewDidScroll(scrollView: UIScrollView) {
// Get centered point within collectionView contentSize, y value not crucial, just needs to always be in center
let centerPoint = CGPointMake(self.center.x + self.contentOffset.x,
self.contentSize.height / 2)
if let attributes = grabCellAttributesAtPoint(centerPoint) {
// true when center cell has changed, revert old center cell to normal cell
if selectedIndexPath != attributes.indexPath {
if let oldPath = selectedIndexPath {
if let previousCenterCell = self.cellForItemAtIndexPath(oldPath) as? RatingCollectionViewCell {
previousCenterCell.setAsNormalCell()
}
}
// make current center cell a highlighted cell
let cell = self.cellForItemAtIndexPath(attributes.indexPath) as! RatingCollectionViewCell
cell.setAsHighlightedCell()
selectedIndexPath = attributes.indexPath
}
}
}
/**
Autolayout constraints for the circular background view
*/
func setUpAutoLayoutConstraints() {
self.circularView.translatesAutoresizingMaskIntoConstraints = false
self.dummyBackgroundView.addConstraint(NSLayoutConstraint(
item:self.circularView, attribute:.CenterX,
relatedBy:.Equal, toItem:self.dummyBackgroundView,
attribute:.CenterX, multiplier:1, constant:0))
self.dummyBackgroundView.addConstraint(NSLayoutConstraint(
item:self.circularView, attribute:.CenterY,
relatedBy:.Equal, toItem:self.dummyBackgroundView,
attribute:.CenterY, multiplier:1, constant:0))
self.dummyBackgroundView.addConstraint(NSLayoutConstraint(
item:self.circularView, attribute:.Height,
relatedBy:.Equal, toItem:nil,
attribute:.NotAnAttribute, multiplier:1, constant:100))
self.dummyBackgroundView.addConstraint(NSLayoutConstraint(
item:self.circularView, attribute:.Width,
relatedBy:.Equal, toItem:nil,
attribute:.NotAnAttribute, multiplier:1, constant:100))
}
}
| epl-1.0 | de6f551b8f6275c99de96c190603510a | 38.042056 | 140 | 0.662238 | 5.867275 | false | false | false | false |
JanGorman/SwiftMessageBar | SwiftMessageBar/SwiftMessageBar.swift | 1 | 15434 | //
// Copyright (c) 2015 Schnaub. All rights reserved.
//
import UIKit
public typealias Callback = () -> Void
public final class SwiftMessageBar {
public struct Config {
public struct Defaults {
public static let errorColor: UIColor = .red
public static let successColor: UIColor = .green
public static let infoColor: UIColor = .blue
public static let titleColor: UIColor = .white
public static let messageColor: UIColor = .white
public static let isStatusBarHidden = false
public static let titleFont: UIFont = .boldSystemFont(ofSize: 16)
public static let messageFont: UIFont = .systemFont(ofSize: 14)
public static let isHapticFeedbackEnabled = true
public static let windowLevel:UIWindow.Level = .normal
}
let errorColor: UIColor
let successColor: UIColor
let infoColor: UIColor
let titleColor: UIColor
let messageColor: UIColor
let isStatusBarHidden: Bool
let successIcon: UIImage?
let infoIcon: UIImage?
let errorIcon: UIImage?
let titleFont: UIFont
let messageFont: UIFont
let isHapticFeedbackEnabled: Bool
let windowLevel: UIWindow.Level
public init(errorColor: UIColor = Defaults.errorColor,
successColor: UIColor = Defaults.successColor,
infoColor: UIColor = Defaults.infoColor,
titleColor: UIColor = Defaults.titleColor,
messageColor: UIColor = Defaults.messageColor,
isStatusBarHidden: Bool = Defaults.isStatusBarHidden,
successIcon: UIImage? = nil,
infoIcon: UIImage? = nil,
errorIcon: UIImage? = nil,
titleFont: UIFont = Defaults.titleFont,
messageFont: UIFont = Defaults.messageFont,
isHapticFeedbackEnabled: Bool = Defaults.isHapticFeedbackEnabled,
windowLevel: UIWindow.Level = Defaults.windowLevel) {
self.errorColor = errorColor
self.successColor = successColor
self.infoColor = infoColor
self.titleColor = titleColor
self.messageColor = messageColor
self.isStatusBarHidden = isStatusBarHidden
let bundle = Bundle(for: SwiftMessageBar.self)
self.successIcon = successIcon ?? UIImage(named: "icon-success", in: bundle, compatibleWith: nil)
self.infoIcon = infoIcon ?? UIImage(named: "icon-info", in: bundle, compatibleWith: nil)
self.errorIcon = errorIcon ?? UIImage(named: "icon-error", in: bundle, compatibleWith: nil)
self.titleFont = titleFont
self.messageFont = messageFont
self.isHapticFeedbackEnabled = isHapticFeedbackEnabled
self.windowLevel = windowLevel
}
public class Builder {
private var errorColor: UIColor?
private var successColor: UIColor?
private var infoColor: UIColor?
private var titleColor: UIColor?
private var messageColor: UIColor?
private var isStatusBarHidden: Bool?
private var successIcon: UIImage?
private var infoIcon: UIImage?
private var errorIcon: UIImage?
private var titleFont: UIFont?
private var messageFont: UIFont?
private var isHapticFeedbackEnabled: Bool?
private var windowLevel: UIWindow.Level?
public init() {
}
public func withErrorColor(_ color: UIColor) -> Builder {
errorColor = color
return self
}
public func withSuccessColor(_ color: UIColor) -> Builder {
successColor = color
return self
}
public func withInfoColor(_ color: UIColor) -> Builder {
infoColor = color
return self
}
public func withTitleColor(_ color: UIColor) -> Builder {
titleColor = color
return self
}
public func withMessageColor(_ color: UIColor) -> Builder {
messageColor = color
return self
}
public func withStatusBarHidden(_ isHidden: Bool) -> Builder {
isStatusBarHidden = isHidden
return self
}
public func withSuccessIcon(_ icon: UIImage) -> Builder {
successIcon = icon
return self
}
public func withInfoIcon(_ icon: UIImage) -> Builder {
infoIcon = icon
return self
}
public func withErrorIcon(_ icon: UIImage) -> Builder {
errorIcon = icon
return self
}
public func withTitleFont(_ font: UIFont) -> Builder {
titleFont = font
return self
}
public func withMessageFont(_ font: UIFont) -> Builder {
messageFont = font
return self
}
public func withHapticFeedbackEnabled(_ isEnabled: Bool) -> Builder {
isHapticFeedbackEnabled = isEnabled
return self
}
public func withWindowLevel(_ level: UIWindow.Level) -> Builder {
windowLevel = level
return self
}
public func build() -> Config {
Config(errorColor: errorColor ?? Defaults.errorColor,
successColor: successColor ?? Defaults.successColor,
infoColor: infoColor ?? Defaults.infoColor,
titleColor: titleColor ?? Defaults.titleColor,
messageColor: messageColor ?? Defaults.messageColor,
isStatusBarHidden: isStatusBarHidden ?? Defaults.isStatusBarHidden,
successIcon: successIcon, infoIcon: infoIcon, errorIcon: errorIcon,
titleFont: titleFont ?? Defaults.titleFont,
messageFont: messageFont ?? Defaults.messageFont,
isHapticFeedbackEnabled: isHapticFeedbackEnabled ?? Defaults.isHapticFeedbackEnabled,
windowLevel: windowLevel ?? Defaults.windowLevel)
}
}
}
public static let sharedMessageBar = SwiftMessageBar()
private static let showHideDuration: TimeInterval = 0.25
private var config: Config
private var messageWindow: MessageWindow?
private var timer: Timer?
public var tapHandler : (() -> Void)?
private func newMessageWindow() -> MessageWindow {
let messageWindow = MessageWindow()
messageWindow.frame = UIScreen.main.bounds
messageWindow.isHidden = false
messageWindow.windowLevel = config.windowLevel
messageWindow.backgroundColor = .clear
messageWindow.messageBarController.statusBarHidden = config.isStatusBarHidden
messageWindow.rootViewController = messageWindow.messageBarController
return messageWindow
}
private var messageQueue: Queue<Message>
private var isMessageVisible = false
private init() {
messageQueue = Queue<Message>()
config = Config()
}
/// Set a message bar configuration used by all displayed messages.
public static func setSharedConfig(_ config: Config) {
sharedMessageBar.config = config
}
/// Display a message
///
/// - Parameters:
/// - title: An optional title
/// - message: An optional message
/// - type: The message type
/// - duration: The time interval in seconds to show the message for
/// - dismiss: Does the message automatically dismiss or not
/// - languageDirection: Set an optional language direction if you require RTL support outside of what the system provides
/// i.e. no need to set this parameter when NSLocale already is set to the proper languageDirection
/// - accessoryView: An optional view to show in the right of the Message Bar
/// - callback: An optional callback to execute when the user taps on a message to dismiss it.
/// - Returns: A UUID for the message. Can be used to cancel the display of a specific message
@discardableResult
public static func showMessage(withTitle title: String? = nil, message: String? = nil, type: MessageType,
duration: TimeInterval = 3, dismiss: Bool = true,
languageDirection: NSLocale.LanguageDirection = .unknown,
accessoryView: UIView? = nil,
callback: Callback? = nil) -> UUID {
sharedMessageBar.showMessage(withTitle: title, message: message, type: type, duration: duration, dismiss: dismiss,
languageDirection: languageDirection, accessoryView: accessoryView, callback: callback)
}
/// Display a message
///
/// - Parameters:
/// - title: An optional title
/// - message: An optional message
/// - type: The message type
/// - duration: The time interval in seconds to show the message for
/// - dismiss: Does the message automatically dismiss or not
/// - languageDirection: Set an optional language direction if you require RTL support outside of what the system provides
/// i.e. no need to set this parameter when NSLocale already is set to the proper languageDirection
/// - accessoryView: An optional view to show in the right of the Message Bar
/// - callback: An optional callback to execute when the user taps on a message to dismiss it.
/// - Returns: A UUID for the message. Can be used to cancel the display of a specific message
@discardableResult
public func showMessage(withTitle title: String? = nil, message: String? = nil, type: MessageType,
duration: TimeInterval = 3, dismiss: Bool = true,
languageDirection: NSLocale.LanguageDirection = .unknown,
accessoryView: UIView? = nil,
callback: Callback? = nil) -> UUID {
let message = Message(type: type, title: title, message: message,
backgroundColor: type.backgroundColor(fromConfig: config), titleFontColor: config.titleColor,
messageFontColor: config.messageColor, icon: type.image(fromConfig: config), duration: duration,
dismiss: dismiss, callback: callback, languageDirection: languageDirection,
titleFont: config.titleFont, messageFont: config.messageFont, accessoryView: accessoryView)
if languageDirection == .rightToLeft {
message.flipHorizontal()
}
messageQueue.enqueue(message)
if !isMessageVisible {
dequeueNextMessage()
}
return message.id
}
/// Cancels the display of all messages.
///
/// - Parameter force: A boolean to force immediate dismissal (without animation). Defaults to `false`
public func cancelAll(force: Bool = false) {
guard !isMessageVisible && messageQueue.isEmpty || force else { return }
if let message = visibleMessage {
if force {
message.removeFromSuperview()
messageWindow = nil
} else {
dismissMessage(message)
}
}
resetTimer()
isMessageVisible = false
messageQueue.removeAll()
}
/// Cancels the display of a specific message
///
/// - Parameter id: The UUID of the message to cancel.
public func cancel(withId id: UUID) {
if let message = visibleMessage, message.id == id {
dismissMessage(message)
messageQueue.removeElement(message)
}
}
private var visibleMessage: Message? {
messageWindow?.messageBarView.subviews.compactMap { $0 as? Message }.first
}
private func dequeueNextMessage() {
guard let message = messageQueue.dequeue() else { return }
let messageWindow: MessageWindow
if let existensWindow = self.messageWindow {
messageWindow = existensWindow
} else {
messageWindow = newMessageWindow()
self.messageWindow = messageWindow
}
messageWindow.messageBarView.addSubview(message)
messageWindow.messageBarView.bringSubviewToFront(message)
isMessageVisible = true
if #available(iOS 11, *) {
message.configureSubviews(topAnchor: messageWindow.messageBarView.safeAreaLayoutGuide.topAnchor)
} else {
message.configureSubviews(topAnchor: messageWindow.messageBarController.topLayoutGuide.bottomAnchor)
}
message.setNeedsUpdateConstraints()
let gesture = UITapGestureRecognizer(target: self, action: #selector(tap))
message.addGestureRecognizer(gesture)
message.transform = CGAffineTransform(translationX: 0, y: -messageWindow.frame.height)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
message.transform = CGAffineTransform(translationX: 0, y: -message.frame.height)
UIView.animate(withDuration: SwiftMessageBar.showHideDuration, animations: {
message.transform = .identity
}, completion: { _ in
self.provideHapticFeedback(for: message)
})
}
if message.dismiss {
resetTimer()
timer = Timer.scheduledTimer(timeInterval: message.duration, target: self, selector: #selector(dismiss),
userInfo: nil, repeats: false)
}
}
private func provideHapticFeedback(for message: Message) {
if #available(iOS 10.0, *), config.isHapticFeedbackEnabled && DeviceType.isPhone {
let generator = UINotificationFeedbackGenerator()
switch message.type! {
case .error:
generator.notificationOccurred(.error)
case .info:
generator.notificationOccurred(.warning)
case .success:
generator.notificationOccurred(.success)
}
}
}
private func resetTimer() {
timer?.invalidate()
timer = nil
}
@objc
private func dismiss() {
resetTimer()
if let message = visibleMessage {
dismissMessage(message)
}
}
private func dismissMessage(_ message: Message) {
dismissMessage(message, fromGesture: false)
}
@objc
private func tap(_ gesture: UITapGestureRecognizer) {
let message = gesture.view as! Message
dismissMessage(message, fromGesture: true)
tapHandler?()
}
private func dismissMessage(_ message: Message, fromGesture: Bool) {
if message.isHit {
return
}
message.isHit = true
UIView.animate(withDuration: SwiftMessageBar.showHideDuration, delay: 0, options: [], animations: {
message.transform = CGAffineTransform(translationX: 0, y: -message.frame.height)
}, completion: { [weak self] _ in
self?.isMessageVisible = false
message.removeFromSuperview()
if fromGesture {
message.callback?()
}
if let messageBar = self , !messageBar.messageQueue.isEmpty {
messageBar.dequeueNextMessage()
} else {
self?.resetTimer()
self?.messageWindow = nil
}
}
)
}
}
private class MessageWindow: UIWindow {
lazy var messageBarController = MessageBarController()
var messageBarView: UIView {
messageBarController.view
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
var hitView = super.hitTest(point, with: event)
if hitView == rootViewController?.view {
hitView = nil
}
return hitView
}
}
private class MessageBarController: UIViewController {
var statusBarStyle: UIStatusBarStyle = .default {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
var statusBarHidden: Bool = false {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
statusBarStyle
}
override var prefersStatusBarHidden: Bool {
statusBarHidden
}
}
| mit | 34e5699b0ea18e2aaff47c564483633b | 33.683146 | 128 | 0.65427 | 5.34974 | false | true | false | false |
googlearchive/science-journal-ios | ScienceJournal/UI/TrialShareSettingsViewController.swift | 1 | 6786 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
import third_party_objective_c_material_components_ios_components_Buttons_Buttons
import third_party_objective_c_material_components_ios_components_ProgressView_ProgressView
import third_party_objective_c_material_components_ios_components_Typography_Typography
/// A view controller for managing trial share settings.
class TrialShareSettingsViewController: ScienceJournalViewController {
private enum Metrics {
static let maxWidth: CGFloat = 414
static let stackSpacing: CGFloat = 14
static let viewInsets = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
static let progressViewHeight: CGFloat = 10
}
/// The state of the share settings view.
///
/// - options: Shows the switch for toggling relative time.
/// - progress: Shows a progress view for the export.
private enum State {
case options
case progress
}
private let titleLabel = UILabel()
private let relativeLabel = UILabel()
private let progressView = MDCProgressView()
private let verticalStack = UIStackView()
private let switchStack = UIStackView()
private let exportType: UserExportType
/// The relative time switch.
let relativeSwitch = UISwitch()
/// The cancel button.
let cancelButton = MDCFlatButton()
/// The share button.
let shareButton = MDCFlatButton()
private var state: State = .options {
didSet {
guard state != oldValue else { return }
switch state {
case .options:
verticalStack.removeArrangedSubview(progressView)
progressView.removeFromSuperview()
verticalStack.insertArrangedSubview(switchStack, at: 1)
shareButton.isEnabled = true
case .progress:
verticalStack.removeArrangedSubview(switchStack)
switchStack.removeFromSuperview()
verticalStack.insertArrangedSubview(progressView, at: 1)
shareButton.isEnabled = false
}
}
}
/// The height required to display the view's content.
private var contentHeight: CGFloat {
let titleHeight =
titleLabel.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
let shareButtonHeight =
shareButton.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
let switchHeight =
relativeSwitch.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize).height
return Metrics.viewInsets.top + Metrics.viewInsets.bottom + titleHeight + shareButtonHeight +
switchHeight + Metrics.stackSpacing * 2
}
/// Designated initializer.
///
/// - Parameters:
/// - analyticsReporter: The analytics reporter.
/// - exportType: The export option type to show.
init(analyticsReporter: AnalyticsReporter, exportType: UserExportType) {
self.exportType = exportType
super.init(analyticsReporter: analyticsReporter)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
// Progress view.
progressView.translatesAutoresizingMaskIntoConstraints = false
// MDCProgressView has no intrinsic content size.
progressView.heightAnchor.constraint(equalToConstant:
Metrics.progressViewHeight).isActive = true
titleLabel.text = String.exportOptionsTitle
titleLabel.font = MDCTypography.titleFont()
titleLabel.translatesAutoresizingMaskIntoConstraints = false
relativeSwitch.translatesAutoresizingMaskIntoConstraints = false
relativeLabel.translatesAutoresizingMaskIntoConstraints = false
relativeLabel.text = String.exportOptionsRelativeTime
relativeLabel.font = MDCTypography.body1Font()
switchStack.addArrangedSubview(relativeSwitch)
switchStack.addArrangedSubview(relativeLabel)
switchStack.spacing = Metrics.stackSpacing
switchStack.translatesAutoresizingMaskIntoConstraints = false
let buttonWrapper = UIView()
buttonWrapper.translatesAutoresizingMaskIntoConstraints = false
buttonWrapper.addSubview(cancelButton)
buttonWrapper.addSubview(shareButton)
cancelButton.setTitle(String.actionCancel, for: .normal)
cancelButton.translatesAutoresizingMaskIntoConstraints = false
let shareButtonTitle: String
switch exportType {
case .share:
shareButtonTitle = String.exportAction
case .saveToFiles:
shareButtonTitle = String.saveToFilesTitle
shareButton.accessibilityHint = String.saveToFilesContentDescription
}
shareButton.setTitle(shareButtonTitle, for: .normal)
shareButton.translatesAutoresizingMaskIntoConstraints = false
shareButton.trailingAnchor.constraint(equalTo: buttonWrapper.trailingAnchor).isActive = true
shareButton.topAnchor.constraint(equalTo: buttonWrapper.topAnchor).isActive = true
shareButton.bottomAnchor.constraint(equalTo: buttonWrapper.bottomAnchor).isActive = true
cancelButton.trailingAnchor.constraint(equalTo: shareButton.leadingAnchor).isActive = true
cancelButton.centerYAnchor.constraint(equalTo: shareButton.centerYAnchor).isActive = true
cancelButton.addTarget(self, action: #selector(cancelButtonPressed), for: .touchUpInside)
verticalStack.addArrangedSubview(titleLabel)
verticalStack.addArrangedSubview(switchStack)
verticalStack.addArrangedSubview(buttonWrapper)
verticalStack.translatesAutoresizingMaskIntoConstraints = false
verticalStack.distribution = .equalSpacing
verticalStack.spacing = Metrics.stackSpacing
verticalStack.axis = .vertical
view.addSubview(verticalStack)
verticalStack.pinToEdgesOfView(view, withInsets: Metrics.viewInsets)
preferredContentSize = CGSize(width: min(Metrics.maxWidth, view.frame.size.width),
height: contentHeight)
}
/// Sets the share settings view to show a progress bar with the given progress.
///
/// - Parameter progress: The progress value to display.
func setProgress(_ progress: Double) {
state = .progress
progressView.progress = Float(progress)
}
@objc private func cancelButtonPressed() {
analyticsReporter.track(.trialExportCancelled)
dismiss(animated: true)
}
}
| apache-2.0 | 978f081295a152d82c7ca22cfeb61bfd | 36.7 | 97 | 0.753168 | 5.326531 | false | false | false | false |
cpuu/OTT | BlueCapKit/Utilities/BCSerialIO.swift | 1 | 2025 | //
// BCSerialIODictionary.swift
// FutureLocation
//
// Created by Troy Stribling on 1/24/16.
// Copyright © 2016 Troy Stribling. All rights reserved.
//
import Foundation
// MARK: Serialize Dictionary Access
public class BCSerialIODictionary<T, U where T: Hashable> {
private var data = [T: U]()
let queue: Queue
init(_ queue: Queue) {
self.queue = queue
}
var values: [U] {
return self.queue.sync { return Array(self.data.values) }
}
var keys: [T] {
return self.queue.sync { return Array(self.data.keys) }
}
var count: Int {
return self.data.count
}
subscript(key: T) -> U? {
get {
return self.queue.sync { return self.data[key] }
}
set {
self.queue.sync { self.data[key] = newValue }
}
}
func removeValueForKey(key: T) {
self.queue.sync { self.data.removeValueForKey(key) }
}
func removeAll() {
self.queue.sync { self.data.removeAll() }
}
}
// MARK: Serialize Array Access
public class BCSerialIOArray<T> {
private var _data = [T]()
let queue: Queue
init(_ queue: Queue) {
self.queue = queue
}
var data: [T] {
get {
return self.queue.sync { return self._data }
}
set {
self.queue.sync { self._data = newValue }
}
}
var first: T? {
return self.queue.sync { return self._data.first }
}
var count: Int {
return self.data.count
}
subscript(i: Int) -> T {
get {
return self.queue.sync { return self._data[i] }
}
set {
self.queue.sync { self._data[i] = newValue }
}
}
func append(value: T) {
self.queue.sync { self._data.append(value) }
}
func removeAtIndex(i: Int) {
self.queue.sync { self._data.removeAtIndex(i) }
}
func map<M>(transform: T -> M) -> [M] {
return self._data.map(transform)
}
}
| mit | 227e69edd6dc9bc70a8254344ee3f6a2 | 19.039604 | 65 | 0.536067 | 3.620751 | false | false | false | false |
KarlWarfel/nutshell-ios | Nutshell/ViewControllers/EventPhotoCollectView.swift | 1 | 7277 | /*
* Copyright (c) 2015, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import UIKit
/// UICollectionView supporting full-view sized photos, with optional page control.
class EventPhotoCollectView: UIControl {
var photoURLs: [String] = []
var photoDisplayMode: UIViewContentMode = .ScaleAspectFit
var imageIndex: Int = 0
var pageControl: UIPageControl?
var delegate: EventPhotoCollectViewDelegate?
private var photoCollectionView: UICollectionView?
private var currentViewHeight: CGFloat = 0.0
func reloadData() {
photoCollectionView?.reloadData()
}
func configurePhotoCollection() {
if photoURLs.count == 0 {
if photoCollectionView != nil {
if let pageControl = pageControl {
pageControl.hidden = true
}
photoCollectionView?.removeFromSuperview()
photoCollectionView = nil
}
return
}
if photoCollectionView != nil {
if currentViewHeight == self.bounds.height {
reloadData()
configurePageControl()
return
}
// size has changed, need to redo...
photoCollectionView?.removeFromSuperview()
photoCollectionView = nil
}
let flow = UICollectionViewFlowLayout()
flow.itemSize = self.bounds.size
flow.scrollDirection = UICollectionViewScrollDirection.Horizontal
photoCollectionView = UICollectionView(frame: self.bounds, collectionViewLayout: flow)
if let photoCollectionView = photoCollectionView {
photoCollectionView.backgroundColor = UIColor.clearColor()
photoCollectionView.showsHorizontalScrollIndicator = false
photoCollectionView.showsVerticalScrollIndicator = false
photoCollectionView.dataSource = self
photoCollectionView.delegate = self
photoCollectionView.pagingEnabled = true
photoCollectionView.registerClass(EventPhotoCollectionCell.self, forCellWithReuseIdentifier: EventPhotoCollectionCell.cellReuseID)
// scroll to current photo...
photoCollectionView.scrollToItemAtIndexPath(NSIndexPath(forRow: imageIndex, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
self.insertSubview(photoCollectionView, atIndex: 0)
if let pageControl = pageControl {
pageControl.hidden = false
self.bringSubviewToFront(pageControl)
}
photoCollectionView.reloadData()
configurePageControl()
}
}
func currentCellIndex() -> NSIndexPath? {
if let collectView = photoCollectionView {
let centerPoint = collectView.center
let pointInCell = CGPoint(x: centerPoint.x + collectView.contentOffset.x, y: centerPoint.y + collectView.contentOffset.y)
return collectView.indexPathForItemAtPoint(pointInCell)
}
return nil
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if let pageControl = pageControl {
if let curIndexPath = currentCellIndex() {
if curIndexPath.row > pageControl.currentPage {
APIConnector.connector().trackMetric("Swiped Left on a Photo (Photo Screen)")
} else if curIndexPath.row < pageControl.currentPage {
APIConnector.connector().trackMetric("Swiped Right on a Photo (Photo Screen)")
}
pageControl.currentPage = curIndexPath.row
}
}
}
private func configurePageControl() {
if let pageControl = pageControl {
pageControl.hidden = photoURLs.count <= 1
pageControl.numberOfPages = photoURLs.count
pageControl.currentPage = imageIndex
}
}
}
class EventPhotoCollectionCell: UICollectionViewCell, UIScrollViewDelegate {
static let cellReuseID = "EventPhotoCollectionCell"
var scrollView: UIScrollView?
var photoView: UIImageView?
var photoUrl = ""
var photoDisplayMode: UIViewContentMode = .ScaleAspectFit
func configureCell(photoUrl: String) {
if (photoView != nil) {
photoView?.removeFromSuperview();
photoView = nil
}
if (scrollView != nil) {
scrollView?.removeFromSuperview()
scrollView = nil
}
self.scrollView = UIScrollView(frame: self.bounds)
self.addSubview(scrollView!)
self.scrollView?.minimumZoomScale = 1.0
self.scrollView?.maximumZoomScale = 4.0
self.scrollView?.delegate = self
self.photoUrl = photoUrl
photoView = UIImageView(frame: self.bounds)
photoView!.contentMode = photoDisplayMode
photoView!.backgroundColor = UIColor.clearColor()
NutUtils.loadImage(photoUrl, imageView: photoView!)
self.scrollView!.addSubview(photoView!)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.photoView
}
}
protocol EventPhotoCollectViewDelegate {
func didSelectItemAtIndexPath(indexPath: NSIndexPath)
}
extension EventPhotoCollectView: UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
delegate?.didSelectItemAtIndexPath(indexPath)
}
}
extension EventPhotoCollectView: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photoURLs.count
}
func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EventPhotoCollectionCell.cellReuseID, forIndexPath: indexPath) as! EventPhotoCollectionCell
// index determines center time...
let photoIndex = indexPath.row
if photoIndex < photoURLs.count {
cell.photoDisplayMode = self.photoDisplayMode
cell.configureCell(photoURLs[photoIndex])
}
return cell
}
}
extension EventPhotoCollectView: UICollectionViewDelegateFlowLayout {
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat
{
return 0.0
}
}
| bsd-2-clause | 4e75d72415fc6bfefa8c26e48c3c9f79 | 36.901042 | 190 | 0.665796 | 6.235647 | false | false | false | false |
stripe/stripe-ios | StripePaymentSheet/StripePaymentSheet/PaymentSheet/Intent.swift | 1 | 7973 | //
// Intent.swift
// StripePaymentSheet
//
// Created by Yuki Tokuhiro on 6/7/21.
// Copyright © 2021 Stripe, Inc. All rights reserved.
//
// This file contains types that abstract over PaymentIntent and SetupIntent for convenience.
//
import Foundation
import UIKit
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
// MARK: - Intent
/// An internal type representing either a PaymentIntent or a SetupIntent
enum Intent {
case paymentIntent(STPPaymentIntent)
case setupIntent(STPSetupIntent)
var livemode: Bool {
switch self {
case .paymentIntent(let pi):
return pi.livemode
case .setupIntent(let si):
return si.livemode
}
}
var clientSecret: String {
switch self {
case .paymentIntent(let pi):
return pi.clientSecret
case .setupIntent(let si):
return si.clientSecret
}
}
var unactivatedPaymentMethodTypes: [STPPaymentMethodType] {
switch self {
case .paymentIntent(let pi):
return pi.unactivatedPaymentMethodTypes
case .setupIntent(let si):
return si.unactivatedPaymentMethodTypes
}
}
/// A sorted list of payment method types supported by the Intent and PaymentSheet, ordered from most recommended to least recommended.
var recommendedPaymentMethodTypes: [STPPaymentMethodType] {
switch self {
case .paymentIntent(let pi):
return pi.orderedPaymentMethodTypes
case .setupIntent(let si):
return si.orderedPaymentMethodTypes
}
}
var isPaymentIntent: Bool {
if case .paymentIntent(_) = self {
return true
}
return false
}
var currency: String? {
switch self {
case .paymentIntent(let pi):
return pi.currency
case .setupIntent:
return nil
}
}
}
// MARK: - IntentClientSecret
/// An internal type representing a PaymentIntent or SetupIntent client secret
enum IntentClientSecret {
/// The [client secret](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-client_secret) of a Stripe PaymentIntent object
case paymentIntent(clientSecret: String)
/// The [client secret](https://stripe.com/docs/api/setup_intents/object#setup_intent_object-client_secret) of a Stripe SetupIntent object
case setupIntent(clientSecret: String)
}
// MARK: - IntentConfirmParams
/// An internal type representing both `STPPaymentIntentParams` and `STPSetupIntentParams`
/// - Note: Assumes you're confirming with a new payment method
class IntentConfirmParams {
let paymentMethodParams: STPPaymentMethodParams
let paymentMethodType: PaymentSheet.PaymentMethodType
/// True if the customer opts to save their payment method for future payments.
/// - Note: PaymentIntent-only
var shouldSavePaymentMethod: Bool = false
/// - Note: PaymentIntent-only
var paymentMethodOptions: STPConfirmPaymentMethodOptions?
var linkedBank: LinkedBank? = nil
var paymentSheetLabel: String {
if let linkedBank = linkedBank,
let last4 = linkedBank.last4 {
return "••••\(last4)"
} else {
return paymentMethodParams.paymentSheetLabel
}
}
func makeIcon(updateImageHandler: DownloadManager.UpdateImageHandler?) -> UIImage {
if let linkedBank = linkedBank,
let bankName = linkedBank.bankName {
return PaymentSheetImageLibrary.bankIcon(for: PaymentSheetImageLibrary.bankIconCode(for: bankName))
} else {
return paymentMethodParams.makeIcon(updateHandler: updateImageHandler)
}
}
convenience init(type: PaymentSheet.PaymentMethodType) {
if let paymentType = type.stpPaymentMethodType {
let params = STPPaymentMethodParams(type: paymentType)
self.init(params:params, type: type)
} else {
let params = STPPaymentMethodParams(type: .unknown)
params.rawTypeString = PaymentSheet.PaymentMethodType.string(from: type)
self.init(params: params, type: type)
}
}
init(params: STPPaymentMethodParams, type: PaymentSheet.PaymentMethodType) {
self.paymentMethodType = type
self.paymentMethodParams = params
}
func makeParams(
paymentIntentClientSecret: String,
configuration: PaymentSheet.Configuration
) -> STPPaymentIntentParams {
let params = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret)
params.paymentMethodParams = paymentMethodParams
let options = paymentMethodOptions ?? STPConfirmPaymentMethodOptions()
options.setSetupFutureUsageIfNecessary(
shouldSavePaymentMethod,
paymentMethodType: paymentMethodType,
customer: configuration.customer
)
params.paymentMethodOptions = options
return params
}
func makeParams(setupIntentClientSecret: String) -> STPSetupIntentConfirmParams {
let params = STPSetupIntentConfirmParams(clientSecret: setupIntentClientSecret)
params.paymentMethodParams = paymentMethodParams
return params
}
func makeDashboardParams(
paymentIntentClientSecret: String,
paymentMethodID: String,
configuration: PaymentSheet.Configuration
) -> STPPaymentIntentParams {
let params = STPPaymentIntentParams(clientSecret: paymentIntentClientSecret)
params.paymentMethodId = paymentMethodID
// Dashboard only supports a specific payment flow today
assert(paymentMethodOptions == nil)
let options = STPConfirmPaymentMethodOptions()
options.setSetupFutureUsageIfNecessary(
shouldSavePaymentMethod,
paymentMethodType: paymentMethodType,
customer: configuration.customer
)
let cardOptions = STPConfirmCardOptions()
cardOptions.additionalAPIParameters["moto"] = true
options.cardOptions = cardOptions
params.paymentMethodOptions = options
return params
}
}
extension STPConfirmPaymentMethodOptions {
/**
Sets `payment_method_options[card][setup_future_usage]`
- Note: PaymentSheet uses this `setup_future_usage` (SFU) value very differently from the top-level one:
We read the top-level SFU to know the merchant’s desired save behavior
We write payment method options SFU to set the customer’s desired save behavior
*/
func setSetupFutureUsageIfNecessary(
_ shouldSave: Bool,
paymentMethodType: STPPaymentMethodType,
customer: PaymentSheet.CustomerConfiguration?
) {
// This property cannot be set if there is no customer.
assert(!(shouldSave && customer == nil))
// Only support card and US bank setup_future_usage in payment_method_options
guard customer != nil && paymentMethodType == .card || paymentMethodType == .USBankAccount
else {
return
}
additionalAPIParameters[STPPaymentMethod.string(from: paymentMethodType)] = [
// We pass an empty string to 'unset' this value. This makes the PaymentIntent inherit the top-level setup_future_usage.
"setup_future_usage": shouldSave ? "off_session" : ""
]
}
func setSetupFutureUsageIfNecessary(
_ shouldSave: Bool,
paymentMethodType: PaymentSheet.PaymentMethodType,
customer: PaymentSheet.CustomerConfiguration?
) {
if let bridgePaymentMethodType = paymentMethodType.stpPaymentMethodType {
setSetupFutureUsageIfNecessary(
shouldSave,
paymentMethodType: bridgePaymentMethodType,
customer: customer
)
}
}
}
| mit | da4cba0da6c8fbae69e868e09b540432 | 33.912281 | 148 | 0.670226 | 5.463281 | false | false | false | false |
carlosypunto/TMDBClient | TMDBClient/Source/TMDBClient.swift | 1 | 4027 | //
// TMDBClient.swift
// TMDBClient
//
// Created by carlos on 17/2/15.
// Copyright (c) 2015 Carlos García. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public enum TMDBAPIService: String {
// MARK: - Configuration
// Documentation: http://docs.themoviedb.apiary.io/#reference/configuration
case Configuration = "configuration"
// MARK: - Movies
// Documentation: http://docs.themoviedb.apiary.io/#reference/movies
case Movie = "movie/{id}"
case MovieAlternativeTitle = "movie/{id}/alternative_titles"
case MovieCasts = "movie/{id}/casts"
case MovieImages = "movie/{id}/images"
case MovieKeywords = "movie/{id}/keywords"
case MovieReleases = "movie/{id}/releases"
case MovieTrailers = "movie/{id}/trailers"
case MovieTranslations = "movie/{id}/translations"
case MovieSimilar = "movie/{id}/similar_movies"
case MovieReviews = "movie/{id}/reviews"
case MovieLists = "movie/{id}/lists"
case MovieChanges = "movie/{id}/changes"
case MovieLatest = "movie/latest"
case MovieUpcoming = "movie/upcoming"
case MovieNowPlaying = "movie/now_playing"
case MoviePopular = "movie/popular"
case MovieTopRated = "movie/top_rated"
// MARK: - People
// Documentation: http://docs.themoviedb.apiary.io/#reference/people
case Person = "person/{id}"
case PersonCredits = "person/{id}/credits"
case PersonImages = "person/{id}/images"
case PersonChanges = "person/{id}/changes"
case PersonPopular = "person/popular"
case PersonLatest = "person/latest"
// MARK: - Companies
// Documentation: http://docs.themoviedb.apiary.io/#reference/companies
case Company = "company/{id}"
case CompanyMovies = "company/{id}/movies"
// MARK: - Genres
// Documentation: http://docs.themoviedb.apiary.io/#reference/genres
case GenreList = "genre/list"
case GenreMovies = "genre/{id}/movies"
// MARK: - Keywords
// Documentation: http://docs.themoviedb.apiary.io/#reference/keywords
case Keyword = "keyword/{id}"
case KeywordMovies = "keyword/{id}/movies"
// MARK: - Search
// Documentation: http://docs.themoviedb.apiary.io/#reference/search
case SearchMovie = "search/movie"
case SearchPerson = "search/person"
case SearchCompany = "search/company"
}
public class TMDBClient {
public var APIKey:String!
public static let sharedInstance = TMDBClient()
private init() {}
public func getRequest(service:TMDBAPIService, withParameters parameters:[String:AnyObject] = [:]) -> Request {
assert(APIKey != nil, "Please, add your APIKey")
var keyParameters = parameters
keyParameters["api_key"] = APIKey
var serviceString = service.rawValue
if serviceString.rangeOfString("{id}", options: NSStringCompareOptions.LiteralSearch, range: nil, locale: nil) != nil {
assert(keyParameters["id"] != nil, "Please, add the id")
let id:AnyObject = keyParameters["id"]!
serviceString = serviceString.stringByReplacingOccurrencesOfString("{id}", withString: "\(id)", options: NSStringCompareOptions.LiteralSearch, range: nil)
}
let request = Alamofire.request(.GET, "http://api.themoviedb.org/3/"+serviceString, parameters: keyParameters)
return request
}
public func callService(service:TMDBAPIService, withParameters parameters:[String:AnyObject] = [:], andResponseCallback callback:(JSON) -> Void) {
let request = getRequest(service, withParameters: parameters)
print(request.request!.URLString)
request.responseJSON { response in
var json: JSON
if let jsonResponse = response.result.value {
json = JSON(jsonResponse)
}
else {
json = JSON.null
}
callback(json)
}
}
}
| mit | a27c6a9b785e80a1b486d1b903b15752 | 33.706897 | 166 | 0.645802 | 4.443709 | false | false | false | false |
VoltDB/app-voltpanel-ios | VoltPanel/HostsViewController.swift | 1 | 2324 | /* This file is part of VoltDB.
* Copyright (C) 2008-2015 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
import UIKit
class HostsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var uiProperties: UITableView!
@IBOutlet weak var uiMessage: UILabel!
let sharedData = SharedData.data
//=== View controller methods
override func viewDidLoad() {
super.viewDidLoad()
self.uiProperties.registerClass(UITableViewCell.self, forCellReuseIdentifier: "propertyCell")
// Register property cell NIB (resource) to allow use in tableView:cellForRowAtIndexPath
let cellNib = UINib(nibName: "PropertyCell", bundle: nil)
self.uiProperties.registerNib(cellNib, forCellReuseIdentifier: "propertyCell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//=== Table view methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.sharedData.hosts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.uiProperties.dequeueReusableCellWithIdentifier("propertyCell") as PropertyCell
cell.uiName.text = "\(indexPath.row+1)"
cell.uiValue.text = self.sharedData.hosts[indexPath.row].name
return cell
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Hosts"
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
}
}
| mit | a775f0cdfc27e81b254909fac9fccc83 | 35.3125 | 109 | 0.728485 | 4.913319 | false | false | false | false |
argent-os/argent-ios | app-ios/MenuChildViewControllerTwo.swift | 1 | 10600 | //
// MenuChildViewControllerTwo.swift
// app-ios
//
// Created by Sinan Ulkuatam on 8/6/16.
// Copyright © 2016 Sinan Ulkuatam. All rights reserved.
//
import Foundation
import XLPagerTabStrip
import KeychainSwift
class MenuChildViewControllerTwo: UIViewController, IndicatorInfoProvider {
var itemInfo: IndicatorInfo = "View"
let btnViewCustomers = UIButton()
let btnViewPlans = UIButton()
let btnViewSubscriptions = UIButton()
init(itemInfo: IndicatorInfo) {
self.itemInfo = itemInfo
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.offWhite()
configureView()
}
func configureView() {
let screen = UIScreen.mainScreen().bounds
let screenWidth = screen.size.width
let screenHeight = screen.size.height
let scrollView = UIScrollView()
scrollView.frame = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight+100)
scrollView.bounces = true
scrollView.alwaysBounceVertical = true
scrollView.scrollEnabled = true
self.view.addSubview(scrollView)
self.loadCustomerList { (customers, err) in
if customers?.count > 99 {
let str1 = adjustAttributedString("VIEW CUSTOMERS (100+)", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.darkBlue(), lineSpacing: 0.0, alignment: .Left)
let str1w = adjustAttributedString("VIEW CUSTOMERS (100+)", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Left)
self.btnViewCustomers.setAttributedTitle(str1, forState: .Normal)
self.btnViewCustomers.setAttributedTitle(str1w, forState: .Highlighted)
} else {
let str1 = adjustAttributedString("VIEW CUSTOMERS (" + String(customers!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.darkBlue(), lineSpacing: 0.0, alignment: .Left)
let str1w = adjustAttributedString("VIEW CUSTOMERS (" + String(customers!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Left)
self.btnViewCustomers.setAttributedTitle(str1, forState: .Normal)
self.btnViewCustomers.setAttributedTitle(str1w, forState: .Highlighted)
}
}
btnViewCustomers.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewCustomers.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewCustomers.contentHorizontalAlignment = .Left
btnViewCustomers.setBackgroundColor(UIColor.oceanBlue(), forState: .Highlighted)
btnViewCustomers.frame = CGRect(x: 15, y: 30, width: screenWidth-30, height: 60)
btnViewCustomers.layer.cornerRadius = 3
btnViewCustomers.layer.masksToBounds = true
btnViewCustomers.layer.borderColor = UIColor.lightBlue().colorWithAlphaComponent(0.2).CGColor
btnViewCustomers.layer.borderWidth = 1
btnViewCustomers.backgroundColor = UIColor.whiteColor()
btnViewCustomers.addTarget(self, action: #selector(viewCustomersButtonSelected(_:)), forControlEvents: .TouchUpInside)
scrollView.addSubview(btnViewCustomers)
scrollView.bringSubviewToFront(btnViewCustomers)
// btnViewCustomers.setImage(UIImage(named: "IconCard"), inFrame: CGRectMake(18, 18, 64, 64), forState: .Normal)
// btnViewCustomers.imageEdgeInsets = UIEdgeInsets(top: 0.0, left: btnViewCustomers.frame.width-20, bottom: 0.0, right: 10.0)
self.loadPlanList("100", starting_after: "") { (plans, err) in
let str2 = adjustAttributedString("VIEW PLANS (" + String(plans!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.darkBlue(), lineSpacing: 0.0, alignment: .Left)
let str2w = adjustAttributedString("VIEW PLANS (" + String(plans!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Left)
self.btnViewPlans.setAttributedTitle(str2, forState: .Normal)
self.btnViewPlans.setAttributedTitle(str2w, forState: .Highlighted)
}
btnViewPlans.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewPlans.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewPlans.contentHorizontalAlignment = .Left
btnViewPlans.setBackgroundColor(UIColor.oceanBlue(), forState: .Highlighted)
btnViewPlans.frame = CGRect(x: 15, y: 100, width: screenWidth-30, height: 60)
btnViewPlans.layer.cornerRadius = 3
btnViewPlans.layer.masksToBounds = true
btnViewPlans.layer.borderColor = UIColor.lightBlue().colorWithAlphaComponent(0.2).CGColor
btnViewPlans.layer.borderWidth = 1
btnViewPlans.backgroundColor = UIColor.whiteColor()
btnViewPlans.addTarget(self, action: #selector(viewPlansButtonSelected(_:)), forControlEvents: .TouchUpInside)
scrollView.addSubview(btnViewPlans)
scrollView.bringSubviewToFront(btnViewPlans)
self.loadSubscriptionList { (subscriptions, err) in
let str3 = adjustAttributedString("VIEW SUBSCRIPTIONS (" + String(subscriptions!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.darkBlue(), lineSpacing: 0.0, alignment: .Left)
let str3w = adjustAttributedString("VIEW SUBSCRIPTIONS (" + String(subscriptions!.count) + ")", spacing: 1, fontName: "SFUIText-Regular", fontSize: 12, fontColor: UIColor.whiteColor(), lineSpacing: 0.0, alignment: .Left)
self.btnViewSubscriptions.setAttributedTitle(str3, forState: .Normal)
self.btnViewSubscriptions.setAttributedTitle(str3w, forState: .Highlighted)
}
btnViewSubscriptions.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewSubscriptions.contentEdgeInsets = UIEdgeInsets(top: 0.0, left: 10.0, bottom: 0.0, right: 0.0)
btnViewSubscriptions.contentHorizontalAlignment = .Left
btnViewSubscriptions.setBackgroundColor(UIColor.oceanBlue(), forState: .Highlighted)
btnViewSubscriptions.frame = CGRect(x: 15, y: 170, width: screenWidth-30, height: 60)
btnViewSubscriptions.layer.cornerRadius = 3
btnViewSubscriptions.layer.masksToBounds = true
btnViewSubscriptions.layer.borderColor = UIColor.lightBlue().colorWithAlphaComponent(0.2).CGColor
btnViewSubscriptions.layer.borderWidth = 1
btnViewSubscriptions.backgroundColor = UIColor.whiteColor()
btnViewSubscriptions.addTarget(self, action: #selector(viewSubscriptionsButtonSelected(_:)), forControlEvents: .TouchUpInside)
scrollView.addSubview(btnViewSubscriptions)
scrollView.bringSubviewToFront(btnViewSubscriptions)
}
func viewCustomersButtonSelected(sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CustomersListTableViewController") as! CustomersListTableViewController
self.presentViewController(vc, animated: true) { }
}
func viewPlansButtonSelected(sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("PlansListTableViewController") as! PlansListTableViewController
self.presentViewController(vc, animated: true) { }
}
func viewSubscriptionsButtonSelected(sender: AnyObject) {
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("SubscriptionsListTableViewController") as! SubscriptionsListTableViewController
self.presentViewController(vc, animated: true) { }
}
// MARK: DATA
// Load user data lists for customer and plan
private func loadCustomerList(completionHandler: ([Customer]?, NSError?) -> ()) {
Customer.getCustomerList("100", starting_after: "", completionHandler: { (customers, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: "Could not load customers \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
print(customers?.count)
completionHandler(customers!, error)
})
}
private func loadPlanList(limit: String, starting_after: String, completionHandler: ([Plan]?, NSError?) -> ()) {
Plan.getPlanList(limit, starting_after: starting_after, completionHandler: { (plans, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: "Could not load plans \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
print(plans?.count)
completionHandler(plans!, error)
})
}
private func loadSubscriptionList(completionHandler: ([Subscription]?, NSError?) -> ()) {
Subscription.getSubscriptionList({ (subscriptions, error) in
if error != nil {
let alert = UIAlertController(title: "Error", message: "Could not load subscriptions \(error?.localizedDescription)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
print(subscriptions?.count)
completionHandler(subscriptions!, error)
})
}
// MARK: - IndicatorInfoProvider
func indicatorInfoForPagerTabStrip(pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
}
| mit | e8154aa44b35253d92ecd2db88771f98 | 57.236264 | 232 | 0.685914 | 5.013718 | false | false | false | false |
jayfour000/finite-state-machines | FiniteStateMachines/Pods/Signals/Signals/Signal.swift | 1 | 11144 | //
// Signal.swift
// Signals
//
// Created by Tuomas Artman on 8/16/2014.
// Copyright (c) 2014 Tuomas Artman. All rights reserved.
//
import Foundation
/// Create instances of `Signal` and assign them to public constants on your class for each event type that your
/// class fires.
final public class Signal<T> {
public typealias SignalCallback = (T) -> Void
/// The number of times the `Signal` has fired.
public private(set) var fireCount: Int = 0
/// Whether or not the `Signal` should retain a reference to the last data it was fired with. Defaults to false.
public var retainLastData: Bool = false {
didSet {
if !retainLastData {
lastDataFired = nil
}
}
}
/// The last data that the `Signal` was fired with. In order for the `Signal` to retain the last fired data, its
/// `retainLastFired`-property needs to be set to true
public private(set) var lastDataFired: T? = nil
/// All the observers of to the `Signal`.
public var observers:[AnyObject] {
get {
return signalListeners.filter {
return $0.observer != nil
}.map {
(signal) -> AnyObject in
return signal.observer!
}
}
}
private var signalListeners = [SignalSubscription<T>]()
/// Initializer.
///
/// - parameter retainLastData: Whether or not the Signal should retain a reference to the last data it was fired
/// with. Defaults to false.
public init(retainLastData: Bool = false) {
self.retainLastData = retainLastData
}
/// Subscribes an observer to the `Signal`.
///
/// - parameter on: The observer that subscribes to the `Signal`. Should the observer be deallocated, the
/// subscription is automatically cancelled.
/// - parameter callback: The closure to invoke whenever the `Signal` fires.
/// - returns: A `SignalSubscription` that can be used to cancel or filter the subscription.
@discardableResult
public func subscribe(on observer: AnyObject, callback: @escaping SignalCallback) -> SignalSubscription<T> {
flushCancelledListeners()
let signalListener = SignalSubscription<T>(observer: observer, callback: callback);
signalListeners.append(signalListener)
return signalListener
}
/// Subscribes an observer to the `Signal`. The subscription is automatically canceled after the `Signal` has
/// fired once.
///
/// - parameter on: The observer that subscribes to the `Signal`. Should the observer be deallocated, the
/// subscription is automatically cancelled.
/// - parameter callback: The closure to invoke when the signal fires for the first time.
@discardableResult
public func subscribeOnce(on observer: AnyObject, callback: @escaping SignalCallback) -> SignalSubscription<T> {
let signalListener = self.subscribe(on: observer, callback: callback)
signalListener.once = true
return signalListener
}
/// Subscribes an observer to the `Signal` and invokes its callback immediately with the last data fired by the
/// `Signal` if it has fired at least once and if the `retainLastData` property has been set to true.
///
/// - parameter on: The observer that subscribes to the `Signal`. Should the observer be deallocated, the
/// subscription is automatically cancelled.
/// - parameter callback: The closure to invoke whenever the `Signal` fires.
@discardableResult
public func subscribePast(on observer: AnyObject, callback: @escaping SignalCallback) -> SignalSubscription<T> {
let signalListener = self.subscribe(on: observer, callback: callback)
if let lastDataFired = lastDataFired {
signalListener.callback(lastDataFired)
}
return signalListener
}
/// Subscribes an observer to the `Signal` and invokes its callback immediately with the last data fired by the
/// `Signal` if it has fired at least once and if the `retainLastData` property has been set to true. If it has
/// not been fired yet, it will continue listening until it fires for the first time.
///
/// - parameter on: The observer that subscribes to the `Signal`. Should the observer be deallocated, the
/// subscription is automatically cancelled.
/// - parameter callback: The closure to invoke whenever the signal fires.
@discardableResult
public func subscribePastOnce(on observer: AnyObject, callback: @escaping SignalCallback) -> SignalSubscription<T> {
let signalListener = self.subscribe(on: observer, callback: callback)
if let lastDataFired = lastDataFired {
signalListener.callback(lastDataFired)
signalListener.cancel()
} else {
signalListener.once = true
}
return signalListener
}
/// Fires the `Singal`.
///
/// - parameter data: The data to fire the `Signal` with.
public func fire(_ data: T) {
fireCount += 1
lastDataFired = retainLastData ? data : nil
flushCancelledListeners()
for signalListener in signalListeners {
if signalListener.filter == nil || signalListener.filter!(data) == true {
_ = signalListener.dispatch(data: data)
}
}
}
/// Cancels all subscriptions for an observer.
///
/// - parameter for: The observer whose subscriptions to cancel
public func cancelSubscription(for observer: AnyObject) {
signalListeners = signalListeners.filter {
if let definiteListener:AnyObject = $0.observer {
return definiteListener !== observer
}
return false
}
}
/// Cancels all subscriptions for the `Signal`.
public func cancelAllSubscriptions() {
signalListeners.removeAll(keepingCapacity: false)
}
/// Clears the last fired data from the `Signal` and resets the fire count.
public func clearLastData() {
lastDataFired = nil
}
// MARK: - Private Interface
private func flushCancelledListeners() {
var removeListeners = false
for signalListener in signalListeners {
if signalListener.observer == nil {
removeListeners = true
}
}
if removeListeners {
signalListeners = signalListeners.filter {
return $0.observer != nil
}
}
}
}
/// A SignalLister represenents an instance and its association with a `Signal`.
final public class SignalSubscription<T> {
public typealias SignalCallback = (T) -> Void
public typealias SignalFilter = (T) -> Bool
// The observer.
weak public var observer: AnyObject?
/// Whether the observer should be removed once it observes the `Signal` firing once. Defaults to false.
public var once = false
fileprivate var queuedData: T?
fileprivate var filter: (SignalFilter)?
fileprivate var callback: SignalCallback
fileprivate var dispatchQueue: DispatchQueue?
private var sampleInterval: TimeInterval?
fileprivate init(observer: AnyObject, callback: @escaping SignalCallback) {
self.observer = observer
self.callback = callback
}
/// Assigns a filter to the `SignalSubscription`. This lets you define conditions under which a observer should actually
/// receive the firing of a `Singal`. The closure that is passed an argument can decide whether the firing of a
/// `Signal` should actually be dispatched to its observer depending on the data fired.
///
/// If the closeure returns true, the observer is informed of the fire. The default implementation always
/// returns `true`.
///
/// - parameter predicate: A closure that can decide whether the `Signal` fire should be dispatched to its observer.
/// - returns: Returns self so you can chain calls.
@discardableResult
public func filter(_ predicate: @escaping SignalFilter) -> SignalSubscription {
self.filter = predicate
return self
}
/// Tells the observer to sample received `Signal` data and only dispatch the latest data once the time interval
/// has elapsed. This is useful if the subscriber wants to throttle the amount of data it receives from the
/// `Singla`.
///
/// - parameter sampleInterval: The number of seconds to delay dispatch.
/// - returns: Returns self so you can chain calls.
@discardableResult
public func sample(every sampleInterval: TimeInterval) -> SignalSubscription {
self.sampleInterval = sampleInterval
return self
}
/// Assigns a dispatch queue to the `SignalSubscription`. The queue is used for scheduling the observer calls. If not
/// nil, the callback is fired asynchronously on the specified queue. Otherwise, the block is run synchronously
/// on the posting thread, which is its default behaviour.
///
/// - parameter queue: A queue for performing the observer's calls.
/// - returns: Returns self so you can chain calls.
@discardableResult
public func dispatch(onQueue queue: DispatchQueue) -> SignalSubscription {
self.dispatchQueue = queue
return self
}
/// Cancels the observer. This will cancelSubscription the listening object from the `Signal`.
public func cancel() {
self.observer = nil
}
// MARK: - Private Interface
fileprivate func dispatch(data: T) -> Bool {
guard observer != nil else {
return false
}
if once {
observer = nil
}
if let sampleInterval = sampleInterval {
if queuedData != nil {
queuedData = data
} else {
queuedData = data
let block = { [weak self] () -> Void in
if let definiteSelf = self {
let data = definiteSelf.queuedData!
definiteSelf.queuedData = nil
if definiteSelf.observer != nil {
definiteSelf.callback(data)
}
}
}
let dispatchQueue = self.dispatchQueue ?? DispatchQueue.main
let deadline = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(sampleInterval * 1000))
dispatchQueue.asyncAfter(deadline: deadline, execute: block)
}
} else {
if let queue = self.dispatchQueue {
queue.async {
self.callback(data)
}
} else {
callback(data)
}
}
return observer != nil
}
}
infix operator =>
/// Helper operator to fire signal data.
public func =><T> (signal: Signal<T>, data: T) -> Void {
signal.fire(data)
}
| mit | 1954edd603db776708e0cebf1575e9aa | 37.965035 | 124 | 0.629666 | 5.256604 | false | false | false | false |
EgeTart/MedicineDMW | DWM/EnterpriseController.swift | 1 | 6252 | //
// EnterpriseController.swift
// DWM
//
// Created by MacBook on 9/26/15.
// Copyright © 2015 EgeTart. All rights reserved.
//
import UIKit
class EnterpriseController: UIViewController {
@IBOutlet weak var enterpriseTableView: UITableView!
let detailController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("detailController")
let MeetingController = UIStoryboard.init(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("MeetingController")
var expandState = false
var rowsOfThirdSection = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
enterpriseTableView.registerNib(UINib(nibName: "optionCell", bundle: nil), forCellReuseIdentifier: "optionCell")
enterpriseTableView.registerNib(UINib(nibName: "EnterpriseHeaderView", bundle: nil), forHeaderFooterViewReuseIdentifier: "headerView")
let tabelFootView = UIView(frame: CGRect(x: 0, y: 0, width: enterpriseTableView.frame.width, height: 1000.0))
tabelFootView.backgroundColor = UIColor(red: 248.0 / 255.0, green: 248.0 / 255.0, blue: 248.0 / 255.0, alpha: 1)
enterpriseTableView.tableFooterView = tabelFootView
enterpriseTableView.scrollEnabled = false
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBarHidden = false
self.navigationController?.navigationBar.backItem?.title = ""
}
}
extension EnterpriseController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 1
case 1:
return 3
case 2:
return rowsOfThirdSection
default:
break
}
return 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
switch indexPath.section {
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("enterpriseCell", forIndexPath: indexPath)
let imageView = cell.viewWithTag(101) as! UIImageView
imageView.layer.borderColor = UIColor(red: 204.0 / 255.0, green: 204.0 / 255.0, blue: 204.0 / 255.0, alpha: 1.0).CGColor
imageView.layer.borderWidth = 0.5
let button = cell.viewWithTag(103) as! UIButton
button.layer.cornerRadius = 3
button.clipsToBounds = true
return cell
case 1:
let cell = tableView.dequeueReusableCellWithIdentifier("optionCell", forIndexPath: indexPath) as! optionCell
switch indexPath.row {
case 0:
cell.typeImage.image = UIImage(named: "medicine_red")
cell.label.text = "药品"
case 1:
cell.typeImage.image = UIImage(named: "video")
cell.label.text = "医药视频"
case 2:
cell.typeImage.image = UIImage(named: "meeting")
cell.label.text = "会议视频"
default:
break
}
return cell
case 2:
let cell = tableView.dequeueReusableCellWithIdentifier("consultCell", forIndexPath: indexPath)
if indexPath.row == 1 {
let wayLabel = cell.viewWithTag(201) as! UILabel
let consultLabel = cell.viewWithTag(202) as! UILabel
wayLabel.text = "邮箱:"
consultLabel.text = "[email protected]"
}
return cell
default:
break
}
return UITableViewCell()
}
}
extension EnterpriseController: UITableViewDelegate {
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.section == 0 {
return 110
}
return 44
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if section == 2 {
let headerView = tableView.dequeueReusableHeaderFooterViewWithIdentifier("headerView") as! EnterpriseHeaderView
headerView.controlButton.addTarget(self, action: "changeExpandState:", forControlEvents: UIControlEvents.TouchUpInside)
return headerView
}
return nil
}
func changeExpandState(button: UIButton) {
if !expandState {
rowsOfThirdSection = 2
button.setImage(UIImage(named: "up"), forState: UIControlState.Normal)
}
else {
rowsOfThirdSection = 0
button.setImage(UIImage(named: "down"), forState: UIControlState.Normal)
}
enterpriseTableView.reloadData()
expandState = !expandState
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if section == 2 {
return 44
}
return 0
}
func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 0
}
return 8
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 && indexPath.row == 0 {
self.navigationController?.pushViewController(detailController, animated: true)
} else if indexPath.section == 1 && indexPath.row == 1 {
self.performSegueWithIdentifier("meeting", sender: self)
} else if indexPath.section == 1 && indexPath.row == 2 {
self.navigationController?.pushViewController(MeetingController, animated: true)
}
}
}
| mit | 106e5176288c6e391220b260c2eabcca | 31.264249 | 142 | 0.597559 | 5.476693 | false | false | false | false |
cnoon/swift-compiler-crashes | crashes-duplicates/05770-swift-sourcemanager-getmessage.swift | 11 | 2522 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f: T>: BooleanType, A {
struct S<T {
var d where T : a {
case c<d = "
case c<T where g
class a {
protocol A {
protocol P {
return "
let f = {
class
struct A {
typealias e == {
println() -> U)
func a
typealias e {
func f: c<T>
struct S<T {
class func a
class func g: T: NSObject {
let t: T>: BooleanType, A {
typealias e {
struct A {
{
func i: P
func i: e == {
let f = [Void{
let t: e : NSObject {
func g
return "\() -> () {
case c<d where g
struct S<T>: e == {
protocol A {
struct S<T: BooleanType, A {
case c,
func g<d where T : Int -> () -> () {
protocol A {
typealias e == [Void{
class a {
typealias e : a {
let t: c {
{
struct Q<d = {
}
func g
func i: BooleanType, A {
let t: a {
}
var d = {
protocol A {
return "
struct Q<d = "[Void{
let t: P
}
class
protocol A {
let f = {
let f = ""
class c,
case c<T : a {
class func g: NSObject {
typealias e {
func i() {
println(f: BooleanType, A {
}
let t: BooleanType, A {
struct A {
struct A {
protocol P {
class b
struct A {
}
}
struct S<T where T : BooleanType, A {
let t: a {
class func f: NSObject {
typealias e {
struct A : b: C {
let f = [Void{
class a<T where g<d = "
func f: P
protocol A {
}
println(f: a {
}
println() -> () {
}
let t: e : Int -> () -> () -> (f: C {
var d where T where T : C {
struct Q<T>: e
struct A : P
}
println(f: a {
{
let t: T: a {
func a<T where g<T : b: T: e {
case c,
}
class
return ""
func a
func g<T: e == "[1)
protocol A {
protocol A {
class c<d = [1)"[1)"
typealias e {
class a {
return "\(f: a {
class
class a {
class
case c,
struct S<T>
}
let t: a {
typealias e : BooleanType, A {
typealias e : BooleanType, A : c {
protocol P {
let t: BooleanType, A : T>: T>: e
}
}
}
typealias e == "
class c<T>
protocol A {
func f: c<T>: C {
func f: Int -> U)"
class a
typealias e : e : b
class b: a {
struct A : b: b
class
func a
class a
return "[1)
let f = [Void{
class a
return "
class a
}
case c,
func a<T {
class a {
var d = "
class func i: Int -> U)"
}
}
var d where T where T {
func f: BooleanType, A : T>
class b
}
class func g
func g: e : e : e
return "[1)"
typealias e {
}
class
return ""
var d where g
var d where T where g
class b: NSObject {
func i: C {
}
class a<d = {
let t: C {
}
class b: BooleanType, A : C {
struct Q<T where g<T>: NSObject {
class func f: b: c,
typealias e == [1)
class
var d where T where g: e : T: Int -> U)
println(f: c<T : NSObject {
}
| mit | ffdd48980e5b3c66061a0189889ed49d | 13.168539 | 87 | 0.599128 | 2.560406 | false | false | false | false |
brentdax/swift | stdlib/public/SDK/Foundation/Notification.swift | 6 | 4739 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
/**
`Notification` encapsulates information broadcast to observers via a `NotificationCenter`.
*/
public struct Notification : ReferenceConvertible, Equatable, Hashable {
public typealias ReferenceType = NSNotification
/// A tag identifying the notification.
public var name: Name
/// An object that the poster wishes to send to observers.
///
/// Typically this is the object that posted the notification.
public var object: Any?
/// Storage for values or objects related to this notification.
public var userInfo: [AnyHashable : Any]?
/// Initialize a new `Notification`.
///
/// The default value for `userInfo` is nil.
public init(name: Name, object: Any? = nil, userInfo: [AnyHashable : Any]? = nil) {
self.name = name
self.object = object
self.userInfo = userInfo
}
public var hashValue: Int {
return name.rawValue.hash
}
public var description: String {
return "name = \(name.rawValue), object = \(String(describing: object)), userInfo = \(String(describing: userInfo))"
}
public var debugDescription: String {
return description
}
// FIXME: Handle directly via API Notes
public typealias Name = NSNotification.Name
/// Compare two notifications for equality.
public static func ==(lhs: Notification, rhs: Notification) -> Bool {
if lhs.name.rawValue != rhs.name.rawValue {
return false
}
if let lhsObj = lhs.object {
if let rhsObj = rhs.object {
if lhsObj as AnyObject !== rhsObj as AnyObject {
return false
}
} else {
return false
}
} else if rhs.object != nil {
return false
}
if lhs.userInfo != nil {
if rhs.userInfo != nil {
// user info must be compared in the object form since the userInfo in swift is not comparable
return lhs._bridgeToObjectiveC() == rhs._bridgeToObjectiveC()
} else {
return false
}
} else if rhs.userInfo != nil {
return false
}
return true
}
}
extension Notification: CustomReflectable {
public var customMirror: Mirror {
var children: [(label: String?, value: Any)] = []
children.append((label: "name", value: self.name.rawValue))
if let o = self.object {
children.append((label: "object", value: o))
}
if let u = self.userInfo {
children.append((label: "userInfo", value: u))
}
let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.class)
return m
}
}
extension Notification : _ObjectiveCBridgeable {
public static func _getObjectiveCType() -> Any.Type {
return NSNotification.self
}
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSNotification {
return NSNotification(name: name, object: object, userInfo: userInfo)
}
public static func _forceBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge type")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSNotification, result: inout Notification?) -> Bool {
result = Notification(name: x.name, object: x.object, userInfo: x.userInfo)
return true
}
@_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSNotification?) -> Notification {
guard let src = source else { return Notification(name: Notification.Name("")) }
return Notification(name: src.name, object: src.object, userInfo: src.userInfo)
}
}
extension NSNotification : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Notification)
}
}
| apache-2.0 | f5e2d01e3fd725838417b0029abe3442 | 33.591241 | 124 | 0.607301 | 5.145494 | false | false | false | false |
huangshuai-IOT/SScheduleView | Example/SScheduleView_Example/CourseModel.swift | 1 | 1238 | //
// CourseModel.swift
// SScheduleView_Example
//
// Created by 黄帅 on 2017/4/28.
// Copyright © 2017年 huangshuai. All rights reserved.
//
import UIKit
import SScheduleView
class CourseModel: NSObject {
// 周几
var dayNum = 0
// 第几节课
var jieNum = 0
// 课程长度
var courseSpan = 0
// 课程名称
var courseName = ""
// 课程地点
var classRoom = ""
// 课程颜色,使用HexString方便保存
var colorString = ""
}
extension CourseModel:SScheduleViewModelProtocol {
// 周几的课 从1开始
func getDay() -> Int {
return dayNum
}
// 第几节课 从1开始
func getJieci() -> Int {
return jieNum
}
//一节课的持续时间
func getSpan() -> Int {
return courseSpan
}
func getCourseName() -> String {
return courseName
}
func getClassRoom() -> String {
return classRoom
}
// 课程的自定义颜色,若nil则采用随机颜色
func getBackColor() -> UIColor? {
if colorString != "" {
return UIColor(hexString: colorString)
} else {
return nil
}
}
}
| mit | ca866955736dc1ca364552cbde02e2c9 | 15.876923 | 54 | 0.53783 | 3.8223 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.