repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
macfeteria/JKNotificationPanel
|
Pod/Classes/JKSubtitleView.swift
|
1
|
5343
|
////
//// JKSubtitleView.swift
//// Pods
////
//// Created by Ter on 9/24/16.
////
////
//
import UIKit
open class JKSubtitleView: UIView {
private let verticalSpace:CGFloat = 8
private let horizontalSpace:CGFloat = 8
private let iconSize:CGFloat = 26
private let titleLableHeight:CGFloat = 22
private let subtitleLabelHeight:CGFloat = 18
var imageIcon:UIImageView!
var textLabel:UILabel!
var subtitleLabel:UILabel!
var baseView:UIView!
override init (frame : CGRect) {
super.init(frame : frame)
imageIcon = UIImageView(frame: CGRect(x: verticalSpace, y: horizontalSpace, width: iconSize, height: iconSize))
imageIcon.backgroundColor = UIColor.clear
let textLabelX = verticalSpace + iconSize + verticalSpace
textLabel = UILabel(frame: CGRect(x: textLabelX, y: 0, width: frame.width - textLabelX - horizontalSpace, height: titleLableHeight))
textLabel.isUserInteractionEnabled = true
textLabel.textColor = UIColor.white
let subtitleLableY = textLabel.frame.origin.y + titleLableHeight
subtitleLabel = UILabel(frame: CGRect(x: textLabelX, y: subtitleLableY, width: frame.width - textLabelX - horizontalSpace, height: subtitleLabelHeight))
subtitleLabel.font = UIFont.systemFont(ofSize: 12)
subtitleLabel.isUserInteractionEnabled = true
subtitleLabel.textColor = UIColor.white
baseView = UIView(frame: frame)
baseView.backgroundColor = UIColor(red: 35.0/255.0, green: 160.0/255.0, blue: 73.0/255.0, alpha: 1)
baseView.addSubview(imageIcon)
baseView.addSubview(textLabel)
baseView.addSubview(subtitleLabel)
self.addSubview(baseView)
}
open func transitionTo(size:CGSize) {
let x = verticalSpace + iconSize + verticalSpace
self.frame.size = CGSize(width: size.width, height: self.frame.height)
textLabel.frame.size = CGSize(width: size.width - x - horizontalSpace, height: titleLableHeight)
subtitleLabel.frame.size = CGSize(width: size.width - x - horizontalSpace, height: subtitleLabelHeight)
baseView.frame.size = CGSize(width: size.width, height: baseView.frame.height)
// adjust text label
self.setTitle(textLabel.text)
self.setMessage(subtitleLabel.text)
}
open func setImage(_ icon:UIImage) {
imageIcon.image = icon
}
open func setColor(_ color:UIColor) {
self.baseView.backgroundColor = color
}
open func setTitle(_ text:String?) {
guard (text != nil) else { return }
textLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
textLabel.text = text
textLabel.numberOfLines = 0
textLabel.sizeToFit()
textLabel.frame.origin.y = 2
let height = textLabel.frame.height
var frameHeight = (verticalSpace * 2) + height
if frameHeight < 44 { frameHeight = 44 }
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: frameHeight)
baseView.frame = self.frame
}
open func setMessage(_ text:String?) {
guard (text != nil) else { return }
// Subtitle
subtitleLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
subtitleLabel.text = text
subtitleLabel.numberOfLines = 0
subtitleLabel.sizeToFit()
subtitleLabel.frame.origin.y = textLabel.frame.origin.y + textLabel.frame.height
let subHeight = subtitleLabel.frame.height + 2
let subFrameHeight = (textLabel.frame.origin.y + textLabel.frame.height) + subHeight
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: self.frame.width, height: subFrameHeight)
baseView.frame = self.frame
}
func loadImageBundle(named imageName:String) ->UIImage? {
let podBundle = Bundle(for: self.classForCoder)
if let bundleURL = podBundle.url(forResource: "JKNotificationPanel", withExtension: "bundle") {
let imageBundel = Bundle(url:bundleURL )
let image = UIImage(named: imageName, in: imageBundel, compatibleWith: nil)
return image
}
return nil
}
open func setPanelStatus(_ status:JKStatus) {
switch (status) {
case .success:
imageIcon.image = loadImageBundle(named: "success-icon")
textLabel.text = "Success"
baseView.backgroundColor = UIColor(red: 35.0/255.0, green: 160.0/255.0, blue: 73.0/255.0, alpha: 1)
case .warning:
imageIcon.image = loadImageBundle(named: "warning-icon")
textLabel.text = "Warning"
baseView.backgroundColor = UIColor(red: 249.0/255.0, green: 169.0/255.0, blue: 69.0/255.0, alpha: 1)
case .failed:
imageIcon.image = loadImageBundle(named: "fail-icon")
textLabel.text = "Failed"
baseView.backgroundColor = UIColor(red: 67.0/255.0, green: 69.0/255.0, blue: 80.0/255.0, alpha: 1)
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
cnoon/swift-compiler-crashes
|
crashes-duplicates/07275-swift-typebase-getcanonicaltype.swift
|
11
|
264
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let t: NSObject {
struct B<T where T where g: a {
var b = a
protocol a : e {
typealias e : T w
|
mit
|
qianqian2/ocStudy1
|
EventView/EventView/detailViewController.swift
|
1
|
861
|
//
// detailViewController.swift
// EventView
//
// Created by arang on 16/12/20.
// Copyright © 2016年 arang. All rights reserved.
//
import UIKit
class detailViewController: 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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
cnoon/swift-compiler-crashes
|
fixed/25583-swift-substitutedtype-get.swift
|
7
|
239
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if{class A<A{class d{class A:A class j:A struct B<T where f:N{class B
|
mit
|
laszlokorte/reform-swift
|
ReformExpression/ReformExpression/ExpressionParser.swift
|
1
|
11412
|
//
// MyParser.swift
// ExpressionEngine
//
// Created by Laszlo Korte on 08.08.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
import Foundation
struct BinaryOperatorDefinition {
let op : BinaryOperator.Type
let precedence : Precedence
let associativity : Associativity
init(_ op: BinaryOperator.Type, _ precedence : Precedence, _ assoc : Associativity) {
self.op = op
self.precedence = precedence
self.associativity = assoc
}
}
struct UnaryOperatorDefinition {
let op : UnaryOperator.Type
let precedence : Precedence
let associativity : Associativity
init(_ op: UnaryOperator.Type, _ precedence : Precedence, _ assoc : Associativity) {
self.op = op
self.precedence = precedence
self.associativity = assoc
}
}
final public class ExpressionParserDelegate : ShuntingYardDelegate {
public typealias NodeType = Expression
private let sheet : Sheet
public init(sheet: Sheet) {
self.sheet = sheet
}
let binaryOperators : [String : BinaryOperatorDefinition] = [
"^" : BinaryOperatorDefinition(BinaryExponentiation.self, Precedence(50), .right),
"*" : BinaryOperatorDefinition(BinaryMultiplication.self, Precedence(40), .left),
"/" : BinaryOperatorDefinition(BinaryDivision.self, Precedence(40), .left),
"%" : BinaryOperatorDefinition(BinaryModulo.self, Precedence(40), .left),
"+" : BinaryOperatorDefinition(BinaryAddition.self, Precedence(30), .left),
"-" : BinaryOperatorDefinition(BinarySubtraction.self, Precedence(30), .left),
"<": BinaryOperatorDefinition(LessThanRelation.self, Precedence(20), .left),
"<=": BinaryOperatorDefinition(LessThanOrEqualRelation.self, Precedence(20), .left),
">": BinaryOperatorDefinition(GreaterThanRelation.self, Precedence(20), .left),
">=": BinaryOperatorDefinition(GreaterThanOrEqualRelation.self, Precedence(20), .left),
"==": BinaryOperatorDefinition(StrictEqualRelation.self, Precedence(10), .left),
"!=": BinaryOperatorDefinition(StrictNotEqualRelation.self, Precedence(10), .left),
"&&": BinaryOperatorDefinition(BinaryLogicAnd.self, Precedence(8), .left),
"||": BinaryOperatorDefinition(BinaryLogicOr.self, Precedence(5), .left),
]
let unaryOperators : [String : UnaryOperatorDefinition] = [
"+" : UnaryOperatorDefinition(UnaryPlus.self, Precedence(45), .left),
"-" : UnaryOperatorDefinition(UnaryMinus.self, Precedence(45), .left),
"~" : UnaryOperatorDefinition(UnaryLogicNegation.self, Precedence(45), .left),
]
let constants : [String : Value] = [
"PI" : Value.doubleValue(value: Double.pi),
"E" : Value.doubleValue(value: M_E),
]
let functions : [String : Function.Type] = [
"sin" : Sinus.self,
"asin" : ArcusSinus.self,
"cos" : Cosinus.self,
"acos" : ArcusCosinus.self,
"tan" : Tangens.self,
"atan" : ArcusTangens.self,
"atan2" : ArcusTangens.self,
"exp" : Exponential.self,
"pow" : Power.self,
"ln" : NaturalLogarithm.self,
"log10" : DecimalLogarithm.self,
"log2" : BinaryLogarithm.self,
"sqrt" : SquareRoot.self,
"round" : Round.self,
"ceil" : Ceil.self,
"floor" : Floor.self,
"abs" : Absolute.self,
"max" : Maximum.self,
"min" : Minimum.self,
"count" : Count.self,
"avg" : Average.self,
"sum" : Sum.self,
"random" : Random.self,
"int" : IntCast.self,
"double" : DoubleCast.self,
"bool" : BoolCast.self,
"string" : StringCast.self,
"rgb" : RGBConstructor.self,
"rgba" : RGBAConstructor.self
]
let matchingPairs : [String:String] = ["(":")"]
public func isMatchingPair(_ left : Token<ShuntingYardTokenType>, right : Token<ShuntingYardTokenType>) -> Bool {
return matchingPairs[left.value] == right.value
}
public func variableTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression {
if let definition = sheet.definitionWithName(token.value) {
return .reference(id: definition.id)
} else {
throw ShuntingYardError.unexpectedToken(token: token, message: "unknown identifier")
}
}
public func constantTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression {
if let val = constants[token.value] {
return Expression.namedConstant(token.value, val)
} else {
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
}
public func emptyNode() throws -> Expression {
return Expression.constant(.intValue(value: 0))
}
public func unaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, operand : Expression) throws -> Expression {
if let o = unaryOperators[op.value] {
return Expression.unary(o.op.init(), operand)
} else {
throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.unary)
}
}
public func binaryOperatorToNode(_ op : Token<ShuntingYardTokenType>, leftHand : Expression, rightHand : Expression) throws -> Expression {
if let o = binaryOperators[op.value] {
return Expression.binary(o.op.init(), leftHand, rightHand)
} else {
throw ShuntingYardError.unknownOperator(token: op, arity: OperatorArity.binary)
}
}
public func functionTokenToNode(_ function : Token<ShuntingYardTokenType>, args : [Expression]) throws -> Expression {
if let f = functions[function.value] {
let arity = f.arity
switch(arity) {
case .fix(let count) where count == args.count:
return .call(f.init(), args)
case .variadic where args.count > 0:
return .call(f.init(), args)
default:
throw ShuntingYardError.unknownFunction(token: function, parameters: args.count)
}
} else {
throw ShuntingYardError.unknownFunction(token: function, parameters: args.count)
}
}
public func hasBinaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool {
return binaryOperators.keys.contains(op.value)
}
public func hasUnaryOperator(_ op : Token<ShuntingYardTokenType>) -> Bool {
return unaryOperators.keys.contains(op.value)
}
public func hasFunctionOfName(_ function : Token<ShuntingYardTokenType>) -> Bool {
return functions.keys.contains(function.value)
}
public func hasConstantOfName(_ token : Token<ShuntingYardTokenType>) -> Bool {
return constants.keys.contains(token.value)
}
public func literalTokenToNode(_ token : Token<ShuntingYardTokenType>) throws -> Expression {
if token.value == "true" {
return Expression.constant(Value.boolValue(value: true))
} else if token.value == "false" {
return Expression.constant(Value.boolValue(value: false))
} else if let range = token.value.range(of: "\\A\"([^\"]*)\"\\Z", options: .regularExpression) {
let string = token.value[range]
let subString = string[string.index(after: string.startIndex)..<string.index(before: string.endIndex)]
return Expression.constant(Value.stringValue(value: String(subString)))
} else if let range = token.value.range(of: "\\A#[0-9a-z]{6}\\Z", options: .regularExpression) {
let string = String(token.value[range].dropFirst())
let digits = string.utf16.map(parseHexDigits)
if let r1 = digits[0],
let r2 = digits[1],
let g1 = digits[2],
let g2 = digits[3],
let b1 = digits[4],
let b2 = digits[5] {
let r = r1<<4 | r2
let g = g1<<4 | g2
let b = b1<<4 | b2
return Expression.constant(Value.colorValue(r: r, g:g, b: b, a: 255))
} else {
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
} else if let range = token.value.range(of: "\\A#[0-9a-z]{8}\\Z", options: .regularExpression) {
let string = String(token.value[range].dropFirst())
let digits = string.utf16.map(parseHexDigits)
if let r1 = digits[0],
let r2 = digits[1],
let g1 = digits[2],
let g2 = digits[3],
let b1 = digits[4],
let b2 = digits[5],
let a1 = digits[6],
let a2 = digits[7] {
let r = r1<<4 | r2
let g = g1<<4 | g2
let b = b1<<4 | b2
let a = a1<<4 | a2
return Expression.constant(Value.colorValue(r: r, g:g, b: b, a: a))
} else {
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
} else if let int = Int(token.value) {
return Expression.constant(Value.intValue(value: int))
} else if let double = Double(token.value) {
return Expression.constant(Value.doubleValue(value: double))
} else {
throw ShuntingYardError.unexpectedToken(token: token, message: "")
}
}
private func parseHexDigits(_ char: UTF16.CodeUnit) -> UInt8? {
let zero = 0x30
let nine = 0x39
let lowerA = 0x61
let lowerF = 0x66
let upperA = 0x41
let upperF = 0x46
let value = Int(char)
switch (value) {
case zero...nine:
return UInt8(value - zero)
case lowerA...lowerF:
return UInt8(value - lowerA + 10)
case upperA...upperF:
return UInt8(value - upperA + 10)
default:
return nil
}
}
public func assocOfOperator(_ token : Token<ShuntingYardTokenType>) -> Associativity? {
return binaryOperators[token.value]?.associativity
}
public func precedenceOfOperator(_ token : Token<ShuntingYardTokenType>, unary : Bool) -> Precedence? {
if(unary) {
return unaryOperators[token.value]?.precedence
} else {
return binaryOperators[token.value]?.precedence
}
}
func uniqueNameFor(_ wantedName: String, definition: Definition? = nil) -> String {
var testName = wantedName
var postfix = 0
var otherDef = sheet.definitionWithName(testName)
while (otherDef?.id != nil && otherDef?.id != definition?.id || functions.keys.contains(testName) || constants.keys.contains(testName))
{
postfix += 1
testName = "\(wantedName)\(postfix)"
otherDef = sheet.definitionWithName(testName)
}
if (postfix > 0)
{
return testName
}
else
{
return wantedName
}
}
}
|
mit
|
sundance2000/LegoDimensionsCalculator
|
LegoDimensionsCalculator/Figure.swift
|
1
|
713
|
//
// Figure.swift
// LegoDimensionsCalculator
//
// Created by Christian Oberdörfer on 04.05.16.
// Copyright © 2016 sundance. All rights reserved.
//
class Figure: CustomStringConvertible, Hashable {
let name: String
/// All abilities of all versions of the figure
var abilities: Set<Ability>
var description: String {
get {
return self.name
}
}
var hashValue: Int {
get {
return self.name.hashValue
}
}
init(let name: String, abilities: Set<Ability>) {
self.name = name
self.abilities = abilities
}
}
func ==(lhs: Figure, rhs: Figure) -> Bool {
return lhs.name == rhs.name
}
|
mit
|
cnoon/swift-compiler-crashes
|
crashes-duplicates/05377-swift-sourcemanager-getmessage.swift
|
11
|
290
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
? {
class c : j { func a
enum S<T where T: j { func j>
func j
{
if true {
protocol A : a {
struct B<T: a {
class
case c,
|
mit
|
xu6148152/binea_project_for_ios
|
Trax MapKit Swift 1.2/Trax/GPXViewController.swift
|
1
|
4388
|
//
// GPXViewController.swift
// Trax
//
// Created by CS193p Instructor.
// Copyright (c) 2015 Stanford University. All rights reserved.
//
import UIKit
import MapKit
class GPXViewController: UIViewController, MKMapViewDelegate
{
// MARK: - Outlets
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.mapType = .Satellite
mapView.delegate = self
}
}
// MARK: - Public API
var gpxURL: NSURL? {
didSet {
clearWaypoints()
if let url = gpxURL {
GPX.parse(url) {
if let gpx = $0 {
self.handleWaypoints(gpx.waypoints)
}
}
}
}
}
// MARK: - Waypoints
private func clearWaypoints() {
if mapView?.annotations != nil { mapView.removeAnnotations(mapView.annotations as! [MKAnnotation]) }
}
private func handleWaypoints(waypoints: [GPX.Waypoint]) {
mapView.addAnnotations(waypoints)
mapView.showAnnotations(waypoints, animated: true)
}
// MARK: - MKMapViewDelegate
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
var view = mapView.dequeueReusableAnnotationViewWithIdentifier(Constants.AnnotationViewReuseIdentifier)
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: Constants.AnnotationViewReuseIdentifier)
view.canShowCallout = true
} else {
view.annotation = annotation
}
view.leftCalloutAccessoryView = nil
view.rightCalloutAccessoryView = nil
if let waypoint = annotation as? GPX.Waypoint {
if waypoint.thumbnailURL != nil {
view.leftCalloutAccessoryView = UIImageView(frame: Constants.LeftCalloutFrame)
}
if waypoint.imageURL != nil {
view.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton
}
}
return view
}
func mapView(mapView: MKMapView!, didSelectAnnotationView view: MKAnnotationView!) {
if let waypoint = view.annotation as? GPX.Waypoint {
if let thumbnailImageView = view.leftCalloutAccessoryView as? UIImageView {
if let imageData = NSData(contentsOfURL: waypoint.thumbnailURL!) { // blocks main thread!
if let image = UIImage(data: imageData) {
thumbnailImageView.image = image
}
}
}
}
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
performSegueWithIdentifier(Constants.ShowImageSegue, sender: view)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constants.ShowImageSegue {
if let waypoint = (sender as? MKAnnotationView)?.annotation as? GPX.Waypoint {
if let ivc = segue.destinationViewController as? ImageViewController {
ivc.imageURL = waypoint.imageURL
ivc.title = waypoint.name
}
}
}
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// sign up to hear about GPX files arriving
let center = NSNotificationCenter.defaultCenter()
let queue = NSOperationQueue.mainQueue()
let appDelegate = UIApplication.sharedApplication().delegate
center.addObserverForName(GPXURL.Notification, object: appDelegate, queue: queue) { notification in
if let url = notification?.userInfo?[GPXURL.Key] as? NSURL {
self.gpxURL = url
}
}
// gpxURL = NSURL(string: "http://cs193p.stanford.edu/Vacation.gpx") // for demo/debug/testing
}
// MARK: - Constants
private struct Constants {
static let LeftCalloutFrame = CGRect(x: 0, y: 0, width: 59, height: 59)
static let AnnotationViewReuseIdentifier = "waypoint"
static let ShowImageSegue = "Show Image"
}
}
|
mit
|
xeo-it/contacts-sample
|
totvs-contacts-test/Services/SpinerLayer.swift
|
6
|
1589
|
import UIKit
class SpinerLayer: CAShapeLayer {
var spinnerColor = UIColor.whiteColor() {
didSet {
strokeColor = spinnerColor.CGColor
}
}
init(frame:CGRect) {
super.init()
let radius:CGFloat = (frame.height / 2) * 0.5
self.frame = CGRectMake(0, 0, frame.height, frame.height)
let center = CGPointMake(frame.height / 2, bounds.center.y)
let startAngle = 0 - M_PI_2
let endAngle = M_PI * 2 - M_PI_2
let clockwise: Bool = true
self.path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: clockwise).CGPath
self.fillColor = nil
self.strokeColor = spinnerColor.CGColor
self.lineWidth = 1
self.strokeEnd = 0.4
self.hidden = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func animation() {
self.hidden = false
let rotate = CABasicAnimation(keyPath: "transform.rotation.z")
rotate.fromValue = 0
rotate.toValue = M_PI * 2
rotate.duration = 0.4
rotate.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
rotate.repeatCount = HUGE
rotate.fillMode = kCAFillModeForwards
rotate.removedOnCompletion = false
self.addAnimation(rotate, forKey: rotate.keyPath)
}
func stopAnimation() {
self.hidden = true
self.removeAllAnimations()
}
}
|
mit
|
quickthyme/PUTcat
|
PUTcat/Presentation/Transaction/TableViewCell/TransactionBasicCell.swift
|
1
|
440
|
import UIKit
class TransactionBasicCell: EditableBasicTableViewCell {}
extension TransactionBasicCell : TransactionViewDataItemConfigurable, TransactionViewDataItemEditable {
func configure(transactionViewDataItem item: TransactionViewDataItem) {
self.textLabel?.text = item.title
self.textField.text = item.title
self.textField.placeholder = item.title
self.imageView?.image = item.icon
}
}
|
apache-2.0
|
APUtils/APExtensions
|
APExtensions/Classes/Core/_Extensions/_Foundation/FloatingPoint+Utils.swift
|
1
|
400
|
//
// FloatingPoint+Utils.swift
// APExtensions
//
// Created by Anton Plebanovich on 1/3/20.
// Copyright © 2020 Anton Plebanovich. All rights reserved.
//
import Foundation
// ******************************* MARK: - Checks
public extension FloatingPoint {
/// Checks if `self` is whole number.
var isWhole: Bool {
return truncatingRemainder(dividingBy: 1) == 0
}
}
|
mit
|
danger/danger-swift
|
Sources/RunnerLib/DangerfileArgumentsPath.swift
|
1
|
406
|
import Foundation
public enum DangerfilePathFinder {
public static func dangerfilePath(fromArguments arguments: [String] = CommandLine.arguments) -> String? {
guard let dangerfileArgIndex = arguments.firstIndex(of: "--dangerfile"),
dangerfileArgIndex + 1 < arguments.count
else {
return nil
}
return arguments[dangerfileArgIndex + 1]
}
}
|
mit
|
Cocoastudies/CocoaCast
|
PodcastApp/PodcastApp/AppDelegate.swift
|
1
|
6099
|
//
// AppDelegate.swift
// PodcastApp
//
// Created by Bruno Da luz on 09/05/16.
// Copyright © 2016 cocoastudies. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "io.studies.PodcastApp" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("PodcastApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
AlvinL33/TownHunt
|
TownHunt-1.1 (LoginScreen)/TownHunt/AccountInfoPageViewController.swift
|
1
|
2231
|
//
// AccountInfoPageViewController.swift
// TownHunt
//
// Created by Alvin Lee on 18/02/2017.
// Copyright © 2017 LeeTech. All rights reserved.
//
import UIKit
class AccountInfoPageViewController: UIViewController {
@IBOutlet weak var menuOpenNavBarButton: UIBarButtonItem!
@IBOutlet weak var userIDInfoLabel: UILabel!
@IBOutlet weak var usernameInfoLabel: UILabel!
@IBOutlet weak var emailInfoLabel: UILabel!
@IBOutlet weak var noPacksPlayedInfoLabel: UILabel!
@IBOutlet weak var noPacksCreatedInfoLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
menuOpenNavBarButton.target = self.revealViewController()
menuOpenNavBarButton.action = #selector(SWRevealViewController.revealToggle(_:))
UIGraphicsBeginImageContext(self.view.frame.size)
UIImage(named: "accountInfoBackgroundImage")?.draw(in: self.view.bounds)
let image: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
self.view.backgroundColor = UIColor(patternImage: image)
loadAccountDetails()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func LogoutButtonTapped(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
UserDefaults.standard.removeObject(forKey: "UserID")
UserDefaults.standard.removeObject(forKey: "Username")
UserDefaults.standard.removeObject(forKey: "UserEmail")
UserDefaults.standard.synchronize()
self.performSegue(withIdentifier: "loginViewAfterLogout", sender: self)
}
private func loadAccountDetails(){
userIDInfoLabel.text = "User ID: \(UserDefaults.standard.string(forKey: "UserID")!)"
usernameInfoLabel.text = "Username: \(UserDefaults.standard.string(forKey: "Username")!)"
emailInfoLabel.text = "Email: \(UserDefaults.standard.string(forKey: "UserEmail")!)"
noPacksPlayedInfoLabel.text = "No Of Packs Played: 0"
noPacksCreatedInfoLabel.text = "No Of Packs Created: 0"
}
}
|
apache-2.0
|
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxCocoa/RxCocoa/Foundation/Logging.swift
|
166
|
518
|
//
// Logging.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/3/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.URLRequest
/// Simple logging settings for RxCocoa library.
public struct Logging {
public typealias LogURLRequest = (URLRequest) -> Bool
/// Log URL requests to standard output in curl format.
public static var URLRequests: LogURLRequest = { _ in
#if DEBUG
return true
#else
return false
#endif
}
}
|
mit
|
DrabWeb/Komikan
|
Komikan/Komikan/KMSearchListViewController.swift
|
1
|
15088
|
//
// KMGroupListViewController.swift
// Komikan
//
// Created by Seth on 2016-02-14.
//
import Cocoa
class KMSearchListViewController: NSViewController {
/// The visual effect view for the background of the window
@IBOutlet weak var backgroundVisualEffectView: NSVisualEffectView!
/// The table view for the search list
@IBOutlet weak var searchListTableView: NSTableView!
/// When we click the "Filter" button...
@IBAction func filterButtonPressed(_ sender: AnyObject) {
// Apply the search filter
applyFilter();
}
/// When we click the "Select All" button...
@IBAction func selectAllButtonPressed(_ sender: AnyObject) {
// For every search list item...
for(_, currentSearchListItem) in searchListItems.enumerated() {
// Set the current search list item to be selected
currentSearchListItem.checked = true;
}
// Reload the table view
searchListTableView.reloadData();
}
/// When we click the "Deselect All" button...
@IBAction func deselectAllButtonPressed(_ sender: AnyObject) {
// For every search list item...
for(_, currentSearchListItem) in searchListItems.enumerated() {
// Set the current search list item to be deselected
currentSearchListItem.checked = false;
}
// Reload the table view
searchListTableView.reloadData();
}
/// The search list items for the search list table view
var searchListItems : [KMSearchListItemData] = [];
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
// Style the window
styleWindow();
// Load the items
loadItems();
// Deselect all the items
// For every search list item...
for(_, currentSearchListItem) in searchListItems.enumerated() {
// Set the current search list item to be deselected
currentSearchListItem.checked = false;
}
// Reload the table view
searchListTableView.reloadData();
}
func loadItems() {
// Remove all the group items
searchListItems.removeAll();
// For every series the user has in the manga grid...
for(_, currentSeries) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allSeries().enumerated() {
// Add the current series to the search list items
searchListItems.append(KMSearchListItemData(name: currentSeries, type: KMPropertyType.series));
// Set the items count to the amount of times it's series appears
searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfSeries(currentSeries);
}
// For every artist the user has in the manga grid...
for(_, currentArtist) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allArtists().enumerated() {
// Add the current artist to the search list items
searchListItems.append(KMSearchListItemData(name: currentArtist, type: KMPropertyType.artist));
// Set the items count to the amount of times it's artist appears
searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfArtist(currentArtist);
}
// For every writer the user has in the manga grid...
for(_, currentWriter) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allWriters().enumerated() {
// Add the current writer to the search list items
searchListItems.append(KMSearchListItemData(name: currentWriter, type: KMPropertyType.writer));
// Set the items count to the amount of times it's writer appears
searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfWriter(currentWriter);
}
// For every tag the user has in the manga grid...
for(_, currentTag) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allTags().enumerated() {
// Add the current tag to the search list items
searchListItems.append(KMSearchListItemData(name: currentTag, type: KMPropertyType.tags));
// Set the items count to the amount of times it's tag appears
searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfTag(currentTag);
}
// For every group the user has in the manga grid...
for(_, currentGroup) in (NSApplication.shared().delegate as! AppDelegate).mangaGridController.allGroups().enumerated() {
// Add the current group to the search list items
searchListItems.append(KMSearchListItemData(name: currentGroup, type: KMPropertyType.group));
// Set the items count to the amount of times it's group appears
searchListItems.last!.count = (NSApplication.shared().delegate as! AppDelegate).mangaGridController.countOfGroup(currentGroup);
}
// Reload the table view
searchListTableView.reloadData();
}
/// Takes everything we checked/unchecked and filters by them
func applyFilter() {
/// The string we will search by
var searchString : String = "";
/// Is this the first series search item?
var firstOfSeriesSearch : Bool = true;
/// Is this the first artist search item?
var firstOfArtistSearch : Bool = true;
/// Is this the first writer search item?
var firstOfWriterSearch : Bool = true;
/// Is this the first tags search item?
var firstOfTagsSearch : Bool = true;
/// Is this the first group search item?
var firstOfGroupSearch : Bool = true;
// For every item in the search list items...
for(_, currentItem) in searchListItems.enumerated() {
// If the current item is checked...
if(currentItem.checked) {
// If the current item is for a series...
if(currentItem.type == .series) {
// If this is the first series search term...
if(firstOfSeriesSearch) {
// Add the series search group marker
searchString += "s:\"";
// Say this is no longer the first series search term
firstOfSeriesSearch = false;
}
// Add the current series to the search string
searchString += currentItem.name + ", ";
}
// If the current item is for an artist...
else if(currentItem.type == .artist) {
// If this is the first artist search term...
if(firstOfArtistSearch) {
// If the search string isnt blank...
if(searchString != "") {
// Remove the extra ", " from the search string
searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex)));
// Add the "" a:"" to the search string to denote a new search type
searchString += "\" a:\"";
}
else {
// Add the artist search group marker
searchString += "a:\"";
}
// Say this is no longer the first artist search term
firstOfArtistSearch = false;
}
// Add the current artist to the search string
searchString += currentItem.name + ", ";
}
// If the current item is for a writer...
else if(currentItem.type == .writer) {
// If this is the first writer search term...
if(firstOfWriterSearch) {
// If the search string isnt blank...
if(searchString != "") {
// Remove the extra ", " from the search string
searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex)));
// Add the "" w:"" to the search string to denote a new search type
searchString += "\" w:\"";
}
else {
// Add the writer search group marker
searchString += "w:\"";
}
// Say this is no longer the first writer search term
firstOfWriterSearch = false;
}
// Add the current artist to the search string
searchString += currentItem.name + ", ";
}
// If the current item is for tags...
else if(currentItem.type == .tags) {
// If this is the first tag search term...
if(firstOfTagsSearch) {
// If the search string isnt blank...
if(searchString != "") {
// Remove the extra ", " from the search string
searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex)));
// Add the "" tg:"" to the search string to denote a new search type
searchString += "\" tg:\"";
}
else {
// Add the tags search group marker
searchString += "tg:\"";
}
// Say this is no longer the first tags search term
firstOfTagsSearch = false;
}
// Add the current artist to the search string
searchString += currentItem.name + ", ";
}
// If the current item is for a group...
else if(currentItem.type == .group) {
// If this is the first group search term...
if(firstOfGroupSearch) {
// If the search string isnt blank...
if(searchString != "") {
// Remove the extra ", " from the search string
searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex)));
// Add the "" g:"" to the search string to denote a new search type
searchString += "\" g:\"";
}
else {
// Add the group search group marker
searchString += "g:\"";
}
// Say this is no longer the first group search term
firstOfGroupSearch = false;
}
// Add the current artist to the search string
searchString += currentItem.name + ", ";
}
}
}
// If the search string isnt blank...
if(searchString != "") {
// Remove the extra ", " from the search string
searchString = searchString.substring(to: searchString.index(before: searchString.characters.index(before: searchString.endIndex)));
// Add the """ at the end of the search string to denote the end of the final search term
searchString += "\"";
}
// Set the search fields value to the search string we created
(NSApplication.shared().delegate as! AppDelegate).searchTextField.stringValue = searchString;
// Search for the search string
(NSApplication.shared().delegate as! AppDelegate).mangaGridController.searchFor(searchString);
}
/// Styles the window
func styleWindow() {
// Set the background to be more vibrant
backgroundVisualEffectView.material = NSVisualEffectMaterial.dark;
}
}
extension KMSearchListViewController: NSTableViewDelegate {
func numberOfRows(in aTableView: NSTableView) -> Int {
// Return the amount of search list items
return self.searchListItems.count;
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
/// The cell view it is asking us about for the data
let cellView : NSTableCellView = tableView.make(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView;
// If the column is the Main Column...
if(tableColumn!.identifier == "Main Column") {
/// This items search list data
let searchListItemData = self.searchListItems[row];
// Set the label's string value to the search list items name
cellView.textField!.stringValue = searchListItemData.name;
// Set the checkbox to be checked/unchecked based on if the cell view item is checked
(cellView as? KMSearchListTableViewCell)?.checkbox.state = Int(searchListItemData.checked as NSNumber);
// Set the type label's string value to be this item's type with the count at the end in parenthesis
(cellView as? KMSearchListTableViewCell)?.typeLabel.stringValue = KMEnumUtilities().propertyTypeToString(searchListItemData.type!) + "(" + String(searchListItemData.count) + ")";
// Set the cell views data so it can update it as it is changed
(cellView as? KMSearchListTableViewCell)?.data = searchListItemData;
// Return the modified cell view
return cellView;
}
// Return the unmodified cell view, we didnt need to do anything to this one
return cellView;
}
}
extension KMSearchListViewController: NSTableViewDataSource {
}
|
gpl-3.0
|
LeoMobileDeveloper/MDTable
|
MDTableExample/SystemCellController.swift
|
1
|
2450
|
//
// SystemCellController.swift
// MDTableExample
//
// Created by Leo on 2017/6/15.
// Copyright © 2017年 Leo Huang. All rights reserved.
//
import UIKit
import MDTable
class SystemCellController: UIViewController {
var tableManager:TableManager!
var customSwitchValue = true
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "System cell"
let tableView = UITableView(frame: view.bounds, style: .grouped)
view.addSubview(tableView)
let section0 = buildSection0()
tableView.manager = TableManager(sections: [section0])
}
func buildSection0()->Section{
let row0 = Row(title: "Basic", rowHeight: 40.0, accessoryType: .none)
let row1 = Row(title: "Custom Color", rowHeight: 40.0, accessoryType: .detailDisclosureButton)
row1.onRender { (cell,isInital) in
cell.textLabel?.textColor = UIColor.orange
cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
}.onDidSelected { (tableView, indexPath) in
tableView.deselectRow(at: indexPath, animated: true)
}
let row2 = Row(title: "Title",
image: UIImage(named: "avatar"),
detailTitle: "Detail Title",
rowHeight: 60.0,
accessoryType: .disclosureIndicator);
row2.cellStyle = .value1
let row3 = Row(title: "Title",
image: UIImage(named: "avatar"),
detailTitle: "Sub Title",
rowHeight: 60.0,
accessoryType: .checkmark);
row3.cellStyle = .subtitle
let row4 = Row(title: "Title",
image: UIImage(named: "avatar"),
detailTitle: "Sub Title",
rowHeight: 60.0,
accessoryType: .checkmark);
row4.onRender { (cell,isInital) in
if isInital{
let customSwitch = UISwitch()
cell.accessoryView = customSwitch
}
}
row4.reuseIdentifier = "Cell With Switch"
let section = Section(rows: [row0,row1,row2,row3,row4])
section.heightForHeader = 10.0
section.heightForFooter = 0.0
return section
}
}
|
mit
|
OscarSwanros/swift
|
stdlib/public/SDK/Intents/INSetDefrosterSettingsInCarIntent.swift
|
27
|
936
|
//===----------------------------------------------------------------------===//
//
// 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 Intents
import Foundation
#if os(iOS)
@available(iOS 10.0, *)
extension INSetDefrosterSettingsInCarIntent {
@nonobjc
public convenience init(
enable: Bool? = nil, defroster: INCarDefroster = .unknown
) {
self.init(__enable: enable.map { NSNumber(value: $0) },
defroster: defroster)
}
@nonobjc
public final var enable: Bool? {
return __enable?.boolValue
}
}
#endif
|
apache-2.0
|
litoarias/HAPlayerView
|
HAPlayerView/HABackgroundPlayerView.swift
|
1
|
3439
|
import UIKit
import AVFoundation
@IBDesignable public class HABackgroundPlayerView: UIView {
var player: AVPlayer?
var avPlayerLayer: AVPlayerLayer!
var videoURL: NSURL = NSURL()
var cView: UIView = UIView()
let screenSize = UIScreen.main.bounds
@IBInspectable
public var name: String = "test" {
didSet {
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
}
@IBInspectable
public var mime: String = "mp4" {
didSet {
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
}
@IBInspectable
public var repeats: Bool = true {
didSet {
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
}
@IBInspectable
public var muted: Bool = true {
didSet {
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
}
@IBInspectable
public var layerAlpha: CGFloat = 0.5 {
didSet {
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
inits(resource: name, extensionFormat: mime, repeats: repeats, muted: muted, alpha: layerAlpha)
}
func inits(resource: String, extensionFormat: String, repeats: Bool, muted: Bool, alpha: CGFloat) {
setLayer()
guard let video = Bundle.main.url(forResource: resource,
withExtension: extensionFormat) else {
return
}
videoURL = video as NSURL
if (player == nil) {
player = AVPlayer(url: videoURL as URL)
player?.actionAtItemEnd = .none
player?.isMuted = muted
avPlayerLayer = AVPlayerLayer(player: player)
avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
avPlayerLayer.zPosition = -1
avPlayerLayer.frame = screenSize
player?.play()
layer.addSublayer(avPlayerLayer)
}
if repeats {
NotificationCenter.default.addObserver(self,
selector: #selector(loopVideo),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: player?.currentItem)
}
}
@objc func loopVideo() {
player?.seek(to: CMTime.zero)
player?.play()
}
func setLayer() {
if cView.isDescendant(of: self) {
cView.removeFromSuperview()
} else {
cView = UIView.init(frame: screenSize)
cView.backgroundColor = UIColor.black
cView.alpha = layerAlpha;
cView.layer.zPosition = 0;
self.addSubview(cView)
}
}
}
|
mit
|
lorentey/swift
|
stdlib/public/core/EmptyCollection.swift
|
15
|
5418
|
//===--- EmptyCollection.swift - A collection with no elements ------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Sometimes an operation is best expressed in terms of some other,
// larger operation where one of the parameters is an empty
// collection. For example, we can erase elements from an Array by
// replacing a subrange with the empty collection.
//
//===----------------------------------------------------------------------===//
/// A collection whose element type is `Element` but that is always empty.
@frozen // trivial-implementation
public struct EmptyCollection<Element> {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
extension EmptyCollection {
/// An iterator that never produces an element.
@frozen // trivial-implementation
public struct Iterator {
// no properties
/// Creates an instance.
@inlinable // trivial-implementation
public init() {}
}
}
extension EmptyCollection.Iterator: IteratorProtocol, Sequence {
/// Returns `nil`, indicating that there are no more elements.
@inlinable // trivial-implementation
public mutating func next() -> Element? {
return nil
}
}
extension EmptyCollection: Sequence {
/// Returns an empty iterator.
@inlinable // trivial-implementation
public func makeIterator() -> Iterator {
return Iterator()
}
}
extension EmptyCollection: RandomAccessCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
public typealias Indices = Range<Int>
public typealias SubSequence = EmptyCollection<Element>
/// Always zero, just like `endIndex`.
@inlinable // trivial-implementation
public var startIndex: Index {
return 0
}
/// Always zero, just like `startIndex`.
@inlinable // trivial-implementation
public var endIndex: Index {
return 0
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(after i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Always traps.
///
/// `EmptyCollection` does not have any element indices, so it is not
/// possible to advance indices.
@inlinable // trivial-implementation
public func index(before i: Index) -> Index {
_preconditionFailure("EmptyCollection can't advance indices")
}
/// Accesses the element at the given position.
///
/// Must never be called, since this collection is always empty.
@inlinable // trivial-implementation
public subscript(position: Index) -> Element {
get {
_preconditionFailure("Index out of range")
}
set {
_preconditionFailure("Index out of range")
}
}
@inlinable // trivial-implementation
public subscript(bounds: Range<Index>) -> SubSequence {
get {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
return self
}
set {
_debugPrecondition(bounds.lowerBound == 0 && bounds.upperBound == 0,
"Index out of range")
}
}
/// The number of elements (always zero).
@inlinable // trivial-implementation
public var count: Int {
return 0
}
@inlinable // trivial-implementation
public func index(_ i: Index, offsetBy n: Int) -> Index {
_debugPrecondition(i == startIndex && n == 0, "Index out of range")
return i
}
@inlinable // trivial-implementation
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
_debugPrecondition(i == startIndex && limit == startIndex,
"Index out of range")
return n == 0 ? i : nil
}
/// The distance between two indexes (always zero).
@inlinable // trivial-implementation
public func distance(from start: Index, to end: Index) -> Int {
_debugPrecondition(start == 0, "From must be startIndex (or endIndex)")
_debugPrecondition(end == 0, "To must be endIndex (or startIndex)")
return 0
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_debugPrecondition(index == 0, "out of bounds")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
@inlinable // trivial-implementation
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_debugPrecondition(range == indices, "invalid range for an empty collection")
_debugPrecondition(bounds == indices, "invalid bounds for an empty collection")
}
}
extension EmptyCollection: Equatable {
@inlinable // trivial-implementation
public static func == (
lhs: EmptyCollection<Element>, rhs: EmptyCollection<Element>
) -> Bool {
return true
}
}
|
apache-2.0
|
colbylwilliams/bugtrap
|
iOS/Code/Swift/bugTrap/bugTrapKit/Trackers/Assembla/AssemblaProxy.swift
|
1
|
162
|
//
// AssemblaProxy.swift
// bugTrap
//
// Created by Colby L Williams on 12/13/14.
// Copyright (c) 2014 bugTrap. All rights reserved.
//
import Foundation
|
mit
|
jankase/JKJSON
|
JKJSONTests/JSONTestHelpers.swift
|
1
|
2628
|
//
// Created by Jan Kase on 27/12/15.
// Copyright (c) 2015 Jan Kase. All rights reserved.
//
import Foundation
import XCTest
@testable import JKJSON
struct JSONCreateableTests<T:JSONStaticCreatable> {
static func testCreationFromJSONRepresentation(theJsonRepresentation: T.JSONRepresentationType) {
let aMappedObject = T.instanceFromJSON(theJsonRepresentation)
XCTAssertNotNil(aMappedObject, "Mapped object not created")
}
static func testCreationFromMultipleJSONRepresentation(theJsonRepresentations: [T.JSONRepresentationType]) {
let aMappedObjects = T.instancesFromJSON(theJsonRepresentations)
XCTAssertNotNil(aMappedObjects, "Mapped objects not created")
XCTAssertEqual(aMappedObjects?.count, theJsonRepresentations.count, "Number of created objects does not fit provided JSON representation")
}
static func testEqualityForJsonRepresentations<T:protocol<JSONStaticCreatable, Equatable> where T.JSONRepresentationType == T>(theJsonRepresentation: T.JSONRepresentationType) {
let aMappedObject = T.instanceFromJSON(theJsonRepresentation)
XCTAssertNotNil(aMappedObject, "Mapped object not created")
XCTAssertEqual(aMappedObject, theJsonRepresentation, "Mapped object is not same as provided source")
XCTAssertEqual(aMappedObject?.json, theJsonRepresentation, "Mapped object json representation is not equal to source")
}
static func testEquality<P:JSONStaticCreatable where P.JSONRepresentationType: Equatable>(theJsonRepresentation: P.JSONRepresentationType) {
let aMappedObject = P.instanceFromJSON(theJsonRepresentation)
XCTAssertNotNil(aMappedObject, "Mapped object not created")
XCTAssertEqual(aMappedObject?.json, theJsonRepresentation, "Mapped object json representation is not equal to source")
}
}
extension JSONCreateableTests where T: JSONStringStaticCreatable {
static func testCreationFromString(theStringRepresentation: String, theFailExpected: Bool = false) {
let aMappedObject = T.instanceFromJSONString(theStringRepresentation)
if theFailExpected {
XCTAssertNil(aMappedObject, "Mapped object created even fail expected")
} else {
XCTAssertNotNil(aMappedObject, "Mapped object not created")
}
}
}
struct JSONMutableTests<T:protocol<JSONMutable, JSONStaticCreatable> where T.JSONRepresentationType: Equatable> {
static func testAssignForJSONRepresentedObject(theJsonObject: T, newValue theNewValue: T.JSONRepresentationType) {
var aJsonObject = theJsonObject
aJsonObject.json = theNewValue
XCTAssertEqual(aJsonObject.json, theNewValue, "JSON settings not updated original value")
}
}
|
mit
|
alblue/swift
|
test/SILGen/conditional_conformance.swift
|
2
|
3515
|
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
protocol P1 {
func normal()
func generic<T: P3>(_: T)
}
protocol P2 {}
protocol P3 {}
protocol P4 {
associatedtype AT
}
struct Conformance<A> {}
extension Conformance: P1 where A: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P2> Conformance<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Conformance<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance11ConformanceVyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Conformance<A>
// CHECK-NEXT: conditional_conformance (A: P2): dependent
// CHECK-NEXT: }
struct ConformanceAssoc<A> {}
extension ConformanceAssoc: P1 where A: P4, A.AT: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P4, A.AT : P2> ConformanceAssoc<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> ConformanceAssoc<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance16ConformanceAssocVyxGAA2P1A2A2P4RzAA2P22ATRpzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> ConformanceAssoc<A>
// CHECK-NEXT: conditional_conformance (A: P4): dependent
// CHECK-NEXT: conditional_conformance (A.AT: P2): dependent
// CHECK-NEXT: }
/*
FIXME: same type constraints are modelled incorrectly.
struct SameTypeConcrete<B> {}
extension SameTypeConcrete: P1 where B == Int {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct SameTypeGeneric<C, D> {}
extension SameTypeGeneric: P1 where C == D {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct SameTypeGenericConcrete<E, F> {}
extension SameTypeGenericConcrete: P1 where E == [F] {
func normal() {}
func generic<T: P3>(_: T) {}
}
struct Everything<G, H, I, J, K, L> {}
extension Everything: P1 where G: P2, H == Int, I == J, K == [L] {
func normal() {}
func generic<T: P3>(_: T) {}
}
*/
struct IsP2: P2 {}
struct IsNotP2 {}
class Base<A> {}
extension Base: P1 where A: P2 {
func normal() {}
func generic<T: P3>(_: T) {}
}
// CHECK-LABEL: sil_witness_table hidden <A where A : P2> Base<A>: P1 module conditional_conformance {
// CHECK-NEXT: method #P1.normal!1: <Self where Self : P1> (Self) -> () -> () : @$s23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP6normalyyFTW // protocol witness for P1.normal() in conformance <A> Base<A>
// CHECK-NEXT: method #P1.generic!1: <Self where Self : P1><T where T : P3> (Self) -> (T) -> () : @$s23conditional_conformance4BaseCyxGAA2P1A2A2P2RzlAaEP7genericyyqd__AA2P3Rd__lFTW // protocol witness for P1.generic<A>(_:) in conformance <A> Base<A>
// CHECK-NEXT: conditional_conformance (A: P2): dependent
// CHECK-NEXT: }
// These don't get separate witness tables, but shouldn't crash anything.
class SubclassGood: Base<IsP2> {}
class SubclassBad: Base<IsNotP2> {}
|
apache-2.0
|
scottrhoyt/Jolt
|
Jolt/Source/FloatingTypeExtensions/FloatingTypeOperationsExtensions.swift
|
1
|
1486
|
//
// FloatingTypeOperationsExtensions.swift
// Jolt
//
// Created by Scott Hoyt on 9/8/15.
// Copyright © 2015 Scott Hoyt. All rights reserved.
//
import Accelerate
extension Double : VectorOperations {
public static func magnitude(x: [Double]) -> Double {
return cblas_dnrm2(Int32(x.count), x, 1)
}
public static func unit(x: [Double]) -> [Double] {
// FIXME: Can a vecLib function like vSnorm2 be used?
return Double.div(x, [Double](count: x.count, repeatedValue:magnitude(x)))
}
public static func dot(x: [Double], _ y: [Double]) -> Double {
precondition(x.count == y.count, "Vectors must have equal count")
var result: Double = 0.0
vDSP_dotprD(x, 1, y, 1, &result, vDSP_Length(x.count))
return result
}
}
extension Float : VectorOperations {
public static func magnitude(x: [Float]) -> Float {
return cblas_snrm2(Int32(x.count), x, 1)
}
public static func unit(x: [Float]) -> [Float] {
// FIXME: Can a vecLib function like vSnorm2 be used?
return Float.div(x, [Float](count: x.count, repeatedValue:magnitude(x)))
}
public static func dot(x: [Float], _ y: [Float]) -> Float {
precondition(x.count == y.count, "Vectors must have equal count")
var result: Float = 0.0
vDSP_dotpr(x, 1, y, 1, &result, vDSP_Length(x.count))
return result
}
}
|
mit
|
alblue/swift
|
test/SILGen/dynamic.swift
|
2
|
27440
|
// RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift | %FileCheck %s
// RUN: %target-swift-emit-sil(mock-sdk: -sdk %S/Inputs -I %t) -module-name dynamic -Xllvm -sil-full-demangle -primary-file %s %S/Inputs/dynamic_other.swift -verify
// REQUIRES: objc_interop
import Foundation
import gizmo
class Foo: Proto {
// Not objc or dynamic, so only a vtable entry
init(native: Int) {}
func nativeMethod() {}
var nativeProp: Int = 0
subscript(native native: Int) -> Int {
get { return native }
set {}
}
// @objc, so it has an ObjC entry point but can also be dispatched
// by vtable
@objc init(objc: Int) {}
@objc func objcMethod() {}
@objc var objcProp: Int = 0
@objc subscript(objc objc: AnyObject) -> Int {
get { return 0 }
set {}
}
// dynamic, so it has only an ObjC entry point
@objc dynamic init(dynamic: Int) {}
@objc dynamic func dynamicMethod() {}
@objc dynamic var dynamicProp: Int = 0
@objc dynamic subscript(dynamic dynamic: Int) -> Int {
get { return dynamic }
set {}
}
func overriddenByDynamic() {}
@NSManaged var managedProp: Int
}
protocol Proto {
func nativeMethod()
var nativeProp: Int { get set }
subscript(native native: Int) -> Int { get set }
func objcMethod()
var objcProp: Int { get set }
subscript(objc objc: AnyObject) -> Int { get set }
func dynamicMethod()
var dynamicProp: Int { get set }
subscript(dynamic dynamic: Int) -> Int { get set }
}
// ObjC entry points for @objc and dynamic entry points
// normal and @objc initializing ctors can be statically dispatched
// CHECK-LABEL: sil hidden @$s7dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden @$s7dynamic3FooC{{.*}}tcfC
// CHECK: function_ref @$s7dynamic3FooC{{.*}}tcfc
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC10objcMethod{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC8objcPropSivgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC8objcPropSivsTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC4objcSiyXl_tcigTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC4objcSiyXl_tcisTo
// TODO: dynamic initializing ctor must be objc dispatched
// CHECK-LABEL: sil hidden @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.init!initializer.1.foreign :
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3{{[_0-9a-zA-Z]*}}fcTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC0A4PropSivgTo
// CHECK-LABEL: sil hidden [transparent] [thunk] @$s7dynamic3FooC0A4PropSivsTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooCAAS2i_tcigTo
// CHECK-LABEL: sil hidden [thunk] @$s7dynamic3FooCAAS2i_tcisTo
// Protocol witnesses use best appropriate dispatch
// Native witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP12nativeMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10nativePropSivsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcigTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP6nativeS2i_tcisTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// @objc witnesses use vtable dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP10objcMethod{{[_0-9a-zA-Z]*}}FTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivgTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP8objcPropSivsTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcigTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP4objcSiyXl_tcisTW
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
// Dynamic witnesses use objc dispatch:
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A6Method{{[_0-9a-zA-Z]*}}FTW
// CHECK: function_ref @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A6Method{{[_0-9a-zA-Z]*}}FTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivgTW
// CHECK: function_ref @$s7dynamic3FooC0A4PropSivgTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A4PropSivgTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDP0A4PropSivsTW
// CHECK: function_ref @$s7dynamic3FooC0A4PropSivsTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooC0A4PropSivsTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcigTW
// CHECK: function_ref @$s7dynamic3FooCAAS2i_tcigTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooCAAS2i_tcigTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign :
// CHECK-LABEL: sil private [transparent] [thunk] @$s7dynamic3FooCAA5ProtoA2aDPAAS2i_tcisTW
// CHECK: function_ref @$s7dynamic3FooCAAS2i_tcisTD
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$s7dynamic3FooCAAS2i_tcisTD
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign :
// Superclass dispatch
class Subclass: Foo {
// Native and objc methods can directly reference super members
override init(native: Int) {
super.init(native: native)
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fC
// CHECK: function_ref @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
override func nativeMethod() {
super.nativeMethod()
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC12nativeMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s7dynamic3FooC12nativeMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var nativeProp: Int {
get { return super.nativeProp }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10nativePropSivg
// CHECK: function_ref @$s7dynamic3FooC10nativePropSivg : $@convention(method) (@guaranteed Foo) -> Int
set { super.nativeProp = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10nativePropSivs
// CHECK: function_ref @$s7dynamic3FooC10nativePropSivs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(native native: Int) -> Int {
get { return super[native: native] }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC6nativeS2i_tcig
// CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcig : $@convention(method) (Int, @guaranteed Foo) -> Int
set { super[native: native] = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC6nativeS2i_tcis
// CHECK: function_ref @$s7dynamic3FooC6nativeS2i_tcis : $@convention(method) (Int, Int, @guaranteed Foo) -> ()
}
override init(objc: Int) {
super.init(objc: objc)
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcACSi_tcfc
// CHECK: function_ref @$s7dynamic3FooC4objcACSi_tcfc : $@convention(method) (Int, @owned Foo) -> @owned Foo
override func objcMethod() {
super.objcMethod()
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC10objcMethod{{[_0-9a-zA-Z]*}}F
// CHECK: function_ref @$s7dynamic3FooC10objcMethodyyF : $@convention(method) (@guaranteed Foo) -> ()
override var objcProp: Int {
get { return super.objcProp }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC8objcPropSivg
// CHECK: function_ref @$s7dynamic3FooC8objcPropSivg : $@convention(method) (@guaranteed Foo) -> Int
set { super.objcProp = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC8objcPropSivs
// CHECK: function_ref @$s7dynamic3FooC8objcPropSivs : $@convention(method) (Int, @guaranteed Foo) -> ()
}
override subscript(objc objc: AnyObject) -> Int {
get { return super[objc: objc] }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcSiyXl_tcig
// CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcig : $@convention(method) (@guaranteed AnyObject, @guaranteed Foo) -> Int
set { super[objc: objc] = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC4objcSiyXl_tcis
// CHECK: function_ref @$s7dynamic3FooC4objcSiyXl_tcis : $@convention(method) (Int, @owned AnyObject, @guaranteed Foo) -> ()
}
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.init!initializer.1.foreign :
override func dynamicMethod() {
super.dynamicMethod()
}
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A6Method{{[_0-9a-zA-Z]*}}F
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicMethod!1.foreign :
override var dynamicProp: Int {
get { return super.dynamicProp }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A4PropSivg
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!getter.1.foreign :
set { super.dynamicProp = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassC0A4PropSivs
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.dynamicProp!setter.1.foreign :
}
override subscript(dynamic dynamic: Int) -> Int {
get { return super[dynamic: dynamic] }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassCAAS2i_tcig
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!getter.1.foreign :
set { super[dynamic: dynamic] = newValue }
// CHECK-LABEL: sil hidden @$s7dynamic8SubclassCAAS2i_tcis
// CHECK: objc_super_method {{%.*}} : $Subclass, #Foo.subscript!setter.1.foreign :
}
@objc dynamic override func overriddenByDynamic() {}
}
class SubclassWithInheritedInits: Foo {
// CHECK-LABEL: sil hidden @$s7dynamic26SubclassWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $SubclassWithInheritedInits, #Foo.init!initializer.1.foreign :
}
class GrandchildWithInheritedInits: SubclassWithInheritedInits {
// CHECK-LABEL: sil hidden @$s7dynamic28GrandchildWithInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $GrandchildWithInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
class GrandchildOfInheritedInits: SubclassWithInheritedInits {
// Dynamic methods are super-dispatched by objc_msgSend
override init(dynamic: Int) {
super.init(dynamic: dynamic)
}
// CHECK-LABEL: sil hidden @$s7dynamic26GrandchildOfInheritedInitsC{{[_0-9a-zA-Z]*}}fc
// CHECK: objc_super_method {{%.*}} : $GrandchildOfInheritedInits, #SubclassWithInheritedInits.init!initializer.1.foreign :
}
// CHECK-LABEL: sil hidden @$s7dynamic20nativeMethodDispatchyyF : $@convention(thin) () -> ()
func nativeMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(native: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic18objcMethodDispatchyyF : $@convention(thin) () -> ()
func objcMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(objc: 0)
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $Foo, #Foo.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!getter.1 :
let y = c[objc: 0 as NSNumber]
// CHECK: class_method {{%.*}} : $Foo, #Foo.subscript!setter.1 :
c[objc: 0 as NSNumber] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic0A14MethodDispatchyyF : $@convention(thin) () -> ()
func dynamicMethodDispatch() {
// CHECK: function_ref @$s7dynamic3{{[_0-9a-zA-Z]*}}fC
let c = Foo(dynamic: 0)
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: objc_method {{%.*}} : $Foo, #Foo.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: objc_method {{%.*}} : $Foo, #Foo.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic15managedDispatchyyAA3FooCF
func managedDispatch(_ c: Foo) {
// CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: objc_method {{%.*}} : $Foo, #Foo.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @$s7dynamic21foreignMethodDispatchyyF
func foreignMethodDispatch() {
// CHECK: function_ref @$sSo9GuisemeauC{{[_0-9a-zA-Z]*}}fC
let g = Guisemeau()!
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.frob!1.foreign
g.frob()
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!getter.1.foreign
let x = g.count
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.count!setter.1.foreign
g.count = x
// CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!getter.1.foreign
let y: Any! = g[0]
// CHECK: objc_method {{%.*}} : $Guisemeau, #Guisemeau.subscript!setter.1.foreign
g[0] = y
// CHECK: objc_method {{%.*}} : $NSObject, #NSObject.description!getter.1.foreign
_ = g.description
}
extension Gizmo {
// CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $Gizmo, #Gizmo.init!initializer.1.foreign
convenience init(convenienceInExtension: Int) {
self.init(bellsOn: convenienceInExtension)
}
// CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassFactory x: Int) {
self.init(stuff: x)
}
// CHECK-LABEL: sil hidden @$sSo5GizmoC7dynamicE{{[_0-9a-zA-Z]*}}fC
// CHECK: objc_method {{%.*}} : $@objc_metatype Gizmo.Type, #Gizmo.init!allocator.1.foreign
convenience init(foreignClassExactFactory x: Int) {
self.init(exactlyStuff: x)
}
@objc func foreignObjCExtension() { }
@objc dynamic func foreignDynamicExtension() { }
}
// CHECK-LABEL: sil hidden @$s7dynamic24foreignExtensionDispatchyySo5GizmoCF
// CHECK: bb0([[ARG:%.*]] : @guaranteed $Gizmo):
func foreignExtensionDispatch(_ g: Gizmo) {
// CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignObjCExtension!1.foreign : (Gizmo)
g.foreignObjCExtension()
// CHECK: objc_method [[ARG]] : $Gizmo, #Gizmo.foreignDynamicExtension!1.foreign
g.foreignDynamicExtension()
}
// CHECK-LABEL: sil hidden @$s7dynamic33nativeMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func nativeMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(native: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeMethod!1 :
c.nativeMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!getter.1 :
let x = c.nativeProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.nativeProp!setter.1 :
c.nativeProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[native: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[native: 0] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic31objcMethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func objcMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(objc: 0)
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcMethod!1 :
c.objcMethod()
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!getter.1 :
let x = c.objcProp
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.objcProp!setter.1 :
c.objcProp = x
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1 :
let y = c[objc: 0]
// CHECK: class_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1 :
c[objc: 0] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic0A27MethodDispatchFromOtherFileyyF : $@convention(thin) () -> ()
func dynamicMethodDispatchFromOtherFile() {
// CHECK: function_ref @$s7dynamic13FromOtherFile{{[_0-9a-zA-Z]*}}fC
let c = FromOtherFile(dynamic: 0)
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicMethod!1.foreign
c.dynamicMethod()
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!getter.1.foreign
let x = c.dynamicProp
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.dynamicProp!setter.1.foreign
c.dynamicProp = x
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!getter.1.foreign
let y = c[dynamic: 0]
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.subscript!setter.1.foreign
c[dynamic: 0] = y
}
// CHECK-LABEL: sil hidden @$s7dynamic28managedDispatchFromOtherFileyyAA0deF0CF
func managedDispatchFromOtherFile(_ c: FromOtherFile) {
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!getter.1.foreign
let x = c.managedProp
// CHECK: objc_method {{%.*}} : $FromOtherFile, #FromOtherFile.managedProp!setter.1.foreign
c.managedProp = x
}
// CHECK-LABEL: sil hidden @$s7dynamic0A16ExtensionMethodsyyAA13ObjCOtherFileCF
func dynamicExtensionMethods(_ obj: ObjCOtherFile) {
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionMethod!1.foreign
obj.extensionMethod()
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.extensionProp!getter.1.foreign
_ = obj.extensionProp
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
// CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.extensionClassProp!getter.1.foreign
_ = type(of: obj).extensionClassProp
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionMethod!1.foreign
obj.dynExtensionMethod()
// CHECK: objc_method {{%.*}} : $ObjCOtherFile, #ObjCOtherFile.dynExtensionProp!getter.1.foreign
_ = obj.dynExtensionProp
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick ObjCOtherFile.Type to $@objc_metatype ObjCOtherFile.Type
// CHECK-NEXT: objc_method {{%.*}} : $@objc_metatype ObjCOtherFile.Type, #ObjCOtherFile.dynExtensionClassProp!getter.1.foreign
_ = type(of: obj).dynExtensionClassProp
}
public class Base {
@objc dynamic var x: Bool { return false }
}
public class Sub : Base {
// CHECK-LABEL: sil hidden @$s7dynamic3SubC1xSbvg : $@convention(method) (@guaranteed Sub) -> Bool {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Sub):
// CHECK: [[AUTOCLOSURE:%.*]] = function_ref @$s7dynamic3SubC1xSbvgSbyKXKfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error)
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: = partial_apply [callee_guaranteed] [[AUTOCLOSURE]]([[SELF_COPY]])
// CHECK: return {{%.*}} : $Bool
// CHECK: } // end sil function '$s7dynamic3SubC1xSbvg'
// CHECK-LABEL: sil private [transparent] @$s7dynamic3SubC1xSbvgSbyKXKfu_ : $@convention(thin) (@guaranteed Sub) -> (Bool, @error Error) {
// CHECK: bb0([[VALUE:%.*]] : @guaranteed $Sub):
// CHECK: [[VALUE_COPY:%.*]] = copy_value [[VALUE]]
// CHECK: [[CAST_VALUE_COPY:%.*]] = upcast [[VALUE_COPY]]
// CHECK: [[BORROWED_CAST_VALUE_COPY:%.*]] = begin_borrow [[CAST_VALUE_COPY]]
// CHECK: [[DOWNCAST_FOR_SUPERMETHOD:%.*]] = unchecked_ref_cast [[BORROWED_CAST_VALUE_COPY]]
// CHECK: [[SUPER:%.*]] = objc_super_method [[DOWNCAST_FOR_SUPERMETHOD]] : $Sub, #Base.x!getter.1.foreign : (Base) -> () -> Bool, $@convention(objc_method) (Base) -> ObjCBool
// CHECK: = apply [[SUPER]]([[BORROWED_CAST_VALUE_COPY]])
// CHECK: end_borrow [[BORROWED_CAST_VALUE_COPY]]
// CHECK: destroy_value [[CAST_VALUE_COPY]]
// CHECK: } // end sil function '$s7dynamic3SubC1xSbvgSbyKXKfu_'
override var x: Bool { return false || super.x }
}
public class BaseExt : NSObject {}
extension BaseExt {
@objc public var count: Int {
return 0
}
}
public class SubExt : BaseExt {
public override var count: Int {
return 1
}
}
public class GenericBase<T> {
public func method(_: T) {}
}
public class ConcreteDerived : GenericBase<Int> {
@objc public override dynamic func method(_: Int) {}
}
// The dynamic override has a different calling convention than the base,
// so after re-abstracting the signature we must dispatch to the dynamic
// thunk.
// CHECK-LABEL: sil private @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed ConcreteDerived) -> ()
// CHECK: bb0(%0 : @trivial $*Int, %1 : @guaranteed $ConcreteDerived):
// CHECK-NEXT: [[VALUE:%.*]] = load [trivial] %0 : $*Int
// CHECK: [[DYNAMIC_THUNK:%.*]] = function_ref @$s7dynamic15ConcreteDerivedC6methodyySiFTD : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK-NEXT: apply [[DYNAMIC_THUNK]]([[VALUE]], %1) : $@convention(method) (Int, @guaranteed ConcreteDerived) -> ()
// CHECK: return
// Vtable contains entries for native and @objc methods, but not dynamic ones
// CHECK-LABEL: sil_vtable Foo {
// CHECK-NEXT: #Foo.init!allocator.1: {{.*}} : @$s7dynamic3FooC6nativeACSi_tcfC
// CHECK-NEXT: #Foo.nativeMethod!1: {{.*}} : @$s7dynamic3FooC12nativeMethodyyF
// CHECK-NEXT: #Foo.nativeProp!getter.1: {{.*}} : @$s7dynamic3FooC10nativePropSivg // dynamic.Foo.nativeProp.getter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!setter.1: {{.*}} : @$s7dynamic3FooC10nativePropSivs // dynamic.Foo.nativeProp.setter : Swift.Int
// CHECK-NEXT: #Foo.nativeProp!modify.1:
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcig // dynamic.Foo.subscript.getter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : @$s7dynamic3FooC6nativeS2i_tcis // dynamic.Foo.subscript.setter : (native: Swift.Int) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!modify.1:
// CHECK-NEXT: #Foo.init!allocator.1: {{.*}} : @$s7dynamic3FooC4objcACSi_tcfC
// CHECK-NEXT: #Foo.objcMethod!1: {{.*}} : @$s7dynamic3FooC10objcMethodyyF
// CHECK-NEXT: #Foo.objcProp!getter.1: {{.*}} : @$s7dynamic3FooC8objcPropSivg // dynamic.Foo.objcProp.getter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!setter.1: {{.*}} : @$s7dynamic3FooC8objcPropSivs // dynamic.Foo.objcProp.setter : Swift.Int
// CHECK-NEXT: #Foo.objcProp!modify.1:
// CHECK-NEXT: #Foo.subscript!getter.1: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcig // dynamic.Foo.subscript.getter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!setter.1: {{.*}} : @$s7dynamic3FooC4objcSiyXl_tcis // dynamic.Foo.subscript.setter : (objc: Swift.AnyObject) -> Swift.Int
// CHECK-NEXT: #Foo.subscript!modify.1:
// CHECK-NEXT: #Foo.overriddenByDynamic!1: {{.*}} : @$s7dynamic3FooC19overriddenByDynamic{{[_0-9a-zA-Z]*}}
// CHECK-NEXT: #Foo.deinit!deallocator.1: {{.*}}
// CHECK-NEXT: }
// Vtable uses a dynamic thunk for dynamic overrides
// CHECK-LABEL: sil_vtable Subclass {
// CHECK: #Foo.overriddenByDynamic!1: {{.*}} : public @$s7dynamic8SubclassC19overriddenByDynamic{{[_0-9a-zA-Z]*}}FTD
// CHECK: }
// Check vtables for implicitly-inherited initializers
// CHECK-LABEL: sil_vtable SubclassWithInheritedInits {
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26SubclassWithInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildWithInheritedInits {
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic28GrandchildWithInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// CHECK-LABEL: sil_vtable GrandchildOfInheritedInits {
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC6nativeACSi_tcfC
// CHECK: #Foo.init!allocator.1: (Foo.Type) -> (Int) -> Foo : @$s7dynamic26GrandchildOfInheritedInitsC4objcACSi_tcfC
// CHECK-NOT: .init!
// CHECK: }
// No vtable entry for override of @objc extension property
// CHECK-LABEL: sil_vtable [serialized] SubExt {
// CHECK-NEXT: #SubExt.deinit!deallocator.1: @$s7dynamic6SubExtCfD // dynamic.SubExt.__deallocating_deinit
// CHECK-NEXT: }
// Dynamic thunk + vtable re-abstraction
// CHECK-LABEL: sil_vtable [serialized] ConcreteDerived {
// CHECK-NEXT: #GenericBase.method!1: <T> (GenericBase<T>) -> (T) -> () : public @$s7dynamic15ConcreteDerivedC6methodyySiFAA11GenericBaseCADyyxFTV [override] // vtable thunk for dynamic.GenericBase.method(A) -> () dispatching to dynamic.ConcreteDerived.method(Swift.Int) -> ()
// CHECK-NEXT: #GenericBase.init!allocator.1: <T> (GenericBase<T>.Type) -> () -> GenericBase<T> : @$s7dynamic15ConcreteDerivedCACycfC [override]
// CHECK-NEXT: #ConcreteDerived.deinit!deallocator.1: @$s7dynamic15ConcreteDerivedCfD // dynamic.ConcreteDerived.__deallocating_deinit
// CHECK-NEXT: }
|
apache-2.0
|
Constructor-io/constructorio-client-swift
|
AutocompleteClient/FW/Logic/Session/Persistence/CIOSessionLoader.swift
|
1
|
784
|
//
// CIOSessionLoader.swift
// AutocompleteClient
//
// Copyright © Constructor.io. All rights reserved.
// http://constructor.io/
//
import Foundation
struct CIOSessionLoader: SessionLoader {
init() {}
func loadSession() -> Session? {
if let data = UserDefaults.standard.object(forKey: Constants.Session.key) as? Data {
return NSKeyedUnarchiver.unarchiveObject(with: data) as? Session
} else {
return nil
}
}
func saveSession(_ session: Session) {
let data = NSKeyedArchiver.archivedData(withRootObject: session)
UserDefaults.standard.set(data, forKey: Constants.Session.key)
}
func clearSession() {
UserDefaults.standard.removeObject(forKey: Constants.Session.key)
}
}
|
mit
|
hardikdevios/HKKit
|
Pod/Classes/HKExtensions/UIKit+Extensions/UIColor+Extension.swift
|
1
|
1634
|
//
// UIColor+Extension.swift
// HKCustomization
//
// Created by Hardik on 10/18/15.
// Copyright © 2015 . All rights reserved.
//
import UIKit
extension UIColor {
convenience public init(hexString:String) {
let r, g, b : CGFloat
if hexString.hasPrefix("#") {
let start = hexString.index(hexString.startIndex, offsetBy: 1)
let hexColor = String(hexString[start...])
if hexColor.count <= 8 {
let scanner = Scanner(string: hexColor)
var hexNumber: UInt64 = 0
if scanner.scanHexInt64(&hexNumber) {
r = CGFloat((hexNumber & 0xff0000) >> 16) / 255
g = CGFloat((hexNumber & 0xff00) >> 8) / 255
b = CGFloat(hexNumber & 0xff) / 255
self.init(red: r, green: g, blue: b, alpha: 1)
return
}
}
}
self.init(red: 0, green: 0, blue: 0, alpha: 1)
}
public class func getRandomColor() -> UIColor{
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
convenience public init(clearRed:CGFloat,clearGreen:CGFloat,clearBlue:CGFloat){
self.init(red: clearRed/255.0, green: clearGreen/255.0, blue: clearBlue/255, alpha: 1)
}
}
|
mit
|
benlangmuir/swift
|
test/TBD/implied_objc_symbols.swift
|
12
|
508
|
// REQUIRES: VENDOR=apple
// RUN: %empty-directory(%t)
// RUN: echo "import Foundation" > %t/main.swift
// RUN: echo "@objc(CApi) public class Api {}" >> %t/main.swift
// RUN: %target-swift-frontend -emit-ir -o/dev/null -parse-as-library -module-name test -import-objc-header %S/Inputs/objc_class_header.h -validate-tbd-against-ir=missing %t/main.swift -disable-objc-attr-requires-foundation-module -emit-tbd -emit-tbd-path %t/main.tbd
// RUN: %FileCheck %s < %t/main.tbd
// CHECK: objc-classes: [ CApi ]
|
apache-2.0
|
mobgeek/swift
|
Swift em 4 Semanas/Swift4Semanas (7.0).playground/Pages/S2 - Tuplas.xcplaygroundpage/Contents.swift
|
1
|
566
|
//: [Anterior: Optionals](@previous)
// Playground - noun: a place where people can play
import UIKit
let compra = (5, "KG", "Maça") // (Int, String, String)
let (quantidade, unidade, mercadoria) = compra
print("Você comprou \(quantidade) \(unidade) de \(mercadoria).")
let (_,_,produto) = compra
print("\(produto) foi adicionada ao seu carrinho :-)")
print("\(compra.2) foi adicionada ao seu carrinho.")
let minhaCompra = (quantidade: 2, unidade: "KG", mercadoria: "Laranja")
let meuProduto = minhaCompra.mercadoria
//: [Próximo: Funções](@next)
|
mit
|
HeartRateLearning/HRLApp
|
HRLApp/Modules/ListWorkouts/Presenter/ListWorkoutsModuleInput.swift
|
1
|
224
|
//
// ListWorkoutsListWorkoutsModuleInput.swift
// HRLApp
//
// Created by Enrique de la Torre on 16/01/2017.
// Copyright © 2017 Enrique de la Torre. All rights reserved.
//
protocol ListWorkoutsModuleInput: class {}
|
mit
|
sora0077/AppleMusicKit
|
Sources/Attributes/EditorialNotes.swift
|
1
|
730
|
//
// EditorialNotes.swift
// AppleMusicKit
//
// Created by 林 達也 on 2017/06/30.
// Copyright © 2017年 jp.sora0077. All rights reserved.
//
import Foundation
public protocol EditorialNotesDecodable: Decodable {
}
// MARK: - EditorialNotes
public protocol EditorialNotes: EditorialNotesDecodable {
init(standard: String, short: String) throws
}
private enum CodingKeys: String, CodingKey {
case standard, short
}
extension EditorialNotes {
public init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
try self.init(standard: c.decodeIfPresent(forKey: .standard) ?? "",
short: c.decodeIfPresent(forKey: .short) ?? "")
}
}
|
mit
|
ZekeSnider/Jared
|
Pods/Telegraph/Sources/Protocols/WebSockets/Models/HTTPMessage+WebSocket.swift
|
1
|
2790
|
//
// HTTPMessage+WebSocket.swift
// Telegraph
//
// Created by Yvo van Beek on 2/16/17.
// Copyright © 2017 Building42. All rights reserved.
//
import Foundation
extension HTTPMessage {
public static let webSocketMagicGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
public static let webSocketProtocol = "websocket"
public static let webSocketVersion = "13"
/// Is this an upgrade to the WebSocket protocol?
var isWebSocketUpgrade: Bool {
return headers.upgrade?.caseInsensitiveCompare(HTTPMessage.webSocketProtocol) == .orderedSame
}
}
extension HTTPRequest {
/// Creates a websocket handshake request.
static func webSocketHandshake(host: String, port: Int = 80, protocolName: String? = nil) -> HTTPRequest {
let request = HTTPRequest()
request.webSocketHandshake(host: host, port: port, protocolName: protocolName)
return request
}
/// Decorates a request with websocket handshake headers.
func webSocketHandshake(host: String, port: Int = 80, protocolName: String? = nil) {
method = .GET
setHostHeader(host: host, port: port)
headers.connection = "Upgrade"
headers.upgrade = HTTPMessage.webSocketProtocol
headers.webSocketKey = Data(randomNumberOfBytes: 16).base64EncodedString()
headers.webSocketVersion = HTTPMessage.webSocketVersion
// Only send the 'Sec-WebSocket-Protocol' if it has a value (according to spec)
if let protocolName = protocolName, !protocolName.isEmpty {
headers.webSocketProtocol = protocolName
}
}
}
public extension HTTPResponse {
/// Creates a websocket handshake response.
static func webSocketHandshake(key: String, protocolName: String? = nil) -> HTTPResponse {
let response = HTTPResponse()
response.webSocketHandshake(key: key, protocolName: protocolName)
return response
}
/// Decorates a response with websocket handshake headers.
func webSocketHandshake(key: String, protocolName: String? = nil) {
// Take the incoming key, append the static GUID and return a base64 encoded SHA-1 hash
let webSocketKey = key.appending(HTTPMessage.webSocketMagicGUID)
let webSocketAccept = SHA1.hash(webSocketKey).base64EncodedString()
status = .switchingProtocols
headers.connection = "Upgrade"
headers.upgrade = HTTPMessage.webSocketProtocol
headers.webSocketAccept = webSocketAccept
// Only send the 'Sec-WebSocket-Protocol' if it has a value (according to spec)
if let protocolName = protocolName, !protocolName.isEmpty {
headers.webSocketProtocol = protocolName
}
}
// Returns a boolean indicating if the response is a websocket handshake.
var isWebSocketHandshake: Bool {
return status == .switchingProtocols && isWebSocketUpgrade &&
headers.webSocketAccept?.isEmpty == false
}
}
|
apache-2.0
|
ThumbWorks/i-meditated
|
Pods/RxTests/RxTests/Schedulers/TestSchedulerVirtualTimeConverter.swift
|
4
|
3034
|
//
// TestSchedulerVirtualTimeConverter.swift
// Rx
//
// Created by Krunoslav Zaher on 12/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
/**
Converter from virtual time and time interval measured in `Int`s to `NSDate` and `NSTimeInterval`.
*/
public struct TestSchedulerVirtualTimeConverter : VirtualTimeConverterType {
/**
Virtual time unit used that represents ticks of virtual clock.
*/
public typealias VirtualTimeUnit = Int
/**
Virtual time unit used to represent differences of virtual times.
*/
public typealias VirtualTimeIntervalUnit = Int
private let _resolution: Double
init(resolution: Double) {
_resolution = resolution
}
/**
Converts virtual time to real time.
- parameter virtualTime: Virtual time to convert to `NSDate`.
- returns: `NSDate` corresponding to virtual time.
*/
public func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime {
return Date(timeIntervalSince1970: RxTimeInterval(virtualTime) * _resolution)
}
/**
Converts real time to virtual time.
- parameter time: `NSDate` to convert to virtual time.
- returns: Virtual time corresponding to `NSDate`.
*/
public func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit {
return VirtualTimeIntervalUnit(time.timeIntervalSince1970 / _resolution + 0.5)
}
/**
Converts from virtual time interval to `NSTimeInterval`.
- parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`.
- returns: `NSTimeInterval` corresponding to virtual time interval.
*/
public func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval {
return RxTimeInterval(virtualTimeInterval) * _resolution
}
/**
Converts from virtual time interval to `NSTimeInterval`.
- parameter timeInterval: `NSTimeInterval` to convert to virtual time interval.
- returns: Virtual time interval corresponding to time interval.
*/
public func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit {
return VirtualTimeIntervalUnit(timeInterval / _resolution + 0.5)
}
/**
Adds virtual time and virtual time interval.
- parameter time: Virtual time.
- parameter offset: Virtual time interval.
- returns: Time corresponding to time offsetted by virtual time interval.
*/
public func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit {
return time + offset
}
/**
Compares virtual times.
*/
public func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison {
if lhs < rhs {
return .lessThan
}
else if lhs > rhs {
return .greaterThan
}
else {
return .equal
}
}
}
|
mit
|
jihun-kang/ios_a2big_sdk
|
A2bigSDK/NoticeData.swift
|
1
|
750
|
//
// NoticeData.swift
// nextpage
//
// Created by a2big on 2016. 11. 7..
// Copyright © 2016년 a2big. All rights reserved.
//
//import SwiftyJSON
public class NoticeData{
public var notice_no: String!
public var start_date: String!
public var end_date: String!
public var notice_title: String!
public var notice_ment: String!
public var flag: String!
required public init(json: JSON) {
notice_no = json["notice_no"].stringValue
start_date = json["start_date"].stringValue
end_date = json["end_date"].stringValue
notice_title = json["notice_title"].stringValue
notice_ment = json["notice_ment"].stringValue
flag = json["flag"].stringValue
}
}
|
apache-2.0
|
khizkhiz/swift
|
test/ClangModules/optional.swift
|
1
|
2519
|
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules -emit-silgen -o - %s | FileCheck %s
// REQUIRES: objc_interop
import ObjectiveC
import Foundation
import objc_ext
import TestProtocols
class A {
@objc func foo() -> String? {
return ""
}
// CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3foofT_GSqSS_ : $@convention(objc_method) (A) -> @autoreleased Optional<NSString>
// CHECK: [[T0:%.*]] = function_ref @_TFC8optional1A3foofT_GSqSS_
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]](%0)
// CHECK-NEXT: strong_release
// CHECK: [[T2:%.*]] = select_enum [[T1]]
// CHECK-NEXT: cond_br [[T2]]
// Something branch: project value, translate, inject into result.
// CHECK: [[STR:%.*]] = unchecked_enum_data [[T1]]
// CHECK: [[T0:%.*]] = function_ref @swift_StringToNSString
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[STR]])
// CHECK-NEXT: enum $Optional<NSString>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: br
// Nothing branch: inject nothing into result.
// CHECK: enum $Optional<NSString>, #Optional.none!enumelt
// CHECK-NEXT: br
// Continuation.
// CHECK: bb3([[T0:%.*]] : $Optional<NSString>):
// CHECK-NEXT: return [[T0]]
@objc func bar(x x : String?) {}
// CHECK-LABEL: sil hidden [thunk] @_TToFC8optional1A3barfT1xGSqSS__T_ : $@convention(objc_method) (Optional<NSString>, A) -> ()
// CHECK: [[T1:%.*]] = select_enum %0
// CHECK-NEXT: cond_br [[T1]]
// Something branch: project value, translate, inject into result.
// CHECK: [[NSSTR:%.*]] = unchecked_enum_data %0
// CHECK: [[T0:%.*]] = function_ref @swift_NSStringToString
// Make a temporary initialized string that we're going to clobber as part of the conversion process (?).
// CHECK-NEXT: [[NSSTR_BOX:%.*]] = enum $Optional<NSString>, #Optional.some!enumelt.1, [[NSSTR]] : $NSString
// CHECK-NEXT: [[T1:%.*]] = apply [[T0]]([[NSSTR_BOX]])
// CHECK-NEXT: enum $Optional<String>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: br
// Nothing branch: inject nothing into result.
// CHECK: enum $Optional<String>, #Optional.none!enumelt
// CHECK-NEXT: br
// Continuation.
// CHECK: bb3([[T0:%.*]] : $Optional<String>):
// CHECK: [[T1:%.*]] = function_ref @_TFC8optional1A3barfT1xGSqSS__T_
// CHECK-NEXT: [[T2:%.*]] = apply [[T1]]([[T0]], %1)
// CHECK-NEXT: strong_release %1
// CHECK-NEXT: return [[T2]] : $()
}
// rdar://15144951
class TestWeak : NSObject {
weak var b : WeakObject? = nil
}
class WeakObject : NSObject {}
|
apache-2.0
|
borglab/SwiftFusion
|
Sources/SwiftFusionBenchmarks/Pose2SLAM.swift
|
1
|
2035
|
// Copyright 2020 The SwiftFusion Authors. 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.
/// Benchmarks Pose2SLAM solutions.
import _Differentiation
import Benchmark
import SwiftFusion
let pose2SLAM = BenchmarkSuite(name: "Pose2SLAM") { suite in
let intelDataset =
try! G2OReader.G2OFactorGraph(g2oFile2D: try! cachedDataset("input_INTEL_g2o.txt"))
check(
intelDataset.graph.error(at: intelDataset.initialGuess),
near: 0.5 * 73565.64,
accuracy: 1e-2)
// Uses `FactorGraph` on the Intel dataset.
// The solvers are configured to run for a constant number of steps.
// The nonlinear solver is 10 iterations of Gauss-Newton.
// The linear solver is 500 iterations of CGLS.
suite.benchmark(
"FactorGraph, Intel, 10 Gauss-Newton steps, 500 CGLS steps",
settings: Iterations(1), TimeUnit(.ms)
) {
var x = intelDataset.initialGuess
var graph = intelDataset.graph
graph.store(PriorFactor(TypedID(0), Pose2(0, 0, 0)))
for _ in 0..<10 {
let linearized = graph.linearized(at: x)
var dx = x.tangentVectorZeros
var optimizer = GenericCGLS(precision: 0, max_iteration: 500)
optimizer.optimize(gfg: linearized, initial: &dx)
x.move(along: dx)
}
check(graph.error(at: x), near: 0.5 * 0.987, accuracy: 1e-2)
}
}
func check(_ actual: Double, near expected: Double, accuracy: Double) {
if abs(actual - expected) > accuracy {
print("ERROR: \(actual) != \(expected) (accuracy \(accuracy))")
fatalError()
}
}
|
apache-2.0
|
slavapestov/swift
|
validation-test/compiler_crashers_fixed/27981-std-function-func.swift
|
4
|
262
|
// RUN: not %target-swift-frontend %s -parse
// 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 b{{if{class b<T where k=d{class B{var b={
|
apache-2.0
|
stebojan/Calculator
|
Calculator/ViewController.swift
|
1
|
1546
|
//
// ViewController.swift
// Calculator
//
// Created by Bojan Stevanovic on 6/28/15.
// Copyright (c) 2015 Bojan Stevanovic. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber = false
var brain = CalculatorBrain()
@IBAction func appendDigit(sender: UIButton)
{
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
@IBAction func operate(sender: UIButton) {
if userIsInTheMiddleOfTypingANumber {
enter()
}
if let operation = sender.currentTitle {
if let result = brain.performOperation(operation) {
displayValue = result
} else {
displayValue = 0
}
}
}
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
if let result = brain.pushOperand(displayValue) {
displayValue = result
}
else {
displayValue = 0
}
}
var displayValue: Double {
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
|
mit
|
anirudh24seven/wikipedia-ios
|
Wikipedia/Code/WMFWelcomeIntroductionAnimationView.swift
|
1
|
5356
|
import Foundation
public class WMFWelcomeIntroductionAnimationView : WMFWelcomeAnimationView {
lazy var tubeImgView: UIImageView = {
let tubeRotationPoint = CGPointMake(0.576, 0.38)
let initialTubeRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(0.0)
let rectCorrectingForRotation = CGRectMake(
self.bounds.origin.x - (self.bounds.size.width * (0.5 - tubeRotationPoint.x)),
self.bounds.origin.y - (self.bounds.size.height * (0.5 - tubeRotationPoint.y)),
self.bounds.size.width,
self.bounds.size.height
)
let imgView = UIImageView(frame: rectCorrectingForRotation)
imgView.image = UIImage(named: "ftux-telescope-tube")
imgView.contentMode = UIViewContentMode.ScaleAspectFit
imgView.layer.zPosition = 101
imgView.layer.transform = initialTubeRotationTransform
imgView.layer.anchorPoint = tubeRotationPoint
return imgView
}()
lazy var baseImgView: UIImageView = {
let imgView = UIImageView(frame: self.bounds)
imgView.image = UIImage(named: "ftux-telescope-base")
imgView.contentMode = UIViewContentMode.ScaleAspectFit
imgView.layer.zPosition = 101
imgView.layer.transform = CATransform3DIdentity
return imgView
}()
lazy var dashedCircle: WelcomeCircleShapeLayer = {
return WelcomeCircleShapeLayer(
unitRadius: 0.304,
unitOrigin: CGPointMake(0.521, 0.531),
referenceSize: self.frame.size,
isDashed: true,
transform: self.wmf_scaleZeroTransform,
opacity:0.0
)
}()
lazy var solidCircle: WelcomeCircleShapeLayer = {
return WelcomeCircleShapeLayer(
unitRadius: 0.32,
unitOrigin: CGPointMake(0.625, 0.55),
referenceSize: self.frame.size,
isDashed: false,
transform: self.wmf_scaleZeroTransform,
opacity:0.0
)
}()
lazy var plus1: WelcomePlusShapeLayer = {
return WelcomePlusShapeLayer(
unitOrigin: CGPointMake(0.033, 0.219),
unitWidth: 0.05,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroTransform,
opacity: 0.0
)
}()
lazy var plus2: WelcomePlusShapeLayer = {
return WelcomePlusShapeLayer(
unitOrigin: CGPointMake(0.11, 0.16),
unitWidth: 0.05,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroTransform,
opacity: 0.0
)
}()
lazy var line1: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.91, 0.778),
unitWidth: 0.144,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndRightTransform,
opacity: 0.0
)
}()
lazy var line2: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.836, 0.81),
unitWidth: 0.06,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndRightTransform,
opacity: 0.0
)
}()
lazy var line3: WelcomeLineShapeLayer = {
return WelcomeLineShapeLayer(
unitOrigin: CGPointMake(0.907, 0.81),
unitWidth: 0.0125,
referenceSize: self.frame.size,
transform: self.wmf_scaleZeroAndRightTransform,
opacity: 0.0
)
}()
override public func addAnimationElementsScaledToCurrentFrameSize(){
removeExistingSubviewsAndSublayers()
self.addSubview(self.baseImgView)
self.addSubview(self.tubeImgView)
_ = [
self.solidCircle,
self.dashedCircle,
self.plus1,
self.plus2,
self.line1,
self.line2,
self.line3
].map({ (layer: CALayer) -> () in
self.layer.addSublayer(layer)
})
}
override public func beginAnimations() {
CATransaction.begin()
let tubeOvershootRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(15.0)
let tubeFinalRotationTransform = CATransform3D.wmf_rotationTransformWithDegrees(-2.0)
tubeImgView.layer.wmf_animateToOpacity(1.0,
transform:tubeOvershootRotationTransform,
delay: 0.8,
duration: 0.9
)
tubeImgView.layer.wmf_animateToOpacity(1.0,
transform:tubeFinalRotationTransform,
delay: 1.8,
duration: 0.9
)
self.solidCircle.wmf_animateToOpacity(0.09,
transform: CATransform3DIdentity,
delay: 0.3,
duration: 1.0
)
let animate = { (layer: CALayer) -> () in
layer.wmf_animateToOpacity(0.15,
transform: CATransform3DIdentity,
delay: 0.3,
duration: 1.0
)
}
_ = [
self.dashedCircle,
self.plus1,
self.plus2,
self.line1,
self.line2,
self.line3
].map(animate)
CATransaction.commit()
}
}
|
mit
|
jkereako/LoginView
|
Source/BubblePresentationAnimator.swift
|
1
|
3652
|
//
// BubblePresentationAnimator.swift
//
// Created by Andrea Mazzini on 04/04/15.
// Copyright (c) 2015 Fancy Pixel. All rights reserved.
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Andrea Mazzini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
final class BubblePresentationAnimator: NSObject {
let origin: CGPoint
let backgroundColor: UIColor
init(origin: CGPoint = .zero, backgroundColor: UIColor = .clear) {
self.origin = origin
self.backgroundColor = backgroundColor
}
}
// MARK: - UIViewControllerAnimatedTransitioning
extension BubblePresentationAnimator: UIViewControllerAnimatedTransitioning {
private func frameForBubble(originalCenter: CGPoint, size originalSize: CGSize,
start: CGPoint) -> CGRect {
let lengthX = fmax(start.x, originalSize.width - start.x);
let lengthY = fmax(start.y, originalSize.height - start.y)
let offset = sqrt(lengthX * lengthX + lengthY * lengthY) * 2;
let size = CGSize(width: offset, height: offset)
return CGRect(origin: .zero, size: size)
}
func transitionDuration(
using transitionContext: UIViewControllerContextTransitioning?) ->
TimeInterval {
return 0.5
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let to = transitionContext.view(forKey: UITransitionContextViewKey.to)
let originalCenter = to?.center ?? .zero
let originalSize = to?.frame.size ?? .zero
let bubble = UIView()
bubble.frame = frameForBubble(
originalCenter: originalCenter, size: originalSize, start: .zero
)
bubble.layer.cornerRadius = bubble.frame.size.height / 2
bubble.center = origin
bubble.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
bubble.backgroundColor = backgroundColor
transitionContext.containerView.addSubview(bubble)
to?.center = origin
to?.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
to?.alpha = 0
transitionContext.containerView.addSubview(to ?? UIView())
UIView.animate(
withDuration: 0.5,
animations: {
bubble.transform = .identity
to?.transform = .identity
to?.alpha = 1
to?.center = originalCenter
},
completion: { (done: Bool) in
transitionContext.completeTransition(true)
}
)
}
}
|
mit
|
Jakintosh/WWDC-2015-Application
|
Jak-Tiano/Jak-TianoTests/Jak_TianoTests.swift
|
1
|
901
|
//
// Jak_TianoTests.swift
// Jak-TianoTests
//
// Created by Jak Tiano on 4/23/15.
// Copyright (c) 2015 jaktiano. All rights reserved.
//
import UIKit
import XCTest
class Jak_TianoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
wj2061/ios7ptl-swift3.0
|
ch22-KVC/KVC/KVC/ViewController.swift
|
1
|
486
|
//
// ViewController.swift
// KVC
//
// Created by wj on 15/11/29.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
dnevera/ImageMetalling
|
ImageMetalling-16/ImageMetalling-16/Classes/Common/IMPFilterView.swift
|
1
|
8786
|
//
// IMPCanvasView.swift
// ImageMetalling-16
//
// Created by denis svinarchuk on 21.06.2018.
// Copyright © 2018 ImageMetalling. All rights reserved.
//
import Cocoa
import MetalKit
import IMProcessing
import IMProcessingUI
open class IMPFilterView: MTKView {
public var name:String?
public var debug:Bool = false
public var placeHolderColor:NSColor? {
didSet{
if let color = placeHolderColor{
__placeHolderColor = color.rgba
}
else {
__placeHolderColor = float4(0.5)
}
}
}
open weak var filter:IMPFilter? = nil {
willSet{
filter?.removeObserver(destinationUpdated: destinationObserver)
filter?.removeObserver(newSource: sourceObserver)
}
didSet {
filter?.addObserver(destinationUpdated: destinationObserver)
filter?.addObserver(newSource: sourceObserver)
}
}
public var image:IMPImageProvider? {
return _image
}
public override init(frame frameRect: CGRect, device: MTLDevice?=nil) {
super.init(frame: frameRect, device: device ?? MTLCreateSystemDefaultDevice())
configure()
}
public required init(coder: NSCoder) {
super.init(coder: coder)
device = MTLCreateSystemDefaultDevice()
configure()
}
open override var frame: NSRect {
didSet{
self.filter?.dirty = true
}
}
open override func setNeedsDisplay(_ invalidRect: NSRect) {
super.setNeedsDisplay(invalidRect)
self.filter?.dirty = true
}
open func configure() {
delegate = self
isPaused = false
enableSetNeedsDisplay = false
framebufferOnly = true
postsBoundsChangedNotifications = true
postsFrameChangedNotifications = true
clearColor = MTLClearColorMake(0, 0, 0, 0)
}
private var _image:IMPImageProvider? {
didSet{
refreshQueue.async(flags: [.barrier]) {
self.__source = self.image
if self.image == nil /*&& self.__placeHolderColor == nil*/ {
return
}
if self.isPaused {
self.draw()
}
}
}
}
private var __source:IMPImageProvider?
private var __placeHolderColor = float4(1)
private lazy var destinationObserver:IMPFilter.UpdateHandler = {
let handler:IMPFilter.UpdateHandler = { (destination) in
if self.isPaused {
self._image = destination
self.needProcessing = true
}
}
return handler
}()
private lazy var sourceObserver:IMPFilter.SourceUpdateHandler = {
let handler:IMPFilter.SourceUpdateHandler = { (source) in
self.needProcessing = true
}
return handler
}()
private var needProcessing = true
private lazy var commandQueue:MTLCommandQueue = self.device!.makeCommandQueue(maxCommandBufferCount: IMPFilterView.maxFrames)!
private static let maxFrames = 1
private let mutex = DispatchSemaphore(value: IMPFilterView.maxFrames)
private var framesTimeout:UInt64 = 5
fileprivate func refresh(){
self.filter?.context.runOperation(.async, {
if let filter = self.filter, filter.dirty || self.needProcessing {
self.__source = filter.destination
self.needProcessing = false
if self.debug {
Swift.print("View[\((self.name ?? "-"))] filter = \(filter, self.__source, self.__source?.size)")
}
}
else {
return
}
guard
let pipeline = ((self.__source?.texture == nil) ? self.placeHolderPipeline : self.pipeline),
let commandBuffer = self.commandQueue.makeCommandBuffer() else {
return
}
if !self.isPaused {
guard self.mutex.wait(timeout: DispatchTime(uptimeNanoseconds: 1000000000 * self.framesTimeout)) == .success else {
return
}
}
self.render(commandBuffer: commandBuffer, texture: self.__source?.texture, with: pipeline){
if !self.isPaused {
self.mutex.signal()
}
}
})
}
fileprivate func render(commandBuffer:MTLCommandBuffer, texture:MTLTexture?, with pipeline: MTLRenderPipelineState,
complete: @escaping () -> Void) {
commandBuffer.label = "Frame command buffer"
commandBuffer.addCompletedHandler{ commandBuffer in
complete()
return
}
if let currentDrawable = self.currentDrawable,
let renderPassDescriptor = currentRenderPassDescriptor,
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor){
renderEncoder.label = "IMPProcessingView"
renderEncoder.setRenderPipelineState(pipeline)
renderEncoder.setVertexBuffer(vertexBuffer, offset:0, index:0)
if let texture = texture {
renderEncoder.setFragmentTexture(texture, index:0)
}
else {
renderEncoder.setFragmentBytes(&__placeHolderColor, length: MemoryLayout.size(ofValue: __placeHolderColor), index: 0)
}
renderEncoder.drawPrimitives(type: .triangleStrip, vertexStart:0, vertexCount:4, instanceCount:1)
renderEncoder.endEncoding()
commandBuffer.present(currentDrawable)
commandBuffer.commit()
commandBuffer.waitUntilCompleted()
}
else {
complete()
}
}
private static var library = MTLCreateSystemDefaultDevice()!.makeDefaultLibrary()!
private lazy var fragment = IMPFilterView.library.makeFunction(name: "fragment_passview")
private lazy var fragmentPlaceHolder = IMPFilterView.library.makeFunction(name: "fragment_placeHolderView")
private lazy var vertex = IMPFilterView.library.makeFunction(name: "vertex_passview")
private lazy var pipeline:MTLRenderPipelineState? = {
do {
let descriptor = MTLRenderPipelineDescriptor()
descriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat
descriptor.vertexFunction = self.vertex
descriptor.fragmentFunction = self.fragment
return try self.device!.makeRenderPipelineState(descriptor: descriptor)
}
catch let error as NSError {
NSLog("IMPView error: \(error)")
return nil
}
}()
private lazy var placeHolderPipeline:MTLRenderPipelineState? = {
do {
let descriptor = MTLRenderPipelineDescriptor()
descriptor.colorAttachments[0].pixelFormat = self.colorPixelFormat
descriptor.vertexFunction = self.vertex
descriptor.fragmentFunction = self.fragmentPlaceHolder
return try self.device!.makeRenderPipelineState(descriptor: descriptor)
}
catch let error as NSError {
NSLog("IMPView error: \(error)")
return nil
}
}()
private static let viewVertexData:[Float] = [
-1.0, -1.0, 0.0, 1.0,
1.0, -1.0, 1.0, 1.0,
-1.0, 1.0, 0.0, 0.0,
1.0, 1.0, 1.0, 0.0,
]
private lazy var vertexBuffer:MTLBuffer? = {
let v = self.device?.makeBuffer(bytes: IMPFilterView.viewVertexData, length: MemoryLayout<Float>.size*IMPFilterView.viewVertexData.count, options: [])
v?.label = "Vertices"
return v
}()
public var refreshQueue = DispatchQueue(label: String(format: "com.dehancer.metal.view.refresh-%08x%08x", arc4random(), arc4random()))
}
extension IMPFilterView: MTKViewDelegate {
public func mtkView(_ view: MTKView, drawableSizeWillChange size: CGSize) {}
public func draw(in view: MTKView) {
self.refresh()
}
}
|
mit
|
huangboju/Moots
|
UICollectionViewLayout/uicollectionview-layouts-kit-master/insta-grid/Core/Cell/InstagridCollectionViewCell.swift
|
1
|
1573
|
//
// InstagridCollectionViewCell.swift
// insta-grid
//
// Created by Astemir Eleev on 18/04/2018.
// Copyright © 2018 Astemir Eleev. All rights reserved.
//
import UIKit
class InstagridCollectionViewCell: UICollectionViewCell {
// MARK: - Static properties
static let reusableId = "image-cell"
// MARK: - Properties
var imageName: String = "" {
didSet {
imageView.image = UIImage(named: imageName)
}
}
// MARK: - Outlets
@IBOutlet weak var imageView: UIImageView!
// MARK: - Overrides
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
prepare()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
// MARK: - Methods
override func awakeFromNib() {
super.awakeFromNib()
imageView.contentMode = .scaleAspectFill
}
override class var requiresConstraintBasedLayout: Bool {
return true
}
override func prepareForReuse() {
contentView.backgroundColor = .black
imageView.image = nil
}
// MARK: - Helpers
private func prepare() {
contentView.layer.cornerRadius = 5.0
contentView.layer.borderColor = UIColor.white.cgColor
contentView.layer.borderWidth = 1.0
contentView.layer.shouldRasterize = true
contentView.layer.rasterizationScale = UIScreen.main.scale
contentView.clipsToBounds = true
}
}
|
mit
|
barijaona/vienna-rss
|
Vienna Tests/ArticleTests.swift
|
4
|
9872
|
//
// ArticleTests.swift
// Vienna Tests
//
// Copyright 2020
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
class ArticleTests: XCTestCase {
let guid = "07f446d2-8d6b-4d99-b488-cebc9eac7c33"
let author = "Author McAuthorface"
let title = "Lorem ipsum dolor sit amet"
let link = "http://www.vienna-rss.com"
let enclosure = "http://vienna-rss.sourceforge.net/img/vienna_logo.png"
let enclosureFilename = "vienna_logo.png" // last path component of Enclosure
let body = """
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus
et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae,
ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas
semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend
leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat
wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi.
Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci,
sagittis tempus lacus enim ac dui. <a href="#">Donec non enim</a> in turpis
pulvinar facilisis. Ut felis.</p>
"""
var article: Article!
var articleConverter: WebKitArticleConverter!
override func setUpWithError() throws {
try super.setUpWithError()
// Put setup code here. This method is called before the invocation of each test method in the class.
self.article = Article(guid: guid)
self.articleConverter = WebKitArticleConverter()
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
self.article = nil
try super.tearDownWithError()
}
// MARK: Article Tests
func testAccessInstanceVariablesDirectly() {
XCTAssertFalse(Article.accessInstanceVariablesDirectly)
}
// MARK: - Test custom setters
func testTitle() {
self.article.title = title
XCTAssertEqual(self.article.title, title)
}
func testAuthor() {
self.article.author = author
XCTAssertEqual(self.article.author, author)
}
func testLink() {
self.article.link = link
XCTAssertEqual(self.article.link, link)
}
func testDate() {
let date = Date()
self.article.date = date
XCTAssertEqual(self.article.date, date)
}
func testDateCreated() {
let date = Date()
self.article.createdDate = date
XCTAssertEqual(self.article.createdDate, date)
}
func testBody() {
self.article.body = body
XCTAssertEqual(self.article.body, body)
}
func testEnclosure() {
self.article.enclosure = enclosure
XCTAssertEqual(self.article.enclosure, enclosure)
}
func testEnclosureRemoval() {
self.article.enclosure = nil
XCTAssertNil(self.article.enclosure)
}
func testHasEnclosure() {
self.article.hasEnclosure = true
XCTAssert(self.article.hasEnclosure)
}
func testFolderId() {
let folderId = 111
self.article.folderId = folderId
XCTAssertEqual(self.article.folderId, folderId)
}
func testGuid() {
self.article.guid = guid
XCTAssertEqual(self.article.guid, guid)
}
func testParentId() {
let parentId = 222
self.article.parentId = parentId
XCTAssertEqual(self.article.parentId, parentId)
}
func testStatus() {
let status = ArticleStatus.new.rawValue
self.article.status = status
XCTAssertEqual(self.article.status, status)
}
func testMarkRead() {
XCTAssertFalse(self.article.isRead)
self.article.markRead(true)
XCTAssert(self.article.isRead)
}
func testMarkRevised() {
XCTAssertFalse(self.article.isRevised)
self.article.markRevised(true)
XCTAssert(self.article.isRevised)
}
func testMarkDeleted() {
XCTAssertFalse(self.article.isDeleted)
self.article.markDeleted(true)
XCTAssert(self.article.isDeleted)
}
func testMarkFlagged() {
XCTAssertFalse(self.article.isFlagged)
self.article.markFlagged(true)
XCTAssert(self.article.isFlagged)
}
func testMarkEnclosureDowloaded() {
XCTAssertFalse(self.article.enclosureDownloaded)
self.article.markEnclosureDownloaded(true)
XCTAssert(self.article.enclosureDownloaded)
}
func testCompatibilityDate() {
let date = Date()
let dateKeyPath = "articleData." + MA_Field_Date
self.article.date = date
XCTAssertEqual(self.article.value(forKeyPath: dateKeyPath) as? Date, date)
}
func testCompatibilityAuthor() {
let authorKeyPath = "articleData." + MA_Field_Author
self.article.author = author
XCTAssertEqual(self.article.value(forKeyPath: authorKeyPath) as? String, author)
}
func testCompatibilitySubject() {
let subject = "Lorem ipsum dolor sit amet"
let subjectKeyPath = "articleData." + MA_Field_Subject
self.article.title = subject
XCTAssertEqual(self.article.value(forKeyPath: subjectKeyPath) as? String, subject)
}
func testCompatibilityLink() {
let link = "http://www.vienna-rss.com"
let linkKeyPath = "articleData." + MA_Field_Link
self.article.link = link
XCTAssertEqual(self.article.value(forKeyPath: linkKeyPath) as? String, link)
}
func testCompatibilitySummary() {
let summary = "Lorem ipsum dolor sit amet"
let summaryKeyPath = "articleData." + MA_Field_Summary
self.article.body = summary
XCTAssertEqual(self.article.value(forKeyPath: summaryKeyPath) as? String, summary)
}
// func testRandomCompatibilityKeyPath() {
// let randomArticleDataKeyPath = "articleData.dummyProperty"
//
// XCTAssertThrowsSpecificNamed(self.article.value(forKeyPath: randomArticleDataKeyPath), NSException, NSUndefinedKeyException);
// }
// func testRandomKeyPath() {
// let randomKeyPath = "dummyProperty"
//
// XCTAssertThrowsSpecificNamed(self.article.value(forKeyPath: randomKeyPath), NSException, NSUndefinedKeyException);
// }
func testDescription() {
let title = "Lorem ipsum dolor sit amet"
self.article.guid = guid
self.article.title = title
let expectedDescription = String(format: "{GUID=%@ title=\"%@\"", guid, title)
XCTAssertEqual(self.article.description, expectedDescription)
}
// MARK: - Expand tags
func testExpandLinkTag() {
let string = "$ArticleLink$/development"
let expectedString = link + "/development"
self.article.link = link
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testExpandTitleTag() {
let string = "$ArticleTitle$"
let expectedString = title
self.article.title = title
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testExpandArticleBodyTag() {
let string = "$ArticleBody$"
let expectedString = body
self.article.body = body
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testExpandArticleAuthorTag() {
let string = "$ArticleAuthor$"
let expectedString = author
self.article.author = author
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testExpandArticleEnclosureLinkTag() {
let string = "$ArticleEnclosureLink$"
let expectedString = enclosure
self.article.enclosure = enclosure
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testExpandArticleEnclosureFileName() {
let string = "$ArticleEnclosureFilename$"
let expectedString = enclosureFilename
self.article.enclosure = enclosure
let expandedString = self.articleConverter.expandTags(of: self.article, intoTemplate: string, withConditional: true)
XCTAssertEqual(expandedString, expectedString)
}
func testURLIDNinArticleView() {
self.article.link = "http://ουτοπία.δπθ.gr/نجيب_محفوظ/"
let htmlTextFromIDNALink = self.articleConverter.articleText(from: [ self.article ])
self.article.link = "http://xn--kxae4bafwg.xn--pxaix.gr/%D9%86%D8%AC%D9%8A%D8%A8_%D9%85%D8%AD%D9%81%D9%88%D8%B8/"
let htmlTextFromResolvedIDNALink = self.articleConverter.articleText(from: [ self.article ])
XCTAssertEqual(htmlTextFromIDNALink, htmlTextFromResolvedIDNALink)
}
}
|
apache-2.0
|
tectijuana/patrones
|
Bloque1SwiftArchivado/PracticasSwift/LardizabalJuan/practica6.swift
|
1
|
1107
|
/*
.__ _____ __
________ _ _|__|/ ____\/ |_
/ ___/\ \/ \/ / \ __\\ __\
\___ \ \ /| || | | |
/____ > \/\_/ |__||__| |__|
\/
Programa 6
Descripcion : Resolver un sistema de ecuaciones
Nombre: Lardizabal Ramirez Juan Carlos
*/
var a:[Int] = [2,3,-4]
var b:[Int] = [4,-2,5]
var c:[Int] = [-5,-2,3]
var d:[Int] = [3,-14,-10]
var det = 0, detx = 0, dety = 0, detz = 0, x=0, y=0, z=0
det = ((a[1] * ((b[2] * c[3]) - (b[3] * c[2]))) - (b[1] * ((a[2] * c[3]) - (a[3] * c[2]))) + (c[1] * ((a[2] * b[3]) - (a[3] * b[2]))))
detx = ((d[1] * ((b[2] * c[3]) - (b[3] * c[2]))) - (b[1] * ((d[2] * c[3]) - (d[3] * c[2]))) + (c[1] * ((d[2] * b[3]) - (d[3] * b[2]))))
dety = ((a[1] * ((d[2] * c[3]) - (d[3] * c[2]))) - (d[1] * ((a[2] * c[3]) - (a[3] * c[2]))) + (c[1] * ((a[2] * d[3]) - (a[3] * d[2]))))
detz = ((a[1] * ((b[2] * d[3]) - (b[3] * d[2]))) - (b[1] * ((a[2] * d[3]) - (a[3] * d[2]))) + (d[1] * ((a[2] * b[3]) - (a[3] * b[2]))))
x = detx / det
y = dety / det
z = detz / det
print ("x = ", x)
print ("y = ", y)
print ("z = ", z)
|
gpl-3.0
|
mmrmmlrr/ExamMaster
|
ExamMaster/Kit Decoration/AppSessionControllerConfiguration.swift
|
1
|
461
|
//
// AppServiceLocatorConfiguration.swift
// ExamMaster
//
// Created by aleksey on 27.02.16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import Foundation
import ModelsTreeKit
extension SessionControllerConfiguration {
static func appConfiguration() -> SessionControllerConfiguration {
return SessionControllerConfiguration(
keychainAccessKey: "ExamMaster",
credentialsPrimaryKey: AppCredentialsKeys.Uid)
}
}
|
mit
|
mightydeveloper/swift
|
test/SILGen/writeback.swift
|
10
|
8295
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(inout x x: Foo) {}
func bas(inout x x: Foo)(inout y: Foo) {}
func zim(inout x x: Foo)(inout y: Foo) -> (inout z: Foo) -> () {
return { (inout z: Foo) in }
}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[FOO:%.*]] = function_ref @_TFV9writeback3Foo3foo{{.*}} : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [[X_TEMP]]#1
// CHECK: apply [[FOO]]([[X_TEMP]]#1) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [[X_TEMP]]#1 : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]]#0 : $*@local_storage Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[BAR:%.*]] = function_ref @_TF9writeback3barFT1xRVS_3Foo_T_ : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [[X_TEMP]]#1 : $*Foo
// CHECK: apply [[BAR]]([[X_TEMP]]#1) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [[X_TEMP]]#1 : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]]#0 : $*@local_storage Foo
// Writeback to curried arguments
bas(x: &x)(y: &y)
// CHECK: [[BAS:%.*]] = function_ref @_TF9writeback3basfT1xRVS_3Foo_FT1yRS0__T_ : $@convention(thin) (@inout Foo, @inout Foo) -> ()
// CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo
// CHECK: {{%.*}} = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: [[GET_Y:%.*]] = function_ref @_TF9writebackg1yVS_3Foo : $@convention(thin) () -> Foo
// CHECK: {{%.*}} = apply [[GET_Y]]() : $@convention(thin) () -> Foo
// CHECK: apply [[BAS]]({{%.*}}, {{%.*}}) : $@convention(thin) (@inout Foo, @inout Foo) -> ()
// CHECK: [[SET_Y:%.*]] = function_ref @_TF9writebacks1yVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_Y]]({{%.*}}) : $@convention(thin) (Foo) -> ()
// CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]({{%.*}}) : $@convention(thin) (Foo) -> ()
// Writeback to curried arguments to function that returns a function
zim(x: &x)(y: &y)(z: &z)
// CHECK: [[ZIM:%.*]] = function_ref @_TF9writeback3zimfT1xRVS_3Foo_FT1yRS0__FT1zRS0__T_ : $@convention(thin) (@inout Foo, @inout Foo) -> @owned @callee_owned (@inout Foo) -> ()
// CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo
// CHECK: {{%.*}} = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: [[GET_Y:%.*]] = function_ref @_TF9writebackg1yVS_3Foo : $@convention(thin) () -> Foo
// CHECK: {{%.*}} = apply [[GET_Y]]() : $@convention(thin) () -> Foo
// CHECK: [[ZIM2:%.*]] = apply [[ZIM]]({{%.*}}, {{%.*}}) : $@convention(thin) (@inout Foo, @inout Foo) -> @owned @callee_owned (@inout Foo) -> ()
// CHECK: [[SET_Y:%.*]] = function_ref @_TF9writebacks1yVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_Y]]({{%.*}}) : $@convention(thin) (Foo) -> ()
// CHECK: [[SET_X:%.*]] = function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]({{%.*}}) : $@convention(thin) (Foo) -> ()
// CHECK: [[GET_Z:%.*]] = function_ref @_TF9writebackg1zVS_3Foo : $@convention(thin) () -> Foo
// CHECK: {{%.*}} = apply [[GET_Z]]() : $@convention(thin) () -> Foo
// CHECK: apply [[ZIM2]]({{%.*}}) : $@callee_owned (@inout Foo) -> ()
// CHECK: [[SET_Z:%.*]] = function_ref @_TF9writebacks1zVS_3Foo : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_Z]]({{%.*}}) : $@convention(thin) (Foo) -> ()
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @_TF9writeback4zangFT1xVS_3Foo_T_ : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_TF9writebacks1xVS_3Foo
zang(x: readonly)
// CHECK: function_ref @_TF9writeback4zangFT1xVS_3Foo_T_ : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_TF9writebacks8readonlyVS_3Foo
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[BAR:%.*]] = function_ref @_TF9writeback3barFT1xRVS_3Foo_T_ : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[ZUNG:%.*]] = function_ref @_TF9writeback4zungFT_Si : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @_TF9writebackg1xVS_3Foo : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_TFV9writeback3Foog9subscript{{.*}} : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_TFV9writeback3Foos9subscript{{.*}} : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @_TF9writebacks1xVS_3Foo : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(inout x x: Fungible) {}
funge(x: &addressOnly)
// CHECK: [[FUNGE:%.*]] = function_ref @_TF9writeback5fungeFT1xRPS_8Fungible__T_ : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
// CHECK: [[GET:%.*]] = function_ref @_TF9writebackg11addressOnlyPS_8Fungible_ : $@convention(thin) (@out Fungible) -> ()
// CHECK: apply [[GET]]([[TEMP]]#1) : $@convention(thin) (@out Fungible) -> ()
// CHECK: apply [[FUNGE]]([[TEMP]]#1) : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @_TF9writebacks11addressOnlyPS_8Fungible_ : $@convention(thin) (@in Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]#1) : $@convention(thin) (@in Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]]#0 : $*@local_storage Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
typealias Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
typealias Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden @_TF9writeback12test_generic
// CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1
func test_generic<Runce: Runcible>(inout runce runce: Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden @_TF9writeback15loadAddressOnlyFT_PS_8Fungible_ : $@convention(thin) (@out Fungible) -> () {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden @_TF9writeback10loadMember
// CHECK: witness_method $Runce, #Runcible.frob!getter.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
|
apache-2.0
|
huonw/swift
|
validation-test/stdlib/Slice/MutableSlice_Of_DefaultedMutableCollection_FullWidth.swift
|
34
|
3425
|
// -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Slice/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
// FIXME: the test is too slow when the standard library is not optimized.
// REQUIRES: optimized_stdlib
import StdlibUnittest
import StdlibCollectionUnittest
var SliceTests = TestSuite("Collection")
let prefix: [Int] = []
let suffix: [Int] = []
func makeCollection(elements: [OpaqueValue<Int>])
-> MutableSlice<DefaultedMutableCollection<OpaqueValue<Int>>> {
var baseElements = prefix.map(OpaqueValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(OpaqueValue.init))
let base = DefaultedMutableCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return MutableSlice(
base: base,
bounds: startIndex..<endIndex)
}
func makeCollectionOfEquatable(elements: [MinimalEquatableValue])
-> MutableSlice<DefaultedMutableCollection<MinimalEquatableValue>> {
var baseElements = prefix.map(MinimalEquatableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalEquatableValue.init))
let base = DefaultedMutableCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return MutableSlice(
base: base,
bounds: startIndex..<endIndex)
}
func makeCollectionOfComparable(elements: [MinimalComparableValue])
-> MutableSlice<DefaultedMutableCollection<MinimalComparableValue>> {
var baseElements = prefix.map(MinimalComparableValue.init)
baseElements.append(contentsOf: elements)
baseElements.append(contentsOf: suffix.map(MinimalComparableValue.init))
let base = DefaultedMutableCollection(elements: baseElements)
let startIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count))
let endIndex = base.index(
base.startIndex,
offsetBy: numericCast(prefix.count + elements.count))
return MutableSlice(
base: base,
bounds: startIndex..<endIndex)
}
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptOnOutOfBoundsIndicesBehavior = .trap
resiliencyChecks.subscriptRangeOnOutOfBoundsRangesBehavior = .trap
SliceTests.addMutableCollectionTests(
"MutableSlice_Of_DefaultedMutableCollection_FullWidth.swift.",
makeCollection: makeCollection,
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: makeCollectionOfEquatable,
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: makeCollectionOfComparable,
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks,
outOfBoundsIndexOffset: 6
, withUnsafeMutableBufferPointerIsSupported: false,
isFixedLengthCollection: true
)
runAllTests()
|
apache-2.0
|
ryanbaldwin/Restivus
|
Sources/HTTPURLResponse+Extensions.swift
|
1
|
1689
|
//
// HTTPURLResponse+Extensions.swift
// Restivus
//
// Created by Ryan Baldwin on 2017-08-21.
// Copyright © 2017 bunnyhug.me. All rights governed under the Apache 2 License Agreement
//
import Foundation
extension HTTPURLResponse {
/// A textual representation of this instance, suitable for debugging.
open override var debugDescription: String {
var fields: [String] = ["\nResponse:", "==============="]
fields.append("Response Code: \(self.statusCode)")
if allHeaderFields.count > 0 {
fields.append("Headers:")
allHeaderFields.forEach { (key, val) in fields.append("\t\(key): \(val)") }
}
return fields.joined(separator: "\n")
}
/// True if this response code is a member of the 1xx Informational set of codes; otherwise false
public var isInformational: Bool {
return 100...199 ~= statusCode
}
/// True if this response code is a member of the 2xx Success response codes; otherwise false
public var isSuccess: Bool {
return 200...299 ~= statusCode
}
/// True if this response code is a member of the 3xx Redirection response codes; otherwise false
public var isRedirection: Bool {
return 300...399 ~= statusCode
}
/// True if this response code is a member of the 4xx Client Error response codes; otherwise false
public var isClientError: Bool {
return 400...499 ~= statusCode
}
/// True if this response code is a member of the 5xx Server Error response codes; otherwise false
public var isServerError: Bool {
return 500...599 ~= statusCode
}
}
|
apache-2.0
|
deltaDNA/ios-smartads-sdk
|
IntegrationTester/DetailViewController.swift
|
1
|
3286
|
//
// Copyright (c) 2017 deltaDNA Ltd. 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
class DetailViewController: UIViewController {
@IBOutlet weak var logoImageView: UIImageView!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var resultLabel: VerticalTopAlignLabel!
@IBOutlet weak var showedSwitch: UISwitch!
@IBOutlet weak var clickedSwitch: UISwitch!
@IBOutlet weak var leftApplicationSwitch: UISwitch!
@IBOutlet weak var closedSwitch: UISwitch!
@IBOutlet weak var adsShown: UILabel!
@IBOutlet weak var rewardedLabel: UILabel!
@IBAction func requestAd(_ sender: AnyObject) {
self.adNetwork?.requestAd()
}
@IBAction func showAd(_ sender: AnyObject) {
self.adNetwork?.showAd(viewController: self)
}
var adNetwork: AdNetwork! {
willSet (newAdNetwork) {
adNetwork?.delegate = nil
}
didSet {
adNetwork?.delegate = self
self.refreshUI()
}
}
override func viewDidLoad() {
super.viewDidLoad()
refreshUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func refreshUI() {
if let adNetwork = adNetwork {
logoImageView?.image = adNetwork.logo()
versionLabel?.text = adNetwork.version()
nameLabel?.text = adNetwork.name
resultLabel?.text = adNetwork.adResult
showedSwitch?.isOn = adNetwork.showedAd
clickedSwitch?.isOn = adNetwork.clickedAd
leftApplicationSwitch?.isOn = adNetwork.leftApplication
closedSwitch?.isOn = adNetwork.closedAd
adsShown?.text = adNetwork.adCount > 0 ? String(format: "x\(adNetwork.adCount)") : ""
if adNetwork.closedAd {
rewardedLabel?.text = adNetwork.canReward ? "reward" : "no reward"
} else {
rewardedLabel?.text = ""
}
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
extension DetailViewController: AdNetworkSelectionDelegate {
func adNetworkSelected(newAdNetwork: AdNetwork) {
adNetwork = newAdNetwork
}
}
extension DetailViewController: AdNetworkDelegate {
func update() {
refreshUI()
}
}
|
apache-2.0
|
klundberg/swift-corelibs-foundation
|
Foundation/NSError.swift
|
1
|
9249
|
// 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
public let NSCocoaErrorDomain: String = "NSCocoaErrorDomain"
public let NSPOSIXErrorDomain: String = "NSPOSIXErrorDomain"
public let NSOSStatusErrorDomain: String = "NSOSStatusErrorDomain"
public let NSMachErrorDomain: String = "NSMachErrorDomain"
public let NSUnderlyingErrorKey: String = "NSUnderlyingError"
public let NSLocalizedDescriptionKey: String = "NSLocalizedDescription"
public let NSLocalizedFailureReasonErrorKey: String = "NSLocalizedFailureReason"
public let NSLocalizedRecoverySuggestionErrorKey: String = "NSLocalizedRecoverySuggestion"
public let NSLocalizedRecoveryOptionsErrorKey: String = "NSLocalizedRecoveryOptions"
public let NSRecoveryAttempterErrorKey: String = "NSRecoveryAttempter"
public let NSHelpAnchorErrorKey: String = "NSHelpAnchor"
public let NSStringEncodingErrorKey: String = "NSStringEncodingErrorKey"
public let NSURLErrorKey: String = "NSURL"
public let NSFilePathErrorKey: String = "NSFilePathErrorKey"
public class NSError : NSObject, NSCopying, NSSecureCoding, NSCoding {
typealias CFType = CFError
internal var _cfObject: CFType {
return CFErrorCreate(kCFAllocatorSystemDefault, domain._cfObject, code, nil)
}
// ErrorType forbids this being internal
public var _domain: String
public var _code: Int
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
private var _userInfo: [String : Any]?
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public init(domain: String, code: Int, userInfo dict: [String : Any]?) {
_domain = domain
_code = code
_userInfo = dict
}
public required init?(coder aDecoder: NSCoder) {
if aDecoder.allowsKeyedCoding {
_code = aDecoder.decodeInteger(forKey: "NSCode")
_domain = aDecoder.decodeObjectOfClass(NSString.self, forKey: "NSDomain")!._swiftObject
if let info = aDecoder.decodeObjectOfClasses([NSSet.self, NSDictionary.self, NSArray.self, NSString.self, NSNumber.self, NSData.self, NSURL.self], forKey: "NSUserInfo") as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjects([]) {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
} else {
var codeValue: Int32 = 0
aDecoder.decodeValue(ofObjCType: "i", at: &codeValue)
_code = Int(codeValue)
_domain = (aDecoder.decodeObject() as? NSString)!._swiftObject
if let info = aDecoder.decodeObject() as? NSDictionary {
var filteredUserInfo = [String : Any]()
// user info must be filtered so that the keys are all strings
info.enumerateKeysAndObjects([]) {
if let key = $0.0 as? NSString {
filteredUserInfo[key._swiftObject] = $0.1
}
}
_userInfo = filteredUserInfo
}
}
}
public static func supportsSecureCoding() -> Bool {
return true
}
public func encode(with aCoder: NSCoder) {
if aCoder.allowsKeyedCoding {
aCoder.encode(_domain.bridge(), forKey: "NSDomain")
aCoder.encode(Int32(_code), forKey: "NSCode")
aCoder.encode(_userInfo?.bridge(), forKey: "NSUserInfo")
} else {
var codeValue: Int32 = Int32(self._code)
aCoder.encodeValue(ofObjCType: "i", at: &codeValue)
aCoder.encode(self._domain.bridge())
aCoder.encode(self._userInfo?.bridge())
}
}
public override func copy() -> AnyObject {
return copy(with: nil)
}
public func copy(with zone: NSZone? = nil) -> AnyObject {
return self
}
public var domain: String {
return _domain
}
public var code: Int {
return _code
}
/// - Experiment: This is a draft API currently under consideration for official import into Foundation
/// - Note: This API differs from Darwin because it uses [String : Any] as a type instead of [String : AnyObject]. This allows the use of Swift value types.
public var userInfo: [String : Any] {
if let info = _userInfo {
return info
} else {
return Dictionary<String, Any>()
}
}
public var localizedDescription: String {
let desc = userInfo[NSLocalizedDescriptionKey] as? String
return desc ?? "The operation could not be completed"
}
public var localizedFailureReason: String? {
return userInfo[NSLocalizedFailureReasonErrorKey] as? String
}
public var localizedRecoverySuggestion: String? {
return userInfo[NSLocalizedRecoverySuggestionErrorKey] as? String
}
public var localizedRecoveryOptions: [String]? {
return userInfo[NSLocalizedRecoveryOptionsErrorKey] as? [String]
}
public var recoveryAttempter: AnyObject? {
return userInfo[NSRecoveryAttempterErrorKey] as? AnyObject
}
public var helpAnchor: String? {
return userInfo[NSHelpAnchorErrorKey] as? String
}
internal typealias NSErrorProvider = (error: NSError, key: String) -> AnyObject?
internal static var userInfoProviders = [String: NSErrorProvider]()
public class func setUserInfoValueProviderForDomain(_ errorDomain: String, provider: ((NSError, String) -> AnyObject?)?) {
NSError.userInfoProviders[errorDomain] = provider
}
public class func userInfoValueProviderForDomain(_ errorDomain: String) -> ((NSError, String) -> AnyObject?)? {
return NSError.userInfoProviders[errorDomain]
}
}
extension NSError : Swift.Error { }
extension NSError : _CFBridgable { }
extension CFError : _NSBridgable {
typealias NSType = NSError
internal var _nsObject: NSType {
let userInfo = CFErrorCopyUserInfo(self)._swiftObject
var newUserInfo: [String: Any] = [:]
for (key, value) in userInfo {
if let key = key as? NSString {
newUserInfo[key._swiftObject] = value
}
}
return NSError(domain: CFErrorGetDomain(self)._swiftObject, code: CFErrorGetCode(self), userInfo: newUserInfo)
}
}
public protocol _ObjectTypeBridgeableErrorType : Swift.Error {
init?(_bridgedNSError: NSError)
}
public protocol __BridgedNSError : RawRepresentable, Swift.Error {
static var __NSErrorDomain: String { get }
}
public func ==<T: __BridgedNSError where T.RawValue: SignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toIntMax() == rhs.rawValue.toIntMax()
}
public extension __BridgedNSError where RawValue: SignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int { return Int(rawValue.toIntMax()) }
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(IntMax(_bridgedNSError.code)))
}
public final var hashValue: Int { return _code }
}
public func ==<T: __BridgedNSError where T.RawValue: UnsignedInteger>(lhs: T, rhs: T) -> Bool {
return lhs.rawValue.toUIntMax() == rhs.rawValue.toUIntMax()
}
public extension __BridgedNSError where RawValue: UnsignedInteger {
public final var _domain: String { return Self.__NSErrorDomain }
public final var _code: Int {
return Int(bitPattern: UInt(rawValue.toUIntMax()))
}
public init?(rawValue: RawValue) {
self = unsafeBitCast(rawValue, to: Self.self)
}
public init?(_bridgedNSError: NSError) {
if _bridgedNSError.domain != Self.__NSErrorDomain {
return nil
}
self.init(rawValue: RawValue(UIntMax(UInt(_bridgedNSError.code))))
}
public final var hashValue: Int { return _code }
}
public protocol _BridgedNSError : __BridgedNSError, Hashable {
// TODO: Was _NSErrorDomain, but that caused a module error.
static var __NSErrorDomain: String { get }
}
|
apache-2.0
|
benlangmuir/swift
|
test/attr/attr_final.swift
|
22
|
3478
|
// RUN: %target-typecheck-verify-swift
class Super {
final var i: Int { get { return 5 } } // expected-note{{overridden declaration is here}}
final func foo() { } // expected-note{{overridden declaration is here}}
final subscript (i: Int) -> Int { // expected-note{{overridden declaration is here}}
get {
return i
}
}
}
class Sub : Super {
override var i: Int { get { return 5 } } // expected-error{{property overrides a 'final' property}}
override func foo() { } // expected-error{{instance method overrides a 'final' instance method}}
override subscript (i: Int) -> Int { // expected-error{{subscript overrides a 'final' subscript}}
get {
return i
}
}
final override init() {} // expected-error {{'final' modifier cannot be applied to this declaration}} {{3-9=}}
}
struct SomeStruct {
final var i: Int = 1 // expected-error {{only classes and class members may be marked with 'final'}}
final var j: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}}
final func f() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
enum SomeEnum {
final var i: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}}
final func f() {} // expected-error {{only classes and class members may be marked with 'final'}}
}
protocol SomeProtocol {
final var i: Int { get } // expected-error {{only classes and class members may be marked with 'final'}}
final func protoFunc() // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeProtocol {
final var i: Int { return 1 } // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
final func protoExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeStruct {
final func structExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension SomeEnum {
final func enumExtensionFunc() {} // expected-error {{only classes and class members may be marked with 'final'}} {{3-9=}}
}
extension Super {
final func someClassMethod() {} // ok
}
final func global_function() {} // expected-error {{only classes and class members may be marked with 'final'}}
final var global_var: Int = 1 // expected-error {{only classes and class members may be marked with 'final'}}
final
class Super2 {
var i: Int { get { return 5 } } // expected-note{{overridden declaration is here}}
func foo() { } // expected-note{{overridden declaration is here}}
subscript (i: Int) -> Int { // expected-note{{overridden declaration is here}}
get {
return i
}
}
}
class Sub2 : Super2 { //// expected-error{{inheritance from a final class 'Super2'}}
override var i: Int { get { return 5 } } // expected-error{{property overrides a 'final' property}}
override func foo() { } // expected-error{{instance method overrides a 'final' instance method}}
override subscript (i: Int) -> Int { // expected-error{{subscript overrides a 'final' subscript}}
get {
return i
}
}
final override init() {} // expected-error {{'final' modifier cannot be applied to this declaration}} {{3-9=}}
}
struct Box<T> {
final class Super3 {}
}
class Sub3: Box<Int>.Super3 {} // expected-error{{inheritance from a final class 'Box.Super3'}}
|
apache-2.0
|
mazvydasb/40SwiftProjects
|
Project 02/OldPhones/OldPhones/Model/Product.swift
|
1
|
854
|
//
// Product.swift
// OldPhones
//
// Created by Mazvydas Bartasius on 20/09/2017.
// Copyright © 2017 Mazvydas Bartasius. All rights reserved.
//
import Foundation
class Product {
var name: String?
var image: String?
var fullscreenImage: String?
init(name: String, image: String, fullscreenImage: String) {
self.name = name
self.image = image
self.fullscreenImage = fullscreenImage
}
}
let products = [
Product(name: "1907 Wall Set", image: "image-cell1", fullscreenImage: "phone-fullscreen1"),
Product(name: "1921 Dial Phone", image: "image-cell2", fullscreenImage: "phone-fullscreen2"),
Product(name: "1937 Desk Set", image: "image-cell3", fullscreenImage: "phone-fullscreen3"),
Product(name: "1984 Moto Portable", image: "image-cell4", fullscreenImage: "phone-fullscreen4")
]
|
mit
|
yangyu2010/DouYuZhiBo
|
DouYuZhiBo/DouYuZhiBo/Class/Home/View/CollectionHeaderView.swift
|
1
|
923
|
//
// CollectionHeaderView.swift
// DouYuZhiBo
//
// Created by Young on 2017/2/17.
// Copyright © 2017年 YuYang. All rights reserved.
//
import UIKit
import Kingfisher
class CollectionHeaderView: UICollectionReusableView {
@IBOutlet weak var iconImg: UIImageView!
@IBOutlet weak var titLab: UILabel!
@IBOutlet weak var moreBtn: UIButton!
var roomList : RoomListModel? {
didSet {
guard let roomList = roomList else { return }
titLab.text = roomList.tag_name
iconImg.image = UIImage(named: roomList.local_icon)
}
}
}
// MARK: 提供个类方法创建xib的view
extension CollectionHeaderView {
class func headerView() -> CollectionHeaderView {
return Bundle.main.loadNibNamed("CollectionHeaderView", owner: nil, options: nil)?.first as! CollectionHeaderView
}
}
|
mit
|
mxcl/PromiseKit
|
Tests/A+/0.0.0.swift
|
1
|
5753
|
import PromiseKit
import Dispatch
import XCTest
enum Error: Swift.Error {
case dummy // we reject with this when we don't intend to test against it
case sentinel(UInt32)
}
private let timeout: TimeInterval = 10
extension XCTestCase {
func describe(_ description: String, file: StaticString = #file, line: UInt = #line, body: () throws -> Void) {
PromiseKit.conf.Q.map = .main
do {
try body()
} catch {
XCTFail(description, file: file, line: line)
}
}
func specify(_ description: String, file: StaticString = #file, line: UInt = #line, body: ((promise: Promise<Void>, fulfill: () -> Void, reject: (Error) -> Void), XCTestExpectation) throws -> Void) {
let expectation = self.expectation(description: description)
let (pending, seal) = Promise<Void>.pending()
do {
try body((pending, seal.fulfill_, seal.reject), expectation)
waitForExpectations(timeout: timeout) { err in
if let _ = err {
XCTFail("wait failed: \(description)", file: file, line: line)
}
}
} catch {
XCTFail(description, file: file, line: line)
}
}
func testFulfilled(file: StaticString = #file, line: UInt = #line, body: @escaping (Promise<UInt32>, XCTestExpectation, UInt32) -> Void) {
testFulfilled(withExpectationCount: 1, file: file, line: line) {
body($0, $1.first!, $2)
}
}
func testRejected(file: StaticString = #file, line: UInt = #line, body: @escaping (Promise<UInt32>, XCTestExpectation, UInt32) -> Void) {
testRejected(withExpectationCount: 1, file: file, line: line) {
body($0, $1.first!, $2)
}
}
func testFulfilled(withExpectationCount: Int, file: StaticString = #file, line: UInt = #line, body: @escaping (Promise<UInt32>, [XCTestExpectation], UInt32) -> Void) {
let specify = mkspecify(withExpectationCount, file: file, line: line, body: body)
specify("already-fulfilled") { value in
return (.value(value), {})
}
specify("immediately-fulfilled") { value in
let (promise, seal) = Promise<UInt32>.pending()
return (promise, {
seal.fulfill(value)
})
}
specify("eventually-fulfilled") { value in
let (promise, seal) = Promise<UInt32>.pending()
return (promise, {
after(ticks: 5) {
seal.fulfill(value)
}
})
}
}
func testRejected(withExpectationCount: Int, file: StaticString = #file, line: UInt = #line, body: @escaping (Promise<UInt32>, [XCTestExpectation], UInt32) -> Void) {
let specify = mkspecify(withExpectationCount, file: file, line: line, body: body)
specify("already-rejected") { sentinel in
return (Promise(error: Error.sentinel(sentinel)), {})
}
specify("immediately-rejected") { sentinel in
let (promise, seal) = Promise<UInt32>.pending()
return (promise, {
seal.reject(Error.sentinel(sentinel))
})
}
specify("eventually-rejected") { sentinel in
let (promise, seal) = Promise<UInt32>.pending()
return (promise, {
after(ticks: 50) {
seal.reject(Error.sentinel(sentinel))
}
})
}
}
/////////////////////////////////////////////////////////////////////////
private func mkspecify(_ numberOfExpectations: Int, file: StaticString, line: UInt, body: @escaping (Promise<UInt32>, [XCTestExpectation], UInt32) -> Void) -> (String, _ feed: (UInt32) -> (Promise<UInt32>, () -> Void)) -> Void {
return { desc, feed in
let value = arc4random()
let (promise, executeAfter) = feed(value)
let expectations = (1...numberOfExpectations).map {
self.expectation(description: "\(desc) (\($0))")
}
body(promise, expectations, value)
executeAfter()
self.waitForExpectations(timeout: timeout) { err in
if let _ = err {
XCTFail("timed out: \(desc)", file: file, line: line)
}
}
}
}
func mkex() -> XCTestExpectation {
return expectation(description: "")
}
}
func after(ticks: Int, execute body: @escaping () -> Void) {
precondition(ticks > 0)
var ticks = ticks
func f() {
DispatchQueue.main.async {
ticks -= 1
if ticks == 0 {
body()
} else {
f()
}
}
}
f()
}
extension Promise {
func test(onFulfilled: @escaping () -> Void, onRejected: @escaping () -> Void) {
tap { result in
switch result {
case .fulfilled:
onFulfilled()
case .rejected:
onRejected()
}
}.silenceWarning()
}
}
prefix func ++(a: inout Int) -> Int {
a += 1
return a
}
extension Promise {
func silenceWarning() {}
}
#if os(Linux)
import func Glibc.random
func arc4random() -> UInt32 {
return UInt32(random())
}
extension XCTestExpectation {
func fulfill() {
fulfill(#file, line: #line)
}
}
extension XCTestCase {
func wait(for: [XCTestExpectation], timeout: TimeInterval, file: StaticString = #file, line: UInt = #line) {
#if !(swift(>=4.0) && !swift(>=4.1))
let line = Int(line)
#endif
waitForExpectations(timeout: timeout, file: file, line: line)
}
}
#endif
|
mit
|
milseman/swift
|
test/Sanitizers/tsan-norace-deinit-run-time.swift
|
9
|
1178
|
// RUN: %target-swiftc_driver %s -g -sanitize=thread -target %sanitizers-target-triple -o %t_tsan-binary
// RUN: env %env-TSAN_OPTIONS=abort_on_error=0:ignore_interceptors_accesses=1 %target-run %t_tsan-binary 2>&1 | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: objc_interop
// REQUIRES: tsan_runtime
// Test that we do not report a race on deinit; the synchronization is guaranteed by runtime.
import Foundation
public class TestDeallocObject : NSObject {
public var v : Int
public override init() {
v = 1
}
@_semantics("optimize.sil.never")
func unoptimize(_ input : Int) -> Int {
return input
}
func accessMember() {
var local : Int = unoptimize(v)
local += 1
}
deinit {
v = 0
}
}
if (true) {
var tdo : TestDeallocObject = TestDeallocObject()
tdo.accessMember()
// Read the value from a different thread.
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.async {
tdo.accessMember()
}
// Read the value from this thread.
tdo.accessMember()
sleep(1)
// Deinit the value.
}
print("Done.")
// CHECK: Done.
// CHECK-NOT: ThreadSanitizer: data race
|
apache-2.0
|
sadawi/ModelKit
|
ModelKit/Models/Model.swift
|
1
|
23300
|
//
// Model.swift
// APIKit
//
// Created by Sam Williams on 11/7/15.
// Copyright © 2015 Sam Williams. All rights reserved.
//
import Foundation
public typealias Identifier = String
open class ModelValueTransformerContext: ValueTransformerContext {
/**
An object that is responsible for keeping track of canonical instances
*/
public var registry:ModelRegistry? = MemoryRegistry()
}
public extension ValueTransformerContext {
static let defaultModelContext = ModelValueTransformerContext(name: "model")
}
open class Model: NSObject, NSCopying, Observable, Blankable {
/**
The class to instantiate, based on a dictionary value. For example, your dictionary might include a "type" string.
Whatever class you attempt to return must be cast to T.Type, which is inferred to be Self.
In other words, if you don't return a subclass, it's likely that you'll silently get an instance of
whatever class defines this method.
*/
open class func instanceClass<T>(for dictionaryValue: AttributeDictionary) -> T.Type? {
return self as? T.Type
}
private static var prototypes = TypeDictionary<Model>()
private static func prototype<T: Model>(for type: T.Type) -> T {
if let existing = prototypes[type] as? T {
return existing
} else {
let prototype = type.init()
prototypes[type] = prototype
return prototype
}
}
/**
Attempts to instantiate a new object from a dictionary representation of its attributes.
If a registry is set, will attempt to reuse the canonical instance for its identifier
- parameter dictionaryValue: The attributes
- parameter configure: A closure to configure a deserialized model, taking a Bool flag indicating whether it was newly instantiated (vs. reused from registry)
*/
open class func from(dictionaryValue:AttributeDictionary, in context: ValueTransformerContext = .defaultModelContext, configure:((Model,Bool) -> Void)?=nil) -> Self? {
var instance = (self.instanceClass(for: dictionaryValue) ?? self).init()
(instance as Model).readDictionaryValue(dictionaryValue, in: context)
var isNew = true
if let modelContext = context as? ModelValueTransformerContext, let registry = modelContext.registry {
// If we have a canonical object for this id, swap it in
if let canonical = registry.canonicalModel(for: instance) {
isNew = false
instance = canonical
(instance as Model).readDictionaryValue(dictionaryValue, in: modelContext)
} else {
isNew = true
registry.didInstantiate(instance)
}
}
configure?(instance, isNew)
return instance
}
public required override init() {
super.init()
self.buildFields()
self.afterInit()
}
open func afterInit() { }
open func afterCreate() { }
open func beforeSave() { }
open func afterDelete() {
self.identifier = nil
}
/**
Returns a unique instance of this class for an identifier. If a matching instance is already registered, returns that. Otherwise, returns a new instance.
*/
open class func with(identifier: Identifier, in context: ModelValueTransformerContext) -> Self {
let instance = self.init()
instance.identifier = identifier
if let registry = context.registry {
if let canonical = registry.canonicalModel(for: instance) {
return canonical
} else {
registry.didInstantiate(instance)
}
}
return instance
}
/**
Returns a canonical instance corresponding to this instance.
*/
open func canonicalInstance(in context: ModelValueTransformerContext) -> Self {
return context.registry?.canonicalModel(for: self) ?? self
}
/**
Creates a clone of this model. It won't exist in the registry.
*/
open func copy(with zone: NSZone?) -> Any {
return self.copy(fields: nil)
}
open func copy(fields: [FieldType]?) -> Any {
return type(of: self).from(dictionaryValue: self.dictionaryValue(fields: fields))!
}
/**
Which field should be treated as the identifier?
If all the models in your system have the same identifier field (e.g., "id"), you'll probably want to just put that in your
base model class.
*/
open var identifierField: FieldType? {
return nil
}
/**
Attempts to find the identifier as a String or Int, and cast it to an Identifier (aka String)
(because it's useful to have an identifier with known type!)
*/
open var identifier:Identifier? {
get {
let value = self.identifierField?.anyObjectValue
if let value = value as? Identifier {
return value
} else if let value = value as? Int {
return String(value)
} else {
return nil
}
}
set {
if let id = newValue {
if let stringField = self.identifierField as? Field<String> {
stringField.value = id
} else if let intField = self.identifierField as? Field<Int> {
intField.value = Int(id)
}
} else {
self.identifierField?.anyValue = nil
}
}
}
// TODO: permissions
open var editable:Bool = true
open var loadState: LoadState = .loaded
/**
Removes all data from this instance except its identifier, and sets the loadState to .incomplete.
*/
open func unload() {
for field in self.interface.fields where field.key != self.identifierField?.key {
field.anyValue = nil
}
self.loadState = .incomplete
}
open class var name:String {
get {
if let name = NSStringFromClass(self).components(separatedBy: ".").last {
return name
} else {
return "Unknown"
}
}
}
open func cascadeDelete(_ cascade: ((Model)->Void), seenModels: inout Set<Model>) {
self.visitAllFields(action: { field in
if let modelField = field as? ModelFieldType , modelField.cascadeDelete {
if let model = modelField.anyObjectValue as? Model {
cascade(model)
} else if let models = modelField.anyObjectValue as? [Model] {
for model in models {
cascade(model)
}
}
}
}, seenModels: &seenModels)
}
/**
Finds a field (possibly belonging to a child model) for a key path, specified as a list of strings.
*/
open func field(at path:FieldPath) -> FieldType? {
var path = path
guard let firstComponent = path.shift() else { return nil }
let interface = self.interface
if let firstField = interface[firstComponent] {
if path.length == 0 {
// No more components. Just return the field
return firstField
} else if let firstValue = firstField.anyValue as? Model {
// There are more components remaining, and we can keep traversing key paths
return firstValue.field(at: path)
}
}
return nil
}
/**
Finds a field (possibly belonging to a child model) for a key path, specified as a single string.
The string will be split using `componentsForKeyPath(_:)`.
*/
open func field(at path:String) -> FieldType? {
return field(at: self.fieldPath(path))
}
/**
Splits a field keypath into an array of field names to be traversed.
For example, "address.street" might be split into ["address", "street"]
To change the default behavior, you'll probably want to subclass.
*/
open func fieldPath(_ path:String) -> FieldPath {
return FieldPath(path, separator: ".")
}
open func fieldPath(for field: FieldType) -> FieldPath? {
if let key = field.key {
return [key]
} else {
return nil
}
}
public var interface = Interface()
/**
Which fields should we include in the dictionaryValue?
By default, includes all of them.
*/
open func defaultFieldsForDictionaryValue() -> [FieldType] {
return self.interface.fields
}
/**
Look at the instance's fields, do some introspection and processing.
*/
internal func buildFields() {
for (key, field) in self.staticFields.fieldsByKey {
if field.key == nil {
field.key = key
}
self.initializeField(field)
self.interface[key] = field
}
}
public static func <<(object: Model, field: FieldType) {
object.add(field: field)
}
public func add(field: FieldType) {
guard let key = field.key else { return }
self.initializeField(field)
self.interface[key] = field
}
open subscript (key: String) -> Any? {
get {
return self[FieldPath(key)]
}
set {
return self[FieldPath(key)] = newValue
}
}
open subscript (keyPath: FieldPath) -> Any? {
get {
guard let field = self.field(at: keyPath) else { return nil }
return field.anyValue
}
set {
guard let field = self.field(at: keyPath) else { return }
field.anyValue = newValue
}
}
lazy open var staticFields: Interface = {
return self.buildStaticFields()
}()
/**
Builds a mapping of keys to fields. Keys are either the field's `key` property (if specified) or the property name of the field.
This can be slow, since it uses reflection. If you find this to be a performance bottleneck, consider overriding the `staticFields` var
with an explicit mapping of keys to fields.
*/
private func buildStaticFields() -> Interface {
let result = Interface()
let mirror = Mirror(reflecting: self)
mirror.eachChild { child in
if let label = child.label, let value = child.value as? FieldType {
// If the field has its key defined, use that; otherwise fall back to the property name.
let key = value.key ?? label
result[key] = value
}
}
return result
}
/**
Performs any model-level field initialization your class may need, before any field values are set.
*/
open func initializeField(_ field:FieldType) {
field.owner = self
// Can't add observeration blocks that take values, since the FieldType protocol doesn't know about the value type
field.addObserver { [weak self] in
var seen = Set<Model>()
self?.fieldValueChanged(field, at: [], seen: &seen)
}
// If it's a model field, add a deep observer for changes on its value.
if let modelField = field as? ModelFieldType {
modelField.addModelObserver(self, updateImmediately: false) { [weak self] model, fieldPath, seen in
let field = field
self?.fieldValueChanged(field, at: fieldPath, seen: &seen)
}
}
}
open func fieldValueChanged(_ field: FieldType, at relativePath: FieldPath, seen: inout Set<Model>) {
// Avoid cycles
guard !seen.contains(self) else { return }
if let path = self.fieldPath(for: field) {
let fullPath = path.appending(path: relativePath)
seen.insert(self)
self.notifyObservers(path: fullPath, seen: &seen)
}
}
public func visitAllFields(recursive:Bool = true, action:((FieldType) -> Void)) {
var seenModels: Set<Model> = Set()
self.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
}
private func visitAllFields(recursive:Bool = true, action:((FieldType) -> Void), seenModels:inout Set<Model>) {
guard !seenModels.contains(self) else { return }
seenModels.insert(self)
for field in self.interface.fields {
action(field)
if recursive {
if let value = field.anyObjectValue as? Model {
value.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
} else if let values = field.anyObjectValue as? NSArray {
for value in values {
if let model = value as? Model {
model.visitAllFields(recursive: recursive, action: action, seenModels: &seenModels)
}
}
}
}
}
}
public func visitAllFieldValues(recursive:Bool = true, action:((Any?) -> Void)) {
var seenModels: Set<Model> = Set()
self.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
}
private func visitAllFieldValues(recursive:Bool = true, action:((Any?) -> Void), seenModels:inout Set<Model>) {
guard !seenModels.contains(self) else { return }
seenModels.insert(self)
for field in self.interface.fields {
action(field.anyValue)
if recursive {
if let value = field.anyObjectValue as? Model {
value.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
} else if let value = field.anyValue, let values = value as? NSArray {
// I'm not sure why I can't cast to [Any]
// http://stackoverflow.com/questions/26226911/how-to-tell-if-a-variable-is-an-array
for value in values {
action(value)
if let modelValue = value as? Model {
modelValue.visitAllFieldValues(recursive: recursive, action: action, seenModels: &seenModels)
}
}
}
}
}
}
/**
Converts this object to its dictionary representation, optionally limited to a subset of its fields. By default, it will
export all fields in `defaultFieldsForDictionaryValue` (which itself defaults to all fields) that have been loaded.
- parameter fields: An array of field objects (belonging to this model) to be included in the dictionary value.
- parameter in: A value transformer context, used to obtain the correct value transformer for each field.
- parameter includeField: A closure determining whether a field should be included in the result. By default, it will be included iff its state is .Set (i.e., it has been explicitly set since it was loaded)
*/
open func dictionaryValue(fields:[FieldType]?=nil, in context: ValueTransformerContext = .defaultContext, includeField: ((FieldType) -> Bool)?=nil) -> AttributeDictionary {
var seenFields:[FieldType] = []
var includeField = includeField
if includeField == nil {
includeField = { (field:FieldType) -> Bool in field.loadState == LoadState.loaded }
}
return self.dictionaryValue(fields: fields, seenFields: &seenFields, in: context, includeField: includeField)
}
internal func dictionaryValue(fields:[FieldType]? = nil, seenFields: inout [FieldType], in context: ValueTransformerContext = .defaultContext, includeField: ((FieldType) -> Bool)? = nil) -> AttributeDictionary {
let fields = fields ?? self.defaultFieldsForDictionaryValue()
var result:AttributeDictionary = [:]
let include = fields
for field in self.interface.fields {
if include.contains(where: { $0 === field }) && includeField?(field) != false {
field.write(to: &result, seenFields: &seenFields, in: context)
}
}
return result
}
/**
Read field values from a dictionary representation. If a field's key is missing from the dictionary,
but the field is included in the fields to be imported, its value will be set to nil.
- parameter dictionaryValue: The dictionary representation of this model's new field values
- parameter fields: An array of field objects whose values are to be found in the dictionary
- parameter in: A value transformer context, used to obtain the correct value transformer for each field
*/
open func readDictionaryValue(_ dictionaryValue: AttributeDictionary, fields:[FieldType]?=nil, in context: ValueTransformerContext=ValueTransformerContext.defaultContext) {
let fields = (fields ?? self.defaultFieldsForDictionaryValue())
for field in self.interface.fields {
if fields.contains(where: { $0 === field }) {
field.read(from: dictionaryValue, in: context)
}
}
}
/**
Finds all values that are incompletely loaded (i.e., a model instantiated from just a foreign key)
*/
open func incompleteChildModels(recursive:Bool = false) -> [Model] {
var results:[Model] = []
self.visitAllFieldValues(recursive: recursive) { value in
if let model = value as? Model, model.loadState == .incomplete {
results.append(model)
}
}
return results
}
/**
All models related with foreignKey fields
*/
open func foreignKeyModels() -> [Model] {
var results:[Model] = []
self.visitAllFields { field in
if let modelField = field as? ModelFieldType , modelField.foreignKey == true {
if let value = modelField.anyObjectValue as? Model {
results.append(value)
} else if let values = modelField.anyObjectValue as? [Model] {
for value in values {
results.append(value)
}
}
}
}
return results
}
// MARK: Validation
/**
Adds a validation error message to a field identified by a key path.
- parameter keyPath: The path to the field (possibly belonging to a child model) that has an error.
- parameter message: A description of what's wrong.
*/
open func addError(at path:FieldPath, message:String) {
if let field = self.field(at: path) {
field.addValidationError(message)
}
}
/**
Test whether this model passes validation. All fields will have their validation states updated.
By default, related models are not themselves validated. Use the `requireValid()` method on those fields for deeper validation.
*/
open func validate() -> ValidationState {
self.resetValidationState()
var messages: [String] = []
self.visitAllFields(recursive: false) { field in
if case .invalid(let fieldMessages) = field.validate() {
messages.append(contentsOf: fieldMessages)
}
}
if messages.count == 0 {
return .valid
} else {
return .invalid(messages)
}
}
open func resetValidationState() {
self.visitAllFields { $0.resetValidationState() }
}
// MARK: - Merging
/**
Merges field values from another model.
Fields are matched by key, and compared using `updatedAt` timestamps; the newer value wins.
*/
public func merge(from model: Model) {
self.merge(from: model, include: self.interface.fields)
}
public func merge(from model: Model, exclude excludedFields: [FieldType]) {
self.merge(from: model) { field, otherField in
!excludedFields.contains { $0 === field }
}
}
public func merge(from model: Model, if condition: @escaping ((FieldType, FieldType)->Bool)) {
let fields = self.interface.fields
merge(from: model, include: fields, if: condition)
}
open func merge(from model: Model, include includedFields: [FieldType], if condition: ((FieldType, FieldType) -> Bool)? = nil) {
let otherFields = model.interface
for field in includedFields {
if let key = field.key, let otherField = otherFields[key] {
var shouldMerge = true
if let condition = condition {
shouldMerge = condition(field, otherField)
}
if shouldMerge {
field.merge(from: otherField)
}
}
}
}
// MARK: -
/**
A object to be used as a standard prototypical instance of this class, for the purpose of accessing fields, etc.
It is reused when possible.
*/
public class func prototype() -> Self {
return Model.prototype(for: self)
}
open var observations = ObservationRegistry<ModelObservation>()
// MARK: - Observations
@discardableResult public func addObserver(_ observer: AnyObject?=nil, for fieldPath: FieldPath?=nil, updateImmediately: Bool = false, action:@escaping ModelObservation.Action) -> ModelObservation {
let observation = ModelObservation(fieldPath: fieldPath, action: action)
self.observations.add(observation, for: observer)
return observation
}
@discardableResult public func addObserver(updateImmediately: Bool, action:@escaping ((Void) -> Void)) {
self.addObserver(updateImmediately: updateImmediately) { _, _, _ in
action()
}
}
public func notifyObservers(path: FieldPath, seen: inout Set<Model>) {
// Changing a value at a path implies a change of all child paths. Notify accordingly.
var path = path
path.isPrefix = true
self.observations.forEach { observation in
observation.perform(model: self, fieldPath: path, seen: &seen)
}
}
public func removeObserver(_ observer: AnyObject) {
self.observations.remove(for: observer)
}
public func removeAllObservers() {
self.observations.clear()
}
// MARK: - Blankable
public var isBlank: Bool {
for field in self.interface.fields {
let value = field.anyValue
if let blankable = value as? Blankable {
if !blankable.isBlank {
return false
}
} else if value != nil {
return false
}
}
return true
}
}
|
mit
|
itsaboutcode/WordPress-iOS
|
WordPress/WordPressTest/ReaderPostCardCellTests.swift
|
1
|
5811
|
@testable import WordPress
import XCTest
class MockContentProvider: NSObject, ReaderPostContentProvider {
func siteID() -> NSNumber {
return NSNumber(value: 15546)
}
func titleForDisplay() -> String! {
return "A title"
}
func authorForDisplay() -> String! {
return "An author"
}
func blogNameForDisplay() -> String! {
return "A blog name"
}
func statusForDisplay() -> String! {
return "A status"
}
func contentForDisplay() -> String! {
return "The post content"
}
func contentPreviewForDisplay() -> String! {
return "The preview content"
}
func avatarURLForDisplay() -> URL! {
return URL(string: "http://automattic.com")!
}
func gravatarEmailForDisplay() -> String! {
return "[email protected]"
}
func dateForDisplay() -> Date! {
return Date(timeIntervalSince1970: 0)
}
func siteIconForDisplay(ofSize size: Int) -> URL! {
return avatarURLForDisplay()
}
func sourceAttributionStyle() -> SourceAttributionStyle {
// will make all buttons visible
return .none
}
func sourceAuthorNameForDisplay() -> String! {
return "An author name"
}
func sourceAuthorURLForDisplay() -> URL! {
return URL(string: "http://automattic.com")
}
func sourceAvatarURLForDisplay() -> URL! {
return sourceAuthorURLForDisplay()
}
func sourceBlogNameForDisplay() -> String! {
return blogNameForDisplay()
}
func sourceBlogURLForDisplay() -> URL! {
return avatarURLForDisplay()
}
func likeCountForDisplay() -> String! {
return "2"
}
func commentCount() -> NSNumber! {
return 2
}
func likeCount() -> NSNumber! {
return 1
}
func commentsOpen() -> Bool {
return true
}
func isFollowing() -> Bool {
return true
}
func isLikesEnabled() -> Bool {
return true
}
func isAtomic() -> Bool {
return false
}
func isPrivate() -> Bool {
return false
}
func isLiked() -> Bool {
return true
}
func isExternal() -> Bool {
return false
}
func isJetpack() -> Bool {
return true
}
func isWPCom() -> Bool {
return false
}
func primaryTag() -> String! {
return "Primary tag"
}
func readingTime() -> NSNumber! {
return 0
}
func wordCount() -> NSNumber! {
return 10
}
func siteURLForDisplay() -> String! {
return "http://automattic.com"
}
func siteHostNameForDisplay() -> String! {
return "automattic.com"
}
func crossPostOriginSiteURLForDisplay() -> String! {
return ""
}
func isCommentCrossPost() -> Bool {
return false
}
func isSavedForLater() -> Bool {
return false
}
}
final class ReaderPostCardCellTests: XCTestCase {
private var cell: ReaderPostCardCell?
private var mock: ReaderPostContentProvider?
private struct TestConstants {
static let headerLabel = NSLocalizedString("Post by %@, from %@", comment: "")
static let saveLabel = NSLocalizedString("Save post", comment: "Save post")
static let moreLabel = NSLocalizedString("More", comment: "More")
static let commentsLabelformat = NSLocalizedString("%@ comments", comment: "Number of Comments")
static let reblogLabel = NSLocalizedString("Reblog post", comment: "Accessibility label for the reblog button.")
}
override func setUp() {
super.setUp()
mock = MockContentProvider()
cell = Bundle.loadRootViewFromNib(type: ReaderPostCardCell.self)
cell?.configureCell(mock!)
}
override func tearDown() {
cell = nil
mock = nil
super.tearDown()
}
func testHeaderLabelMatchesExpectation() {
XCTAssertEqual(cell?.getHeaderButtonForTesting().accessibilityLabel, String(format: TestConstants.headerLabel, "An author", "A blog name" + ", " + mock!.dateForDisplay().mediumString()), "Incorrect accessibility label: Header Button ")
}
func testSaveForLaterButtonLabelMatchesExpectation() {
XCTAssertEqual(cell?.getSaveForLaterButtonForTesting().accessibilityLabel, String(format: "%@", TestConstants.saveLabel), "Incorrect accessibility label: Save for Later button")
}
func testCommentsButtonLabelMatchesExpectation() {
XCTAssertEqual(cell?.getCommentsButtonForTesting().accessibilityLabel, String(format: TestConstants.commentsLabelformat, "\(2)"), "Incorrect accessibility label: Comments button")
}
func testMenuButtonLabelMatchesExpectation() {
XCTAssertEqual(cell?.getMenuButtonForTesting().accessibilityLabel, String(format: "%@", TestConstants.moreLabel), "Incorrect accessibility label: Menu button")
}
func testReblogActionButtonMatchesExpectation() {
XCTAssertEqual(cell?.getReblogButtonForTesting().accessibilityLabel, TestConstants.reblogLabel, "Incorrect accessibility label: Reblog button")
}
func testReblogButtonIsVisible() {
guard let button = cell?.getReblogButtonForTesting() else {
XCTFail("Reblog button not found.")
return
}
XCTAssertFalse(button.isHidden, "Reblog button should be visible.")
}
func testReblogButtonVisibleWithNoLoggedInUser() {
cell?.loggedInActionVisibility = .visible(enabled: false)
cell?.configureCell(mock!)
guard let button = cell?.getReblogButtonForTesting() else {
XCTFail("Reblog button not found.")
return
}
XCTAssertFalse(button.isEnabled, "Reblog button should be disabled.")
}
}
|
gpl-2.0
|
antoniocasero/DOFavoriteButton
|
DOFavoriteButton/DOFavoriteButton.swift
|
2
|
15670
|
//
// DOFavoriteButton.swift
// DOFavoriteButton
//
// Created by Daiki Okumura on 2015/07/09.
// Copyright (c) 2015 Daiki Okumura. All rights reserved.
//
// This software is released under the MIT License.
// http://opensource.org/licenses/mit-license.php
//
import UIKit
@IBDesignable
open class DOFavoriteButton: UIButton {
fileprivate var imageShape: CAShapeLayer!
@IBInspectable open var image: UIImage! {
didSet {
createLayers(image: image)
}
}
@IBInspectable open var imageColorOn: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
if (isSelected) {
imageShape.fillColor = imageColorOn.cgColor
}
}
}
@IBInspectable open var imageColorOff: UIColor! = UIColor(red: 136/255, green: 153/255, blue: 166/255, alpha: 1.0) {
didSet {
if (!isSelected) {
imageShape.fillColor = imageColorOff.cgColor
}
}
}
fileprivate var circleShape: CAShapeLayer!
fileprivate var circleMask: CAShapeLayer!
@IBInspectable open var circleColor: UIColor! = UIColor(red: 255/255, green: 172/255, blue: 51/255, alpha: 1.0) {
didSet {
circleShape.fillColor = circleColor.cgColor
}
}
fileprivate var lines: [CAShapeLayer]!
@IBInspectable open var lineColor: UIColor! = UIColor(red: 250/255, green: 120/255, blue: 68/255, alpha: 1.0) {
didSet {
for line in lines {
line.strokeColor = lineColor.cgColor
}
}
}
fileprivate let circleTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let circleMaskTransform = CAKeyframeAnimation(keyPath: "transform")
fileprivate let lineStrokeStart = CAKeyframeAnimation(keyPath: "strokeStart")
fileprivate let lineStrokeEnd = CAKeyframeAnimation(keyPath: "strokeEnd")
fileprivate let lineOpacity = CAKeyframeAnimation(keyPath: "opacity")
fileprivate let imageTransform = CAKeyframeAnimation(keyPath: "transform")
@IBInspectable open var duration: Double = 1.0 {
didSet {
circleTransform.duration = 0.333 * duration // 0.0333 * 10
circleMaskTransform.duration = 0.333 * duration // 0.0333 * 10
lineStrokeStart.duration = 0.6 * duration //0.0333 * 18
lineStrokeEnd.duration = 0.6 * duration //0.0333 * 18
lineOpacity.duration = 1.0 * duration //0.0333 * 30
imageTransform.duration = 1.0 * duration //0.0333 * 30
}
}
override open var isSelected : Bool {
didSet {
if (isSelected != oldValue) {
if isSelected {
imageShape.fillColor = imageColorOn.cgColor
} else {
deselect()
}
}
}
}
public convenience init() {
self.init(frame: CGRect.zero)
}
public override convenience init(frame: CGRect) {
self.init(frame: frame, image: UIImage())
}
public init(frame: CGRect, image: UIImage!) {
super.init(frame: frame)
self.image = image
createLayers(image: image)
addTargets()
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
createLayers(image: UIImage())
addTargets()
}
fileprivate func createLayers(image: UIImage!) {
self.layer.sublayers = nil
let imageFrame = CGRect(x: frame.size.width / 2 - frame.size.width / 4, y: frame.size.height / 2 - frame.size.height / 4, width: frame.size.width / 2, height: frame.size.height / 2)
let imgCenterPoint = CGPoint(x: imageFrame.midX, y: imageFrame.midY)
let lineFrame = CGRect(x: imageFrame.origin.x - imageFrame.width / 4, y: imageFrame.origin.y - imageFrame.height / 4 , width: imageFrame.width * 1.5, height: imageFrame.height * 1.5)
//===============
// circle layer
//===============
circleShape = CAShapeLayer()
circleShape.bounds = imageFrame
circleShape.position = imgCenterPoint
circleShape.path = UIBezierPath(ovalIn: imageFrame).cgPath
circleShape.fillColor = circleColor.cgColor
circleShape.transform = CATransform3DMakeScale(0.0, 0.0, 1.0)
self.layer.addSublayer(circleShape)
circleMask = CAShapeLayer()
circleMask.bounds = imageFrame
circleMask.position = imgCenterPoint
circleMask.fillRule = kCAFillRuleEvenOdd
circleShape.mask = circleMask
let maskPath = UIBezierPath(rect: imageFrame)
maskPath.addArc(withCenter: imgCenterPoint, radius: 0.1, startAngle: CGFloat(0.0), endAngle: CGFloat(M_PI * 2), clockwise: true)
circleMask.path = maskPath.cgPath
//===============
// line layer
//===============
lines = []
for i in 0 ..< 5 {
let line = CAShapeLayer()
line.bounds = lineFrame
line.position = imgCenterPoint
line.masksToBounds = true
line.actions = ["strokeStart": NSNull(), "strokeEnd": NSNull()]
line.strokeColor = lineColor.cgColor
line.lineWidth = 1.25
line.miterLimit = 1.25
line.path = {
let path = CGMutablePath()
path.move(to: CGPoint(x: lineFrame.midX, y: lineFrame.midY))
path.addLine(to: CGPoint(x: lineFrame.origin.x + lineFrame.width / 2, y: lineFrame.origin.y))
return path
}()
line.lineCap = kCALineCapRound
line.lineJoin = kCALineJoinRound
line.strokeStart = 0.0
line.strokeEnd = 0.0
line.opacity = 0.0
line.transform = CATransform3DMakeRotation(CGFloat(M_PI) / 5 * (CGFloat(i) * 2 + 1), 0.0, 0.0, 1.0)
self.layer.addSublayer(line)
lines.append(line)
}
//===============
// image layer
//===============
imageShape = CAShapeLayer()
imageShape.bounds = imageFrame
imageShape.position = imgCenterPoint
imageShape.path = UIBezierPath(rect: imageFrame).cgPath
imageShape.fillColor = imageColorOff.cgColor
imageShape.actions = ["fillColor": NSNull()]
self.layer.addSublayer(imageShape)
imageShape.mask = CALayer()
imageShape.mask!.contents = image.cgImage
imageShape.mask!.bounds = imageFrame
imageShape.mask!.position = imgCenterPoint
//==============================
// circle transform animation
//==============================
circleTransform.duration = 0.333 // 0.0333 * 10
circleTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/10
NSValue(caTransform3D: CATransform3DMakeScale(0.5, 0.5, 1.0)), // 1/10
NSValue(caTransform3D: CATransform3DMakeScale(1.0, 1.0, 1.0)), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(1.3, 1.3, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(1.37, 1.37, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(1.4, 1.4, 1.0)) // 10/10
]
circleTransform.keyTimes = [
0.0, // 0/10
0.1, // 1/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
1.0 // 10/10
]
circleMaskTransform.duration = 0.333 // 0.0333 * 10
circleMaskTransform.values = [
NSValue(caTransform3D: CATransform3DIdentity), // 0/10
NSValue(caTransform3D: CATransform3DIdentity), // 2/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 1.25, imageFrame.height * 1.25, 1.0)), // 3/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 2.688, imageFrame.height * 2.688, 1.0)), // 4/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 3.923, imageFrame.height * 3.923, 1.0)), // 5/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.375, imageFrame.height * 4.375, 1.0)), // 6/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 4.731, imageFrame.height * 4.731, 1.0)), // 7/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)), // 9/10
NSValue(caTransform3D: CATransform3DMakeScale(imageFrame.width * 5.0, imageFrame.height * 5.0, 1.0)) // 10/10
]
circleMaskTransform.keyTimes = [
0.0, // 0/10
0.2, // 2/10
0.3, // 3/10
0.4, // 4/10
0.5, // 5/10
0.6, // 6/10
0.7, // 7/10
0.9, // 9/10
1.0 // 10/10
]
//==============================
// line stroke animation
//==============================
lineStrokeStart.duration = 0.6 //0.0333 * 18
lineStrokeStart.values = [
0.0, // 0/18
0.0, // 1/18
0.18, // 2/18
0.2, // 3/18
0.26, // 4/18
0.32, // 5/18
0.4, // 6/18
0.6, // 7/18
0.71, // 8/18
0.89, // 17/18
0.92 // 18/18
]
lineStrokeStart.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.333, // 6/18
0.389, // 7/18
0.444, // 8/18
0.944, // 17/18
1.0, // 18/18
]
lineStrokeEnd.duration = 0.6 //0.0333 * 18
lineStrokeEnd.values = [
0.0, // 0/18
0.0, // 1/18
0.32, // 2/18
0.48, // 3/18
0.64, // 4/18
0.68, // 5/18
0.92, // 17/18
0.92 // 18/18
]
lineStrokeEnd.keyTimes = [
0.0, // 0/18
0.056, // 1/18
0.111, // 2/18
0.167, // 3/18
0.222, // 4/18
0.278, // 5/18
0.944, // 17/18
1.0, // 18/18
]
lineOpacity.duration = 1.0 //0.0333 * 30
lineOpacity.values = [
1.0, // 0/30
1.0, // 12/30
0.0 // 17/30
]
lineOpacity.keyTimes = [
0.0, // 0/30
0.4, // 12/30
0.567 // 17/30
]
//==============================
// image transform animation
//==============================
imageTransform.duration = 1.0 //0.0333 * 30
imageTransform.values = [
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 0/30
NSValue(caTransform3D: CATransform3DMakeScale(0.0, 0.0, 1.0)), // 3/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 9/30
NSValue(caTransform3D: CATransform3DMakeScale(1.25, 1.25, 1.0)), // 10/30
NSValue(caTransform3D: CATransform3DMakeScale(1.2, 1.2, 1.0)), // 11/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 14/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 15/30
NSValue(caTransform3D: CATransform3DMakeScale(0.875, 0.875, 1.0)), // 16/30
NSValue(caTransform3D: CATransform3DMakeScale(0.9, 0.9, 1.0)), // 17/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 20/30
NSValue(caTransform3D: CATransform3DMakeScale(1.025, 1.025, 1.0)), // 21/30
NSValue(caTransform3D: CATransform3DMakeScale(1.013, 1.013, 1.0)), // 22/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 25/30
NSValue(caTransform3D: CATransform3DMakeScale(0.95, 0.95, 1.0)), // 26/30
NSValue(caTransform3D: CATransform3DMakeScale(0.96, 0.96, 1.0)), // 27/30
NSValue(caTransform3D: CATransform3DMakeScale(0.99, 0.99, 1.0)), // 29/30
NSValue(caTransform3D: CATransform3DIdentity) // 30/30
]
imageTransform.keyTimes = [
0.0, // 0/30
0.1, // 3/30
0.3, // 9/30
0.333, // 10/30
0.367, // 11/30
0.467, // 14/30
0.5, // 15/30
0.533, // 16/30
0.567, // 17/30
0.667, // 20/30
0.7, // 21/30
0.733, // 22/30
0.833, // 25/30
0.867, // 26/30
0.9, // 27/30
0.967, // 29/30
1.0 // 30/30
]
}
fileprivate func addTargets() {
//===============
// add target
//===============
self.addTarget(self, action: #selector(DOFavoriteButton.touchDown(_:)), for: UIControlEvents.touchDown)
self.addTarget(self, action: #selector(DOFavoriteButton.touchUpInside(_:)), for: UIControlEvents.touchUpInside)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragExit(_:)), for: UIControlEvents.touchDragExit)
self.addTarget(self, action: #selector(DOFavoriteButton.touchDragEnter(_:)), for: UIControlEvents.touchDragEnter)
self.addTarget(self, action: #selector(DOFavoriteButton.touchCancel(_:)), for: UIControlEvents.touchCancel)
}
func touchDown(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchUpInside(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragExit(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
func touchDragEnter(_ sender: DOFavoriteButton) {
self.layer.opacity = 0.4
}
func touchCancel(_ sender: DOFavoriteButton) {
self.layer.opacity = 1.0
}
open func select() {
isSelected = true
imageShape.fillColor = imageColorOn.cgColor
CATransaction.begin()
circleShape.add(circleTransform, forKey: "transform")
circleMask.add(circleMaskTransform, forKey: "transform")
imageShape.add(imageTransform, forKey: "transform")
for i in 0 ..< 5 {
lines[i].add(lineStrokeStart, forKey: "strokeStart")
lines[i].add(lineStrokeEnd, forKey: "strokeEnd")
lines[i].add(lineOpacity, forKey: "opacity")
}
CATransaction.commit()
}
open func deselect() {
isSelected = false
imageShape.fillColor = imageColorOff.cgColor
// remove all animations
circleShape.removeAllAnimations()
circleMask.removeAllAnimations()
imageShape.removeAllAnimations()
lines[0].removeAllAnimations()
lines[1].removeAllAnimations()
lines[2].removeAllAnimations()
lines[3].removeAllAnimations()
lines[4].removeAllAnimations()
}
}
|
mit
|
shaps80/Peek
|
Pod/Classes/Controllers & Views/Inspectors/PreviewCell.swift
|
1
|
1386
|
//
// PreviewCell.swift
// Peek
//
// Created by Shaps Benkau on 24/02/2018.
//
import UIKit
internal final class PreviewCell: UITableViewCell {
internal let previewImageView: UIImageView
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
previewImageView = UIImageView()
previewImageView.contentMode = .scaleAspectFit
previewImageView.clipsToBounds = true
previewImageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
previewImageView.setContentHuggingPriority(.defaultLow, for: .horizontal)
previewImageView.setContentHuggingPriority(.required, for: .vertical)
previewImageView.setContentCompressionResistancePriority(.required, for: .vertical)
super.init(style: .value1, reuseIdentifier: reuseIdentifier)
addSubview(previewImageView, constraints: [
equal(\.layoutMarginsGuide.leadingAnchor, \.leadingAnchor),
equal(\.layoutMarginsGuide.trailingAnchor, \.trailingAnchor),
equal(\.topAnchor, constant: -16),
equal(\.bottomAnchor, constant: 16)
])
clipsToBounds = true
contentView.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
thisfin/IconfontPreview
|
IconfontPreview/WindowController.swift
|
1
|
428
|
//
// WindowController.swift
// IconfontPreview
//
// Created by wenyou on 2018/8/5.
// Copyright © 2018 wenyou. All rights reserved.
//
import Cocoa
class WindowController: NSWindowController {
var titleName: String?
override func windowDidLoad() {
super.windowDidLoad()
}
override func windowTitle(forDocumentDisplayName displayName: String) -> String {
return titleName ?? ""
}
}
|
mit
|
whong7/swift-knowledge
|
思维导图/4-3:网易新闻/网易新闻/NetworkTools.swift
|
1
|
841
|
//
// NetworkTools.swift
// 网易新闻
//
// Created by 吴鸿 on 2017/3/4.
// Copyright © 2017年 吴鸿. All rights reserved.
//
import UIKit
import Alamofire
enum methodType {
case get
case post
}
class NetworkTools {
//类方法
class func requestData(URLString : String,type : methodType,parameters:[String : Any]? = nil,finishedCallback: @escaping(_ result : Any)->()){
let method = type == .get ? HTTPMethod.get : HTTPMethod.post
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
//1.校验是否有结果
guard let result = response.result.value else{
return
}
//2.将结果回调出去
finishedCallback(result)
}
}
}
|
mit
|
tjw/swift
|
test/NameBinding/named_lazy_member_loading_swift_proto.swift
|
3
|
748
|
// RUN: rm -rf %t && mkdir -p %t/stats-pre && mkdir -p %t/stats-post
//
// Compile swiftmodule with decl member name tables
// RUN: %target-swift-frontend -emit-module -o %t/NamedLazyMembers.swiftmodule %S/Inputs/NamedLazyMembers/NamedLazyMembers.swift
//
// Check that named-lazy-member-loading reduces the number of Decls deserialized
// RUN: %target-swift-frontend -typecheck -I %t -disable-named-lazy-member-loading -typecheck -stats-output-dir %t/stats-pre %s
// RUN: %target-swift-frontend -typecheck -I %t -stats-output-dir %t/stats-post %s
// RUN: %utils/process-stats-dir.py --evaluate-delta 'NumDeclsDeserialized < -3' %t/stats-pre %t/stats-post
import NamedLazyMembers
public func test(b: BaseProto) {
let _ = b.protoMemberFunc1()
}
|
apache-2.0
|
CD1212/Doughnut
|
Pods/GRDB.swift/GRDB/Core/SchedulingWatchdog.swift
|
1
|
2605
|
import Dispatch
/// SchedulingWatchdog makes sure that databases connections are used on correct
/// dispatch queues, and warns the user with a fatal error whenever she misuses
/// a database connection.
///
/// Generally speaking, each connection has its own dispatch queue. But it's not
/// enough: users need to use two database connections at the same time:
/// https://github.com/groue/GRDB.swift/issues/55. To support this use case, a
/// single dispatch queue can be temporarily shared by two or more connections.
///
/// - SchedulingWatchdog.makeSerializedQueue(allowingDatabase:) creates a
/// dispatch queue that allows one database.
///
/// It does so by registering one instance of SchedulingWatchdog as a specific
/// of the dispatch queue, a SchedulingWatchdog that allows that database only.
///
/// Later on, the queue can be shared by several databases with the method
/// allowing(databases:execute:). See SerializedDatabase.sync() for
/// an example.
///
/// - preconditionValidQueue() crashes whenever a database is used in an invalid
/// dispatch queue.
final class SchedulingWatchdog {
private static let specificKey = DispatchSpecificKey<SchedulingWatchdog>()
private(set) var allowedDatabases: [Database]
private init(allowedDatabase database: Database) {
allowedDatabases = [database]
}
static func makeSerializedQueue(allowingDatabase database: Database) -> DispatchQueue {
let queue = DispatchQueue(label: "GRDB.SerializedDatabase")
let watchdog = SchedulingWatchdog(allowedDatabase: database)
queue.setSpecific(key: specificKey, value: watchdog)
return queue
}
// Temporarily allows `databases` while executing `body`
func allowing<T>(databases: [Database], execute body: () throws -> T) rethrows -> T {
let backup = allowedDatabases
allowedDatabases.append(contentsOf: databases)
defer { allowedDatabases = backup }
return try body()
}
static func preconditionValidQueue(_ db: Database, _ message: @autoclosure() -> String = "Database was not used on the correct thread.", file: StaticString = #file, line: UInt = #line) {
GRDBPrecondition(allows(db), message, file: file, line: line)
}
static func allows(_ db: Database) -> Bool {
return current?.allows(db) ?? false
}
func allows(_ db: Database) -> Bool {
return allowedDatabases.contains { $0 === db }
}
static var current: SchedulingWatchdog? {
return DispatchQueue.getSpecific(key: specificKey)
}
}
|
gpl-3.0
|
apple/swift
|
test/Interpreter/SDK/GLKit.swift
|
69
|
3996
|
// RUN: %target-run-simple-swift | %FileCheck %s
// REQUIRES: executable_test
// NOTE: Clang used to miscompile GLKit functions on i386. rdar://problem/19184403
// On i386, it seems to work optimized mode, but fails in non-optimized.
// rdar://problem/26392402
// UNSUPPORTED: CPU=i386
// REQUIRES: objc_interop
// GLKit is not available on watchOS.
// UNSUPPORTED: OS=watchos
import GLKit
func printV4(_ v: GLKVector4) {
print("<\(v.x) \(v.y) \(v.z) \(v.w)>")
}
let x = GLKVector4Make(1, 0, 0, 0)
let y = GLKVector4Make(0, 1, 0, 0)
let z = GLKVector4Make(0, 0, 1, 0)
printV4(x) // CHECK: <1.0 0.0 0.0 0.0>
printV4(y) // CHECK-NEXT: <0.0 1.0 0.0 0.0>
printV4(z) // CHECK-NEXT: <0.0 0.0 1.0 0.0>
print(GLKVector4DotProduct(x, y)) // CHECK-NEXT: 0.0
let z2 = GLKVector4CrossProduct(x, y)
print(GLKVector4AllEqualToVector4(z, z2)) // CHECK-NEXT: true
infix operator • : MultiplicationPrecedence
infix operator ⨉ : MultiplicationPrecedence
func •(x: GLKVector4, y: GLKVector4) -> Float {
return GLKVector4DotProduct(x, y)
}
func ⨉(x: GLKVector4, y: GLKVector4) -> GLKVector4 {
return GLKVector4CrossProduct(x, y)
}
func ==(x: GLKVector4, y: GLKVector4) -> Bool {
return GLKVector4AllEqualToVector4(x, y)
}
print(x • y) // CHECK-NEXT: 0.0
print(x ⨉ y == z) // CHECK-NEXT: true
func printM4(_ m: GLKMatrix4) {
print("⎡\(m.m00) \(m.m01) \(m.m02) \(m.m03)⎤")
print("⎢\(m.m10) \(m.m11) \(m.m12) \(m.m13)⎥")
print("⎢\(m.m20) \(m.m21) \(m.m22) \(m.m23)⎥")
print("⎣\(m.m30) \(m.m31) \(m.m32) \(m.m33)⎦")
}
let flipXY = GLKMatrix4Make(0, 1, 0, 0,
1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1)
// CHECK-NEXT: ⎡0.0 1.0 0.0 0.0⎤
// CHECK-NEXT: ⎢1.0 0.0 0.0 0.0⎥
// CHECK-NEXT: ⎢0.0 0.0 1.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(flipXY)
// FIXME: GLKMatrix4MakeWithArray takes mutable pointer arguments for no
// good reason. rdar://problem/19124355
var flipYZElements: [Float] = [1, 0, 0, 0,
0, 0, 1, 0,
0, 1, 0, 0,
0, 0, 0, 1]
let flipYZ = GLKMatrix4MakeWithArray(&flipYZElements)
// CHECK-NEXT: ⎡1.0 0.0 0.0 0.0⎤
// CHECK-NEXT: ⎢0.0 0.0 1.0 0.0⎥
// CHECK-NEXT: ⎢0.0 1.0 0.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(flipYZ)
let rotateXYZ = GLKMatrix4Multiply(flipYZ, flipXY)
// CHECK-NEXT: ⎡0.0 0.0 1.0 0.0⎤
// CHECK-NEXT: ⎢1.0 0.0 0.0 0.0⎥
// CHECK-NEXT: ⎢0.0 1.0 0.0 0.0⎥
// CHECK-NEXT: ⎣0.0 0.0 0.0 1.0⎦
printM4(rotateXYZ)
let y3 = GLKMatrix4MultiplyVector4(flipXY, x)
print(y == y3) // CHECK-NEXT: true
let y4 = GLKMatrix4MultiplyVector4(flipYZ, z)
print(y == y4) // CHECK-NEXT: true
let z3 = GLKMatrix4MultiplyVector4(rotateXYZ, x)
print(z == z3) // CHECK-NEXT: true
func •(x: GLKMatrix4, y: GLKMatrix4) -> GLKMatrix4 {
return GLKMatrix4Multiply(x, y)
}
func •(x: GLKMatrix4, y: GLKVector4) -> GLKVector4 {
return GLKMatrix4MultiplyVector4(x, y)
}
print(y == flipXY • x) // CHECK-NEXT: true
print(x == flipXY • y) // CHECK-NEXT: true
print(z == flipXY • z) // CHECK-NEXT: true
print(x == flipYZ • x) // CHECK-NEXT: true
print(z == flipYZ • y) // CHECK-NEXT: true
print(y == flipYZ • z) // CHECK-NEXT: true
print(z == rotateXYZ • x) // CHECK-NEXT: true
print(x == rotateXYZ • y) // CHECK-NEXT: true
print(y == rotateXYZ • z) // CHECK-NEXT: true
print(z == flipYZ • flipXY • x) // CHECK-NEXT: true
print(x == flipYZ • flipXY • y) // CHECK-NEXT: true
print(y == flipYZ • flipXY • z) // CHECK-NEXT: true
let xxx = GLKVector3Make(1, 0, 0)
let yyy = GLKVector3Make(0, 1, 0)
let zzz = GLKVector3Make(0, 0, 1)
print(GLKVector3DotProduct(xxx, yyy)) // CHECK-NEXT: 0.0
print(GLKVector3AllEqualToVector3(GLKVector3CrossProduct(xxx, yyy), zzz)) // CHECK-NEXT: true
let xx = GLKVector2Make(1, 0)
let yy = GLKVector2Make(0, 1)
print(GLKVector2DotProduct(xx, yy)) // CHECK-NEXT: 0.0
|
apache-2.0
|
libiao88/Moya
|
Demo/DemoTests/MoyaProviderSpec.swift
|
5
|
22147
|
import Quick
import Moya
import Nimble
import ReactiveCocoa
import RxSwift
import Alamofire
class MoyaProviderSpec: QuickSpec {
override func spec() {
describe("valid endpoints") {
describe("with stubbed responses") {
describe("a provider", {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns stubbed data for user profile request") {
var message: String?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
it("returns equivalent Endpoint instances for the same target") {
let target: GitHub = .Zen
let endpoint1 = provider.endpoint(target)
let endpoint2 = provider.endpoint(target)
expect(endpoint1).to(equal(endpoint2))
}
it("returns a cancellable object when a request is made") {
let target: GitHub = .UserProfile("ashfurrow")
let cancellable: Cancellable = provider.request(target) { (_, _, _, _) in }
expect(cancellable).toNot(beNil())
}
it("uses the Alamofire.Manager.sharedInstance by default") {
expect(provider.manager).to(beIdenticalTo(Alamofire.Manager.sharedInstance))
}
it("accepts a custom Alamofire.Manager") {
let manager = Manager()
let provider = MoyaProvider<GitHub>(manager: manager)
expect(provider.manager).to(beIdenticalTo(manager))
}
})
it("notifies at the beginning of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Began {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
it("notifies at the end of network requests") {
var called = false
var provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour, networkActivityClosure: { (change) -> () in
if change == .Ended {
called = true
}
})
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in }
expect(called) == true
}
describe("a provider with lazy data", { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: lazyEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) { (data, statusCode, response, error) in
if let data = data {
message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).to(equal(NSString(data: sampleData, encoding: NSUTF8StringEncoding)))
}
})
it("delays execution when appropriate") {
let provider = MoyaProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(2))
let startDate = NSDate()
var endDate: NSDate?
let target: GitHub = .Zen
waitUntil(timeout: 3) { done in
provider.request(target) { (data, statusCode, response, error) in
endDate = NSDate()
done()
}
return
}
expect{
return endDate?.timeIntervalSinceDate(startDate)
}.to( beGreaterThanOrEqualTo(NSTimeInterval(2)) )
}
describe("a provider with a custom endpoint resolver") { () -> () in
var provider: MoyaProvider<GitHub>!
var executed = false
let newSampleResponse = "New Sample Response"
beforeEach {
executed = false
let endpointResolution = { (endpoint: Endpoint<GitHub>) -> (NSURLRequest) in
executed = true
return endpoint.urlRequest
}
provider = MoyaProvider<GitHub>(endpointResolver: endpointResolution, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("executes the endpoint resolver") {
let target: GitHub = .Zen
provider.request(target, completion: { (data, statusCode, response, error) in })
let sampleData = target.sampleData as NSData
expect(executed).to(beTruthy())
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
called = true
}
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
}
let sampleData = target.sampleData as NSData
expect(message).toNot(beNil())
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeNext { (object) -> Void in
if let response = object as? MoyaResponse {
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical signals for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
// The synchronous nature of stubbed responses makes this kind of tricky. We use the
// subscribeNext closure to get the provider into a state where the signal has been
// added to the inflightRequests dictionary. Then we ask for an identical request,
// which should return the same signal. We can't *test* those signals equivalency
// due to the use of RACSignal.defer, but we can check if the number of inflight
// requests went up or not.
let outerSignal = provider.request(target)
outerSignal.subscribeNext { (object) -> Void in
response = object as? MoyaResponse
expect(provider.inflightRequests.count).to(equal(1))
// Create a new signal and force subscription, so that the inflightRequests dictionary is accessed.
let innerSignal = provider.request(target)
innerSignal.subscribeNext { (object) -> Void in
// nop
}
expect(provider.inflightRequests.count).to(equal(1))
}
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a RxSwift provider", { () -> () in
var provider: RxMoyaProvider<GitHub>!
beforeEach {
provider = RxMoyaProvider(stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns a MoyaResponse object") {
var called = false
provider.request(.Zen) >- subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("returns stubbed data for zen request") {
var message: String?
let target: GitHub = .Zen
provider.request(target) >- subscribeNext { (response) -> Void in
message = NSString(data: response.data, encoding: NSUTF8StringEncoding) as? String
}
let sampleString = NSString(data: (target.sampleData as NSData), encoding: NSUTF8StringEncoding)
expect(message).to(equal(sampleString))
}
it("returns correct data for user profile request") {
var receivedResponse: NSDictionary?
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) >- subscribeNext { (response) -> Void in
receivedResponse = NSJSONSerialization.JSONObjectWithData(response.data, options: nil, error: nil) as? NSDictionary
}
let sampleData = target.sampleData as NSData
let sampleResponse: NSDictionary = NSJSONSerialization.JSONObjectWithData(sampleData, options: nil, error: nil) as! NSDictionary
expect(receivedResponse).toNot(beNil())
}
it("returns identical observables for inflight requests") {
let target: GitHub = .Zen
var response: MoyaResponse!
let parallelCount = 10
let observables = Array(0..<parallelCount).map { _ in provider.request(target) }
var completions = Array(0..<parallelCount).map { _ in false }
let queue = dispatch_queue_create("testing", DISPATCH_QUEUE_CONCURRENT)
dispatch_apply(observables.count, queue, { idx in
let i = idx
observables[i] >- subscribeNext { _ -> Void in
if i == 5 { // We only need to check it once.
expect(provider.inflightRequests.count).to(equal(1))
}
completions[i] = true
}
})
func allTrue(cs: [Bool]) -> Bool {
return cs.reduce(true) { (a,b) -> Bool in a && b }
}
expect(allTrue(completions)).toEventually(beTrue())
expect(provider.inflightRequests.count).to(equal(0))
}
})
describe("a subsclassed reactive provider that tracks cancellation with delayed stubs") {
struct TestCancellable: Cancellable {
static var cancelled = false
func cancel() {
TestCancellable.cancelled = true
}
}
class TestProvider<T: MoyaTarget>: ReactiveCocoaMoyaProvider<T> {
override init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, manager: Manager = Alamofire.Manager.sharedInstance) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure, manager: manager)
}
override func request(token: T, completion: MoyaCompletion) -> Cancellable {
return TestCancellable()
}
}
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
TestCancellable.cancelled = false
provider = TestProvider<GitHub>(stubBehavior: MoyaProvider.DelayedStubbingBehaviour(1))
}
it("cancels network request when subscription is cancelled") {
var called = false
let target: GitHub = .Zen
let disposable = provider.request(target).subscribeCompleted { () -> Void in
// Should never be executed
fail()
}
disposable.dispose()
expect(TestCancellable.cancelled).to( beTrue() )
}
}
}
describe("with stubbed errors") {
describe("a provider") { () -> () in
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect(errored).toEventually(beTruthy())
}
it("returns stubbed data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if error != nil {
errored = true
}
}
let sampleData = target.sampleData as NSData
expect{errored}.toEventually(beTruthy(), timeout: 1, pollInterval: 0.1)
}
it("returns stubbed error data when present") {
var errorMessage = ""
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target) { (object, statusCode, response, error) in
if let object = object {
errorMessage = NSString(data: object, encoding: NSUTF8StringEncoding) as! String
}
}
expect{errorMessage}.toEventually(equal("Houston, we have a problem"), timeout: 1, pollInterval: 0.1)
}
}
describe("a reactive provider", { () -> () in
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns stubbed data for zen request") {
var errored = false
let target: GitHub = .Zen
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
it("returns correct data for user profile request") {
var errored = false
let target: GitHub = .UserProfile("ashfurrow")
provider.request(target).subscribeError { (error) -> Void in
errored = true
}
expect(errored).to(beTruthy())
}
})
describe("a failing reactive provider") {
var provider: ReactiveCocoaMoyaProvider<GitHub>!
beforeEach {
provider = ReactiveCocoaMoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubBehavior: MoyaProvider.ImmediateStubbingBehaviour)
}
it("returns the HTTP status code as the error code") {
var code: Int?
provider.request(.Zen).subscribeError { (error) -> Void in
code = error.code
}
expect(code).toNot(beNil())
expect(code).to(equal(401))
}
}
}
}
}
}
|
mit
|
wilfreddekok/Antidote
|
Antidote/ProfileDetailsController.swift
|
1
|
7979
|
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import UIKit
import LocalAuthentication
protocol ProfileDetailsControllerDelegate: class {
func profileDetailsControllerSetPin(controller: ProfileDetailsController)
func profileDetailsControllerChangeLockTimeout(controller: ProfileDetailsController)
func profileDetailsControllerChangePassword(controller: ProfileDetailsController)
func profileDetailsControllerDeleteProfile(controller: ProfileDetailsController)
}
class ProfileDetailsController: StaticTableController {
weak var delegate: ProfileDetailsControllerDelegate?
private weak var toxManager: OCTManager!
private let pinEnabledModel = StaticTableSwitchCellModel()
private let lockTimeoutModel = StaticTableInfoCellModel()
private let touchIdEnabledModel = StaticTableSwitchCellModel()
private let changePasswordModel = StaticTableButtonCellModel()
private let exportProfileModel = StaticTableButtonCellModel()
private let deleteProfileModel = StaticTableButtonCellModel()
private var documentInteractionController: UIDocumentInteractionController?
init(theme: Theme, toxManager: OCTManager) {
self.toxManager = toxManager
var model = [[StaticTableBaseCellModel]]()
var footers = [String?]()
model.append([pinEnabledModel, lockTimeoutModel])
footers.append(String(localized: "pin_description"))
if LAContext().canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: nil) {
model.append([touchIdEnabledModel])
footers.append(String(localized: "pin_touch_id_description"))
}
model.append([changePasswordModel])
footers.append(nil)
model.append([exportProfileModel, deleteProfileModel])
footers.append(nil)
super.init(theme: theme, style: .Grouped, model: model, footers: footers)
updateModel()
title = String(localized: "profile_details")
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateModel()
reloadTableView()
}
}
extension ProfileDetailsController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
return self
}
func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController) -> UIView? {
return view
}
func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController) -> CGRect {
return view.frame
}
}
private extension ProfileDetailsController {
func updateModel() {
let settings = toxManager.objects.getProfileSettings()
let isPinEnabled = settings.unlockPinCode != nil
pinEnabledModel.title = String(localized: "pin_enabled")
pinEnabledModel.on = isPinEnabled
pinEnabledModel.valueChangedHandler = pinEnabledValueChanged
lockTimeoutModel.title = String(localized: "pin_lock_timeout")
lockTimeoutModel.showArrow = true
lockTimeoutModel.didSelectHandler = changeLockTimeout
switch settings.lockTimeout {
case .Immediately:
lockTimeoutModel.value = String(localized: "pin_lock_immediately")
case .Seconds30:
lockTimeoutModel.value = String(localized: "pin_lock_30_seconds")
case .Minute1:
lockTimeoutModel.value = String(localized: "pin_lock_1_minute")
case .Minute2:
lockTimeoutModel.value = String(localized: "pin_lock_2_minutes")
case .Minute5:
lockTimeoutModel.value = String(localized: "pin_lock_5_minutes")
}
touchIdEnabledModel.enabled = isPinEnabled
touchIdEnabledModel.title = String(localized: "pin_touch_id_enabled")
touchIdEnabledModel.on = settings.useTouchID
touchIdEnabledModel.valueChangedHandler = touchIdEnabledValueChanged
changePasswordModel.title = String(localized: "change_password")
changePasswordModel.didSelectHandler = changePassword
exportProfileModel.title = String(localized: "export_profile")
exportProfileModel.didSelectHandler = exportProfile
deleteProfileModel.title = String(localized: "delete_profile")
deleteProfileModel.didSelectHandler = deleteProfile
}
func pinEnabledValueChanged(on: Bool) {
if on {
delegate?.profileDetailsControllerSetPin(self)
}
else {
let settings = toxManager.objects.getProfileSettings()
settings.unlockPinCode = nil
toxManager.objects.saveProfileSettings(settings)
}
updateModel()
reloadTableView()
}
func changeLockTimeout(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangeLockTimeout(self)
}
func touchIdEnabledValueChanged(on: Bool) {
let settings = toxManager.objects.getProfileSettings()
settings.useTouchID = on
toxManager.objects.saveProfileSettings(settings)
}
func changePassword(_: StaticTableBaseCell) {
delegate?.profileDetailsControllerChangePassword(self)
}
func exportProfile(_: StaticTableBaseCell) {
do {
let path = try toxManager.exportToxSaveFile()
let name = UserDefaultsManager().lastActiveProfile ?? "profile"
documentInteractionController = UIDocumentInteractionController(URL: NSURL.fileURLWithPath(path))
documentInteractionController!.delegate = self
documentInteractionController!.name = "\(name).tox"
documentInteractionController!.presentOptionsMenuFromRect(view.frame, inView:view, animated: true)
}
catch let error as NSError {
handleErrorWithType(.ExportProfile, error: error)
}
}
func deleteProfile(cell: StaticTableBaseCell) {
let title1 = String(localized: "delete_profile_confirmation_title_1")
let title2 = String(localized: "delete_profile_confirmation_title_2")
let message = String(localized: "delete_profile_confirmation_message")
let yes = String(localized: "alert_delete")
let cancel = String(localized: "alert_cancel")
let alert1 = UIAlertController(title: title1, message: message, preferredStyle: .ActionSheet)
alert1.popoverPresentationController?.sourceView = cell
alert1.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert1.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
let alert2 = UIAlertController(title: title2, message: nil, preferredStyle: .ActionSheet)
alert2.popoverPresentationController?.sourceView = cell
alert2.popoverPresentationController?.sourceRect = CGRect(x: cell.frame.size.width / 2, y: cell.frame.size.height / 2, width: 1.0, height: 1.0)
alert2.addAction(UIAlertAction(title: yes, style: .Destructive) { [unowned self] _ -> Void in
self.reallyDeleteProfile()
})
alert2.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
})
alert1.addAction(UIAlertAction(title: cancel, style: .Cancel, handler: nil))
presentViewController(alert1, animated: true, completion: nil)
}
func reallyDeleteProfile() {
delegate?.profileDetailsControllerDeleteProfile(self)
}
}
|
mpl-2.0
|
glimpseio/ChannelZ
|
Playgrounds/ChannelZMac.playground/section-1.swift
|
1
|
7896
|
import Foundation
import ChannelZ
struct Song {
var title: String
}
struct Company {
var name: String
}
struct Artist {
var name: String
var label: Company?
var songs: [Song]
}
struct Album {
var title: String
var year: Int
var producer: Company?
var tracks: [Song]
}
struct Library {
var artists: [Artist] = []
var albums: [Album] = []
}
extension Library {
var songs: [Song] { return artists.flatMap({ $0.songs }) + albums.flatMap({ $0.tracks }) }
}
var library: Library = Library()
library.albums.append(Album(title: "Magenta Snow", year: 1983, producer: nil, tracks: [
Song(title: "Let's Get Silly"),
Song(title: "Take Me with You"),
Song(title: "I Would Die For You")
]))
// Make it funky now
library.albums[0].title = "Purple Rain"
//library.albums[0].tracks[0].title = "Let's Go Crazy"
//library.albums[0].tracks[1].title = "Take Me with U"
//library.albums[0].tracks[2].title = "I Would Die 4 U"
library.albums[0].year = 1984
library.albums[0].producer = Company(name: "Warner Brothers") // not so funky
library.artists.append(Artist(name: "Prince", label: nil, songs: [Song(title: "Red Hat")]))
library.artists[0].songs[0].title = "Raspberry Beret"
func funkify(title: String) -> String {
return title
.stringByReplacingOccurrencesOfString("Get Silly", withString: "Go Crazy")
.stringByReplacingOccurrencesOfString("For", withString: "4")
.stringByReplacingOccurrencesOfString("You", withString: "U")
}
for i in 0..<library.albums[0].tracks.count {
library.albums[0].tracks[i].title = funkify(library.albums[0].tracks[i].title)
}
//dump(library)
let titles = Set(library.songs.map({ $0.title }))
// Verify funkiness
let funky = titles == ["Let's Go Crazy", "Take Me with U", "I Would Die 4 U", "Raspberry Beret"]
// Make it funcy now ¯\_(ツ)_/¯
protocol Focusable {
}
extension Focusable {
static func lens<B>(lens: Lens<Self, B>) -> Lens<Self, B> {
return lens
}
static func lensZ<X, Source : StateEmitterType where Source.Element == Self>(lens: Lens<Self, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
return { channel in focus(channel)(lens) }
}
static func focus<X, Source : StateEmitterType where Source.Element == Self>(channel: Channel<Source, Mutation<Source.Element>>) -> (Lens<Source.Element, X>) -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
return channel.focus
}
}
extension Artist : Focusable {
static let nameλ = Artist.lens(Lens({ $0.name }, { $0.name = $1 }))
static let labelλ = Artist.lens(Lens({ $0.label }, { $0.label = $1 }))
static let songsλ = Artist.lens(Lens({ $0.songs }, { $0.songs = $1 }))
}
extension Company : Focusable {
static let nameλ = Company.lens(Lens({ $0.name }, { $0.name = $1 }))
}
//public extension ChannelType where Element : MutationType {
public extension ChannelType where Source : StateEmitterType, Element == Mutation<Source.Element> {
}
//extension ChannelType where Element : MutationType, Element.T : Focusable {
// func focus<B>(lens: Lens<Element.T, B>) {
// focus
// }
//}
let artist = transceive(library.artists[0])
artist.focus(Artist.nameλ).value = "Foo"
//artist.focus(Artist.labelλ).focus(<#T##lens: Lens<Company?, X>##Lens<Company?, X>#>)
//struct ArtistLens<B> {
// let lens: Lens<Artist, B>
// // error: static stored properties not yet supported in generic types
// static let name = ArtistLens(lens: Lens({ $0.name }, { $0.name = $1 }))
//}
1
//struct ArtistLenses<T> {
// static let name = Lens<Artist, String>({ $0.name }, { $0.name = $1 })
//}
//protocol Focusable {
// associatedtype Prism : PrismType
//}
//
//protocol PrismType {
// associatedtype Focus
//}
//
//extension Focusable {
// static func lensZ<X, Source : StateEmitterType where Source.Element == Self>(lens: Lens<Self, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return { channel in focus(channel)(lens) }
// }
//
// static func focus<X, Source : StateEmitterType where Source.Element == Self>(channel: Channel<Source, Mutation<Source.Element>>) -> (Lens<Source.Element, X>) -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return channel.focus
// }
//}
//
////public extension ChannelType where Source : StateEmitterType, Element == Mutation<Source.Element> {
//
//extension PrismType {
// static func lensZ<X, Source : StateEmitterType where Source.Element == Focus>(lens: Lens<Focus, X>) -> Channel<Source, Mutation<Source.Element>> -> Channel<LensSource<Channel<Source, Mutation<Source.Element>>, X>, Mutation<X>> {
// return { channel in channel.focus(lens) }
// }
//}
//
//extension Song : Focusable {
// var prop: () -> Channel<ValueTransceiver<Song>, Mutation<Song>> { return { transceive(self) } }
//
// struct Prism : PrismType {
// typealias Focus = Song
//// static let title = Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))
// }
//}
//
//protocol Prasm {
// associatedtype Focus
//// var channel: Channel<T, Mutation<T>> { get }
//}
//
//class BasePrasm<T, B> : Prasm {
// typealias Focus = T
// let lens: Lens<T, B>
//
// init(lens: Lens<T, B>) {
// self.lens = lens
// }
//}
//
//extension Artist : Focusable {
// static let nameZ = Lens<Artist, String>({ $0.name }, { $0.name = $1 })
// static let songsZ = Lens<Artist, [Song]>({ $0.songs }, { $0.songs = $1 })
//
// static func focal(prism: Prosm) {
//
// }
//
//// static let nameZ = Artist.lensZ(Lens({ $0.name }, { $0.name = $1 }))(transceive(Artist(name: "", songs: [])))
//
// struct Prism : PrismType {
// typealias Focus = Artist
//
// static let name = Prism(lens: Lens({ $0.name }, { $0.name = $1 }))
//// static let songs = Prism(lens: Lens({ $0.songs }, { $0.songs = $1 }))
//
// let lens: Lens<Artist, String>
// init(lens: Lens<Artist, String>) {
// self.lens = lens
// }
// }
//
// class Prosm<B> : BasePrasm<Artist, B> {
//// let nameZ = Prosm.lensZ(Lens({ $0.name }, { $0.name = $1 }))
// static let name = Prosm(lens: Lens({ $0.name }, { $0.name = $1 }))
//
// override init(lens: Lens<Artist, String>) {
// super.init(lens: lens)
// }
//
// }
//}
//
//
//extension Album : Focusable {
// struct Prism : PrismType {
// typealias Focus = Album
//// static let title = Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))
//// static let year = Prism.lensZ(Lens({ $0.year }, { $0.year = $1 }))
//// static let label = Prism.lensZ(Lens({ $0.label }, { $0.label = $1 }))
//// static let tracks = Prism.lensZ(Lens({ $0.tracks }, { $0.tracks = $1 }))
// }
//}
//
//// Prism=Λ, Lens=λ
//var prince = library.artists[0]
//
//let artistZ = transceive(prince)
//artistZ.value.name
//
//
//Artist.focal(.name)
//
//1
//
//
//let name = Artist.focus(artistZ)(Artist.Prism.name)
//let name = Artist.Prism.name(artistZ)
//
//let name = Artist.Prism.lensZ(Lens({ $0.title }, { $0.title = $1 }))(artistZ)
//name.value = "The Artist Formerly Known As Prince"
//artistZ.value.name
//let princeΛ = prince.focus()
//
//princeΛ.nameλ.get(prince)
//princeΛ.nameλ.value = "The Artist Formerly Known as Prince"
//princeΛ.nameλ.value
//princeName.value
//princeName ∞= "The Artist Formerly Known as Prince"
//princeName.value
//prism.title.get(song)
//
//song = prism.title.set(song, "Blueberry Tophat")
//
//prism.title.get(song)
//song.title
//let prop = transceive((int: 1, dbl: 2.2, str: "Foo", sub: (a: true, b: 22, c: "")))
|
mit
|
tomburns/ios
|
FiveCalls/FiveCalls/MyImpactViewController.swift
|
1
|
4409
|
//
// MyImpactViewController.swift
// FiveCalls
//
// Created by Ben Scheirman on 2/6/17.
// Copyright © 2017 5calls. All rights reserved.
//
import UIKit
import Crashlytics
import Rswift
class MyImpactViewController : UITableViewController {
var viewModel: ImpactViewModel!
var totalCalls: Int?
@IBOutlet weak var headerLabel: UILabel!
@IBOutlet weak var subheadLabel: UILabel!
enum Sections: Int {
case stats
case contacts
case count
var cellIdentifier: Rswift.ReuseIdentifier<UIKit.UITableViewCell>? {
switch self {
case .stats: return R.reuseIdentifier.statCell
case .contacts: return R.reuseIdentifier.contactStatCell
default: return nil
}
}
}
enum StatRow: Int {
case madeContact
case voicemail
case unavailable
case count
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewDidLoad() {
super.viewDidLoad()
Answers.logCustomEvent(withName:"Screen: My Impact")
viewModel = ImpactViewModel(logs: ContactLogs.load().all)
let numberOfCalls = viewModel.numberOfCalls
headerLabel.text = impactMessage(for: numberOfCalls)
subheadLabel.isHidden = numberOfCalls == 0
let op = FetchStatsOperation()
op.completionBlock = {
self.totalCalls = op.numberOfCalls
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
OperationQueue.main.addOperation(op)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return Sections.count.rawValue
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch Sections(rawValue: section)! {
case .stats:
return StatRow.count.rawValue
case .contacts:
return 0
default: return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = Sections(rawValue: indexPath.section)!
let identifier = section.cellIdentifier
let cell = tableView.dequeueReusableCell(withIdentifier: identifier!, for: indexPath)!
switch section {
case .stats:
configureStatRow(cell: cell, stat: StatRow(rawValue: indexPath.row)!)
default: break
}
return cell
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
guard let total = totalCalls, section == Sections.stats.rawValue else { return nil }
let statsVm = StatsViewModel(numberOfCalls: total)
return R.string.localizable.communityCalls(statsVm.formattedNumberOfCalls)
}
private func impactMessage(for numberOfCalls: Int) -> String {
switch numberOfCalls {
case 0:
return R.string.localizable.yourImpactZero(numberOfCalls)
case 1:
return R.string.localizable.yourImpactSingle(numberOfCalls)
default:
return R.string.localizable.yourImpactMultiple(numberOfCalls)
}
}
private func configureStatRow(cell: UITableViewCell, stat: StatRow) {
switch stat {
case .madeContact:
cell.textLabel?.text = R.string.localizable.madeContact()
cell.detailTextLabel?.text = timesString(count: viewModel.madeContactCount)
case .unavailable:
cell.textLabel?.text = R.string.localizable.unavailable()
cell.detailTextLabel?.text = timesString(count: viewModel.unavailableCount)
case .voicemail:
cell.textLabel?.text = R.string.localizable.leftVoicemail()
cell.detailTextLabel?.text = timesString(count: viewModel.voicemailCount)
default: break
}
}
@IBAction func done(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
private func timesString(count: Int) -> String {
guard count != 1 else { return R.string.localizable.calledSingle(count) }
return R.string.localizable.calledMultiple(count)
}
}
|
mit
|
JeeLiu/DKStickyHeaderView
|
DKStickyHeaderView/DKStickyHeaderViewTests/DKStickyHeaderViewTests.swift
|
1
|
926
|
//
// DKStickyHeaderViewTests.swift
// DKStickyHeaderViewTests
//
// Created by 张奥 on 15/5/4.
// Copyright (c) 2015年 ZhangAo. All rights reserved.
//
import UIKit
import XCTest
class DKStickyHeaderViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
|
mit
|
allbto/WayThere
|
ios/WayThere/Pods/Nimble/Nimble/Wrappers/MatcherFunc.swift
|
158
|
2065
|
import Foundation
public struct FullMatcherFunc<T>: Matcher {
public let matcher: (Expression<T>, FailureMessage, Bool) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage, Bool) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage, false)
}
public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return !matcher(actualExpression, failureMessage, true)
}
}
public struct MatcherFunc<T>: BasicMatcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage)
}
}
public struct NonNilMatcherFunc<T>: NonNilBasicMatcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage)
}
}
public func fullMatcherFromBasicMatcher<M: BasicMatcher>(matcher: M) -> FullMatcherFunc<M.ValueType> {
return FullMatcherFunc { actualExpression, failureMessage, expectingToNotMatch in
return matcher.matches(actualExpression, failureMessage: failureMessage) != expectingToNotMatch
}
}
public func basicMatcherWithFailureMessage<M: NonNilBasicMatcher>(matcher: M, postprocessor: (FailureMessage) -> Void) -> NonNilMatcherFunc<M.ValueType> {
return NonNilMatcherFunc<M.ValueType> { actualExpression, failureMessage in
let result = matcher.matches(actualExpression, failureMessage: failureMessage)
postprocessor(failureMessage)
return result
}
}
|
mit
|
jathu/sweetercolor
|
SweetercolorTests/harmony_Test.swift
|
1
|
921
|
//
// harmony_Test.swift
// Sweetercolor
//
// Created by Jathu Satkunarajah - August 2015 - Toronto
// Copyright (c) 2015 Jathu Satkunarajah. All rights reserved.
//
import UIKit
import XCTest
class harmony_Test: XCTestCase {
// Test source: http://www.sessions.edu/color-calculator
func testBlack() {
let black = UIColor.black()
XCTAssertEqual(black.complement, black, "")
}
func testWhite() {
let white = UIColor.black()
XCTAssertEqual(white.complement, white, "")
}
func testSwiftYellow() {
let color = UIColor(hex: "#FFAC45")
XCTAssertTrue( color.complement.isEqual(to: UIColor(hex: "#4599FF"), strict: false) )
}
func testMyBeautifulDarkTwistedPink() {
let color = UIColor(hex: "#C6143B")
XCTAssertTrue( color.complement.isEqual(to: UIColor(hex: "#14C69F"), strict: false) )
}
}
|
mit
|
cc001/learnSwiftBySmallProjects
|
18-LimitCharacters/LimitCharacters/ViewController.swift
|
1
|
3807
|
//
// ViewController.swift
// LimitCharacters
//
// Created by 陈闯 on 2016/12/25.
// Copyright © 2016年 陈闯. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var tweetTextView: UITextView!
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var bottomView: UIView!
@IBOutlet weak var characterCountLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
avatarImageView.layer.cornerRadius = 23
avatarImageView.clipsToBounds = true
tweetTextView.delegate = self
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillShow(_:)), name:NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector:#selector(ViewController.keyBoardWillHide(_:)), name:NSNotification.Name.UIKeyboardWillHide, object: nil)
}
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
characterCountLabel.text = "\(140 - (textView.text?.characters.count)!)"
print(range.length, textView.text.characters.count)
// if range.length > 14 {
// return false
// } else {
let newLength = textView.text.characters.count + range.length
return newLength < 140
// }
}
func textViewDidChange(_ textView: UITextView) {
// var str = textView.text
// let endIndex: String.Index = advance(0, 10)
// var subStr = str.su
// textView.text = textView.text.substring(to: textView.text.sto.advancedBy(14))
}
func keyBoardWillShow(_ note:Notification) {
let userInfo = note.userInfo
let keyBoardBounds = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let deltaY = keyBoardBounds.size.height
let animations:(() -> Void) = {
self.bottomView.transform = CGAffineTransform(translationX: 0,y: -deltaY)
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else {
animations()
}
}
func keyBoardWillHide(_ note:Notification) {
let userInfo = note.userInfo
let duration = (userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
let animations:(() -> Void) = {
self.bottomView.transform = CGAffineTransform.identity
}
if duration > 0 {
let options = UIViewAnimationOptions(rawValue: UInt((userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).intValue << 16))
UIView.animate(withDuration: duration, delay: 0, options:options, animations: animations, completion: nil)
}else{
animations()
}
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
matteinn/VialerSIPLib
|
Example/VialerSIPLib/VSLTransferCallViewController.swift
|
1
|
4337
|
//
// VSLTransferCallViewController.swift
// Copyright © 2016 Devhouse Spindle. All rights reserved.
//
import UIKit
private var myContext = 0
@objc class VSLTransferCallViewController: VSLMakeCallViewController {
// MARK: - Configuration
fileprivate struct Configuration {
struct Segues {
static let SecondCallActive = "SecondCallActiveSegue"
static let UnwindToMainView = "UnwindToMainViewSegue"
static let ShowKeypad = "ShowKeypadSegue"
static let UnwindToFirstCallInProgress = "UnwindToFirstCallInProgressSegue"
}
}
// MARK: - Properties
var currentCall: VSLCall? {
didSet {
updateUI()
}
}
fileprivate var newCall: VSLCall?
// MARK - Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUI()
currentCall?.addObserver(self, forKeyPath: "callState", options: .new, context: &myContext)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
currentCall?.removeObserver(self, forKeyPath: "callState")
}
// MARK: - Outlets
@IBOutlet weak var currentCallNumberLabel: UILabel!
@IBOutlet weak var currentCallStatusLabel: UILabel!
// MARK: - Actions
@IBAction func cancelTransferButtonPressed(_ sender: UIBarButtonItem) {
if let call = currentCall, call.callState != .disconnected {
performSegue(withIdentifier: Configuration.Segues.UnwindToFirstCallInProgress, sender: nil)
} else {
performSegue(withIdentifier: Configuration.Segues.UnwindToMainView, sender: nil)
}
}
@IBAction override func callButtonPressed(_ sender: UIButton) {
guard let number = numberToDialLabel.text, number != "" else { return }
callManager.startCall(toNumber: number, for: currentCall!.account! ) { (call, error) in
if error != nil {
DDLogWrapper.logError("Could not start second call: \(error!)")
} else {
self.newCall = call
DispatchQueue.main.async {
self.performSegue(withIdentifier: Configuration.Segues.SecondCallActive, sender: nil)
}
}
}
}
override func updateUI() {
super.updateUI()
guard let call = currentCall else { return }
currentCallNumberLabel?.text = call.callerNumber!
if call.callState == .disconnected {
currentCallStatusLabel?.text = "Disconnected"
} else {
currentCallStatusLabel?.text = "ON HOLD"
}
}
// MARK: - Segues
@IBAction func unwindToSetupSecondCallSegue(_ segue: UIStoryboardSegue) {}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let secondCallVC = segue.destination as? VSLSecondCallViewController {
secondCallVC.firstCall = currentCall
secondCallVC.activeCall = newCall
} else if let callVC = segue.destination as? VSLCallViewController {
if let call = newCall, call.callState != .null && call.callState != .disconnected {
callVC.activeCall = call
} else if let call = currentCall, call.callState != .null && call.callState != .disconnected {
callVC.activeCall = call
}
}
}
// MARK: - KVO
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if context == &myContext && keyPath == "callState" {
DispatchQueue.main.async {
self.updateUI()
if let call = self.currentCall, call.callState == .disconnected {
if let newCall = self.newCall, newCall.callState != .null {
self.performSegue(withIdentifier: Configuration.Segues.UnwindToFirstCallInProgress, sender: nil)
} else {
self.performSegue(withIdentifier: Configuration.Segues.UnwindToMainView, sender: nil)
}
}
}
} else {
super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
}
}
}
|
gpl-3.0
|
roambotics/swift
|
test/stdlib/StringSwitch.swift
|
2
|
1835
|
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
var StringSwitchTests = TestSuite("StringSwitchTests")
func switchOver(_ s: String) -> Character {
let (first, second) = ("first", "second")
let ret1: Character
switch s {
case first: ret1 = "A"
case second[...]: ret1 = "B"
default: ret1 = "X"
}
let ret2: Character
switch s[...] {
case first: ret2 = "A"
case second[...]: ret2 = "B"
default: ret2 = "X"
}
expectEqual(ret1, ret2)
return ret1
}
func switchOver<S1: StringProtocol, S2: StringProtocol>(
_ s1: S1, _ s2: S2
) -> Character {
let (first, second) = ("first", "second")
// FIXME: Enable (https://github.com/apple/swift/issues/54896)
#if true
fatalError()
#else
let ret1: Character
switch s1 {
case first: ret1 = "A"
case second[...]: ret1 = "B"
case s2: ret2 = "="
default: ret1 = "X"
}
let ret2: Character
switch s2 {
case first: ret1 = "A"
case second[...]: ret1 = "B"
case s1: ret2 = "="
default: ret2 = "X"
}
expectEqual(ret1, ret2)
return ret1
#endif
}
StringSwitchTests.test("switch") {
let (first, second) = ("first", "second")
let same = "same"
let (foo, bar) = ("foo", "bar")
expectEqual("A", switchOver(first))
expectEqual("B", switchOver(second))
expectEqual("X", switchOver(foo))
// FIXME: Enable (https://github.com/apple/swift/issues/54896)
#if true
#else
expectEqual("A", switchOver(first, first))
expectEqual("B", switchOver(second, second))
expectEqual("=", switchOver(same, same))
expectEqual("X", switchOver(foo, bar))
expectEqual("A", switchOver(first[...], first))
expectEqual("B", switchOver(second[...], second))
expectEqual("=", switchOver(same[...], same))
expectEqual("X", switchOver(foo[...], bar))
#endif
}
runAllTests()
|
apache-2.0
|
pmick/RxAVFoundation
|
Package.swift
|
1
|
656
|
// swift-tools-version:5.1
import PackageDescription
let package = Package(
name: "RxAVFoundation",
platforms: [
.macOS(.v10_10), .iOS(.v9), .tvOS(.v9), .watchOS(.v3)
],
products: [
.library(
name: "RxAVFoundation",
targets: ["RxAVFoundation"]),
],
dependencies: [
.package(url: "https://github.com/ReactiveX/RxSwift.git", from: "6.0.0"),
],
targets: [
.target(
name: "RxAVFoundation",
dependencies: ["RxSwift", "RxCocoa"]),
.testTarget(
name: "RxAVFoundationTests",
dependencies: ["RxAVFoundation"]),
]
)
|
mit
|
Legoless/iOS-Course
|
2015-1/Lesson8/Messages/Messages/ReceiverViewController.swift
|
1
|
619
|
//
// ReceiverViewController.swift
// Messages
//
// Created by Dal Rupnik on 04/11/15.
// Copyright © 2015 Unified Sense. All rights reserved.
//
import UIKit
class ReceiverViewController: UIViewController {
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textMessage:", name: "TextMessage", object: nil)
}
func textMessage(notification: NSNotification) {
if let text = notification.object as? String {
textView.text = text
}
}
}
|
mit
|
poetmountain/MotionMachine
|
Tests/Tests/ValueAssistants/ValueAssistantGroupTests.swift
|
1
|
4176
|
//
// ValueAssistantGroupTests.swift
// MotionMachineTests
//
// Created by Brett Walker on 5/24/16.
// Copyright © 2016 Poet & Mountain, LLC. All rights reserved.
//
import XCTest
class ValueAssistantGroupTests: XCTestCase {
func test_add() {
let assistant = ValueAssistantGroup()
assistant.add(CGStructAssistant())
XCTAssertEqual(assistant.assistants.count, 1)
}
func test_additive() {
let structs = CGStructAssistant()
let ci_colors = CIColorAssistant()
let ui_colors = UIColorAssistant()
let assistant = ValueAssistantGroup(assistants: [structs, ci_colors, ui_colors])
assistant.additive = true
assistant.additiveWeighting = 0.5
XCTAssertEqual(structs.additive, assistant.additive)
XCTAssertEqual(ci_colors.additive, assistant.additive)
XCTAssertEqual(ui_colors.additive, assistant.additive)
XCTAssertEqual(structs.additiveWeighting, assistant.additiveWeighting)
XCTAssertEqual(ci_colors.additiveWeighting, assistant.additiveWeighting)
XCTAssertEqual(ui_colors.additiveWeighting, assistant.additiveWeighting)
}
func test_generateProperties() {
let assistant = ValueAssistantGroup(assistants: [CGStructAssistant(), CIColorAssistant(), UIColorAssistant()])
let tester = Tester()
let rect = CGRect.init(x: 0.0, y: 10.0, width: 50.0, height: 0.0)
let path = "rect"
if let struct_val = CGStructAssistant.valueForCGStruct(rect), let target = tester.value(forKeyPath: path) {
let states = PropertyStates(path: path, end: struct_val)
let props = try! assistant.generateProperties(targetObject: target as AnyObject, propertyStates: states)
XCTAssertEqual(props.count, 2)
if (props.count == 2) {
let y_prop = props[0]
let width_prop = props[1]
XCTAssertEqual(y_prop.path, "rect.origin.y")
XCTAssertEqual(y_prop.end, 10.0)
XCTAssertEqual(width_prop.path, "rect.size.width")
XCTAssertEqual(width_prop.end, 50.0)
}
}
}
func test_updateValue_CGRect() {
let assistant = ValueAssistantGroup(assistants: [CGStructAssistant()])
let old_value = NSValue.init(cgRect: CGRect.init(x: 0.0, y: 0.0, width: 10.0, height: 10.0))
var new_value: NSValue
new_value = assistant.updateValue(inObject: old_value, newValues: ["origin.x" : 10.0]) as! NSValue
XCTAssertEqual(new_value.cgRectValue.origin.x, 10.0)
XCTAssertEqual(new_value.cgRectValue.origin.y, old_value.cgRectValue.origin.y)
}
func test_updateValue_UIColor() {
let assistant = ValueAssistantGroup(assistants: [CGStructAssistant(), UIColorAssistant()])
let old_value = UIColor.init(red: 0.0, green: 0.5, blue: 0.0, alpha: 1.0)
var new_value: UIColor
new_value = assistant.updateValue(inObject: old_value, newValues: ["red" : 1.0]) as! UIColor
var red: CGFloat = 0.0, green: CGFloat = 0.0, blue: CGFloat = 0.0, alpha: CGFloat = 0.0
new_value.getRed(&red, green: &green, blue: &blue, alpha: &alpha)
XCTAssertEqual(red, 1.0)
XCTAssertEqual(blue, 0.0)
}
func test_retrieveValue() {
let assistant = ValueAssistantGroup(assistants: [CGStructAssistant(), UIColorAssistant()])
let object = NSValue.init(cgRect: CGRect.init(x: 0.0, y: 0.0, width: 10.0, height: 10.0))
let value = assistant.retrieveValue(inObject: object, keyPath: "size.width")
XCTAssertEqual(value, 10.0)
var color = UIColor.init(red: 0.0, green: 0.0, blue: 0.5, alpha: 1.0)
var cvalue = assistant.retrieveValue(inObject: color, keyPath: "blue")
XCTAssertEqual(cvalue, 0.5)
color = UIColor.init(hue: 0.5, saturation: 0.2, brightness: 1.0, alpha: 1.0)
cvalue = assistant.retrieveValue(inObject: color, keyPath: "hue")
XCTAssertEqual(cvalue, 0.5)
}
}
|
mit
|
gezhixin/MoreThanDrawerMenumDemo
|
special/Mian/favourite/FavouriteViewController.swift
|
1
|
528
|
//
// FavouriteViewController.swift
// special
//
// Created by 葛枝鑫 on 15/4/17.
// Copyright (c) 2015年 葛枝鑫. All rights reserved.
//
import UIKit
class FavouriteViewController: LeftRightMenuBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.navTitle("我已收藏的")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func leftAction() {
self.rootViewController.menuBtnClicked()
}
}
|
mit
|
xedin/swift
|
test/stdlib/VarArgs.swift
|
10
|
4712
|
// RUN: %target-run-stdlib-swift -parse-stdlib %s | %FileCheck %s
// REQUIRES: executable_test
import Swift
#if _runtime(_ObjC)
import Darwin
import CoreGraphics
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku)
import Glibc
typealias CGFloat = Double
#elseif os(Windows)
import MSVCRT
#if arch(x86_64) || arch(arm64)
typealias CGFloat = Double
#else
typealias CGFloat = Float
#endif
#else
#error("Unsupported platform")
#endif
func my_printf(_ format: String, _ arguments: CVarArg...) {
_ = withVaList(arguments) {
vprintf(format, $0)
}
}
func test_varArgs0() {
// CHECK: The answer to life and everything is 42, 42, -42, 3.14
my_printf(
"The answer to life and everything is %ld, %u, %d, %f\n",
42, UInt32(42), Int16(-42), 3.14159279)
}
test_varArgs0()
func test_varArgs1() {
var args = [CVarArg]()
var format = "dig it: "
for i in 0..<12 {
args.append(Int16(-i))
args.append(Float(i))
format += "%d %2g "
}
// CHECK: dig it: 0 0 -1 1 -2 2 -3 3 -4 4 -5 5 -6 6 -7 7 -8 8 -9 9 -10 10 -11 11
_ = withVaList(args) {
vprintf(format + "\n", $0)
}
}
test_varArgs1()
func test_varArgs3() {
var args = [CVarArg]()
let format = "pointers: '%p' '%p' '%p' '%p' '%p'\n"
args.append(OpaquePointer(bitPattern: 0x1234_5670)!)
args.append(OpaquePointer(bitPattern: 0x1234_5671)!)
args.append(UnsafePointer<Int>(bitPattern: 0x1234_5672)!)
args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5673)!)
#if _runtime(_ObjC)
args.append(AutoreleasingUnsafeMutablePointer<AnyObject>(
UnsafeMutablePointer<AnyObject>(bitPattern: 0x1234_5674)!))
#else
//Linux does not support AutoreleasingUnsafeMutablePointer; put placeholder.
args.append(UnsafeMutablePointer<Float>(bitPattern: 0x1234_5674)!)
#endif
// CHECK: {{pointers: '(0x)?0*12345670' '(0x)?0*12345671' '(0x)?0*12345672' '(0x)?0*12345673' '(0x)?0*12345674'}}
_ = withVaList(args) {
vprintf(format, $0)
}
}
test_varArgs3()
func test_varArgs4() {
// Verify alignment of va_list contents.
// On some architectures some types are better-
// aligned than Int and must be packaged with care.
let i8 = Int8(1)
let i16 = Int16(2)
let i32 = Int32(3)
let i64 = 4444444444444444 as Int64
let u8 = UInt8(10)
let u16 = UInt16(20)
let u32 = UInt32(30)
let u64 = 4040404040404040 as UInt64
let f32 = Float(1.1)
let f64 = Double(2.2)
let fCG = CGFloat(3.3)
my_printf("a %g %d %g %d %g %d a\n", f32, i8, f64, i8, fCG, i8)
my_printf("b %d %g %d %g %d %g %d b\n", i8, f32, i8, f64, i8, fCG, i8)
my_printf("c %d %d %d %d %d %lld %d c\n", i8, i16, i8, i32, i8, i64, i8)
my_printf("d %d %d %d %d %d %d %lld %d d\n",i8, i8, i16, i8, i32, i8, i64, i8)
my_printf("e %u %u %u %u %u %llu %u e\n", u8, u16, u8, u32, u8, u64, u8)
my_printf("f %u %u %u %u %u %u %llu %u f\n",u8, u8, u16, u8, u32, u8, u64, u8)
// CHECK: a 1.1 1 2.2 1 3.3 1 a
// CHECK: b 1 1.1 1 2.2 1 3.3 1 b
// CHECK: c 1 2 1 3 1 4444444444444444 1 c
// CHECK: d 1 1 2 1 3 1 4444444444444444 1 d
// CHECK: e 10 20 10 30 10 4040404040404040 10 e
// CHECK: f 10 10 20 10 30 10 4040404040404040 10 f
}
test_varArgs4()
func test_varArgs5() {
var args = [CVarArg]()
// Confirm the absence of a bug (on x86-64) wherein floats were stored in
// the GP register-save area after the SSE register-save area was
// exhausted, rather than spilling into the overflow argument area.
//
// This is not caught by test_varArgs1 above, because it exhauses the
// GP register-save area before the SSE area.
var format = "rdar-32547102: "
for i in 0..<12 {
args.append(Float(i))
format += "%.1f "
}
// CHECK: rdar-32547102: 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0
_ = withVaList(args) {
vprintf(format + "\n", $0)
}
}
test_varArgs5()
func test_varArgs6() {
// Verify alignment of va_list contents when `Float80` is present.
let i8 = Int8(1)
let f32 = Float(1.1)
let f64 = Double(2.2)
#if !os(Windows) && (arch(i386) || arch(x86_64))
let f80 = Float80(4.5)
my_printf("a %g %d %g %d %Lg %d %g a\n", f32, i8, f64, i8, f80, i8, f32)
my_printf("b %d %g %d %g %d %Lg %d %g b\n", i8, f32, i8, f64, i8, f80, i8, f32)
#else // just a dummy to make FileCheck happy, since it ignores `#if`s
let dummy = Double(4.5)
my_printf("a %g %d %g %d %g %d %g a\n", f32, i8, f64, i8, dummy, i8, f32)
my_printf("b %d %g %d %g %d %g %d %g b\n", i8, f32, i8, f64, i8, dummy, i8, f32)
#endif
// CHECK: a 1.1 1 2.2 1 4.5 1 1.1 a
// CHECK: b 1 1.1 1 2.2 1 4.5 1 1.1 b
}
test_varArgs6()
// CHECK: done.
print("done.")
|
apache-2.0
|
turingcorp/kitkat
|
kitkat/Controller/CParent.swift
|
1
|
1379
|
import UIKit
class CParent:UIViewController
{
private var statusBarStyle:UIStatusBarStyle = UIStatusBarStyle.Default
override func viewDidLoad()
{
super.viewDidLoad()
let game:CGame = CGame()
addChildViewController(game)
view.addSubview(game.view)
game.didMoveToParentViewController(self)
let views:[String:AnyObject] = [
"child":game.view]
let metrics:[String:AnyObject] = [:]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-0-[child]-0-|",
options:[],
metrics:metrics,
views:views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(
"V:|-0-[child]-0-|",
options:[],
metrics:metrics,
views:views))
}
override func preferredStatusBarStyle() -> UIStatusBarStyle
{
return statusBarStyle
}
override func prefersStatusBarHidden() -> Bool
{
return true
}
//MARK: public
func statusBarLight()
{
statusBarStyle = UIStatusBarStyle.LightContent
setNeedsStatusBarAppearanceUpdate()
}
func statusBarDefault()
{
statusBarStyle = UIStatusBarStyle.Default
setNeedsStatusBarAppearanceUpdate()
}
}
|
mit
|
geowarsong/UG-Lemondo
|
InstaUG/InstaUG/InstaUG/Core/Constants.swift
|
1
|
265
|
//
// Constants.swift
// InstaUG
//
// Created by C0mrade on 6/14/17.
// Copyright © 2017 Lemondo Apps. All rights reserved.
//
import UIKit
struct Constants {
struct Http {
static let getUrl = "https://mgldev.ge/UsersNew.json"
}
}
|
apache-2.0
|
crazypoo/PTools
|
Pods/Appz/Appz/Appz/Apps/Netflix.swift
|
2
|
979
|
//
// Netflix.swift
// Pods
//
// Created by Mariam AlJamea on 1/8/16.
// Copyright © 2016 kitz. All rights reserved.
//
public extension Applications {
public struct Netflix: ExternalApplication {
public typealias ActionType = Applications.Netflix.Action
public let scheme = "nflx:"
public let fallbackURL = "https://www.netflix.com"
public let appStoreId = "363590051"
public init() {}
}
}
// MARK: - Actions
public extension Applications.Netflix {
public enum Action {
case open
}
}
extension Applications.Netflix.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
case .open:
return ActionPaths(
app: Path(
pathComponents: ["app"],
queryParameters: [:]
),
web: Path()
)
}
}
}
|
mit
|
dche/GLMath
|
Sources/Swizzle.swift
|
1
|
53060
|
//
// GLMath - Swizzle.swift
//
// Copyright (c) 2016 The GLMath authors.
// Licensed under MIT License.
// NOTE:
// - Do NOT edit this file. Edit `Swizzle.swift.gyb` file instead.
// - Combinations of `s, t, u, v` are not implemented.
// TODO: Swizzle properties shall be settable.
public extension Vector2 {
var r: Component { return self.x }
var g: Component { return self.y }
var yy: Self { return Self(self.y, self.y) }
var yx: Self { return Self(self.y, self.x) }
var xy: Self { return Self(self.x, self.y) }
var xx: Self { return Self(self.x, self.x) }
var rr: Self { return Self(self.r, self.r) }
var rg: Self { return Self(self.r, self.g) }
var gr: Self { return Self(self.g, self.r) }
var gg: Self { return Self(self.g, self.g) }
}
public extension Vector3 {
var r: Component { return self.x }
var g: Component { return self.y }
var b: Component { return self.z }
var yy: AssociatedVector2 { return AssociatedVector2(self.y, self.y) }
var yx: AssociatedVector2 { return AssociatedVector2(self.y, self.x) }
var yz: AssociatedVector2 { return AssociatedVector2(self.y, self.z) }
var xy: AssociatedVector2 { return AssociatedVector2(self.x, self.y) }
var xx: AssociatedVector2 { return AssociatedVector2(self.x, self.x) }
var xz: AssociatedVector2 { return AssociatedVector2(self.x, self.z) }
var zy: AssociatedVector2 { return AssociatedVector2(self.z, self.y) }
var zx: AssociatedVector2 { return AssociatedVector2(self.z, self.x) }
var zz: AssociatedVector2 { return AssociatedVector2(self.z, self.z) }
var yyy: Self { return Self(self.y, self.y, self.y) }
var yyx: Self { return Self(self.y, self.y, self.x) }
var yyz: Self { return Self(self.y, self.y, self.z) }
var yxy: Self { return Self(self.y, self.x, self.y) }
var yxx: Self { return Self(self.y, self.x, self.x) }
var yxz: Self { return Self(self.y, self.x, self.z) }
var yzy: Self { return Self(self.y, self.z, self.y) }
var yzx: Self { return Self(self.y, self.z, self.x) }
var yzz: Self { return Self(self.y, self.z, self.z) }
var xyy: Self { return Self(self.x, self.y, self.y) }
var xyx: Self { return Self(self.x, self.y, self.x) }
var xyz: Self { return Self(self.x, self.y, self.z) }
var xxy: Self { return Self(self.x, self.x, self.y) }
var xxx: Self { return Self(self.x, self.x, self.x) }
var xxz: Self { return Self(self.x, self.x, self.z) }
var xzy: Self { return Self(self.x, self.z, self.y) }
var xzx: Self { return Self(self.x, self.z, self.x) }
var xzz: Self { return Self(self.x, self.z, self.z) }
var zyy: Self { return Self(self.z, self.y, self.y) }
var zyx: Self { return Self(self.z, self.y, self.x) }
var zyz: Self { return Self(self.z, self.y, self.z) }
var zxy: Self { return Self(self.z, self.x, self.y) }
var zxx: Self { return Self(self.z, self.x, self.x) }
var zxz: Self { return Self(self.z, self.x, self.z) }
var zzy: Self { return Self(self.z, self.z, self.y) }
var zzx: Self { return Self(self.z, self.z, self.x) }
var zzz: Self { return Self(self.z, self.z, self.z) }
var rr: AssociatedVector2 { return AssociatedVector2(self.r, self.r) }
var rb: AssociatedVector2 { return AssociatedVector2(self.r, self.b) }
var rg: AssociatedVector2 { return AssociatedVector2(self.r, self.g) }
var br: AssociatedVector2 { return AssociatedVector2(self.b, self.r) }
var bb: AssociatedVector2 { return AssociatedVector2(self.b, self.b) }
var bg: AssociatedVector2 { return AssociatedVector2(self.b, self.g) }
var gr: AssociatedVector2 { return AssociatedVector2(self.g, self.r) }
var gb: AssociatedVector2 { return AssociatedVector2(self.g, self.b) }
var gg: AssociatedVector2 { return AssociatedVector2(self.g, self.g) }
var rrr: Self { return Self(self.r, self.r, self.r) }
var rrb: Self { return Self(self.r, self.r, self.b) }
var rrg: Self { return Self(self.r, self.r, self.g) }
var rbr: Self { return Self(self.r, self.b, self.r) }
var rbb: Self { return Self(self.r, self.b, self.b) }
var rbg: Self { return Self(self.r, self.b, self.g) }
var rgr: Self { return Self(self.r, self.g, self.r) }
var rgb: Self { return Self(self.r, self.g, self.b) }
var rgg: Self { return Self(self.r, self.g, self.g) }
var brr: Self { return Self(self.b, self.r, self.r) }
var brb: Self { return Self(self.b, self.r, self.b) }
var brg: Self { return Self(self.b, self.r, self.g) }
var bbr: Self { return Self(self.b, self.b, self.r) }
var bbb: Self { return Self(self.b, self.b, self.b) }
var bbg: Self { return Self(self.b, self.b, self.g) }
var bgr: Self { return Self(self.b, self.g, self.r) }
var bgb: Self { return Self(self.b, self.g, self.b) }
var bgg: Self { return Self(self.b, self.g, self.g) }
var grr: Self { return Self(self.g, self.r, self.r) }
var grb: Self { return Self(self.g, self.r, self.b) }
var grg: Self { return Self(self.g, self.r, self.g) }
var gbr: Self { return Self(self.g, self.b, self.r) }
var gbb: Self { return Self(self.g, self.b, self.b) }
var gbg: Self { return Self(self.g, self.b, self.g) }
var ggr: Self { return Self(self.g, self.g, self.r) }
var ggb: Self { return Self(self.g, self.g, self.b) }
var ggg: Self { return Self(self.g, self.g, self.g) }
}
public extension Vector4 {
var r: Component { return self.x }
var g: Component { return self.y }
var b: Component { return self.z }
var a: Component { return self.w }
var yy: AssociatedVector2 { return AssociatedVector2(self.y, self.y) }
var yx: AssociatedVector2 { return AssociatedVector2(self.y, self.x) }
var yz: AssociatedVector2 { return AssociatedVector2(self.y, self.z) }
var yw: AssociatedVector2 { return AssociatedVector2(self.y, self.w) }
var xy: AssociatedVector2 { return AssociatedVector2(self.x, self.y) }
var xx: AssociatedVector2 { return AssociatedVector2(self.x, self.x) }
var xz: AssociatedVector2 { return AssociatedVector2(self.x, self.z) }
var xw: AssociatedVector2 { return AssociatedVector2(self.x, self.w) }
var zy: AssociatedVector2 { return AssociatedVector2(self.z, self.y) }
var zx: AssociatedVector2 { return AssociatedVector2(self.z, self.x) }
var zz: AssociatedVector2 { return AssociatedVector2(self.z, self.z) }
var zw: AssociatedVector2 { return AssociatedVector2(self.z, self.w) }
var wy: AssociatedVector2 { return AssociatedVector2(self.w, self.y) }
var wx: AssociatedVector2 { return AssociatedVector2(self.w, self.x) }
var wz: AssociatedVector2 { return AssociatedVector2(self.w, self.z) }
var ww: AssociatedVector2 { return AssociatedVector2(self.w, self.w) }
var yyy: AssociatedVector3 { return AssociatedVector3(self.y, self.y, self.y) }
var yyx: AssociatedVector3 { return AssociatedVector3(self.y, self.y, self.x) }
var yyz: AssociatedVector3 { return AssociatedVector3(self.y, self.y, self.z) }
var yyw: AssociatedVector3 { return AssociatedVector3(self.y, self.y, self.w) }
var yxy: AssociatedVector3 { return AssociatedVector3(self.y, self.x, self.y) }
var yxx: AssociatedVector3 { return AssociatedVector3(self.y, self.x, self.x) }
var yxz: AssociatedVector3 { return AssociatedVector3(self.y, self.x, self.z) }
var yxw: AssociatedVector3 { return AssociatedVector3(self.y, self.x, self.w) }
var yzy: AssociatedVector3 { return AssociatedVector3(self.y, self.z, self.y) }
var yzx: AssociatedVector3 { return AssociatedVector3(self.y, self.z, self.x) }
var yzz: AssociatedVector3 { return AssociatedVector3(self.y, self.z, self.z) }
var yzw: AssociatedVector3 { return AssociatedVector3(self.y, self.z, self.w) }
var ywy: AssociatedVector3 { return AssociatedVector3(self.y, self.w, self.y) }
var ywx: AssociatedVector3 { return AssociatedVector3(self.y, self.w, self.x) }
var ywz: AssociatedVector3 { return AssociatedVector3(self.y, self.w, self.z) }
var yww: AssociatedVector3 { return AssociatedVector3(self.y, self.w, self.w) }
var xyy: AssociatedVector3 { return AssociatedVector3(self.x, self.y, self.y) }
var xyx: AssociatedVector3 { return AssociatedVector3(self.x, self.y, self.x) }
var xyz: AssociatedVector3 { return AssociatedVector3(self.x, self.y, self.z) }
var xyw: AssociatedVector3 { return AssociatedVector3(self.x, self.y, self.w) }
var xxy: AssociatedVector3 { return AssociatedVector3(self.x, self.x, self.y) }
var xxx: AssociatedVector3 { return AssociatedVector3(self.x, self.x, self.x) }
var xxz: AssociatedVector3 { return AssociatedVector3(self.x, self.x, self.z) }
var xxw: AssociatedVector3 { return AssociatedVector3(self.x, self.x, self.w) }
var xzy: AssociatedVector3 { return AssociatedVector3(self.x, self.z, self.y) }
var xzx: AssociatedVector3 { return AssociatedVector3(self.x, self.z, self.x) }
var xzz: AssociatedVector3 { return AssociatedVector3(self.x, self.z, self.z) }
var xzw: AssociatedVector3 { return AssociatedVector3(self.x, self.z, self.w) }
var xwy: AssociatedVector3 { return AssociatedVector3(self.x, self.w, self.y) }
var xwx: AssociatedVector3 { return AssociatedVector3(self.x, self.w, self.x) }
var xwz: AssociatedVector3 { return AssociatedVector3(self.x, self.w, self.z) }
var xww: AssociatedVector3 { return AssociatedVector3(self.x, self.w, self.w) }
var zyy: AssociatedVector3 { return AssociatedVector3(self.z, self.y, self.y) }
var zyx: AssociatedVector3 { return AssociatedVector3(self.z, self.y, self.x) }
var zyz: AssociatedVector3 { return AssociatedVector3(self.z, self.y, self.z) }
var zyw: AssociatedVector3 { return AssociatedVector3(self.z, self.y, self.w) }
var zxy: AssociatedVector3 { return AssociatedVector3(self.z, self.x, self.y) }
var zxx: AssociatedVector3 { return AssociatedVector3(self.z, self.x, self.x) }
var zxz: AssociatedVector3 { return AssociatedVector3(self.z, self.x, self.z) }
var zxw: AssociatedVector3 { return AssociatedVector3(self.z, self.x, self.w) }
var zzy: AssociatedVector3 { return AssociatedVector3(self.z, self.z, self.y) }
var zzx: AssociatedVector3 { return AssociatedVector3(self.z, self.z, self.x) }
var zzz: AssociatedVector3 { return AssociatedVector3(self.z, self.z, self.z) }
var zzw: AssociatedVector3 { return AssociatedVector3(self.z, self.z, self.w) }
var zwy: AssociatedVector3 { return AssociatedVector3(self.z, self.w, self.y) }
var zwx: AssociatedVector3 { return AssociatedVector3(self.z, self.w, self.x) }
var zwz: AssociatedVector3 { return AssociatedVector3(self.z, self.w, self.z) }
var zww: AssociatedVector3 { return AssociatedVector3(self.z, self.w, self.w) }
var wyy: AssociatedVector3 { return AssociatedVector3(self.w, self.y, self.y) }
var wyx: AssociatedVector3 { return AssociatedVector3(self.w, self.y, self.x) }
var wyz: AssociatedVector3 { return AssociatedVector3(self.w, self.y, self.z) }
var wyw: AssociatedVector3 { return AssociatedVector3(self.w, self.y, self.w) }
var wxy: AssociatedVector3 { return AssociatedVector3(self.w, self.x, self.y) }
var wxx: AssociatedVector3 { return AssociatedVector3(self.w, self.x, self.x) }
var wxz: AssociatedVector3 { return AssociatedVector3(self.w, self.x, self.z) }
var wxw: AssociatedVector3 { return AssociatedVector3(self.w, self.x, self.w) }
var wzy: AssociatedVector3 { return AssociatedVector3(self.w, self.z, self.y) }
var wzx: AssociatedVector3 { return AssociatedVector3(self.w, self.z, self.x) }
var wzz: AssociatedVector3 { return AssociatedVector3(self.w, self.z, self.z) }
var wzw: AssociatedVector3 { return AssociatedVector3(self.w, self.z, self.w) }
var wwy: AssociatedVector3 { return AssociatedVector3(self.w, self.w, self.y) }
var wwx: AssociatedVector3 { return AssociatedVector3(self.w, self.w, self.x) }
var wwz: AssociatedVector3 { return AssociatedVector3(self.w, self.w, self.z) }
var www: AssociatedVector3 { return AssociatedVector3(self.w, self.w, self.w) }
var yyyy: Self { return Self(self.y, self.y, self.y, self.y) }
var yyyx: Self { return Self(self.y, self.y, self.y, self.x) }
var yyyz: Self { return Self(self.y, self.y, self.y, self.z) }
var yyyw: Self { return Self(self.y, self.y, self.y, self.w) }
var yyxy: Self { return Self(self.y, self.y, self.x, self.y) }
var yyxx: Self { return Self(self.y, self.y, self.x, self.x) }
var yyxz: Self { return Self(self.y, self.y, self.x, self.z) }
var yyxw: Self { return Self(self.y, self.y, self.x, self.w) }
var yyzy: Self { return Self(self.y, self.y, self.z, self.y) }
var yyzx: Self { return Self(self.y, self.y, self.z, self.x) }
var yyzz: Self { return Self(self.y, self.y, self.z, self.z) }
var yyzw: Self { return Self(self.y, self.y, self.z, self.w) }
var yywy: Self { return Self(self.y, self.y, self.w, self.y) }
var yywx: Self { return Self(self.y, self.y, self.w, self.x) }
var yywz: Self { return Self(self.y, self.y, self.w, self.z) }
var yyww: Self { return Self(self.y, self.y, self.w, self.w) }
var yxyy: Self { return Self(self.y, self.x, self.y, self.y) }
var yxyx: Self { return Self(self.y, self.x, self.y, self.x) }
var yxyz: Self { return Self(self.y, self.x, self.y, self.z) }
var yxyw: Self { return Self(self.y, self.x, self.y, self.w) }
var yxxy: Self { return Self(self.y, self.x, self.x, self.y) }
var yxxx: Self { return Self(self.y, self.x, self.x, self.x) }
var yxxz: Self { return Self(self.y, self.x, self.x, self.z) }
var yxxw: Self { return Self(self.y, self.x, self.x, self.w) }
var yxzy: Self { return Self(self.y, self.x, self.z, self.y) }
var yxzx: Self { return Self(self.y, self.x, self.z, self.x) }
var yxzz: Self { return Self(self.y, self.x, self.z, self.z) }
var yxzw: Self { return Self(self.y, self.x, self.z, self.w) }
var yxwy: Self { return Self(self.y, self.x, self.w, self.y) }
var yxwx: Self { return Self(self.y, self.x, self.w, self.x) }
var yxwz: Self { return Self(self.y, self.x, self.w, self.z) }
var yxww: Self { return Self(self.y, self.x, self.w, self.w) }
var yzyy: Self { return Self(self.y, self.z, self.y, self.y) }
var yzyx: Self { return Self(self.y, self.z, self.y, self.x) }
var yzyz: Self { return Self(self.y, self.z, self.y, self.z) }
var yzyw: Self { return Self(self.y, self.z, self.y, self.w) }
var yzxy: Self { return Self(self.y, self.z, self.x, self.y) }
var yzxx: Self { return Self(self.y, self.z, self.x, self.x) }
var yzxz: Self { return Self(self.y, self.z, self.x, self.z) }
var yzxw: Self { return Self(self.y, self.z, self.x, self.w) }
var yzzy: Self { return Self(self.y, self.z, self.z, self.y) }
var yzzx: Self { return Self(self.y, self.z, self.z, self.x) }
var yzzz: Self { return Self(self.y, self.z, self.z, self.z) }
var yzzw: Self { return Self(self.y, self.z, self.z, self.w) }
var yzwy: Self { return Self(self.y, self.z, self.w, self.y) }
var yzwx: Self { return Self(self.y, self.z, self.w, self.x) }
var yzwz: Self { return Self(self.y, self.z, self.w, self.z) }
var yzww: Self { return Self(self.y, self.z, self.w, self.w) }
var ywyy: Self { return Self(self.y, self.w, self.y, self.y) }
var ywyx: Self { return Self(self.y, self.w, self.y, self.x) }
var ywyz: Self { return Self(self.y, self.w, self.y, self.z) }
var ywyw: Self { return Self(self.y, self.w, self.y, self.w) }
var ywxy: Self { return Self(self.y, self.w, self.x, self.y) }
var ywxx: Self { return Self(self.y, self.w, self.x, self.x) }
var ywxz: Self { return Self(self.y, self.w, self.x, self.z) }
var ywxw: Self { return Self(self.y, self.w, self.x, self.w) }
var ywzy: Self { return Self(self.y, self.w, self.z, self.y) }
var ywzx: Self { return Self(self.y, self.w, self.z, self.x) }
var ywzz: Self { return Self(self.y, self.w, self.z, self.z) }
var ywzw: Self { return Self(self.y, self.w, self.z, self.w) }
var ywwy: Self { return Self(self.y, self.w, self.w, self.y) }
var ywwx: Self { return Self(self.y, self.w, self.w, self.x) }
var ywwz: Self { return Self(self.y, self.w, self.w, self.z) }
var ywww: Self { return Self(self.y, self.w, self.w, self.w) }
var xyyy: Self { return Self(self.x, self.y, self.y, self.y) }
var xyyx: Self { return Self(self.x, self.y, self.y, self.x) }
var xyyz: Self { return Self(self.x, self.y, self.y, self.z) }
var xyyw: Self { return Self(self.x, self.y, self.y, self.w) }
var xyxy: Self { return Self(self.x, self.y, self.x, self.y) }
var xyxx: Self { return Self(self.x, self.y, self.x, self.x) }
var xyxz: Self { return Self(self.x, self.y, self.x, self.z) }
var xyxw: Self { return Self(self.x, self.y, self.x, self.w) }
var xyzy: Self { return Self(self.x, self.y, self.z, self.y) }
var xyzx: Self { return Self(self.x, self.y, self.z, self.x) }
var xyzz: Self { return Self(self.x, self.y, self.z, self.z) }
var xyzw: Self { return Self(self.x, self.y, self.z, self.w) }
var xywy: Self { return Self(self.x, self.y, self.w, self.y) }
var xywx: Self { return Self(self.x, self.y, self.w, self.x) }
var xywz: Self { return Self(self.x, self.y, self.w, self.z) }
var xyww: Self { return Self(self.x, self.y, self.w, self.w) }
var xxyy: Self { return Self(self.x, self.x, self.y, self.y) }
var xxyx: Self { return Self(self.x, self.x, self.y, self.x) }
var xxyz: Self { return Self(self.x, self.x, self.y, self.z) }
var xxyw: Self { return Self(self.x, self.x, self.y, self.w) }
var xxxy: Self { return Self(self.x, self.x, self.x, self.y) }
var xxxx: Self { return Self(self.x, self.x, self.x, self.x) }
var xxxz: Self { return Self(self.x, self.x, self.x, self.z) }
var xxxw: Self { return Self(self.x, self.x, self.x, self.w) }
var xxzy: Self { return Self(self.x, self.x, self.z, self.y) }
var xxzx: Self { return Self(self.x, self.x, self.z, self.x) }
var xxzz: Self { return Self(self.x, self.x, self.z, self.z) }
var xxzw: Self { return Self(self.x, self.x, self.z, self.w) }
var xxwy: Self { return Self(self.x, self.x, self.w, self.y) }
var xxwx: Self { return Self(self.x, self.x, self.w, self.x) }
var xxwz: Self { return Self(self.x, self.x, self.w, self.z) }
var xxww: Self { return Self(self.x, self.x, self.w, self.w) }
var xzyy: Self { return Self(self.x, self.z, self.y, self.y) }
var xzyx: Self { return Self(self.x, self.z, self.y, self.x) }
var xzyz: Self { return Self(self.x, self.z, self.y, self.z) }
var xzyw: Self { return Self(self.x, self.z, self.y, self.w) }
var xzxy: Self { return Self(self.x, self.z, self.x, self.y) }
var xzxx: Self { return Self(self.x, self.z, self.x, self.x) }
var xzxz: Self { return Self(self.x, self.z, self.x, self.z) }
var xzxw: Self { return Self(self.x, self.z, self.x, self.w) }
var xzzy: Self { return Self(self.x, self.z, self.z, self.y) }
var xzzx: Self { return Self(self.x, self.z, self.z, self.x) }
var xzzz: Self { return Self(self.x, self.z, self.z, self.z) }
var xzzw: Self { return Self(self.x, self.z, self.z, self.w) }
var xzwy: Self { return Self(self.x, self.z, self.w, self.y) }
var xzwx: Self { return Self(self.x, self.z, self.w, self.x) }
var xzwz: Self { return Self(self.x, self.z, self.w, self.z) }
var xzww: Self { return Self(self.x, self.z, self.w, self.w) }
var xwyy: Self { return Self(self.x, self.w, self.y, self.y) }
var xwyx: Self { return Self(self.x, self.w, self.y, self.x) }
var xwyz: Self { return Self(self.x, self.w, self.y, self.z) }
var xwyw: Self { return Self(self.x, self.w, self.y, self.w) }
var xwxy: Self { return Self(self.x, self.w, self.x, self.y) }
var xwxx: Self { return Self(self.x, self.w, self.x, self.x) }
var xwxz: Self { return Self(self.x, self.w, self.x, self.z) }
var xwxw: Self { return Self(self.x, self.w, self.x, self.w) }
var xwzy: Self { return Self(self.x, self.w, self.z, self.y) }
var xwzx: Self { return Self(self.x, self.w, self.z, self.x) }
var xwzz: Self { return Self(self.x, self.w, self.z, self.z) }
var xwzw: Self { return Self(self.x, self.w, self.z, self.w) }
var xwwy: Self { return Self(self.x, self.w, self.w, self.y) }
var xwwx: Self { return Self(self.x, self.w, self.w, self.x) }
var xwwz: Self { return Self(self.x, self.w, self.w, self.z) }
var xwww: Self { return Self(self.x, self.w, self.w, self.w) }
var zyyy: Self { return Self(self.z, self.y, self.y, self.y) }
var zyyx: Self { return Self(self.z, self.y, self.y, self.x) }
var zyyz: Self { return Self(self.z, self.y, self.y, self.z) }
var zyyw: Self { return Self(self.z, self.y, self.y, self.w) }
var zyxy: Self { return Self(self.z, self.y, self.x, self.y) }
var zyxx: Self { return Self(self.z, self.y, self.x, self.x) }
var zyxz: Self { return Self(self.z, self.y, self.x, self.z) }
var zyxw: Self { return Self(self.z, self.y, self.x, self.w) }
var zyzy: Self { return Self(self.z, self.y, self.z, self.y) }
var zyzx: Self { return Self(self.z, self.y, self.z, self.x) }
var zyzz: Self { return Self(self.z, self.y, self.z, self.z) }
var zyzw: Self { return Self(self.z, self.y, self.z, self.w) }
var zywy: Self { return Self(self.z, self.y, self.w, self.y) }
var zywx: Self { return Self(self.z, self.y, self.w, self.x) }
var zywz: Self { return Self(self.z, self.y, self.w, self.z) }
var zyww: Self { return Self(self.z, self.y, self.w, self.w) }
var zxyy: Self { return Self(self.z, self.x, self.y, self.y) }
var zxyx: Self { return Self(self.z, self.x, self.y, self.x) }
var zxyz: Self { return Self(self.z, self.x, self.y, self.z) }
var zxyw: Self { return Self(self.z, self.x, self.y, self.w) }
var zxxy: Self { return Self(self.z, self.x, self.x, self.y) }
var zxxx: Self { return Self(self.z, self.x, self.x, self.x) }
var zxxz: Self { return Self(self.z, self.x, self.x, self.z) }
var zxxw: Self { return Self(self.z, self.x, self.x, self.w) }
var zxzy: Self { return Self(self.z, self.x, self.z, self.y) }
var zxzx: Self { return Self(self.z, self.x, self.z, self.x) }
var zxzz: Self { return Self(self.z, self.x, self.z, self.z) }
var zxzw: Self { return Self(self.z, self.x, self.z, self.w) }
var zxwy: Self { return Self(self.z, self.x, self.w, self.y) }
var zxwx: Self { return Self(self.z, self.x, self.w, self.x) }
var zxwz: Self { return Self(self.z, self.x, self.w, self.z) }
var zxww: Self { return Self(self.z, self.x, self.w, self.w) }
var zzyy: Self { return Self(self.z, self.z, self.y, self.y) }
var zzyx: Self { return Self(self.z, self.z, self.y, self.x) }
var zzyz: Self { return Self(self.z, self.z, self.y, self.z) }
var zzyw: Self { return Self(self.z, self.z, self.y, self.w) }
var zzxy: Self { return Self(self.z, self.z, self.x, self.y) }
var zzxx: Self { return Self(self.z, self.z, self.x, self.x) }
var zzxz: Self { return Self(self.z, self.z, self.x, self.z) }
var zzxw: Self { return Self(self.z, self.z, self.x, self.w) }
var zzzy: Self { return Self(self.z, self.z, self.z, self.y) }
var zzzx: Self { return Self(self.z, self.z, self.z, self.x) }
var zzzz: Self { return Self(self.z, self.z, self.z, self.z) }
var zzzw: Self { return Self(self.z, self.z, self.z, self.w) }
var zzwy: Self { return Self(self.z, self.z, self.w, self.y) }
var zzwx: Self { return Self(self.z, self.z, self.w, self.x) }
var zzwz: Self { return Self(self.z, self.z, self.w, self.z) }
var zzww: Self { return Self(self.z, self.z, self.w, self.w) }
var zwyy: Self { return Self(self.z, self.w, self.y, self.y) }
var zwyx: Self { return Self(self.z, self.w, self.y, self.x) }
var zwyz: Self { return Self(self.z, self.w, self.y, self.z) }
var zwyw: Self { return Self(self.z, self.w, self.y, self.w) }
var zwxy: Self { return Self(self.z, self.w, self.x, self.y) }
var zwxx: Self { return Self(self.z, self.w, self.x, self.x) }
var zwxz: Self { return Self(self.z, self.w, self.x, self.z) }
var zwxw: Self { return Self(self.z, self.w, self.x, self.w) }
var zwzy: Self { return Self(self.z, self.w, self.z, self.y) }
var zwzx: Self { return Self(self.z, self.w, self.z, self.x) }
var zwzz: Self { return Self(self.z, self.w, self.z, self.z) }
var zwzw: Self { return Self(self.z, self.w, self.z, self.w) }
var zwwy: Self { return Self(self.z, self.w, self.w, self.y) }
var zwwx: Self { return Self(self.z, self.w, self.w, self.x) }
var zwwz: Self { return Self(self.z, self.w, self.w, self.z) }
var zwww: Self { return Self(self.z, self.w, self.w, self.w) }
var wyyy: Self { return Self(self.w, self.y, self.y, self.y) }
var wyyx: Self { return Self(self.w, self.y, self.y, self.x) }
var wyyz: Self { return Self(self.w, self.y, self.y, self.z) }
var wyyw: Self { return Self(self.w, self.y, self.y, self.w) }
var wyxy: Self { return Self(self.w, self.y, self.x, self.y) }
var wyxx: Self { return Self(self.w, self.y, self.x, self.x) }
var wyxz: Self { return Self(self.w, self.y, self.x, self.z) }
var wyxw: Self { return Self(self.w, self.y, self.x, self.w) }
var wyzy: Self { return Self(self.w, self.y, self.z, self.y) }
var wyzx: Self { return Self(self.w, self.y, self.z, self.x) }
var wyzz: Self { return Self(self.w, self.y, self.z, self.z) }
var wyzw: Self { return Self(self.w, self.y, self.z, self.w) }
var wywy: Self { return Self(self.w, self.y, self.w, self.y) }
var wywx: Self { return Self(self.w, self.y, self.w, self.x) }
var wywz: Self { return Self(self.w, self.y, self.w, self.z) }
var wyww: Self { return Self(self.w, self.y, self.w, self.w) }
var wxyy: Self { return Self(self.w, self.x, self.y, self.y) }
var wxyx: Self { return Self(self.w, self.x, self.y, self.x) }
var wxyz: Self { return Self(self.w, self.x, self.y, self.z) }
var wxyw: Self { return Self(self.w, self.x, self.y, self.w) }
var wxxy: Self { return Self(self.w, self.x, self.x, self.y) }
var wxxx: Self { return Self(self.w, self.x, self.x, self.x) }
var wxxz: Self { return Self(self.w, self.x, self.x, self.z) }
var wxxw: Self { return Self(self.w, self.x, self.x, self.w) }
var wxzy: Self { return Self(self.w, self.x, self.z, self.y) }
var wxzx: Self { return Self(self.w, self.x, self.z, self.x) }
var wxzz: Self { return Self(self.w, self.x, self.z, self.z) }
var wxzw: Self { return Self(self.w, self.x, self.z, self.w) }
var wxwy: Self { return Self(self.w, self.x, self.w, self.y) }
var wxwx: Self { return Self(self.w, self.x, self.w, self.x) }
var wxwz: Self { return Self(self.w, self.x, self.w, self.z) }
var wxww: Self { return Self(self.w, self.x, self.w, self.w) }
var wzyy: Self { return Self(self.w, self.z, self.y, self.y) }
var wzyx: Self { return Self(self.w, self.z, self.y, self.x) }
var wzyz: Self { return Self(self.w, self.z, self.y, self.z) }
var wzyw: Self { return Self(self.w, self.z, self.y, self.w) }
var wzxy: Self { return Self(self.w, self.z, self.x, self.y) }
var wzxx: Self { return Self(self.w, self.z, self.x, self.x) }
var wzxz: Self { return Self(self.w, self.z, self.x, self.z) }
var wzxw: Self { return Self(self.w, self.z, self.x, self.w) }
var wzzy: Self { return Self(self.w, self.z, self.z, self.y) }
var wzzx: Self { return Self(self.w, self.z, self.z, self.x) }
var wzzz: Self { return Self(self.w, self.z, self.z, self.z) }
var wzzw: Self { return Self(self.w, self.z, self.z, self.w) }
var wzwy: Self { return Self(self.w, self.z, self.w, self.y) }
var wzwx: Self { return Self(self.w, self.z, self.w, self.x) }
var wzwz: Self { return Self(self.w, self.z, self.w, self.z) }
var wzww: Self { return Self(self.w, self.z, self.w, self.w) }
var wwyy: Self { return Self(self.w, self.w, self.y, self.y) }
var wwyx: Self { return Self(self.w, self.w, self.y, self.x) }
var wwyz: Self { return Self(self.w, self.w, self.y, self.z) }
var wwyw: Self { return Self(self.w, self.w, self.y, self.w) }
var wwxy: Self { return Self(self.w, self.w, self.x, self.y) }
var wwxx: Self { return Self(self.w, self.w, self.x, self.x) }
var wwxz: Self { return Self(self.w, self.w, self.x, self.z) }
var wwxw: Self { return Self(self.w, self.w, self.x, self.w) }
var wwzy: Self { return Self(self.w, self.w, self.z, self.y) }
var wwzx: Self { return Self(self.w, self.w, self.z, self.x) }
var wwzz: Self { return Self(self.w, self.w, self.z, self.z) }
var wwzw: Self { return Self(self.w, self.w, self.z, self.w) }
var wwwy: Self { return Self(self.w, self.w, self.w, self.y) }
var wwwx: Self { return Self(self.w, self.w, self.w, self.x) }
var wwwz: Self { return Self(self.w, self.w, self.w, self.z) }
var wwww: Self { return Self(self.w, self.w, self.w, self.w) }
var aa: AssociatedVector2 { return AssociatedVector2(self.a, self.a) }
var ar: AssociatedVector2 { return AssociatedVector2(self.a, self.r) }
var ab: AssociatedVector2 { return AssociatedVector2(self.a, self.b) }
var ag: AssociatedVector2 { return AssociatedVector2(self.a, self.g) }
var ra: AssociatedVector2 { return AssociatedVector2(self.r, self.a) }
var rr: AssociatedVector2 { return AssociatedVector2(self.r, self.r) }
var rb: AssociatedVector2 { return AssociatedVector2(self.r, self.b) }
var rg: AssociatedVector2 { return AssociatedVector2(self.r, self.g) }
var ba: AssociatedVector2 { return AssociatedVector2(self.b, self.a) }
var br: AssociatedVector2 { return AssociatedVector2(self.b, self.r) }
var bb: AssociatedVector2 { return AssociatedVector2(self.b, self.b) }
var bg: AssociatedVector2 { return AssociatedVector2(self.b, self.g) }
var ga: AssociatedVector2 { return AssociatedVector2(self.g, self.a) }
var gr: AssociatedVector2 { return AssociatedVector2(self.g, self.r) }
var gb: AssociatedVector2 { return AssociatedVector2(self.g, self.b) }
var gg: AssociatedVector2 { return AssociatedVector2(self.g, self.g) }
var aaa: AssociatedVector3 { return AssociatedVector3(self.a, self.a, self.a) }
var aar: AssociatedVector3 { return AssociatedVector3(self.a, self.a, self.r) }
var aab: AssociatedVector3 { return AssociatedVector3(self.a, self.a, self.b) }
var aag: AssociatedVector3 { return AssociatedVector3(self.a, self.a, self.g) }
var ara: AssociatedVector3 { return AssociatedVector3(self.a, self.r, self.a) }
var arr: AssociatedVector3 { return AssociatedVector3(self.a, self.r, self.r) }
var arb: AssociatedVector3 { return AssociatedVector3(self.a, self.r, self.b) }
var arg: AssociatedVector3 { return AssociatedVector3(self.a, self.r, self.g) }
var aba: AssociatedVector3 { return AssociatedVector3(self.a, self.b, self.a) }
var abr: AssociatedVector3 { return AssociatedVector3(self.a, self.b, self.r) }
var abb: AssociatedVector3 { return AssociatedVector3(self.a, self.b, self.b) }
var abg: AssociatedVector3 { return AssociatedVector3(self.a, self.b, self.g) }
var aga: AssociatedVector3 { return AssociatedVector3(self.a, self.g, self.a) }
var agr: AssociatedVector3 { return AssociatedVector3(self.a, self.g, self.r) }
var agb: AssociatedVector3 { return AssociatedVector3(self.a, self.g, self.b) }
var agg: AssociatedVector3 { return AssociatedVector3(self.a, self.g, self.g) }
var raa: AssociatedVector3 { return AssociatedVector3(self.r, self.a, self.a) }
var rar: AssociatedVector3 { return AssociatedVector3(self.r, self.a, self.r) }
var rab: AssociatedVector3 { return AssociatedVector3(self.r, self.a, self.b) }
var rag: AssociatedVector3 { return AssociatedVector3(self.r, self.a, self.g) }
var rra: AssociatedVector3 { return AssociatedVector3(self.r, self.r, self.a) }
var rrr: AssociatedVector3 { return AssociatedVector3(self.r, self.r, self.r) }
var rrb: AssociatedVector3 { return AssociatedVector3(self.r, self.r, self.b) }
var rrg: AssociatedVector3 { return AssociatedVector3(self.r, self.r, self.g) }
var rba: AssociatedVector3 { return AssociatedVector3(self.r, self.b, self.a) }
var rbr: AssociatedVector3 { return AssociatedVector3(self.r, self.b, self.r) }
var rbb: AssociatedVector3 { return AssociatedVector3(self.r, self.b, self.b) }
var rbg: AssociatedVector3 { return AssociatedVector3(self.r, self.b, self.g) }
var rga: AssociatedVector3 { return AssociatedVector3(self.r, self.g, self.a) }
var rgr: AssociatedVector3 { return AssociatedVector3(self.r, self.g, self.r) }
var rgb: AssociatedVector3 { return AssociatedVector3(self.r, self.g, self.b) }
var rgg: AssociatedVector3 { return AssociatedVector3(self.r, self.g, self.g) }
var baa: AssociatedVector3 { return AssociatedVector3(self.b, self.a, self.a) }
var bar: AssociatedVector3 { return AssociatedVector3(self.b, self.a, self.r) }
var bab: AssociatedVector3 { return AssociatedVector3(self.b, self.a, self.b) }
var bag: AssociatedVector3 { return AssociatedVector3(self.b, self.a, self.g) }
var bra: AssociatedVector3 { return AssociatedVector3(self.b, self.r, self.a) }
var brr: AssociatedVector3 { return AssociatedVector3(self.b, self.r, self.r) }
var brb: AssociatedVector3 { return AssociatedVector3(self.b, self.r, self.b) }
var brg: AssociatedVector3 { return AssociatedVector3(self.b, self.r, self.g) }
var bba: AssociatedVector3 { return AssociatedVector3(self.b, self.b, self.a) }
var bbr: AssociatedVector3 { return AssociatedVector3(self.b, self.b, self.r) }
var bbb: AssociatedVector3 { return AssociatedVector3(self.b, self.b, self.b) }
var bbg: AssociatedVector3 { return AssociatedVector3(self.b, self.b, self.g) }
var bga: AssociatedVector3 { return AssociatedVector3(self.b, self.g, self.a) }
var bgr: AssociatedVector3 { return AssociatedVector3(self.b, self.g, self.r) }
var bgb: AssociatedVector3 { return AssociatedVector3(self.b, self.g, self.b) }
var bgg: AssociatedVector3 { return AssociatedVector3(self.b, self.g, self.g) }
var gaa: AssociatedVector3 { return AssociatedVector3(self.g, self.a, self.a) }
var gar: AssociatedVector3 { return AssociatedVector3(self.g, self.a, self.r) }
var gab: AssociatedVector3 { return AssociatedVector3(self.g, self.a, self.b) }
var gag: AssociatedVector3 { return AssociatedVector3(self.g, self.a, self.g) }
var gra: AssociatedVector3 { return AssociatedVector3(self.g, self.r, self.a) }
var grr: AssociatedVector3 { return AssociatedVector3(self.g, self.r, self.r) }
var grb: AssociatedVector3 { return AssociatedVector3(self.g, self.r, self.b) }
var grg: AssociatedVector3 { return AssociatedVector3(self.g, self.r, self.g) }
var gba: AssociatedVector3 { return AssociatedVector3(self.g, self.b, self.a) }
var gbr: AssociatedVector3 { return AssociatedVector3(self.g, self.b, self.r) }
var gbb: AssociatedVector3 { return AssociatedVector3(self.g, self.b, self.b) }
var gbg: AssociatedVector3 { return AssociatedVector3(self.g, self.b, self.g) }
var gga: AssociatedVector3 { return AssociatedVector3(self.g, self.g, self.a) }
var ggr: AssociatedVector3 { return AssociatedVector3(self.g, self.g, self.r) }
var ggb: AssociatedVector3 { return AssociatedVector3(self.g, self.g, self.b) }
var ggg: AssociatedVector3 { return AssociatedVector3(self.g, self.g, self.g) }
var aaaa: Self { return Self(self.a, self.a, self.a, self.a) }
var aaar: Self { return Self(self.a, self.a, self.a, self.r) }
var aaab: Self { return Self(self.a, self.a, self.a, self.b) }
var aaag: Self { return Self(self.a, self.a, self.a, self.g) }
var aara: Self { return Self(self.a, self.a, self.r, self.a) }
var aarr: Self { return Self(self.a, self.a, self.r, self.r) }
var aarb: Self { return Self(self.a, self.a, self.r, self.b) }
var aarg: Self { return Self(self.a, self.a, self.r, self.g) }
var aaba: Self { return Self(self.a, self.a, self.b, self.a) }
var aabr: Self { return Self(self.a, self.a, self.b, self.r) }
var aabb: Self { return Self(self.a, self.a, self.b, self.b) }
var aabg: Self { return Self(self.a, self.a, self.b, self.g) }
var aaga: Self { return Self(self.a, self.a, self.g, self.a) }
var aagr: Self { return Self(self.a, self.a, self.g, self.r) }
var aagb: Self { return Self(self.a, self.a, self.g, self.b) }
var aagg: Self { return Self(self.a, self.a, self.g, self.g) }
var araa: Self { return Self(self.a, self.r, self.a, self.a) }
var arar: Self { return Self(self.a, self.r, self.a, self.r) }
var arab: Self { return Self(self.a, self.r, self.a, self.b) }
var arag: Self { return Self(self.a, self.r, self.a, self.g) }
var arra: Self { return Self(self.a, self.r, self.r, self.a) }
var arrr: Self { return Self(self.a, self.r, self.r, self.r) }
var arrb: Self { return Self(self.a, self.r, self.r, self.b) }
var arrg: Self { return Self(self.a, self.r, self.r, self.g) }
var arba: Self { return Self(self.a, self.r, self.b, self.a) }
var arbr: Self { return Self(self.a, self.r, self.b, self.r) }
var arbb: Self { return Self(self.a, self.r, self.b, self.b) }
var arbg: Self { return Self(self.a, self.r, self.b, self.g) }
var arga: Self { return Self(self.a, self.r, self.g, self.a) }
var argr: Self { return Self(self.a, self.r, self.g, self.r) }
var argb: Self { return Self(self.a, self.r, self.g, self.b) }
var argg: Self { return Self(self.a, self.r, self.g, self.g) }
var abaa: Self { return Self(self.a, self.b, self.a, self.a) }
var abar: Self { return Self(self.a, self.b, self.a, self.r) }
var abab: Self { return Self(self.a, self.b, self.a, self.b) }
var abag: Self { return Self(self.a, self.b, self.a, self.g) }
var abra: Self { return Self(self.a, self.b, self.r, self.a) }
var abrr: Self { return Self(self.a, self.b, self.r, self.r) }
var abrb: Self { return Self(self.a, self.b, self.r, self.b) }
var abrg: Self { return Self(self.a, self.b, self.r, self.g) }
var abba: Self { return Self(self.a, self.b, self.b, self.a) }
var abbr: Self { return Self(self.a, self.b, self.b, self.r) }
var abbb: Self { return Self(self.a, self.b, self.b, self.b) }
var abbg: Self { return Self(self.a, self.b, self.b, self.g) }
var abga: Self { return Self(self.a, self.b, self.g, self.a) }
var abgr: Self { return Self(self.a, self.b, self.g, self.r) }
var abgb: Self { return Self(self.a, self.b, self.g, self.b) }
var abgg: Self { return Self(self.a, self.b, self.g, self.g) }
var agaa: Self { return Self(self.a, self.g, self.a, self.a) }
var agar: Self { return Self(self.a, self.g, self.a, self.r) }
var agab: Self { return Self(self.a, self.g, self.a, self.b) }
var agag: Self { return Self(self.a, self.g, self.a, self.g) }
var agra: Self { return Self(self.a, self.g, self.r, self.a) }
var agrr: Self { return Self(self.a, self.g, self.r, self.r) }
var agrb: Self { return Self(self.a, self.g, self.r, self.b) }
var agrg: Self { return Self(self.a, self.g, self.r, self.g) }
var agba: Self { return Self(self.a, self.g, self.b, self.a) }
var agbr: Self { return Self(self.a, self.g, self.b, self.r) }
var agbb: Self { return Self(self.a, self.g, self.b, self.b) }
var agbg: Self { return Self(self.a, self.g, self.b, self.g) }
var agga: Self { return Self(self.a, self.g, self.g, self.a) }
var aggr: Self { return Self(self.a, self.g, self.g, self.r) }
var aggb: Self { return Self(self.a, self.g, self.g, self.b) }
var aggg: Self { return Self(self.a, self.g, self.g, self.g) }
var raaa: Self { return Self(self.r, self.a, self.a, self.a) }
var raar: Self { return Self(self.r, self.a, self.a, self.r) }
var raab: Self { return Self(self.r, self.a, self.a, self.b) }
var raag: Self { return Self(self.r, self.a, self.a, self.g) }
var rara: Self { return Self(self.r, self.a, self.r, self.a) }
var rarr: Self { return Self(self.r, self.a, self.r, self.r) }
var rarb: Self { return Self(self.r, self.a, self.r, self.b) }
var rarg: Self { return Self(self.r, self.a, self.r, self.g) }
var raba: Self { return Self(self.r, self.a, self.b, self.a) }
var rabr: Self { return Self(self.r, self.a, self.b, self.r) }
var rabb: Self { return Self(self.r, self.a, self.b, self.b) }
var rabg: Self { return Self(self.r, self.a, self.b, self.g) }
var raga: Self { return Self(self.r, self.a, self.g, self.a) }
var ragr: Self { return Self(self.r, self.a, self.g, self.r) }
var ragb: Self { return Self(self.r, self.a, self.g, self.b) }
var ragg: Self { return Self(self.r, self.a, self.g, self.g) }
var rraa: Self { return Self(self.r, self.r, self.a, self.a) }
var rrar: Self { return Self(self.r, self.r, self.a, self.r) }
var rrab: Self { return Self(self.r, self.r, self.a, self.b) }
var rrag: Self { return Self(self.r, self.r, self.a, self.g) }
var rrra: Self { return Self(self.r, self.r, self.r, self.a) }
var rrrr: Self { return Self(self.r, self.r, self.r, self.r) }
var rrrb: Self { return Self(self.r, self.r, self.r, self.b) }
var rrrg: Self { return Self(self.r, self.r, self.r, self.g) }
var rrba: Self { return Self(self.r, self.r, self.b, self.a) }
var rrbr: Self { return Self(self.r, self.r, self.b, self.r) }
var rrbb: Self { return Self(self.r, self.r, self.b, self.b) }
var rrbg: Self { return Self(self.r, self.r, self.b, self.g) }
var rrga: Self { return Self(self.r, self.r, self.g, self.a) }
var rrgr: Self { return Self(self.r, self.r, self.g, self.r) }
var rrgb: Self { return Self(self.r, self.r, self.g, self.b) }
var rrgg: Self { return Self(self.r, self.r, self.g, self.g) }
var rbaa: Self { return Self(self.r, self.b, self.a, self.a) }
var rbar: Self { return Self(self.r, self.b, self.a, self.r) }
var rbab: Self { return Self(self.r, self.b, self.a, self.b) }
var rbag: Self { return Self(self.r, self.b, self.a, self.g) }
var rbra: Self { return Self(self.r, self.b, self.r, self.a) }
var rbrr: Self { return Self(self.r, self.b, self.r, self.r) }
var rbrb: Self { return Self(self.r, self.b, self.r, self.b) }
var rbrg: Self { return Self(self.r, self.b, self.r, self.g) }
var rbba: Self { return Self(self.r, self.b, self.b, self.a) }
var rbbr: Self { return Self(self.r, self.b, self.b, self.r) }
var rbbb: Self { return Self(self.r, self.b, self.b, self.b) }
var rbbg: Self { return Self(self.r, self.b, self.b, self.g) }
var rbga: Self { return Self(self.r, self.b, self.g, self.a) }
var rbgr: Self { return Self(self.r, self.b, self.g, self.r) }
var rbgb: Self { return Self(self.r, self.b, self.g, self.b) }
var rbgg: Self { return Self(self.r, self.b, self.g, self.g) }
var rgaa: Self { return Self(self.r, self.g, self.a, self.a) }
var rgar: Self { return Self(self.r, self.g, self.a, self.r) }
var rgab: Self { return Self(self.r, self.g, self.a, self.b) }
var rgag: Self { return Self(self.r, self.g, self.a, self.g) }
var rgra: Self { return Self(self.r, self.g, self.r, self.a) }
var rgrr: Self { return Self(self.r, self.g, self.r, self.r) }
var rgrb: Self { return Self(self.r, self.g, self.r, self.b) }
var rgrg: Self { return Self(self.r, self.g, self.r, self.g) }
var rgba: Self { return Self(self.r, self.g, self.b, self.a) }
var rgbr: Self { return Self(self.r, self.g, self.b, self.r) }
var rgbb: Self { return Self(self.r, self.g, self.b, self.b) }
var rgbg: Self { return Self(self.r, self.g, self.b, self.g) }
var rgga: Self { return Self(self.r, self.g, self.g, self.a) }
var rggr: Self { return Self(self.r, self.g, self.g, self.r) }
var rggb: Self { return Self(self.r, self.g, self.g, self.b) }
var rggg: Self { return Self(self.r, self.g, self.g, self.g) }
var baaa: Self { return Self(self.b, self.a, self.a, self.a) }
var baar: Self { return Self(self.b, self.a, self.a, self.r) }
var baab: Self { return Self(self.b, self.a, self.a, self.b) }
var baag: Self { return Self(self.b, self.a, self.a, self.g) }
var bara: Self { return Self(self.b, self.a, self.r, self.a) }
var barr: Self { return Self(self.b, self.a, self.r, self.r) }
var barb: Self { return Self(self.b, self.a, self.r, self.b) }
var barg: Self { return Self(self.b, self.a, self.r, self.g) }
var baba: Self { return Self(self.b, self.a, self.b, self.a) }
var babr: Self { return Self(self.b, self.a, self.b, self.r) }
var babb: Self { return Self(self.b, self.a, self.b, self.b) }
var babg: Self { return Self(self.b, self.a, self.b, self.g) }
var baga: Self { return Self(self.b, self.a, self.g, self.a) }
var bagr: Self { return Self(self.b, self.a, self.g, self.r) }
var bagb: Self { return Self(self.b, self.a, self.g, self.b) }
var bagg: Self { return Self(self.b, self.a, self.g, self.g) }
var braa: Self { return Self(self.b, self.r, self.a, self.a) }
var brar: Self { return Self(self.b, self.r, self.a, self.r) }
var brab: Self { return Self(self.b, self.r, self.a, self.b) }
var brag: Self { return Self(self.b, self.r, self.a, self.g) }
var brra: Self { return Self(self.b, self.r, self.r, self.a) }
var brrr: Self { return Self(self.b, self.r, self.r, self.r) }
var brrb: Self { return Self(self.b, self.r, self.r, self.b) }
var brrg: Self { return Self(self.b, self.r, self.r, self.g) }
var brba: Self { return Self(self.b, self.r, self.b, self.a) }
var brbr: Self { return Self(self.b, self.r, self.b, self.r) }
var brbb: Self { return Self(self.b, self.r, self.b, self.b) }
var brbg: Self { return Self(self.b, self.r, self.b, self.g) }
var brga: Self { return Self(self.b, self.r, self.g, self.a) }
var brgr: Self { return Self(self.b, self.r, self.g, self.r) }
var brgb: Self { return Self(self.b, self.r, self.g, self.b) }
var brgg: Self { return Self(self.b, self.r, self.g, self.g) }
var bbaa: Self { return Self(self.b, self.b, self.a, self.a) }
var bbar: Self { return Self(self.b, self.b, self.a, self.r) }
var bbab: Self { return Self(self.b, self.b, self.a, self.b) }
var bbag: Self { return Self(self.b, self.b, self.a, self.g) }
var bbra: Self { return Self(self.b, self.b, self.r, self.a) }
var bbrr: Self { return Self(self.b, self.b, self.r, self.r) }
var bbrb: Self { return Self(self.b, self.b, self.r, self.b) }
var bbrg: Self { return Self(self.b, self.b, self.r, self.g) }
var bbba: Self { return Self(self.b, self.b, self.b, self.a) }
var bbbr: Self { return Self(self.b, self.b, self.b, self.r) }
var bbbb: Self { return Self(self.b, self.b, self.b, self.b) }
var bbbg: Self { return Self(self.b, self.b, self.b, self.g) }
var bbga: Self { return Self(self.b, self.b, self.g, self.a) }
var bbgr: Self { return Self(self.b, self.b, self.g, self.r) }
var bbgb: Self { return Self(self.b, self.b, self.g, self.b) }
var bbgg: Self { return Self(self.b, self.b, self.g, self.g) }
var bgaa: Self { return Self(self.b, self.g, self.a, self.a) }
var bgar: Self { return Self(self.b, self.g, self.a, self.r) }
var bgab: Self { return Self(self.b, self.g, self.a, self.b) }
var bgag: Self { return Self(self.b, self.g, self.a, self.g) }
var bgra: Self { return Self(self.b, self.g, self.r, self.a) }
var bgrr: Self { return Self(self.b, self.g, self.r, self.r) }
var bgrb: Self { return Self(self.b, self.g, self.r, self.b) }
var bgrg: Self { return Self(self.b, self.g, self.r, self.g) }
var bgba: Self { return Self(self.b, self.g, self.b, self.a) }
var bgbr: Self { return Self(self.b, self.g, self.b, self.r) }
var bgbb: Self { return Self(self.b, self.g, self.b, self.b) }
var bgbg: Self { return Self(self.b, self.g, self.b, self.g) }
var bgga: Self { return Self(self.b, self.g, self.g, self.a) }
var bggr: Self { return Self(self.b, self.g, self.g, self.r) }
var bggb: Self { return Self(self.b, self.g, self.g, self.b) }
var bggg: Self { return Self(self.b, self.g, self.g, self.g) }
var gaaa: Self { return Self(self.g, self.a, self.a, self.a) }
var gaar: Self { return Self(self.g, self.a, self.a, self.r) }
var gaab: Self { return Self(self.g, self.a, self.a, self.b) }
var gaag: Self { return Self(self.g, self.a, self.a, self.g) }
var gara: Self { return Self(self.g, self.a, self.r, self.a) }
var garr: Self { return Self(self.g, self.a, self.r, self.r) }
var garb: Self { return Self(self.g, self.a, self.r, self.b) }
var garg: Self { return Self(self.g, self.a, self.r, self.g) }
var gaba: Self { return Self(self.g, self.a, self.b, self.a) }
var gabr: Self { return Self(self.g, self.a, self.b, self.r) }
var gabb: Self { return Self(self.g, self.a, self.b, self.b) }
var gabg: Self { return Self(self.g, self.a, self.b, self.g) }
var gaga: Self { return Self(self.g, self.a, self.g, self.a) }
var gagr: Self { return Self(self.g, self.a, self.g, self.r) }
var gagb: Self { return Self(self.g, self.a, self.g, self.b) }
var gagg: Self { return Self(self.g, self.a, self.g, self.g) }
var graa: Self { return Self(self.g, self.r, self.a, self.a) }
var grar: Self { return Self(self.g, self.r, self.a, self.r) }
var grab: Self { return Self(self.g, self.r, self.a, self.b) }
var grag: Self { return Self(self.g, self.r, self.a, self.g) }
var grra: Self { return Self(self.g, self.r, self.r, self.a) }
var grrr: Self { return Self(self.g, self.r, self.r, self.r) }
var grrb: Self { return Self(self.g, self.r, self.r, self.b) }
var grrg: Self { return Self(self.g, self.r, self.r, self.g) }
var grba: Self { return Self(self.g, self.r, self.b, self.a) }
var grbr: Self { return Self(self.g, self.r, self.b, self.r) }
var grbb: Self { return Self(self.g, self.r, self.b, self.b) }
var grbg: Self { return Self(self.g, self.r, self.b, self.g) }
var grga: Self { return Self(self.g, self.r, self.g, self.a) }
var grgr: Self { return Self(self.g, self.r, self.g, self.r) }
var grgb: Self { return Self(self.g, self.r, self.g, self.b) }
var grgg: Self { return Self(self.g, self.r, self.g, self.g) }
var gbaa: Self { return Self(self.g, self.b, self.a, self.a) }
var gbar: Self { return Self(self.g, self.b, self.a, self.r) }
var gbab: Self { return Self(self.g, self.b, self.a, self.b) }
var gbag: Self { return Self(self.g, self.b, self.a, self.g) }
var gbra: Self { return Self(self.g, self.b, self.r, self.a) }
var gbrr: Self { return Self(self.g, self.b, self.r, self.r) }
var gbrb: Self { return Self(self.g, self.b, self.r, self.b) }
var gbrg: Self { return Self(self.g, self.b, self.r, self.g) }
var gbba: Self { return Self(self.g, self.b, self.b, self.a) }
var gbbr: Self { return Self(self.g, self.b, self.b, self.r) }
var gbbb: Self { return Self(self.g, self.b, self.b, self.b) }
var gbbg: Self { return Self(self.g, self.b, self.b, self.g) }
var gbga: Self { return Self(self.g, self.b, self.g, self.a) }
var gbgr: Self { return Self(self.g, self.b, self.g, self.r) }
var gbgb: Self { return Self(self.g, self.b, self.g, self.b) }
var gbgg: Self { return Self(self.g, self.b, self.g, self.g) }
var ggaa: Self { return Self(self.g, self.g, self.a, self.a) }
var ggar: Self { return Self(self.g, self.g, self.a, self.r) }
var ggab: Self { return Self(self.g, self.g, self.a, self.b) }
var ggag: Self { return Self(self.g, self.g, self.a, self.g) }
var ggra: Self { return Self(self.g, self.g, self.r, self.a) }
var ggrr: Self { return Self(self.g, self.g, self.r, self.r) }
var ggrb: Self { return Self(self.g, self.g, self.r, self.b) }
var ggrg: Self { return Self(self.g, self.g, self.r, self.g) }
var ggba: Self { return Self(self.g, self.g, self.b, self.a) }
var ggbr: Self { return Self(self.g, self.g, self.b, self.r) }
var ggbb: Self { return Self(self.g, self.g, self.b, self.b) }
var ggbg: Self { return Self(self.g, self.g, self.b, self.g) }
var ggga: Self { return Self(self.g, self.g, self.g, self.a) }
var gggr: Self { return Self(self.g, self.g, self.g, self.r) }
var gggb: Self { return Self(self.g, self.g, self.g, self.b) }
var gggg: Self { return Self(self.g, self.g, self.g, self.g) }
}
|
mit
|
crazypoo/PTools
|
Pods/CryptoSwift/Sources/CryptoSwift/BatchedCollection.swift
|
2
|
2588
|
//
// CryptoSwift
//
// Copyright (C) 2014-2022 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
@usableFromInline
struct BatchedCollectionIndex<Base: Collection> {
let range: Range<Base.Index>
}
extension BatchedCollectionIndex: Comparable {
@usableFromInline
static func == <Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
lhs.range.lowerBound == rhs.range.lowerBound
}
@usableFromInline
static func < <Base>(lhs: BatchedCollectionIndex<Base>, rhs: BatchedCollectionIndex<Base>) -> Bool {
lhs.range.lowerBound < rhs.range.lowerBound
}
}
protocol BatchedCollectionType: Collection {
associatedtype Base: Collection
}
@usableFromInline
struct BatchedCollection<Base: Collection>: Collection {
let base: Base
let size: Int
@usableFromInline
init(base: Base, size: Int) {
self.base = base
self.size = size
}
@usableFromInline
typealias Index = BatchedCollectionIndex<Base>
private func nextBreak(after idx: Base.Index) -> Base.Index {
self.base.index(idx, offsetBy: self.size, limitedBy: self.base.endIndex) ?? self.base.endIndex
}
@usableFromInline
var startIndex: Index {
Index(range: self.base.startIndex..<self.nextBreak(after: self.base.startIndex))
}
@usableFromInline
var endIndex: Index {
Index(range: self.base.endIndex..<self.base.endIndex)
}
@usableFromInline
func index(after idx: Index) -> Index {
Index(range: idx.range.upperBound..<self.nextBreak(after: idx.range.upperBound))
}
@usableFromInline
subscript(idx: Index) -> Base.SubSequence {
self.base[idx.range]
}
}
extension Collection {
@inlinable
func batched(by size: Int) -> BatchedCollection<Self> {
BatchedCollection(base: self, size: size)
}
}
|
mit
|
eljeff/AudioKit
|
Sources/AudioKit/Nodes/Playback/Samplers/Apple Sampler/AppleSampler.swift
|
1
|
10855
|
// Copyright AudioKit. All Rights Reserved. Revision History at http://github.com/AudioKit/AudioKit/
import AVFoundation
import CAudioKit
/// Sampler audio generation.
///
/// 1. init the audio unit like this: var sampler = AppleSampler()
/// 2. load a sound a file: sampler.loadWav("path/to/your/sound/file/in/app/bundle") (without wav extension)
/// 3. connect to the engine: engine.output = sampler
/// 4. start the engine engine.start()
///
open class AppleSampler: Node {
// MARK: - Properties
/// Internal audio unit
public private(set) var internalAU: AUAudioUnit?
private var _audioFiles: [AVAudioFile] = []
/// Audio files to use in the sampler
public var audioFiles: [AVAudioFile] {
get {
return _audioFiles
}
set {
do {
try loadAudioFiles(newValue)
} catch {
Log("Could not load audio files")
}
}
}
fileprivate var token: AUParameterObserverToken?
/// Sampler AV Audio Unit
public var samplerUnit = AVAudioUnitSampler()
/// Tuning amount in semitones, from -24.0 to 24.0, Default: 0.0
/// Doesn't transpose by playing another note (and the accoring zone and layer)
/// but bends the sound up and down like tuning.
public var tuning: AUValue {
get {
return AUValue(samplerUnit.globalTuning / 100.0)
}
set {
samplerUnit.globalTuning = Float(newValue * 100.0)
}
}
// MARK: - Initializers
/// Initialize the sampler node
public init(file: String? = nil) {
super.init(avAudioNode: AVAudioNode())
avAudioUnit = samplerUnit
avAudioNode = samplerUnit
internalAU = samplerUnit.auAudioUnit
if let newFile = file {
do {
try loadWav(newFile)
} catch {
Log("Could not load \(newFile)")
}
}
}
/// Utility method to find a file either in the main bundle or at an absolute path
internal func findFileURL(_ path: String, withExtension ext: String) -> URL? {
if path.hasPrefix("/") && FileManager.default.fileExists(atPath: path + "." + ext) {
return URL(fileURLWithPath: path + "." + ext)
} else if let url = Bundle.main.url(forResource: path, withExtension: ext) {
return url
}
return nil
}
/// Load a wav file
///
/// - parameter file: Name of the file without an extension (assumed to be accessible from the bundle)
///
public func loadWav(_ file: String) throws {
guard let url = findFileURL(file, withExtension: "wav") else {
Log("WAV file not found.")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: [url])
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading wav file at \(url)")
throw error
}
}
/// Load an EXS24 sample data file
///
/// - parameter file: Name of the EXS24 file without the .exs extension
///
public func loadEXS24(_ file: String) throws {
try loadInstrument(file, type: "exs")
}
/// Load an AVAudioFile
///
/// - parameter file: an AVAudioFile
///
public func loadAudioFile(_ file: AVAudioFile) throws {
_audioFiles = [file]
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: [file.url])
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading audio file \"\(file.url.lastPathComponent)\"")
throw error
}
}
/// Load an array of AVAudioFiles
///
/// - parameter files: An array of AVAudioFiles
///
/// If a file name ends with a note name (ex: "violinC3.wav")
/// The file will be set to this note
/// Handy to set multi-sampled instruments or a drum kit...
public func loadAudioFiles(_ files: [AVAudioFile] ) throws {
_audioFiles = files
let urls = files.map { $0.url }
do {
try ExceptionCatcher {
try self.samplerUnit.loadAudioFiles(at: urls)
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading audio files \(urls)")
throw error
}
}
/// Load a file path. The sampler can be configured by loading
/// instruments from different types of files such as an aupreset, a DLS or SF2 sound bank,
/// an EXS24 instrument, a single audio file, or an array of audio files.
///
/// - parameter filePath: Name of the file with the extension
///
public func loadPath(_ filePath: String) throws {
do {
try ExceptionCatcher {
try self.samplerUnit.loadInstrument(at: URL(fileURLWithPath: filePath))
self.samplerUnit.reset()
}
} catch {
Log("Error Sampler.loadPath loading file at \(filePath)")
throw error
}
}
internal func loadInstrument(_ file: String, type: String) throws {
//Log("filename is \(file)")
guard let url = findFileURL(file, withExtension: type) else {
Log("File not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try ExceptionCatcher {
try self.samplerUnit.loadInstrument(at: url)
self.samplerUnit.reset()
}
} catch let error as NSError {
Log("Error loading instrument resource \(file)")
throw error
}
}
/// Output Amplitude. Range: -90.0 -> +12 db, Default: 0 db
public var amplitude: AUValue = 0 {
didSet {
samplerUnit.masterGain = Float(amplitude)
}
}
/// Normalized Output Volume. Range: 0 -> 1, Default: 1
public var volume: AUValue = 1 {
didSet {
let newGain = volume.denormalized(to: -90.0 ... 0.0)
samplerUnit.masterGain = Float(newGain)
}
}
/// Pan. Range: -1 -> 1, Default: 0
public var pan: AUValue = 0 {
didSet {
samplerUnit.stereoPan = Float(100.0 * pan)
}
}
// MARK: - Playback
/// Play a MIDI Note or trigger a sample
///
/// - Parameters:
/// - noteNumber: MIDI Note Number to play
/// - velocity: MIDI Velocity
/// - channel: MIDI Channnel
///
/// NB: when using an audio file, noteNumber 60 will play back the file at normal
/// speed, 72 will play back at double speed (1 octave higher), 48 will play back at
/// half speed (1 octave lower) and so on
public func play(noteNumber: MIDINoteNumber = 60,
velocity: MIDIVelocity = 127,
channel: MIDIChannel = 0) throws {
self.samplerUnit.startNote(noteNumber, withVelocity: velocity, onChannel: channel)
}
/// Stop a MIDI Note
///
/// - Parameters:
/// - noteNumber: MIDI Note Number to stop
/// - channel: MIDI Channnel
///
public func stop(noteNumber: MIDINoteNumber = 60, channel: MIDIChannel = 0) throws {
try ExceptionCatcher {
self.samplerUnit.stopNote(noteNumber, onChannel: channel)
}
}
// MARK: - SoundFont Support
// NOTE: The following methods might seem like they belong in the
// SoundFont extension, but when place there, iOS12 beta crashed
fileprivate func loadSoundFont(_ file: String, preset: Int, type: Int) throws {
guard let url = findFileURL(file, withExtension: "sf2") else {
Log("Soundfont file not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
try samplerUnit.loadSoundBankInstrument(
at: url,
program: MIDIByte(preset),
bankMSB: MIDIByte(type),
bankLSB: MIDIByte(kAUSampler_DefaultBankLSB))
samplerUnit.reset()
} catch let error as NSError {
Log("Error loading SoundFont \(file)")
throw error
}
}
/// Load a Bank from a SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
/// - bank: Number of the bank to use
///
public func loadSoundFont(_ file: String, preset: Int, bank: Int) throws {
guard let url = findFileURL(file, withExtension: "sf2") else {
Log("Soundfont file not found: \(file)")
throw NSError(domain: NSURLErrorDomain, code: NSFileReadUnknownError, userInfo: nil)
}
do {
var bMSB: Int
if bank <= 127 {
bMSB = kAUSampler_DefaultMelodicBankMSB
} else {
bMSB = kAUSampler_DefaultPercussionBankMSB
}
let bLSB: Int = bank % 128
try samplerUnit.loadSoundBankInstrument(
at: url,
program: MIDIByte(preset),
bankMSB: MIDIByte(bMSB),
bankLSB: MIDIByte(bLSB))
samplerUnit.reset()
} catch let error as NSError {
Log("Error loading SoundFont \(file)")
throw error
}
}
/// Load a Melodic SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
///
public func loadMelodicSoundFont(_ file: String, preset: Int) throws {
try loadSoundFont(file, preset: preset, type: kAUSampler_DefaultMelodicBankMSB)
}
/// Load a Percussive SoundFont SF2 sample data file
///
/// - Parameters:
/// - file: Name of the SoundFont SF2 file without the .sf2 extension
/// - preset: Number of the program to use
///
public func loadPercussiveSoundFont(_ file: String, preset: Int = 0) throws {
try loadSoundFont(file, preset: preset, type: kAUSampler_DefaultPercussionBankMSB)
}
/// Set the pitch bend amount
/// - Parameters:
/// - amount: Value of the pitch bend
/// - channel: MIDI Channel ot apply the bend to
public func setPitchbend(amount: MIDIWord, channel: MIDIChannel) {
samplerUnit.sendPitchBend(amount, onChannel: channel)
}
/// Reset the internal sampler
public func resetSampler() {
samplerUnit.reset()
}
}
|
mit
|
eaplatanios/swift-rl
|
Sources/ReinforcementLearning/Utilities/General.swift
|
1
|
4284
|
// Copyright 2019, Emmanouil Antonios Platanios. 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 Foundation
import TensorFlow
#if os(Linux)
import FoundationNetworking
#endif
public typealias TensorFlowSeed = (graph: Int32, op: Int32)
public enum ReinforcementLearningError: Error {
case renderingError(String)
}
public struct Empty: Differentiable, KeyPathIterable {
public init() {}
}
public protocol Copyable {
func copy() -> Self
}
public extension Encodable {
func json(pretty: Bool = true) throws -> String {
let encoder = JSONEncoder()
if pretty {
encoder.outputFormatting = .prettyPrinted
}
let data = try encoder.encode(self)
return String(data: data, encoding: .utf8)!
}
}
public extension Decodable {
init(fromJson json: String) throws {
let jsonDecoder = JSONDecoder()
self = try jsonDecoder.decode(Self.self, from: json.data(using: .utf8)!)
}
}
/// Downloads the file at `url` to `path`, if `path` does not exist.
///
/// - Parameters:
/// - from: URL to download data from.
/// - to: Destination file path.
///
/// - Returns: Boolean value indicating whether a download was
/// performed (as opposed to not needed).
public func maybeDownload(from url: URL, to destination: URL) throws {
if !FileManager.default.fileExists(atPath: destination.path) {
// Create any potentially missing directories.
try FileManager.default.createDirectory(
atPath: destination.deletingLastPathComponent().path,
withIntermediateDirectories: true)
// Create the URL session that will be used to download the dataset.
let semaphore = DispatchSemaphore(value: 0)
let delegate = DataDownloadDelegate(destinationFileUrl: destination, semaphore: semaphore)
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
// Download the data to a temporary file and then copy that file to
// the destination path.
print("Downloading \(url).")
let task = session.downloadTask(with: url)
task.resume()
// Wait for the download to finish.
semaphore.wait()
}
}
internal class DataDownloadDelegate: NSObject, URLSessionDownloadDelegate {
let destinationFileUrl: URL
let semaphore: DispatchSemaphore
let numBytesFrequency: Int64
internal var logCount: Int64 = 0
init(
destinationFileUrl: URL,
semaphore: DispatchSemaphore,
numBytesFrequency: Int64 = 1024 * 1024
) {
self.destinationFileUrl = destinationFileUrl
self.semaphore = semaphore
self.numBytesFrequency = numBytesFrequency
}
internal func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64
) -> Void {
if (totalBytesWritten / numBytesFrequency > logCount) {
let mBytesWritten = String(format: "%.2f", Float(totalBytesWritten) / (1024 * 1024))
if totalBytesExpectedToWrite > 0 {
let mBytesExpectedToWrite = String(
format: "%.2f", Float(totalBytesExpectedToWrite) / (1024 * 1024))
print("Downloaded \(mBytesWritten) MBs out of \(mBytesExpectedToWrite).")
} else {
print("Downloaded \(mBytesWritten) MBs.")
}
logCount += 1
}
}
internal func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL
) -> Void {
logCount = 0
do {
try FileManager.default.moveItem(at: location, to: destinationFileUrl)
} catch (let writeError) {
print("Error writing file \(location.path) : \(writeError)")
}
print("The file was downloaded successfully to \(location.path).")
semaphore.signal()
}
}
|
apache-2.0
|
johnno1962d/swift
|
test/Reflection/typeref_lowering.swift
|
1
|
5484
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %S/Inputs/TypeLowering.swift -parse-as-library -emit-module -emit-library -module-name TypeLowering -Xfrontend -enable-reflection-metadata -Xfrontend -enable-reflection-names -o %t/libTypesToReflect
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect -binary-filename %platform-module-dir/libswiftCore.dylib -dump-type-lowering < %s | FileCheck %s
// REQUIRES: OS=macosx
V12TypeLowering11BasicStruct
// CHECK: (struct TypeLowering.BasicStruct)
// CHECK-NEXT: (struct size=16 alignment=4 stride=16 num_extra_inhabitants=0
// CHECK-NEXT: (field name=i1 offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=i2 offset=2
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=i3 offset=4
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-NEXT: (field name=bi1 offset=8
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=bi2 offset=10
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=bi3 offset=12
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))))
V12TypeLowering15AssocTypeStruct
// CHECK: (struct TypeLowering.AssocTypeStruct)
// CHECK-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field name=t offset=0
// CHECK-NEXT: (struct size=7 alignment=2 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field name=a offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=b offset=2
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field name=c offset=4
// CHECK-NEXT: (tuple size=3 alignment=2 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field offset=2
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=1 alignment=1 stride=1 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=1 alignment=1 stride=1 num_extra_inhabitants=0)))))))))))
TGV12TypeLowering3BoxVs5Int16_Vs5Int32_
// CHECK-NEXT: (tuple
// CHECK-NEXT: (bound_generic_struct TypeLowering.Box
// CHECK-NEXT: (struct Swift.Int16))
// CHECK-NEXT: (struct Swift.Int32))
// CHECK-NEXT: (tuple size=8 alignment=4 stride=8 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field name=value offset=0
// CHECK-NEXT: (struct size=2 alignment=2 stride=2 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=2 alignment=2 stride=2 num_extra_inhabitants=0))))))
// CHECK-NEXT: (field offset=4
// CHECK-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-NEXT: (field offset=0
// CHECK-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0)))))
|
apache-2.0
|
archembald/avajo-ios
|
avajo-ios/FetchedResultsTableViewController.swift
|
5
|
6035
|
// Copyright (c) 2014-2015 Martijn Walraven
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import CoreData
import Meteor
class FetchedResultsTableViewController: UITableViewController, ContentLoading, SubscriptionLoaderDelegate, FetchedResultsTableViewDataSourceDelegate {
// MARK: - Lifecycle
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Model
var managedObjectContext: NSManagedObjectContext!
func saveManagedObjectContext() {
var error: NSError?
do {
try managedObjectContext!.save()
} catch let error1 as NSError {
error = error1
print("Encountered error saving managed object context: \(error)")
}
}
// MARK: - View Lifecyle
override func viewDidLoad() {
super.viewDidLoad()
updatePlaceholderView()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
loadContentIfNeeded()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
placeholderView?.frame = tableView.bounds
}
// MARK: - Content Loading
private(set) var contentLoadingState: ContentLoadingState = .Initial {
didSet {
if isViewLoaded() {
updatePlaceholderView()
}
}
}
var isContentLoaded: Bool {
switch contentLoadingState {
case .Loaded:
return true
default:
return false
}
}
private(set) var needsLoadContent: Bool = true
func setNeedsLoadContent() {
needsLoadContent = true
if isViewLoaded() {
loadContentIfNeeded()
}
}
func loadContentIfNeeded() {
if needsLoadContent {
loadContent()
}
}
func loadContent() {
needsLoadContent = false
subscriptionLoader = SubscriptionLoader()
subscriptionLoader!.delegate = self
configureSubscriptionLoader(subscriptionLoader!)
subscriptionLoader!.whenReady { [weak self] in
self?.setUpDataSource()
self?.contentLoadingState = .Loaded
}
if !subscriptionLoader!.isReady {
if Meteor.connectionStatus == .Offline {
contentLoadingState = .Offline
} else {
contentLoadingState = .Loading
}
}
}
func resetContent() {
dataSource = nil
tableView.dataSource = nil
tableView.reloadData()
subscriptionLoader = nil
contentLoadingState = .Initial
}
private var subscriptionLoader: SubscriptionLoader?
func configureSubscriptionLoader(subscriptionLoader: SubscriptionLoader) {
}
var dataSource: FetchedResultsTableViewDataSource!
func setUpDataSource() {
if let fetchedResultsController = createFetchedResultsController() {
dataSource = FetchedResultsTableViewDataSource(tableView: tableView, fetchedResultsController: fetchedResultsController)
dataSource.delegate = self
tableView.dataSource = dataSource
dataSource.performFetch()
}
}
func createFetchedResultsController() -> NSFetchedResultsController? {
return nil
}
// MARK: SubscriptionLoaderDelegate
func subscriptionLoader(subscriptionLoader: SubscriptionLoader, subscription: METSubscription, didFailWithError error: NSError) {
contentLoadingState = .Error(error)
}
// MARK: Connection Status Notification
func connectionStatusDidChange() {
if !isContentLoaded && Meteor.connectionStatus == .Offline {
contentLoadingState = .Offline
}
}
// MARK: - User
var currentUser: User? {
if let userID = Meteor.userID {
let userObjectID = Meteor.objectIDForDocumentKey(METDocumentKey(collectionName: "users", documentID: userID))
return (try? managedObjectContext.existingObjectWithID(userObjectID)) as? User
}
return nil;
}
// MARK: - Placeholder View
private var placeholderView: PlaceholderView?
private var savedCellSeparatorStyle: UITableViewCellSeparatorStyle = .None
func updatePlaceholderView() {
if isContentLoaded {
if placeholderView != nil {
placeholderView?.removeFromSuperview()
placeholderView = nil
swap(&savedCellSeparatorStyle, &tableView.separatorStyle)
}
} else {
if placeholderView == nil {
placeholderView = PlaceholderView()
tableView.addSubview(placeholderView!)
swap(&savedCellSeparatorStyle, &tableView.separatorStyle)
}
}
switch contentLoadingState {
case .Loading:
placeholderView?.showLoadingIndicator()
case .Offline:
placeholderView?.showTitle("Could not establish connection to server", message: nil)
case .Error(let error):
placeholderView?.showTitle(error.localizedDescription, message: error.localizedFailureReason)
default:
break
}
}
// MARK: - FetchedResultsTableViewDataSourceDelegate
func dataSource(dataSource: FetchedResultsTableViewDataSource, didFailWithError error: NSError) {
print("Data source encountered error: \(error)")
}
}
|
agpl-3.0
|
MounikaAnkam/BooksAuthors
|
BooksAuthors/NewAuthorViewController.swift
|
1
|
2683
|
//
// NewAuthorViewController.swift
// BooksAuthors
//
// Created by Jaini,Santhoshi on 3/20/15.
// Copyright (c) 2015 Student. All rights reserved.
//
import UIKit
import CoreData
class NewAuthorViewController: UIViewController , UITextFieldDelegate{
var managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
@IBOutlet weak var SSNTF: UITextField!
@IBOutlet weak var nameTF: UITextField!
@IBOutlet weak var dobTF: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
SSNTF.placeholder = "Enter SSN "
dobTF.placeholder = "MM-DD-YYYY"
nameTF.placeholder = "Enter Name"
nameTF.delegate = self
SSNTF.delegate = self
dobTF.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Done(sender: AnyObject) {
var newAuthor = NSEntityDescription.insertNewObjectForEntityForName("Author",
inManagedObjectContext: managedObjectContext!) as Author
if !dobTF.text.isEmpty && !nameTF.text.isEmpty && !SSNTF.text.isEmpty {
newAuthor.ssn = Int((SSNTF.text as NSString).integerValue)
newAuthor.name = nameTF.text
var dateString = dobTF.text
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
var dateFromString = dateFormatter.dateFromString(dateString)
newAuthor.dob = dateFromString!
var error:NSError?
managedObjectContext?.save(&error)
self.dismissViewControllerAnimated(true , completion: nil )
}
}
@IBAction func Cancel(sender: AnyObject) {
self.dismissViewControllerAnimated(true , completion: nil )
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
nameTF.resignFirstResponder()
SSNTF.resignFirstResponder()
dobTF.resignFirstResponder()
return true
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
SnowdogApps/Project-Needs-Partner
|
CooperationFinder/ViewModels/SDProjectsListViewModel.swift
|
1
|
3958
|
//
// SDProjectsListViewModel.swift
// CooperationFinder
//
// Created by Radoslaw Szeja on 25.02.2015.
// Copyright (c) 2015 Snowdog. All rights reserved.
//
import UIKit
protocol SDListProtocol {
func numberOfSectionsAtIndexPath() -> Int
func numberOfRowsInSection(section: Int) -> Int
func itemAtIndexpath(indexPath: NSIndexPath) -> Project?
}
protocol SDListViewModelDelegate : class {
func didReloadData(count: Int)
}
class SDProjectsListViewModel: NSObject, SDListProtocol {
var tags : [String]?
var status : String?
var trustedOnly : Bool?
var commercial : Bool?
var loggedUser : User?
var itemsArray: [AnyObject] = []
var searchItemsArray: [AnyObject] = []
private var queryIndex = 0;
private var searchQueryIndex = 0;
weak private var delegate: SDListViewModelDelegate?
override init() {
self.delegate = nil
super.init()
}
init(delegate: SDListViewModelDelegate) {
self.delegate = delegate
super.init()
}
func reloadData(searchQuery: String) {
self.queryIndex++
let q = self.queryIndex
let getProjectsBlock : () -> Void = {
Project.getProjects(nil, searchPhrase:searchQuery, tags: self.tags, statuses: self.statuses(), commercial: self.commercial, partner: self.trustedOnly) { (success, projects) -> Void in
if let projs = projects {
self.itemsArray = projs
} else {
self.itemsArray = []
}
Async.main {
if (q == self.queryIndex) {
if let del = self.delegate {
del.didReloadData(self.itemsArray.count)
}
}
}
}
}
if (self.loggedUser != nil) {
getProjectsBlock()
} else {
User.getLoggedUser(completion: { (user) -> () in
self.loggedUser = user
getProjectsBlock()
})
}
}
func statuses() -> [String] {
var statuses : [String] = []
if self.status != nil {
statuses.append(self.status!)
} else {
statuses.append(ProjectStatusOpen)
if let user = self.loggedUser {
if (user.role == UserRoleModerator) {
statuses.append(ProjectStatusWaitingForApproval)
}
}
}
return statuses
}
// MARK: SDListProtocol
func numberOfSectionsAtIndexPath() -> Int {
return 1
}
func numberOfRowsInSection(section: Int) -> Int {
if section == 0 {
return itemsArray.count
}
return 0
}
func numberOfRowsInSearchSection(section: Int) -> Int {
if section == 0 {
return searchItemsArray.count
}
return 0
}
func itemAtIndexpath(indexPath: NSIndexPath) -> Project? {
return itemsArray[indexPath.row] as? Project
}
func searchItemAtIndexPath(indexPath:NSIndexPath) -> Project? {
return searchItemsArray[indexPath.row] as? Project
}
func searchWithPhrase(phrase: String, completion: (success: Bool) -> ()) {
self.searchQueryIndex++
let q = self.searchQueryIndex
Project.getProjects(nil, searchPhrase:phrase, tags: nil, statuses: self.statuses(), commercial: nil, partner: nil) { (success, projects) -> Void in
if let projs = projects {
self.searchItemsArray = projs
} else {
self.searchItemsArray = []
}
Async.main {
if (q == self.searchQueryIndex) {
completion(success: success)
}
}
}
}
}
|
apache-2.0
|
dduan/swift
|
test/1_stdlib/tgmath_optimized.swift
|
1
|
994
|
// RUN: mkdir -p %t
// RUN: %target-build-swift %s -o %t/a.out -Ounchecked
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
#if os(Linux) || os(FreeBSD)
import Glibc
#else
import Darwin
#endif
import StdlibUnittest
// Also import modules which are used by StdlibUnittest internally. This
// workaround is needed to link all required libraries in case we compile
// StdlibUnittest with -sil-serialize-all.
import SwiftPrivate
#if _runtime(_ObjC)
import ObjectiveC
#endif
var TGMathTestSuite = TestSuite("tgmath")
let minusOneDouble = Double(-1.0)
let minusOneFloat = Float(-1.0)
@inline(never)
func minusOneDoubleFunction() -> Double{
return minusOneDouble
}
@inline(never)
func minusOneFloatFunction() -> Float {
return minusOneFloat
}
TGMathTestSuite.test("sqrt") {
expectTrue(isnan(sqrt(minusOneFloat)))
expectTrue(isnan(sqrt(minusOneFloatFunction())))
expectTrue(isnan(sqrt(minusOneDouble)))
expectTrue(isnan(sqrt(minusOneDoubleFunction())))
}
runAllTests()
|
apache-2.0
|
russbishop/swift
|
test/ClangModules/attr-swift_private.swift
|
1
|
4550
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-clang-importer-objc-overlays
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -parse %s -verify
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -emit-ir %s -D IRGEN | FileCheck %s
// RUN: %target-swift-ide-test(mock-sdk: %clang-importer-sdk-nosource -I %t) -I %S/Inputs/custom-modules -print-module -source-filename="%s" -module-to-print SwiftPrivateAttr > %t.txt
// RUN: FileCheck -check-prefix=GENERATED-NEGATIVE %s < %t.txt
// RUN: diff -U3 %S/Inputs/SwiftPrivateAttr.txt %t.txt
// Look for identifiers with "Priv" in them that haven't been prefixed.
// GENERATED-NEGATIVE-NOT: {{[^A-Za-z0-9_][A-Za-z0-9]*[Pp]riv}}
// REQUIRES: objc_interop
import SwiftPrivateAttr
// Note: The long-term plan is for these to only be available from the Swift
// half of a module, or from an overlay. At that point we should test that these
// are available in that case and /not/ in the normal import case.
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}12testProperty
public func testProperty(_ foo: Foo) {
// CHECK: @"\01L_selector(setPrivValue:)"
_ = foo.__privValue
foo.__privValue = foo
// CHECK: @"\01L_selector(setPrivClassValue:)"
_ = Foo.__privClassValue
Foo.__privClassValue = foo
#if !IRGEN
_ = foo.privValue // expected-error {{value of type 'Foo' has no member 'privValue'}}
#endif
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}11testMethods
public func testMethods(_ foo: Foo) {
// CHECK: @"\01L_selector(noArgs)"
foo.__noArgs()
// CHECK: @"\01L_selector(oneArg:)"
foo.__oneArg(1)
// CHECK: @"\01L_selector(twoArgs:other:)"
foo.__twoArgs(1, other: 2)
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}16testInitializers
public func testInitializers() {
// Checked below; look for "CSo3Bar".
_ = Bar(__noArgs: ())
_ = Bar(__oneArg: 1)
_ = Bar(__twoArgs: 1, other: 2)
_ = Bar(__: 1)
}
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}18testFactoryMethods
public func testFactoryMethods() {
// CHECK: @"\01L_selector(fooWithOneArg:)"
_ = Foo(__oneArg: 1)
// CHECK: @"\01L_selector(fooWithTwoArgs:other:)"
_ = Foo(__twoArgs: 1, other: 2)
// CHECK: @"\01L_selector(foo:)"
_ = Foo(__: 1)
}
#if !IRGEN
public func testSubscript(_ foo: Foo) {
_ = foo[foo] // expected-error {{type 'Foo' has no subscript members}}
_ = foo[1] // expected-error {{type 'Foo' has no subscript members}}
}
#endif
// CHECK-LABEL: define{{( protected)?}} void @{{.+}}12testTopLevel
public func testTopLevel() {
// Checked below; look for "PrivFooSub".
let foo = __PrivFooSub()
_ = foo as __PrivProto
// CHECK: @"\01l_OBJC_PROTOCOL_REFERENCE_$_PrivProto"
foo.conforms(to: __PrivProto.self)
// CHECK: call void @privTest()
__privTest()
_ = __PrivS1()
#if !IRGEN
let _ = PrivFooSub() // expected-error {{use of unresolved identifier}}
privTest() // expected-error {{use of unresolved identifier}}
PrivS1() // expected-error {{use of unresolved identifier}}
#endif
}
// CHECK-LABEL: define linkonce_odr hidden %swift.type* @_TMaCSo12__PrivFooSub{{.*}} {
// CHECK: %objc_class** @"OBJC_CLASS_REF_$_PrivFooSub"
// CHECK: }
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_TTOFCSo3BarcfT2__Vs5Int32_GSQS__
// CHECK: @"\01L_selector(init:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_TTOFCSo3BarcfT9__twoArgsVs5Int325otherS0__GSQS__
// CHECK: @"\01L_selector(initWithTwoArgs:other:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_TTOFCSo3BarcfT8__oneArgVs5Int32_GSQS__
// CHECK: @"\01L_selector(initWithOneArg:)"
// CHECK-LABEL: define linkonce_odr hidden {{.+}} @_TTOFCSo3BarcfT8__noArgsT__GSQS__
// CHECK: @"\01L_selector(initWithNoArgs)"
_ = __PrivAnonymousA
_ = __E0PrivA
_ = __PrivE1A as __PrivE1
_ = NSEnum.__privA
_ = NSEnum.B
_ = NSOptions.__privA
_ = NSOptions.B
func makeSureAnyObject(_: AnyObject) {}
#if !IRGEN
func testUnavailableRefs() {
var x: __PrivCFTypeRef // expected-error {{'__PrivCFTypeRef' has been renamed to '__PrivCFType'}}
var y: __PrivCFSubRef // expected-error {{'__PrivCFSubRef' has been renamed to '__PrivCFSub'}}
}
#endif
func testCF(_ a: __PrivCFType, b: __PrivCFSub, c: __PrivInt) {
makeSureAnyObject(a)
makeSureAnyObject(b)
#if !IRGEN
makeSureAnyObject(c) // expected-error {{argument type '__PrivInt' (aka 'Int32') does not conform to expected type 'AnyObject'}}
#endif
}
extension __PrivCFType {}
extension __PrivCFSub {}
_ = 1 as __PrivInt
|
apache-2.0
|
vmanot/swift-package-manager
|
Fixtures/DependencyResolution/Internal/InternalExecutableAsDependency/Package.swift
|
3
|
127
|
import PackageDescription
let package = Package(targets: [
Target(name: "Foo", dependencies: [.Target(name: "Bar")])
])
|
apache-2.0
|
fespinoza/linked-ideas-osx
|
LinkedIdeas-Shared/Sources/ViewModels/DrawableLink.swift
|
1
|
2219
|
//
// DrawableLink.swift
// LinkedIdeas
//
// Created by Felipe Espinoza Castillo on 16/02/2017.
// Copyright © 2017 Felipe Espinoza Dev. All rights reserved.
//
import CoreGraphics
import Foundation
public struct DrawableLink: DrawableElement {
let link: Link
public init(link: Link) {
self.link = link
}
public var drawingBounds: CGRect {
return CGRect(point1: link.originPoint, point2: link.targetPoint)
}
public func draw() {
link.color.set()
constructArrow()?.bezierPath().fill()
drawSelectedRing()
drawLinkText()
drawForDebug()
}
func drawLinkText() {
guard link.stringValue != "" else {
return
}
// background
Color.white.set()
var textSize = link.attributedStringValue.size()
let padding: CGFloat = 8.0
textSize.width += padding
textSize.height += padding
let textRect = CGRect(center: link.centerPoint, size: textSize)
textRect.fill()
// text
let bottomLeftTextPoint = link.centerPoint.translate(
deltaX: -(textSize.width - padding) / 2.0,
deltaY: -(textSize.height - padding) / 2.0
)
// swiftlint:disable:next force_cast
let attributedStringValue = link.attributedStringValue.mutableCopy() as! NSMutableAttributedString
attributedStringValue.addAttributes(
[.foregroundColor: Color.gray],
range: NSRangeFromString(link.attributedStringValue.string)
)
attributedStringValue.draw(at: bottomLeftTextPoint)
}
func drawSelectedRing() {
guard link.isSelected else {
return
}
Color.red.set()
constructArrow()?.bezierPath().stroke()
}
func constructArrow() -> Arrow? {
let originPoint = link.originPoint
let targetPoint = link.targetPoint
if let intersectionPointWithOrigin = link.originRect.firstIntersectionTo(targetPoint),
let intersectionPointWithTarget = link.targetRect.firstIntersectionTo(originPoint) {
return Arrow(point1: intersectionPointWithOrigin, point2: intersectionPointWithTarget)
} else {
return nil
}
}
public func drawForDebug() {
if isDebugging() {
drawDebugHelpers()
Color.magenta.set()
BezierPath(rect: link.area).stroke()
}
}
}
|
mit
|
clwm01/RTKitDemo
|
RCToolsDemo/RCToolsDemo/ThirdViewController.swift
|
2
|
542
|
//
// ThirdViewController.swift
// RCToolsDemo
//
// Created by Rex Cao on 29/9/15.
// Copyright (c) 2015 rexcao. All rights reserved.
//
import UIKit
class ThirdViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
RTPrint.shareInstance().prt("third VC loaded")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
AMarones/AMPickerView
|
Sample/Sample/MultiplesPickersViewController.swift
|
1
|
2163
|
//
// MultiplesPickersViewController.swift
// Sample
//
// Created by Alexandre Marones on 11/10/15.
//
//
import UIKit
class MultiplesPickersViewController: UIViewController , AMPickerViewDelegate {
@IBOutlet weak var buttonSelectValue: UIButton!
@IBOutlet weak var buttonSelectCard: UIButton!
private var _cards = ["•••• 5858", "•••• 4444", "•••• 3269", "•••• 1109"]
private var _values = ["$10", "$20", "$35", "$60"]
private var _datasource = [String]()
private let _sentByValues = "values"
private let _sentByCards = "cards"
private var _sentBy = String()
private var _alertPickerView = AMPickerView()
override func viewDidLoad() {
super.viewDidLoad()
_alertPickerView = AMPickerView(delegate: self, ownerViewControler: self)
}
func showPickerView() {
var pickerTitle = "Select Card"
if _sentBy == _sentByValues {
pickerTitle = "Select Value"
}
_alertPickerView.show(pickerTitle, datasource: _datasource)
}
// MARK: - IBAction
@IBAction func selectValueButtonPressed(sender: AnyObject) {
_datasource.removeAll(keepCapacity: false)
_datasource = _values
_sentBy = _sentByValues
showPickerView()
}
@IBAction func selectCardButtonPressed(sender: AnyObject) {
_datasource.removeAll(keepCapacity: false)
_datasource = _cards
_sentBy = _sentByCards
showPickerView()
}
// MARK: - AMActionPickerViewDelegate
func cancelButtonPressed() {
_alertPickerView.close()
}
func doneButtonPressed(index: Int) {
let selectedValue = _datasource[index]
if _sentBy == _sentByValues {
buttonSelectValue.setTitle(selectedValue, forState: UIControlState.Normal)
} else {
buttonSelectCard.setTitle(selectedValue, forState: UIControlState.Normal)
}
_alertPickerView.close()
}
}
|
mit
|
vakoc/particle-swift
|
Sources/Errors.swift
|
1
|
15493
|
// This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016, 2018 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See https://www.vakoc.com/LICENSE.txt for license information
import Foundation
/// Errors that can be thrown during particle operations
public enum ParticleError: Error {
case missingCredentials,
listAccessTokensFailed(Error),
callFunctionFailed(Error),
deviceListFailed(Error),
deviceDetailedInformationFailed(Error),
deviceInformationFailed(String, Error),
oauthTokenCreationFailed(Error),
oauthTokenParseFailed,
oauthTokenDeletionFailed(Error),
invalidURLRequest(Error),
claimDeviceFailed(Error),
transferDeviceFailed(Error),
createClaimCode(Error),
unclaimDeviceFailed(Error),
webhookListFailed(Error),
webhookGetFailed(String,Error),
createWebhookFailed(Error),
failedToParseJsonFile,
deleteWebhookFailed(String,Error),
httpResponseParseFailed(String?),
variableValueFailed(Error),
compileRequestFailed(String),
librariesRequestFailed(String),
librariesUrlMalformed(String),
libraryVersionsRequestFailed(String),
productsListFailed(Error),
productTeamMembersFailed(Error),
inviteTeamMemberFailed(Error),
removeTeamMemberFailed(Error),
invalidUsername,
downloadBinaryFailed(Error),
downloadError,
flashDeviceFailed(Error),
invalidToken,
particleError(String, String),
genericError,
pingDeviceFailed(Error),
addNoteFailed(Error),
signalDeviceFailed(Error),
genericErrorMessage(String),
invalidVariableValue(String),
listOAuthClientsFailed(Error),
createOAuthClientFailed(Error),
updateOAuthClientFailed(String, Error),
deleteOAuthClientFailed(String, Error)
}
extension ParticleError: CustomStringConvertible {
public var description: String { return errorDescription ?? String(describing: self) }
}
// Linux doesn't support variadic lists including strings, reference https://bugs.swift.org/browse/SR-957
#if os(Linux)
extension ParticleError: LocalizedError {
public var errorDescription: String? {
switch (self) {
case .missingCredentials:
return "Missing username or password credentials"
case .listAccessTokensFailed(let error):
return "The request to list available access tokens failed with error: \(error)"
case .callFunctionFailed(let error):
return "The request to call the function afiled with error: \(error)"
case .deviceListFailed(let error):
return "The request to obtain available devices failed with error: \(error)"
case .deviceInformationFailed(let deviceID, let error):
return "The request to obtain device information for device ID \(deviceID) failed with error: \(error)"
case .deviceDetailedInformationFailed(let error):
return "The request to obtain detailed device information failed with error: \(error)"
case .oauthTokenCreationFailed(let error):
return "Failed to create an OAuth token with error: \(error)"
case .oauthTokenDeletionFailed(let error):
return "Failed to delete an OAuth token with error: \(error)"
case .oauthTokenParseFailed:
return "The HTTP response could not be parsed as a valid token"
case .invalidURLRequest(let error):
return "Failed to create a valid URL request with error: \(error)"
case .claimDeviceFailed(let error):
return "Failed to claim device with error: \(error)"
case .transferDeviceFailed(let error):
return "Failed to transfer device with error: \(error)"
case .createClaimCode(let error):
return "Failed to create a claim code with error: \(error)"
case .unclaimDeviceFailed(let error):
return "Failed to unclaim a device with error: \(error)"
case .webhookListFailed(let error):
return "Failed to list the available webhooks with error: \(error)"
case .webhookGetFailed(let webhookID, let error):
return "Failed to get the webhook \(webhookID) with error: \(error)"
case .createWebhookFailed(let error):
return "Failed to create the webhook with error: \(error)"
case .failedToParseJsonFile:
return "Failed to parse the specified JSON file"
case .deleteWebhookFailed(let webhookID, let error):
return "Failed to delete the webhook \(webhookID) with error: \(error)"
case .httpResponseParseFailed(let message):
return "Failed to parse the HTTP response '\(message ?? "")'"
case .variableValueFailed(let error):
return "Failed to obtain variable value with error: \(error)"
case .compileRequestFailed(let message):
return "Failed to compile source files value with response \(message)"
case .librariesRequestFailed(let error):
return "Failed to obtain the available libraries with error: \(error)"
case .librariesUrlMalformed(let string):
return "Failed to construct a valid url for the libraries api using \(string)"
case .libraryVersionsRequestFailed(let string):
return "Failed to obtain library versions with error \(string)"
case .productsListFailed(let error):
return "Failed to list the products with error: \(error)"
case .productTeamMembersFailed(let error):
return "Failed to obtain the product team members with error: \(error)"
case .inviteTeamMemberFailed(let error):
return "Failed to invite team member with error: \(error)"
case .removeTeamMemberFailed(let error):
return "Failed to remove team member with error: \(error)"
case .invalidUsername:
return "Invalid Username"
case .downloadBinaryFailed(let error):
return "Failed to download binary with error: \(error)"
case .downloadError:
return "Failed to download binary"
case .flashDeviceFailed(let error):
return "Failed to flash device with error: \(error)"
case .invalidToken:
return "Failed to complete request due to an invalid token"
case .particleError(let errorCode, let errorDescription):
return "Received the error \(errorCode): \(errorDescription)"
case .genericError:
return "An unexpected error occurred"
case .pingDeviceFailed(let error):
return "Failed to ping device with error \(String(describing: error))"
case .addNoteFailed(let error):
return "Failed to add a device note with error \(String(describing: error))"
case .signalDeviceFailed(let error):
return "Failed to signal device with error \(String(describing: error))"
case .genericErrorMessage(let msg):
return "A generic error occurred: \(msg)"
case .invalidVariableValue(let val):
return "Failed due to an invalid variable value: \(val)"
case .listOAuthClientsFailed(let error):
return "Failed to list OAuth clients with error: \(String(describing: error))"
case .createOAuthClientFailed(let error):
return "Failed to create an OAuth client with error: \(String(describing: error))"
case .updateOAuthClientFailed(let identifier, let error):
return "Failed to update the OAuth client identified by \(identifier) with error: \(String(describing: error))"
case .deleteOAuthClientFailed(let identifier, let error):
return "Failed to delete the OAuth client identified by \(identifier) with error: \(String(describing: error))"
}
}
}
#else
extension ParticleError: LocalizedError {
public var errorDescription: String? {
switch (self) {
case .missingCredentials:
return String.localizedStringWithFormat("Missing username or password credentials")
case .listAccessTokensFailed(let error):
return String.localizedStringWithFormat("The request to list available access tokens failed with error: %1@", "\(error)")
case .callFunctionFailed(let error):
return String.localizedStringWithFormat("The request to call the function afiled with error: %1@", "\(error)")
case .deviceListFailed(let error):
return String.localizedStringWithFormat("The request to obtain available devices failed with error: %1@", "\(error)")
case .deviceInformationFailed(let deviceID, let error):
return String.localizedStringWithFormat("The request to obtain device information for device ID %1@ failed with error %2@", deviceID, "\(error)")
case .deviceDetailedInformationFailed(let error):
return String.localizedStringWithFormat("The request to obtain detailed device information failed with error: %1@", "\(error)")
case .oauthTokenCreationFailed(let error):
return String.localizedStringWithFormat("Failed to create an OAuth token with error: %1@", "\(error)")
case .oauthTokenDeletionFailed(let error):
return "Failed to delete an OAuth token with error: \(error)"
case .oauthTokenParseFailed:
return String.localizedStringWithFormat("The HTTP response could not be parsed as a valid token")
case .invalidURLRequest(let error):
return String.localizedStringWithFormat("Failed to create a valid URL request with error: %1@", "\(error)")
case .claimDeviceFailed(let error):
return String.localizedStringWithFormat("Failed to claim device with error: %1@", "\(error)")
case .transferDeviceFailed(let error):
return String.localizedStringWithFormat("Failed to transfer device with error: %1@", "\(error)")
case .createClaimCode(let error):
return String.localizedStringWithFormat("Failed to create a claim code with error: %1@", "\(error)")
case .unclaimDeviceFailed(let error):
return String.localizedStringWithFormat("Failed to unclaim a device with error: %1@", "\(error)")
case .webhookListFailed(let error):
return String.localizedStringWithFormat("Failed to list the available webhooks with error: %1@", "\(error)")
case .webhookGetFailed(let webhookID, let error):
return String.localizedStringWithFormat("Failed to get the webhook %1@ with error %2@", "\(webhookID)", "\(error)")
case .createWebhookFailed(let error):
return String.localizedStringWithFormat("Failed to create the webhook with error: %1@", "\(error)")
case .failedToParseJsonFile:
return String.localizedStringWithFormat("Failed to parse the specified JSON file")
case .deleteWebhookFailed(let webhookID, let error):
return String.localizedStringWithFormat("Failed to delete the webhook %1@ with error %2@", "\(webhookID)", "\(error)")
case .httpResponseParseFailed(let message):
return String.localizedStringWithFormat("Failed to parse the HTTP response '%1@'", message ?? "")
case .variableValueFailed(let error):
return String.localizedStringWithFormat("Failed to obtain variable value with error: %1@", "\(error)")
case .compileRequestFailed(let message):
return String.localizedStringWithFormat("Failed to compile source files value with response %1@", "\(message)")
case .librariesRequestFailed(let error):
return String.localizedStringWithFormat("Failed to obtain the available libraries with error: %1@", String(describing: error))
case .librariesUrlMalformed(let string):
return String.localizedStringWithFormat("Failed to construct a valid url for the libraries api using %1@", string)
case .libraryVersionsRequestFailed(let string):
return String.localizedStringWithFormat("Failed to obtain library versions with error: %1@", String(describing: string))
case .productsListFailed(let error):
return String.localizedStringWithFormat("Failed to list the products with error: %1@", String(describing: error))
case .productTeamMembersFailed(let error):
return String.localizedStringWithFormat("Failed to obtain the product team members with error: %1@", String(describing: error))
case .inviteTeamMemberFailed(let error):
return String.localizedStringWithFormat("Failed to invite team member with error: %1@", String(describing: error))
case .removeTeamMemberFailed(let error):
return String.localizedStringWithFormat("Failed to remove team member with error: %1@", String(describing: error))
case .invalidUsername:
return String.localizedStringWithFormat("Invalid username")
case .downloadBinaryFailed(let error):
return String.localizedStringWithFormat("Failed to download binary with error: %1@", String(describing: error))
case .downloadError:
return String.localizedStringWithFormat("Failed to download binary")
case .flashDeviceFailed:
return String.localizedStringWithFormat("Failed to flash device with error: %1@", String(describing: error))
case .invalidToken:
return String.localizedStringWithFormat("Failed to complete request due to an invalid token")
case .particleError(let errorCode, let errorDescription):
return String.localizedStringWithFormat("Received the error %1@: %2@", errorCode, errorDescription)
case .genericError:
return String.localizedStringWithFormat("An unexpected error occurred")
case .pingDeviceFailed(let error):
return String.localizedStringWithFormat("Failed to ping device with error %1@", String(describing: error))
case .addNoteFailed(let error):
return String.localizedStringWithFormat("Failed to add a device note with error %1@", String(describing: error))
case .signalDeviceFailed(let error):
return String.localizedStringWithFormat("Failed to signal a device error %1@", String(describing: error))
case .genericErrorMessage(let msg):
return String.localizedStringWithFormat("A generic error occurred: %1@", String(describing: msg))
case .invalidVariableValue(let val):
return String.localizedStringWithFormat("Failed due to an invalid variable value: %1@", String(describing: val))
case .listOAuthClientsFailed(let error):
return String.localizedStringWithFormat("Failed to list OAuth clients with error: %1@", String(describing: error))
case .createOAuthClientFailed(let error):
return String.localizedStringWithFormat("Failed to create an OAuth client with error: %1@", String(describing: error))
case .updateOAuthClientFailed(let identifier, let error):
return String.localizedStringWithFormat("Failed to update the OAuth client identified by %1@ with error: %2@", identifier, String(describing: error))
case .deleteOAuthClientFailed(let identifier, let error):
return String.localizedStringWithFormat("Failed to delete the OAuth client identified by %1@ with error: %2@", identifier, String(describing: error))
}
}
}
#endif
|
apache-2.0
|
swift102016team5/mefocus
|
MeFocus/Pods/AutoCompleteTextField/Pod/Classes/AutoCompleteTextFieldProtocols.swift
|
1
|
3886
|
//
// AutoCompleteTextFieldProtocols.swift
// Pods
//
// Created by Neil Francis Hipona on 16/07/2016.
// Copyright (c) 2016 Neil Francis Ramirez Hipona. All rights reserved.
//
import Foundation
import UIKit
// MARK: - AutoCompleteTextField Protocol
public protocol AutoCompleteTextFieldDataSource: NSObjectProtocol {
// Required protocols
func autoCompleteTextFieldDataSource(_ autoCompleteTextField: AutoCompleteTextField) -> [String] // called when in need of suggestions.
}
@objc public protocol AutoCompleteTextFieldDelegate: UITextFieldDelegate {
// Optional protocols
// return NO to disallow editing. Defaults to YES.
@objc optional func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool
// became first responder
@objc optional func textFieldDidBeginEditing(_ textField: UITextField)
// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end. Defaults to YES.
@objc optional func textFieldShouldEndEditing(_ textField: UITextField) -> Bool
// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
@objc optional func textFieldDidEndEditing(_ textField: UITextField)
// return NO to not change text. Defaults to YES.
@objc optional func textField(_ textField: UITextField, changeCharactersInRange range: NSRange, replacementString string: String) -> Bool
// called when clear button pressed. return NO to ignore (no notifications)
@objc optional func textFieldShouldClear(_ textField: UITextField) -> Bool
// called when 'return' key pressed. return NO to ignore.
@objc optional func textFieldShouldReturn(_ textField: UITextField) -> Bool
}
// MARK: - UITextFieldDelegate
extension AutoCompleteTextField: UITextFieldDelegate {
// MARK: - UITextFieldDelegate
public func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldShouldBeginEditing else { return true }
return delegateCall(self)
}
public func textFieldDidBeginEditing(_ textField: UITextField) {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldDidBeginEditing else { return }
delegateCall(self)
}
public func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldShouldEndEditing else { return true }
return delegateCall(self)
}
public func textFieldDidEndEditing(_ textField: UITextField) {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldDidEndEditing else { return }
delegateCall(self)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textField(_:changeCharactersInRange:replacementString:) else { return true }
return delegateCall(textField, range, string)
}
public func textFieldShouldClear(_ textField: UITextField) -> Bool {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldShouldClear else { return true }
return delegateCall(self)
}
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
guard let delegate = autoCompleteTextFieldDelegate, let delegateCall = delegate.textFieldShouldReturn else { return endEditing(true) }
return delegateCall(self)
}
}
|
mit
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.