repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
BlenderSleuth/Unlokit | Unlokit/Nodes/Blocks/BlockNode.swift | 1 | 4895 | //
// BlockNode.swift
// Unlokit
//
// Created by Ben Sutherland on 26/1/17.
// Copyright © 2017 blendersleuthdev. All rights reserved.
//
import SpriteKit
enum Side {
case up
case down
case left
case right
case centre
static let all: [Side] = [.up, .down, .left, .right, .centre]
var position: CGPoint {
switch self {
case .up:
return CGPoint(x: 0.0, y: 64)
case .down:
return CGPoint(x: 0.0, y: -64)
case .left:
return CGPoint(x: -64, y: 0.0)
case .right:
return CGPoint(x: 64, y: 0.0)
case .centre:
return CGPoint.zero
}
}
}
class BlockNode: SKSpriteNode, NodeSetup {
// If this block is in a beam block
var beamNode: BeamBlockNode?
var beamJoints: [SKPhysicsJoint]?
// For calculating the side that was contacted
var up: CGPoint!
var down: CGPoint!
var left: CGPoint!
var right: CGPoint!
var centre: CGPoint!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Physics
physicsBody?.categoryBitMask = Category.beamBlock
physicsBody?.contactTestBitMask = Category.zero
physicsBody?.collisionBitMask = Category.all
//physicsBody?.fieldBitMask = Category.fields
//physicsBody?.mass = 10
// Get coordinates of sides of block
let halfWidth = frame.width / 2
let halfHeight = frame.height / 2
up = CGPoint(x: frame.origin.x + halfWidth, y: frame.origin.y + frame.size.height)
down = CGPoint(x: frame.origin.x + halfWidth, y: frame.origin.y)
left = CGPoint(x: frame.origin.x, y: frame.origin.y + halfHeight)
right = CGPoint(x: frame.origin.x + frame.size.width, y: frame.origin.y + halfHeight)
centre = CGPoint.zero
}
func setup(scene: GameScene) {
// Make all children had same properties
for child in children {
if let sprite = child as? SKSpriteNode {
sprite.lightingBitMask = Category.all
sprite.shadowCastBitMask = Category.zero
sprite.shadowedBitMask = Category.controllerLight | Category.toolLight | Category.lockLight
}
}
//Lighting properties
lightingBitMask = Category.all
shadowCastBitMask = Category.zero
shadowedBitMask = Category.controllerLight | Category.toolLight | Category.lockLight
getDataFromParent()
}
private func getDataFromParent() {
var data: NSDictionary?
// Find user data from parents
var tempNode: SKNode = self
while !(tempNode is SKScene) {
if let userData = tempNode.userData {
data = userData
}
tempNode = tempNode.parent!
}
if let addLight = data?["light"] as? Bool, addLight {
let light = SKLightNode()
light.falloff = 3
light.categoryBitMask = Category.blockLight
addChild(light)
let emitter = SKEmitterNode(fileNamed: "LightBlock")!
addChild(emitter)
}
}
// Find side from contact
func getSide(contact: SKPhysicsContact) -> Side {
guard let scene = scene else {
return .centre
}
// Get point in block coordinates
let point = convert(contact.contactPoint, from: scene)
let upDistance = getDistance(p1: point, p2: up)
let downDistance = getDistance(p1: point, p2: down)
let leftDistance = getDistance(p1: point, p2: left)
let rightDistance = getDistance(p1: point, p2: right)
let dict = [Side.up: upDistance, Side.down: downDistance, Side.left: leftDistance, Side.right: rightDistance]
var side = Side.up
// Large number to start
var smallestDistance = CGFloat(UInt32.max)
// Find smallest distance
for (sideName, distance) in dict {
if distance < smallestDistance {
smallestDistance = distance
side = sideName
}
}
return side
}
// Difference between two points
func getDistance(p1:CGPoint,p2:CGPoint) -> CGFloat {
let xDist = (p2.x - p1.x)
let yDist = (p2.y - p1.y)
return CGFloat(sqrt((xDist * xDist) + (yDist * yDist)))
}
func bounce(side: Side) {
let bounce: SKAction
switch side{
case .up:
bounce = SKAction.sequence([SKAction.moveBy(x: 0, y: -30, duration: 0.1), SKAction.moveBy(x: 0, y: 30, duration: 0.1)])
bounce.timingMode = .easeInEaseOut
case .down:
bounce = SKAction.sequence([SKAction.moveBy(x: 0, y: 30, duration: 0.1), SKAction.moveBy(x: 0, y: -30, duration: 0.1)])
bounce.timingMode = .easeInEaseOut
case .left:
bounce = SKAction.sequence([SKAction.moveBy(x: -30, y: 0, duration: 0.1), SKAction.moveBy(x: 30, y: 0, duration: 0.1)])
bounce.timingMode = .easeInEaseOut
case .right:
bounce = SKAction.sequence([SKAction.moveBy(x: 30, y: 0, duration: 0.1), SKAction.moveBy(x: -30, y: 0, duration: 0.1)])
bounce.timingMode = .easeInEaseOut
default:
return
}
run(bounce)
run(SoundFX.sharedInstance["block"]!)
}
func addPinJoint(with body: SKPhysicsBody, node: SKNode, scene: GameScene) {
let anchor = scene.convert(node.position, from: node.parent!)
let jointPin = SKPhysicsJointPin.joint(withBodyA: self.physicsBody!, bodyB: body, anchor: anchor)
scene.physicsWorld.add(jointPin)
}
}
| gpl-3.0 | 8613580df48ef57eed8d4006ccc94778 | 26.649718 | 122 | 0.689211 | 3.264843 | false | false | false | false |
Marketcloud/marketcloud-swift-application | mCloudSampleApp/ProductsViewController.swift | 1 | 4516 | import UIKit
import Marketcloud
//Controller for the products list view
class ProductsViewController: UIViewController, UITextFieldDelegate,UITableViewDelegate, UITableViewDataSource {
var marketcloud:Marketcloud? = MarketcloudMain.getMcloud()
@IBOutlet weak var tblProducts: UITableView!
//logs out, destroyes the cart and returns to the login view
@IBAction func logoutPressed(_ sender: UIBarButtonItem) {
let res = marketcloud!.logOut()
if(res["Ok"] != nil ) {
print(res)
print("Logout button Pressed")
Cart.products.removeAll()
Cart.lastCart = nil
Cart.cartId = -1
print("CartId is now \(Cart.cartId)")
}
else {
print(res)
}
navigationController?.popToRootViewController(animated: true)
}
override func viewDidLoad() {
self.automaticallyAdjustsScrollViewInsets = false
self.navigationItem.setHidesBackButton(true, animated: false)
self.title = "Products List"
print("printing cart")
print(marketcloud!.getCart())
}
//-------------TABLEVIEW
override func viewWillAppear(_ animated: Bool) {
tblProducts.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Product.getProductsCount()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if (Product.products[indexPath.row].show == false) {
return 0
} else {
return 110
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//sincronizza le celle in base alla posizione nell'array tasks
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CellProductsController
cell.titleCell.text = Product.products[indexPath.row].name!
//cell.descrCell.text = Products.products[indexPath.row].description
cell.priceCell.text = "Price: \(String(Product.products[indexPath.row].price!))€";
DispatchQueue.main.async(execute: {
// check if the cell is still on screen, and only if it is, update the image.
let updateCell = tableView.cellForRow(at: indexPath)
if updateCell != nil {
if(Product.products[indexPath.row].images!.count != 0) {
if(ImageCache.isInCache(Product.products[indexPath.row].id!)) {
//print("Image is in Cache")
let image = ImageCache.get(Product.products[indexPath.row].id!)
cell.imgCell.image = nil;
cell.imgCell.image = image
}
else
{
//print("\n Image was not in cache ...\nSetting image from url \(Product.products[indexPath.row].images![0]) with id \(Product.products[indexPath.row].id!)")
cell.imgCell.image = nil;
cell.imgCell.load_image(Product.products[indexPath.row].images![0],imageId: Product.products[indexPath.row].id!)
}
}
else {
//print("No image found for \(Product.products[indexPath.row].name!)")
cell.imgCell.image = nil;
cell.imgCell.image = UIImage(named: "logo")
}
cell.setNeedsLayout()
}
})
return cell
}
//---------------------
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return false
}
//for filtering purposes
func textFieldDidEndEditing(_ textField: UITextField) {
let filter = textField.text!
if (filter == "") {
Product.removeFilters()
} else {
Product.filter(filter)
print("Filtering \(filter)")
}
tblProducts.reloadData()
}
//---------------------
//-----------SEGUE
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if(segue.identifier == "detail"){
UserData.selectedProduct = Product.products[(tblProducts.indexPathForSelectedRow?.row)!]
//print("setted \(Product.products[tblProducts.indexPathForSelectedRow!.row])")
}
}
}
| apache-2.0 | 2176e2385beeb634cf98d03ea3969fff | 36.932773 | 177 | 0.574878 | 5.049217 | false | false | false | false |
ktatroe/MPA-Horatio | HoratioDemo/HoratioDemo/Classes/Persistence/InitializeObjectStoreOperation.swift | 2 | 1356 | //
// Copyright © 2016 Kevin Tatroe. All rights reserved.
// See LICENSE.txt for this sample’s licensing information
import CoreData
/**
A `GroupOperation` subclass that encompasses the various steps required to fully
initialize the local storage; this includes clearing the re-generatable data (if
necessary), initializing the Core Data stack, performing any emergency data updates
within the stack, and, if not yet primed, priming the local store by fetching
feeds as needed.
*/
class InitializeObjectStoreOperation: GroupOperation {
// MARK: Initialization
init() {
super.init(operations: [])
let resetOperation = ResetObjectStoreOperation()
let loadOperation = LoadObjectStoreOperation()
loadOperation.addDependency(resetOperation)
let upgradeOperation = UpgradeObjectStoreOperation()
upgradeOperation.addDependency(loadOperation)
let delayedOperation = BlockOperation {
self.produceOperation(PrimeObjectStoreOperation())
}
delayedOperation.addDependency(upgradeOperation)
for operation in [resetOperation, loadOperation, upgradeOperation, delayedOperation] {
addOperation(operation)
}
addCondition(MutuallyExclusive<InitializeObjectStoreOperation>())
name = "Initialize Object Store"
}
}
| mit | de0a90ea406ae0c58b326f46e38af34e | 30.465116 | 94 | 0.725795 | 5.203846 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/Events/Upcoming/WhenObservingUpcomingEvents_ThenLoadSucceeds.swift | 1 | 3336 | import EurofurenceModel
import XCTest
class WhenObservingUpcomingEvents_ThenLoadSucceeds: XCTestCase {
func testTheObserverIsProvidedWithTheUpcomingEvents() {
let syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement().element
let simulatedTime = randomEvent.startDateTime.addingTimeInterval(-1)
let context = EurofurenceSessionTestBuilder().with(simulatedTime).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
context.performSuccessfulSync(response: syncResponse)
EventAssertion(context: context, modelCharacteristics: syncResponse)
.assertCollection(observer.upcomingEvents, containsEventCharacterisedBy: randomEvent)
}
func testTheObserverIsNotProvidedWithEventsThatHaveBegan() {
let syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement().element
let simulatedTime = randomEvent.startDateTime.addingTimeInterval(-1)
let context = EurofurenceSessionTestBuilder().with(simulatedTime).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
context.performSuccessfulSync(response: syncResponse)
let expectedEvents = syncResponse.events.changed.filter { (event) -> Bool in
return event.startDateTime > simulatedTime
}
EventAssertion(context: context, modelCharacteristics: syncResponse)
.assertEvents(observer.upcomingEvents, characterisedBy: expectedEvents)
}
func testTheObserverIsNotProvidedWithEventsTooFarIntoTheFuture() {
let timeIntervalForUpcomingEventsSinceNow: TimeInterval = .random
let syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement().element
let simulatedTime = randomEvent.startDateTime.addingTimeInterval(-timeIntervalForUpcomingEventsSinceNow - 1)
let context = EurofurenceSessionTestBuilder().with(simulatedTime).with(timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
context.performSuccessfulSync(response: syncResponse)
XCTAssertFalse(observer.upcomingEvents.contains(where: { $0.identifier.rawValue == randomEvent.identifier }))
}
func testEventsThatHaveJustStartedAreNotConsideredUpcoming() {
let timeIntervalForUpcomingEventsSinceNow: TimeInterval = .random
let syncResponse = ModelCharacteristics.randomWithoutDeletions
let randomEvent = syncResponse.events.changed.randomElement().element
let simulatedTime = randomEvent.startDateTime
let context = EurofurenceSessionTestBuilder().with(simulatedTime).with(timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow).build()
let observer = CapturingEventsServiceObserver()
context.eventsService.add(observer)
context.performSuccessfulSync(response: syncResponse)
XCTAssertFalse(observer.upcomingEvents.contains(where: { $0.identifier.rawValue == randomEvent.identifier }))
}
}
| mit | 39dd68370893436c07971434a564691f | 52.806452 | 164 | 0.768285 | 6.330171 | false | true | false | false |
Coderian/SwiftedGPX | SwiftedGPX/Elements/Route.swift | 1 | 4681 | //
// Rte.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX Route
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:element name="rte" type="rteType" minOccurs="0" maxOccurs="unbounded">
/// <xsd:annotation>
/// <xsd:documentation>
/// A list of routes.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
public class Route : SPXMLElement, HasXMLElementValue {
public static var elementName: String = "rte"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch self.parent {
case let v as Gpx: v.value.rte.append(self)
default: break
}
}
}
}
public var value: RteType = RteType()
public required init(attributes:[String:String]){
super.init(attributes: attributes)
}
}
/// GPX RteType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:complexType name="rteType">
/// <xsd:annotation>
/// <xsd:documentation>
/// rte represents route - an ordered list of waypoints representing a series of turn points leading to a destination.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:sequence>
/// <xsd:element name="name" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// GPS name of route.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="cmt" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// GPS comment for route.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="desc" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Text description of route for user. Not sent to GPS.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="src" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Source of data. Included to give user some idea of reliability and accuracy of data.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="link" type="linkType" minOccurs="0" maxOccurs="unbounded">
/// <xsd:annotation>
/// <xsd:documentation>
/// Links to external information about the route.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="number" type="xsd:nonNegativeInteger" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// GPS route number.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// <xsd:element name="type" type="xsd:string" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// Type (classification) of route.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
///
/// <xsd:element name="extensions" type="extensionsType" minOccurs="0">
/// <xsd:annotation>
/// <xsd:documentation>
/// You can add extend GPX by adding your own elements from another schema here.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
///
/// <xsd:element name="rtept" type="wptType" minOccurs="0" maxOccurs="unbounded">
/// <xsd:annotation>
/// <xsd:documentation>
/// A list of route points.
/// </xsd:documentation>
/// </xsd:annotation>
/// </xsd:element>
/// </xsd:sequence>
/// </xsd:complexType>
public class RteType {
public var name:Name!
public var cmt:Comment!
public var desc:Description!
public var src:Source!
public var link:Link!
public var number:Number!
public var type:Type!
public var extensions:Extensions!
public var rtept:[RoutePoint] = [RoutePoint]()
} | mit | dba58b7c40a0bdae1fe2c84eb79ac3bd | 34.576923 | 128 | 0.532007 | 3.732042 | false | false | false | false |
socialbanks/ios-wallet | SocialWallet/APIManager.swift | 1 | 9790 | //
// APIManager.swift
// SocialWallet
//
// Created by Mauricio de Oliveira on 5/9/15.
// Copyright (c) 2015 SocialBanks. All rights reserved.
//
import Foundation
import Parse
//get_balances("1Ko36AjTKYh6EzToLU737Bs2pxCsGReApK")
class APIManager {
//MARK: - Singleton
class var sharedInstance : APIManager {
struct Static {
static let instance : APIManager = APIManager()
}
return Static.instance
}
//MARK: - Saves
func saveWallet(bitcoinAddress:String, socialBank:SocialBank, completion:() -> Void) {
let relation:PFRelation = PFUser.currentUser()!.relationForKey("wallet");
let newWallet:Wallet = Wallet(className: "Wallet")
newWallet.setObject(0, forKey: "balance")
newWallet.setObject(AppManager.sharedInstance.userLocalData!.getPublicKey(), forKey: "bitcoinAddress")
newWallet.setObject(AppManager.sharedInstance.userLocalData!.bt!.key.privateKey, forKey: "wif_remove")
newWallet.setObject(PFUser.currentUser()!, forKey: "user")
socialBank.fetchIfNeeded()
newWallet.setObject(socialBank, forKey: "socialBank")
newWallet.save()
relation.addObject(newWallet);
PFUser.currentUser()!.saveInBackgroundWithBlock { (success:Bool, error:NSError?) -> Void in
if(error != nil || !success) {
// an error has occured
}else{
completion()
}
}
}
func saveTransaction(receiverAddress:String, value:Int, receiverDescription:String, senderWallet:Wallet, senderDescription:String, completion: (error:NSError?) -> Void) {
let recQuery:PFQuery = PFQuery(className: "Wallet")
recQuery.whereKey("bitcoinAddress", equalTo: receiverAddress)
recQuery.findObjectsInBackgroundWithBlock { (results:[AnyObject]?, error: NSError?) -> Void in
if(error != nil) {
// There was an error
completion(error: error!)
return
}
if let recWallet:Wallet? = results?[0] as? Wallet {
let trans:Transaction = Transaction(className: "Transaction")
// TODO: A virgula maldita!
trans.setObject(value, forKey: "value")
trans.setObject(senderWallet, forKey: "senderWallet")
//trans.setObject(senderWallet.getBitcoinAddress(), forKey: "senderAddress")
trans.setObject(senderDescription, forKey: "senderDescription")
trans.setObject(recWallet!, forKey: "receiverWallet")
//trans.setObject(recWallet!.getBitcoinAddress(), forKey: "receiverAddress")
trans.setObject(receiverDescription, forKey: "receiverDescription")
var error:NSError?
trans.save(&error)
completion(error: error)
}else{
println("error - wallet not found...")
completion(error: nil)
}
}
}
func saveTransactionToUser(toUser:PFUser, value:Int, senderWallet:Wallet, senderDescription:String, completion: (error:NSError?) -> Void) {
let recQuery:PFQuery = PFQuery(className: "Wallet")
recQuery.whereKey("user", equalTo: toUser)
recQuery.whereKey("socialBank", equalTo: senderWallet.getSocialBank())
recQuery.findObjectsInBackgroundWithBlock { (results:[AnyObject]?, error: NSError?) -> Void in
if(error != nil) {
// There was an error
completion(error: error!)
return
}
if let recWallet:Wallet? = results?[0] as? Wallet {
let trans:Transaction = Transaction(className: "Transaction")
// TODO: A virgula maldita!
trans.setObject(value, forKey: "value")
trans.setObject(senderWallet, forKey: "senderWallet")
//trans.setObject(senderWallet.getBitcoinAddress(), forKey: "senderAddress")
trans.setObject(senderDescription, forKey: "senderDescription")
//trans.setObject(recWallet!, forKey: "receiverWallet")
trans.setObject(recWallet!.getBitcoinAddress(), forKey: "receiverAddress")
trans.setObject("Received from " + (PFUser.currentUser()!.objectForKey("email") as! String), forKey: "receiverDescription")
var error:NSError?
trans.save(&error)
completion(error: error)
}else{
println("error - wallet not found...")
let error:NSError = NSError(domain: "user doesn`t have a wallet with yours` socialbank", code: 404, userInfo: nil)
completion(error: error)
}
}
}
//MARK: - Queries
func getWalletsFromCurrentUser(completion: (results:[Wallet]) -> Void) {
//let query:PFQuery = PFQuery(className: "Wallet")
//let relation = PFUser.currentUser()!.relationForKey("wallet")
let query = PFQuery(className: "Wallet")
query.whereKey("bitcoinAddress", equalTo: AppManager.sharedInstance.userLocalData!.bt!.address)
query.whereKey("user", equalTo: PFUser.currentUser()!)
query.includeKey("socialBank")
if Network.hasConnectivity() {
query.findObjectsInBackgroundWithBlock({ (results: [AnyObject]?, error: NSError?) -> Void in
if (error != nil) {
// There was an error
} else {
completion(results: results as! [Wallet])
}
})
}
}
func getSocialBanksWithName(name:String, completion: (results:[SocialBank]) -> Void) {
let query:PFQuery = PFQuery(className: "SocialBank")
query.whereKey("name", containsString: name)
if Network.hasConnectivity() && !name.isEmpty {
query.findObjectsInBackgroundWithBlock({ (results: [AnyObject]?, error: NSError?) -> Void in
if (error != nil) {
// There was an error
} else {
//println(results)
completion(results: results as! [SocialBank])
}
})
}
}
func getWalletFromBitcoinAddres(bitcoinAddress:String, completion: (result:Wallet) -> Void) {
let query:PFQuery = PFQuery(className: "Wallet")
query.whereKey("bitcoinAddress", equalTo: bitcoinAddress)
query.whereKey("user", notEqualTo: PFUser.currentUser()!)
query.includeKey("user")
query.includeKey("socialBank")
if Network.hasConnectivity() {
query.findObjectsInBackgroundWithBlock({ (results: [AnyObject]?, error: NSError?) -> Void in
if (error != nil) {
// There was an error
} else {
if(results!.count > 0) {
completion(result: results![0] as! Wallet)
}
}
})
}
}
func getWalletsWithUserEmailAndSocialBank(email:String, socialBank:SocialBank, completion: (results:[Wallet]) -> Void) {
let userQuery = PFUser.query()!
userQuery.whereKey("email", containsString: email)
let walletQuery = PFQuery(className: "Wallet")
walletQuery.whereKey("user", notEqualTo: PFUser.currentUser()!)
walletQuery.whereKey("user", matchesQuery: userQuery)
walletQuery.whereKey("socialBank", equalTo: socialBank)
walletQuery.includeKey("user")
if Network.hasConnectivity() && !email.isEmpty {
walletQuery.findObjectsInBackgroundWithBlock({ (results: [AnyObject]?, error: NSError?) -> Void in
if (error != nil) {
// There was an error
} else {
//println(results)
completion(results: results as! [Wallet])
}
})
}
}
func getTransactionsFromWallet(wallet:Wallet, completion: (results:[Transaction]) -> Void) {
//let query:PFQuery = PFQuery(className: "Wallet")
let querySender:PFQuery = PFQuery(className: "Transaction")
querySender.whereKey("senderWallet", equalTo: wallet)
let queryReceiver:PFQuery = PFQuery(className: "Transaction")
queryReceiver.whereKey("receiverWallet", equalTo: wallet)
let superQuery = PFQuery.orQueryWithSubqueries(NSArray(objects: queryReceiver, querySender) as [AnyObject])
superQuery.includeKey("senderWallet")
superQuery.includeKey("receiverWallet")
superQuery.orderByDescending("createdAt")
if Network.hasConnectivity() {
superQuery.findObjectsInBackgroundWithBlock({ (results: [AnyObject]?, error: NSError?) -> Void in
if (error != nil) {
// There was an error
} else {
//println(results)
completion(results: results as! [Transaction])
}
})
}
}
// MARK: - Cloud functions
func getBalances(completion: (results:AnyObject?, error:NSError?) -> Void) {
PFCloud.callFunctionInBackground("get_balances", withParameters: ["address":["1Ko36AjTKYh6EzToLU737Bs2pxCsGReApK"]]) { (results, error) -> Void in
if((error) != nil) {
println("error on getBalances - ", error!.description)
}else{
completion(results: results, error: error)
}
}
}
} | mit | fd9fd889fb8602b5f1a9a7c515edf59e | 41.569565 | 174 | 0.5762 | 4.954453 | false | false | false | false |
Palleas/Rewatch | RewatchPlayground.playground/Pages/Arrow animation.xcplaygroundpage/Sources/Utils.swift | 2 | 664 | import UIKit
public struct RewatchColorScheme {
public static let secondaryColor = UIColor.whiteColor()
public static let mainColor = UIColor(red: 247/255, green: 78/255, blue: 64/255, alpha: 1)
}
public func createArrowLayer() -> CAShapeLayer {
let arrowPath = UIBezierPath()
arrowPath.moveToPoint(CGPoint(x: 0, y: 0))
arrowPath.addLineToPoint(CGPoint(x: 30, y: 0))
arrowPath.addLineToPoint(CGPoint(x: 15, y: 15))
arrowPath.addLineToPoint(CGPoint(x: 0, y: 0))
let arrowLayer = CAShapeLayer()
arrowLayer.path = arrowPath.CGPath
arrowLayer.fillColor = RewatchColorScheme.mainColor.CGColor
return arrowLayer
} | mit | 5880fc9eac7b4526e32287f9877afb7b | 32.25 | 95 | 0.712349 | 4.04878 | false | false | false | false |
gpichot/JSONJoy-Swift | JSONJoy.swift | 3 | 6023 | //////////////////////////////////////////////////////////////////////////////////////////////////
//
// JSONJoy.swift
//
// Created by Dalton Cherry on 9/17/14.
// Copyright (c) 2014 Vluxe. All rights reserved.
//
//////////////////////////////////////////////////////////////////////////////////////////////////
import Foundation
public class JSONDecoder {
var value: AnyObject?
///print the description of the JSONDecoder
public var description: String {
return self.print()
}
///convert the value to a String
public var string: String? {
return value as? String
}
///convert the value to an Int
public var integer: Int? {
return value as? Int
}
///convert the value to an UInt
public var unsigned: UInt? {
return value as? UInt
}
///convert the value to a Double
public var double: Double? {
return value as? Double
}
///convert the value to a float
public var float: Float? {
return value as? Float
}
///convert the value to an NSNumber
public var number: NSNumber? {
return value as? NSNumber
}
///treat the value as a bool
public var bool: Bool {
if let str = self.string {
let lower = str.lowercaseString
if lower == "true" || lower.toInt() > 0 {
return true
}
} else if let num = self.integer {
return num > 0
} else if let num = self.double {
return num > 0.99
} else if let num = self.float {
return num > 0.99
}
return false
}
//get the value if it is an error
public var error: NSError? {
return value as? NSError
}
//get the value if it is a dictionary
public var dictionary: Dictionary<String,JSONDecoder>? {
return value as? Dictionary<String,JSONDecoder>
}
//get the value if it is an array
public var array: Array<JSONDecoder>? {
return value as? Array<JSONDecoder>
}
//pull the raw values out of an array
public func getArray<T>(inout collect: Array<T>?) {
if let array = value as? Array<JSONDecoder> {
if collect == nil {
collect = Array<T>()
}
for decoder in array {
if let obj = decoder.value as? T {
collect?.append(obj)
}
}
}
}
///pull the raw values out of a dictionary.
public func getDictionary<T>(inout collect: Dictionary<String,T>?) {
if let dictionary = value as? Dictionary<String,JSONDecoder> {
if collect == nil {
collect = Dictionary<String,T>()
}
for (key,decoder) in dictionary {
if let obj = decoder.value as? T {
collect?[key] = obj
}
}
}
}
///the init that converts everything to something nice
public init(_ raw: AnyObject) {
var rawObject: AnyObject = raw
if let data = rawObject as? NSData {
var error: NSError?
var response: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: &error)
if error != nil || response == nil {
value = error
return
}
rawObject = response!
}
if let array = rawObject as? NSArray {
var collect = [JSONDecoder]()
for val: AnyObject in array {
collect.append(JSONDecoder(val))
}
value = collect
} else if let dict = rawObject as? NSDictionary {
var collect = Dictionary<String,JSONDecoder>()
for (key,val: AnyObject) in dict {
collect[key as! String] = JSONDecoder(val)
}
value = collect
} else {
value = rawObject
}
}
///Array access support
public subscript(index: Int) -> JSONDecoder {
get {
if let array = self.value as? NSArray {
if array.count > index {
return array[index] as! JSONDecoder
}
}
return JSONDecoder(createError("index: \(index) is greater than array or this is not an Array type."))
}
}
///Dictionary access support
public subscript(key: String) -> JSONDecoder {
get {
if let dict = self.value as? NSDictionary {
if let value: AnyObject = dict[key] {
return value as! JSONDecoder
}
}
return JSONDecoder(createError("key: \(key) does not exist or this is not a Dictionary type"))
}
}
///private method to create an error
func createError(text: String) -> NSError {
return NSError(domain: "JSONJoy", code: 1002, userInfo: [NSLocalizedDescriptionKey: text]);
}
///print the decoder in a JSON format. Helpful for debugging.
public func print() -> String {
if let arr = self.array {
var str = "["
for decoder in arr {
str += decoder.print() + ","
}
str.removeAtIndex(advance(str.endIndex, -1))
return str + "]"
} else if let dict = self.dictionary {
var str = "{"
for (key, decoder) in dict {
str += "\"\(key)\": \(decoder.print()),"
}
str.removeAtIndex(advance(str.endIndex, -1))
return str + "}"
}
if value != nil {
if let str = self.string {
return "\"\(value!)\""
} else if let null = value as? NSNull {
return "null"
}
return "\(value!)"
}
return ""
}
}
///Implement this protocol on all objects you want to use JSONJoy with
public protocol JSONJoy {
init(_ decoder: JSONDecoder)
}
| apache-2.0 | d260b49a764adce2edbd0b4582fd0a8e | 31.733696 | 131 | 0.507222 | 4.90872 | false | false | false | false |
SwiftKit/Torch | Generator/Source/VersionCommand.swift | 1 | 926 | //
// VersionCommand.swift
// TorchGenerator
//
// Created by Filip Dolnik on 21.07.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import Commandant
import Result
public struct VersionCommand: CommandType {
static let appVersion = NSBundle.allFrameworks().filter {
$0.bundleIdentifier == "org.brightify.TorchGeneratorFramework"
}.first?.objectForInfoDictionaryKey("CFBundleShortVersionString") as? String ?? ""
public let verb = "version"
public let function = "Prints the version of this generator."
public func run(options: Options) -> Result<Void, TorchGeneratorError> {
print(VersionCommand.appVersion)
return .Success()
}
public struct Options: OptionsType {
public static func evaluate(m: CommandMode) -> Result<Options, CommandantError<TorchGeneratorError>> {
return .Success(Options())
}
}
} | mit | 78ccde611dd32f2028ffaea02312bd7c | 28.870968 | 110 | 0.677838 | 4.74359 | false | false | false | false |
igormatyushkin014/Solid | Solid/Queries/Boolean/Base/SDBooleanQuery.swift | 1 | 1602 | //
// SDBooleanQuery.swift
// Solid
//
// Created by Igor Matyushkin on 09.11.15.
// Copyright © 2015 Igor Matyushkin. All rights reserved.
//
import UIKit
public class SDBooleanQuery: SDQuery {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
// MARK: Public methods
public func perform(withArray array: [AnyObject]) -> Bool {
assertionFailure("This method should be overriden in subclass")
return false
}
public func endQuery() -> Bool {
// Check existance of previous query
guard previousQuery != nil else {
return false
}
// Check that previous query is not a boolean query
guard !(previousQuery is SDBooleanQuery) else {
return false
}
// Obtain result array of previous query
var resultArray: [AnyObject]? = nil
if previousQuery is SDArrayQuery {
let arrayQuery = previousQuery as! SDArrayQuery
resultArray = arrayQuery.endQuery()
}
else {
resultArray = []
}
// Obtain result
let result = perform(withArray: resultArray!)
// Return result
return result
}
// MARK: Private methods
// MARK: Protocol methods
}
| mit | 5ae552513200044df5e626827f2a8463 | 18.52439 | 71 | 0.517801 | 5.464164 | false | false | false | false |
tibo/SwiftRSS | Tests/RSSItem_Tests.swift | 1 | 2526 | //
// RSSItem_Tests.swift
// SwiftRSS_Example
//
// Created by Thibaut LE LEVIER on 13/10/2014.
// Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved.
//
import UIKit
import XCTest
class RSSItem_Tests: XCTestCase {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func test_setLink_withAValidURLString_shouldCreateAValidURL()
{
var item: RSSItem = RSSItem()
item.setLink("http://www.apple.com")
if let link = item.link?
{
XCTAssert(true, "link is valid")
}
else
{
XCTFail("link should be valid")
}
}
func test_archivingAndUnarchiving_withValidObject_shouldReturnValidObjectWithSameValues()
{
var item: RSSItem = RSSItem()
item.title = "Hello"
item.setLink("http://www.apple.com")
item.guid = "1234"
item.pubDate = NSDate()
item.itemDescription = "Big Description"
item.content = "Here is the content"
item.setCommentsLink("http://www.test.com")
item.setCommentRSSLink("http://www.whatever.com/")
item.commentsCount = 666
item.author = "John Doe"
item.categories = ["One","Two","Tree"]
let archive = documentsPath.stringByAppendingString("test.archive")
NSKeyedArchiver.archiveRootObject(item, toFile: archive)
var item2 = NSKeyedUnarchiver.unarchiveObjectWithFile(archive) as RSSItem
XCTAssert(item.title == item2.title, "")
XCTAssert(item.link == item2.link, "")
XCTAssert(item.guid == item2.guid, "")
XCTAssert(item.pubDate == item2.pubDate, "")
XCTAssert(item.itemDescription == item2.itemDescription, "")
XCTAssert(item.content == item2.content, "")
XCTAssert(item.commentsLink!.absoluteString == item2.commentsLink!.absoluteString, "")
XCTAssert(item.commentRSSLink!.absoluteString == item2.commentRSSLink!.absoluteString, "")
XCTAssert(item.commentsCount == item2.commentsCount, "")
XCTAssert(item.author == item2.author, "")
XCTAssert(item.categories[0] == item2.categories[0], "")
XCTAssert(item.categories[1] == item2.categories[1], "")
XCTAssert(item.categories[2] == item2.categories[2], "")
}
}
| mit | d6bd1c38e1b41c790d20bac9e91fb472 | 31.805195 | 115 | 0.615202 | 4.347676 | false | true | false | false |
iOS-mamu/SS | P/Potatso/Advance/RuleSetsSelectionViewController.swift | 1 | 2426 | //
// RuleSetsSelectionViewController.swift
// Potatso
//
// Created by LEI on 3/9/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import UIKit
import Eureka
import PotatsoLibrary
import PotatsoModel
class RuleSetsSelectionViewController: FormViewController {
var selectedRuleSets: [RuleSet]
var callback: (([RuleSet]) -> Void)?
var ruleSets: [RuleSet] = []
init(selectedRuleSets: [RuleSet], callback: (([RuleSet]) -> Void)?) {
self.selectedRuleSets = selectedRuleSets
self.callback = callback
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "Choose Rule Set".localized()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
generateForm()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
selectedRuleSets.removeAll()
let values = form.values()
for ruleSet in ruleSets {
if let checked = values[ruleSet.name] as? Bool, checked {
selectedRuleSets.append(ruleSet)
}
}
self.callback?(selectedRuleSets)
}
func generateForm() {
form.delegate = nil
form.removeAll()
ruleSets = defaultRealm.objects(RuleSet.self).sorted(byProperty: "createAt").map({ $0 })
form +++ Section("Rule Set".localized())
for ruleSet in ruleSets {
form[0]
<<< CheckRow(ruleSet.name) {
$0.title = ruleSet.name
$0.value = selectedRuleSets.contains(ruleSet)
}
}
form[0] <<< BaseButtonRow () {
$0.title = "Add Rule Set".localized()
}.cellUpdate({ (cell, row) in
cell.textLabel?.textColor = Color.Brand
}).onCellSelection({ [unowned self] (cell, row) -> () in
self.showRuleSetConfiguration(nil)
})
form.delegate = self
tableView?.reloadData()
}
func showRuleSetConfiguration(_ ruleSet: RuleSet?) {
let vc = RuleSetConfigurationViewController(ruleSet: ruleSet)
navigationController?.pushViewController(vc, animated: true)
}
}
| mit | 771789f3081484651159c13c824c6fff | 29.3125 | 96 | 0.599175 | 4.47417 | false | false | false | false |
frootloops/swift | test/SILGen/guaranteed_normal_args.swift | 1 | 3998 | // RUN: %target-swift-frontend -parse-as-library -module-name Swift -parse-stdlib -emit-silgen -enable-sil-ownership -enable-guaranteed-normal-arguments %s | %FileCheck %s
// This test checks specific codegen related to normal arguments being passed at
// +0. Eventually, it should be merged into normal SILGen tests.
/////////////////
// Fake Stdlib //
/////////////////
precedencegroup AssignmentPrecedence {
assignment: true
}
enum Optional<T> {
case none
case some(T)
}
class Klass {
init() {}
}
struct Buffer {
var k: Klass
init(inK: Klass) {
k = inK
}
}
typealias AnyObject = Builtin.AnyObject
protocol Protocol {
associatedtype AssocType
static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ())
}
///////////
// Tests //
///////////
class KlassWithBuffer {
var buffer: Buffer
// Make sure that the allocating init forwards into the initializing init at +1.
// CHECK-LABEL: sil hidden @_T0s15KlassWithBufferCABs0A0C3inK_tcfC : $@convention(method) (@owned Klass, @thick KlassWithBuffer.Type) -> @owned KlassWithBuffer {
// CHECK: bb0([[ARG:%.*]] : @owned $Klass,
// CHECK: [[INITIALIZING_INIT:%.*]] = function_ref @_T0s15KlassWithBufferCABs0A0C3inK_tcfc : $@convention(method) (@owned Klass, @owned KlassWithBuffer) -> @owned KlassWithBuffer
// CHECK: apply [[INITIALIZING_INIT]]([[ARG]],
// CHECK: } // end sil function '_T0s15KlassWithBufferCABs0A0C3inK_tcfC'
init(inK: Klass = Klass()) {
buffer = Buffer(inK: inK)
}
// This test makes sure that we:
//
// 1. Are able to propagate a +0 value value buffer.k into a +0 value and that
// we then copy that +0 value into a +1 value, before we begin the epilog and
// then return that value.
// CHECK-LABEL: sil hidden @_T0s15KlassWithBufferC03getC14AsNativeObjectBoyF : $@convention(method) (@guaranteed KlassWithBuffer) -> @owned Builtin.NativeObject {
// CHECK: bb0([[SELF:%.*]] : @guaranteed $KlassWithBuffer):
// CHECK: [[BUF_BOX:%.*]] = alloc_stack $Buffer
// CHECK: [[METHOD:%.*]] = class_method [[SELF]] : $KlassWithBuffer, #KlassWithBuffer.buffer!getter.1
// CHECK: [[BUF:%.*]] = apply [[METHOD]]([[SELF]])
// CHECK: store [[BUF]] to [init] [[BUF_BOX]]
// CHECK: [[GEP:%.*]] = struct_element_addr [[BUF_BOX]] : $*Buffer, #Buffer.k
// CHECK: [[BUF_KLASS:%.*]] = load [copy] [[GEP]]
// CHECK: destroy_addr [[BUF_BOX]]
// CHECK: [[BORROWED_BUF_KLASS:%.*]] = begin_borrow [[BUF_KLASS]]
// CHECK: [[CASTED_BORROWED_BUF_KLASS:%.*]] = unchecked_ref_cast [[BORROWED_BUF_KLASS]]
// CHECK: [[COPY_CASTED_BORROWED_BUF_KLASS:%.*]] = copy_value [[CASTED_BORROWED_BUF_KLASS]]
// CHECK: end_borrow [[BORROWED_BUF_KLASS]]
// CHECK: destroy_value [[BUF_KLASS]]
// CHECK: return [[COPY_CASTED_BORROWED_BUF_KLASS]]
// CHECK: } // end sil function '_T0s15KlassWithBufferC03getC14AsNativeObjectBoyF'
func getBufferAsNativeObject() -> Builtin.NativeObject {
return Builtin.unsafeCastToNativeObject(buffer.k)
}
}
struct StructContainingBridgeObject {
var rawValue: Builtin.BridgeObject
// CHECK-LABEL: sil hidden @_T0s28StructContainingBridgeObjectVAByXl8swiftObj_tcfC : $@convention(method) (@owned AnyObject, @thin StructContainingBridgeObject.Type) -> @owned StructContainingBridgeObject {
// CHECK: bb0([[ARG:%.*]] : @owned $AnyObject,
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[CASTED_ARG:%.*]] = unchecked_ref_cast [[BORROWED_ARG]] : $AnyObject to $Builtin.BridgeObject
// CHECK: [[COPY_CASTED_ARG:%.*]] = copy_value [[CASTED_ARG]]
// CHECK: assign [[COPY_CASTED_ARG]] to
// CHECK: } // end sil function '_T0s28StructContainingBridgeObjectVAByXl8swiftObj_tcfC'
init(swiftObj: AnyObject) {
rawValue = Builtin.reinterpretCast(swiftObj)
}
}
struct ReabstractionThunkTest : Protocol {
typealias AssocType = Builtin.Int32
static func useInput(_ input: Builtin.Int32, into processInput: (AssocType) -> ()) {
processInput(input)
}
}
| apache-2.0 | 66c3d8bad009aaebcea6de40e8999083 | 38.584158 | 208 | 0.670585 | 3.641166 | false | false | false | false |
leacode/LCYCoreDataHelper | LCYCoreDataHelperExample/LCYCoreDataHelperExample/CoreDataCollectionViewControllerExample.swift | 1 | 2548 |
//
// CoreDataCollectionViewControllerExample.swift
// LCYCoreDataHelperExample
//
// Created by LiChunyu on 16/1/25.
// Copyright © 2016年 leacode. All rights reserved.
//
import UIKit
import LCYCoreDataHelper
import CoreData
private let reuseIdentifier = "Cell"
class CoreDataCollectionViewControllerExample: LCYCoreDataCVC {
override func viewDidLoad() {
super.viewDidLoad()
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "User")
let sortDescriptor = NSSortDescriptor(key: "id", ascending: true)
let sortDescriptors = [sortDescriptor]
fetchRequest.sortDescriptors = sortDescriptors
self.frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: globalContext!, sectionNameKeyPath: nil, cacheName: "UserCache")
self.frc.delegate = self
do {
try self.performFetch()
} catch {
fatalError("Failed to initialize FetchedResultsController: \(error)")
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! UserCollectionViewCell
let user: User? = self.frc.object(at: indexPath as IndexPath) as? User
cell.usernameLabel.text = user?.username ?? ""
return cell
}
// MRK: - CRUD
@IBAction func addNewItem(_ sender: AnyObject) {
if (self.frc.fetchedObjects?.count)! > 0 {
let user = (self.frc.fetchedObjects?.last)! as! User
User.i = user.id + 1
}
User.insertCoreDataModel()
}
@IBAction func deleteLast(_ sender: AnyObject) {
if let object = frc.fetchedObjects?.last, let context = globalContext {
context.delete(object as! NSManagedObject)
do {
try coreDataHelper?.backgroundSaveContext()
} catch {
fatalError("Failure to save context: \(error)")
}
}
}
@IBAction func deleteAll(_ sender: AnyObject) {
do {
try coreDataHelper?.deleteAllExistingObjectOfEntity("User", ctx: globalContext!)
NSFetchedResultsController<NSFetchRequestResult>.deleteCache(withName: "UserCache")
try self.performFetch()
} catch {
}
}
}
| mit | 7486e175dad7685ea8722c71b456845d | 32.051948 | 160 | 0.635756 | 5.29106 | false | false | false | false |
ygweric/swift-extension | UILabel+Extension.swift | 1 | 944 | //
// UILabel+Extension.swift
// ZBCool
//
// Created by ericyang on 11/24/15.
// Copyright © 2015 i-chou. All rights reserved.
//
import UIKit
extension UILabel{
convenience init(
frame_:CGRect = CGRectZero,
text:String? = nil,
font:UIFont? = nil,
textColor:UIColor? = nil,
backgroundColor:UIColor = UIColor.clearColor(),
textAlignment:NSTextAlignment = .Left,
userInteractionEnabled:Bool = false
){
self.init(frame:frame_)
if !text.isNilOrEmpty{
self.text=text
}
if (textColor != nil){
self.textColor=textColor
}
self.backgroundColor=backgroundColor
if (font != nil){
self.font=font
}
self.textAlignment=textAlignment
self.userInteractionEnabled=userInteractionEnabled
}
}
| apache-2.0 | 25aab2835d1f698b4d2a5bb7124b12c4 | 22 | 62 | 0.545069 | 4.811224 | false | false | false | false |
evering7/iSpeak8 | Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaThumbnail.swift | 2 | 3721 | //
// MediaThumbnail.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Allows particular images to be used as representative images for the
/// media object. If multiple thumbnails are included, and time coding is not
/// at play, it is assumed that the images are in order of importance. It has
/// one required attribute and three optional attributes.
public class MediaThumbnail {
/// The element's attributes.
public class Attributes {
/// Specifies the url of the thumbnail. It is a required attribute.
public var url: String?
/// Specifies the height of the thumbnail. It is an optional attribute.
public var width: String?
/// Specifies the width of the thumbnail. It is an optional attribute.
public var height: String?
/// Specifies the time offset in relation to the media object. Typically this
/// is used when creating multiple keyframes within a single video. The format
/// for this attribute should be in the DSM-CC's Normal Play Time (NTP) as used in
/// RTSP [RFC 2326 3.6 Normal Play Time]. It is an optional attribute.
public var time: String?
}
/// The element's attributes.
public var attributes: Attributes?
/// The element's value.
public var value: String?
}
// MARK: - Initializers
extension MediaThumbnail {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = MediaThumbnail.Attributes(attributes: attributeDict)
}
}
extension MediaThumbnail.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.url = attributeDict["url"]
self.height = attributeDict["height"]
self.width = attributeDict["width"]
self.time = attributeDict["time"]
}
}
// MARK: - Equatable
extension MediaThumbnail: Equatable {
public static func ==(lhs: MediaThumbnail, rhs: MediaThumbnail) -> Bool {
return
lhs.value == rhs.value &&
lhs.attributes == rhs.attributes
}
}
extension MediaThumbnail.Attributes: Equatable {
public static func ==(lhs: MediaThumbnail.Attributes, rhs: MediaThumbnail.Attributes) -> Bool {
return
lhs.url == rhs.url &&
lhs.height == rhs.height &&
lhs.width == rhs.height &&
lhs.time == rhs.time
}
}
| mit | 7dc06fb80eb8a199d61d958aa0e52e52 | 31.640351 | 99 | 0.657888 | 4.710127 | false | false | false | false |
akuraru/PureViewIcon | PureViewIcon/Views/PVINone.swift | 1 | 1492 | //
// PVI.swift
//
// Created by akuraru on 2017/02/11.
//
import UIKit
import SnapKit
extension PVIView {
func makeNoneConstraints() {
base.snp.updateConstraints { (make) in
make.width.equalToSuperview()
make.height.equalToSuperview()
make.center.equalToSuperview()
}
base.transform = resetTransform()
before.setup(width: 2)
main.setup(width: 2)
after.setup(width: 2)
// before
before.top.alpha = 0
before.left.alpha = 0
before.right.alpha = 0
before.bottom.alpha = 0
before.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(0)
}
before.view.transform = resetTransform()
// main
main.top.alpha = 0
main.left.alpha = 0
main.right.alpha = 0
main.bottom.alpha = 0
main.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(0)
}
main.view.transform = resetTransform()
// after
after.top.alpha = 0
after.left.alpha = 0
after.right.alpha = 0
after.bottom.alpha = 0
after.view.snp.makeConstraints { (make) in
make.center.equalToSuperview()
make.size.equalTo(0)
}
after.view.transform = resetTransform()
}
}
| mit | 3929c1563a8d77e98dae8911846f7728 | 24.288136 | 51 | 0.536863 | 4.349854 | false | false | false | false |
liuxuan30/SwiftCharts | SwiftCharts/Layers/ChartStackedBarsLayer.swift | 1 | 6423 | //
// ChartStackedBarsLayer.swift
// Examples
//
// Created by ischuetz on 15/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public typealias ChartStackedBarItemModel = (quantity: CGFloat, bgColor: UIColor)
public class ChartStackedBarModel: ChartBarModel {
let items: [ChartStackedBarItemModel]
public init(constant: ChartAxisValue, start: ChartAxisValue, items: [ChartStackedBarItemModel]) {
self.items = items
let axisValue2Scalar = items.reduce(start.scalar) {sum, item in
sum + item.quantity
}
let axisValue2 = start.copy(axisValue2Scalar)
super.init(constant: constant, axisValue1: start, axisValue2: axisValue2)
}
lazy var totalQuantity: CGFloat = {
return self.items.reduce(0) {total, item in
total + item.quantity
}
}()
}
class ChartStackedBarsViewGenerator<T: ChartStackedBarModel>: ChartBarsViewGenerator<T> {
private typealias FrameBuilder = (barModel: ChartStackedBarModel, item: ChartStackedBarItemModel, currentTotalQuantity: CGFloat) -> (frame: ChartPointViewBarStackedFrame, length: CGFloat)
override init(horizontal: Bool, xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, chartInnerFrame: CGRect, barWidth barWidthMaybe: CGFloat?, barSpacing barSpacingMaybe: CGFloat?) {
super.init(horizontal: horizontal, xAxis: xAxis, yAxis: yAxis, chartInnerFrame: chartInnerFrame, barWidth: barWidthMaybe, barSpacing: barSpacingMaybe)
}
override func generateView(barModel: T, constantScreenLoc constantScreenLocMaybe: CGFloat? = nil, bgColor: UIColor? = nil, animDuration: Float) -> ChartPointViewBar {
let constantScreenLoc = constantScreenLocMaybe ?? self.constantScreenLoc(barModel)
let frameBuilder: FrameBuilder = {
switch self.direction {
case .LeftToRight:
return {barModel, item, currentTotalQuantity in
let p0 = self.xAxis.screenLocForScalar(currentTotalQuantity)
let p1 = self.xAxis.screenLocForScalar(currentTotalQuantity + item.quantity)
let length = p1 - p0
let barLeftScreenLoc = self.xAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar)
return (frame: ChartPointViewBarStackedFrame(rect:
CGRectMake(
p0 - barLeftScreenLoc,
0,
length,
self.barWidth), color: item.bgColor), length: length)
}
case .BottomToTop:
return {barModel, item, currentTotalQuantity in
let p0 = self.yAxis.screenLocForScalar(currentTotalQuantity)
let p1 = self.yAxis.screenLocForScalar(currentTotalQuantity + item.quantity)
let length = p1 - p0
let barTopScreenLoc = self.yAxis.screenLocForScalar(length > 0 ? barModel.axisValue1.scalar : barModel.axisValue2.scalar)
return (frame: ChartPointViewBarStackedFrame(rect:
CGRectMake(
0,
p0 - barTopScreenLoc,
self.barWidth,
length), color: item.bgColor), length: length)
}
}
}()
let stackFrames = barModel.items.reduce((currentTotalQuantity: CGFloat(0), currentTotalLength: CGFloat(0), frames: Array<ChartPointViewBarStackedFrame>())) {tuple, item in
let frameWithLength = frameBuilder(barModel: barModel, item: item, currentTotalQuantity: tuple.currentTotalQuantity)
return (currentTotalQuantity: tuple.currentTotalQuantity + item.quantity, currentTotalLength: tuple.currentTotalLength + frameWithLength.length, frames: tuple.frames + [frameWithLength.frame])
}
let viewPoints = self.viewPoints(barModel, constantScreenLoc: constantScreenLoc)
return ChartPointViewBarStacked(p1: viewPoints.p1, p2: viewPoints.p2, width: self.barWidth, stackFrames: stackFrames.frames, animDuration: animDuration)
}
}
public class ChartStackedBarsLayer: ChartCoordsSpaceLayer {
private let barModels: [ChartStackedBarModel]
private let horizontal: Bool
private let barWidth: CGFloat?
private let barSpacing: CGFloat?
private let animDuration: Float
public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat, animDuration: Float) {
self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: barWidth, barSpacing: nil, animDuration: animDuration)
}
public convenience init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barSpacing: CGFloat, animDuration: Float) {
self.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, barModels: barModels, horizontal: horizontal, barWidth: nil, barSpacing: barSpacing, animDuration: animDuration)
}
private init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, barModels: [ChartStackedBarModel], horizontal: Bool = false, barWidth: CGFloat? = nil, barSpacing: CGFloat?, animDuration: Float) {
self.barModels = barModels
self.horizontal = horizontal
self.barWidth = barWidth
self.barSpacing = barSpacing
self.animDuration = animDuration
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
public override func chartInitialized(#chart: Chart) {
let barsGenerator = ChartStackedBarsViewGenerator(horizontal: self.horizontal, xAxis: self.xAxis, yAxis: self.yAxis, chartInnerFrame: self.innerFrame, barWidth: self.barWidth, barSpacing: self.barSpacing)
for barModel in self.barModels {
chart.addSubview(barsGenerator.generateView(barModel, animDuration: self.animDuration))
}
}
}
| apache-2.0 | 561b2696991daa3d17f8e431cb8f6eeb | 48.790698 | 214 | 0.651098 | 5.508576 | false | false | false | false |
playgroundscon/Playgrounds | Playgrounds/ScheduleViewController.swift | 1 | 2318 | //
// FirstViewController.swift
// Playgrounds
//
// Created by Andyy Hope on 18/11/16.
// Copyright © 2016 Andyy Hope. All rights reserved.
//
import UIKit
fileprivate extension Selector {
static let daySegmentedControlValueChanged = #selector(ScheduleViewController.daySegmentedControlValueChanged(_:))
}
protocol ScheduleViewControllerDelegate: class {
func switchDataSource(for day: Schedule.Day)
func filterDataSource(for filter: Schedule.Filter)
func prepareSegue(for indexPath: IndexPath)
func title(forSection section: Int) -> String
}
final class ScheduleViewController: UIViewController {
// MARK: - Properties
weak var delegate: ScheduleViewControllerDelegate?
// MARK: - IBOUtlets
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var daySegmentedControl: SegmentedControl! { didSet {
daySegmentedControl.style()
daySegmentedControl.addTarget(self, action: .daySegmentedControlValueChanged, for: .valueChanged)
}
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.backgroundColor = .interface(.background)
tableView.separatorStyle = .none
}
// MARK: - Selector
@objc fileprivate func daySegmentedControlValueChanged(_ sender: UISegmentedControl) {
guard let day = Schedule.Day(rawValue: sender.selectedSegmentIndex) else {
assertionFailure("Out of bounds segment index")
return
}
delegate?.switchDataSource(for: day)
}
}
extension ScheduleViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return ScheduleSpeakerCell.defaultHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
delegate?.prepareSegue(for: indexPath)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 28)
let label = SectionLabel(frame: frame)
label.text = delegate?.title(forSection: section)
return label
}
}
| gpl-3.0 | cfb69c985ad11d6499cbb4fdfb09e2f4 | 29.486842 | 118 | 0.685801 | 5.148889 | false | false | false | false |
zhxnlai/DongerListKeyboard | DongerListKeyboard/DLKeyboard/DLEmoticonCollectionViewCell.swift | 1 | 904 | //
// DLEmoticonCollectionViewCell.swift
// DongerListKeyboard
//
// Created by Zhixuan Lai on 11/12/14.
// Copyright (c) 2014 Zhixuan Lai. All rights reserved.
//
import UIKit
class DLEmoticonCollectionViewCell: DLTextCollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
var backgroundView = UIView()
backgroundView.backgroundColor = UIColor.lightGrayColor()
self.selectedBackgroundView = backgroundView
// contentView.layer.borderColor = UIColor.darkGrayColor().CGColor;
// contentView.layer.borderWidth = 1;
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.selectedBackgroundView.frame = self.contentView.frame
}
}
| mit | f151039b1494d82b9174aca8a2ce17f0 | 24.111111 | 74 | 0.654867 | 4.834225 | false | false | false | false |
myafer/AFUIKit | AFUIKit/NSMutableAttributedString+AFExtension.swift | 1 | 2160 |
//
// NSMutableAttributedString+AFExtension.swift
// AFUIKitExample
//
// Created by 口贷网 on 16/8/17.
// Copyright © 2016年 Afer. All rights reserved.
//
import UIKit
@available(iOS 6.0, *)
public let AFFont = NSFontAttributeName
@available(iOS 6.0, *)
public let AFParagraphStyle = NSParagraphStyleAttributeName
@available(iOS 6.0, *)
public let AFFontColor = NSForegroundColorAttributeName
@available(iOS 6.0, *)
public let AFBgColor = NSBackgroundColorAttributeName
@available(iOS 6.0, *)
public let AFLigature = NSLigatureAttributeName
@available(iOS 6.0, *)
public let AFKern = NSKernAttributeName
@available(iOS 6.0, *)
public let AFStrikethroughStyle = NSStrikethroughStyleAttributeName
@available(iOS 6.0, *)
public let AFUnderlineStyle = NSUnderlineStyleAttributeName
@available(iOS 6.0, *)
public let AStrokeColor = NSStrokeColorAttributeName
@available(iOS 6.0, *)
public let AFStrokeWidth = NSStrokeWidthAttributeName
@available(iOS 6.0, *)
public let AFShadow = NSShadowAttributeName
@available(iOS 7.0, *)
public let AFTextEffect = NSTextEffectAttributeName
@available(iOS 7.0, *)
public let AFAttachment = NSAttachmentAttributeName
@available(iOS 7.0, *)
public let AFLink = NSLinkAttributeName
@available(iOS 7.0, *)
public let AFBaselineOffset = NSBaselineOffsetAttributeName
@available(iOS 7.0, *)
public let AFStrikethroughColor = NSStrikethroughColorAttributeName
@available(iOS 7.0, *)
public let AFObliqueness = NSObliquenessAttributeName
@available(iOS 7.0, *)
public let AFExpansion = NSExpansionAttributeName
@available(iOS 7.0, *)
public let AFWritingDirection = NSWritingDirectionAttributeName
@available(iOS 7.0, *)
public let AFVerticalGlyphForm = NSVerticalGlyphFormAttributeName
extension NSMutableAttributedString {
public func append_attr(_ string: String, _ attributes: [String : AnyObject]?) -> Self {
let attr = NSAttributedString.init(string: string, attributes: attributes)
append(attr)
return self
}
}
| mit | 237684dad1270fdad1730277a3c977f9 | 25.555556 | 92 | 0.715481 | 4.176699 | false | false | false | false |
jongwonwoo/elastic-motion | ElasticMotion/ElasticTransition.swift | 1 | 8381 | //
// ElasticTransition.swift
// ElasticMotion
//
// Created by jongwon woo on 2016. 3. 25..
// Copyright © 2016년 jongwonwoo. All rights reserved.
//
import Foundation
import UIKit
public class ElasticTransition : NSObject, ElasticMotionStateMachineDelegate {
let presentedViewController: UIViewController
let presentingViewWidth: Float
let stateMachine:ElasticMotionStateMachine
let threshold: Float
init(presentedViewController: UIViewController, presentingViewWidth: Float, direction: ElasticMotionDirection) {
self.presentedViewController = presentedViewController
self.presentingViewWidth = presentingViewWidth
self.threshold = presentingViewWidth / 2
self.stateMachine = ElasticMotionStateMachine(direction, threshold: threshold, vibrationSec: 0.5)
super.init()
self.stateMachine.delegate = self
}
func handlePanGesture(recognizer: UIPanGestureRecognizer) {
let currentPoint = recognizer.translationInView(presentedViewController.view)
switch recognizer.state {
case .Began, .Changed:
stateMachine.keepMoving(currentPoint)
default:
stateMachine.stopMoving()
}
}
func elasticMotionStateMachine(stateMachine: ElasticMotionStateMachine, didChangeState state: ElasticMotionState, deltaPoint: CGPoint) {
switch stateMachine.direction {
case .Right:
self.handleRightDirection(state, deltaPoint: deltaPoint)
case .Left:
self.handleLeftDirection(state, deltaPoint: deltaPoint)
case .Bottom:
self.handleBottomDirection(state, deltaPoint: deltaPoint)
case .Top:
self.handleTopDirection(state, deltaPoint: deltaPoint)
}
}
// TODO: make subclass
func handleRightDirection(state: ElasticMotionState, deltaPoint: CGPoint) {
let fullOpenedWidth = CGFloat(presentingViewWidth)
switch state {
case .MayOpen:
let newOriginX = presentedViewController.view.frame.origin.x + deltaPoint.x
if newOriginX >= 0 && newOriginX < CGFloat(threshold) {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x + deltaPoint.x, presentedViewController.view.center.y)
}
case .WillOpen:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 + CGFloat(threshold), presentedViewController.view.center.y)
case .Opened:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 + fullOpenedWidth, presentedViewController.view.center.y)
case .MayClose:
let newOriginX = presentedViewController.view.frame.origin.x + deltaPoint.x
if newOriginX >= 0 && newOriginX < fullOpenedWidth {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x + deltaPoint.x, presentedViewController.view.center.y)
}
case .WillClose:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 + CGFloat(threshold), presentedViewController.view.center.y)
case .Closed:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2, presentedViewController.view.center.y)
}
}
func handleLeftDirection(state: ElasticMotionState, deltaPoint: CGPoint) {
let fullOpenedWidth = CGFloat(presentingViewWidth)
switch state {
case .MayOpen:
let newOriginX = presentedViewController.view.frame.origin.x + deltaPoint.x
if newOriginX <= 0 && -(newOriginX) < CGFloat(threshold) {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x + deltaPoint.x, presentedViewController.view.center.y)
}
case .WillOpen:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 - CGFloat(threshold), presentedViewController.view.center.y)
case .Opened:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 - fullOpenedWidth, presentedViewController.view.center.y)
case .MayClose:
let newOriginX = presentedViewController.view.frame.origin.x + deltaPoint.x
if newOriginX <= 0 && -(newOriginX) < fullOpenedWidth {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x + deltaPoint.x, presentedViewController.view.center.y)
}
case .WillClose:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2 - CGFloat(threshold), presentedViewController.view.center.y)
case .Closed:
presentedViewController.view.center = CGPointMake(presentedViewController.view.frame.width / 2, presentedViewController.view.center.y)
}
}
func handleBottomDirection(state: ElasticMotionState, deltaPoint: CGPoint) {
let fullOpenedWidth = CGFloat(presentingViewWidth)
switch state {
case .MayOpen:
let newOriginY = presentedViewController.view.frame.origin.y + deltaPoint.y
if newOriginY >= 0 && newOriginY < CGFloat(threshold) {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.center.y + deltaPoint.y)
}
case .WillOpen:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 + CGFloat(threshold))
case .Opened:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 + fullOpenedWidth)
case .MayClose:
let newOriginY = presentedViewController.view.frame.origin.y + deltaPoint.y
if newOriginY >= 0 && newOriginY < fullOpenedWidth {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.center.y + deltaPoint.y)
}
case .WillClose:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 + CGFloat(threshold))
case .Closed:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2)
}
}
func handleTopDirection(state: ElasticMotionState, deltaPoint: CGPoint) {
let fullOpenedWidth = CGFloat(presentingViewWidth)
switch state {
case .MayOpen:
let newOriginY = presentedViewController.view.frame.origin.y + deltaPoint.y
if newOriginY <= 0 && -(newOriginY) < CGFloat(threshold) {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.center.y + deltaPoint.y)
}
case .WillOpen:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 - CGFloat(threshold))
case .Opened:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 - fullOpenedWidth)
case .MayClose:
let newOriginY = presentedViewController.view.frame.origin.y + deltaPoint.y
if newOriginY <= 0 && -(newOriginY) < fullOpenedWidth {
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.center.y + deltaPoint.y)
}
case .WillClose:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2 - CGFloat(threshold))
case .Closed:
presentedViewController.view.center = CGPointMake(presentedViewController.view.center.x, presentedViewController.view.frame.height / 2)
}
}
} | mit | 8951ccb9a022ae00f233b477227047e5 | 54.125 | 168 | 0.701122 | 5.130435 | false | false | false | false |
jacobwhite/firefox-ios | Shared/NotificationConstants.swift | 1 | 2964 | /* 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/. */
extension Notification.Name {
public static let DataLoginDidChange = Notification.Name("DataLoginDidChange")
// add a property to allow the observation of firefox accounts
public static let FirefoxAccountChanged = Notification.Name("FirefoxAccountChanged")
public static let FirefoxAccountProfileChanged = Notification.Name("FirefoxAccountProfileChanged")
public static let FirefoxAccountDeviceRegistrationUpdated = Notification.Name("FirefoxAccountDeviceRegistrationUpdated")
public static let PrivateDataClearedHistory = Notification.Name("PrivateDataClearedHistory")
// Fired when the user finishes navigating to a page and the location has changed
public static let OnLocationChange = Notification.Name("OnLocationChange")
public static let DidRestoreSession = Notification.Name("DidRestoreSession")
// MARK: Notification UserInfo Keys
public static let UserInfoKeyHasSyncableAccount = Notification.Name("UserInfoKeyHasSyncableAccount")
// Fired when the FxA account has been verified. This should only be fired by the FxALoginStateMachine.
public static let FirefoxAccountVerified = Notification.Name("FirefoxAccountVerified")
// Fired when the login synchronizer has finished applying remote changes
public static let DataRemoteLoginChangesWereApplied = Notification.Name("DataRemoteLoginChangesWereApplied")
// Fired when a the page metadata extraction script has completed and is being passed back to the native client
public static let OnPageMetadataFetched = Notification.Name("OnPageMetadataFetched")
public static let ProfileDidStartSyncing = Notification.Name("ProfileDidStartSyncing")
public static let ProfileDidFinishSyncing = Notification.Name("ProfileDidFinishSyncing")
public static let DatabaseWasRecreated = Notification.Name("DatabaseWasRecreated")
public static let PasscodeDidChange = Notification.Name("PasscodeDidChange")
public static let PasscodeDidCreate = Notification.Name("PasscodeDidCreate")
public static let PasscodeDidRemove = Notification.Name("PasscodeDidRemove")
public static let DynamicFontChanged = Notification.Name("DynamicFontChanged")
public static let UserInitiatedSyncManually = Notification.Name("UserInitiatedSyncManually")
public static let BookmarkBufferValidated = Notification.Name("BookmarkBufferValidated")
public static let FaviconDidLoad = Notification.Name("FaviconDidLoad")
public static let ReachabilityStatusChanged = Notification.Name("ReachabilityStatusChanged")
public static let ContentBlockerTabSetupRequired = Notification.Name("ContentBlockerTabSetupRequired")
public static let HomePanelPrefsChanged = Notification.Name("HomePanelPrefsChanged")
}
| mpl-2.0 | fdab65c6bb0a8b2e7b72486737901787 | 51 | 124 | 0.800607 | 5.75534 | false | false | false | false |
ZamzamInc/SwiftyPress | Sources/SwiftyPress/Repositories/Media/Services/MediaRealmCache.swift | 1 | 3100 | //
// MediaRealmCache.swift
// SwiftyPress
//
// Created by Basem Emara on 2018-10-20.
// Copyright © 2019 Zamzam Inc. All rights reserved.
//
import Foundation
import RealmSwift
import ZamzamCore
public struct MediaRealmCache: MediaCache {
private let log: LogRepository
public init(log: LogRepository) {
self.log = log
}
}
public extension MediaRealmCache {
func fetch(id: Int, completion: @escaping (Result<Media, SwiftyPressError>) -> Void) {
DispatchQueue.database.async {
let realm: Realm
do {
realm = try Realm()
} catch {
DispatchQueue.main.async { completion(.failure(.databaseFailure(error))) }
return
}
guard let object = realm.object(ofType: MediaRealmObject.self, forPrimaryKey: id) else {
DispatchQueue.main.async { completion(.failure(.nonExistent)) }
return
}
let item = Media(from: object)
DispatchQueue.main.async {
completion(.success(item))
}
}
}
}
public extension MediaRealmCache {
func fetch(ids: Set<Int>, completion: @escaping (Result<[Media], SwiftyPressError>) -> Void) {
DispatchQueue.database.async {
let realm: Realm
do {
realm = try Realm()
} catch {
DispatchQueue.main.async { completion(.failure(.databaseFailure(error))) }
return
}
let items: [Media] = realm.objects(MediaRealmObject.self, forPrimaryKeys: ids)
.map { Media(from: $0) }
DispatchQueue.main.async {
completion(.success(items))
}
}
}
}
public extension MediaRealmCache {
func createOrUpdate(_ request: Media, completion: @escaping (Result<Media, SwiftyPressError>) -> Void) {
DispatchQueue.database.async {
let realm: Realm
do {
realm = try Realm()
} catch {
DispatchQueue.main.async { completion(.failure(.databaseFailure(error))) }
return
}
do {
try realm.write {
realm.add(MediaRealmObject(from: request), update: .modified)
}
} catch {
DispatchQueue.main.async { completion(.failure(.databaseFailure(error))) }
return
}
// Get refreshed object to return
guard let object = realm.object(ofType: MediaRealmObject.self, forPrimaryKey: request.id) else {
DispatchQueue.main.async { completion(.failure(.nonExistent)) }
return
}
let item = Media(from: object)
DispatchQueue.main.async {
completion(.success(item))
}
}
}
}
| mit | 82e26ffaaf8916141108112229b75a59 | 28.235849 | 108 | 0.511455 | 5.173623 | false | false | false | false |
gongruike/RKRequest3 | RKRequest/Request.swift | 2 | 3729 | // The MIT License (MIT)
//
// Copyright (c) 2016 Ruike Gong
//
// 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 Alamofire
/*
Type is the data type from server, like JSON, XML, String, Data,
Value is the type that user-defined model, like "User model", "Feed list", "Node info"
*/
open class Request<Type, Value>: Requestable {
public typealias CompletionHandler = (Result<Value>) -> Void
open var url: Alamofire.URLConvertible
open var method: Alamofire.HTTPMethod = .get
open var parameters: Alamofire.Parameters = [:]
open var encoding: Alamofire.ParameterEncoding = URLEncoding.default
open var headers: Alamofire.HTTPHeaders = [:]
open var timeoutInterval: TimeInterval = 10;
open var aRequest: Alamofire.Request?
open var response: Alamofire.DataResponse<Type>?
open var requestQueue: RequestQueueType?
open var completionHandler: CompletionHandler?
public init(url: String, completionHandler: CompletionHandler?) {
self.url = url
self.completionHandler = completionHandler
}
open func prepare(in aRequestQueue: RequestQueueType) {
requestQueue = aRequestQueue
do {
let originalRequest = try URLRequest(url: url, method: method, headers: headers)
var encodedURLRequest = try encoding.encode(originalRequest, with: parameters)
encodedURLRequest.timeoutInterval = timeoutInterval
aRequest = aRequestQueue.sessionManager.request(encodedURLRequest);
} catch {
aRequest = aRequestQueue.sessionManager.request(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: headers
)
}
}
open func start() {
setResponseHandler()
aRequest?.resume()
requestQueue?.onRequestStarted(self)
}
open func cancel() {
aRequest?.cancel()
}
open func setResponseHandler() {
// Different Type
}
open func parse(_ dataResponse: DataResponse<Type>) -> Result<Value> {
return Result.failure(RKError.invalidRequestType)
}
open func deliver(_ dataResponse: DataResponse<Type>) {
//
self.response = dataResponse;
//
DispatchQueue.global(qos: .default).async {
let result = self.parse(dataResponse);
DispatchQueue.main.async {
self.completionHandler?(result)
}
self.requestQueue?.onRequestFinished(self)
}
}
}
| mit | 51be4b1420739678e2c11e58022b1276 | 32.294643 | 92 | 0.652186 | 5.129298 | false | false | false | false |
cotkjaer/Silverback | Silverback/UIKitLocalizedString.swift | 1 | 1066 | //
// UIKitLocalizedString.swift
// Silverback
//
// Created by Christian Otkjær on 15/01/16.
// Copyright © 2016 Christian Otkjær. All rights reserved.
//
import Foundation
// MARK: - Localization
public enum UIKitLocalizeableString : String
{
case Search = "Search"
case Done = "Done"
case Cancel = "Cancel"
case Delete = "Delete"
case Edit = "Edit"
var localizedString: String
{
return NSBundle(identifier: "com.apple.UIKit")?.localizedStringForKey(rawValue, value: nil, table: nil) ?? rawValue
}
}
/// localized System UIKit Strings, like "Search", "Cancel", "Done", "Delete"
public func UIKitLocalizedString(key: String) -> String
{
return NSBundle(identifier: "com.apple.UIKit")?.localizedStringForKey(key, value: nil, table: nil) ?? key
}
/// localized System UIKit Strings, like "Search", "Cancel", "Done", "Delete"
public func UIContactsLocalizedString(key: String) -> String
{
return NSBundle(identifier: "com.apple.ContactsUI")?.localizedStringForKey(key, value: nil, table: nil) ?? key
}
| mit | 72db42e6936462872cb1281076c28594 | 26.973684 | 123 | 0.691439 | 3.951673 | false | false | false | false |
jackwilsdon/GTFSKit | GTFSKit/Stop.swift | 1 | 2821 | //
// Stop.swift
// GTFSKit
//
import Foundation
import CoreLocation
public struct Stop: CSVParsable {
public let id: String // stop_id (Required)
public let code: String? // stop_code (Optional)
public let name: String // stop_name (Required)
public let desc: String? // stop_desc (Optional)
public let location: CLLocationCoordinate2D // stop_lat, stop_lon (Required)
public let zoneId: String? // zone_id (Optional)
public let url: String? // stop_url (Optional)
public let locationType: LocationType? // location_type (Optional)
public let parentStation: String? // parent_station (Optional)
public let stopTimezone: String? // stop_timezone (Optional)
public let wheelchairBoarding: Accessibility? // wheelchair_boarding (Optional)
public init(id: String, code: String?, name: String, desc: String?, location: CLLocationCoordinate2D, zoneId: String?, url: String?, locationType: LocationType?, parentStation: String?, stopTimezone: String?, wheelchairBoarding: Accessibility?) {
self.id = id
self.code = code
self.name = name
self.desc = desc
self.location = location
self.zoneId = zoneId
self.url = url
self.locationType = locationType
self.parentStation = parentStation
self.stopTimezone = stopTimezone
self.wheelchairBoarding = wheelchairBoarding
}
public static func parse(data: CSVData) -> Stop? {
if !data.containsColumns("stop_id", "stop_name", "stop_lat", "stop_lon") {
return nil
}
let id = data["stop_id"]!
let code = data["stop_code"]
let name = data["stop_name"]!
let desc = data["stop_desc"]
let location = CLLocationCoordinate2D(latitude: (data["stop_lat"]! as NSString).doubleValue, longitude: (data["stop_lon"]! as NSString).doubleValue)
let zoneId = data["zone_id"]
let url = data["stop_url"]
let locationType = data.get("location_type", parser: LocationType.fromString(LocationType.Stop))
let parentStation = data["parent_station"]
let stopTimezone = data["stop_timezone"]
let wheelchairBoarding: Accessibility? = data.get("wheelchair_boarding", parser: Accessibility.fromString(Accessibility.Unknown))
return Stop(id: id, code: code, name: name, desc: desc, location: location, zoneId: zoneId, url: url, locationType: locationType, parentStation: parentStation, stopTimezone: stopTimezone, wheelchairBoarding: wheelchairBoarding)
}
}
| gpl-3.0 | 028393975af8fad3f009e79cbd4a0382 | 46.813559 | 250 | 0.606877 | 4.44252 | false | false | false | false |
22377832/ccyswift | Data1/Data1/AppDelegate.swift | 1 | 5818 | //
// AppDelegate.swift
// Data1
//
// Created by sks on 17/2/24.
// Copyright © 2017年 chen. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let entityName = NSStringFromClass(Person.classForCoder())
func populateDatabase(){
for counter in 0..<1000{
let person = NSEntityDescription.insertNewObject(forEntityName: entityName, into: persistentContainer.viewContext) as! Person
person.age = Int64(arc4random_uniform(120))
person.name = "\(counter)"
}
saveContext()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
populateDatabase()
let batch = NSBatchUpdateRequest(entityName: entityName)
batch.propertiesToUpdate = ["age": 18]
batch.predicate = NSPredicate(format: "age < %@", 18 as NSNumber)
batch.resultType = .updatedObjectsCountResultType
do{
let relust = try persistentContainer.viewContext.execute(batch)
if let theResult = relust as? NSBatchUpdateResult {
if let numberOfAffectedPersons = theResult.result as? Int{
print("Number of people who were previously younger than " + "18 years old and whose age is now set to " + "18 is \(numberOfAffectedPersons)")
}
}
} catch{
print("Could not perfrom batch request. Error = \(error)")
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Data1")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 27a4b9140405620fd83d3e1db523972e | 46.276423 | 285 | 0.664488 | 5.740375 | false | false | false | false |
yogeshbh/SimpleLogger | SimpleLogger/Logger/YBLogger.swift | 1 | 3793 | //
// YBLogger.swift
// SimpleLogger
//
// Created by Yogesh Bhople on 10/07/17.
// Copyright © 2017 Yogesh Bhople. All rights reserved.
//
import Foundation
protocol YBLoggerConfiguration {
func allowToPrint() -> Bool
func allowToLogWrite() -> Bool
func addTimeStamp() -> Bool
func addFileName() -> Bool
func addFunctionName() -> Bool
func addLineNumber() -> Bool
}
extension YBLoggerConfiguration {
func addTimeStamp() -> Bool {return false}
func addFileName() -> Bool {return false}
func addFunctionName() -> Bool {return true}
func addLineNumber() -> Bool {return true}
}
public enum YBLogger : YBLoggerConfiguration {
case DEBUG,INFO,ERROR,EXCEPTION,WARNING
fileprivate func symbolString() -> String {
var messgeString = ""
switch self {
case .DEBUG:
messgeString = "\u{0001F539} "
case .INFO:
messgeString = "\u{0001F538} "
case .ERROR:
messgeString = "\u{0001F6AB} "
case .EXCEPTION:
messgeString = "\u{2757}\u{FE0F} "
case .WARNING:
messgeString = "\u{26A0}\u{FE0F} "
}
var logLevelString = "\(self)"
for _ in 0 ..< (10 - logLevelString.count) {
logLevelString.append(" ")
}
messgeString = messgeString + logLevelString + "➯ "
return messgeString
}
}
public func print(_ message: Any...,logLevel:YBLogger,_ callingFunctionName: String = #function,_ lineNumber: UInt = #line,_ fileName:String = #file) {
let messageString = message.map({"\($0)"}).joined(separator: " ")
var fullMessageString = logLevel.symbolString()
if logLevel.addTimeStamp() {
fullMessageString = fullMessageString + Date().formattedISO8601 + " ⇨ "
}
if logLevel.addFileName() {
let fileName = URL(fileURLWithPath: fileName).deletingPathExtension().lastPathComponent
fullMessageString = fullMessageString + fileName + " ⇨ "
}
if logLevel.addFunctionName() {
fullMessageString = fullMessageString + callingFunctionName
if logLevel.addLineNumber() {
fullMessageString = fullMessageString + " : \(lineNumber)" + " ⇨ "
} else {
fullMessageString = fullMessageString + " ⇨ "
}
}
fullMessageString = fullMessageString + messageString
if logLevel.allowToPrint() {
print(fullMessageString)
}
if logLevel.allowToLogWrite() {
var a = YBFileLogger.default
print(fullMessageString,to:&a)
}
}
extension Foundation.Date {
/* Reference : http://stackoverflow.com/questions/28016578/
//swift-how-to-create-a-date-time-stamp-and-format-as-iso-8601-rfc-3339-utc-tim
*/
struct Date {
static let formatterISO8601: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSX"
return formatter
}()
static let formatteryyyyMMdd: DateFormatter = {
let formatter = DateFormatter()
formatter.calendar = Calendar(identifier: Calendar.Identifier.iso8601)
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "yyyyMMdd"
return formatter
}()
}
var formattedISO8601: String { return Date.formatterISO8601.string(from: self) }
var currentDate: String { return Date.formatteryyyyMMdd.string(from: self) }
}
| apache-2.0 | c90c0fcf8daef722faa4db54813c73c3 | 33.072072 | 151 | 0.622686 | 4.183628 | false | false | false | false |
mckaskle/FlintKit | FlintKit/Sys/Sys.swift | 1 | 1794 | //
// MIT License
//
// Sys.swift
//
// Copyright (c) 2016 Devin McKaskle
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public struct Sys {
// MARK: - Enum
private enum SysError: Error {
case CouldNotDetermineMachineNameSize
case CouldNotDetermineMachineName
}
// MARK: - Public Methods
public static func platform() throws -> String {
var size = 0
guard sysctlbyname("hw.machine", nil, &size, nil, 0) == 0 else { throw SysError.CouldNotDetermineMachineNameSize }
var machine = [CChar](repeating: 0, count: size)
guard sysctlbyname("hw.machine", &machine, &size, nil, 0) == 0 else { throw SysError.CouldNotDetermineMachineName }
return String(cString: machine)
}
}
| mit | ccc6970846deb1863615df601582d28f | 34.88 | 119 | 0.722965 | 4.181818 | false | false | false | false |
Erudika/para-client-ios | Sources/ParaClient.swift | 1 | 58223 | // Copyright 2013-2021 Erudika. https://erudika.com
//
// 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.
//
// For issues and patches go to: https://github.com/erudika
import Foundation
import SwiftyJSON
import Alamofire
/**
The Swift REST client for communicating with a Para API server.
*/
open class ParaClient {
let DEFAULT_ENDPOINT: String = "https://paraio.com"
let DEFAULT_PATH: String = "/v1/"
let JWT_PATH: String = "/jwt_auth"
let SEPARATOR: String = ":"
var endpoint: String
var path: String
var tokenKey: String?
var tokenKeyExpires: UInt64?
var tokenKeyNextRefresh: UInt64?
var accessKey: String
var secretKey: String
fileprivate final let signer = Signer()
public required init (accessKey: String, secretKey: String?) {
self.accessKey = accessKey
self.secretKey = secretKey ?? ""
self.endpoint = DEFAULT_ENDPOINT
self.path = DEFAULT_PATH
self.tokenKey = loadPref("tokenKey")
let tke = loadPref("tokenKeyExpires")
let tknr = loadPref("tokenKeyNextRefresh")
self.tokenKeyExpires = tke != nil ? UInt64(tke!) : nil
self.tokenKeyNextRefresh = tknr != nil ? UInt64(tknr!) : nil
if (self.secretKey).isEmpty {
print("Secret key not provided. Make sure you call 'signIn()' first.")
}
}
// MARK: Public methods
open func setEndpoint(_ endpoint: String) {
self.endpoint = endpoint
}
/// Returns the endpoint URL
open func getEndpoint() -> String {
if self.endpoint.isEmpty {
return DEFAULT_ENDPOINT
} else {
return self.endpoint
}
}
/// Sets the API request path
open func setApiPath(_ path: String) {
self.path = path
}
/// Returns the API request path
open func getApiPath() -> String {
if (self.tokenKey ?? "").isEmpty {
return DEFAULT_PATH
} else {
if !self.path.hasSuffix("/") {
self.path += "/"
}
return self.path
}
}
/// Returns the version of Para server
open func getServerVersion(_ callback: @escaping (String?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokeGet("", rawResult: true, callback: { res in
var ver = res?.dictionaryObject ?? [:]
if ver.isEmpty || !ver.keys.contains("version") {
callback("unknown")
} else {
callback(ver["version"] as? String)
}
} as (JSON?) -> Void, error: error)
}
/// Sets the JWT access token.
open func setAccessToken(_ token: String) {
if !token.isEmpty {
var parts = token.components(separatedBy: ".")
do {
let decoded:JSON = try JSON(data: NSData(base64Encoded: parts[1],
options: NSData.Base64DecodingOptions(rawValue: 0))! as Data)
if decoded != JSON.null && decoded["exp"] != JSON.null {
self.tokenKeyExpires = decoded.dictionaryValue["exp"]?.uInt64Value
self.tokenKeyNextRefresh = decoded.dictionaryValue["refresh"]?.uInt64Value
} else {
self.tokenKeyExpires = nil
self.tokenKeyNextRefresh = nil
}
} catch {
print("Error \(error)")
}
}
self.tokenKey = token
}
/// Returns the JWT access token, or null if not signed in
open func getAccessToken() -> String? {
return self.tokenKey
}
// MARK: Private methods
/// Clears the JWT token from memory, if such exists.
fileprivate func clearAccessToken() {
self.tokenKey = nil
self.tokenKeyExpires = nil
self.tokenKeyNextRefresh = nil
self.clearPref("tokenKey")
self.clearPref("tokenKeyExpires")
self.clearPref("tokenKeyNextRefresh")
}
/// Saves JWT tokens to disk
fileprivate func saveAccessToken(_ jwtData: NSDictionary?) {
if jwtData != nil && jwtData!.count > 0 {
self.tokenKey = String(describing: jwtData!["access_token"]!)
self.tokenKeyExpires = jwtData!["expires"] as? UInt64
self.tokenKeyNextRefresh = jwtData!["refresh"] as? UInt64
self.savePref("tokenKey", value: self.tokenKey)
self.savePref("tokenKeyExpires", value: String(describing: self.tokenKeyExpires))
self.savePref("tokenKeyNextRefresh", value: String(describing: self.tokenKeyNextRefresh))
}
}
/// Clears the JWT token from memory, if such exists.
fileprivate func key(_ refresh: Bool) -> String {
if self.tokenKey != nil {
if refresh {
refreshToken({ _ in })
}
return "Bearer \(self.tokenKey ?? "")"
}
return self.secretKey
}
internal func getFullPath(_ resourcePath: String) -> String {
if !resourcePath.isEmpty && resourcePath.hasPrefix(JWT_PATH) {
return resourcePath
}
if resourcePath.hasPrefix("/") {
return getApiPath() + String(resourcePath[resourcePath.index(resourcePath.startIndex, offsetBy: 1)...])
} else {
return getApiPath() + resourcePath
}
}
fileprivate func currentTimeMillis() -> UInt64 {
return UInt64(Date().timeIntervalSince1970 * 1000)
}
open func invokeGet<T>(_ resourcePath: String, params: [String: AnyObject]? = [:],
rawResult: Bool? = true, callback: @escaping (T?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
signer.invokeSignedRequest(self.accessKey, secretKey: key(JWT_PATH != resourcePath), httpMethod: "GET",
endpointURL: getEndpoint(), reqPath: getFullPath(resourcePath),
params: params, rawResult: rawResult, callback: callback, error: error)
}
open func invokePost<T>(_ resourcePath: String, entity: JSON?, rawResult: Bool? = true,
callback: @escaping (T?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
signer.invokeSignedRequest(self.accessKey, secretKey: key(false), httpMethod: "POST",
endpointURL: getEndpoint(), reqPath: getFullPath(resourcePath),
body: entity, rawResult: rawResult, callback: callback, error: error)
}
open func invokePut<T>(_ resourcePath: String, entity: JSON?, rawResult: Bool? = true,
callback: @escaping (T?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
signer.invokeSignedRequest(self.accessKey, secretKey: key(false), httpMethod: "PUT",
endpointURL: getEndpoint(), reqPath: getFullPath(resourcePath),
body: entity, rawResult: rawResult, callback: callback, error: error)
}
open func invokePatch<T>(_ resourcePath: String, entity: JSON?, rawResult: Bool? = true,
callback: @escaping (T?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
signer.invokeSignedRequest(self.accessKey, secretKey: key(false), httpMethod: "PATCH",
endpointURL: getEndpoint(), reqPath: getFullPath(resourcePath),
body: entity, rawResult: rawResult, callback: callback, error: error)
}
open func invokeDelete<T>(_ resourcePath: String, params: [String: AnyObject]? = [:],
rawResult: Bool? = true, callback: @escaping (T?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
signer.invokeSignedRequest(self.accessKey, secretKey: key(false), httpMethod: "DELETE",
endpointURL: getEndpoint(), reqPath: getFullPath(resourcePath),
params: params, rawResult: rawResult, callback: callback, error: error)
}
open func pagerToParams(_ pager: Pager? = nil) -> NSMutableDictionary {
let map:NSMutableDictionary = [:]
if pager != nil {
map["page"] = String(pager!.page)
map["desc"] = String(pager!.desc)
map["limit"] = String(pager!.limit)
if let lastKey = pager?.lastKey {
map["lastKey"] = lastKey
}
if let sortby = pager?.sortby {
map["sort"] = sortby
}
if let select = pager?.select {
map["select"] = select
}
}
return map
}
open func getItemsFromList(_ result: [JSON]? = []) -> [ParaObject] {
if result != nil && !result!.isEmpty {
var objects = [ParaObject]()
for map in result! {
let p = ParaObject()
p.setFields(map.dictionaryObject)
objects.append(p)
}
return objects
}
return []
}
fileprivate func getTotalHits(_ result: [String: JSON]? = [:]) -> UInt {
if result != nil && !result!.isEmpty && result!.keys.contains("totalHits") {
return result!["totalHits"]?.uIntValue ?? 0
}
return 0
}
open func getItems(_ result: [String: JSON]? = [:], at: String, pager: Pager? = nil) -> [ParaObject] {
if result != nil && !result!.isEmpty && result!.keys.contains(at) {
if pager != nil && result!.keys.contains("totalHits") {
pager?.count = result!["totalHits"]?.uIntValue ?? 0
}
if pager != nil && result!.keys.contains("lastKey") {
pager?.lastKey = result!["lastKey"]?.stringValue
}
return getItemsFromList(result![at]?.arrayValue)
}
return []
}
fileprivate func getItems(_ result: [String: JSON]? = [:], pager: Pager? = nil) -> [ParaObject] {
return getItems(result, at: "items", pager: pager)
}
fileprivate func savePref(_ key: String, value: String?) {
let defaults = UserDefaults.standard
defaults.setValue(value, forKey: key)
defaults.synchronize()
}
fileprivate func loadPref(_ key: String) -> String? {
let defaults = UserDefaults.standard
return defaults.string(forKey: key)
}
fileprivate func clearPref(_ key: String) {
let defaults = UserDefaults.standard
defaults.removeObject(forKey: key)
}
/////////////////////////////////////////////
// MARK: PERSISTENCE
/////////////////////////////////////////////
//
/**
Persists an object to the data store. If the object's type and id are given,
then the request will be a PUT request and any existing object will be
overwritten.
- parameter obj: the domain object
- parameter callback: called with response object when the request is completed
*/
open func create(_ obj: ParaObject, callback: @escaping (ParaObject?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || (obj.type ).isEmpty {
invokePost(Signer.encodeURIComponent(obj.type), entity: JSON(obj.getFields()), rawResult: false, callback: callback, error: error)
} else {
invokePut(obj.getObjectURI(), entity: JSON(obj.getFields()), rawResult: false,
callback: callback, error: error)
}
}
/**
Retrieves an object from the data store.
- parameter type: the type of the object to read
- parameter id: the id of the object to read
- parameter callback: called with response object when the request is completed
*/
open func read(_ type: String? = nil, id: String, callback: @escaping (ParaObject?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if (type ?? "").isEmpty {
invokeGet("_id/\(Signer.encodeURIComponent(id))", rawResult: false, callback: callback, error: error)
} else {
invokeGet("\(Signer.encodeURIComponent(type!))/\(Signer.encodeURIComponent(id))", rawResult: false, callback: callback, error: error)
}
}
/**
Updates an object permanently. Supports partial updates.
- parameter obj: the object to update
- parameter callback: called with response object when the request is completed
*/
open func update(_ obj: ParaObject, callback: @escaping (ParaObject?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokePatch(obj.getObjectURI(), entity: JSON(obj.getFields()), rawResult: false, callback: callback, error: error)
}
/**
Deletes an object permanently.
- parameter obj: tobject to delete
- parameter callback: called with response object when the request is completed
*/
open func delete(_ obj: ParaObject, callback: ((Any?) -> Void)? = { _ in }, error: ((NSError) -> Void)? = { _ in }) {
invokeDelete(obj.getObjectURI(), rawResult: false, callback: callback!, error: error)
}
/**
Saves multiple objects to the data store.
- parameter objects: the list of objects to save
- parameter callback: called with response object when the request is completed
*/
open func createAll(_ objects: [ParaObject], callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if objects.isEmpty {
callback([])
return
}
var entity = [[String:Any]]()
for po in objects {
entity.append(po.getFields())
}
invokePost("_batch", entity: JSON(entity), callback: { res in
callback(self.getItemsFromList(res?.arrayValue))
} as (JSON?) -> Void, error: error)
}
/**
Retrieves multiple objects from the data store.
- parameter keys: a list of object ids
- parameter callback: called with response object when the request is completed
*/
open func readAll(_ keys: [String], callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if keys.isEmpty {
callback([])
return
}
invokeGet("_batch", params: ["ids": keys as AnyObject], callback: { res in
callback(self.getItemsFromList(res?.arrayValue))
} as (JSON?) -> Void, error: error)
}
/**
Updates multiple objects.
- parameter objects: the objects to update
- parameter callback: called with response object when the request is completed
*/
open func updateAll(_ objects: [ParaObject], callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if objects.isEmpty {
callback([])
return
}
var entity = [[String:Any]]()
for po in objects {
entity.append(po.getFields())
}
invokePatch("_batch", entity: JSON(entity), callback: { res in
callback(self.getItemsFromList(res?.arrayValue))
} as (JSON?) -> Void, error: error)
}
/**
Deletes multiple objects.
- parameter keys: the ids of the objects to delete
- parameter callback: called with response object when the request is completed
*/
open func deleteAll(_ keys: [String], callback: @escaping (([Any]?) -> Void) = { _ in },
error: ((NSError) -> Void)? = { _ in }) {
if keys.isEmpty {
callback([])
return
}
invokeDelete("_batch", params: ["ids": keys as AnyObject], callback: callback, error: error)
}
/**
Returns a list all objects found for the given type.
The result is paginated so only one page of items is returned, at a time.
- parameter type: the type of objects to search for
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func list(_ type: String, pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if type.isEmpty {
callback([])
return
}
invokeGet(Signer.encodeURIComponent(type), params: (pagerToParams(pager) as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res?.dictionaryValue, pager: pager))
} as (JSON?) -> Void, error: error)
}
/////////////////////////////////////////////
// MARK: SEARCH
/////////////////////////////////////////////
//
/**
Simple id search.
- parameter id: an id
- parameter callback: called with response object when the request is completed
*/
open func findById(_ id: String, callback: @escaping (ParaObject?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params:NSMutableDictionary = ["id": id]
find("id", params: params, callback: { res in
let list = self.getItems(res)
callback(list.isEmpty ? nil : list[0])
}, error: error)
}
/**
Simple multi id search.
- parameter ids: a list of ids to search for
- parameter callback: called with response object when the request is completed
*/
open func findByIds(_ ids: [String], callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params:NSMutableDictionary = ["ids": ids]
find("ids", params: params, callback: { res in
callback(self.getItems(res))
}, error: error)
}
/**
Search through all Address objects in a radius of X km from a given point.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter query: the query string
- parameter radius: the radius of the search circle
- parameter lat: latitude
- parameter lng: longitude
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findNearby(_ type: String, query: String, radius: Int, lat: Double, lng: Double,
pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["latlng"] = "\(lat),\(lng)"
params["radius"] = String(radius)
params["q"] = query
params["type"] = type
find("nearby", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for objects that have a property which value starts with a given prefix.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter field: the property name of an object
- parameter prefix: the prefix
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findPrefix(_ type: String, field: String, prefix: String,
pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["field"] = field
params["prefix"] = prefix
params["type"] = type
find("prefix", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Simple query string search. This is the basic search method.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter query: the query string
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findQuery(_ type: String, query: String, pager: Pager? = nil,
callback: @escaping ([ParaObject]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["q"] = query
params["type"] = type
find("", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches within a nested field. The objects of the given type must contain a nested field "nstd".
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter field: the name of the field to target (within a nested field "nstd")
- parameter query: the query string
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findNestedQuery(_ type: String, field: String, query: String, pager: Pager? = nil,
callback: @escaping ([ParaObject]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["q"] = query
params["field"] = field
params["type"] = type
find("nested", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for objects that have similar property values to a given text.
A "find like this" query.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter filterKey: exclude an object with this key from the results (optional)
- parameter fields: a list of property names
- parameter liketext: text to compare to
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findSimilar(_ type: String, filterKey: String, fields: [String]? = nil, liketext: String,
pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["fields"] = fields
params["filterid"] = filterKey
params["like"] = liketext
params["type"] = type
find("similar", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for objects tagged with one or more tags.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter tags: the list of tags
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findTagged(_ type: String, tags: [String] = [], pager: Pager? = nil,
callback: @escaping ([ParaObject]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["tags"] = tags
params["type"] = type
find("tagged", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for Tag objects. This method might be deprecated in the future.
- parameter keyword: the tag keyword to search for
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findTags(_ keyword: String? = nil, pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let kword = (keyword ?? "").isEmpty ? "*" : "\(keyword!)*"
findWildcard("tag", field: "tag", wildcard: kword, pager: pager, callback: callback, error: error)
}
/**
Searches for objects having a property value that is in list of possible values.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter field: the property name of an object
- parameter terms: a list of terms (property values)
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findTermInList(_ type: String, field: String, terms: [String],
pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["field"] = field
params["terms"] = terms
params["type"] = type
find("in", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for objects that have properties matching some given values. A terms query.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter terms: a list of terms (property values)
- parameter matchAll: match all terms. If true - AND search, if false - OR search
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findTerms(_ type: String, terms: [String: AnyObject], matchAll: Bool,
pager: Pager? = nil, callback: @escaping ([ParaObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if terms.isEmpty {
callback([])
return
}
let params = pagerToParams(pager)
var list = [String]()
params["matchall"] = String(matchAll)
for (key, value) in terms {
if value.description != nil {
list.append("\(key):\(value.description!)")
}
}
if !terms.isEmpty {
params["terms"] = list
}
params["type"] = type
find("terms", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Searches for objects that have a property with a value matching a wildcard query.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter field: the property name of an object
- parameter wildcard: wildcard query string. For example "cat*".
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findWildcard(_ type: String, field: String, wildcard: String, pager: Pager? = nil,
callback: @escaping ([ParaObject]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = pagerToParams(pager)
params["field"] = field
params["q"] = wildcard
params["type"] = type
find("wildcard", params: params, callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Counts indexed objects.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter callback: called with response object when the request is completed
*/
open func getCount(_ type: String, callback: @escaping (UInt) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params:NSMutableDictionary = ["type": type]
find("count", params: params, callback: { res in
callback(self.getTotalHits(res))
}, error: error)
}
/**
Counts indexed objects matching a set of terms/values.
- parameter type: the type of object to search for. See ParaObject.getType()
- parameter terms: a list of terms (property values)
- parameter callback: called with response object when the request is completed
*/
open func getCount(_ type: String, terms: [String: AnyObject], callback: @escaping (UInt) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if terms.isEmpty {
callback(0)
return
}
let params = NSMutableDictionary()
var list = [String]()
for (key, value) in terms {
if value.description != nil {
list.append("\(key):\(value.description!)")
}
}
if !terms.isEmpty {
params["terms"] = list
}
params["type"] = type
params["count"] = "true"
find("terms", params: params, callback: { res in
callback(self.getTotalHits(res))
}, error: error)
}
fileprivate func find(_ queryType: String, params: NSMutableDictionary,
callback: @escaping ([String: JSON]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if params.count > 0 {
let qType = queryType.isEmpty ? "/default" : "/" + queryType
if ((params["type"] ?? "") as! String).isEmpty {
invokeGet("search" + qType, params: (params as NSDictionary) as? [String: AnyObject], rawResult: true,
callback: { res in callback(res?.dictionaryValue) } as (JSON?) -> Void, error: error)
} else {
invokeGet("\(params["type"] ?? "")/search" + qType, params: (params as NSDictionary) as? [String: AnyObject],
rawResult: true, callback: { res in callback(res?.dictionaryValue) } as (JSON?) -> Void, error: error)
}
return
}
callback(["items": [:], "totalHits": 0])
}
/////////////////////////////////////////////
// MARK: LINKS
/////////////////////////////////////////////
//
/**
Count the total number of links between this object and another type of object.
- parameter obj: the object to execute this method on
- parameter type2: the other type of object
- parameter callback: called with response object when the request is completed
*/
open func countLinks(_ obj: ParaObject, type2: String, callback: @escaping (UInt) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback(0)
return
}
let params = ["count": "true"]
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params: params as [String : AnyObject]?, callback: { res in
callback(self.getTotalHits(res?.dictionaryValue))
} as (JSON?) -> Void, error: error)
}
/**
Returns all objects linked to the given one. Only applicable to many-to-many relationships.
- parameter obj: the object to execute this method on
- parameter type2: the other type of object
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func getLinkedObjects(_ obj: ParaObject, type2: String, pager: Pager? = nil,
callback: @escaping ([ParaObject]) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params:
(pagerToParams(pager) as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res?.dictionaryValue, pager: pager))
} as (JSON?) -> Void, error: error)
}
/**
Searches through all linked objects in many-to-many relationships.
- parameter obj: the object to execute this method on
- parameter type2: the other type of object
- parameter field: the name of the field to target (within a nested field "nstd")
- parameter query: a query string
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findLinkedObjects(_ obj: ParaObject, type2: String, field: String, query: String? = "*", pager: Pager? = nil,
callback: @escaping ([ParaObject]) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
let params = pagerToParams(pager)
params["field"] = field
params["q"] = query ?? "*"
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params:
(params as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res?.dictionaryValue, pager: pager))
} as (JSON?) -> Void, error: error)
}
/**
Checks if an object is linked to another.
- parameter obj: the object to execute this method on
- parameter type2: the other type
- parameter id2: the other id
- parameter callback: called with response object when the request is completed
*/
open func isLinked(_ obj: ParaObject, type2: String, id2: String, callback: @escaping (Bool) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty || id2.isEmpty {
callback(false)
return
}
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))/\(Signer.encodeURIComponent(id2))", callback: { res in
callback((res ?? "") == "true")
} as (String?) -> Void, error: error)
}
/**
Checks if a given object is linked to this one.
- parameter obj: the object to execute this method on
- parameter toObj: the other object
- parameter callback: called with response object when the request is completed
*/
open func isLinked(_ obj: ParaObject, toObj: ParaObject, callback: @escaping (Bool) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || toObj.id.isEmpty {
callback(false)
return
}
isLinked(obj, type2: toObj.type, id2: toObj.id, callback: callback, error: error)
}
/**
Links an object to this one in a many-to-many relationship.
Only a link is created. Objects are left untouched.
The type of the second object is automatically determined on read.
- parameter obj: the object to execute this method on
- parameter id2: link to the object with this id
- parameter callback: called with response object when the request is completed
*/
open func link(_ obj: ParaObject, id2: String, callback: @escaping (String?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || id2.isEmpty {
callback(nil)
return
}
invokePost("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(id2))", entity: nil, callback: callback, error: error)
}
/**
Unlinks an object from this one. Only a link is deleted. Objects are left untouched.
- parameter obj: the object to execute this method on
- parameter type2: the other type
- parameter id2: the other id
- parameter callback: called with response object when the request is completed
*/
open func unlink(_ obj: ParaObject, type2: String, id2: String, callback: @escaping (Any?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty || id2.isEmpty {
callback(nil)
return
}
invokeDelete("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))/\(Signer.encodeURIComponent(id2))", callback: callback, error: error)
}
/**
Unlinks all objects that are linked to this one.
- parameter obj: the object to execute this method on
- parameter callback: called with response object when the request is completed
*/
open func unlinkAll(_ obj: ParaObject, callback: @escaping (Any?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty {
callback(nil)
return
}
invokeDelete("\(obj.getObjectURI())/links", callback: callback, error: error)
}
/**
Count the total number of child objects for this object.
- parameter obj: the object to execute this method on
- parameter type2: the type of the other object
- parameter callback: called with response object when the request is completed
*/
open func countChildren(_ obj: ParaObject, type2: String, callback: @escaping (UInt) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback(0)
return
}
let params = ["count": "true", "childrenonly": "true"]
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params: params as [String : AnyObject]?, callback: { res in
callback(self.getTotalHits(res?.dictionaryValue))
} as (JSON?) -> Void, error: error)
}
/**
Returns all child objects linked to this object.
- parameter obj: the object to execute this method on
- parameter type2: the type of the other object
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func getChildren(_ obj: ParaObject, type2: String, pager: Pager? = nil,
callback: @escaping ([ParaObject]) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
let params = pagerToParams(pager)
params["childrenonly"] = "true"
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params:
(params as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Returns all child objects linked to this object.
- parameter obj: the object to execute this method on
- parameter type2: the type of the other object
- parameter field: the field name to use as filter
- parameter term: the field value to use as filter
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func getChildren(_ obj: ParaObject, type2: String, field: String, term: String,
pager: Pager? = nil, callback: @escaping ([ParaObject]) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
let params = pagerToParams(pager)
params["childrenonly"] = "true"
params["field"] = field
params["term"] = term
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params:
(params as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Search through all child objects. Only searches child objects directly
connected to this parent via the {@code parentid} field.
- parameter obj: the object to execute this method on
- parameter type2: the type of the other object
- parameter query: a query string
- parameter pager: a Pager
- parameter callback: called with response object when the request is completed
*/
open func findChildren(_ obj: ParaObject, type2: String, query: String? = "*", pager: Pager? = nil,
callback: @escaping ([ParaObject]) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
let params = pagerToParams(pager)
params["childrenonly"] = "true"
params["q"] = query ?? "*"
invokeGet("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params:
(params as NSDictionary) as? [String: AnyObject], callback: { res in
callback(self.getItems(res, pager: pager))
}, error: error)
}
/**
Deletes all child objects permanently.
- parameter obj: the object to execute this method on
- parameter type2: the type of the other object
- parameter callback: called with response object when the request is completed
*/
open func deleteChildren(_ obj: ParaObject, type2: String, callback: @escaping (Any?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || type2.isEmpty {
callback([])
return
}
invokeDelete("\(obj.getObjectURI())/links/\(Signer.encodeURIComponent(type2))", params: ["childrenonly": "true" as AnyObject],
callback: callback, error: error)
}
/////////////////////////////////////////////
// MARK: UTILS
/////////////////////////////////////////////
//
/**
Generates a new unique id.
- parameter callback: called with response object when the request is completed
*/
open func newId(_ callback: @escaping (String?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokeGet("utils/newid", callback: callback, error: error)
}
/**
Returns the current timestamp.
- parameter callback: called with response object when the request is completed
*/
open func getTimestamp(_ callback: @escaping (UInt64) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokeGet("utils/timestamp", callback: { res in
callback(UInt64(res ?? "0")!)
} as (String?) -> Void, error: error)
}
/**
Formats a date in a specific format.
- parameter format: the date format eg. "yyyy MMM dd"
- parameter locale: the locale, eg. "en_US"
- parameter callback: called with response object when the request is completed
*/
open func formatDate(_ format: String, locale: String, callback: @escaping (String?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = ["format": format, "locale": locale]
invokeGet("utils/formatdate", params: params as [String : AnyObject]?, callback: callback, error: error)
}
/**
Converts spaces to dashes.
- parameter str: a string with spaces
- parameter replaceWith: a string to replace spaces it with
- parameter callback: called with response object when the request is completed
*/
open func noSpaces(_ str: String, replaceWith: String, callback: @escaping (String?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = ["string": str, "replacement": replaceWith]
invokeGet("utils/nospaces", params: params as [String : AnyObject]?, callback: callback, error: error)
}
/**
Strips all symbols, punctuation, whitespace and control chars from a string.
- parameter str: a dirty string
- parameter callback: called with response object when the request is completed
*/
open func stripAndTrim(_ str: String, callback: @escaping (String?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = ["string": str]
invokeGet("utils/nosymbols", params: params as [String : AnyObject]?, callback: callback, error: error)
}
/**
Converts Markdown to HTML
- parameter markdownString: Markdown
- parameter callback: called with response object when the request is completed
*/
open func markdownToHtml(_ markdownString: String, callback: @escaping (String?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = ["md": markdownString]
invokeGet("utils/md2html", params: params as [String : AnyObject]?, callback: callback, error: error)
}
/**
Returns the number of minutes, hours, months elapsed for a time delta (milliseconds).
- parameter delta: the time delta between two events, in milliseconds
- parameter callback: called with response object when the request is completed
*/
open func approximately(_ delta: UInt, callback: @escaping (String?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = ["delta": delta]
invokeGet("utils/timeago", params: params as [String : AnyObject]?, callback: callback, error: error)
}
/////////////////////////////////////////////
// MARK: MISC
/////////////////////////////////////////////
//
/**
Generates a new set of access/secret keys. Old keys are discarded and invalid after this.
- parameter callback: called with response object when the request is completed
*/
open func newKeys(_ callback: @escaping ([String: AnyObject]) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokePost("_newkeys", entity: nil, callback: { res in
let keys = res?.dictionaryObject ?? [:]
if keys.keys.contains("secretKey") {
self.secretKey = keys["secretKey"]! as! String
}
callback(keys as [String : AnyObject])
} as (JSON?) -> Void, error: error)
}
/**
Returns all registered types for this App.
- parameter callback: called with response object when the request is completed
*/
open func types(_ callback: @escaping ([String: String]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokeGet("_types", callback: { res in
callback(res?.dictionaryObject as? [String: String])
} as (JSON?) -> Void, error: error)
}
/**
Returns the number of objects for each existing type in this App.
- parameter callback: called with response object when the request is completed
*/
open func typesCount(_ callback: @escaping ([String: String]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let params = ["count": "true"]
invokeGet("_types", params: params as [String : AnyObject]?, callback: { res in
callback(res?.dictionaryObject as? [String: String])
} as (JSON?) -> Void, error: error)
}
/**
Returns a User or an App that is currently authenticated.
- parameter accessToken: a valid JWT access token (optional)
- parameter callback: called with response object when the request is completed
*/
open func me(_ accessToken: String? = nil, _ callback: @escaping (ParaObject?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if (accessToken ?? "").isEmpty {
invokeGet("_me", rawResult: false, callback: callback, error: error)
} else {
var auth = accessToken;
if !accessToken!.hasPrefix("Bearer") {
auth = "Bearer \(accessToken ?? "")"
}
let headers:NSMutableDictionary = ["Authorization": auth ?? ""]
signer.invokeSignedRequest(self.accessKey, secretKey: key(true), httpMethod: "GET",
endpointURL: getEndpoint(), reqPath: getFullPath("_me"), headers: headers,
rawResult: false, callback: callback, error: error)
}
}
/**
Upvote an object and register the vote in DB. Returns true if vote was successful.
- parameter obj: the object to receive +1 votes
- parameter voterid: the userid of the voter
*/
open func voteUp(_ obj: ParaObject, voterid: String, callback: @escaping (Bool) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || voterid.isEmpty {
callback(false)
return
}
invokePatch(obj.getObjectURI(), entity: JSON(["_voteup": voterid]), callback: { res in
callback((res ?? "") == "true")
} as (String?) -> Void, error: error)
}
/**
Downvote an object and register the vote in DB. Returns true if vote was successful.
- parameter obj: the object to receive -1 votes
- parameter voterid: the userid of the voter
*/
open func voteDown(_ obj: ParaObject, voterid: String, callback: @escaping (Bool) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if obj.id.isEmpty || voterid.isEmpty {
callback(false)
return
}
invokePatch(obj.getObjectURI(), entity: JSON(["_votedown": voterid]), callback: { res in
callback((res ?? "") == "true")
} as (String?) -> Void, error: error)
}
/**
Rebuilds the entire search index.
*/
open func rebuildIndex(_ callback: @escaping ([String: AnyObject]?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokePost("_reindex", entity: nil, callback: { res in
callback(res?.dictionaryObject as [String: AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Rebuilds the entire search index.
- parameter destinationIndex: an existing index as destination
*/
open func rebuildIndex(_ destinationIndex: String, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
let params = ["destinationIndex": destinationIndex as AnyObject]
signer.invokeSignedRequest(self.accessKey, secretKey: key(true), httpMethod: "POST",
endpointURL: getEndpoint(), reqPath: getFullPath("_reindex"), params: params,
rawResult: true, callback: callback, error: error)
}
/////////////////////////////////////////////
// MARK: VALIDATION CONSTRAINTS
/////////////////////////////////////////////
//
/**
Returns the validation constraints map.
- parameter callback: called with response object when the request is completed
*/
open func validationConstraints(_ callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
invokeGet("_constraints", callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Returns the validation constraints map for a given type.
- parameter type: a type
- parameter callback: called with response object when the request is completed
*/
open func validationConstraints(_ type: String, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
invokeGet("_constraints/\(Signer.encodeURIComponent(type))", callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Add a new constraint for a given field.
- parameter type: a type
- parameter field: a field name
- parameter constraint: a Constraint
- parameter callback: called with response object when the request is completed
*/
open func addValidationConstraint(_ type: String, field: String, constraint: Constraint,
callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if type.isEmpty || field.isEmpty {
callback([:])
return
}
invokePut("_constraints/\(Signer.encodeURIComponent(type))/\(field)/\(constraint.name)", entity: JSON(constraint.payload), callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Removes a validation constraint for a given field.
- parameter type: a type
- parameter field: a field name
- parameter constraintName: the name of the constraint to remove
- parameter callback: called with response object when the request is completed
*/
open func removeValidationConstraint(_ type: String, field: String, constraintName: String,
callback: @escaping (Any?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if type.isEmpty || field.isEmpty || constraintName.isEmpty {
callback([:])
return
}
invokeDelete("_constraints/\(Signer.encodeURIComponent(type))/\(field)/\(constraintName)", callback: callback, error: error)
}
/////////////////////////////////////////////
// MARK: RESOURCE PERMISSIONS
/////////////////////////////////////////////
//
/**
Returns the permissions for all subjects and resources for current app.
- parameter callback: called with response object when the request is completed
*/
open func resourcePermissions(_ callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
invokeGet("_permissions", callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Returns only the permissions for a given subject (user) of the current app.
- parameter subjectid: the subject id (user id)
- parameter callback: called with response object when the request is completed
*/
open func resourcePermissions(_ subjectid: String, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
invokeGet("_permissions/\(Signer.encodeURIComponent(subjectid))", callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Grants a permission to a subject that allows them to call the specified HTTP methods on a given resource.
- parameter subjectid: the subject id (user id)
- parameter resourcePath: resource path or object type
- parameter permission: an array of allowed HTTP methods
- parameter allowGuestAccess: if true - all unauthenticated requests will go through, 'false' by default.
- parameter callback: called with response object when the request is completed
*/
open func grantResourcePermission(_ subjectid: String, resourcePath: String, permission: [String],
allowGuestAccess: Bool = false, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if subjectid.isEmpty || resourcePath.isEmpty || permission.isEmpty {
callback([:])
return
}
var permit = permission
if allowGuestAccess && subjectid == "*" {
permit.append("?")
}
let resPath = Signer.encodeURIComponent(resourcePath)
invokePut("_permissions/\(Signer.encodeURIComponent(subjectid))/\(resPath)", entity: JSON(permit), callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Revokes a permission for a subject, meaning they no longer will be able to access the given resource.
- parameter subjectid: the subject id (user id)
- parameter resourcePath: resource path or object type
- parameter callback: called with response object when the request is completed
*/
open func revokeResourcePermission(_ subjectid: String, resourcePath: String,
callback: @escaping (Any?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if subjectid.isEmpty || resourcePath.isEmpty {
callback([:])
return
}
let resPath = Signer.encodeURIComponent(resourcePath)
invokeDelete("_permissions/\(Signer.encodeURIComponent(subjectid))/\(resPath)", callback: { res in
callback(res?.dictionaryObject)
} as (JSON?) -> Void, error: error)
}
/**
Revokes all permission for a subject.
- parameter subjectid: the subject id (user id)
- parameter callback: called with response object when the request is completed
*/
open func revokeAllResourcePermissions(_ subjectid: String, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if subjectid.isEmpty {
callback([:])
return
}
invokeDelete("_permissions/\(Signer.encodeURIComponent(subjectid))", callback: { res in
callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
/**
Checks if a subject is allowed to call method X on resource Y.
- parameter subjectid: the subject id (user id)
- parameter resourcePath: resource path or object type
- parameter httpMethod: HTTP method name
- parameter callback: called with response object when the request is completed
*/
open func isAllowedTo(_ subjectid: String, resourcePath: String, httpMethod: String,
callback: @escaping (Bool) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if subjectid.isEmpty || resourcePath.isEmpty {
callback(false)
return
}
let resPath = Signer.encodeURIComponent(resourcePath)
invokeGet("_permissions/\(Signer.encodeURIComponent(subjectid))/\(resPath)/\(httpMethod)",
callback: { res in callback((res ?? "") == "true") } as (String?) -> Void,
error: { _ in callback(false) })
}
/////////////////////////////////////////////
// MARK: APP SETTINGS
/////////////////////////////////////////////
//
/**
Returns the map containing app-specific settings or the value of a specific app setting (property) for a given key.
- parameter key: a key
- parameter callback: called with response object when the request is completed
*/
open func appSettings(_ key: String? = nil, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if (key ?? "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty {
invokeGet("_settings", rawResult: true, callback: {
res in callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
} else {
invokeGet("_settings/\(key!)", rawResult: true, callback: {
res in callback(res?.dictionaryObject as [String : AnyObject]?)
} as (JSON?) -> Void, error: error)
}
}
/**
Adds or overwrites an app-specific setting.
- parameter key: a key
- parameter value: a value
- parameter callback: called with response object when the request is completed
*/
open func addAppSetting(_ key: String, value: AnyObject, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if !key.isEmpty {
invokePut("_settings/\(key)", entity: JSON(["value": value]), callback: callback, error: error)
}
}
/**
Overwrites all app-specific settings.
- parameter settings: a key-value map of properties
- parameter callback: called with response object when the request is completed
*/
open func setAppSettings(_ settings: [String: AnyObject], callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if !settings.isEmpty {
invokePut("_settings", entity: JSON(settings), callback: callback, error: error)
}
}
/**
Removes an app-specific setting.
- parameter key: a key
- parameter callback: called with response object when the request is completed
*/
open func removeAppSetting(_ key: String, callback: @escaping ([String: AnyObject]?) -> Void,
error: ((NSError) -> Void)? = { _ in }) {
if !key.isEmpty {
invokeDelete("_settings/\(key)", callback: callback, error: error)
}
}
/////////////////////////////////////////////
// MARK: ACCESS TOKENS
/////////////////////////////////////////////
//
/**
Takes an identity provider access token and fetches the user data from that provider.
A new User object is created if that user doesn't exist.
Access tokens are returned upon successful authentication using one of the SDKs from
Facebook, Google, Twitter, etc.
<b>Note:</b> Twitter uses OAuth 1 and gives you a token and a token secret.
<b>You must concatenate them like this: <code>{oauth_token}:{oauth_token_secret}</code> and
use that as the provider access token.</b>
- parameter provider: identity provider, e.g. 'facebook', 'google'...
- parameter providerToken: access token from a provider like Facebook, Google, Twitter
- parameter rememberJWT: if true the access token returned by Para will be stored locally and
available through getAccessToken(). True by default.
- parameter callback: called with response object when the request is completed
*/
open func signIn(_ provider: String, providerToken: String, rememberJWT: Bool? = true,
callback: @escaping (ParaObject?) -> Void, error: ((NSError) -> Void)? = { _ in }) {
if !provider.isEmpty && !providerToken.isEmpty {
var credentials = [String:String]()
credentials["appid"] = self.accessKey
credentials["provider"] = provider
credentials["token"] = providerToken
invokePost(JWT_PATH, entity: JSON(credentials), callback: { res in
let result = res?.dictionaryObject
if result != nil && (result?.keys.contains("user"))! && (result?.keys.contains("jwt"))! {
let jwtData:NSDictionary = result!["jwt"] as! NSDictionary
if rememberJWT! {
self.saveAccessToken(jwtData)
}
let user = ParaObject()
user.setFields(result!["user"] as! [String: AnyObject])
callback(user)
} else {
self.clearAccessToken()
callback(nil)
}
} as (JSON?) -> Void, error: { e in
self.clearAccessToken()
error!(e)
})
} else {
callback(nil)
}
}
/**
Clears the JWT access token but token is not revoked.
Tokens can be revoked globally per user with revokeAllTokens().
*/
open func signOut() {
clearAccessToken()
}
/**
Refreshes the JWT access token. This requires a valid existing token. Call link signIn() first.
- parameter callback: called with response object when the request is completed
*/
open func refreshToken(_ callback: @escaping (Bool) -> Void, error: ((NSError) -> Void)? = { _ in }) {
let now = currentTimeMillis()
let notExpired = self.tokenKeyExpires != nil && self.tokenKeyExpires! > now
let canRefresh = self.tokenKeyNextRefresh != nil &&
(self.tokenKeyNextRefresh! < now || self.tokenKeyNextRefresh! > self.tokenKeyExpires!)
// token present and NOT expired
if tokenKey != nil && notExpired && canRefresh {
invokeGet(JWT_PATH, callback: { res in
let result = res?.dictionaryObject
if result != nil && (result?.keys.contains("user"))! && (result?.keys.contains("jwt"))! {
let jwtData:NSDictionary = result!["jwt"] as! NSDictionary
self.saveAccessToken(jwtData)
callback(true)
} else {
callback(false)
}
} as (JSON?) -> Void, error: { e in
self.clearAccessToken()
error!(e)
})
} else {
callback(false)
}
}
/**
Revokes all user tokens for a given user id.
This would be equivalent to "logout everywhere".
<b>Note:</b> Generating a new API secret on the server will also invalidate all client tokens.
Requires a valid existing token.
- parameter callback: called with response object when the request is completed
*/
open func revokeAllTokens(_ callback: @escaping (Bool) -> Void, error: ((NSError) -> Void)? = { _ in }) {
invokeDelete(JWT_PATH, callback: { res in callback(res != nil) }, error: error)
}
}
| apache-2.0 | 68812bb78b13af19bd6e79c3408d639a | 38.393099 | 149 | 0.648644 | 3.750757 | false | false | false | false |
natestedman/LayoutModules | Example/LayoutModulesExample/AppDelegate.swift | 1 | 1444 | // LayoutModules
// Written in 2015 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
@objc lazy var window: UIWindow? = UIWindow(frame: UIScreen.mainScreen().bounds)
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
func controller(viewController: UIViewController, title: String) -> UIViewController
{
viewController.title = title
return UINavigationController(rootViewController: viewController)
}
let tabBarController = UITabBarController()
tabBarController.viewControllers = [
controller(ModulesViewController(), title: "Modules"),
controller(InitialFinalViewController(), title: "Insert & Delete")
]
window?.backgroundColor = UIColor.whiteColor()
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
}
| cc0-1.0 | d19fcb20d083dbed9c56a60ea98c190a | 37 | 125 | 0.711219 | 5.490494 | false | false | false | false |
shajrawi/swift | test/Constraints/keypath_dynamic_member_lookup.swift | 1 | 11406 | // RUN: %target-swift-frontend -emit-sil -verify %s | %FileCheck %s
struct Point {
let x: Int
var y: Int
}
struct Rectangle {
var topLeft, bottomRight: Point
}
@dynamicMemberLookup
struct Lens<T> {
var obj: T
init(_ obj: T) {
self.obj = obj
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> Lens<U> {
get { return Lens<U>(obj[keyPath: member]) }
set { obj[keyPath: member] = newValue.obj }
}
// Used to make sure that keypath and string based lookup are
// property disambiguated.
subscript(dynamicMember member: String) -> Lens<Int> {
return Lens<Int>(42)
}
}
var topLeft = Point(x: 0, y: 0)
var bottomRight = Point(x: 10, y: 10)
var lens = Lens(Rectangle(topLeft: topLeft,
bottomRight: bottomRight))
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig
// CHECK-NEXT: apply %45<Rectangle, Point>({{.*}})
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig
// CHECK-NEXT: apply %54<Point, Int>({{.*}})
_ = lens.topLeft.x
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig
// CHECK-NEXT: apply %69<Rectangle, Point>({{.*}})
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig
// CHECK-NEXT: apply %76<Point, Int>({{.*}})
_ = lens.topLeft.y
lens.topLeft = Lens(Point(x: 1, y: 2)) // Ok
lens.bottomRight.y = Lens(12) // Ok
@dynamicMemberLookup
class A<T> {
var value: T
init(_ v: T) {
self.value = v
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
get { return value[keyPath: member] }
}
}
// Let's make sure that keypath dynamic member lookup
// works with inheritance
class B<T> : A<T> {}
func bar(_ b: B<Point>) {
let _: Int = b.x
let _ = b.y
}
struct Point3D {
var x, y, z: Int
}
// Make sure that explicitly declared members take precedence
class C<T> : A<T> {
var x: Float = 42
}
func baz(_ c: C<Point3D>) {
// CHECK: ref_element_addr {{.*}} : $C<Point3D>, #C.x
let _ = c.x
// CHECK: [[Y:%.*]] = keypath $KeyPath<Point3D, Int>, (root $Point3D; stored_property #Point3D.z : $Int)
// CHECK: [[KEYPATH:%.*]] = function_ref @$s29keypath_dynamic_member_lookup1AC0B6Memberqd__s7KeyPathCyxqd__G_tcluig
// CHECK-NEXT: apply [[KEYPATH]]<Point3D, Int>({{.*}}, [[Y]], {{.*}})
let _ = c.z
}
@dynamicMemberLookup
struct SubscriptLens<T> {
var value: T
subscript(foo: String) -> Int {
get { return 42 }
}
subscript<U>(dynamicMember member: KeyPath<T, U>) -> U {
get { return value[keyPath: member] }
}
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return value[keyPath: member] }
set { value[keyPath: member] = newValue }
}
}
func keypath_with_subscripts(_ arr: SubscriptLens<[Int]>,
_ dict: inout SubscriptLens<[String: Int]>) {
// CHECK: keypath $WritableKeyPath<Array<Int>, ArraySlice<Int>>, (root $Array<Int>; settable_property $ArraySlice<Int>, id @$sSays10ArraySliceVyxGSnySiGcig : {{.*}})
_ = arr[0..<3]
// CHECK: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}})
for idx in 0..<arr.count {
// CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}})
let _ = arr[idx]
// CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}})
print(arr[idx])
}
// CHECK: function_ref @$s29keypath_dynamic_member_lookup13SubscriptLensVySiSScig
_ = arr["hello"]
// CHECK: function_ref @$s29keypath_dynamic_member_lookup13SubscriptLensVySiSScig
_ = dict["hello"]
if let index = dict.value.firstIndex(where: { $0.value == 42 }) {
// CHECK: keypath $KeyPath<Dictionary<String, Int>, (key: String, value: Int)>, (root $Dictionary<String, Int>; gettable_property $(key: String, value: Int), id @$sSDyx3key_q_5valuetSD5IndexVyxq__Gcig : {{.*}})
let _ = dict[index]
}
// CHECK: keypath $WritableKeyPath<Dictionary<String, Int>, Optional<Int>>, (root $Dictionary<String, Int>; settable_property $Optional<Int>, id @$sSDyq_Sgxcig : {{.*}})
dict["ultimate question"] = 42
}
struct DotStruct {
var x, y: Int
}
class DotClass {
var x, y: Int
init(x: Int, y: Int) {
self.x = x
self.y = y
}
}
@dynamicMemberLookup
struct DotLens<T> {
var value: T
subscript<U>(dynamicMember member: WritableKeyPath<T, U>) -> U {
get { return value[keyPath: member] }
set { value[keyPath: member] = newValue }
}
subscript<U>(dynamicMember member: ReferenceWritableKeyPath<T, U>) -> U {
get { return value[keyPath: member] }
set { value[keyPath: member] = newValue }
}
}
func dot_struct_test(_ lens: inout DotLens<DotStruct>) {
// CHECK: keypath $WritableKeyPath<DotStruct, Int>, (root $DotStruct; stored_property #DotStruct.x : $Int)
lens.x = 1
// CHECK: keypath $WritableKeyPath<DotStruct, Int>, (root $DotStruct; stored_property #DotStruct.y : $Int)
let _ = lens.y
}
func dot_class_test(_ lens: inout DotLens<DotClass>) {
// CHECK: keypath $ReferenceWritableKeyPath<DotClass, Int>, (root $DotClass; settable_property $Int, id #DotClass.x!getter.1 : (DotClass) -> () -> Int, getter @$s29keypath_dynamic_member_lookup8DotClassC1xSivpACTK : {{.*}})
lens.x = 1
// CHECK: keypath $ReferenceWritableKeyPath<DotClass, Int>, (root $DotClass; settable_property $Int, id #DotClass.y!getter.1 : (DotClass) -> () -> Int, getter @$s29keypath_dynamic_member_lookup8DotClassC1ySivpACTK : {{.*}})
let _ = lens.y
}
@dynamicMemberLookup
struct OverloadedLens<T> {
var value: T
subscript<U>(keyPath: KeyPath<T, U>) -> U {
get { return value[keyPath: keyPath] }
}
subscript<U>(dynamicMember keyPath: KeyPath<T, U>) -> U {
get { return value[keyPath: keyPath] }
}
}
// Make sure if there is a subscript which accepts key path,
// existing dynamic member overloads wouldn't interfere.
func test_direct_subscript_ref(_ lens: OverloadedLens<Point>) {
// CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensVyqd__s7KeyPathCyxqd__Gcluig
_ = lens[\.x]
// CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensVyqd__s7KeyPathCyxqd__Gcluig
_ = lens[\.y]
// CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensV0B6Memberqd__s7KeyPathCyxqd__G_tcluig
_ = lens.x
// CHECK: function_ref @$s29keypath_dynamic_member_lookup14OverloadedLensV0B6Memberqd__s7KeyPathCyxqd__G_tcluig
_ = lens.y
}
func test_keypath_dynamic_lookup_inside_keypath() {
// CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int)
// CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<Point>.x
// CHECK: keypath $WritableKeyPath<Rectangle, Point>, (root $Rectangle; stored_property #Rectangle.topLeft : $Point)
// CHECK-NEXT: keypath $WritableKeyPath<Point, Int>, (root $Point; stored_property #Point.y : $Int)
// CHECK-NEXT: keypath $WritableKeyPath<Lens<Rectangle>, Lens<Int>>, (root $Lens<Rectangle>; settable_property $Lens<Point>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<Rectangle>.topLeft.y
// CHECK: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Lens<Array<Int>>, Lens<Int>>, (root $Lens<Array<Int>>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<[Int]>.count
// CHECK: keypath $WritableKeyPath<Array<Int>, Int>, (root $Array<Int>; settable_property $Int, id @$sSayxSicig : {{.*}})
// CHECK-NEXT: keypath $WritableKeyPath<Lens<Array<Int>>, Lens<Int>>, (root $Lens<Array<Int>>; settable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<[Int]>.[0]
// CHECK: keypath $WritableKeyPath<Array<Array<Int>>, Array<Int>>, (root $Array<Array<Int>>; settable_property $Array<Int>, id @$sSayxSicig : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Array<Int>, Int>, (root $Array<Int>; gettable_property $Int, id @$sSa5countSivg : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Lens<Array<Array<Int>>>, Lens<Int>>, (root $Lens<Array<Array<Int>>>; settable_property $Lens<Array<Int>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<[[Int]]>.[0].count
}
func test_recursive_dynamic_lookup(_ lens: Lens<Lens<Point>>) {
// CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int)
// CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig
_ = lens.x
// CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int)
// CHECK: function_ref @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig
_ = lens.obj.x
// CHECK: [[FIRST_OBJ:%.*]] = struct_extract {{.*}} : $Lens<Lens<Point>>, #Lens.obj
// CHECK-NEXT: [[SECOND_OBJ:%.*]] = struct_extract [[FIRST_OBJ]] : $Lens<Point>, #Lens.obj
// CHECK-NEXT: struct_extract [[SECOND_OBJ]] : $Point, #Point.y
_ = lens.obj.obj.y
// CHECK: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int)
// CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Lens<Lens<Point>>, Lens<Lens<Int>>>, (root $Lens<Lens<Point>>; gettable_property $Lens<Lens<Int>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<Lens<Point>>.x
// CHECK: keypath $WritableKeyPath<Rectangle, Point>, (root $Rectangle; stored_property #Rectangle.topLeft : $Point)
// CHECK-NEXT: keypath $WritableKeyPath<Lens<Rectangle>, Lens<Point>>, (root $Lens<Rectangle>; settable_property $Lens<Point>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Point, Int>, (root $Point; stored_property #Point.x : $Int)
// CHECK-NEXT: keypath $KeyPath<Lens<Point>, Lens<Int>>, (root $Lens<Point>; gettable_property $Lens<Int>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs7KeyPathCyxqd__G_tcluig : {{.*}})
// CHECK-NEXT: keypath $KeyPath<Lens<Lens<Rectangle>>, Lens<Lens<Int>>>, (root $Lens<Lens<Rectangle>>; settable_property $Lens<Lens<Point>>, id @$s29keypath_dynamic_member_lookup4LensV0B6MemberACyqd__Gs15WritableKeyPathCyxqd__G_tcluig : {{.*}})
_ = \Lens<Lens<Rectangle>>.topLeft.x
}
| apache-2.0 | 6099c3312e51ab22b1e574e67adb2119 | 44.261905 | 247 | 0.6771 | 3.166574 | false | false | false | false |
mumbler/PReVo-iOS | PoshReVo/Motoroj/UzantDatumaro.swift | 1 | 10086 | //
// UzantDatumaro.swift
// PoshReVo
//
// Created by Robin Hill on 3/10/16.
// Copyright © 2016 Robin Hill. All rights reserved.
//
import Foundation
import UIKit
import ReVoModeloj
import ReVoDatumbazo
let oftajLimo = 5 // Limo de lingvoj en la "oftaj uzataj serch-lingvoj" listo
let historioLimo = 32 // Limo de artikoloj en la historio-listo
/*
La UzantDatumaro enhavas datumojn pri la uzado de la programo. Chi tiuj datumoj
estas konservitaj ke re-uzataj kiam la programo rekomencas.
*/
class UzantDatumaro {
static var serchLingvo: Lingvo = Lingvo.esperanto
static var oftajSerchLingvoj: [Lingvo] = [Lingvo]()
static var tradukLingvoj: Set<Lingvo> = Set<Lingvo>()
static var historio: [Listero] = [Listero]()
static var konservitaj: [Listero] = [Listero]()
static var stilo: KolorStilo = KolorStilo.Hela
static var konserviSerchLingvon: Bool = false
static var konserviOftajnLingvojn: Bool = false
static var konserviTradukLingvojn: Bool = false
static var konserviHistorion: Bool = false
static var konserviKonservitajn: Bool = false
static var konserviStilon: Bool = false
static func starigi() {
let testTrapaso = UserDefaults.standard.bool(forKey: "TestTrapaso")
if testTrapaso {
sharghiTrapasajnDatumojn()
} else {
sharghiJeKonservitajnDatumojn()
}
// Se datumoj ne estas trovitaj, starigi bazajn informojn
// Trovi lingvojn el la aparataj agordoj, kaj uzi ilin
if oftajSerchLingvoj.count == 0 {
for kodo in NSLocale.preferredLanguages {
let bazKodo = kodo.components(separatedBy: "-").first
if let lingvo = VortaroDatumbazo.komuna.lingvo(porKodo: bazKodo ?? kodo),
lingvo != Lingvo.esperanto {
tradukLingvoj.insert(lingvo)
oftajSerchLingvoj.append(lingvo)
}
}
konserviTradukLingvojn = true
konserviDatumojn()
}
elektisSerchLingvon(UzantDatumaro.serchLingvo)
if oftajSerchLingvoj.count > oftajLimo {
oftajSerchLingvoj = Array(oftajSerchLingvoj.prefix(oftajLimo))
}
}
// MARK: - Lingvaj agoj
// Uzata post kiam oni elektas serch-lingvon. Ghi ghisdatigas parencajn aferojn
static func elektisSerchLingvon(_ elektita: Lingvo) {
serchLingvo = elektita
if let indekso = oftajSerchLingvoj.firstIndex(where: { (nuna: Lingvo) -> Bool in
return nuna.kodo == elektita.kodo
}) {
oftajSerchLingvoj.remove(at: indekso)
}
oftajSerchLingvoj.insert(elektita, at: 0)
if oftajSerchLingvoj.count > oftajLimo {
oftajSerchLingvoj = Array(oftajSerchLingvoj.prefix(oftajLimo))
}
konserviSerchLingvon = true
konserviOftajnLingvojn = true
konserviDatumojn()
}
// Uzata post elekto de traduk-lingvojn. Ghi konservas la novajn.
static func elektisTradukLingvojn() {
konserviTradukLingvojn = true
konserviDatumojn()
}
// MARK: - Historiaj registraĵoj
// Uzata kiam oni vizitas artikolon por konservi ghin kaj ghisdatigi
// la historion
static func visitisPaghon(_ artikolo: Listero) {
if let trovo = historio.firstIndex(where: { (nuna: Listero) -> Bool in
nuna.indekso == artikolo.indekso
}) {
historio.remove(at: trovo)
}
historio.insert(artikolo, at: 0)
if historio.count > historioLimo {
historio = Array(historio.prefix(historioLimo))
}
konserviHistorion = true
konserviDatumojn()
}
static func nuligiHistorion() {
historio.removeAll()
konserviHistorion = true
konserviDatumojn()
}
// MARK: - Konservado de artikoloj
static func konserviPaghon(_ artikolo: Listero) {
konservitaj.append(artikolo)
konservitaj.sort(by: { (unua: Listero, dua: Listero) -> Bool in
return unua.nomo.compare(dua.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending
})
konserviKonservitajn = true
konserviDatumojn()
}
static func malkonserviPaghon(_ artikolo: Listero) {
if let trovo = konservitaj.firstIndex(where: { (nuna: Listero) -> Bool in
return nuna.indekso == artikolo.indekso
}) {
konservitaj.remove(at: trovo)
}
konserviKonservitajn = true
konserviDatumojn()
}
// Konservi au malkonservi lausituacio
static func shanghiKonservitecon(artikolo: Listero) {
if !konservitaj.contains(where: {(unua: Listero) -> Bool in
return unua.indekso == artikolo.indekso
}) {
konserviPaghon(artikolo)
} else {
malkonserviPaghon(artikolo)
}
}
static func nuligiKonservitajn() {
konservitaj.removeAll()
konserviKonservitajn = true
konserviDatumojn()
}
// MARK: Ŝanĝado de stiloj
static func shanghisStilon(novaStilo: KolorStilo) {
stilo = novaStilo
Stiloj.efektivigiStilon(novaStilo)
konserviStilon = true
konserviDatumojn()
}
// MARK: - Ŝarĝado por testoj
static func sharghiTrapasajnDatumojn() {
if let trapasaSerchLingvoKodo = UserDefaults.standard.string(forKey: "TestSerchLingvo"),
let trapasaSerchLingvo = VortaroDatumbazo.komuna.lingvo(porKodo: trapasaSerchLingvoKodo) {
serchLingvo = trapasaSerchLingvo
}
if let trapasaOftajKodoj = UserDefaults.standard.string(forKey: "TestOftajSerchLingvoj") {
for kodo in trapasaOftajKodoj.split(separator: ",") {
if let trapasaLingvo = VortaroDatumbazo.komuna.lingvo(porKodo: String(kodo)) {
oftajSerchLingvoj.append(trapasaLingvo)
}
}
}
if let trapasaTradukLingvoj = UserDefaults.standard.string(forKey: "TestTradukLingvoj") {
for kodo in trapasaTradukLingvoj.split(separator: ",") {
if let trapasaLingvo = VortaroDatumbazo.komuna.lingvo(porKodo: String(kodo)) {
tradukLingvoj.insert(trapasaLingvo)
}
}
}
}
// MARK: - Konservado kaj reŝarĝado de datumoj
// Konservi la uzant datumojn por reuzi ghin post rekomenco de la programo
static func konserviDatumojn() {
let defaults = UserDefaults.standard
if konserviSerchLingvon {
let datumoj = NSKeyedArchiver.archivedData(withRootObject: serchLingvo)
defaults.set(datumoj, forKey: "serchLingvo")
konserviSerchLingvon = false
}
if konserviOftajnLingvojn {
let datumoj = NSKeyedArchiver.archivedData(withRootObject: oftajSerchLingvoj)
defaults.set(datumoj, forKey: "oftajSerchLingvoj")
konserviOftajnLingvojn = false
}
if konserviTradukLingvojn {
let datumoj = NSKeyedArchiver.archivedData(withRootObject: Array(tradukLingvoj))
defaults.set(datumoj, forKey: "tradukLingvoj")
konserviTradukLingvojn = false
}
if konserviHistorion {
let datumoj = NSKeyedArchiver.archivedData(withRootObject: historio)
defaults.set(datumoj, forKey: "historio")
konserviHistorion = false
}
if konserviKonservitajn {
let datumoj = NSKeyedArchiver.archivedData(withRootObject: konservitaj)
defaults.set(datumoj, forKey: "konservitaj")
konserviKonservitajn = false
}
if konserviStilon {
defaults.set(stilo.rawValue, forKey: "stilo")
konserviStilon = false
}
defaults.synchronize()
}
// Trovi kaj starigi jamajn datumojn pri uzado
static func sharghiJeKonservitajnDatumojn() {
let defaults = UserDefaults.standard
// Legi malnoveg-nomajn aferojn
NSKeyedUnarchiver.setClass(Lingvo.self, forClassName: "PReVo.Lingvo")
NSKeyedUnarchiver.setClass(Listero.self, forClassName: "PReVo.Listero")
// Legi malnov-nomajn aferojn
NSKeyedUnarchiver.setClass(Lingvo.self, forClassName: "PoshReVo.Lingvo")
NSKeyedUnarchiver.setClass(Listero.self, forClassName: "PoshReVo.Listero")
if let datumoj = defaults.object(forKey: "serchLingvo") as? Data,
let trovo = NSKeyedUnarchiver.unarchiveObject(with: datumoj) as? Lingvo {
serchLingvo = trovo
}
if let datumoj = defaults.object(forKey: "oftajSerchLingvoj") as? Data,
let trovo = NSKeyedUnarchiver.unarchiveObject(with: datumoj) as? [Lingvo] {
oftajSerchLingvoj = trovo
}
if let datumoj = defaults.object(forKey: "tradukLingvoj") as? Data,
let trovo = NSKeyedUnarchiver.unarchiveObject(with: datumoj) as? [Lingvo] {
tradukLingvoj = Set<Lingvo>(trovo)
}
if let datumoj = defaults.object(forKey: "historio") as? Data,
let trovo = NSKeyedUnarchiver.unarchiveObject(with: datumoj) as? [Listero] {
historio = trovo
}
if let datumoj = defaults.object(forKey: "konservitaj") as? Data,
let trovo = NSKeyedUnarchiver.unarchiveObject(with: datumoj) as? [Listero] {
konservitaj = trovo
}
stilo = KolorStilo(rawValue: defaults.integer(forKey: "stilo")) ?? KolorStilo.Hela
}
}
| mit | 73ebee919de4f87348feff8661dbe8d7 | 32.93266 | 140 | 0.60637 | 3.576295 | false | false | false | false |
stoner30/BigBrother | BigBrotherTests/BigBrotherTests.swift | 2 | 2478 | //
// BigBrotherTests.swift
// BigBrother
//
// Created by Marcelo Fabri on 02/01/15.
// Copyright (c) 2015 Marcelo Fabri. All rights reserved.
//
import UIKit
import XCTest
import BigBrother
class BigBrotherTests: XCTestCase {
let mockApplication: NetworkActivityIndicatorOwner = MockApplication()
override func setUp() {
super.setUp()
BigBrother.URLProtocol.manager = BigBrother.Manager(application: mockApplication)
}
override func tearDown() {
BigBrother.URLProtocol.manager = BigBrother.Manager()
super.tearDown()
}
func testThatNetworkActivityIndicationTurnsOffWithURL(URL: NSURL) {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
BigBrother.addToSessionConfiguration(configuration)
let session = NSURLSession(configuration: configuration)
let expectation = expectationWithDescription("GET \(URL)")
let task = session.dataTaskWithURL(URL) { (data, response, error) in
delay(0.2) {
expectation.fulfill()
XCTAssertFalse(self.mockApplication.networkActivityIndicatorVisible)
}
}
task.resume()
let invisibilityDelayExpectation = expectationWithDescription("TurnOnInvisibilityDelayExpectation")
delay(0.2) {
invisibilityDelayExpectation.fulfill()
XCTAssertTrue(self.mockApplication.networkActivityIndicatorVisible)
}
waitForExpectationsWithTimeout(task.originalRequest.timeoutInterval + 1) { (error) in
task.cancel()
}
}
func testThatNetworkActivityIndicatorTurnsOffIndicatorWhenRequestSucceeds() {
let URL = NSURL(string: "http://httpbin.org/get")!
testThatNetworkActivityIndicationTurnsOffWithURL(URL)
}
func testThatNetworkActivityIndicatorTurnsOffIndicatorWhenRequestFails() {
let URL = NSURL(string: "http://httpbin.org/status/500")!
testThatNetworkActivityIndicationTurnsOffWithURL(URL)
}
}
private class MockApplication: NetworkActivityIndicatorOwner {
var networkActivityIndicatorVisible = false
}
private func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
| mit | c1075dade6ebf63c5e439488c6b9459d | 29.975 | 107 | 0.664245 | 5.1625 | false | true | false | false |
piscoTech/MBLibrary | MBLibraryTests/MiscTests.swift | 1 | 1483 | //
// MiscTests.swift
// MBLibrary
//
// Created by Marco Boschi on 20/07/16.
// Copyright © 2016 Marco Boschi. All rights reserved.
//
import XCTest
import CoreGraphics
class MiscTests: 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 testSign() {
XCTAssertTrue(sgn(1) > 0)
XCTAssertTrue(sgn(-1) < 0)
XCTAssertEqual(sgn(0), 0)
XCTAssertTrue(sgn(1.0) > 0)
let neg = -2.5
XCTAssertTrue(sgn(neg) < 0)
XCTAssertEqual(sgn(0.0), 0)
var f: Float = 1
XCTAssertTrue(sgn(f) > 0)
f = -2.5
XCTAssertTrue(sgn(f) < 0)
f = 0
XCTAssertEqual(sgn(f), 0)
var cgf: CGFloat = 1
XCTAssertTrue(sgn(cgf) > 0)
cgf = -2.5
XCTAssertTrue(sgn(cgf) < 0)
cgf = 0
XCTAssertEqual(sgn(cgf), 0)
}
func testClamp() {
XCTAssertEqual(1, 0.clamped(to: 1 ... 3))
XCTAssertEqual(2, 2.clamped(to: 1 ... 3))
XCTAssertEqual(3, 5.clamped(to: 1 ... 3))
XCTAssertEqual(1, 1.clamped(to: 1 ... 3))
XCTAssertEqual(3, 3.clamped(to: 1 ... 3))
XCTAssertEqual(1.5, 0.clamped(to: 1.5 ... 3))
XCTAssertEqual(2.1, (2.1).clamped(to: 1.5 ... 3))
XCTAssertEqual(3, (3.1).clamped(to: 1.5 ... 3))
XCTAssertEqual(3, 3.clamped(to: 1.5 ... 3))
}
}
| mit | 2f9fb33fa020706b82826112725d4054 | 22.903226 | 111 | 0.619433 | 2.96994 | false | true | false | false |
nathawes/swift | test/SILOptimizer/sil_combine_protocol_conf.swift | 8 | 13823 | // RUN: %target-swift-frontend %s -O -wmo -emit-sil -Xllvm -sil-disable-pass=DeadFunctionElimination | %FileCheck %s
// case 1: class protocol -- should optimize
internal protocol SomeProtocol : class {
func foo(x:SomeProtocol) -> Int
func foo_internal() -> Int
}
internal class SomeClass: SomeProtocol {
func foo_internal() ->Int {
return 10
}
func foo(x:SomeProtocol) -> Int {
return x.foo_internal()
}
}
// case 2: non-class protocol -- should optimize
internal protocol SomeNonClassProtocol {
func bar(x:SomeNonClassProtocol) -> Int
func bar_internal() -> Int
}
internal class SomeNonClass: SomeNonClassProtocol {
func bar_internal() -> Int {
return 20
}
func bar(x:SomeNonClassProtocol) -> Int {
return x.bar_internal()
}
}
// case 3: class conforming to protocol has a derived class -- should not optimize
internal protocol DerivedProtocol {
func foo() -> Int
}
internal class SomeDerivedClass: DerivedProtocol {
func foo() -> Int {
return 20
}
}
internal class SomeDerivedClassDerived: SomeDerivedClass {
}
// case 3: public protocol -- should not optimize
public protocol PublicProtocol {
func foo() -> Int
}
internal class SomePublicClass: PublicProtocol {
func foo() -> Int {
return 20
}
}
// case 4: Chain of protocols P1->P2->C -- optimize
internal protocol MultiProtocolChain {
func foo() -> Int
}
internal protocol RefinedMultiProtocolChain : MultiProtocolChain {
func bar() -> Int
}
internal class SomeMultiClass: RefinedMultiProtocolChain {
func foo() -> Int {
return 20
}
func bar() -> Int {
return 30
}
}
// case 5: Generic conforming type -- should not optimize
internal protocol GenericProtocol {
func foo() -> Int
}
internal class GenericClass<T> : GenericProtocol {
var items = [T]()
func foo() -> Int {
return items.count
}
}
// case 6: two classes conforming to protocol
internal protocol MultipleConformanceProtocol {
func foo() -> Int
}
internal class Klass1: MultipleConformanceProtocol {
func foo() -> Int {
return 20
}
}
internal class Klass2: MultipleConformanceProtocol {
func foo() -> Int {
return 30
}
}
internal class Other {
let x:SomeProtocol
let y:SomeNonClassProtocol
let z:DerivedProtocol
let p:PublicProtocol
let q:MultiProtocolChain
let r:GenericProtocol
let s:MultipleConformanceProtocol
init(x:SomeProtocol, y:SomeNonClassProtocol, z:DerivedProtocol, p:PublicProtocol, q:MultiProtocolChain, r:GenericProtocol, s:MultipleConformanceProtocol) {
self.x = x;
self.y = y;
self.z = z;
self.p = p;
self.q = q;
self.r = r;
self.s = s;
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF : $@convention(method) (@guaranteed Other) -> Int {
// CHECK: bb0
// CHECK: debug_value
// CHECK: integer_literal
// CHECK: [[R1:%.*]] = ref_element_addr %0 : $Other, #Other.z
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*DerivedProtocol to $*@opened("{{.*}}") DerivedProtocol
// CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") DerivedProtocol, #DerivedProtocol.foo : <Self where Self : DerivedProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") DerivedProtocol : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W1]]<@opened("{{.*}}") DerivedProtocol>([[O1]]) : $@convention(witness_method: DerivedProtocol) <τ_0_0 where τ_0_0 : DerivedProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R2:%.*]] = ref_element_addr %0 : $Other, #Other.p
// CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*PublicProtocol to $*@opened("{{.*}}") PublicProtocol
// CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") PublicProtocol, #PublicProtocol.foo : <Self where Self : PublicProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") PublicProtocol : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W2]]<@opened("{{.*}}") PublicProtocol>([[O2]]) : $@convention(witness_method: PublicProtocol) <τ_0_0 where τ_0_0 : PublicProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R3:%.*]] = ref_element_addr %0 : $Other, #Other.r
// CHECK: [[O3:%.*]] = open_existential_addr immutable_access [[R3]] : $*GenericProtocol to $*@opened("{{.*}}") GenericProtocol
// CHECK: [[W3:%.*]] = witness_method $@opened("{{.*}}") GenericProtocol, #GenericProtocol.foo : <Self where Self : GenericProtocol> (Self) -> () -> Int, [[O3]] : $*@opened("{{.*}}") GenericProtocol : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W3]]<@opened("{{.*}}") GenericProtocol>([[O3]]) : $@convention(witness_method: GenericProtocol) <τ_0_0 where τ_0_0 : GenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R4:%.*]] = ref_element_addr %0 : $Other, #Other.s
// CHECK: [[O4:%.*]] = open_existential_addr immutable_access %36 : $*MultipleConformanceProtocol to $*@opened("{{.*}}") MultipleConformanceProtocol
// CHECK: [[W4:%.*]] = witness_method $@opened("{{.*}}") MultipleConformanceProtocol, #MultipleConformanceProtocol.foo : <Self where Self : MultipleConformanceProtocol> (Self) -> () -> Int, %37 : $*@opened("{{.*}}") MultipleConformanceProtocol : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W4]]<@opened("{{.*}}") MultipleConformanceProtocol>(%37) : $@convention(witness_method: MultipleConformanceProtocol) <τ_0_0 where τ_0_0 : MultipleConformanceProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf5OtherC11doWorkClassSiyF'
@inline(never) func doWorkClass () ->Int {
return self.x.foo(x:self.x) // optimize
+ self.y.bar(x:self.y) // optimize
+ self.z.foo() // do not optimize
+ self.p.foo() // do not optimize
+ self.q.foo() // optimize
+ self.r.foo() // do not optimize
+ self.s.foo() // do not optimize
}
}
// case 1: struct -- optimize
internal protocol PropProtocol {
var val: Int { get set }
}
internal struct PropClass: PropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
// case 2: generic struct -- do not optimize
internal protocol GenericPropProtocol {
var val: Int { get set }
}
internal struct GenericPropClass<T>: GenericPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
// case 3: nested struct -- optimize
internal protocol NestedPropProtocol {
var val: Int { get }
}
struct Outer {
struct Inner : NestedPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
}
// case 4: generic nested struct -- do not optimize
internal protocol GenericNestedPropProtocol {
var val: Int { get }
}
struct GenericOuter<T> {
struct GenericInner : GenericNestedPropProtocol {
var val: Int
init(val: Int) {
self.val = val
}
}
}
internal class OtherClass {
var arg1: PropProtocol
var arg2: GenericPropProtocol
var arg3: NestedPropProtocol
var arg4: GenericNestedPropProtocol
init(arg1:PropProtocol, arg2:GenericPropProtocol, arg3: NestedPropProtocol, arg4: GenericNestedPropProtocol) {
self.arg1 = arg1
self.arg2 = arg2
self.arg3 = arg3
self.arg4 = arg4
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF : $@convention(method) (@guaranteed OtherClass) -> Int {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: debug_value
// CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg1
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*PropProtocol to $*@opened("{{.*}}") PropProtocol
// CHECK: [[U1:%.*]] = unchecked_addr_cast [[O1]] : $*@opened("{{.*}}") PropProtocol to $*PropClass
// CHECK: [[S1:%.*]] = struct_element_addr [[U1]] : $*PropClass, #PropClass.val
// CHECK: [[S11:%.*]] = struct_element_addr [[S1]] : $*Int, #Int._value
// CHECK: load [[S11]]
// CHECK: [[R2:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg2
// CHECK: [[O2:%.*]] = open_existential_addr immutable_access [[R2]] : $*GenericPropProtocol to $*@opened("{{.*}}") GenericPropProtocol
// CHECK: [[W2:%.*]] = witness_method $@opened("{{.*}}") GenericPropProtocol, #GenericPropProtocol.val!getter : <Self where Self : GenericPropProtocol> (Self) -> () -> Int, [[O2]] : $*@opened("{{.*}}") GenericPropProtocol : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W2]]<@opened("{{.*}}") GenericPropProtocol>([[O2]]) : $@convention(witness_method: GenericPropProtocol) <τ_0_0 where τ_0_0 : GenericPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R4:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg3
// CHECK: [[O4:%.*]] = open_existential_addr immutable_access [[R4]] : $*NestedPropProtocol to $*@opened("{{.*}}") NestedPropProtocol
// CHECK: [[U4:%.*]] = unchecked_addr_cast [[O4]] : $*@opened("{{.*}}") NestedPropProtocol to $*Outer.Inner
// CHECK: [[S4:%.*]] = struct_element_addr [[U4]] : $*Outer.Inner, #Outer.Inner.val
// CHECK: [[S41:%.*]] = struct_element_addr [[S4]] : $*Int, #Int._value
// CHECK: load [[S41]]
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: [[R5:%.*]] = ref_element_addr [[ARG]] : $OtherClass, #OtherClass.arg4
// CHECK: [[O5:%.*]] = open_existential_addr immutable_access [[R5]] : $*GenericNestedPropProtocol to $*@opened("{{.*}}") GenericNestedPropProtocol
// CHECK: [[W5:%.*]] = witness_method $@opened("{{.*}}") GenericNestedPropProtocol, #GenericNestedPropProtocol.val!getter : <Self where Self : GenericNestedPropProtocol> (Self) -> () -> Int, [[O5:%.*]] : $*@opened("{{.*}}") GenericNestedPropProtocol : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W5]]<@opened("{{.*}}") GenericNestedPropProtocol>([[O5]]) : $@convention(witness_method: GenericNestedPropProtocol) <τ_0_0 where τ_0_0 : GenericNestedPropProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherClassC12doWorkStructSiyF'
@inline(never) func doWorkStruct () -> Int{
return self.arg1.val // optimize
+ self.arg2.val // do not optimize
+ self.arg3.val // optimize
+ self.arg4.val // do not optimize
}
}
// case 1: enum -- optimize
internal protocol AProtocol {
var val: Int { get }
mutating func getVal() -> Int
}
internal enum AnEnum : AProtocol {
case avalue
var val: Int {
switch self {
case .avalue:
return 10
}
}
mutating func getVal() -> Int { return self.val }
}
// case 2: generic enum -- do not optimize
internal protocol AGenericProtocol {
var val: Int { get }
mutating func getVal() -> Int
}
internal enum AGenericEnum<T> : AGenericProtocol {
case avalue
var val: Int {
switch self {
case .avalue:
return 10
}
}
mutating func getVal() -> Int {
return self.val
}
}
internal class OtherKlass {
var arg1: AProtocol
var arg2: AGenericProtocol
init(arg1:AProtocol, arg2:AGenericProtocol) {
self.arg1 = arg1
self.arg2 = arg2
}
// CHECK-LABEL: sil hidden [noinline] @$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF : $@convention(method) (@guaranteed OtherKlass) -> Int {
// CHECK: bb0([[ARG:%.*]] :
// CHECK: debug_value
// CHECK: integer_literal
// CHECK: [[R1:%.*]] = ref_element_addr [[ARG]] : $OtherKlass, #OtherKlass.arg2
// CHECK: [[O1:%.*]] = open_existential_addr immutable_access [[R1]] : $*AGenericProtocol to $*@opened("{{.*}}") AGenericProtocol
// CHECK: [[W1:%.*]] = witness_method $@opened("{{.*}}") AGenericProtocol, #AGenericProtocol.val!getter : <Self where Self : AGenericProtocol> (Self) -> () -> Int, [[O1]] : $*@opened("{{.*}}") AGenericProtocol : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: apply [[W1]]<@opened("{{.*}}") AGenericProtocol>([[O1]]) : $@convention(witness_method: AGenericProtocol) <τ_0_0 where τ_0_0 : AGenericProtocol> (@in_guaranteed τ_0_0) -> Int
// CHECK: struct_extract
// CHECK: integer_literal
// CHECK: builtin
// CHECK: tuple_extract
// CHECK: tuple_extract
// CHECK: cond_fail
// CHECK: struct
// CHECK: return
// CHECK: } // end sil function '$s25sil_combine_protocol_conf10OtherKlassC10doWorkEnumSiyF'
@inline(never) func doWorkEnum() -> Int {
return self.arg1.val // optimize
+ self.arg2.val // do not optimize
}
}
| apache-2.0 | 904572737a0291768f2c1def509d63c9 | 38.150568 | 386 | 0.654597 | 3.728626 | false | false | false | false |
sschiau/swift | test/decl/var/property_wrappers.swift | 1 | 48212 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{'init(wrappedValue:)' cannot be failable}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue // expected-error{{property wrappers are not yet supported on local properties}}
var x = 17
x = 42
_ = x
}
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
@Wrapper(stored: 17)
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17)
var x3 = 42 // expected-error{{extra argument 'wrappedValue' in call}}
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
// FIXME: For some reason this is type-checked twice, second time around solver complains about <<error type>> argument
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to expected argument type 'Int'}}
// expected-error@-1 {{cannot convert value of type '<<error type>>' to expected argument type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{property wrapper type 'WrapperForHashable' declared here}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
// FIXME: Diagnostic should be better here
@WrapperForHashable
var y: NotHashable // expected-error{{property type 'NotHashable' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperForHashable'}}
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
// FIXME: Need a better diagnostic here
@HasNestedWrapper.NestedWrapper
var w: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'HasNestedWrapper.NestedWrapper'}}
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{property wrapper type 'Function' declared here}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
@Function var f2: (Int) -> Float // expected-error{{property type '(Int) -> Float' does not match that of the 'wrappedValue' property of its wrapper type 'Function'}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> {
@propertyWrapper
struct NestedWrapper<U> { // expected-note{{property wrapper type 'NestedWrapper' declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{incorrect argument label in call (have 'x:', expected 'y:')}}
// expected-error@-1 {{cannot convert value of type 'Wrapper<Bool>' to expected argument type 'Int'}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
// expected-note@-2{{'BrokenLazy' declared here}}
struct S {
@BrokenLazy // expected-error{{struct 'BrokenLazy' cannot be used as an attribute}}
var wrappedValue: Int
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper { // expected-note{{property wrapper type 'SR_10899_Wrapper' declared here}}
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match that of the 'wrappedValue' property of its wrapper type 'SR_10899_Wrapper'}}
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> {
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> { // expected-note{{property wrapper type 'WrapperD' declared here}}
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{property type 'Int' does not match that of the 'wrappedValue' property of its wrapper type 'WrapperD<WrapperC, Int, String>'}}
func triggerErrors(d: Double) {
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
}
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
@Foo var x: Int = 42 // expected-error {{cannot invoke initializer for ty}}
// expected-note@-1{{overloads for 'Foo<_>' exist with these partially matching paramet}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject {
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error 2 {{'SR_11288_S4.SR_11288_Wrapper4.Type' (aka 'SR_11288_S0.Type') requires that 'SR_11288_S4' conform to 'AnyObject'}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
| apache-2.0 | 220046cca2e98c424a462f2b64862616 | 26.948986 | 234 | 0.64652 | 4.185433 | false | false | false | false |
sschiau/swift | test/Driver/linker.swift | 3 | 17184 | // Must be able to run xcrun-return-self.sh
// REQUIRES: shell
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck %s < %t.simple.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple.txt
// RUN: not %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -static-stdlib %s 2>&1 | %FileCheck -check-prefix=SIMPLE_STATIC %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-tvos9.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix tvOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target i386-apple-watchos2.0 %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix watchOS_SIMPLE %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-x86_64 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv6-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv6 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-armv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target thumbv7-unknown-linux-gnueabihf -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-thumbv7 %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-none-linux-androideabi -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7 %s < %t.android.txt
// RUN: %FileCheck -check-prefix ANDROID-armv7-NEGATIVE %s < %t.android.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.cygwin.txt
// RUN: %FileCheck -check-prefix CYGWIN-x86_64 %s < %t.cygwin.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -Ffoo -Fsystem car -F cdr -framework bar -Lbaz -lboo -Xlinker -undefined %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-x86_64 %s < %t.windows.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-unknown-linux-gnu %s -Lbar -o dynlib.out 2>&1 > %t.linux.dynlib.txt
// RUN: %FileCheck -check-prefix LINUX_DYNLIB-x86_64 %s < %t.linux.dynlib.txt
// RUN: %swiftc_driver -driver-print-jobs -emit-library -target x86_64-apple-macosx10.9.1 %s -sdk %S/../Inputs/clang-importer-sdk -lfoo -framework bar -Lbaz -Fgarply -Fsystem car -F cdr -Xlinker -undefined -Xlinker dynamic_lookup -o sdk.out 2>&1 > %t.complex.txt
// RUN: %FileCheck %s < %t.complex.txt
// RUN: %FileCheck -check-prefix COMPLEX %s < %t.complex.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-ios7.1 -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.simple.txt
// RUN: %FileCheck -check-prefix IOS-linker-order %s < %t.simple.txt
// RUN: %swiftc_driver -driver-print-jobs -target armv7-unknown-linux-gnueabihf -Xlinker -rpath -Xlinker customrpath -L foo %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.linux.txt
// RUN: %FileCheck -check-prefix LINUX-clang-linker-order %s < %t.linux.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -Xclang-linker -foo -Xclang-linker foopath %s 2>&1 > %t.windows.txt
// RUN: %FileCheck -check-prefix WINDOWS-clang-linker-order %s < %t.windows.txt
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -g %s | %FileCheck -check-prefix DEBUG %s
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: touch %t/a.swiftmodule
// RUN: touch %t/b.o
// RUN: touch %t/b.swiftmodule
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o %t/a.swiftmodule %t/b.o %t/b.swiftmodule -o linker | %FileCheck -check-prefix LINK-SWIFTMODULES %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.10 %s > %t.simple-macosx10.10.txt
// RUN: %FileCheck %s < %t.simple-macosx10.10.txt
// RUN: %FileCheck -check-prefix SIMPLE %s < %t.simple-macosx10.10.txt
// RUN: %empty-directory(%t)
// RUN: touch %t/a.o
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -o linker 2>&1 | %FileCheck -check-prefix COMPILE_AND_LINK %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 %s %t/a.o -driver-filelist-threshold=0 -o linker 2>&1 | %FileCheck -check-prefix FILELIST %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-linux-gnu -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_LINUX %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-cygnus -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-unknown-windows-msvc -emit-library %s -module-name LINKER | %FileCheck -check-prefix INFERRED_NAME_WINDOWS %s
// Here we specify an output file name using '-o'. For ease of writing these
// tests, we happen to specify the same file name as is inferred in the
// INFERRED_NAMED_DARWIN tests above: 'libLINKER.dylib'.
// RUN: %swiftc_driver -driver-print-jobs -target x86_64-apple-macosx10.9 -emit-library %s -o libLINKER.dylib | %FileCheck -check-prefix INFERRED_NAME_DARWIN %s
// There are more RUN lines further down in the file.
// CHECK: swift
// CHECK: -o [[OBJECTFILE:.*]]
// CHECK-NEXT: {{(bin/)?}}ld{{"? }}
// CHECK-DAG: [[OBJECTFILE]]
// CHECK-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)macosx]]
// CHECK-DAG: -rpath [[STDLIB_PATH]]
// CHECK-DAG: -lSystem
// CHECK-DAG: -arch x86_64
// CHECK: -o {{[^ ]+}}
// SIMPLE: {{(bin/)?}}ld{{"? }}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -macosx_version_min 10.{{[0-9]+}}.{{[0-9]+}}
// SIMPLE-NOT: -syslibroot
// SIMPLE: -o linker
// SIMPLE_STATIC: error: -static-stdlib is no longer supported on Apple platforms
// IOS_SIMPLE: swift
// IOS_SIMPLE: -o [[OBJECTFILE:.*]]
// IOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// IOS_SIMPLE-DAG: [[OBJECTFILE]]
// IOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator}}
// IOS_SIMPLE-DAG: -lSystem
// IOS_SIMPLE-DAG: -arch x86_64
// IOS_SIMPLE-DAG: -ios_simulator_version_min 7.1.{{[0-9]+}}
// IOS_SIMPLE: -o linker
// tvOS_SIMPLE: swift
// tvOS_SIMPLE: -o [[OBJECTFILE:.*]]
// tvOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// tvOS_SIMPLE-DAG: [[OBJECTFILE]]
// tvOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)appletvsimulator}}
// tvOS_SIMPLE-DAG: -lSystem
// tvOS_SIMPLE-DAG: -arch x86_64
// tvOS_SIMPLE-DAG: -tvos_simulator_version_min 9.0.{{[0-9]+}}
// tvOS_SIMPLE: -o linker
// watchOS_SIMPLE: swift
// watchOS_SIMPLE: -o [[OBJECTFILE:.*]]
// watchOS_SIMPLE: {{(bin/)?}}ld{{"? }}
// watchOS_SIMPLE-DAG: [[OBJECTFILE]]
// watchOS_SIMPLE-DAG: -L {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)watchsimulator}}
// watchOS_SIMPLE-DAG: -lSystem
// watchOS_SIMPLE-DAG: -arch i386
// watchOS_SIMPLE-DAG: -watchos_simulator_version_min 2.0.{{[0-9]+}}
// watchOS_SIMPLE: -o linker
// LINUX-x86_64: swift
// LINUX-x86_64: -o [[OBJECTFILE:.*]]
// LINUX-x86_64: clang{{(\.exe)?"? }}
// LINUX-x86_64-DAG: -pie
// LINUX-x86_64-DAG: [[OBJECTFILE]]
// LINUX-x86_64-DAG: -lswiftCore
// LINUX-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-x86_64-DAG: -F foo -iframework car -F cdr
// LINUX-x86_64-DAG: -framework bar
// LINUX-x86_64-DAG: -L baz
// LINUX-x86_64-DAG: -lboo
// LINUX-x86_64-DAG: -Xlinker -undefined
// LINUX-x86_64: -o linker
// LINUX-armv6: swift
// LINUX-armv6: -o [[OBJECTFILE:.*]]
// LINUX-armv6: clang{{(\.exe)?"? }}
// LINUX-armv6-DAG: -pie
// LINUX-armv6-DAG: [[OBJECTFILE]]
// LINUX-armv6-DAG: -lswiftCore
// LINUX-armv6-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv6-DAG: -target armv6-unknown-linux-gnueabihf
// LINUX-armv6-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv6-DAG: -F foo -iframework car -F cdr
// LINUX-armv6-DAG: -framework bar
// LINUX-armv6-DAG: -L baz
// LINUX-armv6-DAG: -lboo
// LINUX-armv6-DAG: -Xlinker -undefined
// LINUX-armv6: -o linker
// LINUX-armv7: swift
// LINUX-armv7: -o [[OBJECTFILE:.*]]
// LINUX-armv7: clang{{(\.exe)?"? }}
// LINUX-armv7-DAG: -pie
// LINUX-armv7-DAG: [[OBJECTFILE]]
// LINUX-armv7-DAG: -lswiftCore
// LINUX-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-armv7-DAG: -target armv7-unknown-linux-gnueabihf
// LINUX-armv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-armv7-DAG: -F foo -iframework car -F cdr
// LINUX-armv7-DAG: -framework bar
// LINUX-armv7-DAG: -L baz
// LINUX-armv7-DAG: -lboo
// LINUX-armv7-DAG: -Xlinker -undefined
// LINUX-armv7: -o linker
// LINUX-thumbv7: swift
// LINUX-thumbv7: -o [[OBJECTFILE:.*]]
// LINUX-thumbv7: clang{{(\.exe)?"? }}
// LINUX-thumbv7-DAG: -pie
// LINUX-thumbv7-DAG: [[OBJECTFILE]]
// LINUX-thumbv7-DAG: -lswiftCore
// LINUX-thumbv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)]]
// LINUX-thumbv7-DAG: -target thumbv7-unknown-linux-gnueabihf
// LINUX-thumbv7-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// LINUX-thumbv7-DAG: -F foo -iframework car -F cdr
// LINUX-thumbv7-DAG: -framework bar
// LINUX-thumbv7-DAG: -L baz
// LINUX-thumbv7-DAG: -lboo
// LINUX-thumbv7-DAG: -Xlinker -undefined
// LINUX-thumbv7: -o linker
// ANDROID-armv7: swift
// ANDROID-armv7: -o [[OBJECTFILE:.*]]
// ANDROID-armv7: clang{{(\.exe)?"? }}
// ANDROID-armv7-DAG: -pie
// ANDROID-armv7-DAG: [[OBJECTFILE]]
// ANDROID-armv7-DAG: -lswiftCore
// ANDROID-armv7-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// ANDROID-armv7-DAG: -target armv7-unknown-linux-androideabi
// ANDROID-armv7-DAG: -F foo -iframework car -F cdr
// ANDROID-armv7-DAG: -framework bar
// ANDROID-armv7-DAG: -L baz
// ANDROID-armv7-DAG: -lboo
// ANDROID-armv7-DAG: -Xlinker -undefined
// ANDROID-armv7: -o linker
// ANDROID-armv7-NEGATIVE-NOT: -Xlinker -rpath
// CYGWIN-x86_64: swift
// CYGWIN-x86_64: -o [[OBJECTFILE:.*]]
// CYGWIN-x86_64: clang{{(\.exe)?"? }}
// CYGWIN-x86_64-DAG: [[OBJECTFILE]]
// CYGWIN-x86_64-DAG: -lswiftCore
// CYGWIN-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift]]
// CYGWIN-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH]]
// CYGWIN-x86_64-DAG: -F foo -iframework car -F cdr
// CYGWIN-x86_64-DAG: -framework bar
// CYGWIN-x86_64-DAG: -L baz
// CYGWIN-x86_64-DAG: -lboo
// CYGWIN-x86_64-DAG: -Xlinker -undefined
// CYGWIN-x86_64: -o linker
// WINDOWS-x86_64: swift
// WINDOWS-x86_64: -o [[OBJECTFILE:.*]]
// WINDOWS-x86_64: clang{{(\.exe)?"? }}
// WINDOWS-x86_64-DAG: [[OBJECTFILE]]
// WINDOWS-x86_64-DAG: -L [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)windows(/|\\\\)x86_64]]
// WINDOWS-x86_64-DAG: -F foo -iframework car -F cdr
// WINDOWS-x86_64-DAG: -framework bar
// WINDOWS-x86_64-DAG: -L baz
// WINDOWS-x86_64-DAG: -lboo
// WINDOWS-x86_64-DAG: -Xlinker -undefined
// WINDOWS-x86_64: -o linker
// COMPLEX: {{(bin/)?}}ld{{"? }}
// COMPLEX-DAG: -dylib
// COMPLEX-DAG: -syslibroot {{.*}}/Inputs/clang-importer-sdk
// COMPLEX-DAG: -lfoo
// COMPLEX-DAG: -framework bar
// COMPLEX-DAG: -L baz
// COMPLEX-DAG: -F garply -F car -F cdr
// COMPLEX-DAG: -undefined dynamic_lookup
// COMPLEX-DAG: -macosx_version_min 10.9.1
// COMPLEX: -o sdk.out
// LINUX_DYNLIB-x86_64: swift
// LINUX_DYNLIB-x86_64: -o [[OBJECTFILE:.*]]
// LINUX_DYNLIB-x86_64: -o {{"?}}[[AUTOLINKFILE:.*]]
// LINUX_DYNLIB-x86_64: clang{{(\.exe)?"? }}
// LINUX_DYNLIB-x86_64-DAG: -shared
// LINUX_DYNLIB-x86_64-DAG: -fuse-ld=gold
// LINUX_DYNLIB-x86_64-NOT: -pie
// LINUX_DYNLIB-x86_64-DAG: -Xlinker -rpath -Xlinker [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux]]
// LINUX_DYNLIB-x86_64: [[STDLIB_PATH]]{{/|\\\\}}x86_64{{/|\\\\}}swiftrt.o
// LINUX_DYNLIB-x86_64-DAG: [[OBJECTFILE]]
// LINUX_DYNLIB-x86_64-DAG: @[[AUTOLINKFILE]]
// LINUX_DYNLIB-x86_64-DAG: [[STDLIB_PATH]]
// LINUX_DYNLIB-x86_64-DAG: -lswiftCore
// LINUX_DYNLIB-x86_64-DAG: -L bar
// LINUX_DYNLIB-x86_64: -o dynlib.out
// IOS-linker-order: swift
// IOS-linker-order: -o [[OBJECTFILE:.*]]
// IOS-linker-order: {{(bin/)?}}ld{{"? }}
// IOS-linker-order: -rpath [[STDLIB_PATH:[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)iphonesimulator]]
// IOS-linker-order: -L foo
// IOS-linker-order: -rpath customrpath
// IOS-linker-order: -o {{.*}}
// LINUX-linker-order: swift
// LINUX-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-linker-order: clang{{(\.exe)?"? }}
// LINUX-linker-order: -Xlinker -rpath -Xlinker {{[^ ]+(/|\\\\)lib(/|\\\\)swift(/|\\\\)linux}}
// LINUX-linker-order: -L foo
// LINUX-linker-order: -Xlinker -rpath -Xlinker customrpath
// LINUX-linker-order: -o {{.*}}
// LINUX-clang-linker-order: swift
// LINUX-clang-linker-order: -o [[OBJECTFILE:.*]]
// LINUX-clang-linker-order: clang{{"? }}
// LINUX-clang-linker-order: -foo foopath
// LINUX-clang-linker-order: -o {{.*}}
// WINDOWS-clang-linker-order: swift
// WINDOWS-clang-linker-order: -o [[OBJECTFILE:.*]]
// WINDOWS-clang-linker-order: clang{{"? }}
// WINDOWS-clang-linker-order: -foo foopath
// WINDOWS-clang-linker-order: -o {{.*}}
// DEBUG: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// DEBUG-NEXT: {{(bin/)?}}ld{{"? }}
// DEBUG: -add_ast_path {{.*(/|\\\\)[^/]+}}.swiftmodule
// DEBUG: -o linker
// DEBUG-NEXT: bin{{/|\\\\}}dsymutil
// DEBUG: linker
// DEBUG: -o linker.dSYM
// LINK-SWIFTMODULES: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// LINK-SWIFTMODULES-NEXT: {{(bin/)?}}ld{{"? }}
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/a.swiftmodule
// LINK-SWIFTMODULES-SAME: -add_ast_path {{.*}}/b.swiftmodule
// LINK-SWIFTMODULES-SAME: -o linker
// COMPILE_AND_LINK: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK: linker.swift
// COMPILE_AND_LINK-NOT: /a.o
// COMPILE_AND_LINK-NEXT: {{(bin/)?}}ld{{"? }}
// COMPILE_AND_LINK-DAG: /a.o
// COMPILE_AND_LINK-DAG: .o
// COMPILE_AND_LINK: -o linker
// FILELIST: {{(bin/)?}}ld{{"? }}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -filelist {{"?[^-]}}
// FILELIST-NOT: .o{{"? }}
// FILELIST: /a.o{{"? }}
// FILELIST-NOT: .o{{"? }}
// FILELIST: -o linker
// INFERRED_NAME_DARWIN: bin{{/|\\\\}}swift{{c?(\.EXE)?}}
// INFERRED_NAME_DARWIN: -module-name LINKER
// INFERRED_NAME_DARWIN: {{(bin/)?}}ld{{"? }}
// INFERRED_NAME_DARWIN: -o libLINKER.dylib
// INFERRED_NAME_LINUX: -o libLINKER.so
// INFERRED_NAME_WINDOWS: -o LINKER.dll
// Test ld detection. We use hard links to make sure
// the Swift driver really thinks it's been moved.
// RUN: rm -rf %t
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/bin)
// RUN: touch %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: chmod +x %t/DISTINCTIVE-PATH/usr/bin/ld
// RUN: %hardlink-or-copy(from: %swift_driver_plain, to: %t/DISTINCTIVE-PATH/usr/bin/swiftc)
// RUN: %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE-LINKER %s
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}swift
// RELATIVE-LINKER: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}bin{{/|\\\\}}ld
// RELATIVE-LINKER: -o {{[^ ]+}}
// Also test arclite detection. This uses xcrun to find arclite when it's not
// next to Swift.
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/bin)
// RUN: %empty-directory(%t/ANOTHER-DISTINCTIVE-PATH/usr/lib/arc)
// RUN: cp %S/Inputs/xcrun-return-self.sh %t/ANOTHER-DISTINCTIVE-PATH/usr/bin/xcrun
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=XCRUN_ARCLITE %s
// XCRUN_ARCLITE: bin{{/|\\\\}}ld
// XCRUN_ARCLITE: {{/|\\\\}}ANOTHER-DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// XCRUN_ARCLITE: -o {{[^ ]+}}
// RUN: %empty-directory(%t/DISTINCTIVE-PATH/usr/lib/arc)
// RUN: env PATH=%t/ANOTHER-DISTINCTIVE-PATH/usr/bin %t/DISTINCTIVE-PATH/usr/bin/swiftc -target x86_64-apple-macosx10.9 %s -### | %FileCheck -check-prefix=RELATIVE_ARCLITE %s
// RELATIVE_ARCLITE: bin{{/|\\\\}}ld
// RELATIVE_ARCLITE: {{/|\\\\}}DISTINCTIVE-PATH{{/|\\\\}}usr{{/|\\\\}}lib{{/|\\\\}}arc{{/|\\\\}}libarclite_macosx.a
// RELATIVE_ARCLITE: -o {{[^ ]+}}
// Clean up the test executable because hard links are expensive.
// RUN: rm -rf %t/DISTINCTIVE-PATH/usr/bin/swiftc
| apache-2.0 | 208b2760072406ddcb088822081c3eeb | 42.067669 | 262 | 0.650431 | 2.876465 | false | false | false | false |
apple/swift-format | Tests/SwiftFormatPrettyPrintTests/FunctionTypeTests.swift | 1 | 3565 | final class FunctionTypeTests: PrettyPrintTestCase {
func testFunctionType() {
let input =
"""
func f(g: (_ somevalue: Int) -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: Int) -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: inout Int) -> String?) {
let a = 123
let b = "abc"
}
func f(g: (variable1: Int, variable2: Double, variable3: Bool) -> Double) {
let a = 123
let b = "abc"
}
func f(g: (variable1: Int, variable2: Double, variable3: Bool, variable4: String) -> Double) {
let a = 123
let b = "abc"
}
"""
let expected =
"""
func f(g: (_ somevalue: Int) -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: Int) -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: inout Int) -> String?) {
let a = 123
let b = "abc"
}
func f(
g: (variable1: Int, variable2: Double, variable3: Bool) ->
Double
) {
let a = 123
let b = "abc"
}
func f(
g: (
variable1: Int, variable2: Double, variable3: Bool,
variable4: String
) -> Double
) {
let a = 123
let b = "abc"
}
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 60)
}
func testFunctionTypeThrows() {
let input =
"""
func f(g: (_ somevalue: Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: inout Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(g: (variable1: Int, variable2: Double, variable3: Bool) throws -> Double) {
let a = 123
let b = "abc"
}
func f(g: (variable1: Int, variable2: Double, variable3: Bool, variable4: String) throws -> Double) {
let a = 123
let b = "abc"
}
"""
let expected =
"""
func f(g: (_ somevalue: Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(g: (currentLevel: inout Int) throws -> String?) {
let a = 123
let b = "abc"
}
func f(
g: (variable1: Int, variable2: Double, variable3: Bool) throws ->
Double
) {
let a = 123
let b = "abc"
}
func f(
g: (
variable1: Int, variable2: Double, variable3: Bool,
variable4: String
) throws -> Double
) {
let a = 123
let b = "abc"
}
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 67)
}
func testFunctionTypeInOut() {
let input =
"""
func f(g: (firstArg: inout FirstArg, secondArg: inout SecondArg) -> Result) {
let a = 123
let b = "abc"
}
"""
let expected =
"""
func f(
g: (
firstArg:
inout
FirstArg,
secondArg:
inout
SecondArg
) -> Result
) {
let a = 123
let b = "abc"
}
"""
assertPrettyPrintEqual(input: input, expected: expected, linelength: 17)
}
}
| apache-2.0 | 6ec5eb22211dbb4c41195950674619fd | 22.300654 | 107 | 0.460589 | 3.76452 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSCFArray.swift | 1 | 5046 | // 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
//
@_implementationOnly import CoreFoundation
internal final class _NSCFArray : NSMutableArray {
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
required init(coder: NSCoder) {
fatalError()
}
required init(objects: UnsafePointer<AnyObject>?, count cnt: Int) {
fatalError()
}
required public convenience init(arrayLiteral elements: Any...) {
fatalError()
}
override var count: Int {
return CFArrayGetCount(_cfObject)
}
override func object(at index: Int) -> Any {
let value = CFArrayGetValueAtIndex(_cfObject, index)
return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self))
}
override func insert(_ value: Any, at index: Int) {
let anObject = __SwiftValue.store(value)
CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self))
}
override func removeObject(at index: Int) {
CFArrayRemoveValueAtIndex(_cfMutableObject, index)
}
override var classForCoder: AnyClass {
return NSMutableArray.self
}
}
internal func _CFSwiftArrayGetCount(_ array: AnyObject) -> CFIndex {
return (array as! NSArray).count
}
internal func _CFSwiftArrayGetValueAtIndex(_ array: AnyObject, _ index: CFIndex) -> Unmanaged<AnyObject> {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
return Unmanaged.passUnretained(arr._storage[index])
} else {
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
return Unmanaged.passUnretained(value)
}
}
internal func _CFSwiftArrayGetValues(_ array: AnyObject, _ range: CFRange, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>) {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
for idx in 0..<range.length {
values[idx] = Unmanaged.passUnretained(arr._storage[idx + range.location])
}
} else {
for idx in 0..<range.length {
let index = idx + range.location
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
values[idx] = Unmanaged.passUnretained(value)
}
}
}
internal func _CFSwiftArrayAppendValue(_ array: AnyObject, _ value: AnyObject) {
(array as! NSMutableArray).add(value)
}
internal func _CFSwiftArraySetValueAtIndex(_ array: AnyObject, _ value: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayReplaceValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayInsertValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).insert(value, at: idx)
}
internal func _CFSwiftArrayExchangeValuesAtIndices(_ array: AnyObject, _ idx1: CFIndex, _ idx2: CFIndex) {
(array as! NSMutableArray).exchangeObject(at: idx1, withObjectAt: idx2)
}
internal func _CFSwiftArrayRemoveValueAtIndex(_ array: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).removeObject(at: idx)
}
internal func _CFSwiftArrayRemoveAllValues(_ array: AnyObject) {
(array as! NSMutableArray).removeAllObjects()
}
internal func _CFSwiftArrayReplaceValues(_ array: AnyObject, _ range: CFRange, _ newValues: UnsafeMutablePointer<Unmanaged<AnyObject>>, _ newCount: CFIndex) {
let buffer: UnsafeBufferPointer<Unmanaged<AnyObject>> = UnsafeBufferPointer(start: newValues, count: newCount)
let replacements = Array(buffer).map { $0.takeUnretainedValue() }
(array as! NSMutableArray).replaceObjects(in: NSRange(location: range.location, length: range.length), withObjectsFrom: replacements)
}
internal func _CFSwiftArrayIsSubclassOfNSMutableArray(_ array: AnyObject) -> _DarwinCompatibleBoolean {
return array is NSMutableArray ? true : false
}
| apache-2.0 | 5055dde9e4bde138ba7bf1ba5e3fee7a | 36.377778 | 158 | 0.675386 | 4.533693 | false | false | false | false |
Five3Apps/HealthKitDemo | Activity Check/WriteViewController.swift | 1 | 2574 | //
// WriteViewController.swift
// Activity Check
//
// Created by Justin Bergen on 4/24/17.
// Copyright © 2017 Five3 Apps. All rights reserved.
//
import Foundation
import UIKit
import HealthKit
class WriteViewController: UIViewController {
//MARK: Properties
let activityKit = ActivityKit()
@IBOutlet var timestampTextField: UITextField!
@IBOutlet var caloriesTextField: UITextField!
//MARK: Overrides
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: Actions
@IBAction func saveActiveCalorieSample(_ sender: UIButton) {
guard self.timestampTextField.text != nil || self.caloriesTextField.text != nil else {
NSLog("Cannot save active calorie sample without a timestamp and active calorie value")
return
}
guard let quantityType = HKObjectType.quantityType(forIdentifier: HKQuantityTypeIdentifier.activeEnergyBurned) else {
NSLog("Unable to create active calorie quantity type")
return
}
guard let startDate = ISO8601DateFormatter().date(from: self.timestampTextField.text!) else {
NSLog("Unable to create a sample date")
return
}
guard let calories = Double(self.caloriesTextField.text!) else {
NSLog("Unable to create active calorie quantity")
return
}
let calorieQuantity = HKQuantity.init(unit: HKUnit.kilocalorie(), doubleValue: calories)
let activeCalorieSample = HKQuantitySample.init(type: quantityType, quantity: calorieQuantity, start: startDate, end: startDate)
self.activityKit.saveActivitySample(sample: activeCalorieSample, completion: { success, error in
guard success else {
NSLog("An error occured saving active calories. The error was: %@.", [error])
return
}
})
}
@IBAction func dismissKeyboard(_ sender: UITapGestureRecognizer) {
self.view.endEditing(true)
}
//MARK: <UITextFieldDelegate>
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.timestampTextField {
self.caloriesTextField.becomeFirstResponder()
}
else if textField == self.caloriesTextField {
self.caloriesTextField.resignFirstResponder()
}
return true
}
}
| mit | aa1545e3f2c1e9cc7776d33e61b82d4b | 28.574713 | 136 | 0.609794 | 5.486141 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Metadata/Sources/MetadataKit/Errors/MetadataInitializationError.swift | 1 | 1611 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public enum MetadataInitialisationError: Error, Equatable {
case failedToDeriveSecondPasswordNode(DeriveSecondPasswordNodeError)
case failedToLoadRemoteMetadataNode(LoadRemoteMetadataError)
case failedToDecodeRemoteMetadataNode(DecodingError)
case failedToDeriveRemoteMetadataNode(MetadataInitError)
case failedToGenerateNodes(Error)
public static func == (lhs: MetadataInitialisationError, rhs: MetadataInitialisationError) -> Bool {
switch (lhs, rhs) {
case (.failedToDeriveSecondPasswordNode(let leftError), .failedToDeriveSecondPasswordNode(let rightError)):
return leftError.localizedDescription == rightError.localizedDescription
case (.failedToLoadRemoteMetadataNode(let leftError), .failedToLoadRemoteMetadataNode(let rightError)):
return leftError.localizedDescription == rightError.localizedDescription
case (.failedToDecodeRemoteMetadataNode(let leftError), .failedToDecodeRemoteMetadataNode(let rightError)):
return leftError.localizedDescription == rightError.localizedDescription
case (.failedToDeriveRemoteMetadataNode(let leftError), .failedToDeriveRemoteMetadataNode(let rightError)):
return leftError.localizedDescription == rightError.localizedDescription
case (.failedToGenerateNodes(let leftError), .failedToGenerateNodes(let rightError)):
return leftError.localizedDescription == rightError.localizedDescription
default:
return false
}
}
}
| lgpl-3.0 | e237a8768db9b5cb71eb8d34bea90467 | 56.5 | 115 | 0.77205 | 5.227273 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Blockchain/Authentication/PasswordScreen/PasswordViewController.swift | 1 | 2172 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import PlatformUIKit
import RxSwift
final class PasswordViewController: BaseScreenViewController {
// MARK: - IBOutlet Properties
@IBOutlet private var descriptionLabel: UILabel!
@IBOutlet private var textFieldView: PasswordTextFieldView!
@IBOutlet private var buttonView: ButtonView!
private var keyboardInteractionController: KeyboardInteractionController!
private let disposeBag = DisposeBag()
// MARK: - Injected
private let presenter: PasswordScreenPresenter
// MARK: - Setup
init(presenter: PasswordScreenPresenter) {
self.presenter = presenter
super.init(nibName: PasswordViewController.objectName, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
set(barStyle: presenter.navBarStyle, leadingButtonStyle: presenter.leadingButton)
titleViewStyle = presenter.titleStyle
keyboardInteractionController = KeyboardInteractionController(in: self)
descriptionLabel.text = presenter.description
descriptionLabel.font = .main(.medium, 14)
descriptionLabel.textColor = .descriptionText
textFieldView.setup(
viewModel: presenter.textFieldViewModel,
keyboardInteractionController: keyboardInteractionController
)
buttonView.viewModel = presenter.buttonViewModel
buttonView.viewModel.tapRelay
.dismissKeyboard(using: keyboardInteractionController)
.subscribe()
.disposed(by: disposeBag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
presenter.viewWillAppear()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
presenter.viewDidDisappear()
}
// MARK: - Navigation
override func navigationBarLeadingButtonPressed() {
presenter.navigationBarLeadingButtonPressed()
}
}
| lgpl-3.0 | 9593d27cc976bb7521931160e952cfd5 | 29.152778 | 89 | 0.701981 | 5.743386 | false | false | false | false |
blkbrds/intern09_final_project_tung_bien | MyApp/View/Controllers/Cart/CartViewController.swift | 1 | 5038 | //
// CartViewController.swift
// MyApp
//
// Created by AST on 7/19/17.
// Copyright © 2017 Asian Tech Co., Ltd. All rights reserved.
//
import UIKit
import SwiftUtils
import MVVM
import SVProgressHUD
class CartViewController: ViewController {
// MARK: - Properties
@IBOutlet weak var cartTableView: UITableView!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var orderButton: UIButton!
@IBOutlet weak var noItemLabel: UILabel!
fileprivate var viewModel = CartViewModel() {
didSet {
updateView()
}
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupData()
NotificationCenter.default.addObserver(self, selector: #selector(receiveNotification), name: .kNotificationCart, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Private
private func setupUI() {
navigationItem.title = App.String.CartViewControllerTitle
cartTableView.register(CartTableViewCell.self)
cartTableView.dataSource = self
cartTableView.rowHeight = 95
}
private func setupData() {
viewModel.fetchCartItem()
if viewModel.cartItemIsEmpty() {
noItemLabel.isHidden = false
orderButton.isEnabled = false
orderButton.alpha = 0.5
} else {
noItemLabel.isHidden = true
}
cartTableView.reloadData()
totalLabel.text = "\(viewModel.getTotalOrder().formattedWithSeparator()) \(App.String.UnitCurrency)"
}
func updateView() {
guard isViewLoaded else { return }
cartTableView.reloadData()
totalLabel.text = "\(viewModel.getTotalOrder().formattedWithSeparator()) \(App.String.UnitCurrency)"
}
@objc private func receiveNotification() {
setupData()
}
// MARK: - Action
@IBAction func orderButtonTouchUpInside(_ sender: UIButton) {
SVProgressHUD.show()
SVProgressHUD.setDefaultMaskType(.gradient)
viewModel.fetchCurrentBalance(completion: { [weak self] (result) in
guard let this = self else { return }
switch result {
case .success:
let confirmView: ConfirmOrderView = ConfirmOrderView.loadNib()
confirmView.delegate = self
confirmView.totalOrder = this.viewModel.getTotalOrder()
confirmView.balance = this.viewModel.getCurrentBalance()
confirmView.remainingBalance = this.viewModel.getRemainingBalance()
confirmView.show()
case .failure(let error):
this.alert(error: error)
}
SVProgressHUD.dismiss()
})
}
}
extension CartViewController: ConfirmOrderViewDelegate {
func confirmOrderViewDelegate() {
SVProgressHUD.show()
viewModel.sendOrderToServer { [weak self] (result) in
guard let this = self else { return }
switch result {
case .success:
this.viewModel.sendedToServer()
let alert = UIAlertController(title: App.String.OrderSuccessAlert, message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: App.String.ok, style: .default, handler: { (_: UIAlertAction!) in
let recentVC = RecentViewController()
let navi = UINavigationController(rootViewController: recentVC)
if let sideMenuController = this.sideMenuController {
sideMenuController.rootViewController = navi
}
}))
this.present(alert, animated: true, completion: nil)
case .failure(let error):
this.alert(error: error)
}
SVProgressHUD.dismiss()
}
}
}
// MARK: - UITableDataSource
extension CartViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfItems(inSection: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeue(CartTableViewCell.self)
cell.viewModel = viewModel.viewModelForItem(at: indexPath)
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let cell = tableView.dequeue(CartTableViewCell.self)
cell.viewModel = viewModel.viewModelForItem(at: indexPath)
cell.delete()
}
}
// MARK: - ViewModelDelegate
extension CartViewController: ViewModelDelegate {
func viewModel(_ viewModel: ViewModel, didChangeItemsAt indexPaths: [IndexPath], for changeType: ChangeType) {
updateView()
}
}
| mit | 2044cd6a7c15974cfdbdf2515a9e901c | 33.265306 | 133 | 0.637086 | 5.192784 | false | false | false | false |
cfilipov/MuscleBook | MuscleBook/DB+Workouts.swift | 1 | 8569 | /*
Muscle Book
Copyright (C) 2016 Cristian Filipov
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import SQLite
extension DB {
func all(type: Workout.Type) throws -> AnySequence<Workout> {
return try db.prepare(Workout.Schema.table.order(Workout.Schema.startTime.desc))
}
func count(type: Workout.Type) -> Int {
return db.scalar(Workout.Schema.table.count)
}
func count(type: Workout.Type, after startTime: NSDate) -> Int {
typealias WO = Workout.Schema
return db.scalar(
WO.table
.select(WO.workoutID.count)
.filter(WO.startTime > startTime)
)
}
func count(type: Workout.Type, forDay date: NSDate) -> Int {
return db.scalar(
Workout.Schema.table.filter(
Workout.Schema.startTime.localDay == date.localDay
).count
)
}
func count(type: Workout.Type, exerciseID: Int64) -> Int {
typealias WS = Workset.Schema
return db.scalar(
WS.table
.select(WS.workoutID.distinct.count)
.filter(WS.exerciseID == exerciseID)
)
}
func countByDay(type: Workout.Type) throws -> [(NSDate, Int)] {
let cal = NSCalendar.currentCalendar()
let date = Workout.Schema.startTime
let count = Workout.Schema.workoutID.count
let rows = try db.prepare(
Workout.Schema.table.select(date, count).group(date.localDay))
return rows.map { row in
return (cal.startOfDayForDate(row[date]), row[count])
}
}
func create(type: Workout.Type, startDate: NSDate) throws -> Int64 {
typealias WO = Workout.Schema
return try db.run(
WO.table.insert(
WO.startTime <- startDate,
WO.sets <- 0,
WO.reps <- 0,
WO.duration <- 0,
WO.restDuration <- 0,
WO.activeDuration <- 0,
WO.avePercentMaxDuration <- 0,
WO.maxDuration <- 0,
WO.activation <- MuscleBook.ActivationLevel.Light))
}
func endDate(workout: Workout) -> NSDate? {
let row = db.pluck(Workset.Schema.table
.select(Workset.Schema.startTime.max)
.filter(Workset.Schema.workoutID == workout.workoutID)
.limit(1))
return row?[Workset.Schema.startTime.max]
}
func firstWorkoutDay() -> NSDate? {
typealias W = Workout.Schema
return db.scalar(W.table.select(W.startTime.min))
}
func get(type: Workout.Type, workoutID: Int64) -> Workout? {
return db.pluck(Workout.Schema.table.filter(Workout.Schema.workoutID == workoutID))
}
func getOrCreate(type: Workout.Type, input: Workset.Input) throws -> Int64 {
typealias WS = Workset.Schema
typealias WO = Workout.Schema
guard let lastWorkset: Workset = db.pluck(WS.table.order(WS.startTime.desc)) else {
return try create(Workout.self, startDate: input.startTime)
}
let diff = input.startTime.timeIntervalSinceDate(lastWorkset.input.startTime)
/* TODO: Inserting new worksets into the past is not supported right now */
guard diff > 0 else {
throw Error.CannotInsertWorkset
}
if diff < 3600 {
return lastWorkset.workoutID
} else {
return try create(Workout.self, startDate: input.startTime)
}
}
func lastWorkoutDay() -> NSDate? {
typealias W = Workout.Schema
return db.scalar(W.table.select(W.startTime.max))
}
func nextAvailableRowID(type: Workout.Type) -> Int64 {
typealias S = Workset.Schema
let max = db.scalar(S.table.select(S.workoutID.max))
return (max ?? 0) + 1
}
func next(workout: Workout) -> Workout? {
let date = Workset.Schema.startTime
return db.pluck(Workset.Schema.table
.order(date.asc)
.filter(date > workout.startTime)
.limit(1))
}
func prev(workout: Workout) -> Workout? {
typealias W = Workset.Schema
let date = W.startTime
return db.pluck(W.table
.order(date.desc)
.filter(date < workout.startTime)
.limit(1))
}
func recalculate(workoutID workoutID: Int64) throws {
typealias WS = Workset.Schema
guard let row = db.pluck(WS.table
.select(
WS.startTime.min,
WS.startTime.max,
WS.worksetID.count,
WS.reps.sum,
WS.volume.sum,
WS.duration.sum,
WS.duration.max,
WS.activation.max)
.filter(WS.workoutID == workoutID))
else { throw Error.RecalculateWorkoutFailed }
let averages = db.pluck(WS.table
.select(
WS.percentMaxVolume.average,
WS.percentMaxDuration.average,
WS.intensity.average)
.filter(
WS.workoutID == workoutID &&
WS.warmup == false))
guard let
startTime = row[WS.startTime.min],
endTime = row[WS.startTime.max]
else { throw Error.RecalculateWorkoutFailed }
let lastDuration = db.scalar(WS.table
.select(WS.duration)
.filter(WS.workoutID == workoutID)
.order(WS.startTime.desc)
.limit(1))
let avePcVolume = averages?[WS.percentMaxVolume.average]
let aveIntensity = averages?[WS.intensity.average]
let activeDuration = row[WS.duration.sum]
let duration: Double?
if let lastDuration = lastDuration {
duration = endTime.timeIntervalSinceDate(startTime) + lastDuration
assert(duration > 0)
} else {
duration = nil
}
let restDuration: Double?
if let duration = duration, activeDuration = activeDuration {
restDuration = duration - activeDuration
} else {
restDuration = nil
}
let activation: ActivationLevel
if let avePcVolume = avePcVolume, aveIntensity = aveIntensity {
activation = ActivationLevel(percent: max(aveIntensity, avePcVolume))
} else if let avePcVolume = avePcVolume {
activation = ActivationLevel(percent: avePcVolume)
} else if let aveIntensity = aveIntensity {
activation = ActivationLevel(percent: aveIntensity)
} else {
activation = .Light
}
typealias WO = Workout.Schema
try db.run(WO.table
.filter(WS.workoutID == workoutID)
.update(
WO.startTime <- startTime,
WO.sets <- row[WS.worksetID.count],
WO.reps <- (row[WS.reps.sum] ?? 0),
WO.duration <- duration,
WO.restDuration <- restDuration,
WO.activeDuration <- activeDuration,
WO.volume <- row[WS.volume.sum],
WO.avePercentMaxVolume <- avePcVolume,
WO.avePercentMaxDuration <- averages?[WS.percentMaxDuration.average],
WO.aveIntensity <- aveIntensity,
WO.maxDuration <- row[WS.duration.max],
WO.activation <- activation
)
)
}
func startDate(workout: Workout) -> NSDate? {
let row = db.pluck(Workset.Schema.table
.select(Workset.Schema.startTime.min)
.filter(Workset.Schema.workoutID == workout.workoutID)
.limit(1)
)
return row?[Workset.Schema.startTime.min]
}
func totalWorkouts(sinceDate date: NSDate) -> Int {
typealias W = Workset.Schema
return db.scalar(W.table
.select(W.workoutID.distinct.count)
.filter(W.startTime.localDay >= date)
)
}
}
| gpl-3.0 | a34dc88d944b4074509a85a2acf52b62 | 34.556017 | 91 | 0.583382 | 4.263184 | false | false | false | false |
karwa/swift-corelibs-foundation | Foundation/NSPersonNameComponents.swift | 3 | 4203 | // 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
//
public class NSPersonNameComponents : NSObject, NSCopying, NSSecureCoding {
public convenience required init?(coder aDecoder: NSCoder) {
self.init()
if aDecoder.allowsKeyedCoding {
self.namePrefix = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.namePrefix") as NSString?)?.bridge()
self.givenName = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.givenName") as NSString?)?.bridge()
self.middleName = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.middleName") as NSString?)?.bridge()
self.familyName = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.familyName") as NSString?)?.bridge()
self.nameSuffix = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.nameSuffix") as NSString?)?.bridge()
self.nickname = (aDecoder.decodeObjectOfClass(NSString.self, forKey: "NS.nickname") as NSString?)?.bridge()
} else {
self.namePrefix = (aDecoder.decodeObject() as? NSString)?.bridge()
self.givenName = (aDecoder.decodeObject() as? NSString)?.bridge()
self.middleName = (aDecoder.decodeObject() as? NSString)?.bridge()
self.familyName = (aDecoder.decodeObject() as? NSString)?.bridge()
self.nameSuffix = (aDecoder.decodeObject() as? NSString)?.bridge()
self.nickname = (aDecoder.decodeObject() as? NSString)?.bridge()
}
}
static public func supportsSecureCoding() -> Bool { return true }
public func encodeWithCoder(_ aCoder: NSCoder) {
if aCoder.allowsKeyedCoding {
aCoder.encodeObject(self.namePrefix?.bridge(), forKey: "NS.namePrefix")
aCoder.encodeObject(self.givenName?.bridge(), forKey: "NS.givenName")
aCoder.encodeObject(self.middleName?.bridge(), forKey: "NS.middleName")
aCoder.encodeObject(self.familyName?.bridge(), forKey: "NS.familyName")
aCoder.encodeObject(self.nameSuffix?.bridge(), forKey: "NS.nameSuffix")
aCoder.encodeObject(self.nickname?.bridge(), forKey: "NS.nickname")
} else {
// FIXME check order
aCoder.encodeObject(self.namePrefix?.bridge())
aCoder.encodeObject(self.givenName?.bridge())
aCoder.encodeObject(self.middleName?.bridge())
aCoder.encodeObject(self.familyName?.bridge())
aCoder.encodeObject(self.nameSuffix?.bridge())
aCoder.encodeObject(self.nickname?.bridge())
}
}
public func copyWithZone(_ zone: NSZone) -> AnyObject { NSUnimplemented() }
/* The below examples all assume the full name Dr. Johnathan Maple Appleseed Esq., nickname "Johnny" */
/* Pre-nominal letters denoting title, salutation, or honorific, e.g. Dr., Mr. */
public var namePrefix: String?
/* Name bestowed upon an individual by one's parents, e.g. Johnathan */
public var givenName: String?
/* Secondary given name chosen to differentiate those with the same first name, e.g. Maple */
public var middleName: String?
/* Name passed from one generation to another to indicate lineage, e.g. Appleseed */
public var familyName: String?
/* Post-nominal letters denoting degree, accreditation, or other honor, e.g. Esq., Jr., Ph.D. */
public var nameSuffix: String?
/* Name substituted for the purposes of familiarity, e.g. "Johnny"*/
public var nickname: String?
/* Each element of the phoneticRepresentation should correspond to an element of the original PersonNameComponents instance.
The phoneticRepresentation of the phoneticRepresentation object itself will be ignored. nil by default, must be instantiated.
*/
/*@NSCopying*/ public var phoneticRepresentation: NSPersonNameComponents?
}
| apache-2.0 | 7af11256d7eb7da4722d10a8229e3ab0 | 51.5375 | 132 | 0.674042 | 4.722472 | false | false | false | false |
devxoul/Drrrible | Drrrible/Sources/Services/AuthService.swift | 1 | 4501 | //
// AuthService.swift
// Drrrible
//
// Created by Suyeol Jeon on 08/03/2017.
// Copyright © 2017 Suyeol Jeon. All rights reserved.
//
import SafariServices
import URLNavigator
import Alamofire
import KeychainAccess
import RxSwift
protocol AuthServiceType {
var currentAccessToken: AccessToken? { get }
/// Start OAuth authorization process.
///
/// - returns: An Observable of `AccessToken` instance.
func authorize() -> Observable<Void>
/// Call this method when redirected from OAuth process to request access token.
///
/// - parameter code: `code` from redirected url.
func callback(code: String)
func logout()
}
final class AuthService: AuthServiceType {
fileprivate let clientID = "130182af71afe5247b857ef622bd344ca5f1c6144c8fa33c932628ac31c5ad78"
fileprivate let clientSecret = "bbebedc51c2301049c2cb57953efefc30dc305523b8fdfadb9e9a25cb81efa1e"
fileprivate var currentViewController: UIViewController?
fileprivate let callbackSubject = PublishSubject<String>()
fileprivate let keychain = Keychain(service: "com.drrrible.ios")
private(set) var currentAccessToken: AccessToken?
private let navigator: NavigatorType
init(navigator: NavigatorType) {
self.navigator = navigator
self.currentAccessToken = self.loadAccessToken()
log.debug("currentAccessToken exists: \(self.currentAccessToken != nil)")
}
func authorize() -> Observable<Void> {
let parameters: [String: String] = [
"client_id": self.clientID,
"scope": "public+write+comment+upload",
]
let parameterString = parameters.map { "\($0)=\($1)" }.joined(separator: "&")
let url = URL(string: "https://dribbble.com/oauth/authorize?\(parameterString)")!
// Default animation of presenting SFSafariViewController is similar to 'push' animation
// (from right to left). To use 'modal' animation (from bottom to top), we have to wrap
// SFSafariViewController with UINavigationController and set navigation bar hidden.
let safariViewController = SFSafariViewController(url: url)
let navigationController = UINavigationController(rootViewController: safariViewController)
navigationController.isNavigationBarHidden = true
self.navigator.present(navigationController)
self.currentViewController = navigationController
return self.callbackSubject
.flatMap(self.accessToken)
.do(onNext: { [weak self] accessToken in
try self?.saveAccessToken(accessToken)
self?.currentAccessToken = accessToken
})
.map { _ in }
}
func callback(code: String) {
self.callbackSubject.onNext(code)
self.currentViewController?.dismiss(animated: true, completion: nil)
self.currentViewController = nil
}
func logout() {
self.currentAccessToken = nil
self.deleteAccessToken()
}
fileprivate func accessToken(code: String) -> Single<AccessToken> {
let urlString = "https://dribbble.com/oauth/token"
let parameters: Parameters = [
"client_id": self.clientID,
"client_secret": self.clientSecret,
"code": code,
]
return Single.create { observer in
let request = AF
.request(urlString, method: .post, parameters: parameters)
.responseData { response in
switch response.result {
case let .success(jsonData):
do {
let accessToken = try JSONDecoder().decode(AccessToken.self, from: jsonData)
observer(.success(accessToken))
} catch let error {
observer(.error(error))
}
case let .failure(error):
observer(.error(error))
}
}
return Disposables.create {
request.cancel()
}
}
}
fileprivate func saveAccessToken(_ accessToken: AccessToken) throws {
try self.keychain.set(accessToken.accessToken, key: "access_token")
try self.keychain.set(accessToken.tokenType, key: "token_type")
try self.keychain.set(accessToken.scope, key: "scope")
}
fileprivate func loadAccessToken() -> AccessToken? {
guard let accessToken = self.keychain["access_token"],
let tokenType = self.keychain["token_type"],
let scope = self.keychain["scope"]
else { return nil }
return AccessToken(accessToken: accessToken, tokenType: tokenType, scope: scope)
}
fileprivate func deleteAccessToken() {
try? self.keychain.remove("access_token")
try? self.keychain.remove("token_type")
try? self.keychain.remove("scope")
}
}
| mit | 132707240a9779905e8ad07b4521f3e7 | 31.608696 | 99 | 0.694444 | 4.477612 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/LinearEquations/Projects/Main/MLinearEquationsProject.swift | 1 | 13806 | import UIKit
class MLinearEquationsProject
{
var rows:[MLinearEquationsProjectRow]
var project:DProject?
private weak var controller:CLinearEquationsProject?
init(project:DProject?)
{
rows = []
self.project = project
}
//MARK: private
private func loadFinished()
{
DispatchQueue.main.async
{ [weak self] in
self?.controller?.modelLoaded()
}
}
private func createProject()
{
DManager.sharedInstance?.createData(
entityName:DProject.entityName)
{ [weak self] (created) in
self?.project = created as? DProject
self?.project?.created = Date().timeIntervalSince1970
let defaultSymbol:String = NSLocalizedString("MLinearEquationsProject_defaultIndeterminate", comment:"")
self?.createIndeterminate(
symbol:defaultSymbol)
{ [weak self] in
self?.createRow()
}
}
}
private func createIndeterminate(
symbol:String,
completion:(() -> ())?)
{
DManager.sharedInstance?.createData(
entityName:DIndeterminate.entityName)
{ [weak self] (created) in
guard
let project:DProject = self?.project,
let indeterminate:DIndeterminate = created as? DIndeterminate
else
{
return
}
indeterminate.symbol = symbol
indeterminate.project = project
completion?()
}
}
private func createEquation(completion:(() -> ())?)
{
DManager.sharedInstance?.createData(
entityName:DEquation.entityName)
{ [weak self] (created) in
guard
let project:DProject = self?.project,
let indeterminatesArray:[DIndeterminate] = project.indeterminates?.array as? [DIndeterminate],
let equation:DEquation = created as? DEquation
else
{
return
}
equation.created = Date().timeIntervalSince1970
equation.project = project
self?.createPolynomials(
equation:equation,
indeterminates:indeterminatesArray,
completion:completion)
}
}
private func createPolynomials(
equation:DEquation,
indeterminates:[DIndeterminate],
completion:(() -> ())?)
{
DManager.sharedInstance?.createData(
entityName:DPolynomial.entityName)
{ [weak self] (created) in
guard
let polynomial:DPolynomial = created as? DPolynomial
else
{
return
}
if indeterminates.count > 0
{
var indeterminates:[DIndeterminate] = indeterminates
let indeterminate:DIndeterminate = indeterminates.removeFirst()
polynomial.indeterminate = indeterminate
polynomial.equationPolynomials = equation
self?.createPolynomials(
equation:equation,
indeterminates:indeterminates,
completion:completion)
}
else
{
self?.createResult(
equation:equation,
completion:completion)
}
}
}
private func createResult(
equation:DEquation,
completion:(() -> ())?)
{
DManager.sharedInstance?.createData(
entityName:DPolynomial.entityName)
{ (created) in
guard
let result:DPolynomial = created as? DPolynomial
else
{
return
}
result.equationResult = equation
completion?()
}
}
private func refreshRows()
{
guard
let project:DProject = self.project,
let equationSet:NSOrderedSet = project.equations,
let equationArray:[DEquation] = equationSet.array as? [DEquation]
else
{
return
}
var rows:[MLinearEquationsProjectRow] = []
for equation:DEquation in equationArray
{
let row:MLinearEquationsProjectRow = MLinearEquationsProjectRow(
equation:equation)
rows.append(row)
}
let lastRow:MLinearEquationsProjectRow = MLinearEquationsProjectRow.lastRow()
rows.append(lastRow)
self.rows = rows
loadFinished()
}
private func saveAndRefresh()
{
DManager.sharedInstance?.save
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.refreshRows()
}
}
}
private func compareResult(
equation:DEquation,
polynomial:DPolynomial,
result:DPolynomial)
{
if polynomial.indeterminate == result.indeterminate
{
guard
let inversedResult:DPolynomial = result.inversed()
else
{
return
}
polynomial.add(polynomial:inversedResult)
equation.restartResult()
}
}
private func comparePolynomials(
equation:DEquation,
polynomial:DPolynomial,
compare:DPolynomial)
{
if polynomial.indeterminate == compare.indeterminate
{
polynomial.add(polynomial:compare)
equation.deletePolynomial(polynomial:compare)
}
}
private func indeterminatesToLeft()
{
guard
let project:DProject = self.project,
let equations:[DEquation] = project.equations?.array as? [DEquation]
else
{
return
}
for equation:DEquation in equations
{
guard
let result:DPolynomial = equation.result
else
{
continue
}
if result.indeterminate != nil
{
equation.moveToLeft(polynomial:result)
}
}
}
private func constantsToRight()
{
guard
let project:DProject = self.project,
let equations:[DEquation] = project.equations?.array as? [DEquation]
else
{
return
}
for equation:DEquation in equations
{
guard
let polynomials:[DPolynomial] = equation.polynomials?.array as? [DPolynomial],
let result:DPolynomial = equation.result
else
{
continue
}
if result.indeterminate == nil
{
for polynomial:DPolynomial in polynomials
{
if polynomial.indeterminate == nil
{
equation.moveToRight(polynomial:polynomial)
}
}
}
}
}
private func addEverything()
{
guard
let project:DProject = self.project,
let equations:[DEquation] = project.equations?.array as? [DEquation]
else
{
return
}
for equation:DEquation in equations
{
guard
let polynomials:[DPolynomial] = equation.polynomials?.array as? [DPolynomial],
let result:DPolynomial = equation.result
else
{
continue
}
let countPolynomials:Int = polynomials.count
if countPolynomials > 1
{
for indexPolynomial:Int in 0 ..< countPolynomials
{
let polynomial:DPolynomial = polynomials[indexPolynomial]
for indexComparison:Int in indexPolynomial + 1 ..< countPolynomials
{
let comparePolynomial:DPolynomial = polynomials[indexComparison]
comparePolynomials(
equation:equation,
polynomial:polynomial,
compare:comparePolynomial)
}
compareResult(
equation:equation,
polynomial:polynomial,
result:result)
}
}
else if countPolynomials == 1
{
let polynomial:DPolynomial = polynomials[0]
compareResult(
equation:equation,
polynomial:polynomial,
result:result)
}
else
{
project.deleteEquation(equation:equation)
}
}
}
private func removeZeros()
{
guard
let project:DProject = self.project,
let equations:[DEquation] = project.equations?.array as? [DEquation]
else
{
return
}
for equation:DEquation in equations
{
guard
let polynomials:[DPolynomial] = equation.polynomials?.array as? [DPolynomial]
else
{
continue
}
var hasCoefficient:Bool = false
for polynomial:DPolynomial in polynomials
{
let coefficient:Double = polynomial.coefficient()
if coefficient != 0
{
hasCoefficient = true
break
}
}
if !hasCoefficient
{
project.deleteEquation(equation:equation)
}
}
}
//MARK: public
func load(controller:CLinearEquationsProject)
{
self.controller = controller
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
if self?.project == nil
{
self?.createProject()
}
else
{
self?.refreshRows()
}
}
}
func createPolynomial(equation:DEquation)
{
DManager.sharedInstance?.createData(
entityName:DPolynomial.entityName)
{ [weak self] (created) in
guard
let polynomial:DPolynomial = created as? DPolynomial
else
{
return
}
polynomial.equationPolynomials = equation
self?.saveAndRefresh()
}
}
func createRow()
{
createEquation
{ [weak self] in
self?.saveAndRefresh()
}
}
func addIndeterminate(
name:String,
completion:(() -> ())?)
{
createIndeterminate(symbol:name)
{
DManager.sharedInstance?.save()
completion?()
}
}
func removeIndeterminate(indeterminate:DIndeterminate)
{
project?.deleteIndeterminate(indeterminate:indeterminate)
saveAndRefresh()
}
func removeEquation(index:Int)
{
guard
let equation:DEquation = project?.equations?.array[index] as? DEquation
else
{
return
}
project?.deleteEquation(equation:equation)
saveAndRefresh()
}
func moveUp(index:Int)
{
guard
var equations:[DEquation] = project?.equations?.array as? [DEquation]
else
{
return
}
let equation:DEquation = equations[index]
equations.insert(equation, at:index - 1)
let orderedSet:NSOrderedSet = NSOrderedSet(array:equations)
project?.equations = orderedSet
saveAndRefresh()
}
func moveDown(index:Int)
{
guard
var equations:[DEquation] = project?.equations?.array as? [DEquation]
else
{
return
}
let equationBelow:DEquation = equations[index + 1]
equations.insert(equationBelow, at:index)
let orderedSet:NSOrderedSet = NSOrderedSet(array:equations)
project?.equations = orderedSet
saveAndRefresh()
}
func compress()
{
indeterminatesToLeft()
addEverything()
removeZeros()
constantsToRight()
saveAndRefresh()
}
}
| mit | 2d6d8fcea8f7ba7c7e566045ec21e627 | 24.66171 | 116 | 0.465377 | 5.98699 | false | false | false | false |
naocanfen/CDNY | cdny/cdny/Tools/common.swift | 1 | 1351 | //
// common.swift
// one
//
// Created by moon on 2017/7/17.
// Copyright © 2017年 moon. All rights reserved.
//
import Foundation
import UIKit
//16进制颜色
func RGBColorFromHex(rgbValue: Int) -> (UIColor) {
return UIColor(red: ((CGFloat)((rgbValue & 0xFF0000) >> 16)) / 255.0,
green: ((CGFloat)((rgbValue & 0xFF00) >> 8)) / 255.0,
blue: ((CGFloat)(rgbValue & 0xFF)) / 255.0,
alpha: 1.0)
}
//加载webview
func initWebview(view: UIView, weburl: String){
let webview = UIWebView(frame: view.bounds)
let url = URL(string: weburl)
let request = URLRequest(url: url!)
webview.loadRequest(request)
view.addSubview(webview)
}
//扩展uiview。 获取当前view
extension UIViewController {
class func currentViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return currentViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
return currentViewController(base: tab.selectedViewController)
}
if let presented = base?.presentedViewController {
return currentViewController(base: presented)
}
return base
}
}
| mit | 2879ee5cddb8d0442b226ed51048653f | 27.73913 | 137 | 0.640696 | 4.264516 | false | false | false | false |
tecgirl/firefox-ios | Client/Utils/FaviconFetcher.swift | 1 | 12400 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Storage
import Shared
import Alamofire
import XCGLogger
import Deferred
import SDWebImage
import Fuzi
import SwiftyJSON
private let log = Logger.browserLogger
private let queue = DispatchQueue(label: "FaviconFetcher", attributes: DispatchQueue.Attributes.concurrent)
class FaviconFetcherErrorType: MaybeErrorType {
let description: String
init(description: String) {
self.description = description
}
}
/* A helper class to find the favicon associated with a URL.
* This will load the page and parse any icons it finds out of it.
* If that fails, it will attempt to find a favicon.ico in the root host domain.
*/
open class FaviconFetcher: NSObject, XMLParserDelegate {
open static var userAgent: String = ""
static let ExpirationTime = TimeInterval(60*60*24*7) // Only check for icons once a week
fileprivate static var characterToFaviconCache = [String: UIImage]()
static var defaultFavicon: UIImage = {
return UIImage(named: "defaultFavicon")!
}()
static var colors: [String: UIColor] = [:] //An in-Memory data store that stores background colors domains. Stored using url.baseDomain.
// Sites can be accessed via their baseDomain.
static var defaultIcons: [String: (color: UIColor, url: String)] = {
return FaviconFetcher.getDefaultIcons()
}()
static let multiRegionDomains = ["craigslist", "google", "amazon"]
class func getDefaultIconForURL(url: URL) -> (color: UIColor, url: String)? {
// Problem: Sites like amazon exist with .ca/.de and many other tlds.
// Solution: They are stored in the default icons list as "amazon" instead of "amazon.com" this allows us to have favicons for every tld."
// Here, If the site is in the multiRegionDomain array look it up via its second level domain (amazon) instead of its baseDomain (amazon.com)
let hostName = url.hostSLD
if multiRegionDomains.contains(hostName), let icon = defaultIcons[hostName] {
return icon
}
if let name = url.baseDomain, let icon = defaultIcons[name] {
return icon
}
return nil
}
class func getForURL(_ url: URL, profile: Profile) -> Deferred<Maybe<[Favicon]>> {
let f = FaviconFetcher()
return f.loadFavicons(url, profile: profile)
}
fileprivate func loadFavicons(_ url: URL, profile: Profile, oldIcons: [Favicon] = [Favicon]()) -> Deferred<Maybe<[Favicon]>> {
if isIgnoredURL(url) {
return deferMaybe(FaviconFetcherErrorType(description: "Not fetching ignored URL to find favicons."))
}
let deferred = Deferred<Maybe<[Favicon]>>()
var oldIcons: [Favicon] = oldIcons
queue.async {
self.parseHTMLForFavicons(url).bind({ (result: Maybe<[Favicon]>) -> Deferred<[Maybe<Favicon>]> in
var deferreds = [Deferred<Maybe<Favicon>>]()
if let icons = result.successValue {
deferreds = icons.map { self.getFavicon(url, icon: $0, profile: profile) }
}
return all(deferreds)
}).bind({ (results: [Maybe<Favicon>]) -> Deferred<Maybe<[Favicon]>> in
for result in results {
if let icon = result.successValue {
oldIcons.append(icon)
}
}
oldIcons = oldIcons.sorted {
return $0.width! > $1.width!
}
return deferMaybe(oldIcons)
}).upon({ (result: Maybe<[Favicon]>) in
deferred.fill(result)
return
})
}
return deferred
}
lazy fileprivate var alamofire: SessionManager = {
let configuration = URLSessionConfiguration.default
var defaultHeaders = SessionManager.default.session.configuration.httpAdditionalHeaders ?? [:]
defaultHeaders["User-Agent"] = FaviconFetcher.userAgent
configuration.httpAdditionalHeaders = defaultHeaders
configuration.timeoutIntervalForRequest = 5
return SessionManager(configuration: configuration)
}()
fileprivate func fetchDataForURL(_ url: URL) -> Deferred<Maybe<Data>> {
let deferred = Deferred<Maybe<Data>>()
alamofire.request(url).response { response in
// Don't cancel requests just because our Manager is deallocated.
withExtendedLifetime(self.alamofire) {
if response.error == nil {
if let data = response.data {
deferred.fill(Maybe(success: data))
return
}
}
let errorDescription = (response.error as NSError?)?.description ?? "No content."
deferred.fill(Maybe(failure: FaviconFetcherErrorType(description: errorDescription)))
}
}
return deferred
}
// Loads and parses an html document and tries to find any known favicon-type tags for the page
fileprivate func parseHTMLForFavicons(_ url: URL) -> Deferred<Maybe<[Favicon]>> {
return fetchDataForURL(url).bind({ result -> Deferred<Maybe<[Favicon]>> in
var icons = [Favicon]()
guard let data = result.successValue, result.isSuccess,
let root = try? HTMLDocument(data: data as Data) else {
return deferMaybe([])
}
var reloadUrl: URL? = nil
for meta in root.xpath("//head/meta") {
if let refresh = meta["http-equiv"], refresh == "Refresh",
let content = meta["content"],
let index = content.range(of: "URL="),
let url = NSURL(string: content.substring(from: index.upperBound)) {
reloadUrl = url as URL
}
}
if let url = reloadUrl {
return self.parseHTMLForFavicons(url)
}
for link in root.xpath("//head//link[contains(@rel, 'icon')]") {
guard let href = link["href"] else {
continue //Skip the rest of the loop. But don't stop the loop
}
if let iconUrl = NSURL(string: href, relativeTo: url as URL), let absoluteString = iconUrl.absoluteString {
let icon = Favicon(url: absoluteString)
icons = [icon]
}
// If we haven't got any options icons, then use the default at the root of the domain.
if let url = NSURL(string: "/favicon.ico", relativeTo: url as URL), icons.isEmpty, let absoluteString = url.absoluteString {
let icon = Favicon(url: absoluteString)
icons = [icon]
}
}
return deferMaybe(icons)
})
}
func getFavicon(_ siteUrl: URL, icon: Favicon, profile: Profile) -> Deferred<Maybe<Favicon>> {
let deferred = Deferred<Maybe<Favicon>>()
let url = icon.url
let manager = SDWebImageManager.shared()
let site = Site(url: siteUrl.absoluteString, title: "")
var fav = Favicon(url: url)
if let url = url.asURL {
var fetch: SDWebImageOperation?
fetch = manager.loadImage(with: url,
options: .lowPriority,
progress: { (receivedSize, expectedSize, _) in
if receivedSize > FaviconHandler.MaximumFaviconSize || expectedSize > FaviconHandler.MaximumFaviconSize {
fetch?.cancel()
}
},
completed: { (img, _, _, _, _, url) in
guard let url = url else {
deferred.fill(Maybe(failure: FaviconError()))
return
}
fav = Favicon(url: url.absoluteString)
if let img = img {
fav.width = Int(img.size.width)
fav.height = Int(img.size.height)
profile.favicons.addFavicon(fav, forSite: site)
} else {
fav.width = 0
fav.height = 0
}
deferred.fill(Maybe(success: fav))
})
} else {
return deferMaybe(FaviconFetcherErrorType(description: "Invalid URL \(url)"))
}
return deferred
}
// Returns a single Favicon UIImage for a given URL
class func fetchFavImageForURL(forURL url: URL, profile: Profile) -> Deferred<Maybe<UIImage>> {
let deferred = Deferred<Maybe<UIImage>>()
FaviconFetcher.getForURL(url.domainURL, profile: profile).uponQueue(.main) { result in
var iconURL: URL?
if let favicons = result.successValue, favicons.count > 0, let faviconImageURL = favicons.first?.url.asURL {
iconURL = faviconImageURL
} else {
return deferred.fill(Maybe(failure: FaviconError()))
}
SDWebImageManager.shared().loadImage(with: iconURL, options: .continueInBackground, progress: nil) { (image, _, _, _, _, _) in
if let image = image {
deferred.fill(Maybe(success: image))
} else {
deferred.fill(Maybe(failure: FaviconError()))
}
}
}
return deferred
}
// Returns the default favicon for a site based on the first letter of the site's domain
class func getDefaultFavicon(_ url: URL) -> UIImage {
guard let character = url.baseDomain?.first else {
return defaultFavicon
}
let faviconLetter = String(character).uppercased()
if let cachedFavicon = characterToFaviconCache[faviconLetter] {
return cachedFavicon
}
var faviconImage = UIImage()
let faviconLabel = UILabel(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
faviconLabel.text = faviconLetter
faviconLabel.textAlignment = .center
faviconLabel.font = UIFont.systemFont(ofSize: 40, weight: UIFont.Weight.medium)
faviconLabel.textColor = UIColor.Photon.White100
UIGraphicsBeginImageContextWithOptions(faviconLabel.bounds.size, false, 0.0)
faviconLabel.layer.render(in: UIGraphicsGetCurrentContext()!)
faviconImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
characterToFaviconCache[faviconLetter] = faviconImage
return faviconImage
}
// Returns a color based on the url's hash
class func getDefaultColor(_ url: URL) -> UIColor {
guard let hash = url.baseDomain?.hashValue else {
return UIColor.Photon.Grey50
}
let index = abs(hash) % (UIConstants.DefaultColorStrings.count - 1)
let colorHex = UIConstants.DefaultColorStrings[index]
return UIColor(colorString: colorHex)
}
// Default favicons and background colors provided via mozilla/tippy-top-sites
class func getDefaultIcons() -> [String: (color: UIColor, url: String)] {
let filePath = Bundle.main.path(forResource: "top_sites", ofType: "json")
let file = try! Data(contentsOf: URL(fileURLWithPath: filePath!))
let json = JSON(file)
var icons: [String: (color: UIColor, url: String)] = [:]
json.forEach({
guard let url = $0.1["domain"].string, let color = $0.1["background_color"].string, var path = $0.1["image_url"].string else {
return
}
path = path.replacingOccurrences(of: ".png", with: "")
let filePath = Bundle.main.path(forResource: "TopSites/" + path, ofType: "png")
if let filePath = filePath {
if color == "#fff" || color == "#FFF" {
icons[url] = (UIColor.clear, filePath)
} else {
icons[url] = (UIColor(colorString: color.replacingOccurrences(of: "#", with: "")), filePath)
}
}
})
return icons
}
}
| mpl-2.0 | f6fa7f2f94bf9e12b55dab31b7221d83 | 41.320819 | 149 | 0.582823 | 4.987932 | false | false | false | false |
ixx1232/FoodTrackerStudy | FoodTracker/FoodTracker/Meal.swift | 1 | 1715 | //
// Meal.swift
// FoodTracker
//
// Created by apple on 15/12/24.
// Copyright © 2015年 www.ixx.com. All rights reserved.
//
import UIKit
class Meal: NSObject, NSCoding {
// MARK: Properties
// MARK: Archiving Paths
static let DocumentsDirectory = NSFileManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).first!
static let ArchiveURL = DocumentsDirectory.URLByAppendingPathComponent("meals")
// MARK: Types
struct PropertyKey {
static let nameKey = "name"
static let photoKey = "photo"
static let ratingKey = "rating"
}
var name: String
var photo : UIImage?
var rating: Int
// MARK: Initialization
init?(name: String, photo: UIImage?, rating: Int) {
self.name = name
self.photo = photo
self.rating = rating
super.init()
if name.isEmpty || rating < 0 {
return nil
}
}
// MARK: NSCoding
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: PropertyKey.nameKey)
aCoder.encodeObject(photo, forKey: PropertyKey.photoKey)
aCoder.encodeInteger(rating, forKey: PropertyKey.ratingKey)
}
required convenience init?(coder aDecoder: NSCoder) {
let name = aDecoder.decodeObjectForKey(PropertyKey.nameKey) as! String
let photo = aDecoder.decodeObjectForKey(PropertyKey.photoKey) as? UIImage
let rating = aDecoder.decodeIntegerForKey(PropertyKey.ratingKey)
self.init(name: name, photo: photo, rating: rating)
}
}
| mit | 88529d683b46824672801ee6d1920ff7 | 26.612903 | 166 | 0.627921 | 4.891429 | false | false | false | false |
someoneAnyone/Nightscouter | Nightscouter/SiteDetailViewController.swift | 1 | 12248 | //
// ViewController.swift
// Nightscout
//
// Created by Peter Ina on 5/14/15.
// Copyright (c) 2015 Peter Ina. All rights reserved.
//
import UIKit
import NightscouterKit
import WebKit
class SiteDetailViewController: UIViewController, WKNavigationDelegate, AlarmStuff {
// MARK: IBOutlets
@IBOutlet weak var siteCompassControl: CompassControl?
@IBOutlet weak var siteLastReadingHeader: UILabel?
@IBOutlet weak var siteLastReadingLabel: UILabel?
@IBOutlet weak var siteBatteryHeader: UILabel?
@IBOutlet weak var siteBatteryLabel: UILabel?
@IBOutlet weak var siteRawHeader: UILabel?
@IBOutlet weak var siteRawLabel: UILabel?
@IBOutlet weak var siteNameLabel: UILabel?
@IBOutlet weak var siteWebView: WKWebView?
@IBOutlet weak var siteActivityView: UIActivityIndicatorView?
@IBOutlet fileprivate weak var snoozeAlarmButton: UIBarButtonItem!
@IBOutlet fileprivate weak var headerView: BannerMessage?
// MARK: Properties
var site: Site? {
didSet {
guard let site = site else {
return
}
configureView(withSite: site)
}
}
var data = [AnyObject]() {
didSet {
loadWebView()
}
}
var timer: Timer?
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// remove any uneeded decorations from this view if contained within a UI page view controller
if let _ = parent as? UIPageViewController {
// println("contained in UIPageViewController")
self.view.backgroundColor = UIColor.clear
self.siteNameLabel?.removeFromSuperview()
}
configureView()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
self.siteWebView?.reload()
}
override var preferredStatusBarStyle : UIStatusBarStyle {
return .lightContent
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
UIApplication.shared.isIdleTimerDisabled = false
}
}
// MARK: WebKit WebView Delegates
extension SiteDetailViewController {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print(">>> Entering \(#function) <<<")
let updateData = """
updateData(\(self.data))
"""
if let configuration = site?.configuration {
let updateUnits = """
updateUnits(\(configuration.displayUnits))
"""
webView.evaluateJavaScript(updateUnits, completionHandler: nil)
}
webView.evaluateJavaScript(updateData, completionHandler: nil)
siteActivityView?.stopAnimating()
}
}
extension SiteDetailViewController {
func configureView() {
headerView?.isHidden = true
self.siteCompassControl?.color = NSAssetKit.predefinedNeutralColor
if let siteOptional = site {
UIApplication.shared.isIdleTimerDisabled = siteOptional.overrideScreenLock
} else {
site = SitesDataSource.sharedInstance.sites[SitesDataSource.sharedInstance.lastViewedSiteIndex]
}
if #available(iOS 10.0, *) {
self.timer = Timer.scheduledTimer(withTimeInterval: TimeInterval.OneMinute, repeats: true, block: { (timer) in
DispatchQueue.main.async {
self.updateUI()
}
})
} else {
self.timer = Timer.scheduledTimer(timeInterval: TimeInterval.OneMinute, target: self, selector: #selector(SiteListTableViewController.updateUI), userInfo: nil, repeats: true)
}
setupNotifications()
updateData()
}
func setupNotifications() {
// Listen for global update timer.
NotificationCenter.default.addObserver(self, selector: #selector(updateSite(_:)), name: .nightscoutDataStaleNotification, object: nil)
NotificationCenter.default.addObserver(forName: .nightscoutAlarmNotification, object: nil, queue: .main) { (notif) in
if (notif.object as? AlarmObject) != nil {
self.updateUI()
}
}
//NotificationCenter.default.addObserver(self, selector: #selector(SiteListTableViewController.updateData), name: .NightscoutDataUpdatedNotification, object: nil)
}
@objc func updateSite(_ notification: Notification?) {
print(">>> Entering \(#function) <<<")
self.updateData()
}
func updateData() {
guard let site = self.site else { return }
UIApplication.shared.isNetworkActivityIndicatorVisible = true
self.siteActivityView?.startAnimating()
site.fetchDataFromNetwork() { (updatedSite, err) in
if let _ = err {
DispatchQueue.main.async {
// self.presentAlertDialog(site.url, index: index, error: error.kind.description)
}
return
}
SitesDataSource.sharedInstance.updateSite(updatedSite)
self.site = updatedSite
DispatchQueue.main.async {
UIApplication.shared.isNetworkActivityIndicatorVisible = false
self.siteActivityView?.stopAnimating()
self.updateUI()
}
}
}
func updateUI() {
guard let site = site else {
return
}
configureView(withSite: site)
}
@IBAction func unwindToSiteDetail(_ segue:UIStoryboardSegue) {
// print(">>> Entering \(#function) <<<")
// print("\(segue)")
}
@IBAction func manageAlarm(_ sender: AnyObject?) {
presentSnoozePopup(forViewController: self)
}
@IBAction func gotoSiteSettings(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: LocalizedString.uiAlertScreenOverrideTitle.localized, message: LocalizedString.uiAlertScreenOverrideMessage.localized, preferredStyle: .actionSheet)
let cancelAction = UIAlertAction(title: LocalizedString.generalCancelLabel.localized, style: .cancel) { (action) in
#if DEBUG
print("Canceled action: \(action)")
#endif
}
alertController.addAction(cancelAction)
let checkEmoji = "✓ "
var yesString = " "
if site?.overrideScreenLock == true {
yesString = checkEmoji
}
let yesAction = UIAlertAction(title: "\(yesString)\(LocalizedString.generalYesLabel.localized)", style: .default) { (action) -> Void in
self.updateScreenOverride(true)
#if DEBUG
print("Yes action: \(action)")
#endif
}
alertController.addAction(yesAction)
alertController.preferredAction = yesAction
var noString = " "
if (site!.overrideScreenLock == false) {
noString = checkEmoji
}
let noAction = UIAlertAction(title: "\(noString)\(LocalizedString.generalNoLabel.localized)", style: .destructive) { (action) -> Void in
self.updateScreenOverride(false)
#if DEBUG
print("No action: \(action)")
#endif
}
alertController.addAction(noAction)
alertController.view.tintColor = NSAssetKit.darkNavColor
self.view.window?.tintColor = nil
if let popoverController = alertController.popoverPresentationController {
popoverController.barButtonItem = sender
}
self.present(alertController, animated: true) {
#if DEBUG
print("presentViewController: \(alertController.debugDescription)")
#endif
}
}
}
extension SiteDetailViewController {
func configureView(withSite site: Site) {
UIApplication.shared.isIdleTimerDisabled = site.overrideScreenLock
let dataSource = site.summaryViewModel
siteLastReadingLabel?.text = dataSource.lastReadingDate.timeAgoSinceNow
siteLastReadingLabel?.textColor = dataSource.lastReadingColor
siteBatteryHeader?.isHidden = dataSource.batteryHidden
siteBatteryLabel?.isHidden = dataSource.batteryHidden
siteBatteryLabel?.text = dataSource.batteryLabel
siteBatteryLabel?.textColor = dataSource.batteryColor
siteRawLabel?.isHidden = dataSource.rawHidden
siteRawHeader?.isHidden = dataSource.rawHidden
siteRawLabel?.text = dataSource.rawFormatedLabel
siteRawLabel?.textColor = dataSource.rawColor
siteNameLabel?.text = dataSource.nameLabel
siteCompassControl?.configure(withDataSource: dataSource, delegate: dataSource)
self.updateTitles(dataSource.nameLabel)
data = site.sgvs.map{ $0.jsonForChart as AnyObject }
snoozeAlarmButton.isEnabled = false
if let alarmObject = alarmObject {
if alarmObject.warning == true || alarmObject.isSnoozed {
let activeColor = alarmObject.urgent ? NSAssetKit.predefinedAlertColor : NSAssetKit.predefinedWarningColor
self.snoozeAlarmButton.isEnabled = true
self.snoozeAlarmButton.tintColor = activeColor
if alarmObject.isSnoozed {
self.snoozeAlarmButton.image = #imageLiteral(resourceName: "alarmSliencedIcon")
}
if let headerView = self.headerView {
headerView.isHidden = false
headerView.tintColor = activeColor
headerView.message = AlarmRule.isSnoozed ? alarmObject.snoozeText : LocalizedString.generalAlarmMessage.localized
}
} else if alarmObject.warning == false && !alarmObject.isSnoozed {
self.snoozeAlarmButton.isEnabled = false
self.snoozeAlarmButton.tintColor = nil
} else {
self.snoozeAlarmButton.image = #imageLiteral(resourceName: "alarmIcon")
}
} else {
self.snoozeAlarmButton.image = #imageLiteral(resourceName: "alarmIcon")
self.snoozeAlarmButton.isEnabled = false
self.snoozeAlarmButton.tintColor = nil
self.headerView?.isHidden = true
}
self.siteWebView?.reload()
}
func updateTitles(_ title: String) {
self.navigationItem.title = title
self.navigationController?.navigationItem.title = title
self.siteNameLabel?.text = title
}
func loadWebView () {
self.siteWebView?.navigationDelegate = self
self.siteWebView?.scrollView.bounces = false
self.siteWebView?.scrollView.isScrollEnabled = false
self.siteWebView?.isOpaque = false
let filePath = Bundle.main.path(forResource: "index", ofType: "html", inDirectory: "html")
let defaultDBPath = "\(String(describing: Bundle.main.resourcePath))\\html"
let fileExists = FileManager.default.fileExists(atPath: filePath!)
if !fileExists {
do {
try FileManager.default.copyItem(atPath: defaultDBPath, toPath: filePath!)
} catch _ {
}
}
let request = URLRequest(url: URL(fileURLWithPath: filePath!))
self.siteWebView?.load(request)
}
func updateScreenOverride(_ shouldOverride: Bool) {
self.site?.overrideScreenLock = shouldOverride
SitesDataSource.sharedInstance.updateSite(self.site!)
UIApplication.shared.isIdleTimerDisabled = site?.overrideScreenLock ?? false
}
}
| mit | 03e34e0d83e730a2f7da73ba26046602 | 34.495652 | 203 | 0.617916 | 5.496409 | false | false | false | false |
sozorogami/SackOfRainbows | SackOfRainbowsTests/SackOfRainbowsTests.swift | 1 | 9449 | import Quick
import Nimble
import SackOfRainbows
extension ColorGenerator {
mutating func repeats(period period: Int, times: Int) -> Bool {
var timesRemaining = times - 1
var firstColors: [UIColor] = []
for _ in 0..<period {
if let color = next() {
firstColors.append(color)
} else {
return false
}
}
while timesRemaining > 0 {
for color in firstColors {
if let testColor = next() {
if !color.isEqual(testColor) {
return false
}
} else {
return false
}
}
timesRemaining--
}
return true;
}
}
class SackOfRainbowsTests: QuickSpec {
override func spec() {
describe("Sack of rainbows") {
describe("theColor") {
it("generates a color once") {
var redColor = theColor(red)
expect{redColor.next()}.to(equal(red))
expect{redColor.next()}.to(beNil())
}
context("when it is set to run a particular number of times") {
it("generates the color that many times") {
var tripleRed = theColor(red).times(3)
expect{tripleRed.next()}.to(equal(red))
expect{tripleRed.next()}.to(equal(red))
expect{tripleRed.next()}.to(equal(red))
expect{tripleRed.next()}.to(beNil())
}
}
context("when it is set to run forever") {
it("generates the same color endlessly") {
var infiniteRed = theColor(red).times(20)
let repeatsIndefinitely = infiniteRed.repeats(period: 1, times: 20)
expect(repeatsIndefinitely).to(beTrue())
}
}
}
describe("theColors") {
context("when given a single color") {
it("creates a single color generator") {
var oneColor = theColors(gray) as! SingleColorGen
expect(oneColor.next()).to(equal(gray))
expect(oneColor.next()).to(beNil())
}
}
context("when given multiple colors") {
it("chains them as generators in sequence") {
var newspaper = theColors(black, white, red) as! SerialColorGen
expect(newspaper.next()).to(equal(black))
expect(newspaper.next()).to(equal(white))
expect(newspaper.next()).to(equal(red))
expect(newspaper.next()).to(beNil())
}
}
}
describe("then") {
it("chains two generators in sequence") {
var redThenBlue = theColor(red).then(theColor(blue))
expect(redThenBlue.next()).to(equal(red))
expect(redThenBlue.next()).to(equal(blue))
expect(redThenBlue.next()).to(beNil())
}
context("when the first generator runs multiple times") {
it("runs until empty, then moves to the second") {
var red2thenBlue = theColor(red).times(2).then(theColor(blue))
expect(red2thenBlue.next()).to(equal(red))
expect(red2thenBlue.next()).to(equal(red))
expect(red2thenBlue.next()).to(equal(blue))
expect(red2thenBlue.next()).to(beNil())
}
}
context("when it is set to run a particular number of times") {
it("runs that many times, then returns nil") {
var redThenBlueFiveTimes = theColor(red).then(theColor(blue)).times(5)
let repeatsFiveTimes = redThenBlueFiveTimes.repeats(period: 2, times: 5)
expect(repeatsFiveTimes).to(beTrue())
expect(redThenBlueFiveTimes.next()).to(beNil())
}
}
context("when it is set to run forever") {
it("returns the generators in sequence forever") {
var redThenBlueForever = theColor(red).then(theColor(blue)).forever()
let repeatsForever = redThenBlueForever.repeats(period: 2, times: 25)
expect(repeatsForever).to(beTrue())
}
}
}
describe("alternate") {
it("chains multiple generators in paralell") {
let red2 = theColor(red).times(2)
let white2 = theColor(white).times(2)
let blue2 = theColor(blue).times(2)
var usa = alternate(red2, white2, blue2)
expect(usa.next()).to(equal(red))
expect(usa.next()).to(equal(white))
expect(usa.next()).to(equal(blue))
expect(usa.next()).to(equal(red))
expect(usa.next()).to(equal(white))
expect(usa.next()).to(equal(blue))
expect(usa.next()).to(beNil())
}
context("when it is set to run a particular number of times") {
it("runs that many times, then returns nil") {
let red2 = theColor(red).times(2)
let white2 = theColor(white).times(2)
let blue2 = theColor(blue).times(2)
var uk = alternate(red2, white2, blue2).times(2)
let repeatsTwice = uk.repeats(period: 6, times: 2)
expect(repeatsTwice).to(beTrue())
expect(uk.next()).to(beNil())
}
}
context("when a generator runs out of colors") {
it("skips it") {
let threeReds = theColors(red, red, red)
let twoBlues = theColors(blue, blue)
let oneYellow = theColor(yellow)
var alternator = alternate(threeReds, twoBlues, oneYellow)
expect(alternator.next()).to(equal(red))
expect(alternator.next()).to(equal(blue))
expect(alternator.next()).to(equal(yellow))
expect(alternator.next()).to(equal(red))
expect(alternator.next()).to(equal(blue))
expect(alternator.next()).to(equal(red))
expect(alternator.next()).to(beNil())
}
}
context("when it is set to run forever") {
it("alternates through the generators indefinitely") {
let threeReds = theColors(red, red, red)
var alternator = alternate(threeReds, theColor(orange)).forever()
expect(alternator.repeats(period: 4, times: 25)).to(beTrue())
}
}
}
describe("gradients") {
let midwayColor = UIColor(red: 0.5, green: 0.0, blue: 0.5, alpha: 1)
it("generates colors in a gradient between the start and end color") {
var aGradient = gradient().from(red).to(blue).steps(3)
let firstColor = aGradient.next()
let secondColor = aGradient.next()
let thirdColor = aGradient.next()
expect(firstColor).to(equal(red))
expect(secondColor).to(equal(midwayColor))
expect(thirdColor).to(equal(blue))
}
context("when there is one step to the gradient") {
it("returns the start color") {
var barelyAGradient = gradient().from(red).to(blue).steps(1)
expect(barelyAGradient.next()).to(equal(red))
expect(barelyAGradient.next()).to(beNil())
}
}
context("when it is set to run a particular number of times") {
it("repeats that many times, then returns nil") {
var repeatingGradient = gradient().from(red).to(blue).steps(3).times(5)
let repeatsFiveTimes = repeatingGradient.repeats(period: 3, times: 5)
expect(repeatsFiveTimes).to(beTrue())
expect(repeatingGradient.next()).to(beNil())
}
}
context("when it is set to run forever") {
it("repeats the gradient forever") {
var foreverGradient = gradient().from(red).to(blue).steps(3).forever()
let repeatsForever = foreverGradient.repeats(period: 3, times: 30)
expect(repeatsForever).to(beTrue())
}
}
}
}
}
}
| mit | 8aea2f88db4b2e4c7c6c8a227a780566 | 43.781991 | 96 | 0.462059 | 4.98365 | false | false | false | false |
velvetroom/columbus | Source/View/Plans/VPlansList.swift | 1 | 2922 | import UIKit
final class VPlansList:VCollection<
ArchPlans,
VPlansListCell>
{
private var cellSize:CGSize?
required init(controller:CPlans)
{
super.init(controller:controller)
config()
}
required init?(coder:NSCoder)
{
return nil
}
override func collectionView(
_ collectionView:UICollectionView,
numberOfItemsInSection section:Int) -> Int
{
guard
let count:Int = controller.model.plans?.count
else
{
return 0
}
return count
}
override func collectionView(
_ collectionView:UICollectionView,
layout collectionViewLayout:UICollectionViewLayout,
referenceSizeForHeaderInSection section:Int) -> CGSize
{
let count:Int = collectionView.numberOfItems(inSection:section)
guard
count > 0
else
{
let size:CGSize = CGSize(
width:0,
height:VPlansList.Constants.headerHeight)
return size
}
return CGSize.zero
}
override func collectionView(
_ collectionView:UICollectionView,
layout collectionViewLayout:UICollectionViewLayout,
sizeForItemAt indexPath:IndexPath) -> CGSize
{
guard
let cellSize:CGSize = self.cellSize
else
{
let width:CGFloat = collectionView.bounds.width
let cellSize:CGSize = CGSize(
width:width,
height:VPlansList.Constants.cellHeight)
self.cellSize = cellSize
return cellSize
}
return cellSize
}
override func collectionView(
_ collectionView:UICollectionView,
viewForSupplementaryElementOfKind kind:String,
at indexPath:IndexPath) -> UICollectionReusableView
{
let header:VPlansListHeader = reusableAtIndex(
kind:kind,
indexPath:indexPath)
return header
}
override func collectionView(
_ collectionView:UICollectionView,
cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:DPlan = modelAtIndex(index:indexPath)
let active:Bool = modelIsActive(model:item)
let cell:VPlansListCell = cellAtIndex(indexPath:indexPath)
cell.config(
controller:controller,
model:item,
active:active)
return cell
}
override func collectionView(
_ collectionView:UICollectionView,
didSelectItemAt indexPath:IndexPath)
{
let item:DPlan = modelAtIndex(index:indexPath)
controller.showDetail(plan:item)
}
}
| mit | 7c8478b3f09ae52a43c0c12f68219091 | 23.35 | 71 | 0.564339 | 5.95112 | false | false | false | false |
nkirby/Humber | _lib/HMGithub/_src/Types/GithubOverviewItemThreshold.swift | 1 | 492 | // =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import HMCore
// =======================================================
public class GithubOverviewItemThreshold: NSObject {
public static func stringValue(threshold threshold: Int) -> String {
if threshold < 0 {
return "None"
} else {
return "\(threshold)"
}
}
}
| mit | e352206fafe3a38c42ef220472773d49 | 23.6 | 72 | 0.388211 | 6.38961 | false | false | false | false |
StartAppsPe/StartAppsKitExtensions | Sources/NumberExtensions.swift | 1 | 3398 | //
// NumberExtensions.swift
// StartAppsKit
//
// Created by Gabriel Lanata on 6/15/15.
// Copyright (c) 2015 StartApps. All rights reserved.
//
import Foundation
public func clamped<T>(_ value: T, _ range: ClosedRange<T>) -> T {
return range.lowerBound > value ? range.lowerBound
: range.upperBound < value ? range.upperBound
: value
}
/********************************************************************************************************/
// MARK: Bool Extensions
/********************************************************************************************************/
extension Bool {
public func toggled() -> Bool {
return !self
}
}
/********************************************************************************************************/
// MARK: Int Extensions
/********************************************************************************************************/
extension Int {
public init?(string: String) {
let nan = NSDecimalNumber.notANumber
let decimal = NSDecimalNumber(string: string)
guard decimal != nan else { return nil }
self = decimal.intValue
}
public func nonZero() -> Int? {
return (self != 0 ? self : nil)
}
}
/********************************************************************************************************/
// MARK: NSDecimalNumber Extensions
/********************************************************************************************************/
extension NSDecimalNumber {
public convenience init?(fromString: String) {
let nan = NSDecimalNumber.notANumber
let decimal = NSDecimalNumber(string: fromString)
guard decimal != nan else { return nil }
self.init(string: fromString)
}
public var twoDecimalString: String {
let numberFormatter = NumberFormatter()
numberFormatter.minimumIntegerDigits = 1
numberFormatter.minimumFractionDigits = 2
numberFormatter.maximumFractionDigits = 2
numberFormatter.usesGroupingSeparator = true
return numberFormatter.string(from: self)!
}
}
extension NSDecimalNumber: Comparable {}
public func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedSame
}
public func +=(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.adding(rhs)
}
public func -=(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.subtracting(rhs)
}
public func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.adding(rhs)
}
public func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.subtracting(rhs)
}
public func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.multiplying(by: rhs)
}
public func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.dividing(by: rhs)
}
public func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber {
return lhs.raising(toPower: rhs)
}
public func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
public prefix func -(value: NSDecimalNumber) -> NSDecimalNumber {
return value.multiplying(by: NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true))
}
| mit | cd6ab34fa3b34b248ec66e8c6370612b | 29.339286 | 107 | 0.547675 | 5.284603 | false | false | false | false |
qiscus/qiscus-sdk-ios | Qiscus/Qiscus/View/QChatCell/QCellAudio.swift | 1 | 1381 | //
// QCellAudio.swift
// QiscusSDK
//
// Created by Ahmad Athaullah on 1/6/17.
// Copyright © 2017 Ahmad Athaullah. All rights reserved.
//
import UIKit
protocol ChatCellAudioDelegate {
func didTapPlayButton(_ button: UIButton, onCell cell: QCellAudio)
func didTapPauseButton(_ button: UIButton, onCell cell: QCellAudio)
func didTapDownloadButton(_ button: UIButton, onCell cell: QCellAudio)
func didStartSeekTimeSlider(_ slider: UISlider, onCell cell: QCellAudio)
func didEndSeekTimeSlider(_ slider: UISlider, onCell cell: QCellAudio)
}
class QCellAudio: QChatCell {
var audioCellDelegate: ChatCellAudioDelegate?
var _timeFormatter: DateComponentsFormatter?
var currentTime = TimeInterval()
var timeFormatter: DateComponentsFormatter? {
get {
if _timeFormatter == nil {
_timeFormatter = DateComponentsFormatter()
_timeFormatter?.zeroFormattingBehavior = .pad;
_timeFormatter?.allowedUnits = [.minute, .second]
_timeFormatter?.unitsStyle = .positional;
}
return _timeFormatter
}
set {
_timeFormatter = newValue
}
}
open func displayAudioDownloading(){
}
open func updateAudioDisplay(withTimeInterval timeInterval:TimeInterval){
}
}
| mit | 00789e4dda0403381a0539f1358f7ff4 | 29.666667 | 77 | 0.649275 | 4.842105 | false | false | false | false |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Renderers/RadarChartRenderer.swift | 19 | 13239 | //
// RadarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class RadarChartRenderer: LineRadarRenderer
{
open weak var chart: RadarChartView?
public init(chart: RadarChartView?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.chart = chart
}
open override func drawData(context: CGContext)
{
guard let chart = chart else { return }
let radarData = chart.data
if radarData != nil
{
let mostEntries = radarData?.maxEntryCountSet?.entryCount ?? 0
for set in radarData!.dataSets as! [IRadarChartDataSet]
{
if set.isVisible
{
drawDataSet(context: context, dataSet: set, mostEntries: mostEntries)
}
}
}
}
/// Draws the RadarDataSet
///
/// - parameter context:
/// - parameter dataSet:
/// - parameter mostEntries: the entry count of the dataset with the most entries
internal func drawDataSet(context: CGContext, dataSet: IRadarChartDataSet, mostEntries: Int)
{
guard let
chart = chart,
let animator = animator
else { return }
context.saveGState()
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let entryCount = dataSet.entryCount
let path = CGMutablePath()
var hasMovedToPoint = false
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat((e.y - chart.chartYMin) * Double(factor) * phaseY),
angle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
if p.x.isNaN
{
continue
}
if !hasMovedToPoint
{
path.move(to: p)
hasMovedToPoint = true
}
else
{
path.addLine(to: p)
}
}
// if this is the largest set, close it
if dataSet.entryCount < mostEntries
{
// if this is not the largest set, draw a line to the center before closing
path.addLine(to: center)
}
path.closeSubpath()
// draw filled
if dataSet.isDrawFilledEnabled
{
if dataSet.fill != nil
{
drawFilledPath(context: context, path: path, fill: dataSet.fill!, fillAlpha: dataSet.fillAlpha)
}
else
{
drawFilledPath(context: context, path: path, fillColor: dataSet.fillColor, fillAlpha: dataSet.fillAlpha)
}
}
// draw the line (only if filled is disabled or alpha is below 255)
if !dataSet.isDrawFilledEnabled || dataSet.fillAlpha < 1.0
{
context.setStrokeColor(dataSet.color(atIndex: 0).cgColor)
context.setLineWidth(dataSet.lineWidth)
context.setAlpha(1.0)
context.beginPath()
context.addPath(path)
context.strokePath()
}
context.restoreGState()
}
open override func drawValues(context: CGContext)
{
guard
let chart = chart,
let data = chart.data,
let animator = animator
else { return }
let phaseX = animator.phaseX
let phaseY = animator.phaseY
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value to pixels
let factor = chart.factor
let center = chart.centerOffsets
let yoffset = CGFloat(5.0)
for i in 0 ..< data.dataSetCount
{
let dataSet = data.getDataSetByIndex(i) as! IRadarChartDataSet
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let entryCount = dataSet.entryCount
for j in 0 ..< entryCount
{
guard let e = dataSet.entryForIndex(j) else { continue }
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(e.y - chart.chartYMin) * factor * CGFloat(phaseY),
angle: sliceangle * CGFloat(j) * CGFloat(phaseX) + chart.rotationAngle)
let valueFont = dataSet.valueFont
guard let formatter = dataSet.valueFormatter else { continue }
ChartUtils.drawText(
context: context,
text: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: i,
viewPortHandler: viewPortHandler),
point: CGPoint(x: p.x, y: p.y - yoffset - valueFont.lineHeight),
align: .center,
attributes: [NSFontAttributeName: valueFont,
NSForegroundColorAttributeName: dataSet.valueTextColorAt(j)]
)
}
}
}
open override func drawExtras(context: CGContext)
{
drawWeb(context: context)
}
fileprivate var _webLineSegmentsBuffer = [CGPoint](repeating: CGPoint(), count: 2)
open func drawWeb(context: CGContext)
{
guard
let chart = chart,
let data = chart.data
else { return }
let sliceangle = chart.sliceAngle
context.saveGState()
// calculate the factor that is needed for transforming the value to
// pixels
let factor = chart.factor
let rotationangle = chart.rotationAngle
let center = chart.centerOffsets
// draw the web lines that come from the center
context.setLineWidth(chart.webLineWidth)
context.setStrokeColor(chart.webColor.cgColor)
context.setAlpha(chart.webAlpha)
let xIncrements = 1 + chart.skipWebLineCount
let maxEntryCount = chart.data?.maxEntryCountSet?.entryCount ?? 0
for i in stride(from: 0, to: maxEntryCount, by: xIncrements)
{
let p = ChartUtils.getPosition(
center: center,
dist: CGFloat(chart.yRange) * factor,
angle: sliceangle * CGFloat(i) + rotationangle)
_webLineSegmentsBuffer[0].x = center.x
_webLineSegmentsBuffer[0].y = center.y
_webLineSegmentsBuffer[1].x = p.x
_webLineSegmentsBuffer[1].y = p.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
// draw the inner-web
context.setLineWidth(chart.innerWebLineWidth)
context.setStrokeColor(chart.innerWebColor.cgColor)
context.setAlpha(chart.webAlpha)
let labelCount = chart.yAxis.entryCount
for j in 0 ..< labelCount
{
for i in 0 ..< data.entryCount
{
let r = CGFloat(chart.yAxis.entries[j] - chart.chartYMin) * factor
let p1 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i) + rotationangle)
let p2 = ChartUtils.getPosition(center: center, dist: r, angle: sliceangle * CGFloat(i + 1) + rotationangle)
_webLineSegmentsBuffer[0].x = p1.x
_webLineSegmentsBuffer[0].y = p1.y
_webLineSegmentsBuffer[1].x = p2.x
_webLineSegmentsBuffer[1].y = p2.y
context.strokeLineSegments(between: _webLineSegmentsBuffer)
}
}
context.restoreGState()
}
fileprivate var _highlightPointBuffer = CGPoint()
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let chart = chart,
let radarData = chart.data as? RadarChartData,
let animator = animator
else { return }
context.saveGState()
let sliceangle = chart.sliceAngle
// calculate the factor that is needed for transforming the value pixels
let factor = chart.factor
let center = chart.centerOffsets
for high in indices
{
guard
let set = chart.data?.getDataSetByIndex(high.dataSetIndex) as? IRadarChartDataSet,
set.isHighlightEnabled
else { continue }
guard let e = set.entryForIndex(Int(high.x)) as? RadarChartDataEntry
else { continue }
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
context.setLineWidth(radarData.highlightLineWidth)
if radarData.highlightLineDashLengths != nil
{
context.setLineDash(phase: radarData.highlightLineDashPhase, lengths: radarData.highlightLineDashLengths!)
}
else
{
context.setLineDash(phase: 0.0, lengths: [])
}
context.setStrokeColor(set.highlightColor.cgColor)
let y = e.y - chart.chartYMin
_highlightPointBuffer = ChartUtils.getPosition(
center: center,
dist: CGFloat(y) * factor * CGFloat(animator.phaseY),
angle: sliceangle * CGFloat(high.x) * CGFloat(animator.phaseX) + chart.rotationAngle)
high.setDraw(pt: _highlightPointBuffer)
// draw the lines
drawHighlightLines(context: context, point: _highlightPointBuffer, set: set)
if set.isDrawHighlightCircleEnabled
{
if !_highlightPointBuffer.x.isNaN && !_highlightPointBuffer.y.isNaN
{
var strokeColor = set.highlightCircleStrokeColor
if strokeColor == nil
{
strokeColor = set.color(atIndex: 0)
}
if set.highlightCircleStrokeAlpha < 1.0
{
strokeColor = strokeColor?.withAlphaComponent(set.highlightCircleStrokeAlpha)
}
drawHighlightCircle(
context: context,
atPoint: _highlightPointBuffer,
innerRadius: set.highlightCircleInnerRadius,
outerRadius: set.highlightCircleOuterRadius,
fillColor: set.highlightCircleFillColor,
strokeColor: strokeColor,
strokeWidth: set.highlightCircleStrokeWidth)
}
}
}
context.restoreGState()
}
internal func drawHighlightCircle(
context: CGContext,
atPoint point: CGPoint,
innerRadius: CGFloat,
outerRadius: CGFloat,
fillColor: NSUIColor?,
strokeColor: NSUIColor?,
strokeWidth: CGFloat)
{
context.saveGState()
if let fillColor = fillColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
if innerRadius > 0.0
{
context.addEllipse(in: CGRect(x: point.x - innerRadius, y: point.y - innerRadius, width: innerRadius * 2.0, height: innerRadius * 2.0))
}
context.setFillColor(fillColor.cgColor)
context.fillPath(using: .evenOdd)
}
if let strokeColor = strokeColor
{
context.beginPath()
context.addEllipse(in: CGRect(x: point.x - outerRadius, y: point.y - outerRadius, width: outerRadius * 2.0, height: outerRadius * 2.0))
context.setStrokeColor(strokeColor.cgColor)
context.setLineWidth(strokeWidth)
context.strokePath()
}
context.restoreGState()
}
}
| mit | 90416cd968f80ceca7701b6a3d6ee2e5 | 32.263819 | 151 | 0.528816 | 5.70155 | false | false | false | false |
fe9lix/PennyPincher | PennyPincher/PennyPincher.swift | 1 | 3368 | import UIKit
public typealias PennyPincherResult = (template: PennyPincherTemplate, similarity: CGFloat)
public class PennyPincher {
private static let NumResamplingPoints = 16
public class func createTemplate(_ id: String, points: [CGPoint]) -> PennyPincherTemplate? {
guard points.count > 0 else { return nil }
return PennyPincherTemplate(id: id, points: PennyPincher.resampleBetweenPoints(points))
}
public class func recognize(_ points: [CGPoint], templates: [PennyPincherTemplate]) -> PennyPincherResult? {
guard points.count > 0 && templates.count > 0 else { return nil }
let c = PennyPincher.resampleBetweenPoints(points)
guard c.count > 0 else { return nil }
var similarity = CGFloat.leastNormalMagnitude
var t: PennyPincherTemplate!
var d: CGFloat
for template in templates {
d = 0.0
let count = min(c.count, template.points.count)
for i in 0...count - 1 {
let tp = template.points[i]
let cp = c[i]
d = d + tp.x * cp.x + tp.y * cp.y
if d > similarity {
similarity = d
t = template
}
}
}
guard t != nil else { return nil }
return (t, similarity)
}
private class func resampleBetweenPoints(_ p: [CGPoint]) -> [CGPoint] {
var points = p
let i = pathLength(points) / CGFloat(PennyPincher.NumResamplingPoints - 1)
var d: CGFloat = 0.0
var v = [CGPoint]()
var prev = points.first!
var index = 0
for _ in points {
if index == 0 {
index += 1
continue
}
let thisPoint = points[index]
let prevPoint = points[index - 1]
let pd = distanceBetween(thisPoint, to: prevPoint)
if (d + pd) >= i {
let q = CGPoint(
x: prevPoint.x + (thisPoint.x - prevPoint.x) * (i - d) / pd,
y: prevPoint.y + (thisPoint.y - prevPoint.y) * (i - d) / pd
)
var r = CGPoint(x: q.x - prev.x, y: q.y - prev.y)
let rd = distanceBetween(CGPoint.zero, to: r)
r.x = r.x / rd
r.y = r.y / rd
d = 0.0
prev = q
v.append(r)
points.insert(q, at: index)
index += 1
} else {
d = d + pd
}
index += 1
}
return v
}
private class func pathLength(_ points: [CGPoint]) -> CGFloat {
var d: CGFloat = 0.0
for i in 1..<points.count {
d = d + distanceBetween(points[i - 1], to: points[i])
}
return d
}
private class func distanceBetween(_ pointA: CGPoint, to pointB: CGPoint) -> CGFloat {
let distX = pointA.x - pointB.x
let distY = pointA.y - pointB.y
return sqrt((distX * distX) + (distY * distY))
}
}
| mit | b921232e00763ef03d9315f9358990e4 | 29.618182 | 112 | 0.461995 | 4.466844 | false | false | false | false |
brentdax/swift | test/SILGen/toplevel_errors.swift | 2 | 894 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
enum MyError : Error {
case A, B
}
throw MyError.A
// CHECK: sil @main
// CHECK: [[T0:%.*]] = enum $MyError, #MyError.A!enumelt
// CHECK: [[ERR:%.*]] = alloc_existential_box $Error, $MyError
// CHECK: [[ADDR:%.*]] = project_existential_box $MyError in [[ERR]] : $Error
// CHECK: store [[ERR]] to [init] [[ERRBUF:%.*]] :
// CHECK: store [[T0]] to [trivial] [[ADDR]] : $*MyError
// CHECK: [[ERR2:%.*]] = load [take] [[ERRBUF]]
// CHECK: builtin "willThrow"([[ERR2]] : $Error)
// CHECK: br bb2([[ERR2]] : $Error)
// CHECK: bb1([[T0:%.*]] : @trivial $Int32):
// CHECK: return [[T0]] : $Int32
// CHECK: bb2([[T0:%.*]] : @owned $Error):
// CHECK: builtin "errorInMain"([[T0]] : $Error)
// CHECK: [[T0:%.*]] = integer_literal $Builtin.Int32, 1
// CHECK: [[T1:%.*]] = struct $Int32 ([[T0]] : $Builtin.Int32)
// CHECK: br bb1([[T1]] : $Int32)
| apache-2.0 | 9fb892b20210348d31c9b4a0017b8682 | 33.384615 | 77 | 0.56264 | 2.865385 | false | false | false | false |
dabing1022/AlgorithmRocks | Books/剑指Offer.playground/Pages/36 InversePairs.xcplaygroundpage/Contents.swift | 1 | 1889 | //: [Previous](@previous)
/*:
*/
class Solution {
var helper: [Int] = [Int]()
var result: [(Int, Int)] = [(Int, Int)]()
func inversePairs(inout numbers: [Int]) -> [(Int, Int)] {
helper = Array(count: numbers.count, repeatedValue: 0)
sort(&numbers, low: 0, high: numbers.count - 1)
return result
}
func sort(inout numbers: [Int], low: Int, high: Int) -> Void {
if (low >= high) { return }
let middle = low + (high - low) >> 1
sort(&numbers, low: low, high: middle)
numbers
sort(&numbers, low: middle + 1, high: high)
numbers
merge(&numbers, low: low, middle: middle, high: high)
}
func merge(inout numbers: [Int], low: Int, middle: Int, high: Int) -> Void {
var i = middle
var j = high
for k in low...high {
helper[k] = numbers[k]
}
for k in (low...high).reverse() {
if (i < low) {
i
low
helper[j]
numbers[k] = helper[j]
j -= 1
} else if (j < middle + 1) {
numbers[k] = helper[i]
i -= 1
} else if (helper[i] > helper[j]) {
numbers[k] = helper[i]
var m = j
while m > middle {
result.append((helper[i], helper[m]))
m -= 1
}
i -= 1
} else {
numbers[k] = helper[j];
j -= 1
}
print("low high k numbers helper i j : \(low), \(high), \(k), \(numbers), \(helper), \(i), \(j)")
}
}
}
var numbers = [7, 5, 6, 4]
// 逆序对有:(7,5) (7,6) (7,4) (6,4) (5, 4)
let s = Solution()
// 逆序对
s.inversePairs(&numbers)
numbers
//: [Next](@next)
| mit | 2484c0689436f456c9fbe9ec4289156a | 25.013889 | 109 | 0.41858 | 3.658203 | false | false | false | false |
jc-andrade/Swift | WorldTrotter/WorldTrotter/ConversionViewController.swift | 1 | 4116 | //
// ConversionViewController.swift
// WorldTrotter
//
// Created by Julio Andrade on 5/11/16.
// Copyright © 2016 Julio Andrade. All rights reserved.
//
import UIKit
// Page 175
// Gets current hour and minute so that we can change background color depending on time
let hour = NSCalendar.currentCalendar().component(.Hour, fromDate: NSDate())
let minute = NSCalendar.currentCalendar().component(.Minute, fromDate: NSDate())
class ConversionViewControlller: UIViewController, UITextFieldDelegate // the UITextFieldDelegate declares that ConversionViewController conforms to the UITExtFieldDelegate protocolor
{
// override viewDidLoad to print a statement to the console
override func viewDidLoad()
{
// Always call the super implementation of viewDidLoad
super.viewDidLoad()
print("ConversionViewController loaded its view.")
}
override func viewWillAppear(animated: Bool)
{
// If evening [defined as 5:30pm]
if (hour >= 17 && minute >= 30) {
self.view.backgroundColor = UIColor.lightGrayColor()
} else {/*defaultColor*/}
}
/****************************
* IB Outlets *
*****************************/
@IBOutlet var celsiusLabel: UILabel! // Create outlet for celsiusLabel
@IBOutlet var textField: UITextField! // Declare outlet to reference text field
/****************************
* IB Actions *
*****************************/
@IBAction func fahrenheitFieldEditingChanged(textField: UITextField) // Create function that changes celsiusLabel to whatever textField says.
{
if let text = textField.text, value = Double(text) { // Check if there's text and can be represented by a double
fahrenheitValue = value
}
else {
fahrenheitValue = nil
}
} // fahrenheitFieldEditingChanged function
// Function that makes keyboard go away by using resignFirstResponder method
@IBAction func dismissKeyboard(sender: AnyObject) {
textField.resignFirstResponder();
}
/****************************
* Number formatter *
*****************************/
// Used to customer the display of a number.
let numberFormatter: NSNumberFormatter = {
let nf = NSNumberFormatter()
nf.numberStyle = .DecimalStyle
nf.minimumFractionDigits = 0
nf.maximumFractionDigits = 1
return nf
}()
/****************************
* variables *
*****************************/
var fahrenheitValue: Double? {
didSet {
updateCelsiusLabel()
}
}// optional double for the Fahrenheit value
// Create celsiusValue [optional] computed from fahrenheitValue double above
var celsiusValue: Double? {
if let value = fahrenheitValue { // If there's a value
return (value - 32) * (5/9) // Convert
} else {
return nil
}
}
/****************************
* Regular functions *
*****************************/
func updateCelsiusLabel() {
if let value = celsiusValue {
celsiusLabel.text = numberFormatter.stringFromNumber(value) // Modified to use numberFormatter declared up top
} else {
celsiusLabel.text = "???"
}
}
// Supposed to print text fields current text as well as replacement string, Return true for easiness
// Also supposed to not let us put more than 1 decimal in at a time.
func textField(textField: UITextField,
shouldChangeCharactersInRage range: NSRange,
replacementString string: String) -> Bool {
let numberOnly = NSCharacterSet.init(charactersInString: "0123456789")
let stringFromTextField = NSCharacterSet.init(charactersInString: string)
let strValid = numberOnly.isSupersetOfSet(stringFromTextField)
return strValid
// ------------------------------------------- This dont work atm
}
} | mit | 53d35e117e53d01f0844a9659440236b | 34.482759 | 183 | 0.585419 | 5.479361 | false | false | false | false |
zisko/swift | test/IRGen/mixed_mode_class_with_unimportable_fields.swift | 1 | 3632 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-swift-frontend -emit-module -o %t/UsingObjCStuff.swiftmodule -module-name UsingObjCStuff -I %t -I %S/Inputs/mixed_mode -swift-version 4 %S/Inputs/mixed_mode/UsingObjCStuff.swift
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 3 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V3
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/mixed_mode -module-name main -swift-version 4 %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-V4
// REQUIRES: objc_interop
import UsingObjCStuff
public class SubButtHolder: ButtHolder {
final var w: Double = 0
override public func virtual() {}
public func subVirtual() {}
}
public class SubSubButtHolder: SubButtHolder {
public override func virtual() {}
public override func subVirtual() {}
}
// CHECK-LABEL: define {{.*}} @{{.*}}accessFinalFields
public func accessFinalFields(of holder: ButtHolder) -> (Any, Any) {
// x and z came from the other module, so we should use their accessors.
// CHECK: [[OFFSET:%.*]] = load [[WORD:i[0-9]+]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd"
// CHECK: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd"
// CHECK: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
return (holder.x, holder.z)
}
// CHECK-LABEL: define {{.*}} @{{.*}}accessFinalFields
public func accessFinalFields(ofSub holder: SubButtHolder) -> (Any, Any, Any) {
// We should use the runtime-adjusted ivar offsets since we may not have
// a full picture of the layout in mixed Swift language version modes.
// CHECK: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1xSivpWvd"
// CHECK: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S14UsingObjCStuff10ButtHolderC1zSSvpWvd"
// CHECK: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
// CHECK: [[OFFSET:%.*]] = load [[WORD]], [[WORD]]* @"$S4main13SubButtHolderC1wSdvpWvd"
// CHECK: [[INSTANCE_RAW:%.*]] = bitcast {{.*}} to i8*
// CHECK: getelementptr inbounds i8, i8* [[INSTANCE_RAW]], [[WORD]] [[OFFSET]]
return (holder.x, holder.z, holder.w)
}
// CHECK-LABEL: define {{.*}} @{{.*}}invokeMethod
public func invokeMethod(on holder: SubButtHolder) {
// CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 10
// CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 13
// CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]]
// CHECK: call swiftcc void [[IMPL]]
holder.virtual()
// CHECK-64: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 15
// CHECK-32: [[IMPL_ADDR:%.*]] = getelementptr inbounds {{.*}}, [[WORD]] 18
// CHECK: [[IMPL:%.*]] = load {{.*}} [[IMPL_ADDR]]
// CHECK: call swiftcc void [[IMPL]]
holder.subVirtual()
}
// CHECK-V3-LABEL: define private void @initialize_metadata_SubButtHolder
// CHECK-V3: call void @swift_initClassMetadata_UniversalStrategy
// CHECK-V3-LABEL: define private void @initialize_metadata_SubSubButtHolder
// CHECK-V3: call void @swift_initClassMetadata_UniversalStrategy
| apache-2.0 | 66149f28e7701a985340c97f7cc2ba6c | 47.426667 | 205 | 0.651156 | 3.553816 | false | false | false | false |
zisko/swift | tools/SwiftSyntax/SyntaxData.swift | 1 | 8063 | //===-------------------- SyntaxData.swift - Syntax Data ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
/// A unique identifier for a node in the tree.
/// Currently, this is an index path from the current node to the root of the
/// tree. It's an implementation detail and shouldn't be
/// exposed to clients.
typealias NodeIdentifier = [Int]
/// SyntaxData is the underlying storage for each Syntax node.
/// It's modelled as an array that stores and caches a SyntaxData for each raw
/// syntax node in its layout. It is up to the specific Syntax nodes to maintain
/// the correct layout of their SyntaxData backing stores.
///
/// SyntaxData is an implementation detail, and should not be exposed to clients
/// of libSyntax.
///
/// The following relationships are preserved:
/// parent.cachedChild(at: indexInParent) === self
/// raw.layout.count == childCaches.count
/// pathToRoot.first === indexInParent
final class SyntaxData: Equatable {
let raw: RawSyntax
let indexInParent: Int
weak var parent: SyntaxData?
let childCaches: [AtomicCache<SyntaxData>]
/// Creates a SyntaxData with the provided raw syntax, pointing to the
/// provided index, in the provided parent.
/// - Parameters:
/// - raw: The raw syntax underlying this node.
/// - indexInParent: The index in the parent's layout where this node will
/// reside.
/// - parent: The parent of this node, or `nil` if this node is the root.
required init(raw: RawSyntax, indexInParent: Int = 0,
parent: SyntaxData? = nil) {
self.raw = raw
self.indexInParent = indexInParent
self.parent = parent
self.childCaches = raw.layout.map { _ in AtomicCache<SyntaxData>() }
}
/// The index path from this node to the root. This can be used to uniquely
/// identify this node in the tree.
lazy private(set) var pathToRoot: NodeIdentifier = {
var path = [Int]()
var node = self
while let parent = node.parent {
path.append(node.indexInParent)
node = parent
}
return path
}()
/// Returns the child data at the provided index in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the index is out of the bounds of the
/// data's layout.
///
/// - Parameter index: The index to create and cache.
/// - Returns: The child's data at the provided index.
func cachedChild(at index: Int) -> SyntaxData? {
if raw.layout[index] == nil { return nil }
return childCaches[index].value { realizeChild(index) }
}
/// Returns the child data at the provided cursor in this data's layout.
/// This child is cached and will be used in subsequent accesses.
/// - Note: This function traps if the cursor is out of the bounds of the
/// data's layout.
///
/// - Parameter cursor: The cursor to create and cache.
/// - Returns: The child's data at the provided cursor.
func cachedChild<CursorType: RawRepresentable>(
at cursor: CursorType) -> SyntaxData?
where CursorType.RawValue == Int {
return cachedChild(at: cursor.rawValue)
}
/// Walks up the provided node's parent tree looking for the receiver.
/// - parameter data: The potential child data.
/// - returns: `true` if the receiver exists in the parent chain of the
/// provided data.
/// - seealso: isDescendent(of:)
func isAncestor(of data: SyntaxData) -> Bool {
return data.isDescendent(of: self)
}
/// Walks up the receiver's parent tree looking for the provided node.
/// - parameter data: The potential ancestor data.
/// - returns: `true` if the data exists in the parent chain of the receiver.
/// - seealso: isAncestor(of:)
func isDescendent(of data: SyntaxData) -> Bool {
if data == self { return true }
var node = self
while let parent = node.parent {
if parent == data { return true }
node = parent
}
return false
}
/// Creates a copy of `self` and recursively creates `SyntaxData` nodes up to
/// the root.
/// - parameter newRaw: The new RawSyntax that will back the new `Data`
/// - returns: A tuple of both the new root node and the new data with the raw
/// layout replaced.
func replacingSelf(
_ newRaw: RawSyntax) -> (root: SyntaxData, newValue: SyntaxData) {
// If we have a parent already, then ask our current parent to copy itself
// recursively up to the root.
if let parent = parent {
let (root, newParent) = parent.replacingChild(newRaw, at: indexInParent)
let newMe = newParent.cachedChild(at: indexInParent)!
return (root: root, newValue: newMe)
} else {
// Otherwise, we're already the root, so return the new data as both the
// new root and the new data.
let newMe = SyntaxData(raw: newRaw, indexInParent: indexInParent,
parent: nil)
return (root: newMe, newValue: newMe)
}
}
/// Creates a copy of `self` with the child at the provided index replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - index: The index pointing to where in the raw layout to place this
/// child.
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild(_ child: RawSyntax,
at index: Int) -> (root: SyntaxData, newValue: SyntaxData) {
let newRaw = raw.replacingChild(index, with: child)
return replacingSelf(newRaw)
}
/// Creates a copy of `self` with the child at the provided cursor replaced
/// with a new SyntaxData containing the raw syntax provided.
///
/// - Parameters:
/// - child: The raw syntax for the new child to replace.
/// - cursor: A cursor that points to the index of the child you wish to
/// replace
/// - Returns: The new root node created by this operation, and the new child
/// syntax data.
/// - SeeAlso: replacingSelf(_:)
func replacingChild<CursorType: RawRepresentable>(_ child: RawSyntax,
at cursor: CursorType) -> (root: SyntaxData, newValue: SyntaxData)
where CursorType.RawValue == Int {
return replacingChild(child, at: cursor.rawValue)
}
/// Creates the child's syntax data for the provided cursor.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild<CursorType: RawRepresentable>(
_ cursor: CursorType) -> SyntaxData
where CursorType.RawValue == Int {
return realizeChild(cursor.rawValue)
}
/// Creates the child's syntax data for the provided index.
///
/// - Parameter cursor: The cursor pointing into the raw syntax's layout for
/// the child you're creating.
/// - Returns: A new SyntaxData for the specific child you're
/// creating, whose parent is pointing to self.
func realizeChild(_ index: Int) -> SyntaxData {
return SyntaxData(raw: raw.layout[index]!,
indexInParent: index,
parent: self)
}
/// Tells whether two SyntaxData nodes have the same identity.
/// This is not structural equality.
/// - Returns: True if both datas are exactly the same.
static func ==(lhs: SyntaxData, rhs: SyntaxData) -> Bool {
return lhs === rhs
}
}
| apache-2.0 | bf831f60e03d59a2474e360fbb1b779c | 39.315 | 80 | 0.652239 | 4.268396 | false | false | false | false |
zisko/swift | stdlib/public/core/Print.swift | 1 | 8814 | //===--- Print.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Writes the textual representations of the given items into the standard
/// output.
///
/// You can pass zero or more items to the `print(_:separator:terminator:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a string,
/// a closed range of integers, and a group of floating-point values to
/// standard output:
///
/// print("One two three four five")
/// // Prints "One two three four five"
///
/// print(1...5)
/// // Prints "1...5"
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `print(_:separator:terminator:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// for n in 1...5 {
/// print(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
public func print(
_ items: Any...,
separator: String = " ",
terminator: String = "\n"
) {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_print(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_print(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the standard output.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:)` function. The textual representation
/// for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints the debugging
/// representation of a string, a closed range of integers, and a group of
/// floating-point values to standard output:
///
/// debugPrint("One two three four five")
/// // Prints "One two three four five"
///
/// debugPrint(1...5)
/// // Prints "ClosedRange(1...5)"
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0)
/// // Prints "1.0 2.0 3.0 4.0 5.0"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ")
/// // Prints "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0"
///
/// The output from each call to `debugPrint(_:separator:terminator:)` includes
/// a newline by default. To print the items without a trailing newline, pass
/// an empty string as `terminator`.
///
/// for n in 1...5 {
/// debugPrint(n, terminator: "")
/// }
/// // Prints "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
@inline(never)
public func debugPrint(
_ items: Any...,
separator: String = " ",
terminator: String = "\n") {
if let hook = _playgroundPrintHook {
var output = _TeeStream(left: "", right: _Stdout())
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
hook(output.left)
}
else {
var output = _Stdout()
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
}
/// Writes the textual representations of the given items into the given output
/// stream.
///
/// You can pass zero or more items to the `print(_:separator:terminator:to:)`
/// function. The textual representation for each item is the same as that
/// obtained by calling `String(item)`. The following example prints a closed
/// range of integers to a string:
///
/// var range = "My range: "
/// print(1...5, to: &range)
/// // range == "My range: 1...5\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// print(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `print(_:separator:terminator:to:)` includes a
/// newline by default. To print the items without a trailing newline, pass an
/// empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// print(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func print<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_print(items, separator: separator, terminator: terminator, to: &output)
}
/// Writes the textual representations of the given items most suitable for
/// debugging into the given output stream.
///
/// You can pass zero or more items to the
/// `debugPrint(_:separator:terminator:to:)` function. The textual
/// representation for each item is the same as that obtained by calling
/// `String(reflecting: item)`. The following example prints a closed range of
/// integers to a string:
///
/// var range = "My range: "
/// debugPrint(1...5, to: &range)
/// // range == "My range: ClosedRange(1...5)\n"
///
/// To print the items separated by something other than a space, pass a string
/// as `separator`.
///
/// var separated = ""
/// debugPrint(1.0, 2.0, 3.0, 4.0, 5.0, separator: " ... ", to: &separated)
/// // separated == "1.0 ... 2.0 ... 3.0 ... 4.0 ... 5.0\n"
///
/// The output from each call to `debugPrint(_:separator:terminator:to:)`
/// includes a newline by default. To print the items without a trailing
/// newline, pass an empty string as `terminator`.
///
/// var numbers = ""
/// for n in 1...5 {
/// debugPrint(n, terminator: "", to: &numbers)
/// }
/// // numbers == "12345"
///
/// - Parameters:
/// - items: Zero or more items to print.
/// - separator: A string to print between each item. The default is a single
/// space (`" "`).
/// - terminator: The string to print after all items have been printed. The
/// default is a newline (`"\n"`).
/// - output: An output stream to receive the text representation of each
/// item.
@_inlineable // FIXME(sil-serialize-all)
@inline(__always)
public func debugPrint<Target : TextOutputStream>(
_ items: Any...,
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
_debugPrint(
items, separator: separator, terminator: terminator, to: &output)
}
@_versioned
@inline(never)
internal func _print<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_print_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
@_versioned
@inline(never)
internal func _debugPrint<Target : TextOutputStream>(
_ items: [Any],
separator: String = " ",
terminator: String = "\n",
to output: inout Target
) {
var prefix = ""
output._lock()
defer { output._unlock() }
for item in items {
output.write(prefix)
_debugPrint_unlocked(item, &output)
prefix = separator
}
output.write(terminator)
}
| apache-2.0 | 6bb76e50985dd00e635ed23d0989b7d2 | 32.513308 | 80 | 0.611641 | 3.677096 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/remove-all-adjacent-duplicates-in-string-ii.swift | 2 | 863 | /**
* https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/
*
*
*/
// Date: Fri Apr 16 14:11:45 PDT 2021
class Solution {
func removeDuplicates(_ s: String, _ k: Int) -> String {
var stack: [(c: Character, count: Int)] = []
for cc in s {
if let last = stack.last, last.c == cc {
stack.removeLast()
stack.append((cc, last.count + 1))
} else {
stack.append((cc, 1))
}
while let last = stack.last, last.count == k {
stack.removeLast()
}
}
var result = ""
for item in stack {
var text = ""
for _ in 0 ..< item.count {
text.append(item.c)
}
result += text
}
return result
}
} | mit | 672bf8749886c28ba94df2d988319e0c | 26 | 77 | 0.439166 | 4.109524 | false | false | false | false |
tinrobots/Mechanica | Tests/StandardLibraryTests/DictionaryUtilsTests.swift | 1 | 1574 | import XCTest
@testable import Mechanica
extension DictionaryUtilsTests {
static var allTests = [
("testHasKey", testHasKey),
("testRemoveAll", testRemoveAll)
]
}
final class DictionaryUtilsTests: XCTestCase {
func testHasKey() {
do {
let dictionary: [String:Int] = [:]
XCTAssertFalse(dictionary.hasKey(""))
XCTAssertFalse(dictionary.hasKey("robot"))
}
do {
let dictionary: [String:Int] = ["robot":1, "robot2":2]
XCTAssertFalse(dictionary.hasKey(""))
XCTAssertTrue(dictionary.hasKey("robot"))
}
}
func testRemoveAll() {
var dictionary = ["a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7, "i": 8, "l": 9, "m": 10]
do {
let removed = dictionary.removeAll(forKeys: ["a", "b", "c"])
if removed != nil {
XCTAssertTrue(removed!.count == 3)
} else {
XCTAssertNotNil(dictionary)
}
}
do {
let removed = dictionary.removeAll(forKeys: ["a", "b", "c", "d"])
if removed != nil {
XCTAssertTrue(removed!.count == 1)
} else {
XCTAssertNotNil(dictionary)
}
}
do {
let removed = dictionary.removeAll(forKeys: ["k"])
XCTAssertNil(removed)
}
do {
let removed = dictionary.removeAll(forKeys: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "l", "m"])
XCTAssertNotNil(removed)
XCTAssertNil(removed!["a"])
XCTAssertNil(dictionary["a"])
XCTAssertNotNil(removed!["l"])
XCTAssertNil(dictionary["l"])
XCTAssert(dictionary.isEmpty)
}
}
}
| mit | 84ca3a4fc0e404064638a0f02a853351 | 23.59375 | 110 | 0.562262 | 3.792771 | false | true | false | false |
patrick-ogrady/godseye-ios | sample/SampleBroadcaster-Swift/SampleBroadcaster-Swift/AppDelegate.swift | 1 | 4233 | /*
Video Core
Copyright (c) 2014 James G. Hurley
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.
*/
//
// AppDelegate.swift
// SampleBroadcaster-Swift
//
// Created by Josh Lieberman on 4/11/15.
// Copyright (c) 2015 videocore. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
Parse.setApplicationId("HSPKoZpqyPfrGkmQV5rQ18DIUtPT54Ds4PhiJJix",
clientKey: "pDreMDJo9xe7e2heKrWDfH1xIE1WNmdKCMPg75Ex")
PFUser.enableAutomaticUser();
PFUser.currentUser()?.save()
var currentUser = PFUser.currentUser()!
currentUser["name"] = "Anonymous"
currentUser.save()
let userNotificationTypes = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
application.registerUserNotificationSettings(userNotificationTypes)
application.registerForRemoteNotifications()
return true
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let installation = PFInstallation.currentInstallation()
installation.setDeviceTokenFromData(deviceToken)
installation["user"] = PFUser.currentUser()!
installation.saveInBackground()
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | c1b10ac6b220adc76ae374f1176a61be | 43.557895 | 285 | 0.748169 | 5.271482 | false | false | false | false |
at-internet/atinternet-ios-swift-sdk | Tracker/Tracker/LiveAudio.swift | 1 | 5276 | /*
This SDK is licensed under the MIT license (MIT)
Copyright (c) 2015- Applied Technologies Internet SAS (registration number B 403 261 258 - Trade and Companies Register of Bordeaux – France)
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.
*/
//
// LiveAudio.swift
// Tracker
//
import UIKit
public class LiveAudio: RichMedia {
/// Media type
let type: String = "audio"
/// Set parameters in buffer
override func setEvent() {
super.broadcastMode = .Live
super.setEvent()
self.tracker = self.tracker.setParam("type", value: type)
}
}
public class LiveAudios {
var list: [String: LiveAudio] = [String: LiveAudio]()
/// MediaPlayer instance
var player: MediaPlayer
/**
LiveAudios initializer
- parameter player: the player instance
- returns: LiveAudios instance
*/
init(player: MediaPlayer) {
self.player = player
}
/**
Create a new live audio
- parameter audio: name
- parameter first: chapter
- returns: live audio instance
*/
public func add(_ name:String) -> LiveAudio {
if let audio = self.list[name] {
self.player.tracker.delegate?.warningDidOccur("A LiveAudio with the same name already exists.")
return audio
} else {
let audio = LiveAudio(player: player)
audio.name = name
self.list[name] = audio
return audio
}
}
/**
Create a new live audio
- parameter audio: name
- parameter first: chapter
- returns: live audio instance
*/
public func add(_ name: String, chapter1: String) -> LiveAudio {
if let audio = self.list[name] {
self.player.tracker.delegate?.warningDidOccur("A LiveAudio with the same name already exists.")
return audio
} else {
let audio = LiveAudio(player: player)
audio.name = name
audio.chapter1 = chapter1
self.list[name] = audio
return audio
}
}
/**
Create a new live audio
- parameter audio: name
- parameter first: chapter
- parameter second: chapter
- returns: live audio instance
*/
public func add(_ name: String, chapter1: String, chapter2: String) -> LiveAudio {
if let audio = self.list[name] {
self.player.tracker.delegate?.warningDidOccur("A LiveAudio with the same name already exists.")
return audio
} else {
let audio = LiveAudio(player: player)
audio.name = name
audio.chapter1 = chapter1
audio.chapter2 = chapter2
self.list[name] = audio
return audio
}
}
/**
Create a new live audio
- parameter audio: name
- parameter first: chapter
- parameter second: chapter
- parameter third: chapter
- returns: live audio instance
*/
public func add(_ name: String, chapter1: String, chapter2: String, chapter3: String) -> LiveAudio {
if let audio = self.list[name] {
self.player.tracker.delegate?.warningDidOccur("A LiveAudio with the same name already exists.")
return audio
} else {
let audio = LiveAudio(player: player)
audio.name = name
audio.chapter1 = chapter1
audio.chapter2 = chapter2
audio.chapter3 = chapter3
self.list[name] = audio
return audio
}
}
/**
Remove a live audio
- parameter audio: name
*/
public func remove(_ name: String) {
if let timer = list[name]?.timer {
if timer.isValid {
list[name]!.sendStop()
}
}
self.list.removeValue(forKey: name)
}
/**
Remove all live audios
*/
public func removeAll() {
for (_, value) in self.list {
if let timer = value.timer {
if timer.isValid {
value.sendStop()
}
}
}
self.list.removeAll(keepingCapacity: false)
}
}
| mit | 5fa2cec23f28b2b33d1969ef1501738e | 27.819672 | 141 | 0.59708 | 4.713137 | false | false | false | false |
khizkhiz/swift | validation-test/compiler_crashers_2_fixed/0027-rdar21514140.swift | 5 | 12851 | // RUN: not %target-swift-frontend %s -parse
/// A type that is just a wrapper over some base Sequence
internal protocol _SequenceWrapper {
typealias Base : Sequence
typealias Iterator : IteratorProtocol = Base.Iterator
var _base: Base {get}
}
extension Sequence
where Self : _SequenceWrapper, Self.Iterator == Self.Base.Iterator {
public func makeIterator() -> Base.Iterator {
return self._base.makeIterator()
}
public func underestimatedCount() -> Int {
return _base.underestimatedCount()
}
public func _customContainsEquatableElement(
element: Base.Iterator.Element
) -> Bool? {
return _base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(@noescape preprocess: (Self) -> R) -> R? {
return _base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
return _base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) {
return _base._copyContents(initializing: ptr)
}
}
internal protocol _CollectionWrapper : _SequenceWrapper {
typealias Base : Collection
typealias Index : ForwardIndex = Base.Index
var _base: Base {get}
}
extension Collection
where Self : _CollectionWrapper, Self.Index == Self.Base.Index {
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Base.Index {
return _base.startIndex
}
/// The collection's "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Base.Index {
return _base.endIndex
}
/// Access the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> Base.Iterator.Element {
return _base[position]
}
}
//===--- New stuff --------------------------------------------------------===//
public protocol _prext_LazySequence : Sequence {
/// A Sequence that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazySequence` layer.
typealias Elements: Sequence = Self
/// A sequence containing the same elements as this one, possibly with
/// a simpler type.
///
/// When implementing lazy operations, wrapping `elements` instead
/// of `self` can prevent result types from growing a `_prext_LazySequence`
/// layer.
///
/// Note: this property need not be implemented by conforming types,
/// it has a default implementation in a protocol extension that
/// just returns `self`.
var elements: Elements {get}
/// An Array, created on-demand, containing the elements of this
/// lazy Sequence.
///
/// Note: this property need not be implemented by conforming types, it has a
/// default implementation in a protocol extension.
var array: [Iterator.Element] {get}
}
extension _prext_LazySequence {
/// an Array, created on-demand, containing the elements of this
/// lazy Sequence.
public var array: [Iterator.Element] {
return Array(self)
}
}
extension _prext_LazySequence where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazySequence where Self : _SequenceWrapper {
public var elements: Base { return _base }
}
/// A sequence that forwards its implementation to an underlying
/// sequence instance while exposing lazy computations as methods.
public struct _prext_LazySequence<Base_ : Sequence> : _SequenceWrapper {
var _base: Base_
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<S : Sequence>(s: S) -> _prext_LazySequence<S> {
return _prext_LazySequence(_base: s)
}
public extension Sequence
where Self.Iterator == Self, Self : IteratorProtocol {
public func makeIterator() -> Self {
return self
}
}
//===--- LazyCollection.swift ---------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol _prext_LazyCollection : Collection, _prext_LazySequence {
/// A Collection that can contain the same elements as this one,
/// possibly with a simpler type.
///
/// This associated type is used to keep the result type of
/// `lazy(x).operation` from growing a `_prext_LazyCollection` layer.
typealias Elements: Collection = Self
}
extension _prext_LazyCollection where Elements == Self {
public var elements: Self { return self }
}
extension _prext_LazyCollection where Self : _CollectionWrapper {
public var elements: Base { return _base }
}
/// A collection that forwards its implementation to an underlying
/// collection instance while exposing lazy computations as methods.
public struct _prext_LazyCollection<Base_ : Collection>
: /*_prext_LazyCollection,*/ _CollectionWrapper {
typealias Base = Base_
typealias Index = Base.Index
/// Construct an instance with `base` as its underlying Collection
/// instance.
public init(_ base: Base_) {
self._base = base
}
public var _base: Base_
// FIXME: Why is this needed?
// public var elements: Base { return _base }
}
/// Augment `s` with lazy methods such as `map`, `filter`, etc.
public func _prext_lazy<Base: Collection>(s: Base) -> _prext_LazyCollection<Base> {
return _prext_LazyCollection(s)
}
//===--- New stuff --------------------------------------------------------===//
/// The `IteratorProtocol` used by `_prext_MapSequence` and `_prext_MapCollection`.
/// Produces each element by passing the output of the `Base`
/// `IteratorProtocol` through a transform function returning `T`.
public struct _prext_MapIterator<
Base: IteratorProtocol, T
> : IteratorProtocol, Sequence {
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`.
public mutating func next() -> T? {
let x = _base.next()
if x != nil {
return _transform(x!)
}
return nil
}
var _base: Base
var _transform: (Base.Element)->T
}
//===--- Sequences --------------------------------------------------------===//
/// A `Sequence` whose elements consist of those in a `Base`
/// `Sequence` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapSequence<Base : Sequence, T>
: _prext_LazySequence, _SequenceWrapper {
typealias Elements = _prext_MapSequence
public func makeIterator() -> _prext_MapIterator<Base.Iterator,T> {
return _prext_MapIterator(
_base: _base.makeIterator(), _transform: _transform)
}
var _base: Base
var _transform: (Base.Iterator.Element)->T
}
//===--- Collections ------------------------------------------------------===//
/// A `Collection` whose elements consist of those in a `Base`
/// `Collection` passed through a transform function returning `T`.
/// These elements are computed lazily, each time they're read, by
/// calling the transform function on a base element.
public struct _prext_MapCollection<Base : Collection, T>
: _prext_LazyCollection, _CollectionWrapper {
public var startIndex: Base.Index { return _base.startIndex }
public var endIndex: Base.Index { return _base.endIndex }
/// Access the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Base.Index) -> T {
return _transform(_base[position])
}
public func makeIterator() -> _prext_MapIterator<Base.Iterator, T> {
return _prext_MapIterator(_base: _base.makeIterator(), _transform: _transform)
}
public func underestimatedCount() -> Int {
return _base.underestimatedCount()
}
var _base: Base
var _transform: (Base.Iterator.Element)->T
}
//===--- Support for lazy(s) ----------------------------------------------===//
extension _prext_LazySequence {
/// Return a `_prext_MapSequence` over this `Sequence`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Iterator.Element) -> U
) -> _prext_MapSequence<Self.Elements, U> {
return _prext_MapSequence(_base: self.elements, _transform: transform)
}
}
extension _prext_LazyCollection {
/// Return a `_prext_MapCollection` over this `Collection`. The elements of
/// the result are computed lazily, each time they are read, by
/// calling `transform` function on a base element.
public func map<U>(
transform: (Elements.Iterator.Element) -> U
) -> _prext_MapCollection<Self.Elements, U> {
return _prext_MapCollection(_base: self.elements, _transform: transform)
}
}
// ${'Local Variables'}:
// eval: (read-only-mode 1)
// End:
//===--- New stuff --------------------------------------------------------===//
internal protocol _prext_ReverseIndex : BidirectionalIndex {
typealias Base : BidirectionalIndex
/// A type that can represent the number of steps between pairs of
/// `_prext_ReverseIndex` values where one value is reachable from the other.
typealias Distance: _SignedInteger = Base.Distance
var _base: Base { get }
init(_ base: Base)
}
/// A wrapper for a `BidirectionalIndex` that reverses its
/// direction of traversal.
extension BidirectionalIndex where Self : _prext_ReverseIndex {
/// Returns the next consecutive value after `self`.
///
/// - Precondition: The next value is representable.
public func successor() -> Self {
return Self(_base.predecessor())
}
/// Returns the previous consecutive value before `self`.
///
/// - Precondition: The previous value is representable.
public func predecessor() -> Self {
return Self(_base.successor())
}
}
public struct _prext_ReverseIndex<Base: BidirectionalIndex>
: BidirectionalIndex, _prext_ReverseIndex {
internal init(_ base: Base) { self._base = base }
internal let _base: Base
}
public func == <I> (lhs: _prext_ReverseIndex<I>, rhs: _prext_ReverseIndex<I>) -> Bool {
return lhs._base == rhs._base
}
public struct _prext_ReverseRandomAccessIndex<Base: RandomAccessIndex>
: RandomAccessIndex, _prext_ReverseIndex {
typealias Distance = Base.Distance
internal init(_ base: Base) { self._base = base }
internal let _base: Base
/// Return the minimum number of applications of `successor` or
/// `predecessor` required to reach `other` from `self`.
///
/// - Complexity: O(1).
public func distance(to other: _prext_ReverseRandomAccessIndex) -> Distance {
return other._base.distance(to: _base)
}
/// Return `self` offset by `n` steps.
///
/// - Returns: If `n > 0`, the result of applying `successor` to
/// `self` `n` times. If `n < 0`, the result of applying
/// `predecessor` to `self` `-n` times. Otherwise, `self`.
///
/// - Complexity: O(1).
public func advanced(by amount: Distance) -> _prext_ReverseRandomAccessIndex {
return _prext_ReverseRandomAccessIndex(_base.advanced(by: -amount))
}
}
internal protocol __prext_ReverseCollection
: _prext_LazyCollection, _CollectionWrapper {
typealias Base : Collection
var _base : Base {get}
}
extension Collection
where Self : __prext_ReverseCollection,
Self.Index : _prext_ReverseIndex,
Self.Index.Base == Self.Base.Index,
Iterator.Element == Self.Base.Iterator.Element
{
public var startIndex : Index { return Index(_base.endIndex) }
public var endIndex : Index { return Index(_base.startIndex) }
public subscript(position: Index) -> Self.Base.Iterator.Element {
return _base[position._base.predecessor()]
}
}
| apache-2.0 | 4c236e2bf82de6e8ab7e0063b43833ba | 31.45202 | 87 | 0.665396 | 4.171048 | false | false | false | false |
LeLuckyVint/MessageKit | Example/Sources/MockMessage.swift | 1 | 2588 | /*
MIT License
Copyright (c) 2017 MessageKit
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import Foundation
import MessageKit
import CoreLocation
struct MockMessage: MessageType {
var messageId: String
var sender: Sender
var sentDate: Date
var data: MessageData
init(data: MessageData, sender: Sender, messageId: String, date: Date) {
self.data = data
self.sender = sender
self.messageId = messageId
self.sentDate = date
}
init(text: String, sender: Sender, messageId: String, date: Date) {
self.init(data: .text(text), sender: sender, messageId: messageId, date: date)
}
init(attributedText: NSAttributedString, sender: Sender, messageId: String, date: Date) {
self.init(data: .attributedText(attributedText), sender: sender, messageId: messageId, date: date)
}
init(image: UIImage, sender: Sender, messageId: String, date: Date) {
self.init(data: .photo(image), sender: sender, messageId: messageId, date: date)
}
init(thumbnail: UIImage, sender: Sender, messageId: String, date: Date) {
let url = URL(fileURLWithPath: "")
self.init(data: .video(file: url, thumbnail: thumbnail), sender: sender, messageId: messageId, date: date)
}
init(location: CLLocation, sender: Sender, messageId: String, date: Date) {
self.init(data: .location(location), sender: sender, messageId: messageId, date: date)
}
init(emoji: String, sender: Sender, messageId: String, date: Date) {
self.init(data: .emoji(emoji), sender: sender, messageId: messageId, date: date)
}
}
| mit | 5af13348569d7584f271c6f00c856bff | 37.058824 | 114 | 0.727589 | 4.22186 | false | false | false | false |
mehulparmar4ever/TodayWidget | My Widget/TodayViewController.swift | 1 | 5463 | //
// TodayViewController.swift
// My Widget
//
// Created by mehulmac on 18/09/17.
// Copyright © 2017 mehulmac. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var table: UITableView!
var strStaticMessage = "Please wait, while loading data"
var arrList = [ListModel]()
// MARK:
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
self.table.tableFooterView = UIView()
extensionContext?.widgetLargestAvailableDisplayMode = .expanded
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
let expanded = activeDisplayMode == .expanded
let count = self.arrList.count * 44
preferredContentSize = expanded ? CGSize(width: maxSize.width, height: CGFloat(count)) : maxSize
}
//Use below method to set data
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
switch NetworkManagerExtension().checkInternetConnection() {
case .available:
APIService().getQuestions({ (response) in
if let arrDict = response.array {
self.arrList = ModelManager.sharedInstance.getListModelArray(arrDict)
completionHandler(.newData)
}
else {
completionHandler(.noData)
}
self.table.reloadData()
}) { (error) in
print(error as Any)
self.table.reloadData()
completionHandler(.failed)
}
break
case .notAvailable:
strStaticMessage = "No internet connection"
self.table.reloadData()
break
}
}
}
// MARK:
// MARK: UITableViewCell, UITableViewDataSource, UITableViewDelegate
class WidgetCell: UITableViewCell {
@IBOutlet weak var lblGameName: UILabel!
@IBOutlet weak var lblWinningNumber: UILabel!
@IBOutlet weak var lblDrawNumber: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
}
extension TodayViewController : UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.arrList.count > 0 {
return self.arrList.count
}
else {
return 1
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "WidgetCell", for: indexPath) as! WidgetCell
cell.lblGameName.text = strStaticMessage
cell.lblWinningNumber.text = ""
cell.lblDrawNumber.text = ""
if self.arrList.count > 0 {
let dataWidget = self.arrList[indexPath.row]
if let data = dataWidget.strQuestion {
cell.lblGameName.text = data
}
if let data = dataWidget.arrChoices?.first?.strChoices {
cell.lblWinningNumber.text = data
}
if let data = dataWidget.arrChoices?.first?.strVotes {
cell.lblDrawNumber.text = data
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell : WidgetCell = tableView.cellForRow(at: indexPath) as! WidgetCell
if cell.lblGameName.text != strStaticMessage {
if self.arrList.count > 0 {
let dataWidget = self.arrList[indexPath.row]
if let strData : String = dataWidget.toJSONString() {
//Save data to application
if let defaults = UserDefaults(suiteName: "group.Sooryen.DemoTodayWidget") {
defaults.set(strData, forKey: "extensionSharedDataString")
defaults.synchronize()
//Redirect to application
if let myAppUrl = URL(string: "MyWidget://") {
self.extensionContext?.open(myAppUrl, completionHandler: { (success) in
if !success {
print("error: failed to open app from Today Extension")
}
else {
print("data sending done")
}
})
}
}
}
}
}
}
}
| mit | eea687073a59c970cac557ed8678c28d | 33.789809 | 118 | 0.560784 | 5.489447 | false | false | false | false |
movem3nt/StreamBaseKit | StreamBaseKit/ResourceBase.swift | 2 | 23086 | //
// ResourceBase.swift
// StreamBaseKit
//
// Created by Steve Farrell on 9/3/15.
// Copyright (c) 2015 Movem3nt. All rights reserved.
//
import Foundation
import Firebase
/**
A dictionary for associating object instances with keys. These keys are
used for interpolating paths.
*/
public typealias ResourceDict = [String: BaseItemProtocol]
/**
An error handler invoked when a persistance operation fails.
*/
public typealias ResourceErrorHandler = (error: NSError) -> Void
/**
A done handler. Operation was successful if error is nil.
*/
public typealias ResourceDoneHandler = (error: NSError?) -> Void
/**
A predicate that is evaluated when updating counters.
*/
public typealias CounterPredicate = BaseItemProtocol -> Bool
/**
An interface for registering resources, binding classes with the location
of where they are stored in Firebase.
*/
public protocol ResourceRegistry {
/// This handler is invoked when persistance operations fail.
var errorHandler: ResourceErrorHandler? { get set }
/**
Register a specific type with a path. Each class can only be registered
one time. The path is interpolated dynamically based on context. For
example,
registry.resource(Message.self, "group/$group/messages/@")
will have $group interpolated by context, and that the message id
(represented by "@") will be filled in using childByAutoId() for
```create()``` or the value of the object's key for ```update()``` and
```destroy()```.
If you want to store the same object in two different paths, you can do
so by subclassing it.
:param: type The object type being registered.
:param: path The path being registered with this object type.
*/
func resource(type: BaseItemProtocol.Type, path: String)
/**
Register a counter so that a field is updated on one object whenever another
object is created or destroyed. For example,
registry.counter(Message.self, "like_count", MessageLike.self)
says that the message's ```like_count``` should be incremented when messages
are liked, and decremented when those likes are removed.
It's ok to register multiple counters for the same object.
Note that these counters are computed client-side. You may also need a server-side
job to correct the inconsistencies that will inevitably occur.
:param: type The object type that has a counter.
:param: name The name of the counter property.
:param: countingType The object type that is being counted.
*/
func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type)
/**
Register a counter with a predicate. The predicate can be used to filter which
objects affect the count. If the object is updated, the predicate is evaulated
before and after the change and the counter is updated accordingly.
:param: type The object type that has a counter.
:param: name The name of the counter property.
:param: countingType The object type that is being counted.
:param: predicate A predicate that determines whether the counter applies.
*/
func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type, predicate: CounterPredicate?)
}
/**
Core functionality for persisting BaseItems. It coordinates the mapping from
objects to firebase storage through create/update/delete operations. Extensible
to provide custom functionality through subclassing.
NOTE: Client code should not interact with this class directly. Use the ResourceRegistry
protocol to register paths, and the far more convient ResourceContext to invoke
create/update/destroy. The public methods in this class generally are so for subclasses.
*/
public class ResourceBase : CustomDebugStringConvertible {
struct ResourceSpec : CustomDebugStringConvertible {
let type: BaseItemProtocol.Type
let path: String
init(type: BaseItemProtocol.Type, path: String) {
self.type = type
self.path = path
}
var debugDescription: String {
return "\(path) \(type)"
}
}
struct CounterSpec : CustomDebugStringConvertible, Equatable {
let type: BaseItemProtocol.Type
let countingType: BaseItemProtocol.Type
let path: String
let predicate: CounterPredicate?
init(type: BaseItemProtocol.Type, countingType: BaseItemProtocol.Type, path: String, predicate: CounterPredicate?) {
self.type = type
self.countingType = countingType
self.path = path
self.predicate = predicate
}
var debugDescription: String {
return "\(path) \(type) counting: \(countingType)"
}
}
struct ResolvedCounter : Hashable {
let spec: CounterSpec
let counterInstance: BaseItemProtocol
init(spec: CounterSpec, counterInstance: BaseItemProtocol) {
self.spec = spec
self.counterInstance = counterInstance
}
var hashValue: Int {
return spec.path.hashValue
}
}
/// The underlying firebase instance for this base.
public let firebase: Firebase
var resources = [ResourceSpec]()
var counters = [CounterSpec]()
/// An error handler. Set this to be notified of errors communicating with Firebase.
public var errorHandler: ResourceErrorHandler?
/**
Construct a new instance.
:param: firebase The underlying Firebase store.
*/
public init(firebase: Firebase) {
self.firebase = firebase
}
/// Provide a description including basic stats.
public var debugDescription: String {
return "ResourceBase with \(resources.count) resources and \(counters.count) counters"
}
// MARK: Create hooks
/**
Called before creating an instance. Subclass can invoke done handler when ready (eg,
after performing some network operation, including one with firebase). If ```done()```
is not invoked, then nothing happens. If it's invoked with an error, then the error
handler is invoked and no futher processing happens.
:param: instance The instance to create. Typically the key is nil.
:param: key The key for the instance. Typically this is a new auto id.
:param: context The resouce context for this request.
:param: done The handler to call (or not) for storage process to continue.
*/
public func willCreateInstance(instance: BaseItemProtocol, key: String, context: ResourceContext, done: ResourceDoneHandler) {
done(error: nil)
}
/**
Called immediately after a newly created instance has added to local storage. The
underlying Firebase will asynchronously push that instance to cloud storage.
:param: instance The instance that was just created with key filled in.
:param: context The resource context.
*/
public func didCreateInstance(instance: BaseItemProtocol, context: ResourceContext) {
}
/**
Called after a newly created instance has been successfully persisted. Note that
if the client is offline, this may never be called even if the operation succeeeds.
For example, the app might be restarted before it goes back online.
:param: instance The instance just persisted.
:param: context The resource context.
:param: error The error. If non-nil, the instance is NOT expected to be stored in cloud.
*/
public func didCreateAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) {
}
// MARK: Update hooks
/**
Called before updating an instance. Subclasses can reject this operation by not
calling ```done()```.
:param: instance The instance being updated.
:param: context The resource context.
:param: done Invoke this when ready to proceed with update.
*/
public func willUpdateInstance(instance: BaseItemProtocol, context: ResourceContext, done: ResourceDoneHandler) {
done(error: nil)
}
/**
Called immediately after an instance has been updated.
:param: instance The instance updated.
:param: context The resource context.
*/
public func didUpdateInstance(instance: BaseItemProtocol, context: ResourceContext) {
}
/**
Called after an instance update has been successfully persisted. Note that if the
client is offline, this may never be called even if the operation succeeeds. For example,
the app might be restarted before it goes back online.
:param: instance The instance just persisted.
:param: context The resource context.
:param: error The error. If non-nil, the update is NOT expected to be stored in cloud.
*/
public func didUpdateAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) {
}
// MARK: Destroy hooks
/**
Called before deleting an instance. Subclasses can reject this operation by not
calling ```done()```.
:param: instance The instance being updated.
:param: context The resource context.
:param: done Invoke this when ready to proceed with update.
*/
public func willDestroyInstance(instance: BaseItemProtocol, context: ResourceContext, done: ResourceDoneHandler) {
done(error: nil)
}
/**
Called immediately after an instance has been deleted.
:param: instance The instance updated.
:param: context The resource context.
*/
public func didDestroyInstance(instance: BaseItemProtocol, context: ResourceContext) {
}
/**
Called after an instance delete has been successfully persisted. Note that if the client
is offline, this may never be called even if the operation succeeeds. For example, the
app might be restarted before it goes back online.
:param: instance The instance just deleted from persistent store.
:param: context The resource context.
:param: error The error. If non-nil, the delete is NOT expected to be stored in cloud.
*/
public func didDestroyAndPersistInstance(instance: BaseItemProtocol, context: ResourceContext, error: NSError?) {
}
/**
Return the path part of the Firebase ref. Eg, if the ref is ```"https://my.firebaseio.com/a/b/c"```,
this method would return ```"/a/b/c"```.
:param: ref The Firebase ref.
:returns: The path part of the ref URL.
*/
public class func refToPath(ref: Firebase) -> String {
return NSURL(string: ref.description())!.path!
}
/**
Override to maintain an log of actions for server-side processing of side-effects, notifications, etc.
For more information, see: https://medium.com/@spf2/action-logs-for-firebase-30a699200660
:param: path The path of the resource that just changed.
:param: old The previous state of the data. If present, this is an update or delete.
:param: new The new state of the data. If present, this is a create or update.
:param: extraContext The context values that were not used in resolving the path.
*/
public func logAction(path: String, old: FDataSnapshot?, new: BaseItemProtocol?, extraContext: ResourceDict) {
}
/**
Helper for splitting a path into components like "/a/b/c" -> ["a", "b", "c"]. Leading "/" ignored.
:param: path The path to split.
:returns: An array of path components.
*/
public class func splitPath(path: String) -> [String] {
var p = path
p.trimPrefix("/")
return p.componentsSeparatedByString("/")
}
func buildRef(path: String, key: String?, context: ResourceContext) -> Firebase {
var ref = firebase
for part in ResourceBase.splitPath(path) {
if part == "@" {
if let k = key {
ref = ref.childByAppendingPath(k)
} else {
ref = ref.childByAutoId()
}
} else if part.hasPrefix("$") {
let name = part.prefixTrimmed("$")
if let obj = context.get(name) {
ref = ref.childByAppendingPath(obj.key!)
} else {
fatalError("Cannot find \"\(name)\" for \(path) with context: \(context)")
}
} else {
ref = ref.childByAppendingPath(part)
}
}
return ref
}
private func log(ref: Firebase, old: FDataSnapshot?, new: BaseItemProtocol?, context: ResourceContext, path: String) {
let path = ResourceBase.refToPath(ref)
var extra = ResourceDict()
let skip = Set(ResourceBase.splitPath(path).filter{ $0.hasPrefix("$") }.map{ $0.prefixTrimmed("$") })
for (k, v) in context {
if !skip.contains(k) {
extra[k] = v
}
}
logAction(path, old: old, new: new, extraContext: extra)
}
func incrementCounter(ref: Firebase, by: Int) {
ref.runTransactionBlock({ current in
var result = max(0, by)
if let v = current.value as? Int {
result = v + by
}
current.value = result
return FTransactionResult.successWithValue(current)
})
}
public func findResourcePath(type: BaseItemProtocol.Type, context: ResourceContext?) -> String? {
return resources.filter({ $0.type.self === type }).first?.path
}
func findCounters(countingInstance: BaseItemProtocol, context: ResourceContext) -> [ResolvedCounter] {
return counters.filter { spec in
if spec.countingType.self !== countingInstance.dynamicType.self {
return false
}
if let pred = spec.predicate {
return pred(countingInstance)
}
return true
}.map { spec in
(spec, self.findCounterInstance(spec.type, context: context))
}.filter { (spec, instance) in
instance != nil
}.map { (spec, instance) in
ResolvedCounter(spec: spec, counterInstance: instance!)
}
}
func findCounterInstance(type: BaseItemProtocol.Type, context: ResourceContext) -> BaseItemProtocol? {
for (_, v) in context {
if v.dynamicType.self === type.self {
return v
}
}
return nil
}
/**
Get the Firebase ref for a given instance in this context.
:param: instance The instance.
:param: context The resource context.
:returns: A firebase ref for this instance in this context.
*/
public func ref(instance: BaseItemProtocol, context: ResourceContext) -> Firebase {
let path = findResourcePath(instance.dynamicType, context: context)
assert(path != nil, "Cannot find ref for type \(instance.dynamicType)")
return buildRef(path!, key: instance.key, context: context)
}
/**
Get a Firebase ref for where instances of this type are stored.
:param: type The type.
:param: context The resource context.
:returns: A firebase ref where to find instances of the given type.
*/
public func collectionRef(type: BaseItemProtocol.Type, context: ResourceContext) -> Firebase {
let path = findResourcePath(type, context: context)
assert(path != nil, "Cannot find stream for type \(type)")
return buildRef(path!, key: "~", context: context).parent
}
/**
Store a a new item. If the key is not provided and the path its type is
registered with contains "@", then an auto-id will be generated.
:param: instance The instance to create.
:param: context The resource context.
*/
public func create(instance: BaseItemProtocol, context: ResourceContext) {
let path = findResourcePath(instance.dynamicType, context: context)!
let ref = buildRef(path, key: instance.key, context: context)
let inflight = Inflight()
willCreateInstance(instance, key: ref.key, context: context) { (error) in
if let err = error {
self.errorHandler?(error: err)
} else {
instance.key = ref.key
ref.setValue(instance.dict) { (error, ref) in
inflight.hold()
if let err = error {
self.errorHandler?(error: err)
}
self.didCreateAndPersistInstance(instance, context: context, error: error)
}
for counter in self.findCounters(instance, context: context) {
let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context)
self.incrementCounter(counterRef, by: 1)
}
self.log(ref, old: nil, new: instance, context: context, path: path)
self.didCreateInstance(instance, context: context)
}
}
}
/**
Store updates made to an item.
:param: instance The instance to update.
:param: context The resource context.
*/
public func update(instance: BaseItemProtocol, context: ResourceContext) {
let path = findResourcePath(instance.dynamicType, context: context)!
let ref = buildRef(path, key: instance.key, context: context)
let inflight = Inflight()
willUpdateInstance(instance, context: context) { (error) in
if let err = error {
self.errorHandler?(error: err)
} else {
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
ref.updateChildValues(instance.dict) { (error, ref) in
inflight.hold()
if let err = error {
self.errorHandler?(error: err)
}
self.didUpdateAndPersistInstance(instance, context: context, error: error)
}
// If this change affects any counters, do corresponding increments and decrements.
if let dict = snapshot.value as? [String: AnyObject] {
let prev = instance.clone()
prev.update(dict)
let prevCounters = Set(self.findCounters(prev, context: context))
let curCounters = Set(self.findCounters(instance, context: context))
for counter in curCounters.subtract(prevCounters) {
let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context)
self.incrementCounter(counterRef, by: 1)
}
for counter in prevCounters.subtract(curCounters) {
let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context)
self.incrementCounter(counterRef, by: -1)
}
}
self.log(ref, old: snapshot, new: instance, context: context, path: path)
}, withCancelBlock: { error in
self.errorHandler?(error: error)
})
self.didUpdateInstance(instance, context: context)
}
}
}
/**
Remove an item from cloud store.
:param: instance The instance to update.
:param: context The resource context.
*/
public func destroy(instance: BaseItemProtocol, context: ResourceContext) {
let path = findResourcePath(instance.dynamicType, context: context)!
let ref = buildRef(path, key: instance.key, context: context)
let inflight = Inflight()
willDestroyInstance(instance, context: context) { (error) in
if let err = error {
self.errorHandler?(error: err)
} else {
ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
ref.removeValueWithCompletionBlock { (error, ref) in
inflight.hold()
if let err = error {
self.errorHandler?(error: err)
}
self.didDestroyAndPersistInstance(instance, context: context, error: error)
}
for counter in self.findCounters(instance, context: context) {
let counterRef = self.buildRef(counter.spec.path, key: counter.counterInstance.key, context: context)
self.incrementCounter(counterRef, by: -1)
}
self.log(ref, old: snapshot, new: nil, context: context, path: path)
}, withCancelBlock: { error in
self.errorHandler?(error: error)
})
self.didDestroyInstance(instance, context: context)
}
}
}
}
extension ResourceBase : ResourceRegistry {
public func resource(type: BaseItemProtocol.Type, path: String) {
precondition(findResourcePath(type, context: nil) == nil, "Attempted to add resource twice for same type: \(type) at \(path)")
let spec = ResourceSpec(type: type, path: path)
resources.append(spec)
}
public func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type) {
counter(type, name: name, countingType: countingType, predicate: nil)
}
public func counter(type: BaseItemProtocol.Type, name: String, countingType: BaseItemProtocol.Type, predicate: CounterPredicate?) {
let path = [findResourcePath(type, context: nil)!, name].joinWithSeparator("/")
counters.append(CounterSpec(type: type, countingType: countingType, path: path, predicate: predicate))
}
}
func ==(lhs: ResourceBase.CounterSpec, rhs: ResourceBase.CounterSpec) -> Bool {
return lhs.path == rhs.path && lhs.countingType === rhs.countingType
}
func ==(lhs: ResourceBase.ResolvedCounter, rhs: ResourceBase.ResolvedCounter) -> Bool {
return lhs.spec == rhs.spec && lhs.counterInstance === rhs.counterInstance
}
| mit | bc45c41e39b7579ce6f7adccf3ae51db | 39.932624 | 135 | 0.613575 | 4.835777 | false | false | false | false |
CoderAlexChan/AlexCocoa | Date/String+date.swift | 1 | 1331 | //
// String+extension.swift
// Main
//
// Created by 陈文强 on 17/4/12.
// Copyright © 2017年 陈文强. All rights reserved.
//
import Foundation
extension String {
/// Creates a `Date` instance representing the receiver parsed into `Date` in a given format.
///
/// - parameter format: The format to be used to parse.
/// - returns: The created `Date` instance.
public func date(format: String) -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter.date(from: self)
}
/// Creates a `Date` instance representing the receiver in ISO8601 format parsed into `Date` with given options.
///
/// - parameter options: The options to be used to parse.
/// - returns: The created `Date` instance.
@available(iOS 10.0, OSX 10.12, watchOS 3.0, tvOS 10.0, *)
public func dateInISO8601Format(options: ISO8601DateFormatter.Options = [.withInternetDateTime]) -> Date? {
let dateFormatter = ISO8601DateFormatter()
dateFormatter.formatOptions = options
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter.date(from: self)
}
}
| mit | 897dacacdb4fbfe9b9be94a4207a7b61 | 36.6 | 116 | 0.669453 | 4.2589 | false | false | false | false |
wirawansanusi/WSPagePreview | Example/WSPagePreview/ViewController.swift | 1 | 2894 | //
// ViewController.swift
// WSPagePreview
//
// Created by wirawan-syscli on 07/23/2015.
// Copyright (c) 2015 wirawan-syscli. All rights reserved.
//
import UIKit
class ViewController: UIViewController, WSPagePreviewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
var pagePreview: WSPagePreview?
override func viewDidLoad() {
super.viewDidLoad()
// Convenience init with default settings (Paper size: A4, Margin: 0 cm)
pagePreview = WSPagePreview()
// Default init requires you to specify the paper size and page margin
// pagePreview = WSPagePreview(pageSize: CGSize, pageMargin: UIEdgeInsets, fontSize: CGFloat)
pagePreview?.delegate = self
}
override func viewDidLayoutSubviews() {
// You need to run this following code on viewDidLayoutSubviews
// in order to get the correct scrollView frame / bounds size
pagePreview?.initDefaultSettings(scrollView)
// Optional
customConfigurations()
}
// You must implement this delegate method
func WSPagePreviewSetTextContent(pagePreview: WSPagePreview) -> String {
// Set text
let path = NSBundle.mainBundle().pathForResource("sampleText", ofType: ".txt")
let textNSString = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: nil)
let text = String(textNSString!)
return text
}
}
// OPTIONAL
extension ViewController {
// Use this function to show the page control
func WSPagePreviewShowPageControl(pagePreview: WSPagePreview, pageControl: UIPageControl) {
// For the sake of styling and ofcourse it's optional
pageControl.frame = CGRectMake(pageControl.frame.origin.x, pageControl.frame.origin.y + 20.0, pageControl.frame.width, pageControl.frame.height)
pageControl.currentPageIndicatorTintColor = UIColor.lightGrayColor()
pageControl.pageIndicatorTintColor = UIColor.whiteColor()
// Show page control in view
view.addSubview(pageControl)
}
func customConfigurations() {
// Set a custom page margin
let margin = UIEdgeInsetsMake(20.0, 20.0, 20.0, 20.0)
pagePreview?.setPageMargin(margin)
// Set a custom page size
let size = CGSize(width: 500.0, height: 500.0)
pagePreview?.setPageSize(size)
// Set a custom font size
pagePreview?.setFontSize(14.0)
}
func setHorizontalMargin() {
// Set a custom page horizontal margin
pagePreview?.setPageMarginHorizontally(20.0, right: 20.0)
}
func setVerticalMargin() {
// Set a custom page vertical margin
pagePreview?.setPageMarginVertically(20.0, bottom: 20.0)
}
}
| apache-2.0 | 538b8762898db3982be688ee05d6152d | 30.456522 | 152 | 0.646164 | 4.831386 | false | false | false | false |
cemolcay/YSCards | YSCards/YSCards/Helpers/YSBlockButton.swift | 1 | 2485 | //
// YSBlockButton.swift
// YSCards
//
// Created by Cem Olcay on 30/10/15.
// Copyright © 2015 prototapp. All rights reserved.
//
import UIKit
typealias YSBlockButtonAction = (sender: YSBlockButton) -> Void
class YSBlockButton: UIButton {
// MARK: Propeties
var highlightLayer: CALayer?
var action: YSBlockButtonAction?
// MARK: Init
init (x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init (frame: CGRect (x: x, y: y, width: w, height: h))
defaulInit()
}
init (x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: YSBlockButtonAction?) {
super.init (frame: CGRect (x: x, y: y, width: w, height: h))
self.action = action
defaulInit()
}
override init (frame: CGRect) {
super.init(frame: frame)
defaulInit()
}
init (frame: CGRect, action: YSBlockButtonAction) {
super.init(frame: frame)
self.action = action
defaulInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func defaulInit () {
addTarget(self, action: "didPressed:", forControlEvents: .TouchUpInside)
addTarget(self, action: "highlight", forControlEvents: [.TouchDown, .TouchDragEnter])
addTarget(self, action: "unhighlight", forControlEvents: [.TouchUpInside, .TouchUpOutside, .TouchCancel, .TouchDragExit])
}
// MARK: Action
func didPressed (sender: YSBlockButton) {
action? (sender: sender)
}
// MARK: Highlight
func highlight () {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.blackColor().CGColor
highlightLayer.opacity = 0.5
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let maskImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage.CGImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
func unhighlight () {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
| mit | be1053e1e1f789ebfc9da6ba6d378e94 | 26.910112 | 129 | 0.630435 | 4.5 | false | false | false | false |
huangboju/Moots | Examples/UIScrollViewDemo/UIScrollViewDemo/Account/Views/Cells/TextFiledCell.swift | 1 | 2509 | //
// TextFiledCell.swift
// UIScrollViewDemo
//
// Created by 黄伯驹 on 2017/11/3.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
class TextFiledCell: UITableViewCell, Updatable {
typealias FileItem = (placeholder: String?, iconName: String)
final var inputText: String? {
return textField.text
}
final func setField(with item: FileItem) {
var attri: NSAttributedString?
if let placeholder = item.placeholder {
attri = NSAttributedString(string: placeholder, attributes: [
.font: UIFontMake(15)
])
}
textField.attributedPlaceholder = attri
imageView?.image = UIImage(named: item.iconName)
}
final func setRightView(with rightView: UIView?) {
guard let rightView = rightView else {
textField.rightView = nil
textField.rightViewMode = .never
return
}
textField.rightView = rightView
textField.rightViewMode = .always
}
let textField = UITextField()
private let bottomLine = UIView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
contentView.addSubview(textField)
textField.snp.makeConstraints { (make) in
make.leading.equalTo(45)
make.trailing.equalTo(-16)
make.top.bottom.equalTo(self)
}
textField.addTarget(self, action: #selector(editingDidBeginAction), for: .editingDidBegin)
textField.addTarget(self, action: #selector(editingDidEndAction), for: .editingDidEnd)
contentView.addSubview(bottomLine)
bottomLine.snp.makeConstraints { (make) in
make.height.equalTo(1)
make.leading.equalTo(16)
make.trailing.equalTo(-16)
make.bottom.equalToSuperview()
}
bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC)
didInitialzed()
}
open func didInitialzed() {}
@objc
private func editingDidBeginAction() {
bottomLine.backgroundColor = UIColor(hex: 0xA356AB)
}
@objc
private func editingDidEndAction() {
bottomLine.backgroundColor = UIColor(hex: 0xCCCCCC)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func update(viewData: NoneItem) {}
}
| mit | 811d83b0b19dbdc2ec9ec20471cf9a08 | 27.340909 | 98 | 0.630714 | 4.796154 | false | false | false | false |
ilyapuchka/SwiftNetworking | SwiftNetworking/APIRequest.swift | 1 | 4139 | //
// APIRequest.swift
// SwiftNetworking
//
// Created by Ilya Puchka on 16.08.15.
// Copyright © 2015 Ilya Puchka. All rights reserved.
//
import Foundation
public enum HTTPMethod: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
}
public protocol Endpoint {
var path: String {get}
var signed: Bool {get}
var method: HTTPMethod {get}
}
public typealias MIMEType = String
public enum HTTPContentType: RawRepresentable {
case JSON
case form
case multipart(String)
public typealias RawValue = MIMEType
public init?(rawValue: HTTPContentType.RawValue) {
switch rawValue {
case "application/json": self = .JSON
default: return nil
}
}
public var rawValue: HTTPContentType.RawValue {
switch self {
case .JSON: return "application/json"
case .form: return "application/x-www-form-urlencoded"
case .multipart(let boundary): return "multipart/form-data; boundary=\(boundary)"
}
}
}
public enum HTTPHeader: Equatable {
case ContentDisposition(String)
case Accept([HTTPContentType])
case ContentType(HTTPContentType)
case Authorization(AccessToken)
case Custom(String, String)
public var key: String {
switch self {
case .ContentDisposition:
return "Content-Disposition"
case .Accept:
return "Accept"
case .ContentType:
return "Content-Type"
case .Authorization:
return "Authorization"
case .Custom(let key, _):
return key
}
}
public var requestHeaderValue: String {
switch self {
case .ContentDisposition(let disposition):
return disposition
case .Accept(let types):
let typeStrings = types.map({$0.rawValue})
return typeStrings.joinWithSeparator(", ")
case .ContentType(let type):
return type.rawValue
case .Authorization(let token):
return token.requestHeaderValue
case .Custom(_, let value):
return value
}
}
public func setRequestHeader(request: NSMutableURLRequest) {
request.setValue(requestHeaderValue, forHTTPHeaderField: key)
}
}
//MARK: - Equatable
public func ==(lhs: HTTPHeader, rhs: HTTPHeader) -> Bool {
return lhs.key == rhs.key && lhs.requestHeaderValue == rhs.requestHeaderValue
}
public protocol APIRequestDataEncodable {
func encodeForAPIRequestData() throws -> NSData
}
public protocol APIResponseDecodable {
init?(apiResponseData: NSData) throws
}
public typealias APIRequestQuery = [String: String]
public protocol APIRequestType {
var body: NSData? {get}
var endpoint: Endpoint {get}
var baseURL: NSURL {get}
var headers: [HTTPHeader] {get}
var query: APIRequestQuery {get}
}
public struct APIRequestFor<ResultType: APIResponseDecodable>: APIRequestType {
public let body: NSData?
public let endpoint: Endpoint
public let baseURL: NSURL
public let headers: [HTTPHeader]
public let query: APIRequestQuery
public init(endpoint: Endpoint, baseURL: NSURL, query: APIRequestQuery = APIRequestQuery(), headers: [HTTPHeader] = []) {
self.endpoint = endpoint
self.baseURL = baseURL
self.query = query
self.headers = headers
self.body = nil
}
public init(endpoint: Endpoint, baseURL: NSURL, input: APIRequestDataEncodable, query: APIRequestQuery = APIRequestQuery(), headers: [HTTPHeader] = []) throws {
self.endpoint = endpoint
self.baseURL = baseURL
self.query = query
self.headers = headers
self.body = try input.encodeForAPIRequestData()
}
public init(endpoint: Endpoint, baseURL: NSURL, body: NSData, query: APIRequestQuery = APIRequestQuery(), headers: [HTTPHeader] = []) {
self.endpoint = endpoint
self.baseURL = baseURL
self.query = query
self.headers = headers
self.body = body
}
}
| mit | 4db184eeecf0c0efc51f44d3f1454b21 | 26.045752 | 164 | 0.639198 | 4.602892 | false | false | false | false |
steelwheels/KiwiScript | KiwiLibrary/Test/UnitTest/UTCommand.swift | 1 | 2540 | /*
* @file UTCommand.swift
* @brief Unit test for KLCommand class
* @par Copyright
* Copyright (C) 2020 Steel Wheels Project
*/
import KiwiLibrary
import KiwiEngine
import CoconutData
import JavaScriptCore
import Foundation
public func UTCommand(context ctxt: KEContext, console cons: CNFileConsole, environment env: CNEnvironment) -> Bool
{
let res0 = UTCdCommand(context: ctxt, console: cons, environment: env)
return res0
}
private func UTCdCommand(context ctxt: KEContext, console cons: CNFileConsole, environment env: CNEnvironment) -> Bool
{
var result = true
let orgdir = env.currentDirectory
cons.print(string: "Before execute cd command: curdir=\(orgdir.absoluteString) \n")
/* Change directory to parent */
let res0 = execCdCommand(context: ctxt, path: "..", cons: cons, environment: env)
if res0 != 0 {
cons.print(string: "[Error] cd is failed\n")
result = false
}
/* Change directory to invalid directory */
let res1 = execCdCommand(context: ctxt, path: "Hoge", cons: cons, environment: env)
if res1 == 0 {
cons.print(string: "[Error] cd is successed\n")
result = false
}
/* Change directory to "Debug" directory */
let res2 = execCdCommand(context: ctxt, path: "./Debug", cons: cons, environment: env)
if res2 != 0 {
cons.print(string: "[Error] cd is failed\n")
result = false
}
/* Change directory to "Home" directory */
let res3 = execCdCommand(context: ctxt, path: nil, cons: cons, environment: env)
if res3 != 0 {
cons.print(string: "[Error] cd is failed\n")
result = false
}
return result
}
private func execCdCommand(context ctxt: KEContext, path pstr: String?, cons: CNFileConsole, environment env: CNEnvironment) -> Int32 {
cons.print(string: "cd command: \(String(describing: pstr))\n")
cons.print(string: "(prev) dir \(env.currentDirectory.absoluteString)\n")
let cdparam = makeCdParameter(context: ctxt, path: pstr)
let cdcmd = KLCdCommand(context: ctxt, console: cons, environment: env)
cdcmd.start(cdparam)
var dowait = true
while dowait {
let val = cdcmd.isRunning
if val.isBoolean {
dowait = val.toBool()
} else {
cons.print(string: "[Error] Invalid data type")
}
}
let res = cdcmd.exitCode.toInt32()
cons.print(string: " -> result \(res)\n")
cons.print(string: "(after) dir \(env.currentDirectory.absoluteString)\n")
return res
}
private func makeCdParameter(context ctxt: KEContext, path pstr: String?) -> JSValue {
if let path = pstr {
return JSValue(object: path, in: ctxt)
} else {
return JSValue(nullIn: ctxt)
}
}
| lgpl-2.1 | 13e5fc3f725624fe16885e5ffad15731 | 28.534884 | 135 | 0.706693 | 3.227446 | false | false | false | false |
kripple/bti-watson | ios-app/Carthage/Checkouts/AlamofireObjectMapper/Carthage/Checkouts/ObjectMapper/ObjectMapper/Core/Map.swift | 3 | 3464 | //
// Map.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-10-09.
// Copyright © 2015 hearst. All rights reserved.
//
import Foundation
/// A class used for holding mapping data
public final class Map {
public let mappingType: MappingType
var JSONDictionary: [String : AnyObject] = [:]
var currentValue: AnyObject?
var currentKey: String?
var keyIsNested = false
/// Counter for failing cases of deserializing values to `let` properties.
private var failedCount: Int = 0
public init(mappingType: MappingType, JSONDictionary: [String : AnyObject]) {
self.mappingType = mappingType
self.JSONDictionary = JSONDictionary
}
/// Sets the current mapper value and key.
/// The Key paramater can be a period separated string (ex. "distance.value") to access sub objects.
public subscript(key: String) -> Map {
// save key and value associated to it
return self[key, nested: true]
}
public subscript(key: String, nested nested: Bool) -> Map {
// save key and value associated to it
currentKey = key
keyIsNested = nested
// check if a value exists for the current key
if nested == false {
currentValue = JSONDictionary[key]
} else {
// break down the components of the key that are separated by .
currentValue = valueFor(ArraySlice(key.componentsSeparatedByString(".")), collection: JSONDictionary)
}
return self
}
// MARK: Immutable Mapping
public func value<T>() -> T? {
return currentValue as? T
}
public func valueOr<T>(@autoclosure defaultValue: () -> T) -> T {
return value() ?? defaultValue()
}
/// Returns current JSON value of type `T` if it is existing, or returns a
/// unusable proxy value for `T` and collects failed count.
public func valueOrFail<T>() -> T {
if let value: T = value() {
return value
} else {
// Collects failed count
failedCount++
// Returns dummy memory as a proxy for type `T`
let pointer = UnsafeMutablePointer<T>.alloc(0)
pointer.dealloc(0)
return pointer.memory
}
}
/// Returns whether the receiver is success or failure.
public var isValid: Bool {
return failedCount == 0
}
}
/// Fetch value from JSON dictionary, loop through them until we reach the desired object.
private func valueFor(keyPathComponents: ArraySlice<String>, collection: AnyObject?) -> AnyObject? {
// Implement it as a tail recursive function.
if keyPathComponents.isEmpty {
return nil
}
//optional object to keep optional retreived from collection
var optionalObject: AnyObject?
//check if collection is dictionary or array (if it's array, also try to convert keypath to Int as index)
if let dictionary = collection as? [String : AnyObject],
let keyPath = keyPathComponents.first {
//keep retreved optional
optionalObject = dictionary[keyPath]
} else if let array = collection as? [AnyObject],
let keyPath = keyPathComponents.first,
index = Int(keyPath) {
//keep retreved optional
optionalObject = array[index]
}
if let object = optionalObject {
if object is NSNull {
return nil
} else if let dict = object as? [String : AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, collection: dict)
} else if let dict = object as? [AnyObject] where keyPathComponents.count > 1 {
let tail = keyPathComponents.dropFirst()
return valueFor(tail, collection: dict)
} else {
return object
}
}
return nil
} | mit | 0cbcc5d4c4e33b4f9ad50c30985ea5da | 27.162602 | 106 | 0.705458 | 3.886644 | false | false | false | false |
RicardoDaSilvaSouza/StudyProjects | RSSAvaliacaoIntro/RSSAvaliacaoIntro/RSSImageSelectViewController.swift | 1 | 1813 | //
// RSSImageSelectViewController.swift
// RSSAvaliacaoIntro
//
// Created by Usuário Convidado on 23/02/16.
// Copyright © 2016 Usuário Convidado. All rights reserved.
//
import UIKit
class RSSImageSelectViewController: UIViewController {
var delegate:RSSImageSelectViewControllerDelegate?
var fruitNames:[String] = ["abacaxi","banana","cereja","kiwi","laranja","limao","manga","uva"]
override func viewDidLoad() {
super.viewDidLoad()
var x:Int = 20
let y:Int = 110
var counter:Int = 1
var line:Int = 1
for fruitName:String in fruitNames {
let uiButton:UIButton = UIButton(frame: CGRect(x: CGFloat(x), y: CGFloat(y * line), width: CGFloat(100), height: CGFloat(100)))
uiButton.titleLabel?.text = fruitName
uiButton.setImage(UIImage(named: fruitName), forState: UIControlState.Normal)
uiButton.addTarget(self, action: "fruitClick:", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(uiButton)
if(counter == 2){
counter = 1
line += 1
x = 20
} else {
counter += 1
x = 180
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func fruitClick(caller:UIButton){
self.delegate?.fruitIsSelected((caller.titleLabel?.text)!)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
protocol RSSImageSelectViewControllerDelegate{
func fruitIsSelected(fruit:String) -> Void
}
| apache-2.0 | 21b9aec6965e09bde276c0a38a7690e7 | 30.206897 | 139 | 0.602762 | 4.605598 | false | false | false | false |
QuarkWorks/RealmModelGenerator | RealmModelGenerator/AttributesRelationshipsMainVC.swift | 1 | 3303 |
// AttributesRelationshipsMainVC.swift
// RealmModelGenerator
//
// Created by Zhaolong Zhong on 3/31/16.
// Copyright © 2016 QuarkWorks. All rights reserved.
//
import Cocoa
protocol AttributesRelationshipsVCDelegate: AnyObject {
func attributesRelationshipsVC(attributesRelationshipsVC:AttributesRelationshipsMainVC, selectedAttributeDidChange attribute:Attribute?)
func attributesRelationshipsVC(attributesRelationshipsVC:AttributesRelationshipsMainVC, selectedRelationshipDidChange relationship:Relationship?)
}
class AttributesRelationshipsMainVC: NSViewController, AttributesVCDelegate, RelationshipsVCDelegate {
static let TAG = NSStringFromClass(AttributesRelationshipsMainVC.self)
var attributesVC:AttributesVC! {
didSet {
self.attributesVC.delegate = self
}
}
var relationshipsVC:RelationshipsVC! {
didSet {
self.relationshipsVC.delegate = self
}
}
@IBOutlet weak var relationshipsContainerView: NSView!
@IBOutlet weak var attributesContainerView: NSView!
weak var delegate: AttributesRelationshipsVCDelegate?
weak var selectedEntity:Entity? {
didSet {
if self.selectedEntity === oldValue { return }
self.selectedAttribute = nil
self.selectedRelationship = nil
self.invalidateViews()
}
}
weak var selectedAttribute: Attribute? {
didSet {
if self.selectedAttribute === oldValue { return }
self.delegate?.attributesRelationshipsVC(attributesRelationshipsVC: self, selectedAttributeDidChange: self.selectedAttribute)
self.invalidateViews()
}
}
weak var selectedRelationship: Relationship? {
didSet {
if self.selectedRelationship === oldValue { return }
self.delegate?.attributesRelationshipsVC(attributesRelationshipsVC: self, selectedRelationshipDidChange: self.selectedRelationship)
self.invalidateViews()
}
}
// MARK - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear() {
super.viewWillAppear()
self.invalidateViews()
}
// MARK - Invalidation
func invalidateViews() {
if !isViewLoaded { return }
self.attributesVC.selectedEntity = self.selectedEntity
self.relationshipsVC.selectedEntity = self.selectedEntity
}
// MARK: - AttributesVC delegate
func attributesVC(attributesVC: AttributesVC, selectedAttributeDidChange attribute:Attribute?) {
self.selectedAttribute = attribute
}
// MARK: - RelationshipsVC delegate
func relationshipsVC(relationshipsVC: RelationshipsVC, selectedRelationshipDidChange relationship: Relationship?) {
self.selectedRelationship = relationship
}
// MARK: - Segue
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.destinationController is AttributesVC {
self.attributesVC = segue.destinationController as! AttributesVC
} else if segue.destinationController is RelationshipsVC {
self.relationshipsVC = segue.destinationController as! RelationshipsVC
}
}
}
| mit | 0bd925c5337479ea402f5b0ab153c3e9 | 33.041237 | 149 | 0.691399 | 5.475954 | false | false | false | false |
ashfurrow/eidolon | Kiosk/Bid Fulfillment/BidCheckingNetworkModel.swift | 2 | 6013 | import UIKit
import RxSwift
import Moya
enum BidCheckingError: String {
case PollingExceeded
}
extension BidCheckingError: Swift.Error { }
protocol BidCheckingNetworkModelType {
var bidDetails: BidDetails { get }
var bidIsResolved: Variable<Bool> { get }
var isHighestBidder: Variable<Bool> { get }
var reserveNotMet: Variable<Bool> { get }
func waitForBidResolution (bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void>
}
class BidCheckingNetworkModel: NSObject, BidCheckingNetworkModelType {
fileprivate var pollInterval = TimeInterval(1)
fileprivate var maxPollRequests = 20
fileprivate var pollRequests = 0
// inputs
let provider: Networking
let bidDetails: BidDetails
// outputs
var bidIsResolved = Variable(false)
var isHighestBidder = Variable(false)
var reserveNotMet = Variable(false)
fileprivate var mostRecentSaleArtwork: SaleArtwork?
init(provider: Networking, bidDetails: BidDetails) {
self.provider = provider
self.bidDetails = bidDetails
}
func waitForBidResolution (bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> {
return self
.poll(forUpdatedBidderPosition: bidderPositionId, provider: provider)
.then {
return self.getUpdatedSaleArtwork()
.flatMap { saleArtwork -> Observable<Void> in
// This is an updated model – hooray!
self.mostRecentSaleArtwork = saleArtwork
self.bidDetails.saleArtwork?.updateWithValues(saleArtwork)
self.reserveNotMet.value = ReserveStatus.initOrDefault(saleArtwork.reserveStatus).reserveNotMet
return .just(Void())
}
.do(onError: { _ in
logger.log("Bidder position was processed but corresponding saleArtwork was not found")
})
.catchErrorJustReturn(Void())
.flatMap { _ -> Observable<Void> in
return self.checkForMaxBid(provider: provider)
}
}.do(onNext: { _ in
self.bidIsResolved.value = true
// If polling fails, we can still show bid confirmation. Do not error.
}).catchErrorJustReturn(Void())
}
fileprivate func poll(forUpdatedBidderPosition bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<Void> {
let updatedBidderPosition = getUpdatedBidderPosition(bidderPositionId: bidderPositionId, provider: provider)
.flatMap { bidderPositionObject -> Observable<Void> in
self.pollRequests += 1
logger.log("Polling \(self.pollRequests) of \(self.maxPollRequests) for updated sale artwork")
if let processedAt = bidderPositionObject.processedAt {
logger.log("BidPosition finished processing at \(processedAt), proceeding...")
return .just(Void())
} else {
// The backend hasn't finished processing the bid yet
guard self.pollRequests < self.maxPollRequests else {
// We have exceeded our max number of polls, fail.
throw BidCheckingError.PollingExceeded
}
// We didn't get an updated value, so let's try again.
return Observable<Int>.interval(self.pollInterval, scheduler: MainScheduler.instance)
.take(1)
.map(void)
.then {
return self.poll(forUpdatedBidderPosition: bidderPositionId, provider: provider)
}
}
}
return Observable<Int>.interval(pollInterval, scheduler: MainScheduler.instance)
.take(1)
.map(void)
.then { updatedBidderPosition }
}
fileprivate func checkForMaxBid(provider: AuthorizedNetworking) -> Observable<Void> {
return getMyBidderPositions(provider: provider)
.do(onNext: { newBidderPositions in
if let topBidID = self.mostRecentSaleArtwork?.saleHighestBid?.id {
for position in newBidderPositions where position.highestBid?.id == topBidID {
self.isHighestBidder.value = true
}
}
})
.map(void)
}
fileprivate func getMyBidderPositions(provider: AuthorizedNetworking) -> Observable<[BidderPosition]> {
let artworkID = bidDetails.saleArtwork!.artwork.id;
let auctionID = bidDetails.saleArtwork!.auctionID!
let endpoint = ArtsyAuthenticatedAPI.myBidPositionsForAuctionArtwork(auctionID: auctionID, artworkID: artworkID)
return provider
.request(endpoint)
.filterSuccessfulStatusCodes()
.mapJSON()
.mapTo(arrayOf: BidderPosition.self)
}
fileprivate func getUpdatedSaleArtwork() -> Observable<SaleArtwork> {
let artworkID = bidDetails.saleArtwork!.artwork.id;
let auctionID = bidDetails.saleArtwork!.auctionID!
let endpoint: ArtsyAPI = ArtsyAPI.auctionInfoForArtwork(auctionID: auctionID, artworkID: artworkID)
return provider
.request(endpoint)
.filterSuccessfulStatusCodes()
.mapJSON()
.mapTo(object: SaleArtwork.self)
}
fileprivate func getUpdatedBidderPosition(bidderPositionId: String, provider: AuthorizedNetworking) -> Observable<BidderPosition> {
let endpoint = ArtsyAuthenticatedAPI.myBidPosition(id: bidderPositionId)
return provider
.request(endpoint)
.filterSuccessfulStatusCodes()
.mapJSON()
.mapTo(object: BidderPosition.self)
}
}
| mit | 3b9ffa0ea4ff44123814913f46f610c6 | 38.546053 | 135 | 0.612876 | 5.504579 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/BlockchainNamespace/Sources/BlockchainNamespace/Session/Session+Observer.swift | 1 | 1321 | public protocol SessionObserver: AnyObject, CustomStringConvertible {
func start()
func stop()
}
extension Session {
public typealias Observer = SessionObserver
public class Observers {
var observers: Set<AnyHashable> = []
public func insert<O: Observer>(_ observer: O) {
let (inserted, _) = observers.insert(AnyHashable(Box(observer)))
guard inserted else { return }
observer.start()
}
public func remove<O: Observer>(_ observer: O) {
(observers.remove(AnyHashable(Box(observer))) as? Box<O>)?.value?.stop()
}
}
}
extension SessionObserver {
public var description: String {
"\(type(of: self))"
}
}
private struct Box<Wrapped: AnyObject> {
var value: Wrapped?
init(_ value: Wrapped? = nil) {
self.value = value
}
}
extension Box: Equatable {
static func == (lhs: Box, rhs: Box) -> Bool {
guard let lhs = lhs.value, let rhs = rhs.value else {
return lhs.value == nil && rhs.value == nil
}
return ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}
extension Box: Hashable {
func hash(into hasher: inout Hasher) {
guard let value = value else { return }
hasher.combine(ObjectIdentifier(value))
}
}
| lgpl-3.0 | ea133e5ec11a7ec89dd762298f4dcc6f | 22.589286 | 84 | 0.597275 | 4.288961 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/Blogging Reminders/BloggingRemindersAnimator.swift | 2 | 3523 | /// A transition animator that moves in the pushed view controller horizontally.
/// Does not handle the pop animation since the BloggingReminders setup flow does not allow to navigate back.
class BloggingRemindersAnimator: NSObject, UIViewControllerAnimatedTransitioning {
var popStyle = false
private static let animationDuration: TimeInterval = 0.2
private static let sourceEndFrameOffset: CGFloat = -60.0
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return Self.animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
guard !popStyle else {
animatePop(using: transitionContext)
return
}
guard let sourceViewController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let destinationViewController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else {
return
}
// final position of the destination view
let destinationEndFrame = transitionContext.finalFrame(for: destinationViewController)
// final position of the source view
let sourceEndFrame = transitionContext.initialFrame(for: sourceViewController).offsetBy(dx: Self.sourceEndFrameOffset, dy: .zero)
// initial position of the destination view
let destinationStartFrame = destinationEndFrame.offsetBy(dx: destinationEndFrame.width, dy: .zero)
destinationViewController.view.frame = destinationStartFrame
transitionContext.containerView.insertSubview(destinationViewController.view, aboveSubview: sourceViewController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: {
destinationViewController.view.frame = destinationEndFrame
sourceViewController.view.frame = sourceEndFrame
}, completion: {_ in
transitionContext.completeTransition(true)
})
}
func animatePop(using transitionContext: UIViewControllerContextTransitioning) {
guard let sourceViewController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from),
let destinationViewController =
transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) else {
return
}
let destinationEndFrame = transitionContext.finalFrame(for: destinationViewController)
let destinationStartFrame = destinationEndFrame.offsetBy(dx: Self.sourceEndFrameOffset, dy: .zero)
destinationViewController.view.frame = destinationStartFrame
transitionContext.containerView.insertSubview(destinationViewController.view, belowSubview: sourceViewController.view)
UIView.animate(withDuration: transitionDuration(using: transitionContext),
animations: {
destinationViewController.view.frame = destinationEndFrame
sourceViewController.view.transform = sourceViewController.view.transform.translatedBy(x: sourceViewController.view.frame.width, y: 0)
}, completion: {_ in
transitionContext.completeTransition(true)
})
}
}
| gpl-2.0 | 819462ddacba9636443ebafab56c60a5 | 51.58209 | 158 | 0.699688 | 6.854086 | false | false | false | false |
tjw/swift | test/SILGen/guaranteed_self.swift | 1 | 26049 |
// RUN: %target-swift-frontend -module-name guaranteed_self -Xllvm -sil-full-demangle -emit-silgen %s -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
protocol Fooable {
init()
func foo(_ x: Int)
mutating func bar()
mutating func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get nonmutating set }
}
protocol Barrable: class {
init()
func foo(_ x: Int)
func bar()
func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get set }
}
struct S: Fooable {
var x: C? // Make the type nontrivial, so +0/+1 is observable.
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S
init() {}
// TODO: Way too many redundant r/r pairs here. Should use +0 rvalues.
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func foo(_ x: Int) {
self.foo(x)
}
func foooo(_ x: (Int, Bool)) {
self.foooo(x)
}
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> ()
// CHECK: bb0([[SELF:%.*]] : @trivial $*S):
// CHECK-NOT: destroy_addr [[SELF]]
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> ()
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func bas() {
self.bas()
}
var prop1: Int = 0
// Getter for prop1
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// Setter for prop1
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// materializeForSet for prop1
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop1Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
var prop2: Int {
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop2Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden @$S15guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self1SV5prop3Sivm : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
nonmutating set { }
}
}
// Witness thunk for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for mutating 'bar'
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> () {
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for 'bas', which is mutating in the protocol, but nonmutating
// in the implementation
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) (@inout S) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK: end_borrow [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 getter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 setter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop1SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 getter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 setter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW : $@convention(witness_method: Fooable) (Int, @inout S) -> () {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop2SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 getter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW : $@convention(witness_method: Fooable) (@in_guaranteed S) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating setter
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW : $@convention(witness_method: Fooable) (Int, @in_guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating materializeForSet
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW : $@convention(witness_method: Fooable) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed S) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: } // end sil function '$S15guaranteed_self1SVAA7FooableA2aDP5prop3SivmTW'
//
// TODO: Expected output for the other cases
//
struct AO<T>: Fooable {
var x: T?
init() {}
// CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
func foo(_ x: Int) {
self.foo(x)
}
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
func bas() {
self.bas()
}
var prop1: Int = 0
var prop2: Int {
// CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
// CHECK-LABEL: sil hidden @$S15guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK-LABEL: sil hidden [transparent] @$S15guaranteed_self2AOV5prop3Sivm : $@convention(method) <T> (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @in_guaranteed AO<T>) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
nonmutating set { }
}
}
// Witness for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (Int, @in_guaranteed AO<τ_0_0>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness for 'bar', which is mutating in protocol but nonmutating in impl
// CHECK-LABEL: sil private [transparent] [thunk] @$S15guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Fooable) <τ_0_0> (@inout AO<τ_0_0>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : @trivial $*AO<τ_0_0>):
// -- NB: This copy is not necessary, since we're willing to assume an inout
// parameter is not mutably aliased.
// CHECK: apply {{.*}}([[SELF_ADDR]])
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
class C: Fooable, Barrable {
// Allocating initializer
// CHECK-LABEL: sil hidden @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
// CHECK: [[SELF1:%.*]] = alloc_ref $C
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// Initializing constructors still have the +1 in, +1 out convention.
// CHECK-LABEL: sil hidden @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C {
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]]
// CHECK: destroy_value [[MARKED_SELF]]
// CHECK: return [[MARKED_SELF_RESULT]]
// CHECK: } // end sil function '$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc'
// @objc thunk for initializing constructor
// CHECK-LABEL: sil hidden [thunk] @$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK: } // end sil function '$S15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo'
@objc required init() {}
// CHECK-LABEL: sil hidden @$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $C):
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: } // end sil function '$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [thunk] @$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: } // end sil function '$S15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo'
@objc func foo(_ x: Int) {
self.foo(x)
}
@objc func bar() {
self.bar()
}
@objc func bas() {
self.bas()
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @$S15guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int
// CHECK: bb0([[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}([[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @$S15guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}} [[BORROWED_SELF_COPY]]
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
@objc var prop1: Int = 0
@objc var prop2: Int {
get { return 0 }
set {}
}
@objc var prop3: Int {
get { return 0 }
set {}
}
}
class D: C {
// CHECK-LABEL: sil hidden @$S15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D
// CHECK: [[SELF1:%.*]] = alloc_ref $D
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK-LABEL: sil hidden @$S15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D
// CHECK: bb0([[SELF:%.*]] : @owned $D):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D }
// CHECK-NEXT: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[MARKED_SELF_BOX]]
// CHECK-NEXT: store [[SELF]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK: [[SELF1:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]]
// CHECK-NOT: [[PB]]
// CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]])
// CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]]
// CHECK-NEXT: store [[SELF2]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SUPER1]]
// CHECK-NOT: [[SELF2]]
// CHECK-NOT: [[SUPER2]]
// CHECK: [[SELF_FINAL:%.*]] = load [copy] [[PB]]
// CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]]
// CHECK-NEXT: return [[SELF_FINAL]]
required init() {
super.init()
}
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$S15guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $D):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
dynamic override func foo(_ x: Int) {
self.foo(x)
}
}
func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) {
return (S.foo /*, s.foo*/)
}
func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) {
return (AO.foo /*, ao.foo*/)
}
// ----------------------------------------------------------------------------
// Make sure that we properly translate in_guaranteed parameters
// correctly if we are asked to.
// ----------------------------------------------------------------------------
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] @$S15guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW : $@convention(witness_method: Sequence) (@in_guaranteed FakeElement, @in_guaranteed FakeArray) -> () {
// CHECK: bb0([[ARG0_PTR:%.*]] : @trivial $*FakeElement, [[ARG1_PTR:%.*]] : @trivial $*FakeArray):
// CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]]
// CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement
// CHECK: [[FUN:%.*]] = function_ref @{{.*}}
// CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]])
class Z {}
public struct FakeGenerator {}
public struct FakeArray {
var z = Z()
}
public struct FakeElement {}
public protocol FakeGeneratorProtocol {
associatedtype Element
}
extension FakeGenerator : FakeGeneratorProtocol {
public typealias Element = FakeElement
}
public protocol SequenceDefaults {
associatedtype Element
associatedtype Generator : FakeGeneratorProtocol
}
extension SequenceDefaults {
public func _constrainElement(_: FakeGenerator.Element) {}
}
public protocol Sequence : SequenceDefaults {
func _constrainElement(_: Element)
}
extension FakeArray : Sequence {
public typealias Element = FakeElement
public typealias Generator = FakeGenerator
func _containsElement(_: Element) {}
}
// -----------------------------------------------------------------------------
// Make sure that we do not emit extra copy_values when accessing let fields of
// guaranteed parameters.
// -----------------------------------------------------------------------------
class Kraken {
func enrage() {}
}
func destroyShip(_ k: Kraken) {}
class LetFieldClass {
let letk = Kraken()
var vark = Kraken()
// CHECK-LABEL: sil hidden @$S15guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load_borrow [[KRAKEN_ADDR]]
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN2:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Kraken
// CHECK-NEXT: [[BORROWED_KRAKEN_COPY:%.*]] = begin_borrow [[KRAKEN_COPY]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func letkMethod() {
letk.enrage()
let ll = letk
destroyShip(ll)
var lv = letk
destroyShip(lv)
}
// CHECK-LABEL: sil hidden @$S15guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[BORROWED_KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]] from [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_BOX]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter.1 : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Kraken
// CHECK-NEXT: [[BORROWED_KRAKEN_COPY:%.*]] = begin_borrow [[KRAKEN_COPY]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$S15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN_COPY]])
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func varkMethod() {
vark.enrage()
let vl = vark
destroyShip(vl)
var vv = vark
destroyShip(vv)
}
}
// -----------------------------------------------------------------------------
// Make sure that in all of the following cases find has only one copy_value in it.
// -----------------------------------------------------------------------------
class ClassIntTreeNode {
let value : Int
let left, right : ClassIntTreeNode
init() {}
// CHECK-LABEL: sil hidden @$S15guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode {
// CHECK-NOT: destroy_value
// CHECK: copy_value
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: return
func find(_ v : Int) -> ClassIntTreeNode {
if v == value { return self }
if v < value { return left.find(v) }
return right.find(v)
}
}
| apache-2.0 | 16f27312aef00e2a5d877ca3ff9a4559 | 46.350909 | 267 | 0.593864 | 3.426711 | false | false | false | false |
KahunaSystems/KahunaControlAppBootup | KahunaControlAppBootup/Classes/AppBootupHandler.swift | 1 | 8062 | //
// AppBootupHandler.swift
// Pods
//
// Created by Kahuna on 8/1/17.
//
//
import Foundation
import UIKit
public class AppBootupHandler: NSObject {
var serverBaseURL = String()
var appId = String()
var appVersion = String()
var osVersion = String()
var freeSpace = String()
var appType = String()
let endPoint = "/datarepo/v1/controlAppBootup/check"
let kTimeoutInterval = 60
var production = false
var bootUpViewController: UIViewController!
public let remoteUpdateUpdateAvailableCode = 7001
public enum RemoteUpdateCases {
static let warning = "WARNING"
static let block = "BLOCK"
static let redirectAppStore = "REDIRECT_TO_APPSTORE"
static let redirectSettings = "REDIRECT_TO_SETTINGS"
static let redirectURL = "REDIRECT_TO_URL"
}
public static let sharedInstance = AppBootupHandler()
public typealias AppBootupCompletionBlock = (Bool, AnyObject?) -> Void
override init() {
}
deinit {
print("** InstagramFeedHandler deinit called **")
}
public func isAppTypeProduction(flag: Bool) {
self.production = flag
self.appType = self.production ? "1" : "0"
}
func deviceRemainingFreeSpaceInBytes() -> String? {
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!
guard
let systemAttributes = try? FileManager.default.attributesOfFileSystem(forPath: documentDirectory),
let freeSize = systemAttributes[.systemFreeSize] as? NSNumber
else {
// something failed
return nil
}
return freeSize.stringValue
}
public func initAllAppBootupKeysWithViewController(appId: String, viewController: UIViewController, checkFreeSpace: Bool = false) {
self.appId = appId
if let appVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as? String {
self.appVersion = appVersion
self.osVersion = UIDevice.current.systemVersion
self.appType = self.production ? "1" : "0"
if checkFreeSpace {
let space = self.deviceRemainingFreeSpaceInBytes()
if space != nil {
self.freeSpace = space!
}
}
self.bootUpViewController = viewController
}
}
public func initServerBaseURL(serverBaseURL: String) {
self.serverBaseURL = serverBaseURL
}
func createURLRequest(_ path: String, parameters: NSMutableDictionary, timeoutInterval interval: Int) -> URLRequest? {
var jsonData: Data!
do {
jsonData = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
} catch let error as NSError {
print(error)
}
if let url = NSURL(string: path) as URL? {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
request.timeoutInterval = TimeInterval(interval)
return request
}
return nil
}
func createParametersDic() -> NSMutableDictionary {
let jsonDic = NSMutableDictionary()
jsonDic.setValue(self.appId, forKey: "appId")
jsonDic.setValue(self.appType, forKey: "appType")
jsonDic.setValue(self.appVersion, forKey: "appVersion")
jsonDic.setValue(self.osVersion, forKey: "osVersion")
if self.freeSpace.count > 0 {
jsonDic.setValue(self.freeSpace, forKey: "freeSpace")
}
return jsonDic
}
public func checkForRemoteUpdateByCustomView(completionHandler: @escaping AppBootupCompletionBlock) {
self.getAppBootupActionMessage { (success, jsonObject) in
completionHandler(success, jsonObject)
}
}
func getAppBootupActionMessage(completionHandler: @escaping AppBootupCompletionBlock) {
if self.serverBaseURL.count > 0 && self.appId.count > 0 {
let jsonDic = self.createParametersDic()
let urlStr = self.serverBaseURL + self.endPoint
let request = self.createURLRequest(urlStr, parameters: jsonDic, timeoutInterval: kTimeoutInterval)
guard request != nil else {
completionHandler(false, nil)
return
}
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let task = session.dataTask(with: request! as URLRequest, completionHandler: { (data, response, error) in
if data != nil {
do {
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: [])
DispatchQueue.main.async {
let kahunaAppBootup = KahunaAppBootup(fromDictionary: jsonObject as! NSDictionary)
if kahunaAppBootup.status != nil && kahunaAppBootup.status.code != 200 {
completionHandler(true, kahunaAppBootup)
} else {
completionHandler(false, nil)
}
}
} catch let Error as NSError {
print(Error.description)
completionHandler(false, nil)
}
} else {
completionHandler(false, nil)
}
})
task.resume()
}
}
public func checkForRemoteUpdate(completionHandler: @escaping AppBootupCompletionBlock) {
if self.bootUpViewController != nil {
self.getAppBootupActionMessage { (success, jsonObject) in
if success && jsonObject is KahunaAppBootup {
let kahunaAppBooup = jsonObject as! KahunaAppBootup
//7001 Error Code: Some thing is available for verification
if kahunaAppBooup.status != nil && kahunaAppBooup.status.code != nil && kahunaAppBooup.status.code == self.remoteUpdateUpdateAvailableCode && kahunaAppBooup.title != nil && kahunaAppBooup.message != nil {
let controller = UIAlertController(title: kahunaAppBooup.title, message: kahunaAppBooup.message, preferredStyle: .alert)
if kahunaAppBooup.action != RemoteUpdateCases.block {
var titleStrButton = "Ok"
if kahunaAppBooup.url != nil {
titleStrButton = "Cancel"
let updateAction = UIAlertAction(title: "Continue", style: .default, handler: { (UIAlertAction) in
if kahunaAppBooup.action == RemoteUpdateCases.redirectSettings {
UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
} else {
UIApplication.shared.openURL(URL(string: kahunaAppBooup.url)!)
}
})
controller.addAction(updateAction)
}
if kahunaAppBooup.action == RemoteUpdateCases.warning {
let cancelAction = UIAlertAction(title: titleStrButton, style: .default, handler: nil)
controller.addAction(cancelAction)
}
}
self.bootUpViewController.present(controller, animated: true, completion: nil)
}
}
completionHandler(success, jsonObject)
}
} else {
completionHandler(false, nil)
}
}
}
| mit | 92177313c95c6754011596f469e64a8a | 41.431579 | 224 | 0.57802 | 5.283093 | false | false | false | false |
BlueCocoa/Maria | Maria/AppDelegate.swift | 1 | 11121 | //
// AppDelegate.swift
// Maria
//
// Created by ShinCurry on 16/4/13.
// Copyright © 2016年 ShinCurry. All rights reserved.
//
import Cocoa
import Aria2RPC
import SwiftyJSON
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var maria = Maria.shared
let defaults = MariaUserDefault.auto
var statusItem: NSStatusItem?
var speedStatusTimer: Timer?
var dockTileTimer: Timer?
override init() {
if !MariaUserDefault.main[.isNotFirstLaunch] {
MariaUserDefault.initMain()
MariaUserDefault.initExternal()
MariaUserDefault.initBuiltIn()
}
if !MariaUserDefault.main[.useEmbeddedAria2] {
if defaults[.enableAria2AutoLaunch] {
let task = Process()
let confPath = defaults[.aria2ConfPath]!
let shFilePath = Bundle.main
.path(forResource: "runAria2c", ofType: "sh")
task.launchPath = shFilePath
task.arguments = [confPath]
task.launch()
task.waitUntilExit()
}
}
super.init()
if defaults[.enableAutoConnectAria2] {
maria.rpc?.connect()
}
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
NSUserNotificationCenter.default.delegate = self
if defaults[.enableStatusBarMode] {
statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
statusItem?.button?.action = #selector(AppDelegate.menuClicked)
statusItem?.button?.sendAction(on: [.leftMouseUp, .rightMouseUp])
}
if defaults[.enableStatusBarMode] && defaults[.enableSpeedStatusBar] {
enableSpeedStatusBar()
} else {
disableSpeedStatusBar()
}
for window in NSApp.windows {
window.canHide = false
}
if defaults[.enableStatusBarMode] {
disableDockIcon()
} else {
enableDockIcon()
}
NSApp.dockTile.contentView = dockTileView
dockTileTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateDockTile), userInfo: nil, repeats: true)
}
func applicationWillTerminate(_ aNotification: Notification) {
aria2close()
if !MariaUserDefault.main.bool(forKey: "UseEmbeddedAria2") {
if defaults[.enableAria2AutoLaunch] {
let task = Process()
let pipe = Pipe()
let shFilePath = Bundle.main.path(forResource: "shutdownAria2c", ofType: "sh")
task.launchPath = shFilePath
task.standardOutput = pipe
task.launch()
task.waitUntilExit()
print("EnableAria2AutoLaunch")
let data = pipe.fileHandleForReading.readDataToEndOfFile()
print(String(data: data, encoding: .utf8)!)
}
}
}
func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
if !flag {
for window in NSApp.windows {
window.makeKeyAndOrderFront(self)
}
}
return true
}
// MARK: SpeedBar
func enableSpeedStatusBar() {
speedStatusTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateSpeedStatus), userInfo: nil, repeats: true)
if let button = statusItem?.button {
button.image = nil
}
}
func disableSpeedStatusBar() {
speedStatusTimer?.invalidate()
if let button = statusItem?.button {
button.image = NSImage(named: "Arrow")
button.title = ""
}
}
func menuClicked(sender: NSStatusBarButton) {
if NSApp.currentEvent!.type == NSEventType.rightMouseUp {
statusItem?.popUpMenu(statusMenu)
} else {
if NSApp.isActive {
statusItem?.popUpMenu(statusMenu)
return
}
for window in NSApp.windows {
window.makeKeyAndOrderFront(self)
}
NSApp.activate(ignoringOtherApps: true)
}
}
// MARK: Dock Icon
func enableDockIcon() {
NSApp.setActivationPolicy(.regular)
}
func disableDockIcon() {
NSApp.setActivationPolicy(.accessory)
}
func updateDockTile() {
maria.rpc?.onGlobalStatus = { status in
if !MariaUserDefault.auto[.enableStatusBarMode] {
if status.speed!.download == 0 {
self.dockTileView.badgeBox.isHidden = true
} else {
self.dockTileView.badgeBox.isHidden = false
self.dockTileView.badgeTitle.stringValue = status.speed!.downloadString
}
NSApp.dockTile.display()
}
}
maria.rpc?.getGlobalStatus()
}
func updateSpeedStatus() {
if maria.rpc?.status == .connected {
maria.rpc?.getGlobalStatus()
}
maria.rpc?.onGlobalStatus = { status in
if let button = self.statusItem?.button {
button.title = "⬇︎ " + status.speed!.downloadString + " ⬆︎ " + status.speed!.uploadString
}
}
}
@IBOutlet weak var statusMenu: NSMenu!
@IBOutlet weak var RPCServerStatus: NSMenuItem!
@IBOutlet weak var lowSpeedMode: NSMenuItem!
@IBOutlet weak var dockTileView: DockTileView!
}
extension AppDelegate {
@IBAction func switchRPCServerStatus(_ sender: NSMenuItem) {
let status = sender.state == 0 ? false : true
if status {
aria2close()
} else {
aria2open()
}
}
@IBAction func quit(_ sender: NSMenuItem) {
NSApp.terminate(self)
}
@IBAction func speedLimitMode(_ sender: NSMenuItem) {
let status = sender.state == 0 ? false : true
if status {
lowSpeedModeOff()
defaults[.enableLowSpeedMode] = false
} else {
lowSpeedModeOn()
defaults[.enableLowSpeedMode] = true
}
defaults.synchronize()
}
func lowSpeedModeOff() {
let limitDownloadSpeed = defaults[.globalDownloadRate]
let limitUploadSpeed = defaults[.globalUploadRate]
maria.rpc?.globalSpeedLimit(download: limitDownloadSpeed, upload: limitUploadSpeed)
}
func lowSpeedModeOn() {
let limitDownloadSpeed = defaults[.limitModeDownloadRate]
let limitUploadSpeed = defaults[.limitModeUploadRate]
maria.rpc?.lowSpeedLimit(download: limitDownloadSpeed, upload: limitUploadSpeed)
}
@IBAction func openWebUIApp(_ sender: NSMenuItem) {
if let path = defaults[.webAppPath], !path.isEmpty {
NSWorkspace.shared().open(URL(fileURLWithPath: path))
}
}
}
// MARK: - Aria2 Config
extension AppDelegate: NSUserNotificationCenterDelegate {
func aria2open() {
aria2configure()
maria.rpc?.connect()
RPCServerStatus.state = 1
}
func aria2close() {
maria.rpc?.disconnect()
}
func aria2configure() {
maria.rpc?.onConnect = {
self.RPCServerStatus.state = 1
if self.defaults[.enableLowSpeedMode] {
self.lowSpeedModeOn()
} else {
self.lowSpeedModeOff()
}
if self.defaults[.enableNotificationWhenConnected] {
MariaNotification.notification(title: "Aria2 Connected", details: "Aria2 server connected at \(MariaUserDefault.RPCUrl)")
}
}
maria.rpc?.onDisconnect = {
self.RPCServerStatus.state = 0
if self.defaults[.enableNotificationWhenDisconnected] {
MariaNotification.notification(title: "Aria2 Disconnected", details: "Aria2 server disconnected")
}
}
maria.rpc?.downloadStarted = { name in
if self.defaults[.enableNotificationWhenStarted] {
MariaNotification.notification(title: "Download Started", details: "\(name) started.")
}
}
maria.rpc?.downloadPaused = { name in
if self.defaults[.enableNotificationWhenPaused] {
MariaNotification.notification(title: "Download Paused", details: "\(name) paused.")
}
}
maria.rpc?.downloadStopped = { name in
if self.defaults[.enableNotificationWhenStopped] {
MariaNotification.notification(title: "Download Stopoped", details: "\(name) stopped.")
}
}
maria.rpc?.downloadCompleted = { (name, path) in
if self.defaults[.enableNotificationWhenCompleted] {
MariaNotification.actionNotification(identifier: "complete", title: "Download Completed", details: "\(name) completed.", userInfo: ["path": path as AnyObject])
}
}
maria.rpc?.downloadError = { name in
if self.defaults[.enableNotificationWhenError] {
MariaNotification.notification(title: "Download Error", details: "Download task \(name) have an error.")
}
}
maria.rpc?.onGlobalSpeedLimitOK = { flag in
if flag {
self.lowSpeedMode.state = 0
if let controller = NSApp.mainWindow?.windowController as? MainWindowController {
controller.lowSpeedModeButton.state = 0
if let button = controller.touchBarLowSpeedButton {
button.state = 0
}
}
}
}
maria.rpc?.onLowSpeedLimitOK = { flag in
if flag {
self.lowSpeedMode.state = 1
if let controller = NSApp.mainWindow?.windowController as? MainWindowController {
controller.lowSpeedModeButton.state = 1
if let button = controller.touchBarLowSpeedButton {
button.state = 1
}
}
}
}
}
fileprivate func getStringBy(_ value: Double) -> String {
if value > 1024 {
return String(format: "%.2f MB/s", value / 1024.0)
} else {
return String(format: "%.2f KB/s", value)
}
}
func userNotificationCenter(_ center: NSUserNotificationCenter, didActivate notification: NSUserNotification) {
if let id = notification.identifier {
switch id {
case "complete":
let path = notification.userInfo!["path"] as! String
NSWorkspace.shared().open(URL(string: "file://\(path)")!)
default:
break
}
}
}
}
| gpl-3.0 | 7322f617926782245bd0a0d904ce6429 | 32.363363 | 175 | 0.564806 | 4.90075 | false | false | false | false |
See-Ku/SK4Toolkit | SK4Toolkit/gui/SK4TextExportViewController.swift | 1 | 1043 | //
// SK4TextExportViewController.swift
// SK4Toolkit
//
// Created by See.Ku on 2016/04/03.
// Copyright (c) 2016 AxeRoad. All rights reserved.
//
import UIKit
/// テキストをクリップボードに貼り付けるためのViewController
public class SK4TextExportViewController: SK4TextBaseViewController {
/// クリップボードに貼り付けるテキスト
public var exportText = ""
override public func viewDidLoad() {
super.viewDidLoad()
let exp = sk4BarButtonItem(title: "Copy to clipboard", target: self, action: #selector(SK4TextExportViewController.onExport(_:)))
let flex = sk4BarButtonItem(system: .FlexibleSpace)
toolbarItems = [flex, exp, flex]
}
override public func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
textView.text = exportText
}
public func onExport(sender: AnyObject) {
let board = UIPasteboard.generalPasteboard()
board.setValue(textView.text, forPasteboardType: "public.text")
sk4AlertView(title: "Export OK", message: "", vc: self)
}
}
// eof
| mit | 05e5c78f8b17b676ae5126621019e9d5 | 23.175 | 131 | 0.740434 | 3.357639 | false | false | false | false |
rollbar/rollbar-ios | Examples/RollbarWithinAnotherFramework/KnobShowcase/KnobShowcase/ViewController.swift | 1 | 2746 | /// Copyright (c) 2018 Razeware LLC
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// Notwithstanding the foregoing, you may not use, copy, modify, merge, publish,
/// distribute, sublicense, create a derivative work, and/or sell copies of the
/// Software in any work that is designed, intended, or marketed for pedagogical or
/// instructional purposes related to programming, coding, application development,
/// or information technology. Permission for such use, copying, modification,
/// merger, publication, distribution, sublicensing, creation of derivative works,
/// or sale is expressly withheld.
///
/// 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 KnobControl
class ViewController: UIViewController {
@IBOutlet var valueLabel: UILabel!
@IBOutlet var valueSlider: UISlider!
@IBOutlet var animateSwitch: UISwitch!
@IBOutlet var knob: Knob!
override func viewDidLoad() {
super.viewDidLoad()
knob.lineWidth = 4
knob.pointerLength = 12
knob.setValue(valueSlider.value)
knob.addTarget(self, action: #selector(ViewController.handleValueChanged(_:)), for: .valueChanged)
updateLabel()
}
@IBAction func handleValueChanged(_ sender: Any) {
if sender is UISlider {
knob.setValue(valueSlider.value)
} else {
valueSlider.value = knob.value
}
updateLabel()
}
@IBAction func handleRandomButtonPressed(_ sender: Any) {
let randomValue = Float(arc4random_uniform(101)) / 100.0
knob.setValue(randomValue, animated: animateSwitch.isOn)
valueSlider.setValue(Float(randomValue), animated: animateSwitch.isOn)
updateLabel()
}
private func updateLabel() {
valueLabel.text = String(format: "%.2f", knob.value)
}
}
| mit | ffb00c2c9195fddb37badf95d6628e69 | 38.797101 | 102 | 0.733066 | 4.561462 | false | false | false | false |
kickstarter/ios-oss | Library/ViewModels/SortPagerViewModel.swift | 1 | 6277 | import KsApi
import Prelude
import ReactiveSwift
public protocol SortPagerViewModelInputs {
/// Call with the sorts that the view was configured with.
func configureWith(sorts: [DiscoveryParams.Sort])
/// Call when the view controller's didRotateFromInterfaceOrientation method is called.
func didRotateFromInterfaceOrientation()
/// Call when a sort is selected from outside this view.
func select(sort: DiscoveryParams.Sort)
/// Call when a sort button is tapped.
func sortButtonTapped(index: Int)
/// Call when to update the sort style.
func updateStyle(categoryId: Int?)
/// Call when the view controller's willRotateToInterfaceOrientation method is called.
func willRotateToInterfaceOrientation()
/// Call when the view controller's viewDidAppear method is called.
func viewDidAppear()
/// Call when view controller's viewWillAppear method is called.
func viewWillAppear()
}
public protocol SortPagerViewModelOutputs {
/// Emits a list of sorts that should be used to create sort buttons.
var createSortButtons: Signal<[DiscoveryParams.Sort], Never> { get }
/// Emits a bool whether the indicator view should be hidden, used for rotation.
var indicatorViewIsHidden: Signal<Bool, Never> { get }
/// Emits a sort that should be passed on to the view's delegate.
var notifyDelegateOfSelectedSort: Signal<DiscoveryParams.Sort, Never> { get }
/// Emits an index to pin the indicator view to a particular button view and whether to animate it.
var pinSelectedIndicatorToPage: Signal<(Int, Bool), Never> { get }
/// Emits an index of the selected button to update all button selected states.
var setSelectedButton: Signal<Int, Never> { get }
/// Emits a category id to update style on sort change (e.g. filter selection).
var updateSortStyle: Signal<
(categoryId: Int?, sorts: [DiscoveryParams.Sort], animated: Bool),
Never
> { get }
}
public protocol SortPagerViewModelType {
var inputs: SortPagerViewModelInputs { get }
var outputs: SortPagerViewModelOutputs { get }
}
public final class SortPagerViewModel: SortPagerViewModelType, SortPagerViewModelInputs,
SortPagerViewModelOutputs {
public init() {
let sorts: Signal<[DiscoveryParams.Sort], Never> = Signal.combineLatest(
self.sortsProperty.signal.skipNil(),
self.viewWillAppearProperty.signal
)
.map(first)
self.createSortButtons = sorts.take(first: 1)
self.updateSortStyle = Signal.merge(
sorts.map { ($0, nil, false) }.take(first: 1),
sorts.takePairWhen(self.updateStyleProperty.signal).map { ($0, $1, true) }
)
.map { sorts, id, animated in (categoryId: id, sorts: sorts, animated: animated) }
let selectedPage: Signal<(Int, Int), Never> = Signal.combineLatest(
sorts,
self.selectSortProperty.signal.skipNil()
)
.map { (arg) -> (Int, Int) in
let (sorts, sort) = arg
return (sorts.firstIndex(of: sort) ?? 0, sorts.count)
}
let pageIndex: Signal<Int, Never> = sorts.mapConst(0)
self.setSelectedButton = Signal.merge(
pageIndex.take(first: 1),
self.sortButtonTappedIndexProperty.signal.skipNil(),
selectedPage.map { index, _ in index }
)
.skipRepeats(==)
let selectedPageOnRotate = Signal.merge(pageIndex, selectedPage.map(first))
.takeWhen(self.didRotateProperty.signal)
self.pinSelectedIndicatorToPage = Signal.merge(
pageIndex
.takeWhen(self.viewDidAppearProperty.signal)
.take(first: 1)
.map { ($0, false) },
selectedPage
.map { page, _ in (page, true) }
.skipRepeats(==),
selectedPageOnRotate
.map { ($0, false) }
)
self.notifyDelegateOfSelectedSort = Signal.combineLatest(
sorts.take(first: 1),
self.sortButtonTappedIndexProperty.signal.skipNil()
)
.map { sorts, sortIndex in sorts[sortIndex] }
self.indicatorViewIsHidden = Signal.merge(
self.viewWillAppearProperty.signal
.take(first: 1)
.mapConst(true),
self.viewDidAppearProperty.signal
.take(first: 1)
.mapConst(false)
.ksr_debounce(.milliseconds(100), on: AppEnvironment.current.scheduler),
self.willRotateProperty.signal.mapConst(true),
self.didRotateProperty.signal
.mapConst(false)
.ksr_debounce(.milliseconds(100), on: AppEnvironment.current.scheduler)
)
}
fileprivate let didRotateProperty = MutableProperty(())
public func didRotateFromInterfaceOrientation() {
self.didRotateProperty.value = ()
}
fileprivate let sortsProperty = MutableProperty<[DiscoveryParams.Sort]?>(nil)
public func configureWith(sorts: [DiscoveryParams.Sort]) {
self.sortsProperty.value = sorts
}
fileprivate let selectSortProperty = MutableProperty<DiscoveryParams.Sort?>(nil)
public func select(sort: DiscoveryParams.Sort) {
self.selectSortProperty.value = sort
}
fileprivate let sortButtonTappedIndexProperty = MutableProperty<Int?>(nil)
public func sortButtonTapped(index: Int) {
self.sortButtonTappedIndexProperty.value = index
}
fileprivate let updateStyleProperty = MutableProperty<Int?>(nil)
public func updateStyle(categoryId: Int?) {
self.updateStyleProperty.value = categoryId
}
fileprivate let willRotateProperty = MutableProperty(())
public func willRotateToInterfaceOrientation() {
self.willRotateProperty.value = ()
}
fileprivate let viewDidAppearProperty = MutableProperty(())
public func viewDidAppear() {
self.viewDidAppearProperty.value = ()
}
fileprivate let viewWillAppearProperty = MutableProperty(())
public func viewWillAppear() {
self.viewWillAppearProperty.value = ()
}
public let createSortButtons: Signal<[DiscoveryParams.Sort], Never>
public var indicatorViewIsHidden: Signal<Bool, Never>
public let notifyDelegateOfSelectedSort: Signal<DiscoveryParams.Sort, Never>
public let pinSelectedIndicatorToPage: Signal<(Int, Bool), Never>
public let setSelectedButton: Signal<Int, Never>
public let updateSortStyle: Signal<
(categoryId: Int?, sorts: [DiscoveryParams.Sort], animated: Bool),
Never
>
public var inputs: SortPagerViewModelInputs { return self }
public var outputs: SortPagerViewModelOutputs { return self }
}
| apache-2.0 | 63bb9bd6a8315bc6f2a7e3632977f4e4 | 33.489011 | 101 | 0.719133 | 4.461265 | false | false | false | false |
AlexanderMazaletskiy/MPGTextField | Swift/MPGTextField/MPGTextField-Swift.swift | 4 | 8986 | //
// MPGTextField-Swift.swift
// MPGTextField-Swift
//
// Created by Gaurav Wadhwani on 08/06/14.
// Copyright (c) 2014 Mappgic. All rights reserved.
//
import UIKit
@objc protocol MPGTextFieldDelegate{
func dataForPopoverInTextField(textfield: MPGTextField_Swift) -> Dictionary<String, AnyObject>[]
@optional func textFieldDidEndEditing(textField: MPGTextField_Swift, withSelection data: Dictionary<String,AnyObject>)
@optional func textFieldShouldSelect(textField: MPGTextField_Swift) -> Bool
}
class MPGTextField_Swift: UITextField, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource, UIGestureRecognizerDelegate {
var mDelegate : MPGTextFieldDelegate?
var tableViewController : UITableViewController?
var data = Dictionary<String, AnyObject>[]()
//Set this to override the default color of suggestions popover. The default color is [UIColor colorWithWhite:0.8 alpha:0.9]
@IBInspectable var popoverBackgroundColor : UIColor = UIColor(red: 240.0/255.0, green: 240.0/255.0, blue: 240.0/255.0, alpha: 1.0)
//Set this to override the default frame of the suggestions popover that will contain the suggestions pertaining to the search query. The default frame will be of the same width as textfield, of height 200px and be just below the textfield.
@IBInspectable var popoverSize : CGRect?
//Set this to override the default seperator color for tableView in search results. The default color is light gray.
@IBInspectable var seperatorColor : UIColor = UIColor(white: 0.95, alpha: 1.0)
init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
init(coder aDecoder: NSCoder!){
super.init(coder: aDecoder)
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect)
{
// Drawing code
}
*/
override func layoutSubviews(){
super.layoutSubviews()
let str : String = self.text
if (countElements(str) > 0) && (self.isFirstResponder())
{
if mDelegate{
data = mDelegate!.dataForPopoverInTextField(self)
self.provideSuggestions()
}
else{
println("<MPGTextField> WARNING: You have not implemented the requred methods of the MPGTextField protocol.")
}
}
else{
if let table = self.tableViewController{
if table.tableView.superview != nil{
table.tableView.removeFromSuperview()
self.tableViewController = nil
}
}
}
}
override func resignFirstResponder() -> Bool{
UIView.animateWithDuration(0.3,
animations: ({
self.tableViewController!.tableView.alpha = 0.0
}),
completion:{
(finished : Bool) in
self.tableViewController!.tableView.removeFromSuperview()
self.tableViewController = nil
})
self.handleExit()
return super.resignFirstResponder()
}
func provideSuggestions(){
if let tvc = self.tableViewController {
tableViewController!.tableView.reloadData()
}
else if self.applyFilterWithSearchQuery(self.text).count > 0{
//Add a tap gesture recogniser to dismiss the suggestions view when the user taps outside the suggestions view
let tapRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
tapRecognizer.numberOfTapsRequired = 1
tapRecognizer.cancelsTouchesInView = false
tapRecognizer.delegate = self
self.superview.addGestureRecognizer(tapRecognizer)
self.tableViewController = UITableViewController.alloc()
self.tableViewController!.tableView.delegate = self
self.tableViewController!.tableView.dataSource = self
self.tableViewController!.tableView.backgroundColor = self.popoverBackgroundColor
self.tableViewController!.tableView.separatorColor = self.seperatorColor
if let frameSize = self.popoverSize{
self.tableViewController!.tableView.frame = frameSize
}
else{
//PopoverSize frame has not been set. Use default parameters instead.
var frameForPresentation = self.frame
frameForPresentation.origin.y += self.frame.size.height
frameForPresentation.size.height = 200
self.tableViewController!.tableView.frame = frameForPresentation
}
var frameForPresentation = self.frame
frameForPresentation.origin.y += self.frame.size.height;
frameForPresentation.size.height = 200;
tableViewController!.tableView.frame = frameForPresentation
self.superview.addSubview(tableViewController!.tableView)
self.tableViewController!.tableView.alpha = 0.0
UIView.animateWithDuration(0.3,
animations: ({
self.tableViewController!.tableView.alpha = 1.0
}),
completion:{
(finished : Bool) in
})
}
}
func tapped (sender : UIGestureRecognizer!){
if let table = self.tableViewController{
if !CGRectContainsPoint(table.tableView.frame, sender.locationInView(self.superview)) && self.isFirstResponder(){
self.resignFirstResponder()
}
}
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int{
var count = self.applyFilterWithSearchQuery(self.text).count
if count == 0{
UIView.animateWithDuration(0.3,
animations: ({
self.tableViewController!.tableView.alpha = 0.0
}),
completion:{
(finished : Bool) in
if let table = self.tableViewController{
table.tableView.removeFromSuperview()
self.tableViewController = nil
}
})
}
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MPGResultsCell") as? UITableViewCell
if !cell{
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "MPGResultsCell")
}
cell!.backgroundColor = UIColor.clearColor()
let dataForRowAtIndexPath = self.applyFilterWithSearchQuery(self.text)[indexPath.row]
let displayText : AnyObject? = dataForRowAtIndexPath["DisplayText"]
let displaySubText : AnyObject? = dataForRowAtIndexPath["DisplaySubText"]
cell!.textLabel.text = displayText as String
cell!.detailTextLabel.text = displaySubText as String
return cell!
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!){
//self.text = self.applyFilterWithSearchQuery(self.text)[indexPath.row]["DisplayText"]
self.resignFirstResponder()
}
// #pragma mark Filter Method
func applyFilterWithSearchQuery(filter : String) -> Dictionary<String, AnyObject>[]
{
//let predicate = NSPredicate(format: "DisplayText BEGINSWITH[cd] \(filter)")
var lower = (filter as NSString).lowercaseString
var filteredData = data.filter({
if let match : AnyObject = $0["DisplayText"]{
//println("LCS = \(filter.lowercaseString)")
return (match as NSString).lowercaseString.hasPrefix((filter as NSString).lowercaseString)
}
else{
return false
}
})
return filteredData
}
func handleExit(){
if let table = self.tableViewController{
table.tableView.removeFromSuperview()
}
if mDelegate?.textFieldShouldSelect?(self){
if self.applyFilterWithSearchQuery(self.text).count > 0 {
let selectedData = self.applyFilterWithSearchQuery(self.text)[0]
let displayText : AnyObject? = selectedData["DisplayText"]
self.text = displayText as String
mDelegate?.textFieldDidEndEditing?(self, withSelection: selectedData)
}
else{
mDelegate?.textFieldDidEndEditing?(self, withSelection: ["DisplayText":self.text, "CustomObject":"NEW"])
}
}
}
}
| mit | 3f9ee52165a1f67b1b0e632945192d9b | 39.477477 | 244 | 0.616403 | 5.560644 | false | false | false | false |
ggu/2D-RPG-Template | Borba/game objects/characters/EnemySprite.swift | 2 | 1399 | //
// Enemy.swift
// Borba
//
// Created by Gabriel Uribe on 7/25/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
import SpriteKit
class EnemySprite: Sprite {
var inContactWithPlayer = false
init() {
let texture = AssetManager.enemyTexture
super.init(texture: texture, color: UIColor.whiteColor(), size: texture.size())
setup()
}
func handleSpriteMovement(destinationPos: CGPoint, duration: Double) {
if !inContactWithPlayer {
let action = SKAction.moveTo(destinationPos, duration: duration)
runAction(action)
} else {
removeAllActions()
}
let radians = CGFloat(getRadiansBetweenTwoPoints(position, secondPoint: destinationPos))
zRotation = radians
}
private func setup() {
name = String(ObjectIdentifier(self).uintValue)
setupProperties()
}
private func setupProperties() {
zPosition = zPositions.mapObjects
physicsBody = SKPhysicsBody(rectangleOfSize: size)
physicsBody?.categoryBitMask = CategoryBitMasks.enemy
physicsBody?.collisionBitMask = CategoryBitMasks.hero
physicsBody?.contactTestBitMask = CategoryBitMasks.hero
physicsBody?.affectedByGravity = false
physicsBody?.mass = 100
lightingBitMask = 1
shadowCastBitMask = 1
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 0610eb006f97acef9df437d754e741e1 | 25.396226 | 92 | 0.70193 | 4.498392 | false | false | false | false |
James-swift/JMSQRCode | JMSQRCode/JMSGenerateQRCodeUtils.swift | 1 | 6831 | //
// JMSGenerateQRCodeUtils.swift
// JMSQRCode
//
// Created by James on 2017/3/12.
// Copyright © 2017年 James. All rights reserved.
//
import Foundation
import UIKit
public struct JMSGenerateQRCodeUtils {
/**
生成一张普通的或者带有logo的二维码
- parameter string: 传入你要生成二维码的数据
- parameter imageSize: 生成的二维码图片尺寸
- parameter logoImageName: logo图片名称
- parameter logoImageSize: logo图片尺寸(注意尺寸不要太大(最大不超过二维码图片的%30),太大会造成扫不出来)
- returns: UIImage
*/
public static func jms_generateQRCode(string: String, imageSize: CGSize, logoImageName: String = "", logoImageSize: CGSize = .zero) -> UIImage? {
guard let outputImage = self.outputNormalImage(string: string, imageSize: imageSize) else {
return nil
}
guard let scaledImage = self.createNonInterpolatedImage(outputImage, imageSize) else {
return nil
}
return self.createLogoImage(scaledImage, imageSize, logoImageSize: logoImageSize, logoImageName: logoImageName)
}
/**
生成一张彩色的或者带有logo的二维码
- parameter string: 传入你要生成二维码的数据
- parameter imageSize: 生成的二维码图片尺寸
- parameter rgbColor: rgb颜色
- parameter bgColor: 背景颜色
- parameter logoImageName: logo图片名称
- parameter logoImageSize: logo图片尺寸(注意尺寸不要太大(最大不超过二维码图片的%30),太大会造成扫不出来)
- returns: UIImage
*/
public static func jms_generateColorQRCode(string: String, imageSize: CGSize, rgbColor: CIColor, bgColor: CIColor = CIColor.init(red: 1, green: 1, blue: 1), logoImageName: String = "", logoImageSize: CGSize = .zero) -> UIImage? {
guard let outputImage = self.outputColorImage(string: string, imageSize: imageSize, rgbColor: rgbColor, backgroundColor: bgColor) else {
return nil
}
return self.createLogoImage(UIImage.init(ciImage: outputImage), imageSize, logoImageSize: logoImageSize, logoImageName: logoImageName)
}
// MARK: - Private
/**
获得滤镜输出的图像
- parameter string: 传入你要生成二维码的数据
- parameter imageSize: 生成的二维码图片尺寸
- returns: CIImage
*/
private static func outputNormalImage(string: String, imageSize: CGSize) -> CIImage? {
/// 1.设置数据
let data = string.data(using: .utf8)
/// 2.创建滤镜对象
guard let filter = CIFilter.init(name: "CIQRCodeGenerator") else {
return nil
}
filter.setDefaults()
filter.setValue(data, forKey: "inputMessage") // 通过kvo方式给一个字符串,生成二维码
filter.setValue("H", forKey: "inputCorrectionLevel") // 设置二维码的纠错水平,越高纠错水平越高,可以污损的范围越大
/// 3.获得滤镜输出对象(拿到二维码图片)
guard let outputImage = filter.outputImage else {
return nil
}
return outputImage
}
/**
获得彩色滤镜输出的图像
- parameter string: 传入你要生成二维码的数据
- parameter imageSize: 生成的二维码图片尺寸
- returns: CIImage
*/
private static func outputColorImage(string: String, imageSize: CGSize, rgbColor: CIColor, backgroundColor: CIColor = CIColor.init(red: 1, green: 1, blue: 1)) -> CIImage? {
guard let outputImage = self.outputNormalImage(string: string, imageSize: imageSize) else {
return nil
}
/// 创建颜色滤镜
let colorFilter = CIFilter.init(name: "CIFalseColor")
colorFilter?.setDefaults()
colorFilter?.setValue(outputImage, forKey: "inputImage")
/// 替换颜色
colorFilter?.setValue(rgbColor, forKey: "inputColor0")
/// 替换背景颜色
colorFilter?.setValue(backgroundColor, forKey: "inputColor1")
return colorFilter?.outputImage
}
/**
根据CIImage生成指定大小的UIImage
- parameter image: CIImage对象
- parameter imageSize: 生成的二维码图片尺寸
- returns: UIImage
*/
private static func createNonInterpolatedImage(_ image: CIImage, _ imageSize: CGSize) -> UIImage? {
/// 1.创建bitmap
let context = CIContext(options: nil)
let bitmapImage = context.createCGImage(image, from: image.extent)
let colorSpace = CGColorSpaceCreateDeviceGray()
let bitmapContext = CGContext(data: nil, width: Int(imageSize.width), height: Int(imageSize.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: CGImageAlphaInfo.none.rawValue)
let scale = min(imageSize.width / image.extent.width, imageSize.height / image.extent.height)
bitmapContext!.interpolationQuality = CGInterpolationQuality.none
bitmapContext?.scaleBy(x: scale, y: scale)
bitmapContext?.draw(bitmapImage!, in: image.extent)
/// 2.保存bitmap到图片
guard let scaledImage = bitmapContext?.makeImage() else {
return nil
}
/// 3.生成原图
return UIImage.init(cgImage: scaledImage)
}
/**
生成带有logo二维码图片
- parameter image: UIImage对象
- parameter imageSize: UIImage对象尺寸
- parameter logoImageName: logo图片名称
- parameter logoImageSize: logo图片尺寸(注意尺寸不要太大(最大不超过二维码图片的%30),太大会造成扫不出来)
- returns: UIImage
*/
private static func createLogoImage(_ image: UIImage, _ imageSize: CGSize, logoImageSize: CGSize = .zero, logoImageName: String = "") -> UIImage {
if logoImageSize.equalTo(.zero) && logoImageName == "" {
return image
}
UIGraphicsBeginImageContextWithOptions(imageSize, false, UIScreen.main.scale)
image.draw(in: CGRect.init(x: 0, y: 0, width: imageSize.width, height: imageSize.height))
let waterimage = UIImage.init(named: logoImageName)
waterimage?.draw(in: CGRect.init(x: (imageSize.width - logoImageSize.width) / 2.0, y: (imageSize.height - logoImageSize.height) / 2.0, width: logoImageSize.width, height: logoImageSize.height))
let newPic = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newPic!
}
}
| mit | 2daa7cb46e43b083a0ecc9480ab389a1 | 35.095808 | 233 | 0.639018 | 4.409656 | false | false | false | false |
joemcbride/outlander-osx | src/Outlander/RandomNumbers.swift | 1 | 981 | //
// RandomNumbers.swift
// Outlander
//
// Created by Joseph McBride on 4/18/15.
// https://gist.github.com/indragiek/b16f95d911a37cb963a7
//
import Foundation
public struct RandomNumberGenerator: SequenceType {
let range: Range<Int>
let count: Int
public init(range: Range<Int>, count: Int) {
self.range = range
self.count = count
}
public func generate() -> AnyGenerator<Int> {
var i = 0
return AnyGenerator<Int> {
var result:Int?
if i == self.count {
result = randomNumberFrom(self.range)
}
i += 1
return result
}
}
}
public func randomNumberFrom(from: Range<Int>) -> Int {
return from.startIndex + Int(arc4random_uniform(UInt32(from.endIndex - from.startIndex)))
}
public func randomNumbersFrom(from: Range<Int>, count: Int) -> RandomNumberGenerator {
return RandomNumberGenerator(range: from, count: count)
} | mit | 0c005b946e70c40e6eeff003951221ee | 24.179487 | 93 | 0.616718 | 3.832031 | false | false | false | false |
ileitch/SwiftState | SwiftStateTests/RasmusTest.swift | 1 | 1155 | //
// RasmusTest.swift
// SwiftState
//
// Created by Rasmus Taulborg Hummelmose on 20/08/15.
// Copyright © 2015 Yasuhiro Inami. All rights reserved.
//
import SwiftState
import XCTest
enum RasmusTestState: StateType {
case Any
case State1, State2, State3, State4
init(nilLiteral: Void) {
self = Any
}
}
enum RasmusTestEvent: StateEventType {
case Any
case State2FromState1
case State4FromState2OrState3
init(nilLiteral: Void) {
self = Any
}
}
class RasmusTest: _TestCase {
func testStateRoute() {
let stateMachine = StateMachine<RasmusTestState, RasmusTestEvent>(state: .State1)
stateMachine.addRouteEvent(.State2FromState1, transitions: [ .State1 => .State2 ])
stateMachine.addRouteEvent(.State4FromState2OrState3, routes: [ [ .State2, .State3 ] => .State4 ])
XCTAssertEqual(stateMachine.state, RasmusTestState.State1)
stateMachine <-! .State2FromState1
XCTAssertEqual(stateMachine.state, RasmusTestState.State2)
stateMachine <-! .State4FromState2OrState3
XCTAssertEqual(stateMachine.state, RasmusTestState.State4)
}
}
| mit | 21802efc7af0a6cb6709b54677238731 | 27.85 | 106 | 0.696707 | 3.898649 | false | true | false | false |
shajrawi/swift | test/decl/protocol/protocol_with_superclass.swift | 1 | 11297 | // RUN: %target-typecheck-verify-swift
// Protocols with superclass-constrained Self.
class Concrete {
typealias ConcreteAlias = String
func concreteMethod(_: ConcreteAlias) {}
}
class Generic<T> : Concrete {
typealias GenericAlias = (T, T)
func genericMethod(_: GenericAlias) {}
}
protocol BaseProto {}
protocol ProtoRefinesClass : Generic<Int>, BaseProto {
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias)
// expected-note@-1 {{protocol requires function 'requirementUsesClassTypes' with type '(Generic<Int>.ConcreteAlias, Generic<Int>.GenericAlias) -> ()' (aka '(String, (Int, Int)) -> ()'); do you want to add a stub?}}
}
func duplicateOverload<T : ProtoRefinesClass>(_: T) {}
// expected-note@-1 {{'duplicateOverload' previously declared here}}
func duplicateOverload<T : ProtoRefinesClass & Generic<Int>>(_: T) {}
// expected-error@-1 {{invalid redeclaration of 'duplicateOverload'}}
// expected-warning@-2 {{redundant superclass constraint 'T' : 'Generic<Int>'}}
// expected-note@-3 {{superclass constraint 'T' : 'Generic<Int>' implied here}}
extension ProtoRefinesClass {
func extensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot convert value of type 'Self' to specified type 'Generic<String>'}}
}
}
func usesProtoRefinesClass1(_ t: ProtoRefinesClass) {
let x: ProtoRefinesClass.ConcreteAlias = "hi"
_ = ProtoRefinesClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesClass.GenericAlias = (1, 2)
_ = ProtoRefinesClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'ProtoRefinesClass' to specified type 'Generic<String>'}}
}
func usesProtoRefinesClass2<T : ProtoRefinesClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'T' to specified type 'Generic<String>'}}
}
class BadConformingClass1 : ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass1' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass1]}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-error@-1 {{use of undeclared type 'ConcreteAlias'}}
// expected-error@-2 {{use of undeclared type 'GenericAlias'}}
_ = ConcreteAlias.self
// expected-error@-1 {{use of unresolved identifier 'ConcreteAlias'}}
_ = GenericAlias.self
// expected-error@-1 {{use of unresolved identifier 'GenericAlias'}}
}
}
class BadConformingClass2 : Generic<String>, ProtoRefinesClass {
// expected-error@-1 {{'ProtoRefinesClass' requires that 'BadConformingClass2' inherit from 'Generic<Int>'}}
// expected-note@-2 {{requirement specified as 'Self' : 'Generic<Int>' [with Self = BadConformingClass2]}}
// expected-error@-3 {{type 'BadConformingClass2' does not conform to protocol 'ProtoRefinesClass'}}
func requirementUsesClassTypes(_: ConcreteAlias, _: GenericAlias) {
// expected-note@-1 {{candidate has non-matching type '(BadConformingClass2.ConcreteAlias, BadConformingClass2.GenericAlias) -> ()' (aka '(String, (String, String)) -> ()')}}
_ = ConcreteAlias.self
_ = GenericAlias.self
}
}
class GoodConformingClass : Generic<Int>, ProtoRefinesClass {
func requirementUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
}
}
protocol ProtoRefinesProtoWithClass : ProtoRefinesClass {}
extension ProtoRefinesProtoWithClass {
func anotherExtensionMethodUsesClassTypes(_ x: ConcreteAlias, _ y: GenericAlias) {
_ = ConcreteAlias.self
_ = GenericAlias.self
concreteMethod(x)
genericMethod(y)
let _: Generic<Int> = self
let _: Concrete = self
let _: BaseProto = self
let _: BaseProto & Generic<Int> = self
let _: BaseProto & Concrete = self
let _: Generic<String> = self
// expected-error@-1 {{cannot convert value of type 'Self' to specified type 'Generic<String>'}}
}
}
func usesProtoRefinesProtoWithClass1(_ t: ProtoRefinesProtoWithClass) {
let x: ProtoRefinesProtoWithClass.ConcreteAlias = "hi"
_ = ProtoRefinesProtoWithClass.ConcreteAlias.self
t.concreteMethod(x)
let y: ProtoRefinesProtoWithClass.GenericAlias = (1, 2)
_ = ProtoRefinesProtoWithClass.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'ProtoRefinesProtoWithClass' to specified type 'Generic<String>'}}
}
func usesProtoRefinesProtoWithClass2<T : ProtoRefinesProtoWithClass>(_ t: T) {
let x: T.ConcreteAlias = "hi"
_ = T.ConcreteAlias.self
t.concreteMethod(x)
let y: T.GenericAlias = (1, 2)
_ = T.GenericAlias.self
t.genericMethod(y)
t.requirementUsesClassTypes(x, y)
let _: Generic<Int> = t
let _: Concrete = t
let _: BaseProto = t
let _: BaseProto & Generic<Int> = t
let _: BaseProto & Concrete = t
let _: Generic<String> = t
// expected-error@-1 {{cannot convert value of type 'T' to specified type 'Generic<String>'}}
}
class ClassWithInits<T> {
init(notRequiredInit: ()) {}
// expected-note@-1 6{{selected non-required initializer 'init(notRequiredInit:)'}}
required init(requiredInit: ()) {}
}
protocol ProtocolWithClassInits : ClassWithInits<Int> {}
func useProtocolWithClassInits1() {
_ = ProtocolWithClassInits(notRequiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolWithClassInits' cannot be instantiated}}
_ = ProtocolWithClassInits(requiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolWithClassInits' cannot be instantiated}}
}
func useProtocolWithClassInits2(_ t: ProtocolWithClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'ProtocolWithClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolWithClassInits = t.init(requiredInit: ())
}
func useProtocolWithClassInits3<T : ProtocolWithClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
protocol ProtocolRefinesClassInits : ProtocolWithClassInits {}
func useProtocolRefinesClassInits1() {
_ = ProtocolRefinesClassInits(notRequiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolRefinesClassInits' cannot be instantiated}}
_ = ProtocolRefinesClassInits(requiredInit: ())
// expected-error@-1 {{protocol type 'ProtocolRefinesClassInits' cannot be instantiated}}
}
func useProtocolRefinesClassInits2(_ t: ProtocolRefinesClassInits.Type) {
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'ProtocolRefinesClassInits' with a metatype value must use a 'required' initializer}}
let _: ProtocolRefinesClassInits = t.init(requiredInit: ())
}
func useProtocolRefinesClassInits3<T : ProtocolRefinesClassInits>(_ t: T.Type) {
_ = T(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = T(requiredInit: ())
_ = t.init(notRequiredInit: ())
// expected-error@-1 {{constructing an object of class type 'T' with a metatype value must use a 'required' initializer}}
let _: T = t.init(requiredInit: ())
}
// Make sure that we don't require 'mutating' when the protocol has a superclass
// constraint.
protocol HasMutableProperty : Concrete {
var mutableThingy: Any? { get set }
}
extension HasMutableProperty {
func mutateThingy() {
mutableThingy = nil
}
}
// Some pathological examples -- just make sure they don't crash.
protocol RecursiveSelf : Generic<Self> {}
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self>' is recursive}}
protocol RecursiveAssociatedType : Generic<Self.X> {
// expected-error@-1 {{superclass constraint 'Self' : 'Generic<Self.X>' is recursive}}
associatedtype X
}
protocol BaseProtocol {
typealias T = Int
}
class BaseClass : BaseProtocol {}
protocol RefinedProtocol : BaseClass {
func takesT(_: T)
}
func takesBaseProtocol(_: BaseProtocol) {}
func passesRefinedProtocol(_ r: RefinedProtocol) {
takesBaseProtocol(r)
}
class RefinedClass : BaseClass, RefinedProtocol {
func takesT(_: T) {
_ = T.self
}
}
class LoopClass : LoopProto {}
protocol LoopProto : LoopClass {}
class FirstClass {}
protocol FirstProtocol : FirstClass {}
class SecondClass : FirstClass {}
protocol SecondProtocol : SecondClass, FirstProtocol {}
class FirstConformer : FirstClass, SecondProtocol {}
// expected-error@-1 {{'SecondProtocol' requires that 'FirstConformer' inherit from 'SecondClass'}}
// expected-note@-2 {{requirement specified as 'Self' : 'SecondClass' [with Self = FirstConformer]}}
class SecondConformer : SecondClass, SecondProtocol {}
// Duplicate superclass
// FIXME: Duplicate diagnostics
protocol DuplicateSuper : Concrete, Concrete {}
// expected-note@-1 {{superclass constraint 'Self' : 'Concrete' written here}}
// expected-warning@-2 {{redundant superclass constraint 'Self' : 'Concrete'}}
// expected-error@-3 {{duplicate inheritance from 'Concrete'}}
// Ambigous name lookup situation
protocol Amb : Concrete {}
// expected-note@-1 {{'Amb' previously declared here}}
// expected-note@-2 {{found this candidate}}
protocol Amb : Concrete {}
// expected-error@-1 {{invalid redeclaration of 'Amb'}}
// expected-note@-2 {{found this candidate}}
extension Amb { // expected-error {{'Amb' is ambiguous for type lookup in this context}}
func extensionMethodUsesClassTypes() {
_ = ConcreteAlias.self
}
}
protocol ProtoRefinesClassComposition : Generic<Int> & BaseProto {}
func usesProtoRefinesClass1(_ t: ProtoRefinesClassComposition) {
t.genericMethod((1, 2))
let _: BaseProto = t
}
func usesProtoRefinesClass2<T : ProtoRefinesClassComposition>(_ t: T) {
t.genericMethod((1, 2))
let _: BaseProto = t
} | apache-2.0 | 65b9661a11964539816d82c6560356bf | 30.915254 | 217 | 0.709038 | 3.867511 | false | false | false | false |
brentsimmons/Frontier | BeforeTheRename/FrontierData/FrontierData/Value/ValueProtocol.swift | 1 | 6923 | //
// Value.swift
// FrontierData
//
// Created by Brent Simmons on 4/20/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
// Go with asBool etc. because boolValue and similar conflict with existing methods.
public let emptyValue: Value = NSNull()
public protocol Value {
var valueType: ValueType { get }
// Coercions -- the default implementations all throw a LangError.
func asBool() throws -> Bool
func asChar() throws -> CChar
func asInt() throws -> Int
func asDouble() throws -> Double
func asDate() throws -> Date
func asDirection() throws -> Direction
func asOSType() throws -> OSType
func asEnumValue() throws -> EnumValue
func asString() throws -> String
func asFileSpec() throws -> String
func asAddress() throws -> Address
func asBinary() throws -> Data
func asList() throws -> List
func asRecord() throws -> Record
// Operations
func unaryMinusValue() throws -> Value
func not() throws -> Bool
func beginsWith(_ otherValue: Value) throws -> Bool
func endsWith(_ otherValue: Value) throws -> Bool
func contains(_ otherValue: Value) throws -> Bool
func mod(_ otherValue: Value) throws -> Value
func add(_ otherValue: Value) throws -> Value
func subtract(_ otherValue: Value) throws -> Value
func divide(_ otherValue: Value) throws -> Value
func multiply(_ otherValue: Value) throws -> Value
// Comparisons
func compareTo(_ otherValue: Value) throws -> ComparisonResult
// If you implement compareTo, you can probably stick with the default version of these.
func equals(_ otherValue: Value) throws -> Bool
func lessThan(_ otherValue: Value) throws -> Bool
func lessThanEqual(_ otherValue: Value) throws -> Bool
func greaterThan(_ otherValue: Value) throws -> Bool
func greaterThanEqual(_ otherValue: Value) throws -> Bool
}
public extension Value {
func asBool() throws -> Bool {
throw LangError(.coercionNotPossible)
}
func asChar() throws -> CChar {
throw LangError(.coercionNotPossible)
}
func asInt() throws -> Int {
throw LangError(.coercionNotPossible)
}
func asDate() throws -> Date {
throw LangError(.coercionNotPossible)
}
func asDouble() throws -> Double {
throw LangError(.coercionNotPossible)
}
func asDirection() throws -> Direction {
throw LangError(.coercionNotPossible)
}
func asEnumValue() throws -> EnumValue {
throw LangError(.coercionNotPossible)
}
func asOSType() throws -> OSType {
throw LangError(.coercionNotPossible)
}
func asBinary() throws -> Data {
throw LangError(.coercionNotPossible)
}
func asAddress() throws -> Address {
throw LangError(.coercionNotPossible)
}
func asString() throws -> String {
throw LangError(.coercionNotPossible)
}
func asFileSpec() throws -> String {
throw LangError(.coercionNotPossible)
}
func asList() throws -> List {
throw LangError(.coercionNotPossible)
}
func asRecord() throws -> Record {
throw LangError(.coercionNotPossible)
}
func commonCoercionType(with otherValue: Value) -> ValueType {
return valueType.commonCoercionType(otherValueType: otherValue.valueType)
}
func compareTo(_ otherValue: Value) throws -> ComparisonResult {
do {
return try compareTwoValues(self, otherValue)
}
catch { throw error }
}
func equals(_ otherValue: Value) throws -> Bool {
do {
let comparisonResult = try compareTo(otherValue)
return comparisonResult == .orderedSame
}
catch { throw error }
}
func unaryMinusValue() throws -> Value {
throw LangError(.unaryMinusNotPossible)
}
func not() throws -> Bool {
throw LangError(.booleanCoerce)
}
func beginsWith(_ otherValue: Value) throws -> Bool {
return false // TODO
}
func endsWith(_ otherValue: Value) throws -> Bool {
return false // TODO
}
func contains(_ otherValue: Value) throws -> Bool {
return false // TODO
}
func lessThan(_ otherValue: Value) throws -> Bool {
do {
let comparisonResult = try compareTo(otherValue)
return comparisonResult == .orderedAscending
}
catch { throw error }
}
func lessThanEqual(_ otherValue: Value) throws -> Bool {
do {
let comparisonResult = try compareTo(otherValue)
return comparisonResult == .orderedAscending || comparisonResult == .orderedSame
}
catch { throw error }
}
func greaterThan(_ otherValue: Value) throws -> Bool {
do {
let comparisonResult = try compareTo(otherValue)
return comparisonResult == .orderedDescending
}
catch { throw error }
}
func greaterThanEqual(_ otherValue: Value) throws -> Bool {
do {
let comparisonResult = try compareTo(otherValue)
return comparisonResult == .orderedDescending || comparisonResult == .orderedSame
}
catch { throw error }
}
func mod(_ otherValue: Value) throws -> Value {
return 0 // TODO
}
func add(_ otherValue: Value) throws -> Value {
return 0 // TODO
}
func subtract(_ otherValue: Value) throws -> Value {
return 0 // TODO
}
func divide(_ otherValue: Value) throws -> Value {
return 0 // TODO
}
func multiply(_ otherValue: Value) throws -> Value {
return 0 // TODO
}
}
// MARK: Coercion Utilities
internal extension Value {
func boolAssumingIntValue() -> Bool {
return try! asInt() != 0
}
func charAssumingIntValue() -> CChar {
return try! CChar(asInt())
}
func doubleAssumingIntValue() -> Double {
return try! Double(asInt())
}
func dateAssumingDoubleValue() -> Date {
return try! Date(timeIntervalSince1904: asDouble())
}
func directionAssumingIntValue() throws -> Direction {
do {
if let d = try Direction(rawValue: asInt()) {
return d
}
throw LangError(.coercionNotPossible)
}
catch { throw error }
}
func osTypeAssumingIntValue() -> OSType {
return OSType("none") // TODO
}
func enumValueAssumingIntValue() -> EnumValue {
return EnumValue(osType: osTypeAssumingIntValue())
}
func stringAssumingInterpolation() -> String {
return "\(self)"
}
func listWithValue() -> List {
return List([self])
}
}
private func compareValues<T:Comparable>(_ v1: T, _ v2: T) -> ComparisonResult {
if v1 == v2 {
return .orderedSame
}
return v1 < v2 ? .orderedAscending : .orderedDescending
}
private func compareTwoValues(_ value1: Value, _ value2: Value) throws -> ComparisonResult {
let coercionType = value1.commonCoercionType(with: value2)
do {
switch coercionType {
case .noValue:
return .orderedSame
case .boolean, .char, .int, .direction:
return try compareValues(value1.asInt(), value2.asInt())
case .date, .double:
return try compareValues(value1.asDouble(), value2.asDouble())
case .string:
return try compareValues(value1.asString(), value2.asString())
default:
throw LangError(.coercionNotPossible)
}
}
catch { throw error }
}
| gpl-2.0 | f894fe6ef72f500fbe8db86188f0a233 | 20.039514 | 92 | 0.682173 | 3.856267 | false | false | false | false |
DolphinQuan/DHCircleView | Example/DHCircleView/DHCircleView.swift | 1 | 6727 | //
// CircleView.swift
// circleView
//
// Created by 全达晖 on 2017/7/21.
// Copyright © 2017年 全达晖. All rights reserved.
//
import UIKit
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
protocol DHCircleViewDelegate {
func circleViewDidSelected(circleView:UIView,index:Int)
}
public class DHCircleView: UIView {
/// 轮播的图片数组 触发属性观察器则会更新图片数据
public var imageArray:[UIImage] {
didSet{
resetStatus()
makeUI()
}
}
/// 自动轮播的时间段
public var times:TimeInterval
var delegate:DHCircleViewDelegate?
fileprivate var timer:Timer?
fileprivate var currentPage = 0
fileprivate var lastPosition:CGFloat = screenWidth
fileprivate lazy var scrollView:UIScrollView = {
var view:UIScrollView = UIScrollView(frame: self.bounds)
view.isPagingEnabled = true
view.backgroundColor = .red
view.delegate = self
view.showsHorizontalScrollIndicator = false
view.contentSize = CGSize(width: CGFloat( self.imageArray.count) * screenWidth, height: self.bounds.size.height)
return view
}()
fileprivate lazy var pageControl:UIPageControl = {
var page = UIPageControl()
page.pageIndicatorTintColor = .red
page.currentPage = 0
return page
}()
public init(_ frame:CGRect,images:[UIImage],time:TimeInterval){
times = time
imageArray = images
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func didMoveToSuperview() {
makeUI()
}
fileprivate func resetStatus(){
removeTimer()
for view in subviews {
view.removeFromSuperview()
}
currentPage = 0
pageControl.currentPage = 0
}
fileprivate func makeUI(){
//创建图片
func creatImageView(frame:CGRect,image:UIImage,tag:Int) -> UIImageView{
let imageView = UIImageView(frame:frame)
imageView.image = image
imageView.tag = tag
imageView.isUserInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(didSelect(pan:)))
imageView.addGestureRecognizer(gesture)
return imageView
}
addSubview(scrollView)
for (index,element) in imageArray.enumerated() {
let indexNew = imageArray.count > 1 ? index + 1: index //images 数组大于一个的时候,需要在前后添加一个图片,做循环轮播
let frame = CGRect(x: (CGFloat(indexNew) * screenWidth), y: 0, width: screenWidth, height: self.bounds.height)
scrollView.addSubview(creatImageView(frame: frame, image: element,tag: index))
}
if imageArray.count > 1 {
//添加最后一个图片
let bottomImageframe = CGRect(x: (CGFloat(imageArray.count + 1) * screenWidth), y: 0, width: screenWidth, height: self.bounds.height)
scrollView.addSubview(creatImageView(frame: bottomImageframe, image: imageArray.first!,tag: 0))
//添加第一个图片
let topImageframe = CGRect(x: 0, y: 0, width: screenWidth, height: self.bounds.height)
scrollView.addSubview(creatImageView(frame: topImageframe, image: imageArray.last!,tag: imageArray.count - 1))
//重新设置第一个图片的位置,及滚动区域
scrollView.setContentOffset(CGPoint.init(x: screenWidth, y: 0), animated: false)
scrollView.contentSize = CGSize(width: CGFloat( imageArray.count + 2) * screenWidth, height: self.bounds.size.height)
}
addSubview(pageControl)
pageControl.numberOfPages = imageArray.count
pageControl.center = CGPoint(x: self.center.x, y: self.bounds.size.height - 10)
addTimer()
}
/// 添加定时器
fileprivate func addTimer(){
guard imageArray.count > 1 else {
pageControl.isHidden = true
return
}
timer = Timer(timeInterval: times, target: self, selector: #selector(scrollToNextPage), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: .commonModes)
}
fileprivate func removeTimer(){
timer?.invalidate()
timer = nil
}
/// 滚动到下一页
@objc fileprivate func scrollToNextPage(){
currentPage += 1
let pointX = CGFloat(currentPage + 1) * screenWidth //多了前面第一张图
scrollView.setContentOffset(CGPoint(x: pointX, y: 0), animated: true)
pageControl.currentPage = currentPage
}
@objc fileprivate func didSelect(pan:UITapGestureRecognizer){
guard let delegate = self.delegate else {
return
}
delegate.circleViewDidSelected(circleView: self, index: pan.view!.tag)
}
}
extension DHCircleView:UIScrollViewDelegate {
final public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeTimer()
}
final public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTimer()
}
final public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
//解决自动轮播下,最后一张跳到第一张图片后,立即使用手势拖拽出现的空白页面情况
if currentPage == imageArray.count{
currentPage = 0
pageControl.currentPage = currentPage
scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: false)
}
}
//处理手势结束
final public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let pageWidth = scrollView.frame.size.width;
let fractionalPage = scrollView.contentOffset.x / pageWidth;
let page = Int(fractionalPage);
if page == imageArray.count + 1 {
scrollView.setContentOffset(CGPoint(x: screenWidth, y: 0), animated: false)
pageControl.currentPage = 0
currentPage = 0
}
else if page == 0 {
scrollView.setContentOffset(CGPoint(x: screenWidth * CGFloat( imageArray.count), y: 0), animated: false)
currentPage = imageArray.count - 1
pageControl.currentPage = imageArray.count - 1
}
else{
pageControl.currentPage = page - 1
currentPage = page - 1
}
}
}
| mit | b5ee931b7b00f034c392d87a37c4df4f | 33.213904 | 145 | 0.629103 | 4.78534 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.