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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
xhamr/fave-button | Source/Helpers/Easing.swift | 1 | 4131 | //
// Easing.swift
// FaveButton
//
// Copyright © 2016 Jansel Valentin.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
typealias Easing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat)-> CGFloat
typealias ElasticEasing = (_ t:CGFloat,_ b:CGFloat,_ c:CGFloat,_ d:CGFloat,_ a:CGFloat,_ p:CGFloat)-> CGFloat
// ELASTIC EASING
struct Elastic{
static var EaseIn :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b }
t/=d
if t==1{ return b+c }
let p = d * 0.3
let a = c
let s = p/4
t -= 1
return -(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b;
}
static var EaseOut :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b }
t/=d
if t==1{ return b+c}
let p = d * 0.3
let a = c
let s = p/4
return (a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p ) + c + b);
}
static var EaseInOut :Easing = { (_t,b,c,d) -> CGFloat in
var t = _t
if t==0{ return b}
t = t/(d/2)
if t==2{ return b+c }
let p = d * (0.3*1.5)
let a = c
let s = p/4
if t < 1 {
t -= 1
return -0.5*(a*pow(2,10*t) * sin((t*d-s)*(2*(.pi))/p )) + b;
}
t -= 1
return a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p )*0.5 + c + b;
}
}
extension Elastic{
static var ExtendedEaseIn :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var t = _t
var a = _a
var p = _p
var s:CGFloat = 0.0
if t==0{ return b }
t /= d
if t==1{ return b+c }
if a < abs(c) {
a=c; s = p/4
}else {
s = p/(2*(.pi)) * asin (c/a);
}
t -= 1
return -(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b;
}
static var ExtendedEaseOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var s:CGFloat = 0.0
var t = _t
var a = _a
var p = _p
if t==0 { return b }
t /= d
if t==1 {return b+c}
if a < abs(c) {
a=c; s = p/4;
}else {
s = p/(2*(.pi)) * asin (c/a)
}
return (a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p ) + c + b)
}
static var ExtendedEaseInOut :ElasticEasing = { (_t,b,c,d,_a,_p) -> CGFloat in
var s:CGFloat = 0.0
var t = _t
var a = _a
var p = _p
if t==0{ return b }
t /= d/2
if t==2{ return b+c }
if a < abs(c) {
a=c; s=p/4;
}else {
s = p/(2*(.pi)) * asin (c/a)
}
if t < 1 {
t -= 1
return -0.5*(a*pow(2,10*t) * sin( (t*d-s)*(2*(.pi))/p )) + b;
}
t -= 1
return a*pow(2,-10*t) * sin( (t*d-s)*(2*(.pi))/p )*0.5 + c + b;
}
}
| mit | 31e7a56ca420b7a76316f4fff5b4c040 | 25.993464 | 109 | 0.470218 | 3.317269 | false | false | false | false |
kysonyangs/ysbilibili | ysbilibili/Classes/WebView/YSBilibiliWebViewController.swift | 1 | 2037 | //
// YSBilibiliWebViewController.swift
// ysbilibili
//
// Created by MOLBASE on 2017/8/5.
// Copyright © 2017年 YangShen. All rights reserved.
//
import UIKit
import WebKit
class YSBilibiliWebViewController: YSBaseViewController {
// 展示的url
var urlString:String?
// MARK: - 懒加载控件
lazy var contentWebView: WKWebView = {
let contentWebView = WKWebView()
contentWebView.navigationDelegate = self
return contentWebView
}()
// MARK: - life cycle
override func viewDidLoad() {
super.viewDidLoad()
// 1. 初始化ui
setupUI()
// 2. 加载url
loadRequest()
}
}
extension YSBilibiliWebViewController {
fileprivate func setupUI() {
view.addSubview(contentWebView)
contentWebView.snp.makeConstraints { (make) in
make.left.right.bottom.equalTo(view)
make.top.equalTo(view).offset(kNavBarHeight)
}
}
fileprivate func loadRequest() {
guard let urlString = urlString else {return}
guard let url = URL(string: urlString) else {return}
let request = URLRequest(url: url)
contentWebView.load(request)
}
}
//======================================================================
// MARK:- wkwebview delegate
//======================================================================
extension YSBilibiliWebViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
naviBar.titleLabel.font = UIFont.systemFont(ofSize: 15)
naviBar.titleLabel.text = webView.title
}
}
//======================================================================
// MARK:- target action
//======================================================================
extension YSBilibiliWebViewController {
@objc fileprivate func pravitePopViewController() {
_ = navigationController?.popViewController(animated: true)
}
}
| mit | b517f55ca4374a8184df041c766d5609 | 26.888889 | 77 | 0.551295 | 5.298153 | false | false | false | false |
djschilling/SOPA-iOS | SOPA/view/LevelMode/LevelSelectButton.swift | 1 | 2728 | //
// LevelButton.swift
// SOPA
//
// Created by Raphael Schilling on 01.09.18.
// Copyright © 2018 David Schilling. All rights reserved.
//
import Foundation
import SpriteKit
class LevelSelectButton: SKSpriteNode {
let green = UIColor(red: 169.0 / 255.0, green: 162.0 / 255.0, blue: 121.0 / 255.0, alpha: 1.0)
let grey = UIColor(red: 0.5 , green: 0.5, blue: 0.5, alpha: 1.0)
let levelInfo: LevelInfo
init(levelInfo: LevelInfo, levelButtonPositioner: LevelButtonPositioner) {
self.levelInfo = levelInfo
if !levelInfo.locked {
let texture = SKTexture(imageNamed: "Level")
super.init(texture: texture, color: UIColor.clear, size: levelButtonPositioner.getLevelSize())
position = levelButtonPositioner.getLevelPosition(id: levelInfo.levelId)
addStars(stars: levelInfo.stars)
addLable(id: levelInfo.levelId, color: green)
} else {
let texture = SKTexture(imageNamed: "LevelSW")
super.init(texture: texture, color: UIColor.clear, size: levelButtonPositioner.getLevelSize())
position = levelButtonPositioner.getLevelPosition(id: levelInfo.levelId)
addLable(id: levelInfo.levelId, color: grey)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addStars(stars: Int) {
let star1: SKSpriteNode = generateStar(achieved: stars >= 1)
let star2: SKSpriteNode = generateStar(achieved: stars >= 2)
let star3: SKSpriteNode = generateStar(achieved: stars >= 3)
star1.position = CGPoint(x: -size.width * 0.25, y: -size.height * 0.2)
star2.position = CGPoint(x: 0, y: -size.height * 0.27 )
star3.position = CGPoint(x: size.width * 0.25, y: -size.height * 0.2)
addChild(star1)
addChild(star2)
addChild(star3)
}
func addLable(id: Int, color: UIColor) {
let idLable = SKLabelNode(fontNamed: "Optima-Bold")
idLable.text = String(id)
idLable.horizontalAlignmentMode = SKLabelHorizontalAlignmentMode.center
idLable.verticalAlignmentMode = SKLabelVerticalAlignmentMode.center
idLable.fontSize = size.height * 0.34
idLable.fontColor = color
idLable.zPosition = zPosition + 1
addChild(idLable)
}
func generateStar(achieved: Bool) -> SKSpriteNode {
var star = SKSpriteNode(imageNamed: "starSW")
if achieved {
star = SKSpriteNode(imageNamed: "star")
}
star.size = CGSize(width: size.width/3, height: size.height/3)
star.zPosition = zPosition + 1
return star
}
}
| apache-2.0 | 2ce66efa92dbb9f736f0463a5a9543fc | 34.881579 | 106 | 0.63513 | 4.113122 | false | true | false | false |
swiftde/Udemy-Swift-Kurs | AlamoApp/AlamoApp/AppDelegate.swift | 1 | 6109 | //
// AppDelegate.swift
// AlamoApp
//
// Created by Udemy on 25.02.15.
// Copyright (c) 2015 benchr. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "de.benchr.AlamoApp" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("AlamoApp", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("AlamoApp.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| apache-2.0 | b8ef60347a449e62eda3b48bd32d6b34 | 54.036036 | 290 | 0.715829 | 5.746943 | false | false | false | false |
mike4aday/SwiftlySalesforce | Sources/SwiftlySalesforce/Services/Resource+SObjects.swift | 1 | 4243 | import Foundation
extension Resource {
struct SObjects {
struct Create<E: Encodable>: DataService {
let type: String
let fields: [String: E]
func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.post
let path = Resource.path(for: "sobjects/\(type)")
let body = try JSONEncoder().encode(fields)
return try URLRequest(credential: credential, method: method, path: path, body: body)
}
func transform(data: Data) throws -> String {
let result = try JSONDecoder(dateFormatter: .salesforce(.long)).decode(Result.self, from: data)
return result.id
}
private struct Result: Decodable {
var id: String
}
}
//MARK: - Read record -
struct Read<D: Decodable>: DataService {
typealias Output = D
let type: String
let id: String
var fields: [String]? = nil
func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.get
let path = Resource.path(for: "sobjects/\(type)/\(id)")
let queryItems = fields.map { ["fields": $0.joined(separator: ",")] }
return try URLRequest(credential: credential, method: method, path: path, queryItems: queryItems)
}
}
//MARK: - Update record -
struct Update<E: Encodable>: DataService {
typealias Output = Void
let type: String
let id: String
let fields: [String: E]
public func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.patch
let encoder = JSONEncoder()
let path = Resource.path(for: "sobjects/\(type)/\(id)")
let body = try encoder.encode(fields)
return try URLRequest(credential: credential, method: method, path: path, body: body)
}
}
//MARK: - Delete record -
struct Delete: DataService {
typealias Output = Void
let type: String
let id: String
func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.delete
let path = Resource.path(for: "sobjects/\(type)/\(id)")
return try URLRequest(credential: credential, method: method, path: path)
}
}
//MARK: - Describe SObject -
struct Describe: DataService {
typealias Output = ObjectDescription
let type: String
func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.get
let path = Resource.path(for: "sobjects/\(type)/describe")
return try URLRequest(credential: credential, method: method, path: path)
}
}
//MARK: - Describe all SObjects -
struct DescribeGlobal: DataService {
func createRequest(with credential: Credential) throws -> URLRequest {
let method = HTTP.Method.get
let path = Resource.path(for: "sobjects")
return try URLRequest(credential: credential, method: method, path: path)
}
func transform(data: Data) throws -> [ObjectDescription] {
struct Result: Decodable {
var sobjects: [ObjectDescription]
}
let result = try JSONDecoder(dateFormatter: .salesforce(.long)).decode(Result.self, from: data)
return result.sobjects
}
}
}
}
| mit | e8fe74e4a0f5316674056b46f23c9ac4 | 36.883929 | 113 | 0.497054 | 5.78854 | false | false | false | false |
shial4/api-loltracker | Sources/App/Models/ChampionStats.swift | 1 | 2094 | //
// ChampionStats.swift
// lolTracker-API
//
// Created by Shial on 13/01/2017.
//
//
import Foundation
import Vapor
import Fluent
final class ChampionStats: Model {
var exists: Bool = false
public var id: Node?
var championId: Node?
var season: String
var kills: Int = 0
var deaths: Int = 0
var assists: Int = 0
var cs: Int = 0
var gold: Int = 0
init(season: String, championId: Node? = nil) {
self.id = nil
self.season = season
self.championId = championId
}
required init(node: Node, in context: Context) throws {
id = try node.extract("id")
championId = try node.extract("champion_id")
season = try node.extract("season")
kills = try node.extract("kills")
deaths = try node.extract("deaths")
assists = try node.extract("assists")
cs = try node.extract("cs")
gold = try node.extract("gold")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"champion_id": championId,
"season": season,
"kills": kills,
"deaths": deaths,
"assists": assists,
"cs": cs,
"gold": gold
])
}
}
extension ChampionStats: Preparation {
static func prepare(_ database: Database) throws {
try database.create(entity, closure: { (stats) in
stats.id()
stats.string("season")
stats.int("kills")
stats.int("deaths")
stats.int("assists")
stats.int("cs")
stats.int("gold")
stats.parent(Summoner.self, optional: false)
})
}
static func revert(_ database: Database) throws {
try database.delete(entity)
}
}
extension ChampionStats {
func champion() throws -> Champions? {
return try parent(championId, nil, Champions.self).get()
}
func stats() throws -> [ChampionStats] {
return try children(nil, ChampionStats.self).all()
}
}
| mit | 3c3a57ffa21f9a49a657e937db52ff1d | 24.536585 | 64 | 0.553009 | 3.950943 | false | false | false | false |
NghiaTranUIT/Titan | TitanCore/TitanCore/TableSchemeContextMenuView.swift | 2 | 1990 | //
// TableSchemeContextMenuView.swift
// TitanCore
//
// Created by Nghia Tran on 4/24/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Cocoa
import SwiftyPostgreSQL
public protocol TableSchemeContextMenuViewDelegate: class {
func TableSchemeContextMenuViewDidTapAction(_ action: TableSchemmaContextAction, table: Table)
}
//
// MARK: - Action
public enum TableSchemmaContextAction {
case openNewtab
case copyTableName
case truncate
case delete
}
open class TableSchemeContextMenuView: NSMenu {
//
// MARK: - Variable
public weak var contextDelegate: TableSchemeContextMenuViewDelegate?
public weak var currentItem: Table?
public weak var selectedRow: TableRowCell?
//
// MARK: - Public
public func configureContextView(with table: Table, selectedRow: TableRowCell) {
self.currentItem = table
self.selectedRow = selectedRow
}
//
// MARK: - OUTLET
@IBAction func openInNewTapBtnTapped(_ sender: Any) {
guard let table = self.currentItem else {return}
self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.openNewtab, table: table)
}
@IBAction func copyNameBtnTapped(_ sender: Any) {
guard let table = self.currentItem else {return}
self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.copyTableName, table: table)
}
@IBAction func truncateTableBtnTapped(_ sender: Any) {
guard let table = self.currentItem else {return}
self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.truncate, table: table)
}
@IBAction func deleteTableBtnTapped(_ sender: Any) {
guard let table = self.currentItem else {return}
self.contextDelegate?.TableSchemeContextMenuViewDidTapAction(.delete, table: table)
}
}
//
// MARK: - XIBInitializable
extension TableSchemeContextMenuView: XIBInitializable {
public typealias T = TableSchemeContextMenuView
}
| mit | 121f51c420a58822ef9a28a9342df6d7 | 28.686567 | 98 | 0.712921 | 4.792771 | false | false | false | false |
mmisesin/github_client | Github Client/CommitsTableViewController.swift | 1 | 6455 | //
// CommitsTableViewController.swift
// Github Client
//
// Created by Artem Misesin on 3/18/17.
// Copyright © 2017 Artem Misesin. All rights reserved.
//
import UIKit
import OAuthSwift
import SwiftyJSON
class CommitsTableViewController: UITableViewController {
var repoTitle: String = ""
var commits: [(message: String, author: String, date: String)] = []
var spinner = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
test(SingleOAuth.shared.oAuthSwift as! OAuth2Swift)
self.tableView.allowsSelection = false
self.tableView.separatorStyle = .none
self.spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
self.spinner.frame = CGRect(x: self.tableView.bounds.midX - 10, y: self.tableView.bounds.midY - 10, width: 20.0, height: 20.0) // (or wherever you want it in the button)
self.tableView.addSubview(self.spinner)
self.spinner.startAnimating()
self.spinner.alpha = 1.0
//self.parent.
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
func test(_ oauthswift: OAuth2Swift) {
let url :String = "https://api.github.com/repos/" + SingleOAuth.shared.owner! + "/\(repoTitle)/commits"
let parameters :Dictionary = Dictionary<String, AnyObject>()
let _ = oauthswift.client.get(
url, parameters: parameters,
success: { response in
let jsonDict = try? JSON(response.jsonObject())
if let arrayMessages = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["message"]?.stringValue}){
if let arrayAuthors = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["committer"]?.dictionaryValue}).map({$0?["name"]?.stringValue}){
if let arrayDates = jsonDict?.arrayValue.map({$0["commit"].dictionaryValue}).map({$0["committer"]?.dictionaryValue}).map({$0?["date"]?.stringValue}){
for i in 0..<arrayMessages.count{
let range = arrayDates[i]?.range(of: "T")
let date = arrayDates[i]?.substring(to: (range?.lowerBound)!)
self.commits.append((arrayMessages[i]!, arrayAuthors[i]!, date!))
}
}
}
}
//print(jsonDict)
self.spinner.stopAnimating()
self.spinner.alpha = 0.0
self.tableView.separatorStyle = .singleLine
self.tableView.reloadData()
},
failure: { error in
print(error.localizedDescription)
var message = ""
if error.localizedDescription == "The operation couldn’t be completed. (OAuthSwiftError error -11.)"{
message = "No internet connection"
} else {
message = "No commits found"
}
let alert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)})
}
func close(){
self.dismiss(animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return commits.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = commits[indexPath.row].message
cell.detailTextLabel?.text = commits[indexPath.row].author + ", " + commits[indexPath.row].date
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 843847ad335ab89797aee1a65b0a18da | 40.095541 | 177 | 0.612678 | 5.199033 | false | false | false | false |
masters3d/xswift | exercises/prime-factors/Sources/PrimeFactorsExample.swift | 3 | 548 | struct PrimeFactors {
var number: Int64
var toArray = [Int64]()
private func primesFor( _ number: Int64) -> [Int64] {
var number = number
var primes = [Int64]()
var divisor: Int64 = 2
while number > 1 {
while number % divisor == 0 {
primes.append(divisor)
number /= divisor
}
divisor += 1
}
return primes
}
init(_ value: Int64) {
self.number = value
self.toArray = primesFor(value)
}
}
| mit | 6c69127153fa3b3124c4658955f6df83 | 19.296296 | 57 | 0.483577 | 4.384 | false | false | false | false |
digoreis/swift-proposal-analyzer | swift-proposal-analyzer.playground/Pages/SE-0040.xcplaygroundpage/Contents.swift | 1 | 3683 | /*:
# Replacing Equal Signs with Colons For Attribute Arguments
* Proposal: [SE-0040](0040-attributecolons.md)
* Author: [Erica Sadun](http://github.com/erica)
* Review Manager: [Chris Lattner](https://github.com/lattner)
* Status: **Implemented (Swift 3)**
* Decision Notes: [Rationale](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160307/012100.html)
* Pull Request: [apple/swift#1537](https://github.com/apple/swift/pull/1537)
## Introduction
Attribute arguments are unlike other Swift language arguments. At the call site, they use `=` instead of colons
to distinguish argument names from passed values. This proposal brings attributes into compliance with Swift
standard practices by replacing the use of "=" with ":" in this one-off case.
*Discussion took place on the Swift Evolution mailing list in the [\[Discussion\] Replacing Equal Signs with Colons For Attribute Arguments](https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20160215/010448.html) thread. Thanks to [Doug Gregor](https://github.com/DougGregor) for suggesting this enhancement.*
## Motivation
Attributes enable developers to annotate declarations and types with keywords that constrain behavior.
Recognizable by their [at-sign](http://foldoc.org/strudel) "@" prefix, attributes communicate features,
characteristics, restrictions, and expectations of types and declarations to the Swift compiler.
Common attributes include `@noescape` for parameters that cannot outlive the lifetime of a call,
`@convention`, to indicates whether a type's calling conventions follows a Swift, C, or (Objective-C) block model, and
`@available` to enumerate a declaration's compatibility with platform and OS versions. Swift currently
offers about a dozen distinct attributes, and is likely to expand this vocabulary in future language updates.
Some attributes accept arguments: `@attribute-name(attribute-arguments)` including, at this time,
`@available`, `@warn_unused_result` and `@swift3_migration`. In the current grammar, an equal sign separates attribute
argument keywords from values.
```swift
introduced=version-number
deprecated=version-number
obsoleted=version-number
message=message
renamed=new-name
mutable_variant=method-name
```
Using `=` is out of step with other Swift parameterization call-site patterns.
Although the scope of this proposal is quite small, tweaking the grammar to match the
rest of Swift introduces a small change that adds consistency across the language.
```swift
parameter name: parameter value
```
## Detail Design
This proposal replaces the use of `=` with `:` in the balanced tokens used to compose an attribute
argument clause along the following lines:
```swift
attribute → @ attribute-name attribute-argument-clause<sub>opt</sub>
attribute-name → identifier
attribute-argument-clause → ( balanced-tokens<sub>opt<opt> )
balanced-tokens → balanced-token
balanced-tokens → balanced-token, balanced-tokens
balanced-token → attribute-argument-label : attribute argument-value
```
This design can be summarized as "wherever current Swift attributes use `=`, use `:` instead", for example:
```swift
@available(*, unavailable, renamed: "MyRenamedProtocol")
typealias MyProtocol = MyRenamedProtocol
@warn_unused_result(mutable_variant: "sortInPlace")
public func sort() -> [Self.Generator.Element]
@available(*, deprecated, message: "it will be removed in Swift 3. Use the 'generate()' method on the collection.")
public init(_ bounds: Range<Element>)
```
## Alternatives Considered
There are no alternatives to put forth other than not accepting this proposal.
----------
[Previous](@previous) | [Next](@next)
*/
| mit | 7f4b8fbd846f0db0c1a6e884b451e671 | 42.188235 | 321 | 0.774448 | 4.129359 | false | false | false | false |
oisdk/SwiftDataStructures | SwiftDataStructures/Deque.swift | 1 | 15120 | // MARK: Definition
/**
A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised
of two queues. This implementation has a front queue, which is reversed, and a back queue,
which is not. Operations at either end of the Deque have the same complexity as operations
on the end of either queue.
Three structs conform to the `DequeType` protocol: `Deque`, `DequeSlice`, and
`ContiguousDeque`. These correspond to the standard library array types.
*/
public protocol DequeType :
MutableCollectionType,
RangeReplaceableCollectionType,
CustomDebugStringConvertible,
ArrayLiteralConvertible {
/// The type that represents the queues.
associatedtype Container : RangeReplaceableCollectionType, MutableCollectionType
/// The front queue. It is stored in reverse.
var front: Container { get set }
/// The back queue.
var back : Container { get set }
/// Constructs an empty `Deque`
init()
}
// MARK: DebugDescription
extension DequeType {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
let fStr = front.reverse().map { String(reflecting: $0) }.joinWithSeparator(", ")
let bStr = back.map { String(reflecting: $0) }.joinWithSeparator(", ")
return "[" + fStr + " | " + bStr + "]"
}
}
// MARK: Initializers
extension DequeType {
internal init(balancedF: Container, balancedB: Container) {
self.init()
front = balancedF
back = balancedB
}
/// Construct from a collection
public init<
C : CollectionType where
C.Index : RandomAccessIndexType,
C.SubSequence.Generator.Element == Container.Generator.Element,
C.Index.Distance == Container.Index.Distance
>(col: C) {
self.init()
let mid = col.count / 2
let midInd = col.startIndex.advancedBy(mid)
front.reserveCapacity(mid)
back.reserveCapacity(mid.successor())
front.appendContentsOf(col[col.startIndex..<midInd].reverse())
back.appendContentsOf(col[midInd..<col.endIndex])
}
}
extension DequeType where Container.Index.Distance == Int {
/// Create an instance containing `elements`.
public init(arrayLiteral elements: Container.Generator.Element...) {
self.init(col: elements)
}
/// Initialise from a sequence.
public init<
S : SequenceType where
S.Generator.Element == Container.Generator.Element
>(_ seq: S) {
self.init(col: Array(seq))
}
}
// MARK: Indexing
private enum IndexLocation<I> {
case Front(I), Back(I)
}
extension DequeType where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : ForwardIndexType {
private func translate(i: Container.Index.Distance) -> IndexLocation<Container.Index> {
return i < front.count ?
.Front(front.endIndex.predecessor().advancedBy(-i)) :
.Back(back.startIndex.advancedBy(i - front.count))
}
/**
The position of the first element in a non-empty `Deque`.
In an empty `Deque`, `startIndex == endIndex`.
*/
public var startIndex: Container.Index.Distance { return 0 }
/**
The `Deque`'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 : Container.Index.Distance { return front.count + back.count }
public subscript(i: Container.Index.Distance) -> Container.Generator.Element {
get {
switch translate(i) {
case let .Front(i): return front[i]
case let .Back(i): return back[i]
}
} set {
switch translate(i) {
case let .Front(i): front[i] = newValue
case let .Back(i): back[i] = newValue
}
}
}
}
// MARK: Index Ranges
private enum IndexRangeLocation<I : ForwardIndexType> {
case Front(Range<I>), Over(Range<I>, Range<I>), Back(Range<I>), Between
}
extension DequeType where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : BidirectionalIndexType {
private func translate
(i: Range<Container.Index.Distance>)
-> IndexRangeLocation<Container.Index> {
if i.endIndex <= front.count {
let s = front.endIndex.advancedBy(-i.endIndex)
if s == front.startIndex && i.isEmpty { return .Between }
let e = front.endIndex.advancedBy(-i.startIndex)
return .Front(s..<e)
}
if i.startIndex >= front.count {
let s = back.startIndex.advancedBy(i.startIndex - front.count)
let e = back.startIndex.advancedBy(i.endIndex - front.count)
return .Back(s..<e)
}
let f = front.startIndex..<front.endIndex.advancedBy(-i.startIndex)
let b = back.startIndex..<back.startIndex.advancedBy(i.endIndex - front.count)
return .Over(f, b)
}
}
extension DequeType where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : BidirectionalIndexType,
SubSequence : DequeType,
SubSequence.Container == Container.SubSequence,
SubSequence.Generator.Element == Container.Generator.Element {
public subscript(idxs: Range<Container.Index.Distance>) -> SubSequence {
set { for (index, value) in zip(idxs, newValue) { self[index] = value } }
get {
switch translate(idxs) {
case .Between: return SubSequence()
case let .Over(f, b):
return SubSequence( balancedF: front[f], balancedB: back[b] )
case let .Front(i):
if i.isEmpty { return SubSequence() }
return SubSequence(
balancedF: front[i.startIndex.successor()..<i.endIndex],
balancedB: front[i.startIndex...i.startIndex]
)
case let .Back(i):
if i.isEmpty { return SubSequence() }
return SubSequence(
balancedF: back[i.startIndex..<i.startIndex.successor()],
balancedB: back[i.startIndex.successor()..<i.endIndex]
)
}
}
}
}
// MARK: Balance
private enum Balance {
case FrontEmpty, BackEmpty, Balanced
}
extension DequeType {
private var balance: Balance {
let (f, b) = (front.count, back.count)
if f == 0 {
if b > 1 {
return .FrontEmpty
}
} else if b == 0 {
if f > 1 {
return .BackEmpty
}
}
return .Balanced
}
internal var isBalanced: Bool {
return balance == .Balanced
}
}
extension DequeType where Container.Index : BidirectionalIndexType {
private mutating func check() {
switch balance {
case .FrontEmpty:
let newBack = back.removeLast()
front.reserveCapacity(back.count)
front.replaceRange(front.indices, with: back.reverse())
back.replaceRange(back.indices, with: [newBack])
case .BackEmpty:
let newFront = front.removeLast()
back.reserveCapacity(front.count)
back.replaceRange(back.indices, with: front.reverse())
front.replaceRange(front.indices, with: [newFront])
case .Balanced: return
}
}
}
// MARK: ReserveCapacity
extension DequeType {
/**
Reserve enough space to store `minimumCapacity` elements.
- Postcondition: `capacity >= minimumCapacity` and the `Deque` has mutable
contiguous storage.
- Complexity: O(`count`).
*/
public mutating func reserveCapacity(n: Container.Index.Distance) {
front.reserveCapacity(n / 2)
back.reserveCapacity(n / 2)
}
}
// MARK: ReplaceRange
extension DequeType where
Container.Index : RandomAccessIndexType,
Container.Index.Distance : BidirectionalIndexType {
/**
Replace the given `subRange` of elements with `newElements`.
Invalidates all indices with respect to `self`.
- Complexity: O(`subRange.count`) if `subRange.endIndex == self.endIndex` and
`isEmpty(newElements)`, O(`self.count + newElements.count`) otherwise.
*/
public mutating func replaceRange<
C : CollectionType where C.Generator.Element == Container.Generator.Element
>(subRange: Range<Container.Index.Distance>, with newElements: C) {
defer { check() }
switch translate(subRange) {
case .Between:
back.replaceRange(back.startIndex..<back.startIndex, with: newElements)
case let .Front(r):
front.replaceRange(r, with: newElements.reverse())
case let .Back(r):
back.replaceRange(r, with: newElements)
case let .Over(f, b):
front.removeRange(f)
back.replaceRange(b, with: newElements)
}
}
}
extension RangeReplaceableCollectionType where Index : BidirectionalIndexType {
private mutating func popLast() -> Generator.Element? {
return isEmpty ? nil : removeLast()
}
}
// MARK: StackLike
extension DequeType where Container.Index : BidirectionalIndexType {
/**
If `!self.isEmpty`, remove the first element and return it, otherwise return `nil`.
- Complexity: Amortized O(1)
*/
public mutating func popFirst() -> Container.Generator.Element? {
defer { check() }
return front.popLast() ?? back.popLast()
}
/**
If `!self.isEmpty`, remove the last element and return it, otherwise return `nil`.
- Complexity: Amortized O(1)
*/
public mutating func popLast() -> Container.Generator.Element? {
defer { check() }
return back.popLast() ?? front.popLast()
}
}
// MARK: SequenceType
/// :nodoc:
public struct DequeGenerator<
Container : RangeReplaceableCollectionType where
Container.Index : BidirectionalIndexType
> : GeneratorType {
private let front, back: Container
private var i: Container.Index
private var onBack: Bool
/**
Advance to the next element and return it, or `nil` if no next element exists.
- Requires: `next()` has not been applied to a copy of `self`.
*/
public mutating func next() -> Container.Generator.Element? {
if onBack {
if i == back.endIndex { return nil }
defer { i._successorInPlace() }
return back[i]
}
guard i == front.startIndex else {
i._predecessorInPlace()
return front[i]
}
onBack = true
i = back.startIndex
return next()
}
}
extension DequeType where Container.Index : BidirectionalIndexType {
/**
Return a `DequeGenerator` over the elements of this `Deque`.
- Complexity: O(1)
*/
public func generate() -> DequeGenerator<Container> {
return DequeGenerator(front: front, back: back, i: front.endIndex, onBack: false)
}
}
// MARK: Rotations
extension DequeType where Container.Index : BidirectionalIndexType {
/**
Removes an element from the end of `self`, and prepends it to `self`
```swift
var deque: Deque = [1, 2, 3, 4, 5]
deque.rotateRight()
// deque == [5, 1, 2, 3, 4]
```
- Complexity: Amortized O(1)
*/
public mutating func rotateRight() {
if back.isEmpty { return }
front.append(back.removeLast())
check()
}
/**
Removes an element from the start of `self`, and appends it to `self`
```swift
var deque: Deque = [1, 2, 3, 4, 5]
deque.rotateLeft()
// deque == [2, 3, 4, 5, 1]
```
- Complexity: Amortized O(1)
*/
public mutating func rotateLeft() {
if front.isEmpty { return }
back.append(front.removeLast())
check()
}
/**
Removes an element from the end of `self`, and prepends `x` to `self`
```swift
var deque: Deque = [1, 2, 3, 4, 5]
deque.rotateRight(0)
// deque == [0, 1, 2, 3, 4]
```
- Complexity: Amortized O(1)
*/
public mutating func rotateRight(x: Container.Generator.Element) {
let _ = back.popLast() ?? front.popLast()
front.append(x)
check()
}
/**
Removes an element from the start of `self`, and appends `x` to `self`
```swift
var deque: Deque = [1, 2, 3, 4, 5]
deque.rotateLeft(0)
// deque == [2, 3, 4, 5, 0]
```
- Complexity: Amortized O(1)
*/
public mutating func rotateLeft(x: Container.Generator.Element) {
let _ = front.popLast() ?? back.popLast()
back.append(x)
check()
}
}
// MARK: Reverse
extension DequeType {
/**
Return a `Deque` containing the elements of `self` in reverse order.
*/
public func reverse() -> Self {
return Self(balancedF: back, balancedB: front)
}
}
// MARK: -ending
extension DequeType where Container.Index : BidirectionalIndexType {
/**
Prepend `x` to `self`.
The index of the new element is `self.startIndex`.
- Complexity: Amortized O(1).
*/
public mutating func prepend(x: Container.Generator.Element) {
front.append(x)
check()
}
/**
Prepend the elements of `newElements` to `self`.
- Complexity: O(*length of result*).
*/
public mutating func prextend<
S : SequenceType where
S.Generator.Element == Container.Generator.Element
>(x: S) {
front.appendContentsOf(x.reverse())
check()
}
}
// MARK: Underestimate Count
extension DequeType {
/**
Return a value less than or equal to the number of elements in `self`,
**nondestructively**.
*/
public func underestimateCount() -> Int {
return front.underestimateCount() + back.underestimateCount()
}
}
// MARK: Structs
/**
A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised
of two queues. This implementation has a front queue, which is a reversed array, and a
back queue, which is an array. Operations at either end of the Deque have the same
complexity as operations on the end of either array.
*/
public struct Deque<Element> : DequeType {
/// The front and back queues. The front queue is stored in reverse.
public var front, back: [Element]
public typealias SubSequence = DequeSlice<Element>
/// Initialise an empty `Deque`
public init() { (front, back) = ([], []) }
}
/**
A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised
of two queues. This implementation has a front queue, which is a reversed ArraySlice, and
a back queue, which is an ArraySlice. Operations at either end of the Deque have the same
complexity as operations on the end of either ArraySlice.
Because an `ArraySlice` presents a view onto the storage of some larger array even after
the original array's lifetime ends, storing the slice may prolong the lifetime of elements
that are no longer accessible, which can manifest as apparent memory and object leakage.
To prevent this effect, use `DequeSlice` only for transient computation.
*/
public struct DequeSlice<Element> : DequeType {
/// The front and back queues. The front queue is stored in reverse
public var front, back: ArraySlice<Element>
public typealias SubSequence = DequeSlice
/// Initialise an empty `DequeSlice`
public init() { (front, back) = ([], []) }
}
/**
A [Deque](https://en.wikipedia.org/wiki/Double-ended_queue) is a data structure comprised
of two queues. This implementation has a front queue, which is a reversed ContiguousArray,
and a back queue, which is a ContiguousArray. Operations at either end of the Deque have
the same complexity as operations on the end of either ContiguousArray.
*/
public struct ContiguousDeque<Element> : DequeType {
/// The front and back queues. The front queue is stored in reverse
public var front, back: ContiguousArray<Element>
public typealias SubSequence = DequeSlice<Element>
/// Initialise an empty `ContiguousDeque`
public init() { (front, back) = ([], []) }
} | mit | a8f3491480faa38c7425aa2e16dcd064 | 28.247582 | 90 | 0.67619 | 4.066703 | false | false | false | false |
mrgerych/Cuckoo | Generator/Source/CuckooGeneratorFramework/Tokens/Key.swift | 1 | 678 | //
// Key.swift
// CuckooGenerator
//
// Created by Filip Dolnik on 30.05.16.
// Copyright © 2016 Brightify. All rights reserved.
//
public enum Key: String {
case Substructure = "key.substructure"
case Kind = "key.kind"
case Accessibility = "key.accessibility"
case SetterAccessibility = "key.setter_accessibility"
case Name = "key.name"
case TypeName = "key.typename"
case InheritedTypes = "key.inheritedtypes"
case Length = "key.length"
case Offset = "key.offset"
case NameLength = "key.namelength"
case NameOffset = "key.nameoffset"
case BodyLength = "key.bodylength"
case BodyOffset = "key.bodyoffset"
}
| mit | 8ab63ff26e26ec4bbda40acc88984bc5 | 25.038462 | 57 | 0.667651 | 3.679348 | false | false | false | false |
zisko/swift | test/IRGen/protocol_conformance_records.swift | 1 | 5597 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
// RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-resilience -enable-source-import -I %S/../Inputs | %FileCheck %s
import resilient_struct
import resilient_protocol
public protocol Runcible {
func runce()
}
// CHECK-LABEL: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE:@"\$S28protocol_conformance_records8RuncibleMp"]]
// -- type metadata
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeValueType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- class metadata
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public class NativeClassType: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP"
// -- flags
// CHECK-SAME: i32 0
// CHECK-SAME: },
public struct NativeGenericType<T>: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"$SSi28protocol_conformance_records8RuncibleAAMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- type metadata
// CHECK-SAME: @"got.$SSiMn"
// -- witness table
// CHECK-SAME: @"$SSi28protocol_conformance_records8RuncibleAAWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Int: Runcible {
public func runce() {}
}
// For a resilient struct, reference the NominalTypeDescriptor
// CHECK-LABEL: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ protected | }}constant %swift.protocol_conformance_descriptor {
// -- protocol descriptor
// CHECK-SAME: [[RUNCIBLE]]
// -- nominal type descriptor
// CHECK-SAME: @"got.$S16resilient_struct4SizeVMn"
// -- witness table
// CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP"
// -- reserved
// CHECK-SAME: i32 8
// CHECK-SAME: }
extension Size: Runcible {
public func runce() {}
}
// CHECK-LABEL: @"\01l_protocols"
// CHECK-SAME: @"$S28protocol_conformance_records8RuncibleMp"
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
// TODO: conformances that need lazy initialization
public protocol Spoon { }
// Conditional conformances
// CHECK-LABEL: {{^}}@"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
// -- nominal type descriptor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVMn"
// -- witness table accessor
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlWa
// -- flags
// CHECK-SAME: i32 258
// -- conditional requirement #1
// CHECK-SAME: i32 64,
// CHECK-SAME: i32 0,
// CHECK-SAME: @"$S28protocol_conformance_records5SpoonMp"
// CHECK-SAME: }
extension NativeGenericType : Spoon where T: Spoon {
public func runce() {}
}
// Retroactive conformance
// CHECK-LABEL: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ protected | }}constant
// -- protocol descriptor
// CHECK-SAME: @"got.$S18resilient_protocol22OtherResilientProtocolMp"
// -- nominal type descriptor
// CHECK-SAME: @"got.$SSiMn"
// -- witness table accessor
// CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsWa"
// -- flags
// CHECK-SAME: i32 73,
// -- module context for retroactive conformance
// CHECK-SAME: @"$S28protocol_conformance_recordsMXM"
// CHECK-SAME: }
extension Int : OtherResilientProtocol { }
// CHECK-LABEL: @"\01l_protocol_conformances" = private constant
// CHECK-SAME: @"$S28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc"
// CHECK-SAME: @"$S28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc"
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc"
// CHECK-SAME: @"$S16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc"
// CHECK-SAME: @"$S28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc"
// CHECK-SAME: @"$SSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc"
| apache-2.0 | 1b4aa55c8675117cc388b78b060eff70 | 41.725191 | 165 | 0.697159 | 3.997857 | false | false | false | false |
atl009/WordPress-iOS | WordPress/WordPressTest/PostEditorStateTests.swift | 1 | 9758 | import XCTest
@testable import WordPress
class PostEditorStateTests: XCTestCase {
var context: PostEditorStateContext!
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
context = nil
}
func testContextNoContentPublishButtonDisabled() {
context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self)
context.updated(hasContent: false)
XCTAssertFalse(context.isPublishButtonEnabled)
}
func testContextChangedNewPostToDraft() {
context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self)
context.updated(postStatus: .draft)
XCTAssertEqual(PostEditorAction.save, context.action, "New posts switched to draft should show Save button.")
}
func testContextExistingDraft() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
XCTAssertEqual(PostEditorAction.update, context.action, "Existing draft posts should show Update button.")
}
func testContextPostSwitchedBetweenFutureAndCurrent() {
context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self)
XCTAssertEqual(PostEditorAction.publish, context.action)
context.updated(publishDate: Date.distantFuture)
XCTAssertEqual(PostEditorAction.schedule, context.action)
context.updated(publishDate: nil)
XCTAssertEqual(PostEditorAction.publish, context.action)
}
func testContextScheduledPost() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self)
XCTAssertEqual(PostEditorAction.update, context.action, "Scheduled posts should show Update")
}
func testContextScheduledPostUpdated() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self)
context.updated(postStatus: .scheduled)
XCTAssertEqual(PostEditorAction.update, context.action, "Scheduled posts that get updated should still show Update")
}
}
// These tests are all based off of Calypso unit tests
// https://github.com/Automattic/wp-calypso/blob/master/client/post-editor/editor-publish-button/test/index.jsx
extension PostEditorStateTests {
func testContextChangedPublishedPostStaysPublished() {
context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self)
XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post was originally published and is still slated to be published")
}
func testContextChangedPublishedPostToDraft() {
context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self)
context.updated(postStatus: .draft)
XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post was originally published and is currently reverted to non-published status")
}
func testContextPostFutureDatedButNotYetScheduled() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(postStatus: .publish)
context.updated(publishDate: Date.distantFuture)
XCTAssertEqual(PostEditorAction.schedule, context.action, "should return Schedule if the post is dated in the future and not scheduled")
}
func testContextPostFutureDatedAlreadyPublished() {
context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self)
context.updated(postStatus: .publish)
context.updated(publishDate: Date.distantFuture)
XCTAssertEqual(PostEditorAction.schedule, context.action, "should return Schedule if the post is dated in the future and published")
}
func testContextPostFutureDatedAlreadyScheduled() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self)
context.updated(postStatus: .scheduled)
context.updated(publishDate: Date.distantFuture)
XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post is scheduled and dated in the future")
}
func testContextUpdatingAlreadyScheduledToDraft() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self)
context.updated(publishDate: Date.distantFuture)
context.updated(postStatus: .draft)
XCTAssertEqual(PostEditorAction.update, context.action, "should return Update if the post is scheduled, dated in the future, and next status is draft")
}
func testContextPostPastDatedAlreadyScheduled() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, delegate: self)
context.updated(publishDate: Date.distantPast)
context.updated(postStatus: .scheduled)
XCTAssertEqual(PostEditorAction.publish, context.action, "should return Publish if the post is scheduled and dated in the past")
}
func testContextDraftPost() {
context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self)
XCTAssertEqual(PostEditorAction.publish, context.action, "should return Publish if the post is a draft")
}
func testContextUserCannotPublish() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: false, delegate: self)
XCTAssertEqual(PostEditorAction.submitForReview, context.action, "should return 'Submit for Review' if the post is a draft and user can't publish")
}
func testPublishEnabledHasContentAndChangesNotPublishing() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(hasContent: true)
context.updated(hasChanges: true)
context.updated(isBeingPublished: false)
XCTAssertTrue(context.isPublishButtonEnabled, "should return true if form is not publishing and post is not empty")
}
func testPublishDisabledHasContentAndNoChangesNotPublishing() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(hasContent: true)
context.updated(hasChanges: false)
context.updated(isBeingPublished: false)
XCTAssertFalse(context.isPublishButtonEnabled, "should return true if form is not publishing and post is not empty")
}
// Missing test: should return false if form is not publishing and post is not empty, but user is not verified
// Missing test: should return true if form is not published and post is new and has content, but is not dirty
func testPublishDisabledDuringPublishing() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(isBeingPublished: true)
XCTAssertFalse(context.isPublishButtonEnabled, "should return false if form is publishing")
}
// Missing test: should return false if saving is blocked
// Missing test: should return false if not dirty and has no content
func testPublishDisabledNoContent() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(hasContent: false)
XCTAssertFalse(context.isPublishButtonEnabled, "should return false if post has no content")
}
}
extension PostEditorStateTests {
func testPublishSecondaryDisabledNoContent() {
context = PostEditorStateContext(originalPostStatus: nil, userCanPublish: true, delegate: self)
context.updated(hasContent: false)
XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false if post has no content")
}
func testPublishSecondaryAlreadyPublishedPosts() {
context = PostEditorStateContext(originalPostStatus: .publish, userCanPublish: true, delegate: self)
context.updated(hasContent: true)
XCTAssertEqual(PostEditorAction.update, context.action)
XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for already published posts")
}
func testPublishSecondaryAlreadyDraftedPosts() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, delegate: self)
context.updated(hasContent: true)
XCTAssertTrue(context.isSecondaryPublishButtonShown, "should return true for existing drafts (publish now)")
}
func testPublishSecondaryExistingFutureDatedDrafts() {
context = PostEditorStateContext(originalPostStatus: .draft, userCanPublish: true, publishDate: Date.distantFuture, delegate: self)
context.updated(hasContent: true)
XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for existing future-dated drafts (no publish now)")
}
func testPublishSecondaryAlreadyScheduledPosts() {
context = PostEditorStateContext(originalPostStatus: .scheduled, userCanPublish: true, publishDate: Date.distantFuture, delegate: self)
context.updated(hasContent: true)
XCTAssertFalse(context.isSecondaryPublishButtonShown, "should return false for existing scheduled drafts (no publish now)")
}
}
extension PostEditorStateTests: PostEditorStateContextDelegate {
func context(_ context: PostEditorStateContext, didChangeAction: PostEditorAction) {
}
func context(_ context: PostEditorStateContext, didChangeActionAllowed: Bool) {
}
}
| gpl-2.0 | 9654e57881d8311589d9af5a1a6f7980 | 41.242424 | 174 | 0.746567 | 5.445313 | false | true | false | false |
lorentey/swift | stdlib/public/core/Policy.swift | 6 | 18095 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
// Swift Standard Prolog Library.
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Standardized uninhabited type
//===----------------------------------------------------------------------===//
/// The return type of functions that do not return normally, that is, a type
/// with no values.
///
/// Use `Never` as the return type when declaring a closure, function, or
/// method that unconditionally throws an error, traps, or otherwise does
/// not terminate.
///
/// func crashAndBurn() -> Never {
/// fatalError("Something very, very bad happened")
/// }
@frozen
public enum Never {}
extension Never: Error {}
extension Never: Equatable {}
extension Never: Comparable {
public static func < (lhs: Never, rhs: Never) -> Bool {
}
}
extension Never: Hashable {}
//===----------------------------------------------------------------------===//
// Standardized aliases
//===----------------------------------------------------------------------===//
/// The return type of functions that don't explicitly specify a return type,
/// that is, an empty tuple `()`.
///
/// When declaring a function or method, you don't need to specify a return
/// type if no value will be returned. However, the type of a function,
/// method, or closure always includes a return type, which is `Void` if
/// otherwise unspecified.
///
/// Use `Void` or an empty tuple as the return type when declaring a closure,
/// function, or method that doesn't return a value.
///
/// // No return type declared:
/// func logMessage(_ s: String) {
/// print("Message: \(s)")
/// }
///
/// let logger: (String) -> Void = logMessage
/// logger("This is a void function")
/// // Prints "Message: This is a void function"
public typealias Void = ()
//===----------------------------------------------------------------------===//
// Aliases for floating point types
//===----------------------------------------------------------------------===//
// FIXME: it should be the other way round, Float = Float32, Double = Float64,
// but the type checker loses sugar currently, and ends up displaying 'FloatXX'
// in diagnostics.
/// A 32-bit floating point type.
public typealias Float32 = Float
/// A 64-bit floating point type.
public typealias Float64 = Double
//===----------------------------------------------------------------------===//
// Default types for unconstrained literals
//===----------------------------------------------------------------------===//
/// The default type for an otherwise-unconstrained integer literal.
public typealias IntegerLiteralType = Int
/// The default type for an otherwise-unconstrained floating point literal.
public typealias FloatLiteralType = Double
/// The default type for an otherwise-unconstrained Boolean literal.
///
/// When you create a constant or variable using one of the Boolean literals
/// `true` or `false`, the resulting type is determined by the
/// `BooleanLiteralType` alias. For example:
///
/// let isBool = true
/// print("isBool is a '\(type(of: isBool))'")
/// // Prints "isBool is a 'Bool'"
///
/// The type aliased by `BooleanLiteralType` must conform to the
/// `ExpressibleByBooleanLiteral` protocol.
public typealias BooleanLiteralType = Bool
/// The default type for an otherwise-unconstrained unicode scalar literal.
public typealias UnicodeScalarType = String
/// The default type for an otherwise-unconstrained Unicode extended
/// grapheme cluster literal.
public typealias ExtendedGraphemeClusterType = String
/// The default type for an otherwise-unconstrained string literal.
public typealias StringLiteralType = String
//===----------------------------------------------------------------------===//
// Default types for unconstrained number literals
//===----------------------------------------------------------------------===//
#if !os(Windows) && (arch(i386) || arch(x86_64))
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE80
#else
public typealias _MaxBuiltinFloatType = Builtin.FPIEEE64
#endif
//===----------------------------------------------------------------------===//
// Standard protocols
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// The protocol to which all classes implicitly conform.
///
/// You use `AnyObject` when you need the flexibility of an untyped object or
/// when you use bridged Objective-C methods and properties that return an
/// untyped result. `AnyObject` can be used as the concrete type for an
/// instance of any class, class type, or class-only protocol. For example:
///
/// class FloatRef {
/// let value: Float
/// init(_ value: Float) {
/// self.value = value
/// }
/// }
///
/// let x = FloatRef(2.3)
/// let y: AnyObject = x
/// let z: AnyObject = FloatRef.self
///
/// `AnyObject` can also be used as the concrete type for an instance of a type
/// that bridges to an Objective-C class. Many value types in Swift bridge to
/// Objective-C counterparts, like `String` and `Int`.
///
/// let s: AnyObject = "This is a bridged string." as NSString
/// print(s is NSString)
/// // Prints "true"
///
/// let v: AnyObject = 100 as NSNumber
/// print(type(of: v))
/// // Prints "__NSCFNumber"
///
/// The flexible behavior of the `AnyObject` protocol is similar to
/// Objective-C's `id` type. For this reason, imported Objective-C types
/// frequently use `AnyObject` as the type for properties, method parameters,
/// and return values.
///
/// Casting AnyObject Instances to a Known Type
/// ===========================================
///
/// Objects with a concrete type of `AnyObject` maintain a specific dynamic
/// type and can be cast to that type using one of the type-cast operators
/// (`as`, `as?`, or `as!`).
///
/// This example uses the conditional downcast operator (`as?`) to
/// conditionally cast the `s` constant declared above to an instance of
/// Swift's `String` type.
///
/// if let message = s as? String {
/// print("Successful cast to String: \(message)")
/// }
/// // Prints "Successful cast to String: This is a bridged string."
///
/// If you have prior knowledge that an `AnyObject` instance has a particular
/// type, you can use the unconditional downcast operator (`as!`). Performing
/// an invalid cast triggers a runtime error.
///
/// let message = s as! String
/// print("Successful cast to String: \(message)")
/// // Prints "Successful cast to String: This is a bridged string."
///
/// let badCase = v as! String
/// // Runtime error
///
/// Casting is always safe in the context of a `switch` statement.
///
/// let mixedArray: [AnyObject] = [s, v]
/// for object in mixedArray {
/// switch object {
/// case let x as String:
/// print("'\(x)' is a String")
/// default:
/// print("'\(object)' is not a String")
/// }
/// }
/// // Prints "'This is a bridged string.' is a String"
/// // Prints "'100' is not a String"
///
/// Accessing Objective-C Methods and Properties
/// ============================================
///
/// When you use `AnyObject` as a concrete type, you have at your disposal
/// every `@objc` method and property---that is, methods and properties
/// imported from Objective-C or marked with the `@objc` attribute. Because
/// Swift can't guarantee at compile time that these methods and properties
/// are actually available on an `AnyObject` instance's underlying type, these
/// `@objc` symbols are available as implicitly unwrapped optional methods and
/// properties, respectively.
///
/// This example defines an `IntegerRef` type with an `@objc` method named
/// `getIntegerValue()`.
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
///
/// @objc func getIntegerValue() -> Int {
/// return value
/// }
/// }
///
/// func getObject() -> AnyObject {
/// return IntegerRef(100)
/// }
///
/// let obj: AnyObject = getObject()
///
/// In the example, `obj` has a static type of `AnyObject` and a dynamic type
/// of `IntegerRef`. You can use optional chaining to call the `@objc` method
/// `getIntegerValue()` on `obj` safely. If you're sure of the dynamic type of
/// `obj`, you can call `getIntegerValue()` directly.
///
/// let possibleValue = obj.getIntegerValue?()
/// print(possibleValue)
/// // Prints "Optional(100)"
///
/// let certainValue = obj.getIntegerValue()
/// print(certainValue)
/// // Prints "100"
///
/// If the dynamic type of `obj` doesn't implement a `getIntegerValue()`
/// method, the system returns a runtime error when you initialize
/// `certainValue`.
///
/// Alternatively, if you need to test whether `obj.getIntegerValue()` exists,
/// use optional binding before calling the method.
///
/// if let f = obj.getIntegerValue {
/// print("The value of 'obj' is \(f())")
/// } else {
/// print("'obj' does not have a 'getIntegerValue()' method")
/// }
/// // Prints "The value of 'obj' is 100"
public typealias AnyObject = Builtin.AnyObject
#else
/// The protocol to which all classes implicitly conform.
public typealias AnyObject = Builtin.AnyObject
#endif
/// The protocol to which all class types implicitly conform.
///
/// You can use the `AnyClass` protocol as the concrete type for an instance of
/// any class. When you do, all known `@objc` class methods and properties are
/// available as implicitly unwrapped optional methods and properties,
/// respectively. For example:
///
/// class IntegerRef {
/// @objc class func getDefaultValue() -> Int {
/// return 42
/// }
/// }
///
/// func getDefaultValue(_ c: AnyClass) -> Int? {
/// return c.getDefaultValue?()
/// }
///
/// The `getDefaultValue(_:)` function uses optional chaining to safely call
/// the implicitly unwrapped class method on `c`. Calling the function with
/// different class types shows how the `getDefaultValue()` class method is
/// only conditionally available.
///
/// print(getDefaultValue(IntegerRef.self))
/// // Prints "Optional(42)"
///
/// print(getDefaultValue(NSString.self))
/// // Prints "nil"
public typealias AnyClass = AnyObject.Type
//===----------------------------------------------------------------------===//
// Standard pattern matching forms
//===----------------------------------------------------------------------===//
/// Returns a Boolean value indicating whether two arguments match by value
/// equality.
///
/// The pattern-matching operator (`~=`) is used internally in `case`
/// statements for pattern matching. When you match against an `Equatable`
/// value in a `case` statement, this operator is called behind the scenes.
///
/// let weekday = 3
/// let lunch: String
/// switch weekday {
/// case 3:
/// lunch = "Taco Tuesday!"
/// default:
/// lunch = "Pizza again."
/// }
/// // lunch == "Taco Tuesday!"
///
/// In this example, the `case 3` expression uses this pattern-matching
/// operator to test whether `weekday` is equal to the value `3`.
///
/// - Note: In most cases, you should use the equal-to operator (`==`) to test
/// whether two instances are equal. The pattern-matching operator is
/// primarily intended to enable `case` statement pattern matching.
///
/// - Parameters:
/// - lhs: A value to compare.
/// - rhs: Another value to compare.
@_transparent
public func ~= <T: Equatable>(a: T, b: T) -> Bool {
return a == b
}
//===----------------------------------------------------------------------===//
// Standard precedence groups
//===----------------------------------------------------------------------===//
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
precedencegroup FunctionArrowPrecedence {
associativity: right
higherThan: AssignmentPrecedence
}
precedencegroup TernaryPrecedence {
associativity: right
higherThan: FunctionArrowPrecedence
}
precedencegroup DefaultPrecedence {
higherThan: TernaryPrecedence
}
precedencegroup LogicalDisjunctionPrecedence {
associativity: left
higherThan: TernaryPrecedence
}
precedencegroup LogicalConjunctionPrecedence {
associativity: left
higherThan: LogicalDisjunctionPrecedence
}
precedencegroup ComparisonPrecedence {
higherThan: LogicalConjunctionPrecedence
}
precedencegroup NilCoalescingPrecedence {
associativity: right
higherThan: ComparisonPrecedence
}
precedencegroup CastingPrecedence {
higherThan: NilCoalescingPrecedence
}
precedencegroup RangeFormationPrecedence {
higherThan: CastingPrecedence
}
precedencegroup AdditionPrecedence {
associativity: left
higherThan: RangeFormationPrecedence
}
precedencegroup MultiplicationPrecedence {
associativity: left
higherThan: AdditionPrecedence
}
precedencegroup BitwiseShiftPrecedence {
higherThan: MultiplicationPrecedence
}
//===----------------------------------------------------------------------===//
// Standard operators
//===----------------------------------------------------------------------===//
// Standard postfix operators.
postfix operator ++
postfix operator --
postfix operator ...: Comparable
// Optional<T> unwrapping operator is built into the compiler as a part of
// postfix expression grammar.
//
// postfix operator !
// Standard prefix operators.
prefix operator ++
prefix operator --
prefix operator !: Bool
prefix operator ~: BinaryInteger
prefix operator +: AdditiveArithmetic
prefix operator -: SignedNumeric
prefix operator ...: Comparable
prefix operator ..<: Comparable
// Standard infix operators.
// "Exponentiative"
infix operator <<: BitwiseShiftPrecedence, BinaryInteger
infix operator &<<: BitwiseShiftPrecedence, FixedWidthInteger
infix operator >>: BitwiseShiftPrecedence, BinaryInteger
infix operator &>>: BitwiseShiftPrecedence, FixedWidthInteger
// "Multiplicative"
infix operator *: MultiplicationPrecedence, Numeric
infix operator &*: MultiplicationPrecedence, FixedWidthInteger
infix operator /: MultiplicationPrecedence, BinaryInteger, FloatingPoint
infix operator %: MultiplicationPrecedence, BinaryInteger
infix operator &: MultiplicationPrecedence, BinaryInteger
// "Additive"
infix operator +: AdditionPrecedence, AdditiveArithmetic, String, Array, Strideable
infix operator &+: AdditionPrecedence, FixedWidthInteger
infix operator -: AdditionPrecedence, AdditiveArithmetic, Strideable
infix operator &-: AdditionPrecedence, FixedWidthInteger
infix operator |: AdditionPrecedence, BinaryInteger
infix operator ^: AdditionPrecedence, BinaryInteger
// FIXME: is this the right precedence level for "..." ?
infix operator ...: RangeFormationPrecedence, Comparable
infix operator ..<: RangeFormationPrecedence, Comparable
// The cast operators 'as' and 'is' are hardcoded as if they had the
// following attributes:
// infix operator as: CastingPrecedence
// "Coalescing"
infix operator ??: NilCoalescingPrecedence
// "Comparative"
infix operator <: ComparisonPrecedence, Comparable
infix operator <=: ComparisonPrecedence, Comparable
infix operator >: ComparisonPrecedence, Comparable
infix operator >=: ComparisonPrecedence, Comparable
infix operator ==: ComparisonPrecedence, Equatable
infix operator !=: ComparisonPrecedence, Equatable
infix operator ===: ComparisonPrecedence
infix operator !==: ComparisonPrecedence
// FIXME: ~= will be built into the compiler.
infix operator ~=: ComparisonPrecedence
// "Conjunctive"
infix operator &&: LogicalConjunctionPrecedence, Bool
// "Disjunctive"
infix operator ||: LogicalDisjunctionPrecedence, Bool
// User-defined ternary operators are not supported. The ? : operator is
// hardcoded as if it had the following attributes:
// operator ternary ? : : TernaryPrecedence
// User-defined assignment operators are not supported. The = operator is
// hardcoded as if it had the following attributes:
// infix operator =: AssignmentPrecedence
// Compound
infix operator *=: AssignmentPrecedence, Numeric
infix operator &*=: AssignmentPrecedence, FixedWidthInteger
infix operator /=: AssignmentPrecedence, BinaryInteger
infix operator %=: AssignmentPrecedence, BinaryInteger
infix operator +=: AssignmentPrecedence, AdditiveArithmetic, String, Array, Strideable
infix operator &+=: AssignmentPrecedence, FixedWidthInteger
infix operator -=: AssignmentPrecedence, AdditiveArithmetic, Strideable
infix operator &-=: AssignmentPrecedence, FixedWidthInteger
infix operator <<=: AssignmentPrecedence, BinaryInteger
infix operator &<<=: AssignmentPrecedence, FixedWidthInteger
infix operator >>=: AssignmentPrecedence, BinaryInteger
infix operator &>>=: AssignmentPrecedence, FixedWidthInteger
infix operator &=: AssignmentPrecedence, BinaryInteger
infix operator ^=: AssignmentPrecedence, BinaryInteger
infix operator |=: AssignmentPrecedence, BinaryInteger
// Workaround for <rdar://problem/14011860> SubTLF: Default
// implementations in protocols. Library authors should ensure
// that this operator never needs to be seen by end-users. See
// test/Prototypes/GenericDispatch.swift for a fully documented
// example of how this operator is used, and how its use can be hidden
// from users.
infix operator ~>
| apache-2.0 | 7b3e72b54f30cc583136671bbf4b4d42 | 35.703854 | 88 | 0.635922 | 5.03198 | false | false | false | false |
vermont42/Conjugar | Conjugar/Quiz.swift | 1 | 18150 | //
// Quiz.swift
// Conjugar
//
// Created by Joshua Adams on 6/17/17.
// Copyright © 2017 Josh Adams. All rights reserved.
//
import Foundation
class Quiz {
private(set) var quizState: QuizState = .notStarted
private(set) var elapsedTime: Int = 0
private(set) var score: Int = 0
private(set) var currentQuestionIndex = 0
private(set) var lastRegion: Region = .spain
private(set) var lastDifficulty: Difficulty = .moderate
private(set) var proposedAnswers: [String] = []
private(set) var correctAnswers: [String] = []
private(set) var questions: [(String, Tense, PersonNumber)] = []
private var regularArVerbs = VerbFamilies.regularArVerbs
private var regularArVerbsIndex = 0
private var regularIrVerbs = VerbFamilies.regularIrVerbs
private var regularIrVerbsIndex = 0
private var regularErVerbs = VerbFamilies.regularErVerbs
private var regularErVerbsIndex = 0
private var allRegularVerbs = VerbFamilies.allRegularVerbs
private var allRegularVerbsIndex = 0
private var irregularPresenteDeIndicativoVerbs = VerbFamilies.irregularPresenteDeIndicativoVerbs
private var irregularPresenteDeIndicativoVerbsIndex = 0
private var irregularPreteritoVerbs = VerbFamilies.irregularPreteritoVerbs
private var irregularPreteritoVerbsIndex = 0
private var irregularRaizFuturaVerbs = VerbFamilies.irregularRaizFuturaVerbs
private var irregularRaizFuturaVerbsIndex = 0
private var irregularParticipioVerbs = VerbFamilies.irregularParticipioVerbs
private var irregularParticipioVerbsIndex = 0
private var irregularImperfectoVerbs = VerbFamilies.irregularImperfectivoVerbs
private var irregularImperfectoVerbsIndex = 0
private var irregularPresenteDeSubjuntivoVerbs = VerbFamilies.irregularPresenteDeSubjuntivoVerbs
private var irregularPresenteDeSubjuntivoVerbsIndex = 0
private var irregularGerundioVerbs = VerbFamilies.irregularGerundioVerbs
private var irregularGerundioVerbsIndex = 0
private var irregularTuImperativoVerbs = VerbFamilies.irregularTuImperativoVerbs
private var irregularTuImperativoVerbsIndex = 0
private var irregularVosImperativoVerbs = VerbFamilies.irregularVosImperativoVerbs
private var irregularVosImperativoVerbsIndex = 0
private var timer: Timer?
private var settings: Settings?
private var gameCenter: GameCenterable?
private var personNumbersWithTu: [PersonNumber] = [.firstSingular, .secondSingularTú, .thirdSingular, .firstPlural, .secondPlural, .thirdPlural]
private var personNumbersWithVos: [PersonNumber] = [.firstSingular, .secondSingularVos, .thirdSingular, .firstPlural, .secondPlural, .thirdPlural]
private var personNumbersIndex = 0
private var shouldShuffle = true
weak var delegate: QuizDelegate?
var questionCount: Int {
return questions.count
}
var verb: String {
if questions.count > 0 {
return questions[currentQuestionIndex].0
} else {
return ""
}
}
var tense: Tense {
if questions.count > 0 {
return questions[currentQuestionIndex].1
} else {
return .infinitivo
}
}
var currentPersonNumber: PersonNumber {
if questions.count > 0 {
return questions[currentQuestionIndex].2
} else {
return .none
}
}
init(settings: Settings, gameCenter: GameCenterable, shouldShuffle: Bool = true) {
self.settings = settings
self.gameCenter = gameCenter
self.shouldShuffle = shouldShuffle
}
func start() {
guard let settings = settings else {
fatalError("settings was nil.")
}
lastRegion = settings.region
lastDifficulty = settings.difficulty
questions.removeAll()
proposedAnswers.removeAll()
correctAnswers.removeAll()
if shouldShuffle {
regularArVerbs.shuffle()
regularIrVerbs.shuffle()
regularErVerbs.shuffle()
allRegularVerbs.shuffle()
irregularPresenteDeIndicativoVerbs.shuffle()
irregularPreteritoVerbs.shuffle()
irregularRaizFuturaVerbs.shuffle()
irregularParticipioVerbs.shuffle()
irregularImperfectoVerbs.shuffle()
irregularPresenteDeSubjuntivoVerbs.shuffle()
irregularGerundioVerbs.shuffle()
irregularTuImperativoVerbs.shuffle()
irregularVosImperativoVerbs.shuffle()
}
regularArVerbsIndex = 0
regularIrVerbsIndex = 0
regularErVerbsIndex = 0
allRegularVerbsIndex = 0
irregularPresenteDeIndicativoVerbsIndex = 0
irregularRaizFuturaVerbsIndex = 0
irregularParticipioVerbsIndex = 0
irregularImperfectoVerbsIndex = 0
irregularPresenteDeSubjuntivoVerbsIndex = 0
irregularGerundioVerbsIndex = 0
irregularTuImperativoVerbsIndex = 0
irregularVosImperativoVerbsIndex = 0
switch lastDifficulty {
case .easy:
// questions.append((allRegularVerb, .presenteDeIndicativo, personNumber())) // useful for testing
[regularArVerb, regularArVerb, regularArVerb, regularIrVerb, regularIrVerb, regularIrVerb, regularErVerb, regularErVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...8 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...7 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[regularArVerb, regularArVerb, regularArVerb, regularIrVerb, regularIrVerb, regularErVerb, regularErVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...7 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
for _ in 0...8 {
questions.append((allRegularVerb, .pretérito, personNumber()))
}
case .moderate:
[regularArVerb, regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...3 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularRaizFuturaVerb, .condicional, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .condicional, personNumber()))
}
for _ in 0...2 {
questions.append((irregularParticipioVerb, .perfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .perfectoDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularImperfectoVerb, .imperfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperfectoDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .pretérito, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPresenteDeSubjuntivoVerb, .presenteDeSubjuntivo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .presenteDeSubjuntivo, personNumber()))
}
for _ in 0...1 {
questions.append((irregularGerundioVerb, .gerundio, .none))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .gerundio, .none))
}
for _ in 0...1 {
if settings.secondSingularQuiz == .tu {
questions.append((irregularTuImperativoVerb, .imperativoPositivo, .secondSingularTú))
} else {
questions.append((irregularVosImperativoVerb, .imperativoPositivo, .secondSingularVos))
}
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperativoPositivo, personNumber(skipYo: true, skipTu: true)))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperativoNegativo, personNumber(skipYo: true, skipTu: true)))
}
case .difficult:
for _ in 0...1 {
questions.append((irregularGerundioVerb, .gerundio, .none))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .gerundio, .none))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPresenteDeIndicativoVerb, .presenteDeIndicativo, personNumber()))
}
for _ in 0...2 {
questions.append((irregularPreteritoVerb, .pretérito, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .pretérito, personNumber()))
}
for _ in 0...1 {
questions.append((irregularImperfectoVerb, .imperfectoDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .imperfectoDeIndicativo, personNumber()))
}
for _ in 0...1 {
questions.append((irregularRaizFuturaVerb, .futuroDeIndicativo, personNumber()))
}
[allRegularVerb, allRegularVerb].forEach {
questions.append(($0, .futuroDeIndicativo, personNumber()))
}
for _ in 0...1 {
questions.append((allRegularVerb, .condicional, personNumber()))
}
questions.append((irregularRaizFuturaVerb, .condicional, personNumber()))
for _ in 0...2 {
questions.append((irregularPresenteDeSubjuntivoVerb, .presenteDeSubjuntivo, personNumber()))
}
[regularArVerb, regularIrVerb, regularErVerb].forEach {
questions.append(($0, .presenteDeSubjuntivo, personNumber()))
}
questions.append((irregularPreteritoVerb, .imperfectoDeSubjuntivo1, personNumber()))
questions.append((allRegularVerb, .imperfectoDeSubjuntivo2, personNumber()))
questions.append((irregularPreteritoVerb, .futuroDeSubjuntivo, personNumber()))
questions.append((allRegularVerb, .futuroDeSubjuntivo, personNumber()))
if settings.secondSingularQuiz == .tu {
questions.append((irregularTuImperativoVerb, .imperativoPositivo, .secondSingularTú))
} else {
questions.append((irregularVosImperativoVerb, .imperativoPositivo, .secondSingularVos))
}
questions.append((allRegularVerb, .imperativoPositivo, personNumber(skipYo: true, skipTu: true)))
questions.append((allRegularVerb, .imperativoNegativo, personNumber(skipYo: true, skipTu: true)))
[.perfectoDeIndicativo, .pretéritoAnterior, .pluscuamperfectoDeIndicativo, .futuroPerfecto, .condicionalCompuesto, .perfectoDeSubjuntivo, .pluscuamperfectoDeSubjuntivo1, .pluscuamperfectoDeSubjuntivo2, .futuroPerfectoDeSubjuntivo].forEach {
questions.append((regularOrIrregularParticipioVerb, $0, personNumber()))
}
}
if shouldShuffle {
questions = questions.shuffled().shuffled()
}
score = 0
currentQuestionIndex = 0
elapsedTime = 0
quizState = .inProgress
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(Quiz.eachSecond), userInfo: nil, repeats: true)
delegate?.questionDidChange(verb: questions[0].0, tense: questions[0].1, personNumber: questions[0].2)
delegate?.scoreDidChange(newScore: 0)
delegate?.timeDidChange(newTime: 0)
delegate?.progressDidChange(current: 0, total: questions.count)
}
private var regularOrIrregularParticipioVerb: String {
let diceRoll: Int
if shouldShuffle {
diceRoll = Int.random(in: 0..<2)
} else {
diceRoll = questions.count % 2
}
if diceRoll == 0 {
return allRegularVerb
} else /* diceRoll == 1 */ {
return irregularParticipioVerb
}
}
func process(proposedAnswer: String) -> (ConjugationResult, String?) {
guard let gameCenter = gameCenter else {
fatalError("gameCenter was nil.")
}
let correctAnswerResult = Conjugator.shared.conjugate(infinitive: verb, tense: tense, personNumber: currentPersonNumber)
switch correctAnswerResult {
case let .success(correctAnswer):
let result = ConjugationResult.compare(lhs: proposedAnswer, rhs: correctAnswer)
proposedAnswers.append(proposedAnswer)
correctAnswers.append(correctAnswer)
if result != .noMatch {
score += result.rawValue
delegate?.scoreDidChange(newScore: score)
}
if currentQuestionIndex < questions.count - 1 {
currentQuestionIndex += 1
delegate?.progressDidChange(current: currentQuestionIndex, total: questions.count)
delegate?.questionDidChange(verb: questions[currentQuestionIndex].0, tense: questions[currentQuestionIndex].1, personNumber: questions[currentQuestionIndex].2)
} else {
score = Int(Double(score) * lastRegion.scoreModifier * lastDifficulty.scoreModifier)
timer?.invalidate()
quizState = .finished
delegate?.quizDidFinish()
gameCenter.reportScore(score)
}
if result == .totalMatch {
return (result, nil)
} else {
return (result, correctAnswer)
}
default:
fatalError()
}
}
func quit() {
timer?.invalidate()
quizState = .finished
}
@objc func eachSecond() {
elapsedTime += 1
delegate?.timeDidChange(newTime: elapsedTime)
}
private func personNumber(skipYo: Bool = false, skipTu: Bool = false) -> PersonNumber {
guard let settings = settings else {
fatalError("settings was nil.")
}
let personNumbers: [PersonNumber]
switch settings.secondSingularQuiz {
case .tu:
personNumbers = personNumbersWithTu
case .vos:
personNumbers = personNumbersWithVos
}
personNumbersIndex += 1
if personNumbersIndex == personNumbers.count {
personNumbersIndex = 0
} else if personNumbers[personNumbersIndex].pronoun == PersonNumber.secondPlural.pronoun && lastRegion == .latinAmerica {
personNumbersIndex += 1
}
if (personNumbers[personNumbersIndex].pronoun == PersonNumber.firstSingular.pronoun && skipYo) || (personNumbers[personNumbersIndex].pronoun == PersonNumber.secondSingularTú.pronoun && skipTu) {
return personNumber(skipYo: skipYo, skipTu: skipTu)
} else {
return personNumbers[personNumbersIndex]
}
}
private var regularArVerb: String {
regularArVerbsIndex += 1
if regularArVerbsIndex == regularArVerbs.count {
regularArVerbsIndex = 0
}
return regularArVerbs[regularArVerbsIndex]
}
private var regularIrVerb: String {
regularIrVerbsIndex += 1
if regularIrVerbsIndex == regularIrVerbs.count {
regularIrVerbsIndex = 0
}
return regularIrVerbs[regularIrVerbsIndex]
}
private var regularErVerb: String {
regularErVerbsIndex += 1
if regularErVerbsIndex == regularErVerbs.count {
regularErVerbsIndex = 0
}
return regularErVerbs[regularErVerbsIndex]
}
private var allRegularVerb: String {
allRegularVerbsIndex += 1
if allRegularVerbsIndex == allRegularVerbs.count {
allRegularVerbsIndex = 0
}
return allRegularVerbs[allRegularVerbsIndex]
}
private var irregularPresenteDeIndicativoVerb: String {
irregularPresenteDeIndicativoVerbsIndex += 1
if irregularPresenteDeIndicativoVerbsIndex == irregularPresenteDeIndicativoVerbs.count {
irregularPresenteDeIndicativoVerbsIndex = 0
}
return irregularPresenteDeIndicativoVerbs[irregularPresenteDeIndicativoVerbsIndex]
}
private var irregularRaizFuturaVerb: String {
irregularRaizFuturaVerbsIndex += 1
if irregularRaizFuturaVerbsIndex == irregularRaizFuturaVerbs.count {
irregularRaizFuturaVerbsIndex = 0
}
return irregularRaizFuturaVerbs[irregularRaizFuturaVerbsIndex]
}
private var irregularParticipioVerb: String {
irregularParticipioVerbsIndex += 1
if irregularParticipioVerbsIndex == irregularParticipioVerbs.count {
irregularParticipioVerbsIndex = 0
}
return irregularParticipioVerbs[irregularParticipioVerbsIndex]
}
private var irregularImperfectoVerb: String {
irregularImperfectoVerbsIndex += 1
if irregularImperfectoVerbsIndex == irregularImperfectoVerbs.count {
irregularImperfectoVerbsIndex = 0
}
return irregularImperfectoVerbs[irregularImperfectoVerbsIndex]
}
private var irregularPreteritoVerb: String {
irregularPreteritoVerbsIndex += 1
if irregularPreteritoVerbsIndex == irregularPreteritoVerbs.count {
irregularPreteritoVerbsIndex = 0
}
return irregularPreteritoVerbs[irregularPreteritoVerbsIndex]
}
private var irregularPresenteDeSubjuntivoVerb: String {
irregularPresenteDeSubjuntivoVerbsIndex += 1
if irregularPresenteDeSubjuntivoVerbsIndex == irregularPresenteDeSubjuntivoVerbs.count {
irregularPresenteDeSubjuntivoVerbsIndex = 0
}
return irregularPresenteDeSubjuntivoVerbs[irregularPresenteDeSubjuntivoVerbsIndex]
}
private var irregularGerundioVerb: String {
irregularGerundioVerbsIndex += 1
if irregularGerundioVerbsIndex == irregularGerundioVerbs.count {
irregularGerundioVerbsIndex = 0
}
return irregularGerundioVerbs[irregularGerundioVerbsIndex]
}
private var irregularTuImperativoVerb: String {
irregularTuImperativoVerbsIndex += 1
if irregularTuImperativoVerbsIndex == irregularTuImperativoVerbs.count {
irregularTuImperativoVerbsIndex = 0
}
return irregularTuImperativoVerbs[irregularTuImperativoVerbsIndex]
}
private var irregularVosImperativoVerb: String {
irregularVosImperativoVerbsIndex += 1
if irregularVosImperativoVerbsIndex == irregularVosImperativoVerbs.count {
irregularVosImperativoVerbsIndex = 0
}
return irregularVosImperativoVerbs[irregularVosImperativoVerbsIndex]
}
}
| agpl-3.0 | 7765602a8199f541d5b380137510b76f | 37.673774 | 246 | 0.716782 | 5.340989 | false | false | false | false |
firebase/quickstart-ios | performance/PerformanceExampleSwift/ViewController.swift | 1 | 3546 | //
// Copyright (c) 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import FirebasePerformance
import AVKit
import AVFoundation
@objc(ViewController)
class ViewController: UIViewController {
@IBOutlet var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
// make a file name to write the data to using the documents directory
let fileName = "\(documentsDirectory)/perfsamplelog.txt"
// Start tracing
let trace = Performance.startTrace(name: "request_trace")
let contents: String
do {
contents = try String(contentsOfFile: fileName, encoding: .utf8)
} catch {
print("Log file doesn't exist yet")
contents = ""
}
let fileLength = contents.lengthOfBytes(using: .utf8)
trace?.incrementMetric("log_file_size", by: Int64(fileLength))
let target =
"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png"
guard let targetUrl = URL(string: target) else { return }
guard let metric = HTTPMetric(url: targetUrl, httpMethod: .get) else { return }
metric.start()
var request = URLRequest(url: targetUrl)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
if let httpResponse = response as? HTTPURLResponse {
metric.responseCode = httpResponse.statusCode
}
metric.stop()
if let error = error {
print("error=\(error)")
return
}
DispatchQueue.main.async {
self.imageView.image = UIImage(data: data!)
}
trace?.stop()
if let absoluteString = response?.url?.absoluteString {
let contentToWrite = contents + "\n" + absoluteString
do {
try contentToWrite.write(toFile: fileName, atomically: false, encoding: .utf8)
} catch {
print("Can't write to log file")
}
}
}
task.resume()
trace?.incrementMetric("request_sent", by: 1)
if #available(iOS 10, *) {
let asset =
AVURLAsset(
url: URL(
string: "https://upload.wikimedia.org/wikipedia/commons/thumb/3/36/Two_red_dice_01.svg/220px-Two_red_dice_01.svg.png"
)!
)
let downloadSession =
AVAssetDownloadURLSession(
configuration: URLSessionConfiguration.background(withIdentifier: "avasset"),
assetDownloadDelegate: nil,
delegateQueue: OperationQueue.main
)
let task = downloadSession.makeAssetDownloadTask(asset: asset,
assetTitle: "something",
assetArtworkData: nil,
options: nil)!
task.resume()
trace?.incrementMetric("av_request_sent", by: 1)
}
}
}
| apache-2.0 | 532257ec65fac3e2c96303d048415a6d | 30.380531 | 129 | 0.633954 | 4.494297 | false | false | false | false |
mrdepth/EVEOnlineAPI | EVEAPI/EVEAPI/evecodegen/EVEGlobal.swift | 1 | 6089 | import Foundation
import Alamofire
public extension EVE {
class func loadClassess() {
_ = Corp.ContractItems.Item.classForCoder()
_ = Char.CharacterSheet.JumpClone.classForCoder()
_ = Char.UpcomingCalendarEvents.Event.classForCoder()
_ = Char.Bookmarks.Folder.classForCoder()
_ = Account.AccountStatus.classForCoder()
_ = Char.Research.classForCoder()
_ = Corp.KillMails.classForCoder()
_ = Char.CharacterSheet.Attributes.classForCoder()
_ = Char.AccountBalance.classForCoder()
_ = Char.WalletJournal.classForCoder()
_ = Char.AccountBalance.Account.classForCoder()
_ = Corp.ContactList.Contact.classForCoder()
_ = Char.ContactList.classForCoder()
_ = Char.MarketOrders.classForCoder()
_ = Corp.AssetList.classForCoder()
_ = Char.PlanetaryLinks.Link.classForCoder()
_ = Char.Contracts.Contract.classForCoder()
_ = Char.MailingLists.MailingList.classForCoder()
_ = Corp.Standings.classForCoder()
_ = Corp.Bookmarks.Folder.classForCoder()
_ = Api.CallList.Call.classForCoder()
_ = Char.CharacterSheet.Role.classForCoder()
_ = Char.MailingLists.classForCoder()
_ = Char.KillMails.Kill.classForCoder()
_ = Char.WalletTransactions.classForCoder()
_ = Char.WalletJournal.Transaction.classForCoder()
_ = Char.PlanetaryPins.Pin.classForCoder()
_ = Char.ContactNotifications.Notification.classForCoder()
_ = Corp.IndustryJobs.classForCoder()
_ = Char.MailBodies.Message.classForCoder()
_ = Corp.Medals.classForCoder()
_ = Corp.AccountBalance.Account.classForCoder()
_ = Char.ContractBids.classForCoder()
_ = Eve.RefTypes.classForCoder()
_ = Corp.WalletJournal.classForCoder()
_ = Char.CharacterSheet.Skill.classForCoder()
_ = Char.Clones.classForCoder()
_ = Char.CalendarEventAttendees.classForCoder()
_ = Char.Clones.JumpCloneImplant.classForCoder()
_ = Corp.ContractItems.classForCoder()
_ = Corp.AccountBalance.classForCoder()
_ = Char.MailBodies.classForCoder()
_ = Char.ChatChannels.Channel.classForCoder()
_ = Char.AssetList.Asset.classForCoder()
_ = Char.KillMails.Kill.Attacker.classForCoder()
_ = Char.NotificationTexts.Notification.classForCoder()
_ = Eve.RefTypes.RefType.classForCoder()
_ = Corp.Contracts.Contract.classForCoder()
_ = Corp.Blueprints.Blueprint.classForCoder()
_ = Char.FacWarStats.classForCoder()
_ = Char.ContactList.Label.classForCoder()
_ = Char.IndustryJobs.Job.classForCoder()
_ = Corp.Locations.Location.classForCoder()
_ = Corp.KillMails.Kill.Item.classForCoder()
_ = Char.PlanetaryRoutes.Route.classForCoder()
_ = Char.Messages.Message.classForCoder()
_ = Account.AccountStatus.MultiCharacterTraining.classForCoder()
_ = Char.ContractBids.Bid.classForCoder()
_ = Char.CharacterSheet.Certificate.classForCoder()
_ = Corp.MarketOrders.Order.classForCoder()
_ = Corp.Bookmarks.classForCoder()
_ = Char.Notifications.classForCoder()
_ = Char.ContactNotifications.classForCoder()
_ = Api.CallList.CallGroup.classForCoder()
_ = Char.Blueprints.classForCoder()
_ = Corp.Bookmarks.Folder.Bookmark.classForCoder()
_ = Char.ContractItems.Item.classForCoder()
_ = Char.Contracts.classForCoder()
_ = Char.ChatChannels.Channel.Accessor.classForCoder()
_ = Char.Clones.Attributes.classForCoder()
_ = Account.APIKeyInfo.APIKey.classForCoder()
_ = Corp.ContactList.classForCoder()
_ = Char.MarketOrders.Order.classForCoder()
_ = Char.Locations.classForCoder()
_ = Corp.WalletTransactions.classForCoder()
_ = Corp.WalletTransactions.Transaction.classForCoder()
_ = Char.Standings.Standing.classForCoder()
_ = Char.Messages.classForCoder()
_ = Corp.ContractBids.classForCoder()
_ = Account.Characters.Character.classForCoder()
_ = Char.CharacterSheet.classForCoder()
_ = Char.CalendarEventAttendees.Attendee.classForCoder()
_ = Char.PlanetaryColonies.Colony.classForCoder()
_ = Char.Standings.classForCoder()
_ = Char.Notifications.Notification.classForCoder()
_ = Corp.Medals.Medal.classForCoder()
_ = Char.Medals.Medal.classForCoder()
_ = Char.SkillQueue.Skill.classForCoder()
_ = Corp.Locations.classForCoder()
_ = Corp.KillMails.Kill.Attacker.classForCoder()
_ = Account.APIKeyInfo.classForCoder()
_ = Char.PlanetaryRoutes.classForCoder()
_ = Char.Locations.Location.classForCoder()
_ = Char.PlanetaryPins.classForCoder()
_ = Char.KillMails.Kill.Item.classForCoder()
_ = Char.Skills.Skill.classForCoder()
_ = Corp.KillMails.Kill.Victim.classForCoder()
_ = Account.APIKeyInfo.APIKey.Character.classForCoder()
_ = Char.PlanetaryLinks.classForCoder()
_ = Char.KillMails.classForCoder()
_ = Api.CallList.classForCoder()
_ = Char.WalletTransactions.Transaction.classForCoder()
_ = Char.SkillQueue.classForCoder()
_ = Corp.Blueprints.classForCoder()
_ = Char.CharacterSheet.Implant.classForCoder()
_ = Char.CharacterSheet.JumpCloneImplant.classForCoder()
_ = Char.ContactList.Contact.classForCoder()
_ = Corp.ContractBids.Bid.classForCoder()
_ = Char.Skills.classForCoder()
_ = Char.NotificationTexts.classForCoder()
_ = Corp.Standings.Standing.classForCoder()
_ = Corp.IndustryJobs.Job.classForCoder()
_ = Corp.FacWarStats.classForCoder()
_ = Corp.MarketOrders.classForCoder()
_ = Char.Clones.Implant.classForCoder()
_ = Char.Bookmarks.classForCoder()
_ = Char.UpcomingCalendarEvents.classForCoder()
_ = Char.IndustryJobs.classForCoder()
_ = Corp.Contracts.classForCoder()
_ = Char.PlanetaryColonies.classForCoder()
_ = Char.Clones.JumpClone.classForCoder()
_ = Account.Characters.classForCoder()
_ = Corp.AssetList.Asset.classForCoder()
_ = Char.Research.Research.classForCoder()
_ = Char.ContractItems.classForCoder()
_ = Char.Bookmarks.Folder.Bookmark.classForCoder()
_ = Corp.WalletJournal.Transaction.classForCoder()
_ = Char.Medals.classForCoder()
_ = Char.ChatChannels.classForCoder()
_ = Char.Blueprints.Blueprint.classForCoder()
_ = Char.AssetList.classForCoder()
_ = Corp.ContactList.Label.classForCoder()
_ = Corp.KillMails.Kill.classForCoder()
_ = Char.KillMails.Kill.Victim.classForCoder()
}
}
| mit | d8ac99513a7ddead1573dd981cd2292f | 41.58042 | 66 | 0.739366 | 3.719609 | false | false | false | false |
kasketis/netfox | netfox/iOS/NFXHelper_iOS.swift | 1 | 7942 | //
// NFXHelper.swift
// netfox
//
// Copyright © 2016 netfox. All rights reserved.
//
#if os(iOS)
import UIKit
extension UIWindow {
override open func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
if NFX.sharedInstance().getSelectedGesture() == .shake {
if (event!.type == .motion && event!.subtype == .motionShake) {
NFX.sharedInstance().motionDetected()
}
} else {
super.motionEnded(motion, with: event)
}
}
}
public extension UIDevice {
class func getNFXDeviceType() -> String {
var systemInfo = utsname()
uname(&systemInfo)
let machine = systemInfo.machine
let mirror = Mirror(reflecting: machine)
var identifier = ""
for child in mirror.children {
if let value = child.value as? Int8 , value != 0 {
identifier.append(String(UnicodeScalar(UInt8(value))))
}
}
return parseDeviceType(identifier)
}
class func parseDeviceType(_ identifier: String) -> String {
switch identifier {
case "i386": return "iPhone Simulator"
case "x86_64": return "iPhone Simulator"
case "iPhone1,1": return "iPhone"
case "iPhone1,2": return "iPhone 3G"
case "iPhone2,1": return "iPhone 3GS"
case "iPhone3,1": return "iPhone 4"
case "iPhone3,2": return "iPhone 4 GSM Rev A"
case "iPhone3,3": return "iPhone 4 CDMA"
case "iPhone4,1": return "iPhone 4S"
case "iPhone5,1": return "iPhone 5 (GSM)"
case "iPhone5,2": return "iPhone 5 (GSM+CDMA)"
case "iPhone5,3": return "iPhone 5C (GSM)"
case "iPhone5,4": return "iPhone 5C (Global)"
case "iPhone6,1": return "iPhone 5S (GSM)"
case "iPhone6,2": return "iPhone 5S (Global)"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone7,2": return "iPhone 6"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE (GSM)"
case "iPhone9,1": return "iPhone 7"
case "iPhone9,2": return "iPhone 7 Plus"
case "iPhone9,3": return "iPhone 7"
case "iPhone9,4": return "iPhone 7 Plus"
case "iPhone10,1": return "iPhone 8"
case "iPhone10,2": return "iPhone 8 Plus"
case "iPhone10,3": return "iPhone X Global"
case "iPhone10,4": return "iPhone 8"
case "iPhone10,5": return "iPhone 8 Plus"
case "iPhone10,6": return "iPhone X GSM"
case "iPhone11,2": return "iPhone XS"
case "iPhone11,4": return "iPhone XS Max"
case "iPhone11,6": return "iPhone XS Max Global"
case "iPhone11,8": return "iPhone XR"
case "iPhone12,1": return "iPhone 11"
case "iPhone12,3": return "iPhone 11 Pro"
case "iPhone12,5": return "iPhone 11 Pro Max"
case "iPhone12,8": return "iPhone SE 2nd Gen"
case "iPod1,1": return "1st Gen iPod"
case "iPod2,1": return "2nd Gen iPod"
case "iPod3,1": return "3rd Gen iPod"
case "iPod4,1": return "4th Gen iPod"
case "iPod5,1": return "5th Gen iPod"
case "iPod7,1": return "6th Gen iPod"
case "iPod9,1": return "7th Gen iPod"
case "iPad1,1": return "iPad"
case "iPad1,2": return "iPad 3G"
case "iPad2,1": return "2nd Gen iPad"
case "iPad2,2": return "2nd Gen iPad GSM"
case "iPad2,3": return "2nd Gen iPad CDMA"
case "iPad2,4": return "2nd Gen iPad New Revision"
case "iPad3,1": return "3rd Gen iPad"
case "iPad3,2": return "3rd Gen iPad CDMA"
case "iPad3,3": return "3rd Gen iPad GSM"
case "iPad2,5": return "iPad mini"
case "iPad2,6": return "iPad mini GSM+LTE"
case "iPad2,7": return "iPad mini CDMA+LTE"
case "iPad3,4": return "4th Gen iPad"
case "iPad3,5": return "4th Gen iPad GSM+LTE"
case "iPad3,6": return "4th Gen iPad CDMA+LTE"
case "iPad4,1": return "iPad Air (WiFi)"
case "iPad4,2": return "iPad Air (GSM+CDMA)"
case "iPad4,3": return "1st Gen iPad Air (China)"
case "iPad4,4": return "iPad mini Retina (WiFi)"
case "iPad4,5": return "iPad mini Retina (GSM+CDMA)"
case "iPad4,6": return "iPad mini Retina (China)"
case "iPad4,7": return "iPad mini 3 (WiFi)"
case "iPad4,8": return "iPad mini 3 (GSM+CDMA)"
case "iPad4,9": return "iPad Mini 3 (China)"
case "iPad5,1": return "iPad mini 4 (WiFi)"
case "iPad5,2": return "4th Gen iPad mini (WiFi+Cellular)"
case "iPad5,3": return "iPad Air 2 (WiFi)"
case "iPad5,4": return "iPad Air 2 (Cellular)"
case "iPad6,3": return "iPad Pro (9.7 inch, WiFi)"
case "iPad6,4": return "iPad Pro (9.7 inch, WiFi+LTE)"
case "iPad6,7": return "iPad Pro (12.9 inch, WiFi)"
case "iPad6,8": return "iPad Pro (12.9 inch, WiFi+LTE)"
case "iPad6,11": return "iPad (2017)"
case "iPad6,12": return "iPad (2017)"
case "iPad7,1": return "iPad Pro 2nd Gen (WiFi)"
case "iPad7,2": return "iPad Pro 2nd Gen (WiFi+Cellular)"
case "iPad7,3": return "iPad Pro 10.5-inch"
case "iPad7,4": return "iPad Pro 10.5-inch"
case "iPad7,5": return "iPad 6th Gen (WiFi)"
case "iPad7,6": return "iPad 6th Gen (WiFi+Cellular)"
case "iPad7,11": return "iPad 7th Gen 10.2-inch (WiFi)"
case "iPad7,12": return "iPad 7th Gen 10.2-inch (WiFi+Cellular)"
case "iPad8,1": return "iPad Pro 11 inch (WiFi)"
case "iPad8,2": return "iPad Pro 11 inch (1TB, WiFi)"
case "iPad8,3": return "iPad Pro 11 inch (WiFi+Cellular)"
case "iPad8,4": return "iPad Pro 11 inch (1TB, WiFi+Cellular)"
case "iPad8,5": return "iPad Pro 12.9 inch 3rd Gen (WiFi)"
case "iPad8,6": return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi)"
case "iPad8,7": return "iPad Pro 12.9 inch 3rd Gen (WiFi+Cellular)"
case "iPad8,8": return "iPad Pro 12.9 inch 3rd Gen (1TB, WiFi+Cellular)"
case "iPad8,9": return "iPad Pro 11 inch 2nd Gen (WiFi)"
case "iPad8,10": return "iPad Pro 11 inch 2nd Gen (WiFi+Cellular)"
case "iPad8,11": return "iPad Pro 12.9 inch 4th Gen (WiFi)"
case "iPad8,12": return "iPad Pro 12.9 inch 4th Gen (WiFi+Cellular)"
case "iPad11,1": return "iPad mini 5th Gen (WiFi)"
case "iPad11,2": return "iPad mini 5th Gen"
case "iPad11,3": return "iPad Air 3rd Gen (WiFi)"
case "iPad11,4": return "iPad Air 3rd Gen"
default: return "Not Available"
}
}
}
#endif
protocol DataCleaner {
func clearData(sourceView: UIView, originingIn sourceRect: CGRect?, then: @escaping () -> ())
}
extension DataCleaner where Self: UIViewController {
func clearData(sourceView: UIView, originingIn sourceRect: CGRect?, then: @escaping () -> ()) {
let actionSheetController: UIAlertController = UIAlertController(title: "Clear data?", message: "", preferredStyle: .actionSheet)
actionSheetController.popoverPresentationController?.sourceView = sourceView
if let sourceRect = sourceRect {
actionSheetController.popoverPresentationController?.sourceRect = sourceRect
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { _ in }
actionSheetController.addAction(cancelAction)
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
NFX.sharedInstance().clearOldData()
then()
}
actionSheetController.addAction(yesAction)
let noAction = UIAlertAction(title: "No", style: .default) { _ in }
actionSheetController.addAction(noAction)
present(actionSheetController, animated: true, completion: nil)
}
}
| mit | daecc379d0b9c5cd0c54c1b083b2a8e3 | 41.693548 | 137 | 0.59791 | 3.642661 | false | false | false | false |
shial4/VaporDM | Sources/VaporDM/Controllers/DMController.swift | 1 | 13464 | //
// DMController.swift
// VaporDM
//
// Created by Shial on 19/04/2017.
//
//
import Foundation
import HTTP
import Vapor
import Fluent
public final class DMController<T:DMUser> {
/// Group under which endpoints are grouped
open var group: String = "chat"
/// VaporDM configuraton object
var configuration: DMConfiguration
/// VaporDM connection set
var connections: Set<DMConnection> = []
/// An Droplet instance under endpoint are handled
fileprivate weak var drop: Droplet?
/// Function which expose Models instance for Vapor Fluent to exten your database.
///
/// - Returns: Preparation reuired for VaporDM to work on database
fileprivate func models() -> [Preparation.Type] {
return [Pivot<T, DMRoom>.self,
DMRoom.self,
DMDirective.self,
]
}
/// DMController object which do provide endpoint to work with VaporDM
///
/// - Parameters:
/// - droplet: Droplet object required to correctly set up VaporDM
/// - configuration: DMConfiguration object required to configure VaporDM. Default value is DMDefaultConfiguration() object
public init(drop: Droplet, configuration: DMConfiguration) {
self.drop = drop
self.configuration = configuration
drop.preparations += models()
let chat = drop.grouped(group)
chat.socket("service", T.self, handler: chatService)
chat.post("room", handler: createRoom)
chat.post("room", String.self, handler: addUsersToRoom)
chat.post("room", String.self, "remove", handler: removeUsersFromRoom)
chat.get("room", String.self, handler: getRoom)
chat.get("room", String.self, "participant", handler: getRoomParticipants)
chat.get("participant", T.self, "rooms", handler: getParticipantRooms)
chat.get("history", String.self, handler: history)
}
/// Create chat room.
///```
/// POST: /chat/room
/// "Content-Type" = "application/json"
///```
/// In Body DMRoom object with minimum uniqueid and name parameters.
///```
/// {
/// "uniqueid":"",
/// "name":"RoomName"
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: CHat room
/// - Throws: If room is not found or query do fail
public func createRoom(request: Request) throws -> ResponseRepresentable {
var room = try request.room()
try room.save()
if let users: [String] = try request.json?.extract("participants") {
for userId in users {
do {
if let user = try T.find(userId) {
_ = try Pivot<T, DMRoom>.getOrCreate(user, room)
}
} catch {
T.directMessage(log: DMLog(message: "Unable to find user with id: \(userId)\nError message: \(error)", type: .warning))
}
}
}
return try room.makeJSON()
}
/// Get chat room.
///
///```
/// GET: /chat/room/${room_uuid}
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Chat room
/// - Throws: If room is not found or query do fail
public func getRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
return try room.makeJSON()
}
/// Add users to room.
///
///```
/// POST: /chat/room/${room_uuid}
/// "Content-Type" = "application/json"
///```
/// In Body Your Fluent Model or array of models which is associated with VaporDM.
///```
/// {
/// [
/// ${<User: Model, DMParticipant>},
/// ${<User: Model, DMParticipant>}
/// ]
/// }
///```
/// Or
///```
/// {
/// ${<User: Model, DMParticipant>}
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: CHat room
/// - Throws: If room is not found or query do fail
public func addUsersToRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard var room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
room.time.updated = Date()
try room.save()
for user: T in try request.users() {
_ = try Pivot<T, DMRoom>.getOrCreate(user, room)
}
return try room.makeJSON()
}
/// Remove users from room.
///
///```
/// POST: /chat/room/${room_uuid}/remove
/// "Content-Type" = "application/json"
///```
/// In Body Your Fluent Model or array of models which is associated with VaporDM.
///```
/// {
/// [
/// ${<User: Model, DMParticipant>},
/// ${<User: Model, DMParticipant>}
/// ]
/// }
///```
/// Or
///```
/// {
/// ${<User: Model, DMParticipant>}
/// }
///```
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Chat room
/// - Throws: If room is not found or query do fail
public func removeUsersFromRoom(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard var room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
room.time.updated = Date()
try room.save()
for user: T in try request.users() {
try Pivot<T, DMRoom>.remove(user, room)
}
return try room.makeJSON()
}
/// Get DMRoom participants
///
///```
/// GET: /chat/room/${room_uuid}/participant
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - uniqueId: Chat room UUID
/// - Returns: Array of You Fluent object, which corresponds to DMParticipant and FLuent's Model Protocols
/// - Throws: If room is not found or query do fail
public func getRoomParticipants(request: Request, uniqueId: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(uniqueId.lowercased()) else {
throw Abort.notFound
}
let users: [T] = try room.participants()
return try users.makeJSON()
}
/// Get DMParticipant rooms. This request passes in url Your Fluent model `id` which is associated with VaporDM's
///
///```
/// GET: /chat/participant/${user_id}/rooms
/// "Content-Type" = "application/json"
///```
/// - Parameters:
/// - request: request object
/// - user: Your Fluent Associated model with VaporDM
/// - Returns: Array of DMRoom object which your User participate
/// - Throws: If query goes wrong
public func getParticipantRooms(request: Request, user: T) throws -> ResponseRepresentable {
let rooms: [DMRoom] = try user.rooms().all()
return try rooms.makeJSON()
}
/// Get chat room history. You can pass in request data `from` and `to` values which constrain query
///```
/// GET: /chat/history/${room_uuid}
/// "Content-Type" = "application/json"
///```
///
/// - Parameters:
/// - request: request object
/// - room: chat room UUID for which history will be retirned
/// - Returns: Array of DMDirective objects
/// - Throws: If room is not found or query will throw
public func history(request: Request, room: String) throws -> ResponseRepresentable {
guard let room = try DMRoom.find(room) else {
throw Abort.notFound
}
return try room.messages(from: request.data["from"]?.double, to: request.data["to"]?.double).makeJSON()
}
/// Called when a WebSocket client connects to the server
///```
/// ws: /chat/service/${user_id}
///```
///
/// - Parameters:
/// - request: WebSocket connection request
/// - ws: WebSocket
/// - user: User which did connect
public func chatService<T:DMUser>(request: Request, ws: WebSocket, user: T) {
let connectionIdentifier = UUID().uuidString
openConnection(from: user, ws: ws, identifier: connectionIdentifier)
ws.onText = {[weak self] ws, text in
self?.sendMessage(from: user, message:try? JSON(bytes: Array(text.utf8)))
}
ws.onClose = {[weak self] ws, _, _, _ in
guard let id = user.id?.string else {
T.directMessage(log: DMLog(message: "Unable to get user unigeId", type: .error))
return
}
self?.connections.remove(DMConnection(id: connectionIdentifier, user: id, socket: ws))
self?.sendMessage(from: user, message:JSON([DMKeys.type:String(DMType.disconnected.rawValue).makeNode()]))
}
}
}
extension DMController {
/// After user connect to WebSocket we are opening connection on VaporDM which means creating an connection object to identify user with this connection and being unique with different connection for the same user.
///
/// - Parameters:
/// - user: User which did connect
/// - ws: WebSocket object
/// - identifier: UUID to identify this connection
func openConnection<T:DMUser>(from user: T, ws: WebSocket, identifier: String) {
guard let id = user.id?.string else {
T.directMessage(log: DMLog(message: "Unable to get user unigeId", type: .error))
do {
try ws.close()
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
return
}
T.directMessage(log: DMLog(message: "User: \(user.id ?? "") did connect", type: .info))
sendMessage(from: user, message:JSON([DMKeys.type:String(DMType.connected.rawValue).makeNode()]))
let connection = DMConnection(id: identifier, user: id, socket: ws)
applyConfiguration(for: connection)
self.connections.insert(connection)
}
/// Take message JSON object from sender and parse message with DMFlowCOntroller. After success sends message.
///
/// - Parameters:
/// - user: Sender of this message
/// - message: JSON containing message data
func sendMessage<T:DMUser>(from user: T, message: JSON?) {
guard let json = message else {
T.directMessage(log: DMLog(message: "JSON message is nil", type: .error))
return
}
do {
let flow = try DMFlowController(sender: user, message: json)
self.sendMessage(flow)
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
}
/// Send message over the WebSocket thanks to DMFlowController `parseMessage` method result.
///
/// - Parameter message: DMFlowController instance
func sendMessage<T:DMUser>(_ message: DMFlowController<T>) {
do {
let response: (redirect: JSON?, receivers: [T]) = try message.parseMessage()
guard let redirect = response.redirect else { return }
var offline = response.receivers
var online: [T] = []
for connection in self.connections where response.receivers.contains(where: { reveiver -> Bool in
guard connection.userId == reveiver.id?.string else {
return false
}
return true
}) {
try connection.socket?.send(redirect)
if let removed = offline.remove(connection.userId) {
online.append(removed)
}
}
T.directMessage(event: DMEvent(online ,message: redirect))
T.directMessage(event: DMEvent(offline ,message: redirect, status: .failure))
} catch {
T.directMessage(log: DMLog(message: "\(error)", type: .error))
}
}
/// Apply DMConfiguration instance for current connection passed in argument.
///
/// - Parameter connection: Configuration which specify among others ping time interval.
func applyConfiguration(for connection: DMConnection) {
guard let interval = configuration.pingIterval else {
T.directMessage(log: DMLog(message: "Skipping ping sequence. DMConfiguration do not specify ping interval.", type: .info))
return
}
connection.ping(every: interval)
}
}
extension Request {
/// Parse Requesto JSON to chat room object
///
/// - Returns: chat room object
/// - Throws: Error if something goes wrong
func room() throws -> DMRoom {
guard let json = json else { throw Abort.badRequest }
return try DMRoom(node: json)
}
/// Parse Request JSON to your Fluent model
///
/// - Returns: Array of you Fluent models
/// - Throws: Error if something goes wrong
func users<T:DMUser>() throws -> [T] {
guard let json = json else { throw Abort.badRequest }
guard let array = json.pathIndexableArray else {
return [try T(node: json)]
}
return try array.map() { try T(node: $0)}
}
}
| mit | 0e7966141eebaa3699f593bc49a5ede4 | 36.19337 | 218 | 0.579471 | 4.468636 | false | false | false | false |
WhereYat/whereyat-swift | WhereYat.swift | 1 | 1924 | //
// WhereYat.swift
// Flappy Flag
//
// Created by Zane Shannon on 2/1/15.
// Copyright (c) 2015 Where Y'at. All rights reserved.
//
import Foundation
public class WhereYat {
public class func locate(completionHandler: (WhereYatLocation?, NSError?) -> Void) -> Void {
let request = NSURLRequest(URL: NSURL(string: "https://ip.wherey.at/")!)
let urlSession = NSURLSession.sharedSession()
let dataTask = urlSession.dataTaskWithRequest(request) {
(var data, var response, var error) in
var location:WhereYatLocation? = nil
if (error == nil) {
var parseError : NSError?
let jsonResponse = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &parseError) as Dictionary<String, AnyObject>
location = WhereYatLocation(api_response: jsonResponse)
} else {
println(error)
}
dispatch_async(dispatch_get_main_queue()) {
completionHandler(location, error)
}
}
dataTask.resume()
}
}
public class WhereYatLocation: NSObject {
var success:Bool = false
var city:String?
var metro_code:NSNumber?
var country:String?
var country_code:String?
var time_zone:String?
var longitude:NSNumber?
var latitude:NSNumber?
var ip:String?
var subdivisions:[Dictionary<String, String>]?
init(api_response: Dictionary<String, AnyObject>?) {
if let response = api_response {
if response["status"] as String? == "ok" {
self.success = true
self.city = response["city"] as String?
self.metro_code = response["metro_code"] as NSNumber?
self.country = response["country"] as String?
self.country_code = response["country_code"] as String?
self.time_zone = response["time_zone"] as String?
self.longitude = response["longitude"] as NSNumber?
self.latitude = response["latitude"] as NSNumber?
self.ip = response["ip"] as String?
self.subdivisions = response["subdivisions"] as [Dictionary<String, String>]?
}
}
}
} | mit | 570af89e0d51173ddd996b9ca44aae40 | 28.166667 | 134 | 0.695426 | 3.485507 | false | false | false | false |
nathan-hekman/Chill | Chill/Chill/HomeViewController.swift | 1 | 13196 | //
// ViewController.swift
// Chill
//
// Created by Nathan Hekman on 12/7/15.
// Copyright © 2015 NTH. All rights reserved.
//
// Icons by PixelLove.com
import UIKit
import ChameleonFramework
import HealthKit
class HomeViewController: UIViewController {
@IBOutlet var healthKitView: UIView!
@IBOutlet weak var aboutButton: UIButton!
@IBOutlet weak var setupButton: UIButton!
@IBOutlet weak var lastHeartRateTextLabel: UILabel!
@IBOutlet weak var chillLogoLabel: UILabel!
@IBOutlet weak var heartRateView: UIView!
@IBOutlet weak var contentView: UIView!
@IBOutlet weak var chillResultLabel: UILabel!
@IBOutlet weak var checkWatchLabel: UILabel!
@IBOutlet weak var chillLogoTopConstraint: NSLayoutConstraint!
@IBOutlet weak var heartrateLabel: UILabel!
@IBOutlet var healthKitRequestLabel: UILabel!
let app = UIApplication.sharedApplication()
var hasAnimated = false
override func viewDidLoad() {
super.viewDidLoad()
//temporary-- save a copy of this vc for updating views (need to refactor for MVVM)
PhoneSessionManager.sharedInstance.mainVC = self
//start WCSession to communicate to/from watch
PhoneSessionManager.sharedInstance.startSession()
setupView()
setupHeartRate()
}
override func viewDidAppear(animated: Bool) {
//tryToShowPopup()
if (hasAnimated == false) {
animateToShow()
}
else {
tryToShowPopup()
}
}
func setLabelBasedOnScreenSize() {
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
print("iPhone Classic")
self.healthKitRequestLabel.text = "Tap the ••• button above to see Privacy Policy information."
case 960:
print("iPhone 4 or 4S")
self.healthKitRequestLabel.text = "\n\n\n\nCheck the Health app to grant heart rate permission."
// case 1136:
// print("iPhone 5 or 5S or 5C")
// case 1334:
// print("iPhone 6 or 6S")
// case 2208:
// print("iPhone 6+ or 6S+")
default:
print("normal")
self.healthKitRequestLabel.text = "\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept. Tap the ••• button above to see Privacy Policy information."
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// todo: watch spins but never measures if you press decline in the popup. if you accept then it works
func tryToShowPopup() {
// if let permission = Utils.retrieveHasRespondedToHealthKitFromUserDefaults() {
// if permission == 0 {
//}
//}
//else {
guard HKHealthStore.isHealthDataAvailable() == true else {
return
}
// guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else {
// return
// }
if let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) {
let dataTypes = Set(arrayLiteral: quantityType)
let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate)
if let healthStore = HealthKitManager.sharedInstance.healthStore {
let status = healthStore.authorizationStatusForType(quantityType!)
switch status {
case .SharingAuthorized:
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
self.healthKitView.hidden = true
case .SharingDenied:
dispatch_async(dispatch_get_main_queue()) {
self.setLabelBasedOnScreenSize()
self.healthKitView.hidden = false
self.showPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app in order to check your heart rate and Chill status. Check the Health app to accept.")
}
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
//}
case .NotDetermined:
dispatch_async(dispatch_get_main_queue()) {
self.setLabelBasedOnScreenSize()
//self.healthKitRequestButton.hidden = false
self.healthKitView.hidden = false
//self.tryToShowPopup()
}
if let healthStore = HealthKitManager.sharedInstance.healthStore {
healthStore.requestAuthorizationToShareTypes(dataTypes, readTypes: dataTypes) { (success, error) -> Void in
if success == false { //this is if there is an error like running on simulator
Utils.updateUserDefaultsHasRespondedToHealthKit(0) //update has responded now at this point
}
else if success == true { //user has either confirmed or said not now
self.tryToShowPopup()
Utils.updateUserDefaultsHasRespondedToHealthKit(1) //update has responded now at this point
}
}
}
}
}
}
//showPopup("\"Chill\" needs permission to access heart rate data and save heart rate data to the Health app. Open Chill on your Apple Watch to continue.")
//}
}
func showPopup(message: String!) {
let alert = UIAlertController(title: "Health Access", message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Got it", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func setupView() {
//get color scheme
ColorUtil.sharedInstance.setupFlatColorPaletteWithFlatBaseColor(FlatBlueDark(), colorscheme: ColorScheme.Analogous)
//change colors
setStatusBarStyle(UIStatusBarStyleContrast)
//view.backgroundColor = FlatBlue()
checkWatchLabel.textColor = FlatWhite()
heartrateLabel.textColor = FlatWhite()
chillResultLabel.textColor = FlatWhite()
//checkWatchLabel.hidden = true
heartrateLabel.text = "--"
//chillResultLabel.text = "You're Chill."
//setup button targets
setupButton.addTarget(self, action: "showSetupVC", forControlEvents: .TouchUpInside)
aboutButton.addTarget(self, action: "showAboutVC", forControlEvents: .TouchUpInside)
}
func showSetupVC() {
let setupVC = ViewControllerUtils.vcWithNameFromStoryboardWithName("setup", storyboardName: "Main") as! SetupViewController
presentViewController(setupVC, animated: true, completion: { _ in
})
}
func showAboutVC() {
let aboutVC = ViewControllerUtils.vcWithNameFromStoryboardWithName("about", storyboardName: "Main") as! AboutViewController
presentViewController(aboutVC, animated: true, completion: { _ in
})
}
func animateToShow() {
//checkiPhoneSize()
UIView.animateWithDuration(0.5, delay: 0.5, options: .CurveLinear, animations: { _ in
self.chillLogoLabel.transform = CGAffineTransformScale(self.chillLogoLabel.transform, 1.2, 1.2)
}, completion: { _ in
//self.chillLogoLabel.font = UIFont(name: self.chillLogoLabel.font.fontName, size: 31)
UIView.animateWithDuration(0.7, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 15, options: .CurveEaseInOut, animations: {
self.chillLogoLabel.transform = CGAffineTransformScale(self.chillLogoLabel.transform, 0.3, 0.3)
}, completion: { _ in
//move logo up to top
self.chillLogoTopConstraint.constant = -1 * (UIScreen.mainScreen().bounds.height/2) + 50
UIView.animateWithDuration(0.7, delay: 0.0, options: .CurveEaseInOut, animations: { _ in
//let originalFrame = self.chillLogoLabel.frame
//self.chillLogoLabel.frame = CGRect(x: originalFrame.origin.x, y: originalFrame.origin.y/2, width: originalFrame.width, height: originalFrame.height)
self.view.layoutIfNeeded()
}, completion: { _ in
UIView.animateWithDuration(0.5, delay: 0.3, options: .CurveLinear, animations: { _ in
self.contentView.alpha = 1.0
self.heartRateView.alpha = 1.0
self.lastHeartRateTextLabel.alpha = 1.0
self.aboutButton.alpha = 1.0
self.setupButton.alpha = 1.0
}, completion: { _ in
UIView.animateWithDuration(0.5, delay: 0.3, options: .CurveLinear, animations: { _ in
self.checkWatchLabel.alpha = 1.0
self.chillResultLabel.alpha = 1.0
}, completion: { _ in
self.hasAnimated = true
self.tryToShowPopup()
})
})
})
})
})
}
func checkiPhoneSize() {
let oldConstant = self.chillLogoTopConstraint.constant
if UIDevice().userInterfaceIdiom == .Phone {
switch UIScreen.mainScreen().nativeBounds.height {
case 480:
print("iPhone Classic")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 960:
print("iPhone 4 or 4S")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 1136:
print("iPhone 5 or 5S or 5C")
self.chillLogoTopConstraint.constant = oldConstant - 160
case 1334:
print("iPhone 6 or 6S")
self.chillLogoTopConstraint.constant = oldConstant - 200
case 2208:
print("iPhone 6+ or 6S+")
self.chillLogoTopConstraint.constant = oldConstant - 220
default:
print("unknown")
self.chillLogoTopConstraint.constant = oldConstant - 220
}
}
}
func setupHeartRate() {
//initially tell apple watch what last heart rate was
if let lastHeartRate = Utils.retrieveLastHeartRateFromUserDefaults() {
heartrateLabel.text = "\(lastHeartRate)"
}
if let lastChillString = Utils.retrieveChillStringFromUserDefaults() {
checkWatchLabel.hidden = true
chillResultLabel.text = "\(lastChillString)"
}
}
func sendNotification() {
let alertTime = NSDate().dateByAddingTimeInterval(5)
let notifyAlarm = UILocalNotification()
notifyAlarm.fireDate = alertTime
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.soundName = UILocalNotificationDefaultSoundName
notifyAlarm.category = "CHILL_CATEGORY"
notifyAlarm.alertTitle = "Chill"
notifyAlarm.alertBody = "Yo, Chill!"
app.scheduleLocalNotification(notifyAlarm)
}
}
| mit | 33e651a2e406fe92d5e7fbe8974f0920 | 39.814241 | 291 | 0.540014 | 6.151657 | false | false | false | false |
nghiaphunguyen/NKit | NKit/Source/CustomViews/NKTextView.swift | 1 | 2662 | //
// NKTextView.swift
//
// Created by Nghia Nguyen on 2/6/16.
//
import UIKit
import RxSwift
import RxCocoa
open class NKTextView: UITextView, UITextViewDelegate {
private var _rx_didBeginEdit = Variable<Void>(())
private var _rx_didEndEdit = Variable<Void>(())
public var rx_didBeginEdit: Observable<Void> {
return self._rx_didBeginEdit.asObservable()
}
public var rx_didEndEdit: Observable<Void> {
return self._rx_didEndEdit.asObservable()
}
public var nk_text: String? = nil {
didSet {
self.updateText()
}
}
open var nk_placeholder: String? {
didSet {
self.updateText()
}
}
open var nk_placeholderColor: UIColor? {
didSet {
self.updateText()
}
}
open var nk_contentTextColor: UIColor? {
didSet {
self.updateText()
}
}
private var nk_isEditingMode: Bool = false
private var nk_isTurnOnPlaceholder: Bool {
return !self.nk_isEditingMode && self.nk_text?.isEmpty == true
}
open func updateText() {
if self.nk_isTurnOnPlaceholder {
self.text = self.nk_placeholder
self.textColor = self.nk_placeholderColor
} else {
if self.text != self.nk_text {
self.text = self.nk_text
}
self.textColor = self.nk_contentTextColor
}
}
convenience init() {
self.init(frame: CGRect.zero, textContainer: nil)
self.setupView()
}
public override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.setupView()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupView()
}
func setupView() {
self.delegate = self
self.rx.text.subscribe(onNext: { [unowned self] in
if self.nk_text != $0 && !self.nk_isTurnOnPlaceholder {
self.nk_text = $0
}
}).addDisposableTo(self.nk_disposeBag)
self.updateText()
}
//MARK: UITextViewDelegate
open func textViewDidBeginEditing(_ textView: UITextView) {
self.nk_isEditingMode = true
self.updateText()
self._rx_didBeginEdit.nk_reload()
}
open func textViewDidEndEditing(_ textView: UITextView) {
self.nk_isEditingMode = false
self.updateText()
self._rx_didEndEdit.nk_reload()
}
}
| mit | 6843c546ae6ab99c52da3ec9217e2d02 | 23.422018 | 74 | 0.558603 | 4.527211 | false | false | false | false |
trident10/TDMediaPicker | TDMediaPicker/Classes/Controller/ChildViewControllers/TDMediaPermissionViewController.swift | 1 | 3714 | //
// TDMediaPermissionViewController.swift
// ImagePicker
//
// Created by Abhimanu Jindal on 24/06/17.
// Copyright © 2017 Abhimanu Jindal. All rights reserved.
//
import UIKit
protocol TDMediaPermissionViewControllerDelegate:class{
func permissionControllerDidFinish(_ controller: TDMediaPermissionViewController)
func permissionControllerDidTapClose(_ controller: TDMediaPermissionViewController)
func permissionControllerDidRequestForConfig(_ controller: TDMediaPermissionViewController)-> TDConfigPermissionScreen?
}
class TDMediaPermissionViewController: UIViewController, TDMediaPermissionViewDelegate{
// MARK: - Variables
weak var delegate: TDMediaPermissionViewControllerDelegate?
private lazy var serviceManager = TDPermissionServiceManager()
private var permissionView: TDMediaPermissionView?
// MARK: - Init
public required init() {
super.init(nibName: "TDMediaPermission", bundle: TDMediaUtil.xibBundle())
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life cycle
public override func viewDidLoad() {
super.viewDidLoad()
permissionView = self.view as? TDMediaPermissionView
permissionView?.delegate = self
setupPermissionConfig()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
requestGalleryPermission()
}
//MARK: - Private Method(s)
private func setupPermissionConfig(){
let config = self.delegate?.permissionControllerDidRequestForConfig(self)
//1.
if let customView = config?.customView{
permissionView?.setupCustomView(view: customView)
return
}
//2.
var shouldDisplayDefaultScreen = true
if let standardView = config?.standardView{
permissionView?.setupStandardView(view: standardView)
shouldDisplayDefaultScreen = false
}
if let settingsButtonConfig = config?.settingButton{
permissionView?.setupSettingsButton(buttonConfig: settingsButtonConfig)
shouldDisplayDefaultScreen = false
}
if let cancelButtonConfig = config?.cancelButton{
permissionView?.setupCancelButton(buttonConfig: cancelButtonConfig)
shouldDisplayDefaultScreen = false
}
if let captionConfig = config?.caption{
permissionView?.setupCaptionLabel(captionConfig)
shouldDisplayDefaultScreen = false
}
//3.
if shouldDisplayDefaultScreen{
permissionView?.setupDefaultScreen()
}
}
private func requestGalleryPermission(){
TDMediaUtil.requestForHardwareAccess(accessType: .Gallery) { (isGranted) in
if isGranted{
self.delegate?.permissionControllerDidFinish(self)
}
}
}
//MARK:- View Delegate Method(s)
func permissionViewSettingsButtonTapped(_ view: TDMediaPermissionView) {
DispatchQueue.main.async {
if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
} else {
// Fallback on earlier versions
}
}
}
}
func permissionViewCloseButtonTapped(_ view: TDMediaPermissionView) {
self.delegate?.permissionControllerDidTapClose(self)
}
}
| mit | cef5481a0cb048fdc4dcaecfe00da4a7 | 31.008621 | 123 | 0.648263 | 5.828885 | false | true | false | false |
Johnykutty/SwiftLint | Tests/SwiftLintFrameworkTests/IntegrationTests.swift | 2 | 2464 | //
// IntegrationTests.swift
// SwiftLint
//
// Created by JP Simard on 5/28/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
import SwiftLintFramework
import XCTest
let config: Configuration = {
let directory = #file.bridge()
.deletingLastPathComponent.bridge()
.deletingLastPathComponent.bridge()
.deletingLastPathComponent
_ = FileManager.default.changeCurrentDirectoryPath(directory)
return Configuration(path: Configuration.fileName)
}()
class IntegrationTests: XCTestCase {
func testSwiftLintLints() {
// This is as close as we're ever going to get to a self-hosting linter.
let swiftFiles = config.lintableFiles(inPath: "")
XCTAssert(swiftFiles.map({ $0.path! }).contains(#file), "current file should be included")
let violations = swiftFiles.flatMap {
Linter(file: $0, configuration: config).styleViolations
}
violations.forEach { violation in
violation.location.file!.withStaticString {
XCTFail(violation.reason, file: $0, line: UInt(violation.location.line!))
}
}
}
func testSwiftLintAutoCorrects() {
let swiftFiles = config.lintableFiles(inPath: "")
let corrections = swiftFiles.flatMap { Linter(file: $0, configuration: config).correct() }
for correction in corrections {
correction.location.file!.withStaticString {
XCTFail(correction.ruleDescription.description,
file: $0, line: UInt(correction.location.line!))
}
}
}
}
extension String {
func withStaticString(_ closure: (StaticString) -> Void) {
withCString {
let rawPointer = $0._rawValue
let byteSize = lengthOfBytes(using: .utf8)._builtinWordValue
let isASCII = true._getBuiltinLogicValue()
let staticString = StaticString(_builtinStringLiteral: rawPointer,
utf8CodeUnitCount: byteSize,
isASCII: isASCII)
closure(staticString)
}
}
}
extension IntegrationTests {
static var allTests: [(String, (IntegrationTests) -> () throws -> Void)] {
return [
("testSwiftLintLints", testSwiftLintLints),
("testSwiftLintAutoCorrects", testSwiftLintAutoCorrects)
]
}
}
| mit | 44f8dd4ebc5833046dca39cf7d2ef995 | 32.739726 | 98 | 0.622818 | 5.047131 | false | true | false | false |
wwq0327/iOS8Example | iOSFontList/iOSFontList/DetailViewController.swift | 1 | 863 | //
// DetailViewController.swift
// iOSFontList
//
// Created by wyatt on 15/6/10.
// Copyright (c) 2015年 Wanqing Wang. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
var indexPath = NSIndexPath()
let viewModel = MasterViewModel()
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var fontSize: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let fontName = viewModel.titleAtIndexPath(indexPath)
textView.font = UIFont(name: fontName, size: 12)
}
@IBAction func sliderFontSize(sender: UISlider) {
var size = Int(sender.value)
fontSize.text = "\(size)"
let fontName = viewModel.titleAtIndexPath(indexPath)
textView.font = UIFont(name: fontName, size: CGFloat(size))
}
}
| apache-2.0 | 4260241946e3669a00eca67793c2cf2f | 23.6 | 67 | 0.641115 | 4.531579 | false | false | false | false |
timd/SwiftTable | SwiftTable/ViewController.swift | 1 | 2362 | //
// ViewController.swift
// SwiftTable
//
// Created by Tim on 20/07/14.
// Copyright (c) 2014 Charismatic Megafauna Ltd. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let cellIdentifier = "cellIdentifier"
var tableData = [String]()
@IBOutlet var tableView: UITableView?
override func viewDidLoad() {
super.viewDidLoad()
// Register the UITableViewCell class with the tableView
self.tableView?.registerClass(UITableViewCell.self, forCellReuseIdentifier: self.cellIdentifier)
// Setup table data
for index in 0...100 {
self.tableData.append("Item \(index)")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// UITableViewDataSource methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier) as UITableViewCell
cell.textLabel?.text = self.tableData[indexPath.row]
return cell
}
// UITableViewDelegate methods
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let alert = UIAlertController(title: "Item selected", message: "You selected item \(indexPath.row)", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default,
handler: {
(alert: UIAlertAction!) in println("An alert of type \(alert.style.hashValue) was tapped!")
self.tableView?.deselectRowAtIndexPath(indexPath, animated: true)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
}
| mit | a7ab08919d809c809219abdafe736d2d | 31.356164 | 154 | 0.621507 | 5.949622 | false | false | false | false |
wilzh40/ShirPrize-Me | SwiftSkeleton/ThirdViewController.swift | 1 | 2174 | //
// ThirdViewController.swift
// SwiftSkeleton
//
// Created by Wilson Zhao on 8/17/14.
// Copyright (c) 2014 Wilson Zhao. All rights reserved.
//
import Foundation
import UIKit
class ThirdViewController: UIViewController {
let singleton:Singleton = Singleton.sharedInstance
@IBOutlet var stepper:UIStepper?
@IBOutlet var quantity: UILabel?
@IBOutlet var size: UIButton?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeSizeButton (sender:AnyObject) {
if size?.titleLabel.text == "med" {
size?.setTitle("lrg", forState: UIControlState.Normal)
}
if size?.titleLabel.text == "sma" {
size?.setTitle("med", forState: UIControlState.Normal)
}
if size?.titleLabel.text == "lrg" {
size?.setTitle("sma", forState: UIControlState.Normal)
}
singleton.quoteObject.product.size = size!.titleLabel.text!
}
@IBAction func oneStep (sender:AnyObject) {
quantity?.text = "\(Int(stepper!.value))"
singleton.quoteObject.product.quantity = Int(stepper!.value)
}
@IBAction func loading (sender:AnyObject) {
self.insertSpinner(YYSpinkitView(style:YYSpinKitViewStyle.Pulse,color:UIColor.whiteColor()),
atIndex:4,backgroundColor:UIColor(red:0.498,green:0.549,blue:0.553,alpha:1.0))
}
func insertSpinner(spinner:YYSpinkitView,atIndex index:Int,backgroundColor color:UIColor){
var screenBounds = UIScreen.mainScreen().bounds
var screenWidth = CGRectGetWidth(screenBounds)
var panel = UIView(frame:CGRectOffset(screenBounds, screenWidth * CGFloat(index), 0.0))
panel.backgroundColor = color
spinner.center = CGPointMake(CGRectGetMidX(screenBounds), CGRectGetMidY(screenBounds))
panel.addSubview(spinner)
self.view.addSubview(panel)
}
}
| mit | 6ca9cd5a3493bf0190a085593d94a542 | 32.96875 | 100 | 0.659614 | 4.491736 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT | WeiBo/WeiBo/Classes/View(视图)/Compose(发布)/CustomKeyboard(自定义键盘)/WBKeyboardToolbar.swift | 1 | 3175 | //
// WBKeyboardToolbar.swift
// WeiBo
//
// Created by chenWei on 2017/4/12.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
fileprivate let baseTag = 88
/// 协议
protocol WBKeyboardToolbarDelegate: NSObjectProtocol {
/// 代理方法
///
/// - Parameter section: <#section description#>
func toggleKeyboard(section: Int)
}
class WBKeyboardToolbar: UIStackView {
/// 代理
weak var delegate: WBKeyboardToolbarDelegate?
/// 记录选中的button
var selectedButton: UIButton?
var selectedIndex: Int = 0 {
didSet {
let selectedTag = selectedIndex + baseTag
let button = viewWithTag(selectedTag) as! UIButton
selectedButton?.isSelected = false
button.isSelected = true
selectedButton = button
}
}
override init(frame: CGRect) {
super.init(frame: frame)
//水平还是垂直分布
axis = .horizontal
//等距均匀分布
distribution = .fillEqually
setupUI()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - UI 搭建
extension WBKeyboardToolbar {
func setupUI() {
//有关底部按钮信息的字典数组
let buttonDicArr: [[String: Any]] = [["title": "最近", "image": "left"],
["title": "默认", "image": "mid"],
["title": "emoji", "image": "mid"],
["title": "浪小花", "image": "right"]]
//遍历字典数组创建 button
for (index,dic) in buttonDicArr.enumerated() {
let title = dic["title"] as! String
let imageName = dic["image"] as! String
let normalImageName = "compose_emotion_table_\(imageName)_normal"
let selectedImage = UIImage(named: "compose_emotion_table_\(imageName)_selected")
let button = UIButton(title: title, titleColor: UIColor.white, fontSize: 16, target: self, selector: #selector(toggleKeyobard(button:)), bgImage: normalImageName)
//设置button的选中状态的文字和背景图片
button.setTitleColor(UIColor.darkGray, for: .selected)
button.setBackgroundImage(selectedImage, for: .selected)
button.tag = index + baseTag
//和addSubView的效果是一样的
addArrangedSubview(button)
//默认选中第一个按钮
if index == 0 {
button.isSelected = true
selectedButton = button
}
}
}
}
// MARK: - 点击事件的处理
extension WBKeyboardToolbar {
/// 切换键盘
func toggleKeyobard(button: UIButton) {
selectedButton?.isSelected = false
button.isSelected = true
selectedButton = button
//响应代理方法
delegate?.toggleKeyboard(section: button.tag - baseTag)
}
}
| mit | 63a09f67cdb4da3bfa2efeb9456680da | 25.159292 | 174 | 0.54161 | 4.806504 | false | false | false | false |
felipecarreramo/R3LRackspace | Example/R3LRackspace/ViewController.swift | 1 | 1848 | //
// ViewController.swift
// R3LRackspace
//
// Created by Juan Felipe Carrera Moya on 12/18/2015.
// Copyright (c) 2015 Juan Felipe Carrera Moya. All rights reserved.
//
import UIKit
import R3LRackspace
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let cloud = CloudFiles(username: "##username##", apiKey: "##ApiKey##", region: .Chicago)
let bundle = NSBundle.mainBundle()
let path = bundle.pathForResource("eye", ofType: "jpg")
if let path = path , let data = NSData(contentsOfFile: path) {
cloud.putObject(data, name: "eye.jpg", container: "##containerName##") { success in
if success {
cloud.getPublicURL("##containerName##", name: "eye.jpg") { urlObject in
if let urlObject = urlObject {
print("URL: \(urlObject)")
}
}
}
}
}
//cloud.createContainer("jugofresh-test-cdn")
//cloud.getPublicURL("jugofresh-test-cdn", name:"eye.jpg")
//cloud.getContainers()
//cloud.enableContainerForCDN("jugofresh-test-cdn")
//cloud.getPublicContainers()
// cloud.getPublicURL("jugofresh-JC", name: "testImage.jpg") { urlObject in
//
// if let urlObject = urlObject {
// print(urlObject)
// }
//
// }
//cloud.getContainer("jugofresh-JC")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | a394c4bfa7ef1dff1fee1bcb703e9c15 | 29.295082 | 96 | 0.508658 | 4.850394 | false | true | false | false |
ResearchSuite/ResearchSuiteAppFramework-iOS | Source/Core/Classes/RSAFRootViewController.swift | 1 | 2395 | //
// RSAFRootViewController.swift
// Pods
//
// Created by James Kizer on 3/22/17.
//
//
import UIKit
import ReSwift
import ResearchSuiteTaskBuilder
import ResearchKit
open class RSAFRootViewController: UIViewController, RSAFRootViewControllerProtocol, StoreSubscriber {
public var presentedActivity: UUID?
private var state: RSAFCombinedState?
public var taskBuilder: RSTBTaskBuilder?
weak public var RSAFDelegate: RSAFRootViewControllerProtocolDelegate?
public var contentHidden = false {
didSet {
guard contentHidden != oldValue && isViewLoaded else { return }
if let vc = self.presentedViewController {
vc.view.isHidden = contentHidden
}
self.view.isHidden = contentHidden
}
}
override open func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.store?.subscribe(self)
}
deinit {
self.store?.unsubscribe(self)
}
open func newState(state: RSAFCombinedState) {
self.state = state
if self.presentedActivity == nil,
let coreState = state.coreState as? RSAFCoreState,
let (uuid, activityRun, taskBuilder) = coreState.activityQueue.first {
self.presentedActivity = uuid
self.runActivity(uuid: uuid, activityRun: activityRun, taskBuilder: taskBuilder, completion: { [weak self] in
self?.presentedActivity = nil
//potentially launch new activity
if let state = self?.state {
self?.newState(state: state)
}
self?.RSAFDelegate?.activityRunDidComplete(activityRun: activityRun)
})
}
}
open var store: Store<RSAFCombinedState>? {
guard let delegate = UIApplication.shared.delegate as? RSAFApplicationDelegate else {
return nil
}
return delegate.reduxStore
}
// open var taskBuilder: RSTBTaskBuilder? {
// guard let delegate = UIApplication.shared.delegate as? RSAFApplicationDelegate else {
// return nil
// }
//
// return delegate.taskBuilderManager?.rstb
// }
}
| apache-2.0 | 3bdbc85d70ae2427300db514863dbb78 | 26.528736 | 121 | 0.588727 | 5.357942 | false | false | false | false |
TouchInstinct/LeadKit | TIFoundationUtils/TITimer/Sources/TITimer/TITimer.swift | 1 | 5774 | //
// Copyright (c) 2021 Touch Instinct
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the Software), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import TISwiftUtils
public final class TITimer: ITimer {
private let mode: TimerRunMode
private let type: TimerType
private var sourceTimer: Invalidatable?
private var enterBackgroundDate: Date?
private var interval: TimeInterval = 0
public private(set) var elapsedTime: TimeInterval = 0
public var isRunning: Bool {
sourceTimer != nil
}
public var eventHandler: ParameterClosure<TimeInterval>?
// MARK: - Initialization
public init(type: TimerType, mode: TimerRunMode) {
self.mode = mode
self.type = type
if mode == .activeAndBackground {
addObserver()
}
}
deinit {
if mode == .activeAndBackground {
removeObserver()
}
invalidate()
}
// MARK: - Public
public func start(with interval: TimeInterval = 1) {
invalidate()
self.interval = interval
self.elapsedTime = 0
createTimer(with: interval)
eventHandler?(elapsedTime)
}
public func invalidate() {
sourceTimer?.invalidate()
sourceTimer = nil
}
public func pause() {
guard isRunning else {
return
}
invalidate()
}
public func resume() {
guard !isRunning else {
return
}
createTimer(with: interval)
}
// MARK: - Actions
@objc private func handleSourceUpdate() {
guard enterBackgroundDate == nil else {
return
}
elapsedTime += interval
eventHandler?(elapsedTime)
}
// MARK: - Private
private func createTimer(with interval: TimeInterval) {
switch type {
case let .dispatchSourceTimer(queue):
sourceTimer = startDispatchSourceTimer(interval: interval, queue: queue)
case let .runloopTimer(runloop, mode):
sourceTimer = startTimer(interval: interval, runloop: runloop, mode: mode)
case let .custom(timer):
sourceTimer = timer
timer.start(with: interval)
}
}
}
// MARK: - Factory
extension TITimer {
public convenience init(mode: TimerRunMode = .activeAndBackground) {
self.init(type: .runloopTimer(runloop: .main, mode: .common), mode: mode)
}
}
// MARK: - NotificationCenter
private extension TITimer {
func addObserver() {
NotificationCenter.default.addObserver(self,
selector: #selector(willEnterForegroundNotification),
name: UIApplication.willEnterForegroundNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(didEnterBackgroundNotification),
name: UIApplication.didEnterBackgroundNotification,
object: nil)
}
func removeObserver() {
NotificationCenter.default.removeObserver(self)
}
@objc func willEnterForegroundNotification() {
guard let unwrappedEnterBackgroundDate = enterBackgroundDate else {
return
}
let timeInBackground = -unwrappedEnterBackgroundDate.timeIntervalSinceNow.rounded()
enterBackgroundDate = nil
elapsedTime += timeInBackground
eventHandler?(elapsedTime)
}
@objc func didEnterBackgroundNotification() {
enterBackgroundDate = Date()
}
}
// MARK: - DispatchSourceTimer
private extension TITimer {
func startDispatchSourceTimer(interval: TimeInterval, queue: DispatchQueue) -> Invalidatable? {
let timer = DispatchSource.makeTimerSource(flags: [], queue: queue)
timer.schedule(deadline: .now() + interval, repeating: interval)
timer.setEventHandler() { [weak self] in
self?.handleSourceUpdate()
}
return timer as? DispatchSource
}
}
// MARK: - Timer
private extension TITimer {
func startTimer(interval: TimeInterval, runloop: RunLoop, mode: RunLoop.Mode) -> Invalidatable {
let timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] _ in
self?.handleSourceUpdate()
}
runloop.add(timer, forMode: mode)
return timer
}
}
| apache-2.0 | b00de3592e5f8d7311ae3cb07439eb71 | 27.726368 | 102 | 0.60478 | 5.406367 | false | false | false | false |
peaks-cc/iOS11_samplecode | chapter_11/MyQRCode/MyQRCodeKit/Me.swift | 1 | 4678 | //
// Me.swift
// MyQRCodeKit
//
// Created by Kishikawa Katsumi on 2017/09/04.
// Copyright © 2017 Kishikawa Katsumi. All rights reserved.
//
import Foundation
import CoreImage
public struct Me: Codable {
public let firstname: String?
public let lastname: String?
public let company: String?
public let street: String?
public let city: String?
public let zipcode: String?
public let country: String?
public let phone: String?
public let email: String?
public let website: String?
public let birthday: String?
private static var userDefaults: UserDefaults {
get {
return UserDefaults(suiteName: "group.com.kishikawakatsumi.myqrcode")!
}
}
let key = "me"
public init(firstname: String?, lastname: String?, company: String?,
street: String?, city: String?, zipcode: String?, country: String?,
phone: String?, email: String?, website: String?,
birthday: String?) {
self.firstname = firstname
self.lastname = lastname
self.company = company
self.street = street
self.city = city
self.zipcode = zipcode
self.country = country
self.phone = phone
self.email = email
self.website = website
self.birthday = birthday
}
public func generateVisualCode() -> UIImage? {
let parameters: [String : Any] = [
"inputMessage": vCardRepresentation(),
"inputCorrectionLevel": "L"
]
let filter = CIFilter(name: "CIQRCodeGenerator", withInputParameters: parameters)
guard let outputImage = filter?.outputImage else {
return nil
}
let scaledImage = outputImage.transformed(by: CGAffineTransform(scaleX: 6, y: 6))
guard let cgImage = CIContext().createCGImage(scaledImage, from: scaledImage.extent) else {
return nil
}
return UIImage(cgImage: cgImage)
}
private func vCardRepresentation() -> Data! {
var vCard = [String]()
vCard += ["BEGIN:VCARD"]
vCard += ["VERSION:3.0"]
switch (firstname, lastname) {
case let (firstname?, lastname?):
vCard += ["N:\(lastname);\(firstname);"]
case let (firstname?, nil):
vCard += ["N:\(firstname);"]
case let (nil, lastname?):
vCard += ["N:\(lastname);"]
case (nil, nil):
break
}
if let company = company {
vCard += ["ORG:\(company)"]
}
switch (street, city, zipcode, country) {
case let (street?, city?, zipcode?, country?):
vCard += ["ADR:;;\(street);\(city);;\(zipcode);\(country)"]
case let (nil, city?, zipcode?, country?):
vCard += ["ADR:;;;\(city);;\(zipcode);\(country)"]
case let (street?, nil, zipcode?, country?):
vCard += ["ADR:;;\(street);;;\(zipcode);\(country)"]
case let (street?, city?, nil, country?):
vCard += ["ADR:;;\(street);\(city);;;\(country)"]
case let (street?, city?, zipcode?, nil):
vCard += ["ADR:;;\(street);\(city);;\(zipcode);"]
case let (nil, nil, zipcode?, country?):
vCard += ["ADR:;;;;;\(zipcode);\(country)"]
case let (street?, nil, nil, country?):
vCard += ["ADR:;;\(street);;;;\(country)"]
case let (street?, city?, nil, nil):
vCard += ["ADR:;;\(street);\(city);;;"]
case let (nil, city?, nil, country?):
vCard += ["ADR:;;;\(city);;;\(country)"]
case let (street?, nil, zipcode?, nil):
vCard += ["ADR:;;\(street);;;\(zipcode);"]
case let (nil, city?, zipcode?, nil):
vCard += ["ADR:;;;\(city);;\(zipcode);"]
case let (nil, nil, nil, country?):
vCard += ["ADR:;;;;;;\(country)"]
case let (street?, nil, nil, nil):
vCard += ["ADR:;;\(street);;;;"]
case let (nil, city?, nil, nil):
vCard += ["ADR:;;;\(city);;;"]
case let (nil, nil, zipcode?, nil):
vCard += ["ADR:;;;;;\(zipcode);"]
case (nil, nil, nil, nil):
break
}
if let phone = phone {
vCard += ["TEL:\(phone)"]
}
if let email = email {
vCard += ["EMAIL:\(email)"]
}
if let website = website {
vCard += ["URL:\(website)"]
}
if let birthday = birthday {
vCard += ["BDAY:\(birthday)"]
}
vCard += ["END:VCARD"]
return vCard.joined(separator: "\n").data(using: .utf8)
}
}
| mit | 709761973ae3f10646badeac086aa849 | 31.479167 | 99 | 0.518495 | 4.562927 | false | false | false | false |
pablot/HardRider | HardRider/GameScene.swift | 1 | 2156 | //
// GameScene.swift
// HardRider
//
// Created by Paweł Tymura on 03.03.2016.
// Copyright (c) 2016 Paweł Tymura. All rights reserved.
//
import SpriteKit
import CoreMotion
import UIKit
class GameScene: SKScene {
var mainscreen = UIScreen()
var spaceShip = MainGameObject(imageNamed: "Spaceship")
var sand = SKSpriteNode(imageNamed: "piasek")
var motionManager = CMMotionManager()
var dest = CGPoint(x: 0, y:0)
override func didMoveToView(view:SKView) {
self.backgroundColor = UIColor.yellowColor()
sand.position = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
sand.size = CGSize(width: 1024, height: 768)
self.addChild(sand)
spaceShip.position = CGPoint(x: 674 /*CGRectGetMidX(self.frame)*/, y:700)
spaceShip.size = CGSize(width: 100.0, height: 150.0)
self.addChild(spaceShip)
if motionManager.accelerometerAvailable == true {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler:{
data, error in
let currentX = self.spaceShip.position.x
let currentY = self.spaceShip.position.y
var change: CGFloat = 0
if data!.acceleration.x != 0
{
change = currentX + CGFloat(data!.acceleration.x * 100)
if self.mainscreen.bounds.contains(CGPoint(x: change, y: currentY)) {
self.dest.x = change
}
}
if data!.acceleration.y != 0
{
change = currentY + CGFloat(data!.acceleration.y * 100)
if self.mainscreen.bounds.contains(CGPoint(x: currentX, y: change)) {
self.dest.y = change
}
}
})
}
}
override func update(currentTime: CFTimeInterval) {
let action = SKAction.moveTo(dest, duration: 1)
self.spaceShip.runAction(action)
}
}
| mit | a15fb6f5f9ef68ca376920a281f027ab | 32.65625 | 106 | 0.552461 | 4.734066 | false | false | false | false |
sodascourse/swift-introduction | Swift-Introduction.playground/Pages/Type Casting.xcplaygroundpage/Contents.swift | 1 | 3046 | /*:
# Type Check and Casting
Type casting is a way to check the type of an instance, or to treat that
instance as a different superclass or subclass from somewhere
else in its own class hierarchy.
Type casting in Swift is implemented with the `is` and `as` operators.
These two operators provide a simple and expressive way to
check the type of a value or cast a value to a different type.
*/
protocol Animal {}
protocol FourLegsAnimal: Animal {}
struct Cat: FourLegsAnimal {
func asMaster() -> String {
return "Meow, I'm your master."
}
}
class Dog: FourLegsAnimal {}
class Duck: Animal {}
let zoo: [Animal] = [Cat(), Dog(), Duck(), Dog(), Cat(), Cat()]
//: Use `is` to test whether this variable is an instance of Class/Struct or Protocol conformance
var catsCount = 0, dogsCount = 0, fourLegsCount = 0
for animal in zoo {
if animal is Cat {
catsCount += 1
}
if animal is Dog {
dogsCount += 1
}
if animal is FourLegsAnimal {
fourLegsCount += 1
}
}
"We have \(catsCount) cats in the zoo."
"We have \(dogsCount) dogs in the zoo."
"We have \(fourLegsCount) four-leg animals."
//: Use `as` to cast type of instance
for animal in zoo {
if let cat = animal as? Cat {
cat.asMaster()
}
}
//: The Swift compiler would help you to check the casting between types.
let cat = Cat()
//cat is Animal // Uncomment to see the warning Xcode yields.
//cat is Dog // Uncomment to see the warning Xcode yields.
let animal = cat as Animal // Up-casting. Use `option+click` to see the type of `animal`
//let dog = cat as? Dog // Check the warning and the value of `dog`
//let someDog = cat as Dog // Uncomment to see the error Xcode yields.
//let someDog2 = cat as! Dog // Uncomment to see the error Xcode yields.
let someCat = animal as? Cat // // Down-casting. Use `option+click` to see the type of `someCat`
let someDog3 = animal as? Dog // Down-casting. Check the value and the type of `someDog3`
/*:
## `Any` and `AnyObject`
Swift provides two special types for working with nonspecific types:
- `Any` can represent an instance of any type at all, including function types.
- `AnyObject` can represent an instance of any class type.
Use `Any` and `AnyObject` only when you explicitly need the behavior and capabilities they provide.
It is always better to be specific about the types you expect to work with in your code.
By making the type context clear, Swift could keep your code safe to execute.
*/
var anything: [Any] = [-1, "XD", ["yo"], ["answer": 42], true, 57, "Hello"]
var stringCount = 0, sumOfAllInt = 0
for item in anything {
// Here we uses "Pattern Matching" (google 'Swift Pattern Matching')
// But anyway, you can still use `if-else` to implement this.
switch item {
case is String:
stringCount += 1
case let integer as Int:
sumOfAllInt += integer
default: () // Do nothing
}
}
stringCount
sumOfAllInt
//: ---
//:
//: [<- Previous](@previous) | [Next ->](@next)
//:
| apache-2.0 | 7b26fbed779155adbfd4b1dd205f54d5 | 28.572816 | 100 | 0.671372 | 3.746617 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/ViewControllers/ManageWalletsViewController.swift | 1 | 6320 | //
// ManageWalletsViewController.swift
// breadwallet
//
// Created by Adrian Corscadden on 2019-07-30.
// Copyright © 2019 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import UIKit
private let addWalletButtonHeight: CGFloat = 72.0
class ManageWalletsViewController: UITableViewController {
private let assetCollection: AssetCollection
private let coreSystem: CoreSystem
private var displayData = [CurrencyMetaData]()
init(assetCollection: AssetCollection, coreSystem: CoreSystem) {
self.assetCollection = assetCollection
self.coreSystem = coreSystem
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
tableView.backgroundColor = .darkBackground
tableView.rowHeight = 66.0
tableView.separatorStyle = .none
title = S.TokenList.manageTitle
tableView.register(ManageCurrencyCell.self, forCellReuseIdentifier: ManageCurrencyCell.cellIdentifier)
tableView.setEditing(true, animated: true)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(pushAddWallets))
//If we are first in the nav controller stack, we need a close button
if navigationController?.viewControllers.first == self {
let button = UIButton.close
button.tintColor = .white
button.tap = {
self.dismiss(animated: true, completion: nil)
}
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: button)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
displayData = assetCollection.enabledAssets
tableView.reloadData()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
assetCollection.saveChanges()
}
override func viewDidLayoutSubviews() {
setupAddButton()
}
private func removeCurrency(_ identifier: CurrencyId) {
guard let index = displayData.firstIndex(where: { $0.uid == identifier }) else { return }
displayData.remove(at: index)
assetCollection.removeAsset(at: index)
tableView.performBatchUpdates({
tableView.deleteRows(at: [IndexPath(row: index, section: 0)], with: .left)
}, completion: { [unowned self] _ in
self.tableView.reloadData() // to update isRemovable
})
}
private func setupAddButton() {
guard tableView.tableFooterView == nil else { return }
let topInset: CGFloat = C.padding[1]
let leftRightInset: CGFloat = C.padding[2]
let width = tableView.frame.width - tableView.contentInset.left - tableView.contentInset.right
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: width, height: addWalletButtonHeight))
let addButton = UIButton()
addButton.tintColor = .disabledWhiteText
addButton.setTitleColor(Theme.tertiaryText, for: .normal)
addButton.setTitleColor(.transparentWhite, for: .highlighted)
addButton.titleLabel?.font = Theme.body1
addButton.imageView?.contentMode = .scaleAspectFit
addButton.setBackgroundImage(UIImage(named: "add"), for: .normal)
addButton.contentHorizontalAlignment = .center
addButton.contentVerticalAlignment = .center
addButton.setTitle("+ " + S.TokenList.addTitle, for: .normal)
addButton.tap = { [weak self] in
guard let `self` = self else { return }
self.pushAddWallets()
}
addButton.frame = CGRect(x: leftRightInset, y: topInset,
width: footerView.frame.width - (2 * leftRightInset),
height: addWalletButtonHeight)
footerView.addSubview(addButton)
footerView.backgroundColor = Theme.primaryBackground
tableView.tableFooterView = footerView
}
@objc private func pushAddWallets() {
let vc = AddWalletsViewController(assetCollection: assetCollection, coreSystem: coreSystem)
navigationController?.pushViewController(vc, animated: true)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension ManageWalletsViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ManageCurrencyCell.cellIdentifier, for: indexPath) as? ManageCurrencyCell else {
return UITableViewCell()
}
let metaData = displayData[indexPath.row]
// cannot remove a native currency if its tokens are enabled, or remove the last currency
let currencyIsRemovable = !coreSystem.isWalletRequired(for: metaData.uid) && assetCollection.enabledAssets.count > 1
cell.set(currency: metaData,
balance: nil,
listType: .manage,
isHidden: false,
isRemovable: currencyIsRemovable)
cell.didRemoveIdentifier = { [unowned self] identifier in
self.removeCurrency(identifier)
}
return cell
}
override func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
override func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
let movedObject = displayData[sourceIndexPath.row]
displayData.remove(at: sourceIndexPath.row)
displayData.insert(movedObject, at: destinationIndexPath.row)
assetCollection.moveAsset(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
}
| mit | c0e83c9f19ee600d978dccca3ad2f58f | 38.993671 | 151 | 0.66308 | 5.341505 | false | false | false | false |
zhou9734/Warm | Warm/Classes/Home/Controller/SubjectViewController.swift | 1 | 7055 | //
// SubjectViewController.swift
// Warm
//
// Created by zhoucj on 16/9/22.
// Copyright © 2016年 zhoucj. All rights reserved.
//
import UIKit
import SVProgressHUD
let SubjectSalonTableReuseIdentifier = "SubjectSalonTableReuseIdentifier"
let SubjectClassesTableReuseIdentifier = "SubjectClassesTableReuseIdentifier"
class SubjectViewController: UIViewController {
let homeViewModel = HomeViewModel()
var rdata: WRdata?
var subid: Int64?{
didSet{
guard let _subid = subid else{
SVProgressHUD.showErrorWithStatus("参数传递错误")
return
}
view.addSubview(progressBar)
view.bringSubviewToFront(progressBar)
unowned let tmpSelf = self
tmpSelf.progressBar.progress = 0.7
UIView.animateWithDuration(1) { () -> Void in
tmpSelf.view.layoutIfNeeded()
}
homeViewModel.loadSubjectDetail(_subid) { (data, error) -> () in
guard let _rdata = data as? WRdata else {
return
}
tmpSelf.rdata = _rdata
tmpSelf.tmpWebView.loadRequest(NSURLRequest(URL: NSURL(string: _rdata.content!)!))
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//隐藏navigationBar
navigationController?.navigationBarHidden = false
}
private func setupUI(){
view.backgroundColor = UIColor.whiteColor()
navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: shareBtn), UIBarButtonItem(customView: loveBtn)]
view.addSubview(tableView)
}
private lazy var loveBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "navigationLoveNormal_22x20_"), forState: .Normal)
btn.addTarget(self, action: Selector("loveBtnClick:"), forControlEvents: .TouchUpInside)
btn.setBackgroundImage(UIImage(named: "navigation_liked_22x22_"), forState: .Selected)
btn.sizeToFit()
return btn
}()
private lazy var shareBtn: UIButton = UIButton(target: self, backgroundImage: "navigationShare_20x20_", action: Selector("shareBtnClick"))
private lazy var tableView: UITableView = {
let tv = UITableView(frame: ScreenBounds, style: .Plain)
tv.registerClass(SubjectSalonTableViewCell.self, forCellReuseIdentifier: SubjectSalonTableReuseIdentifier)
tv.registerClass(SubjectClassesTableViewCell.self, forCellReuseIdentifier: SubjectClassesTableReuseIdentifier)
tv.dataSource = self
tv.delegate = self
tv.separatorStyle = .None
return tv
}()
private lazy var tableHeadView: SubjectHeadView = SubjectHeadView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 2))
private lazy var tmpWebView: UIWebView = {
let wv = UIWebView(frame: CGRectMake(0, 0, self.view.frame.size.width, 2))
wv.alpha = 0
wv.delegate = self
wv.sizeToFit()
return wv
}()
//进度条
private lazy var progressBar: UIProgressView = {
let pb = UIProgressView()
pb.frame = CGRect(x: 0, y: 64, width: ScreenWidth, height: 1)
pb.backgroundColor = UIColor.whiteColor()
pb.progressTintColor = UIColor(red: 116.0/255.0, green: 213.0/255.0, blue: 53.0/255.0, alpha: 1.0)
return pb
}()
@objc func loveBtnClick(btn: UIButton){
btn.selected = !btn.selected
}
@objc func shareBtnClick(){
ShareTools.shareApp(self, shareText: nil)
}
deinit{
tmpWebView.delegate = nil
tmpWebView.stopLoading()
SVProgressHUD.dismiss()
}
}
//MARK: - UITableViewDataSource代理
extension SubjectViewController: UITableViewDataSource{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rdata?.itmes?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let item = rdata?.itmes![indexPath.row]
if item?.type == 1 {
let cell = tableView.dequeueReusableCellWithIdentifier(SubjectClassesTableReuseIdentifier, forIndexPath: indexPath) as! SubjectClassesTableViewCell
cell.item = item
return cell
}
let cell = tableView.dequeueReusableCellWithIdentifier(SubjectSalonTableReuseIdentifier, forIndexPath: indexPath) as! SubjectSalonTableViewCell
cell.item = item
return cell
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 140
}
}
//MARK: - UITableViewDelegate代理
extension SubjectViewController: UITableViewDelegate{
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
//释放选中效果
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let item = rdata?.itmes![indexPath.row]
if item?.type == 1{
guard let id = item?.classes?.id else{
alert("数据错误!")
return
}
let classesVC = ClassesViewController()
classesVC.classesId = id
navigationController?.pushViewController(classesVC, animated: true)
}else if item?.type == 2{
guard let id = item?.salon?.id else{
alert("数据错误!")
return
}
let salonVC = SalonViewController()
salonVC.salonId = id
navigationController?.pushViewController(salonVC, animated: true)
}
}
}
extension SubjectViewController: UIWebViewDelegate{
//为了解决UIWebView高度自适应
func webViewDidFinishLoad(webView: UIWebView) {
//客户端高度
let str = "document.body.offsetHeight"
let clientheightStr = webView.stringByEvaluatingJavaScriptFromString(str)
let height = CGFloat((clientheightStr! as NSString).floatValue) + 80
//移除多余的webView
tmpWebView.removeFromSuperview()
unowned let tmpSelf = self
tmpSelf.progressBar.progress = 1.0
UIView.animateWithDuration(1.3, animations: { () -> Void in
tmpSelf.view.layoutIfNeeded()
}) { (_) -> Void in
tmpSelf.progressBar.removeFromSuperview()
}
tableHeadView.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: height)
guard let data = rdata else{
SVProgressHUD.dismiss()
alert("获取数据失败")
return
}
tableHeadView.titleStrng = data.title
tableHeadView.urlString = data.content
tableView.tableHeaderView = tableHeadView
tableView.reloadData()
// SVProgressHUD.dismiss()
}
}
| mit | d6508971c59cab6334c6c043069bf14a | 36.945355 | 159 | 0.642569 | 5.002882 | false | false | false | false |
ZeeQL/ZeeQL3 | Tests/ZeeQLTests/SQLite3OGoAdaptorTests.swift | 1 | 5076 | //
// SQLite3OGoAdaptorTests.swift
// ZeeQL
//
// Created by Helge Hess on 06/03/2017.
// Copyright © 2017 ZeeZide GmbH. All rights reserved.
//
import Foundation
import XCTest
@testable import ZeeQL
class SQLite3OGoAdaptorTests: AdaptorOGoTestCase {
override var adaptor : Adaptor! {
XCTAssertNotNil(_adaptor)
return _adaptor
}
var _adaptor : SQLite3Adaptor = {
var pathToTestDB : String = {
#if ZEE_BUNDLE_RESOURCES
let bundle = Bundle(for: type(of: self) as! AnyClass)
let url = bundle.url(forResource: "OGo", withExtension: "sqlite3")
guard let path = url?.path else { return "OGo.sqlite3" }
return path
#else
let dataPath = lookupTestDataPath()
return "\(dataPath)/OGo.sqlite3"
#endif
}()
return SQLite3Adaptor(pathToTestDB)
}()
func testCount() throws {
let db = Database(adaptor: adaptor)
class OGoObject : ActiveRecord {
// TODO: actually add KVC to store the key in this var
var id : Int { return value(forKey: "id") as! Int }
}
class OGoCodeEntity<T: OGoObject> : CodeEntity<T> {
// add common attributes, and support them in reflection
let objectVersion = Info.Int(column: "object_version")
}
class Person : OGoObject, EntityType {
class Entity : OGoCodeEntity<Person> {
let table = "person"
let id = Info.Int(column: "company_id")
let isPerson = Info.Int(column: "is_person")
let login = Info.OptString(width: 50)
let isLocked = Info.Int(column: "is_locked")
let number = Info.String(width: 100)
let lastname = Info.OptString(column: "name")
let firstname : String? = nil
let middlename : String? = nil
}
static let fields = Entity()
static let entity : ZeeQL.Entity = fields
}
let persons = ActiveDataSource<Person>(database: db)
persons.fetchSpecification = Person
.where(Person.fields.login.like("*"))
.limit(4)
.order(by: Person.fields.login)
do {
let count = try persons.fetchCount()
if printResults {
print("got person count: #\(count)")
}
XCTAssert(count > 2)
}
catch {
XCTAssertNil(error, "catched error: \(error)")
}
}
func testFetchGlobalIDs() throws {
let db = Database(adaptor: adaptor)
class OGoObject : ActiveRecord {
// TODO: actually add KVC to store the key in this var
var id : Int { return value(forKey: "id") as! Int }
}
class OGoCodeEntity<T: OGoObject> : CodeEntity<T> {
// add common attributes, and support them in reflection
let objectVersion = Info.Int(column: "object_version")
}
class Person : OGoObject, EntityType {
class Entity : OGoCodeEntity<Person> {
let table = "person"
let id = Info.Int(column: "company_id")
let isPerson = Info.Int(column: "is_person")
let login = Info.OptString(width: 50)
let isLocked = Info.Int(column: "is_locked")
let number = Info.String(width: 100)
let lastname = Info.OptString(column: "name")
let firstname : String? = nil
let middlename : String? = nil
}
static let fields = Entity()
static let entity : ZeeQL.Entity = fields
}
let persons = ActiveDataSource<Person>(database: db)
persons.fetchSpecification = Person
.where(Person.fields.login.like("*"))
.limit(4)
.order(by: Person.fields.login)
do {
let gids = try persons.fetchGlobalIDs()
if printResults {
print("got person count: \(gids)")
}
XCTAssert(gids.count > 2)
// and now lets fetch the GIDs
let objects = try persons.fetchObjects(with: gids)
if printResults {
print("got persons: #\(objects.count)")
}
XCTAssertEqual(objects.count, gids.count)
}
catch {
XCTAssertNil(error, "catched error: \(error)")
}
}
// MARK: - Non-ObjC Swift Support
static var allTests = [
// super
( "testRawAdaptorChannelQuery", testRawAdaptorChannelQuery ),
( "testEvaluateQueryExpression", testEvaluateQueryExpression ),
( "testRawTypeSafeQuery", testRawTypeSafeQuery ),
( "testSimpleTX", testSimpleTX ),
( "testAdaptorDataSourceFindByID", testAdaptorDataSourceFindByID ),
( "testBasicReflection", testBasicReflection ),
( "testTableReflection", testTableReflection ),
( "testCodeSchema", testCodeSchema ),
( "testCodeSchemaWithJoinQualifier", testCodeSchemaWithJoinQualifier ),
( "testCodeSchemaWithRelshipPrefetch", testCodeSchemaWithRelshipPrefetch ),
( "testCodeSchemaWithTypedFetchSpec", testCodeSchemaWithTypedFetchSpec ),
// own
( "testCount", testCount ),
]
}
| apache-2.0 | 69a02028245842f7650d289d27d91ea4 | 30.918239 | 79 | 0.597635 | 4.246862 | false | true | false | false |
AdaptiveMe/adaptive-arp-api-lib-darwin | Pod/Classes/Sources.Api/AppContextBridge.swift | 1 | 5076 | /**
--| ADAPTIVE RUNTIME PLATFORM |----------------------------------------------------------------------------------------
(C) Copyright 2013-2015 Carlos Lozano Diez t/a Adaptive.me <http://adaptive.me>.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the
License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 . Unless required by appli-
-cable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing
permissions and limitations under the License.
Original author:
* Carlos Lozano Diez
<http://github.com/carloslozano>
<http://twitter.com/adaptivecoder>
<mailto:[email protected]>
Contributors:
* Ferran Vila Conesa
<http://github.com/fnva>
<http://twitter.com/ferran_vila>
<mailto:[email protected]>
* See source code files for contributors.
Release:
* @version v2.2.15
-------------------------------------------| aut inveniam viam aut faciam |--------------------------------------------
*/
import Foundation
/**
Interface for context management purposes
Auto-generated implementation of IAppContext specification.
*/
public class AppContextBridge : IAppContext {
/**
Group of API.
*/
private var apiGroup : IAdaptiveRPGroup = IAdaptiveRPGroup.Kernel
public func getAPIGroup() -> IAdaptiveRPGroup? {
return self.apiGroup
}
/**
API Delegate.
*/
private var delegate : IAppContext? = nil
/**
Constructor with delegate.
@param delegate The delegate implementing platform specific functions.
*/
public init(delegate : IAppContext?) {
self.delegate = delegate
}
/**
Get the delegate implementation.
@return IAppContext delegate that manages platform specific functions..
*/
public final func getDelegate() -> IAppContext? {
return self.delegate
}
/**
Set the delegate implementation.
@param delegate The delegate implementing platform specific functions.
*/
public final func setDelegate(delegate : IAppContext) {
self.delegate = delegate;
}
/**
The main application context. This should be cast to the platform specific implementation.
@return Object representing the specific singleton application context provided by the OS.
@since v2.0
*/
public func getContext() -> AnyObject? {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executing getContext...")
}
var result : AnyObject? = nil
if (self.delegate != nil) {
result = self.delegate!.getContext()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executed 'getContext' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextBridge no delegate for 'getContext'.")
}
}
return result
}
/**
The type of context provided by the getContext method.
@return Type of platform context.
@since v2.0
*/
public func getContextType() -> IOSType? {
// Start logging elapsed time.
let tIn : NSTimeInterval = NSDate.timeIntervalSinceReferenceDate()
let logger : ILogging? = AppRegistryBridge.sharedInstance.getLoggingBridge()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executing getContextType...")
}
var result : IOSType? = nil
if (self.delegate != nil) {
result = self.delegate!.getContextType()
if (logger != nil) {
logger!.log(ILoggingLogLevel.Debug, category: getAPIGroup()!.toString(), message: "AppContextBridge executed 'getContextType' in \(UInt(tIn.distanceTo(NSDate.timeIntervalSinceReferenceDate())*1000)) ms.")
}
} else {
if (logger != nil) {
logger!.log(ILoggingLogLevel.Error, category: getAPIGroup()!.toString(), message: "AppContextBridge no delegate for 'getContextType'.")
}
}
return result
}
}
/**
------------------------------------| Engineered with ♥ in Barcelona, Catalonia |--------------------------------------
*/
| apache-2.0 | 5cda8b2576486c2ac38545ef7b044f1d | 34.732394 | 220 | 0.611746 | 5.252588 | false | false | false | false |
lorentey/swift | test/ClangImporter/enum-anon.swift | 26 | 791 | // RUN: %target-swift-frontend -typecheck %s -enable-objc-interop -import-objc-header %S/Inputs/enum-anon.h -DDIAGS -verify
func testDiags() {
#if _runtime(_ObjC)
let us2 = USConstant2
#else
let us2: UInt16 = 0
#endif
let _: String = us2 // expected-error {{cannot convert value of type 'UInt16' to specified type 'String'}}
#if _runtime(_ObjC)
let usVar2 = USVarConstant2
#else
let usVar2: UInt16 = 0
#endif
let _: String = usVar2 // expected-error {{cannot convert value of type 'UInt16' to specified type 'String'}}
// The nested anonymous enum value should still have top-level scope, because
// that's how C works. It should also have the same type as the field (above).
let _: String = SR2511.SR2511B // expected-error {{type 'SR2511' has no member 'SR2511B'}}
}
| apache-2.0 | b20125274446dc59290c0695c169f621 | 34.954545 | 123 | 0.701643 | 3.337553 | false | false | false | false |
marcelobusico/reddit-ios-app | Reddit-App/Reddit-App/ListReddits/Presenter/ListRedditsPresenter.swift | 1 | 3570 | //
// ListRedditsPresenter.swift
// Reddit-App
//
// Created by Marcelo Busico on 13/2/17.
// Copyright © 2017 Busico. All rights reserved.
//
import UIKit
class ListRedditsPresenter {
// MARK: - Constants
private let pageSize = 50
// MARK: - Properties
private weak var view: ListRedditsViewProtocol?
private let serviceAdapter: RedditServiceAdapterProtocol
private var redditsList = [RedditModel]()
// MARK: - Initialization
init(view: ListRedditsViewProtocol, serviceAdapter: RedditServiceAdapterProtocol) {
self.view = view
self.serviceAdapter = serviceAdapter
}
// MARK: - Internal Methods
func start() {
if redditsList.isEmpty {
loadRedditsAsync(appendToCurrentRedditsList: false)
}
}
func refresh() {
loadRedditsAsync(appendToCurrentRedditsList: false)
}
func saveState(coder: NSCoder) {
coder.encode(redditsList, forKey: "redditsList")
}
func restoreState(coder: NSCoder) {
if let redditsList = coder.decodeObject(forKey: "redditsList") as? [RedditModel] {
self.redditsList = redditsList
}
}
func numberOfElements() -> Int {
return redditsList.count
}
func elementModel(forPosition position: Int) -> RedditModel? {
if position >= redditsList.count {
return nil
}
if position == (redditsList.count - 1) {
loadRedditsAsync(appendToCurrentRedditsList: true)
}
return redditsList[position]
}
func elementPosition(forName name: String) -> Int? {
return redditsList.index { (redditModel) -> Bool in
return redditModel.name == name
}
}
func loadThumbnailForModel(model: RedditModel,
onComplete: @escaping (UIImage?) -> Void) {
guard let thumbnailURL = model.thumbnailURL else {
onComplete(nil)
return
}
DispatchQueue.global().async {
self.serviceAdapter.downloadImage(withURL: thumbnailURL,
onComplete: { image in
DispatchQueue.main.async {
onComplete(image)
}
},
onError: { error in
DispatchQueue.main.async {
onComplete(nil)
}
}
)
}
}
func elementSelected(atPosition position: Int) {
guard let redditModel = elementModel(forPosition: position),
redditModel.imageURL != nil else {
return
}
view?.showDetailsScreen(forModel: redditModel)
}
// MARK: - Private Methods
private func loadRedditsAsync(appendToCurrentRedditsList: Bool) {
var afterName: String? = nil
if appendToCurrentRedditsList,
let lastReddit = redditsList.last {
afterName = lastReddit.name
}
self.view?.showLoading()
DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {
self.serviceAdapter.loadTopReddits(amount: self.pageSize, afterName: afterName,
onComplete: { redditsList in
if appendToCurrentRedditsList {
self.redditsList.append(contentsOf: redditsList)
} else {
self.redditsList = redditsList
}
DispatchQueue.main.async {
if let view = self.view {
view.hideLoading()
view.refreshRedditsList()
}
}
},
onError: { error in
print(error)
DispatchQueue.main.async {
if let view = self.view {
view.hideLoading()
view.displayMessage(title: "Error", message: "Error loading reddits. Please try again later.")
}
}
}
)
}
}
}
| apache-2.0 | e64f95cd3610564ad8ae6142908c332d | 24.133803 | 108 | 0.628467 | 4.677588 | false | false | false | false |
SandcastleApps/partyup | PartyUP/PartyRootController.swift | 1 | 15178 | //
// PartyRootController.swift
// PartyUP
//
// Created by Fritz Vander Heide on 2015-11-07.
// Copyright © 2015 Sandcastle Application Development. All rights reserved.
//
import UIKit
import LocationPickerViewController
import INTULocationManager
import CoreLocation
import SCLAlertView
import Flurry_iOS_SDK
import SCLAlertView
class PartyRootController: UIViewController {
@IBOutlet weak var ackButton: UIButton!
@IBOutlet weak var cameraButton: UIButton! {
didSet {
cameraButton?.enabled = here != nil
}
}
@IBOutlet weak var reminderButton: UIButton!
private var partyPicker: PartyPickerController!
private var here: PartyPlace? {
didSet {
cameraButton?.enabled = here != nil
}
}
private var there: PartyPlace?
private var adRefreshTimer: NSTimer?
private var locationRequestId: INTULocationRequestID = 0
private var favoriting: SCLAlertViewResponder?
private lazy var stickyTowns: [Address] = {
let raw = NSUserDefaults.standardUserDefaults().arrayForKey(PartyUpPreferences.StickyTowns)
let plist = raw as? [[NSObject:AnyObject]]
return plist?.flatMap { Address(plist: $0) } ?? [Address]()
}()
override func viewDidLoad() {
super.viewDidLoad()
refreshReminderButton()
resolveLocalPlacemark()
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: #selector(PartyRootController.observeApplicationBecameActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.refreshSelectedRegion), name: PartyPickerController.VenueRefreshRequest, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.observeCityUpdateNotification(_:)), name: PartyPlace.CityUpdateNotification, object: nil)
nc.addObserver(self, selector: #selector(PartyRootController.refreshReminderButton), name: NSUserDefaultsDidChangeNotification, object: nil)
nc.addObserverForName(PartyUpConstants.RecordVideoNotification, object: nil, queue: nil) {_ in
if self.shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
self.performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
nc.addObserver(self, selector: #selector(PartyRootController.bookmarkLocation), name: PartyUpConstants.FavoriteLocationNotification, object: nil)
nc.addObserverForName(AuthenticationManager.AuthenticationStatusChangeNotification, object: nil, queue: NSOperationQueue.mainQueue()) { note in
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey(PartyUpPreferences.PromptAuthentication) {
if let new = AuthenticationState(rawValue: note.userInfo?["new"] as! Int), let old = AuthenticationState(rawValue: note.userInfo?["old"] as! Int) where new == .Unauthenticated && old == .Transitioning {
let flow = AuthenticationFlow.shared
let allowPutoff = defaults.boolForKey(PartyUpPreferences.AllowAuthenticationPutoff)
flow.setPutoffs( allowPutoff ?
[NSLocalizedString("Miss out on Facebook Posts", comment: "First ignore Facebook button")] : [])
flow.addAction { [weak self] manager, cancelled in
if let me = self {
if allowPutoff { defaults.setBool(false, forKey: PartyUpPreferences.PromptAuthentication) }
me.presentTutorial()
}
}
flow.startOnController(self)
}
}
}
adRefreshTimer = NSTimer.scheduledTimerWithTimeInterval(3600, target: self, selector: #selector(PartyRootController.refreshAdvertising), userInfo: nil, repeats: true)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
presentTutorial()
}
func presentTutorial() {
if !NSUserDefaults.standardUserDefaults().boolForKey(PartyUpPreferences.PromptAuthentication) {
tutorial.start(self)
}
}
func refreshSelectedRegion(note: NSNotification) {
if let adjust = note.userInfo?["adjustLocation"] as? Bool where adjust {
chooseLocation()
} else {
let force = (note.userInfo?["forceUpdate"] as? Bool) ?? false
if there == nil {
resolveLocalPlacemark()
} else {
fetchPlaceVenues(there, force: force)
}
}
}
func refreshAdvertising() {
let cities = [here,there].flatMap { $0?.location }
Advertisement.refresh(cities)
}
func resolveLocalPlacemark() {
partyPicker.isFetching = true
locationRequestId = INTULocationManager.sharedInstance().requestLocationWithDesiredAccuracy(.City, timeout: 60) { (location, accuracy, status) in
self.locationRequestId = 0
if status == .Success {
Address.addressForCoordinates(location.coordinate) { address, error in
if let address = address where error == nil {
self.here = PartyPlace(location: address)
if self.there == nil {
self.there = self.here
}
self.fetchPlaceVenues(self.here)
Flurry.setLatitude(location!.coordinate.latitude, longitude: location!.coordinate.longitude, horizontalAccuracy: Float(location!.horizontalAccuracy), verticalAccuracy: Float(location!.verticalAccuracy))
} else {
self.cancelLocationLookup()
alertFailureWithTitle(NSLocalizedString("Failed to find you", comment: "Location determination failure hud title"), andDetail: NSLocalizedString("Failed to lookup your city.", comment: "Hud message for failed locality lookup"))
Flurry.logError("City_Locality_Failed", message: error?.localizedDescription, error: error)
}
}
} else {
self.cancelLocationLookup()
alertFailureWithLocationServicesStatus(status)
Flurry.logError("City_Determination_Failed", message: "Reason \(status.rawValue)", error: nil)
}
}
}
func cancelLocationLookup() {
here = nil
partyPicker.parties = self.there
partyPicker.isFetching = false
}
func fetchPlaceVenues(place: PartyPlace?, force: Bool = false) {
if let place = place {
partyPicker.isFetching = true
if let categories = NSUserDefaults.standardUserDefaults().stringForKey(PartyUpPreferences.VenueCategories) {
let radius = NSUserDefaults.standardUserDefaults().integerForKey(PartyUpPreferences.ListingRadius)
place.fetch(radius, categories: categories, force: force)
}
}
}
func refreshReminderButton() {
if let settings = UIApplication.sharedApplication().currentUserNotificationSettings() where settings.types != .None {
let defaults = NSUserDefaults.standardUserDefaults()
reminderButton.hidden = !defaults.boolForKey(PartyUpPreferences.RemindersInterface)
switch defaults.integerForKey(PartyUpPreferences.RemindersInterval) {
case 60:
reminderButton.setTitle("60m 🔔", forState: .Normal)
case 30:
reminderButton.setTitle("30m 🔔", forState: .Normal)
default:
reminderButton.setTitle("Off 🔕", forState: .Normal)
}
}
}
func observeCityUpdateNotification(note: NSNotification) {
if let city = note.object as? PartyPlace {
partyPicker.isFetching = city.isFetching
if city.lastFetchStatus.error == nil {
self.partyPicker.parties = self.there
} else {
alertFailureWithTitle(NSLocalizedString("Venue Query Failed", comment: "Hud title failed to fetch venues from google"),
andDetail: NSLocalizedString("The venue query failed.", comment: "Hud detail failed to fetch venues from google"))
}
}
}
deinit {
adRefreshTimer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Navigation
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if (tutorial.tutoring || presentedViewController != nil || navigationController?.topViewController != self) && identifier != "Party Embed Segue" {
return false
}
if identifier == "Bake Sample Segue" {
if !AuthenticationManager.shared.isLoggedIn {
AuthenticationFlow.shared.startOnController(self).addAction { manager, cancelled in
if manager.isLoggedIn {
if self.shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
self.performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
}
return false
}
}
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "Party Embed Segue" {
partyPicker = segue.destinationViewController as! PartyPickerController
partyPicker.parties = nil
}
if segue.identifier == "Bake Sample Segue" {
let bakerVC = segue.destinationViewController as! BakeRootController
bakerVC.venues = here?.venues.flatMap{ $0 } ?? [Venue]()
bakerVC.pregame = here?.pregame
}
}
@IBAction func favoriteLocation(sender: UILongPressGestureRecognizer) {
bookmarkLocation()
}
func bookmarkLocation() {
if var place = there?.location where favoriting == nil {
let alert = SCLAlertView()
let nameField = alert.addTextField(NSLocalizedString("Location Name", comment: "Favorite location text title"))
alert.addButton(NSLocalizedString("Add Favorite", comment: "Add favorite location button")) {
place.identifier = nameField.text
self.stickyTowns.append(place)
NSUserDefaults.standardUserDefaults().setObject(self.stickyTowns.map { $0.plist }, forKey: PartyUpPreferences.StickyTowns)
self.there?.name = place.identifier
self.partyPicker.locationFavorited()
}
favoriting = alert.showEdit(NSLocalizedString("Favorite Location", comment: "Favorite location title"),
subTitle: NSLocalizedString("Add selected location as a favorite.", comment: "Favorite location subtitle"),
closeButtonTitle: NSLocalizedString("Cancel", comment: "Favorite location cancel"),
colorStyle: 0xF45E63)
favoriting?.setDismissBlock { self.favoriting = nil }
}
}
@IBAction func chooseLocation() {
partyPicker.defocusSearch()
let locationPicker = LocationPicker()
let locationNavigator = UINavigationController(rootViewController: locationPicker)
locationPicker.title = NSLocalizedString("Popular Party Places", comment: "Location picker title")
locationPicker.searchBarPlaceholder = NSLocalizedString("Search for place or address", comment: "Location picker search bar")
locationPicker.setColors(UIColor(r: 247, g: 126, b: 86, alpha: 255))
locationPicker.locationDeniedHandler = { _ in
var status: INTULocationStatus
switch INTULocationManager.locationServicesState() {
case .Denied:
status = .ServicesDenied
case .Restricted:
status = .ServicesRestricted
case .Disabled:
status = .ServicesDisabled
case .NotDetermined:
status = .ServicesNotDetermined
case .Available:
status = .Error
}
alertFailureWithLocationServicesStatus(status)
}
locationPicker.pickCompletion = { [weak locationPicker] picked in
let name : String? = picked.mapItem.phoneNumber == "Yep" ? picked.name : nil
let address = Address(coordinate: picked.mapItem.placemark.coordinate, mapkitAddress: picked.addressDictionary!, name: name)
self.there = PartyPlace(location: address)
if picked.mapItem.name == "No matter where you go, there you are!" {
self.here = self.there
}
self.partyPicker.parties = self.there
self.fetchPlaceVenues(self.there)
Flurry.logEvent("Selected_Town", withParameters: ["town" : address.debugDescription])
locationPicker?.dismissViewControllerAnimated(true, completion: nil)
}
locationPicker.selectCompletion = locationPicker.pickCompletion
locationPicker.alternativeLocationEditable = true
locationPicker.deleteCompletion = { picked in
if let index = self.stickyTowns.indexOf({ $0.name == picked.name && ($0.coordinate.latitude == picked.coordinate?.latitude && $0.coordinate.longitude == picked.coordinate?.longitude)}) {
self.stickyTowns.removeAtIndex(index)
NSUserDefaults.standardUserDefaults().setObject(self.stickyTowns.map { $0.plist }, forKey: PartyUpPreferences.StickyTowns)
}
}
locationPicker.addBarButtons(UIBarButtonItem(title: "", style: .Done, target: nil, action: nil))
locationPicker.alternativeLocations = stickyTowns.map {
let item = LocationItem(coordinate: (latitude: $0.coordinate.latitude, longitude: $0.coordinate.longitude), addressDictionary: $0.appleAddressDictionary)
item.mapItem.phoneNumber = "Yep"
return item
}
presentViewController(locationNavigator, animated: true, completion: nil)
}
@IBAction func setReminders(sender: UIButton) {
let defaults = NSUserDefaults.standardUserDefaults()
var interval = defaults.integerForKey(PartyUpPreferences.RemindersInterval)
interval = (interval + 30) % 90
defaults.setInteger(interval, forKey: PartyUpPreferences.RemindersInterval)
refreshReminderButton()
if let delegate = UIApplication.sharedApplication().delegate as? AppDelegate {
delegate.scheduleReminders()
}
}
@IBAction func sequeFromBaking(segue: UIStoryboardSegue) {
}
@IBAction func segueFromAcknowledgements(segue: UIStoryboardSegue) {
}
func observeApplicationBecameActive() {
let defaults = NSUserDefaults.standardUserDefaults()
presentTutorial()
if here == nil {
if INTULocationManager.locationServicesState() == .Available && locationRequestId == 0 {
resolveLocalPlacemark()
}
} else if defaults.boolForKey(PartyUpPreferences.CameraJump) && AuthenticationManager.shared.isLoggedIn {
if shouldPerformSegueWithIdentifier("Bake Sample Segue", sender: nil) {
performSegueWithIdentifier("Bake Sample Segue", sender: nil)
}
}
}
//MARK: - Tutorial
private enum CoachIdentifier: Int {
case Greeting = -1000, City = 1001, About, Camera, Reminder
}
private static let availableCoachMarks = [
TutorialMark(identifier: CoachIdentifier.Greeting.rawValue, hint: NSLocalizedString("Welcome to the PartyUP City Hub!\nThis is where you find the parties.\nTap a place to see what is going on!", comment: "City hub welcome coachmark")),
TutorialMark(identifier: CoachIdentifier.Camera.rawValue, hint: NSLocalizedString("Take video of your\nnightlife adventures!", comment: "City hub camera coachmark")),
TutorialMark(identifier: CoachIdentifier.City.rawValue, hint: NSLocalizedString("See what is going on in\nother party cities.", comment: "City hub location selector coachmark")),
TutorialMark(identifier: CoachIdentifier.Reminder.rawValue, hint: NSLocalizedString("You want to remember to PartyUP?\nSet reminders here.", comment: "City hub reminder button coachmark")),
TutorialMark(identifier: CoachIdentifier.About.rawValue, hint: NSLocalizedString("Learn more about PartyUP!", comment: "City hub acknowledgements coachmark"))]
private let tutorial = TutorialOverlayManager(marks: PartyRootController.availableCoachMarks)
}
| mit | 02b89bb5389529104c20c1b9be63e7ec | 41.968839 | 243 | 0.72053 | 4.592189 | false | false | false | false |
thatseeyou/SpriteKitExamples.playground | Pages/SKEmitterNode.xcplaygroundpage/Contents.swift | 1 | 1255 | /*:
### Particle file을 Xcode를 통해서 생성한 후에 읽을 수 있다.
- Fire.sks 생성하기 : File/New/File에서 Resource/Particle File 선택에서 생성 후 끌어서 Resources 폴더에 놓으면 된다.
*/
import UIKit
import SpriteKit
class GameScene: SKScene {
var contentCreated = false
override func didMove(to view: SKView) {
if self.contentCreated != true {
let fireNode = SKEmitterNode(fileNamed: "Fire.sks")!
fireNode.position = CGPoint(x: self.frame.midX, y: self.frame.midY)
addChild(fireNode)
self.contentCreated = true
}
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// add SKView
do {
let skView = SKView(frame:CGRect(x: 0, y: 0, width: 320, height: 480))
skView.showsFPS = true
//skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
let scene = GameScene(size: CGSize(width: 320, height: 480))
scene.scaleMode = .aspectFit
skView.presentScene(scene)
self.view.addSubview(skView)
}
}
}
PlaygroundHelper.showViewController(ViewController())
| isc | 87e7dadc6d485da6b83f2546a00f4294 | 25.75 | 93 | 0.612574 | 3.962963 | false | false | false | false |
AndrewBennet/readinglist | ReadingList_Foundation/UI/TextBoxAlert.swift | 1 | 1657 | import Foundation
import UIKit
/**
A UIAlertController with a single text field input, and an OK and Cancel action. The OK button is disabled
when the text box is empty or whitespace.
*/
public class TextBoxAlert: UIAlertController {
var textValidator: ((String?) -> Bool)?
public convenience init(title: String, message: String? = nil, initialValue: String? = nil, placeholder: String? = nil,
keyboardAppearance: UIKeyboardAppearance = .default, keyboardType: UIKeyboardType = .default, textValidator: ((String?) -> Bool)? = nil, onCancel: (() -> Void)? = nil, onOK: @escaping (String?) -> Void) {
self.init(title: title, message: message, preferredStyle: .alert)
self.textValidator = textValidator
addTextField { [unowned self] textField in
textField.addTarget(self, action: #selector(self.textFieldDidChange), for: .editingChanged)
textField.autocapitalizationType = .words
textField.keyboardType = keyboardType
textField.keyboardAppearance = keyboardAppearance
textField.placeholder = placeholder
textField.text = initialValue
}
addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
onCancel?()
})
let okAction = UIAlertAction(title: "OK", style: .default) { _ in
onOK(self.textFields![0].text)
}
okAction.isEnabled = textValidator?(initialValue) ?? true
addAction(okAction)
}
@objc func textFieldDidChange(_ textField: UITextField) {
actions[1].isEnabled = textValidator?(textField.text) ?? true
}
}
| gpl-3.0 | 2f929f374ff94694198de77273f62b12 | 40.425 | 232 | 0.65178 | 5.021212 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/SharedViews/UIView+ShimmerLoading.swift | 1 | 3305 | import Foundation
import Library
import ObjectiveC
import UIKit
private enum ShimmerConstants {
enum Locations {
static let start: [NSNumber] = [-1.0, -0.5, 0.0]
static let end: [NSNumber] = [1.0, 1.5, 2.0]
}
enum Animation {
static let movingAnimationDuration: CFTimeInterval = 1.25
static let delayBetweenAnimationLoops: CFTimeInterval = 0.3
}
}
private struct AssociatedKeys {
static var shimmerLayers = "shimmerLayers"
}
protocol ShimmerLoading: AnyObject {
func shimmerViews() -> [UIView]
func startLoading()
func stopLoading()
}
extension ShimmerLoading where Self: UIView {
private var shimmerLayers: [CAGradientLayer] {
get {
guard
let value = objc_getAssociatedObject(self, &AssociatedKeys.shimmerLayers) as? [CAGradientLayer]
else { return [] }
return value
}
set(newValue) {
objc_setAssociatedObject(
self,
&AssociatedKeys.shimmerLayers,
newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
// MARK: - Accessors
func startLoading() {
self.shimmerViews()
.forEach { view in
let gradientLayer = shimmerGradientLayer(with: view.bounds)
let animation = shimmerAnimation()
let animationGroup = shimmerAnimationGroup(with: animation)
gradientLayer.add(animationGroup, forKey: animation.keyPath)
view.layer.addSublayer(gradientLayer)
self.shimmerLayers.append(gradientLayer)
}
}
func stopLoading() {
self.shimmerLayers.forEach { $0.removeFromSuperlayer() }
}
func layoutGradientLayers() {
self.layoutIfNeeded()
self.shimmerLayers.forEach { layer in
layer.frame = layer.superlayer?.bounds ?? .zero
layer.setNeedsLayout()
}
}
}
private func shimmerGradientLayer(with frame: CGRect) -> CAGradientLayer {
let gradientBackgroundColor: CGColor = UIColor(white: 0.85, alpha: 1.0).cgColor
let gradientMovingColor: CGColor = UIColor(white: 0.75, alpha: 1.0).cgColor
let gradientLayer = CAGradientLayer()
gradientLayer.frame = frame
gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)
gradientLayer.colors = [
gradientBackgroundColor,
gradientMovingColor,
gradientBackgroundColor
]
gradientLayer.locations = ShimmerConstants.Locations.start
return gradientLayer
}
private func shimmerAnimation() -> CABasicAnimation {
let locationsKeyPath = \CAGradientLayer.locations
let animation = CABasicAnimation(keyPath: locationsKeyPath._kvcKeyPathString)
animation.fromValue = ShimmerConstants.Locations.start
animation.toValue = ShimmerConstants.Locations.end
animation.duration = ShimmerConstants.Animation.movingAnimationDuration
animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
return animation
}
private func shimmerAnimationGroup(with animation: CABasicAnimation) -> CAAnimationGroup {
let animationGroup = CAAnimationGroup()
animationGroup.duration = ShimmerConstants.Animation.movingAnimationDuration
+ ShimmerConstants.Animation.delayBetweenAnimationLoops
animationGroup.animations = [animation]
animationGroup.repeatCount = .infinity
animationGroup.beginTime = CACurrentMediaTime()
return animationGroup
}
| apache-2.0 | 3c73f641692fb5ee94b5f8380ec18ecb | 26.773109 | 103 | 0.731014 | 4.803779 | false | false | false | false |
uasys/swift | test/SILGen/writeback.swift | 2 | 5798 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen %s | %FileCheck %s
struct Foo {
mutating // used to test writeback.
func foo() {}
subscript(x: Int) -> Foo {
get {
return Foo()
}
set {}
}
}
var x: Foo {
get {
return Foo()
}
set {}
}
var y: Foo {
get {
return Foo()
}
set {}
}
var z: Foo {
get {
return Foo()
}
set {}
}
var readonly: Foo {
get {
return Foo()
}
}
func bar(x x: inout Foo) {}
// Writeback to value type 'self' argument
x.foo()
// CHECK: [[FOO:%.*]] = function_ref @_T09writeback3FooV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]]
// CHECK: apply [[FOO]]([[X_TEMP]]) : $@convention(method) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
// Writeback to inout argument
bar(x: &x)
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X_TEMP:%.*]] = alloc_stack $Foo
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[X:%.*]] = apply [[GET_X]]() : $@convention(thin) () -> Foo
// CHECK: store [[X]] to [trivial] [[X_TEMP]] : $*Foo
// CHECK: apply [[BAR]]([[X_TEMP]]) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[X1:%.*]] = load [trivial] [[X_TEMP]] : $*Foo
// CHECK: [[SET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
// CHECK: apply [[SET_X]]([[X1]]) : $@convention(thin) (Foo) -> ()
// CHECK: dealloc_stack [[X_TEMP]] : $*Foo
func zang(x x: Foo) {}
// No writeback for pass-by-value argument
zang(x: x)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback1xAA3FooVvs
zang(x: readonly)
// CHECK: function_ref @_T09writeback4zangyAA3FooV1x_tF : $@convention(thin) (Foo) -> ()
// CHECK-NOT: @_T09writeback8readonlyAA3FooVvs
func zung() -> Int { return 0 }
// Ensure that subscripts are only evaluated once.
bar(x: &x[zung()])
// CHECK: [[BAR:%.*]] = function_ref @_T09writeback3baryAA3FooVz1x_tF : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[ZUNG:%.*]] = function_ref @_T09writeback4zungSiyF : $@convention(thin) () -> Int
// CHECK: [[INDEX:%.*]] = apply [[ZUNG]]() : $@convention(thin) () -> Int
// CHECK: [[GET_X:%.*]] = function_ref @_T09writeback1xAA3FooVvg : $@convention(thin) () -> Foo
// CHECK: [[GET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}ig : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[GET_SUBSCRIPT]]([[INDEX]], {{%.*}}) : $@convention(method) (Int, Foo) -> Foo
// CHECK: apply [[BAR]]({{%.*}}) : $@convention(thin) (@inout Foo) -> ()
// CHECK: [[SET_SUBSCRIPT:%.*]] = function_ref @_T09writeback3FooV{{[_0-9a-zA-Z]*}}is : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: apply [[SET_SUBSCRIPT]]({{%.*}}, [[INDEX]], {{%.*}}) : $@convention(method) (Foo, Int, @inout Foo) -> ()
// CHECK: function_ref @_T09writeback1xAA3FooVvs : $@convention(thin) (Foo) -> ()
protocol Fungible {}
extension Foo : Fungible {}
var addressOnly: Fungible {
get {
return Foo()
}
set {}
}
func funge(x x: inout Fungible) {}
funge(x: &addressOnly)
// CHECK: [[FUNGE:%.*]] = function_ref @_T09writeback5fungeyAA8Fungible_pz1x_tF : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[TEMP:%.*]] = alloc_stack $Fungible
// CHECK: [[GET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvg : $@convention(thin) () -> @out Fungible
// CHECK: apply [[GET]]([[TEMP]]) : $@convention(thin) () -> @out Fungible
// CHECK: apply [[FUNGE]]([[TEMP]]) : $@convention(thin) (@inout Fungible) -> ()
// CHECK: [[SET:%.*]] = function_ref @_T09writeback11addressOnlyAA8Fungible_pvs : $@convention(thin) (@in Fungible) -> ()
// CHECK: apply [[SET]]([[TEMP]]) : $@convention(thin) (@in Fungible) -> ()
// CHECK: dealloc_stack [[TEMP]] : $*Fungible
// Test that writeback occurs with generic properties.
// <rdar://problem/16525257>
protocol Runcible {
associatedtype Frob: Frobable
var frob: Frob { get set }
}
protocol Frobable {
associatedtype Anse
var anse: Anse { get set }
}
// CHECK-LABEL: sil hidden @_T09writeback12test_generic{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK: witness_method $Runce, #Runcible.frob!materializeForSet.1
func test_generic<Runce: Runcible>(runce runce: inout Runce, anse: Runce.Frob.Anse) {
runce.frob.anse = anse
}
// We should *not* write back when referencing decls or members as rvalues.
// <rdar://problem/16530235>
// CHECK-LABEL: sil hidden @_T09writeback15loadAddressOnlyAA8Fungible_pyF : $@convention(thin) () -> @out Fungible {
func loadAddressOnly() -> Fungible {
// CHECK: function_ref writeback.addressOnly.getter
// CHECK-NOT: function_ref writeback.addressOnly.setter
return addressOnly
}
// CHECK-LABEL: sil hidden @_T09writeback10loadMember{{[_0-9a-zA-Z]*}}F
// CHECK: witness_method $Runce, #Runcible.frob!getter.1
// CHECK: witness_method $Runce.Frob, #Frobable.anse!getter.1
// CHECK-NOT: witness_method $Runce.Frob, #Frobable.anse!setter.1
// CHECK-NOT: witness_method $Runce, #Runcible.frob!setter.1
func loadMember<Runce: Runcible>(runce runce: Runce) -> Runce.Frob.Anse {
return runce.frob.anse
}
| apache-2.0 | bb7eeb4b289de557025889100d48beee | 36.166667 | 137 | 0.615557 | 3.183965 | false | false | false | false |
jackpal/smallpt-swift | smallpt.swift | 1 | 8358 | #!/usr/bin/env xcrun swift -O
// Smallpt in swift
// Based on http://www.kevinbeason.com/smallpt/
import Foundation
class OutputStream : OutputStreamType {
let handle : NSFileHandle
init(handle : NSFileHandle) {
self.handle = handle
}
func write(string: String) {
if let asUTF8 = string.dataUsingEncoding(NSUTF8StringEncoding) {
handle.writeData(asUTF8)
}
}
}
class StandardErrorOutputStream: OutputStream {
init() {
let stderr = NSFileHandle.fileHandleWithStandardError()
super.init(handle:stderr)
}
}
class FileStream : OutputStream {
init(path : String) {
let d = NSFileManager.defaultManager()
d.createFileAtPath(path, contents: nil, attributes: nil)
let h = NSFileHandle(forWritingAtPath: path)
super.init(handle:h!)
}
}
let stderr = StandardErrorOutputStream()
struct Vec {
let x, y, z : Double
init() { self.init(x:0, y:0, z:0) }
init(x : Double, y : Double, z: Double){ self.x=x; self.y=y; self.z=z; }
func length() -> Double { return sqrt(x*x+y*y+z*z) }
func norm() -> Vec { return self * (1/self.length()) }
func dot(b : Vec) -> Double { return x*b.x+y*b.y+z*b.z }
};
func +(a :Vec, b:Vec) -> Vec { return Vec(x:a.x+b.x, y:a.y+b.y, z:a.z+b.z) }
func -(a :Vec, b:Vec) -> Vec { return Vec(x:a.x-b.x, y:a.y-b.y, z:a.z-b.z) }
func *(a :Vec, b : Double) -> Vec { return Vec(x:a.x*b, y:a.y*b, z:a.z*b) }
func *(a :Vec, b : Vec) -> Vec { return Vec(x:a.x*b.x, y:a.y*b.y, z:a.z*b.z) }
// cross product:
func %(a :Vec, b : Vec) -> Vec{
return Vec(x:a.y*b.z-a.z*b.y, y:a.z*b.x-a.x*b.z, z:a.x*b.y-a.y*b.x)
}
struct Ray { let o, d : Vec; init(o : Vec, d : Vec) {self.o = o; self.d = d}}
enum Refl_t { case DIFF; case SPEC; case REFR } // material types, used in radiance()
struct Sphere {
let rad : Double // radius
let p, e, c : Vec // position, emission, color
let refl : Refl_t // reflection type (DIFFuse, SPECular, REFRactive)
init(rad :Double, p: Vec, e: Vec, c: Vec, refl: Refl_t) {
self.rad = rad; self.p = p; self.e = e; self.c = c; self.refl = refl; }
func intersect(r: Ray) -> Double { // returns distance, 0 if nohit
let op = p-r.o // Solve t^2*d.d + 2*t*(o-p).d + (o-p).(o-p)-R^2 = 0
let eps = 1e-4
let b = op.dot(r.d)
let det = b*b-op.dot(op)+rad*rad
if (det<0) {
return 0
}
let det2=sqrt(det)
let t=b-det2
if t > eps {
return t
}
let t2 = b+det2
if t2 > eps {return t2}
return 0
}
}
let spheres :[Sphere] = [//Scene: radius, position, emission, color, material
Sphere(rad:1e5, p:Vec(x: 1e5+1,y:40.8,z:81.6), e:Vec(), c:Vec(x:0.75,y:0.25,z:0.25), refl:Refl_t.DIFF),//Left
Sphere(rad:1e5, p:Vec(x:-1e5+99,y:40.8,z:81.6),e:Vec(), c:Vec(x:0.25,y:0.25,z:0.75), refl:Refl_t.DIFF),//Rght
Sphere(rad:1e5, p:Vec(x:50,y:40.8,z: 1e5), e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Back
Sphere(rad:1e5, p:Vec(x:50,y:40.8,z:-1e5+170), e:Vec(), c:Vec(), refl:Refl_t.DIFF),//Frnt
Sphere(rad:1e5, p:Vec(x:50,y: 1e5,z: 81.6), e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Botm
Sphere(rad:1e5, p:Vec(x:50,y:-1e5+81.6,z:81.6),e:Vec(), c:Vec(x:0.75,y:0.75,z:0.75), refl:Refl_t.DIFF),//Top
Sphere(rad:16.5,p:Vec(x:27,y:16.5,z:47), e:Vec(), c:Vec(x:1,y:1,z:1)*0.999, refl:Refl_t.SPEC),//Mirr
Sphere(rad:16.5,p:Vec(x:73,y:16.5,z:78), e:Vec(), c:Vec(x:1,y:1,z:1)*0.999, refl:Refl_t.REFR),//Glas
Sphere(rad:600, p:Vec(x:50,y:681.6-0.27,z:81.6),e:Vec(x:12,y:12,z:12), c:Vec(), refl:Refl_t.DIFF) //Lite
]
func clamp(x : Double) -> Double { return x < 0 ? 0 : x > 1 ? 1 : x; }
func toInt(x : Double) -> Int { return Int(pow(clamp(x),1/2.2)*255+0.5); }
func intersect(r : Ray, inout t: Double, inout id: Int) -> Bool {
let n = spheres.count
let inf = 1e20
t = inf
for (var i = n-1; i >= 0; i--) {
let d = spheres[i].intersect(r)
if (d != 0.0 && d<t){
t=d
id=i
}
}
return t<inf
}
struct drand {
let pbuffer = UnsafeMutablePointer<UInt16>.alloc(3)
init(a : UInt16) {
pbuffer[2] = a
}
func next() -> Double { return erand48(pbuffer) }
}
func radiance(r: Ray, depthIn: Int, Xi : drand) -> Vec {
var t : Double = 0 // distance to intersection
var id : Int = 0 // id of intersected object
if (!intersect(r, &t, &id)) {return Vec() } // if miss, return black
let obj = spheres[id] // the hit object
let x=r.o+r.d*t
let n=(x-obj.p).norm()
let nl = (n.dot(r.d) < 0) ? n : n * -1
var f=obj.c
let p = f.x > f.y && f.x > f.z ? f.x : f.y > f.z ? f.y : f.z; // max refl
let depth = depthIn+1
// Russian Roulette:
if (depth>5) {
// Limit depth to 150 to avoid stack overflow.
if (depth < 150 && Xi.next()<p) {
f=f*(1/p)
} else {
return obj.e
}
}
switch (obj.refl) {
case Refl_t.DIFF: // Ideal DIFFUSE reflection
let r1=2*M_PI*Xi.next(), r2=Xi.next(), r2s=sqrt(r2);
let w = nl
let u = ((fabs(w.x)>0.1 ? Vec(x:0, y:1, z:0) : Vec(x:1, y:0, z:0)) % w).norm()
let v = w % u
let d = (u*cos(r1)*r2s + v*sin(r1)*r2s + w*sqrt(1-r2)).norm()
return obj.e + f * radiance(Ray(o: x, d:d), depth, Xi)
case Refl_t.SPEC: // Ideal SPECULAR reflection
return obj.e + f * (radiance(Ray(o:x, d:r.d-n*2*n.dot(r.d)), depth, Xi))
case Refl_t.REFR:
let reflRay = Ray(o:x, d:r.d-n*2*n.dot(r.d)) // Ideal dielectric REFRACTION
let into = n.dot(nl)>0 // Ray from outside going in?
let nc = 1, nt=1.5
let nnt = into ? Double(nc) / nt : nt / Double(nc)
let ddn = r.d.dot(nl)
let cos2t=1-nnt*nnt*(1-ddn*ddn)
if (cos2t<0) { // Total internal reflection
return obj.e + f * radiance(reflRay, depth, Xi)
}
let tdir = (r.d * nnt - n * ((into ? 1 : -1)*(ddn*nnt+sqrt(cos2t)))).norm()
let a = nt-Double(nc), b = nt+Double(nc), R0 = a*a/(b*b), c = 1-(into ? -ddn : tdir.dot(n))
let Re=R0+(1-R0)*c*c*c*c*c,Tr=1-Re,P=0.25+0.5*Re,RP=Re/P,TP=Tr/(1-P)
return obj.e + f * (depth>2 ? (Xi.next()<P ? // Russian roulette
radiance(reflRay,depth,Xi) * RP : radiance(Ray(o: x, d: tdir),depth,Xi)*TP) :
radiance(reflRay,depth,Xi) * Re + radiance(Ray(o: x, d: tdir),depth,Xi)*Tr);
}
}
func main() {
let mainQueue = dispatch_get_main_queue()
dispatch_async(mainQueue) {
let argc = C_ARGC, argv = C_ARGV
let w=1024, h=768
// let w = 160, h = 120
let samps = argc==2 ? Int(atoi(argv[1])/4) : 1 // # samples
let cam = Ray(o:Vec(x:50,y:52,z:295.6), d:Vec(x:0,y:-0.042612,z:-1).norm()) // cam pos, dir
let cx = Vec(x:Double(w) * 0.5135 / Double(h), y:0, z:0)
let cy = (cx % cam.d).norm()*0.5135
var c = Array<Vec>(count:w*h, repeatedValue:Vec())
let globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_apply(UInt(h), globalQueue) {
let y = Int($0)
let Xi = drand(a:UInt16(0xffff & (y * y * y)))
let spp = samps*4
let percent = 100.0 * Double(y)/Double(h-1)
stderr.write(String(format:"\rRendering (%d spp) %.2f%%", spp, percent))
for (var x = 0; x < w; x++) { // Loop cols
let i=(h-y-1)*w+x
var r = Vec()
for (var sy=0; sy<2; sy++) { // 2x2 subpixel rows
for (var sx=0; sx<2; sx++) { // 2x2 subpixel cols
for (var s=0; s < samps; s++) {
let r1=2*Xi.next(), dx=r1<1 ? sqrt(r1)-1: 1-sqrt(2-r1)
let r2=2*Xi.next(), dy=r2<1 ? sqrt(r2)-1: 1-sqrt(2-r2)
let part1 = ( ( (Double(sx)+0.5 + Double(dx))/2 + Double(x))/Double(w) - 0.5)
let part2 = ( ( (Double(sy)+0.5 + Double(dy))/2 + Double(y))/Double(h) - 0.5)
let d = cx * part1
+ cy * part2
+ cam.d
let rr = radiance(Ray(o:cam.o+d*140, d:d.norm()), 0, Xi)
r = r + rr * (1.0 / Double(samps))
} // Camera rays are pushed ^^^^^ forward to start in interior
}
}
let result = r*0.25
c[i] = result
}
}
let f = FileStream(path: "image.ppm") // Write image to PPM file.
f.write("P3\n\(w) \(h)\n\(255)\n")
for (var i=0; i<w*h; i++) {
f.write("\(toInt(c[i].x)) \(toInt(c[i].y)) \(toInt(c[i].z)) ")
}
exit(0)
}
dispatch_main();
}
main()
| mit | c96a9264c014d49a33a976d839549de6 | 36.819005 | 111 | 0.544987 | 2.43958 | false | false | false | false |
ngageoint/mage-ios | Mage/SingleUserMapView.swift | 1 | 1464 | //
// SingleUserMap.swift
// MAGE
//
// Created by Daniel Barela on 2/10/22.
// Copyright © 2022 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
class SingleUserMapView: MageMapView, FilteredUsersMap, FilteredObservationsMap, FollowUser {
var filteredObservationsMapMixin: FilteredObservationsMapMixin?
var filteredUsersMapMixin: FilteredUsersMapMixin?
var followUserMapMixin: FollowUserMapMixin?
var user: User?
public init(user: User?, scheme: MDCContainerScheming?) {
self.user = user
super.init(scheme: scheme)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutView() {
super.layoutView()
filteredUsersMapMixin = FilteredUsersMapMixin(filteredUsersMap: self, user: user, scheme: scheme)
filteredObservationsMapMixin = FilteredObservationsMapMixin(filteredObservationsMap: self, user: user)
followUserMapMixin = FollowUserMapMixin(followUser: self, user: user, scheme: scheme)
mapMixins.append(filteredObservationsMapMixin!)
mapMixins.append(filteredUsersMapMixin!)
mapMixins.append(followUserMapMixin!)
initiateMapMixins()
}
override func removeFromSuperview() {
filteredUsersMapMixin = nil
filteredObservationsMapMixin = nil
followUserMapMixin = nil
}
}
| apache-2.0 | 5732beb58829c4864d866f5dbbef946f | 30.804348 | 110 | 0.706083 | 5.027491 | false | false | false | false |
MTTHWBSH/Short-Daily-Devotions | Short Daily Devotions/View Models/PageViewModel.swift | 1 | 1103 | //
// PageViewModel.swift
// Short Daily Devotions
//
// Created by Matthew Bush on 12/21/16.
// Copyright © 2016 Matt Bush. All rights reserved.
//
import Alamofire
class PageViewModel: ViewModel {
private var pageID: String
private var page: Post?
init(pageID: String) {
self.pageID = pageID
super.init()
loadPage(id: pageID, completion: nil)
}
private func loadPage(id: String, completion: ((Void) -> Void)?) {
Alamofire.request(Constants.kPageBaseURL + pageID)
.responseJSON { [weak self] response in
guard let data = response.data,
let json = try? JSONSerialization.jsonObject(with: data, options: []),
let dict = json as? NSDictionary,
let page = Post.from(dict) else { return }
self?.page = page
self?.render?()
completion?()
}
}
func titleForPage() -> String { return page?.title ?? "" }
func pageContent() -> String { return page?.content ?? "" }
}
| mit | 2975460c011471f57cdfa543764e4e60 | 27.25641 | 90 | 0.553539 | 4.390438 | false | false | false | false |
JakeLin/IBAnimatable | IBAnimatableApp/IBAnimatableApp/Playground/Transitions/TransitionTableViewController.swift | 2 | 11031 | //
// Created by Jake Lin on 2/29/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
import IBAnimatable
final class TransitionTableViewController: UITableViewController {
fileprivate var transitionAnimationsHeaders = [String]()
fileprivate var transitionAnimations = [[String]]()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
populateTransitionTypeData()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
guard let toNavigationController = segue.destination as? AnimatableNavigationController, let indexPath = tableView.indexPathForSelectedRow else {
return
}
let transitionString = transitionAnimations[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
let transitionAnimationType = TransitionAnimationType(string: transitionString)
// Set the transition animation type for `AnimatableNavigationController`, used for Push/Pop transitions
toNavigationController.transitionAnimationType = transitionAnimationType
toNavigationController.navigationBar.topItem?.title = transitionString
// Set the transition animation type for `AnimatableViewController`, used for Present/Dismiss transitions
if let toViewController = toNavigationController.topViewController as? TransitionViewController {
toViewController.transitionAnimationType = transitionAnimationType
}
}
}
// MARK: - Factory
private extension TransitionTableViewController {
func populateTransitionTypeData() {
transitionAnimationsHeaders.append("Fade")
let fadeAnimations: [TransitionAnimationType] = [.fade(direction: .in),
.fade(direction: .out),
.fade(direction: .cross)]
transitionAnimations.append(toString(animations: fadeAnimations))
transitionAnimationsHeaders.append("SystemCube")
let cubeAnimations: [TransitionAnimationType] = [.systemCube(from: .left),
.systemCube(from: .right),
.systemCube(from: .top),
.systemCube(from: .bottom)]
transitionAnimations.append(toString(animations: cubeAnimations))
transitionAnimationsHeaders.append("SystemFlip")
let flipSystemAnimations: [TransitionAnimationType] = [.systemFlip(from: .left),
.systemFlip(from: .right),
.systemFlip(from: .top),
.systemFlip(from: .bottom)]
transitionAnimations.append(toString(animations: flipSystemAnimations))
transitionAnimationsHeaders.append("SystemMoveIn")
let moveAnimations: [TransitionAnimationType] = [.systemMoveIn(from: .left),
.systemMoveIn(from: .right),
.systemMoveIn(from: .top),
.systemMoveIn(from: .bottom)]
transitionAnimations.append(toString(animations: moveAnimations))
transitionAnimationsHeaders.append("SystemPush")
let pushAnimations: [TransitionAnimationType] = [.systemPush(from: .left),
.systemPush(from: .right),
.systemMoveIn(from: .top),
.systemMoveIn(from: .bottom)]
transitionAnimations.append(toString(animations: pushAnimations))
transitionAnimationsHeaders.append("SystemReveal")
let revealAnimations: [TransitionAnimationType] = [.systemReveal(from: .left),
.systemReveal(from: .right),
.systemReveal(from: .top),
.systemReveal(from: .bottom)]
transitionAnimations.append(toString(animations: revealAnimations))
transitionAnimationsHeaders.append("SystemPage")
let pageAnimations: [TransitionAnimationType] = [.systemPage(type: .curl), .systemPage(type: .unCurl)]
transitionAnimations.append(toString(animations: pageAnimations))
transitionAnimationsHeaders.append("SystemCameraIris")
let cameraAnimations: [TransitionAnimationType] = [.systemCameraIris(hollowState: .none),
.systemCameraIris(hollowState: .open),
.systemCameraIris(hollowState: .close)]
transitionAnimations.append(toString(animations: cameraAnimations))
transitionAnimationsHeaders.append("Fold")
let foldAnimations: [TransitionAnimationType] = [.fold(from: .left, folds: nil),
.fold(from: .right, folds: nil),
.fold(from: .top, folds: nil),
.fold(from: .bottom, folds: nil)]
transitionAnimations.append(toString(animations: foldAnimations))
transitionAnimationsHeaders.append("Portal")
let portalAnimations: [TransitionAnimationType] = [.portal(direction: .forward, zoomScale: 0.3),
.portal(direction: .backward, zoomScale: nil)]
transitionAnimations.append(toString(animations: portalAnimations))
transitionAnimationsHeaders.append("NatGeo")
let natGeoAnimations: [TransitionAnimationType] = [.natGeo(to: .left), .natGeo(to: .right)]
transitionAnimations.append(toString(animations: natGeoAnimations))
transitionAnimationsHeaders.append("Turn")
let turnAnimations: [TransitionAnimationType] = [.turn(from: .left),
.turn(from: .right),
.turn(from: .top),
.turn(from: .bottom)]
transitionAnimations.append(toString(animations: turnAnimations))
transitionAnimationsHeaders.append("Cards")
let cardAnimations: [TransitionAnimationType] = [.cards(direction: .forward), .cards(direction: .backward)]
transitionAnimations.append(toString(animations: cardAnimations))
transitionAnimationsHeaders.append("Flip")
let flipAnimations: [TransitionAnimationType] = [.flip(from: .left), .flip(from: .right)]
transitionAnimations.append(toString(animations: flipAnimations))
transitionAnimationsHeaders.append("Slide")
let slideAnimations: [TransitionAnimationType] = [.slide(to: .left, isFade: true),
.slide(to: .right, isFade: false),
.slide(to: .top, isFade: true),
.slide(to: .bottom, isFade: false)]
transitionAnimations.append(toString(animations: slideAnimations))
transitionAnimationsHeaders.append("Others")
let otherAnimations: [TransitionAnimationType] = [.systemRotate,
.systemRippleEffect,
.explode(xFactor: nil, minAngle: nil, maxAngle: nil),
.explode(xFactor: 10, minAngle: -20, maxAngle: 20)]
transitionAnimations.append(toString(animations: otherAnimations))
}
private func toString(animations: [TransitionAnimationType]) -> [String] {
return animations.map { $0.asString }
}
}
fileprivate extension TransitionAnimationType {
var asString: String {
switch self {
case .fade(let direction):
return "fade" + "(\(direction.rawValue))"
case .systemCube(let direction):
return "systemCube" + "(\(direction.rawValue))"
case .systemFlip(let direction):
return "systemFlip" + "(\(direction.rawValue))"
case .systemMoveIn(let direction):
return "systemMoveIn" + "(\(direction.rawValue))"
case .systemPush(let direction):
return "systemPush" + "(\(direction.rawValue))"
case .systemReveal(let direction):
return "systemReveal" + "(\(direction.rawValue))"
case .systemPage(let type):
return "systemPage(\(type.rawValue))"
case .systemCameraIris(let hollowState):
return "systemCameraIris" + (hollowState == .none ? "" : "(\(hollowState.rawValue))")
case .fold(let direction, _):
return "fold" + "(\(direction.rawValue))"
case let .portal(direction, zoomScale):
return "portal" + (zoomScale == nil ? "(\(direction.rawValue))" : "(\(direction.rawValue),\(zoomScale!))")
case .natGeo(let direction):
return "natGeo" + "(\(direction.rawValue))"
case .turn(let direction):
return "turn" + "(\(direction.rawValue))"
case .cards(let direction):
return "cards" + "(\(direction.rawValue))"
case .flip(let direction):
return "flip" + "(\(direction.rawValue))"
case let .slide(direction, isFade):
return "slide" + (isFade ? "(\(direction.rawValue), fade)" : "slide" + "(\(direction.rawValue))")
case .systemRotate:
return "systemRotate"
case .systemRippleEffect:
return "systemRippleEffect"
case .systemSuckEffect:
return "systemSuckEffect"
case let .explode(.some(x), .some(min), .some(max)):
return "explode" + "(\(x),\(min),\(max))"
case .explode:
return "explode"
case .none:
return "none"
}
}
}
// MARK: - UITableViewDataSource / UITableViewDelegate
extension TransitionTableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return transitionAnimations.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return transitionAnimations[section].count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return transitionAnimationsHeaders[section]
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "transitionCell", for: indexPath) as UITableViewCell
cell.textLabel?.text = transitionAnimations[(indexPath as NSIndexPath).section][(indexPath as NSIndexPath).row]
return cell
}
// MARK: - reset the group header font color and size
override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? UITableViewHeaderFooterView {
header.textLabel?.textColor = .white
header.textLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.light)
}
}
}
| mit | e9268ae8cef304c9ac6f99d5403f8d84 | 41.099237 | 149 | 0.61641 | 5.610376 | false | false | false | false |
BennyKJohnson/OpenCloudKit | Sources/CKQuery.swift | 1 | 2370 | //
// CKQuery.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 6/07/2016.
//
//
import Foundation
struct CKQueryDictionary {
static let recordType = "recordType"
static let filterBy = "filterBy"
static let sortBy = "sortBy"
}
struct CKSortDescriptorDictionary {
static let fieldName = "fieldName"
static let ascending = "ascending"
static let relativeLocation = "relativeLocation"
}
public class CKQuery: CKCodable {
public var recordType: String
public var predicate: NSPredicate
let filters: [CKQueryFilter]
public init(recordType: String, predicate: NSPredicate) {
self.recordType = recordType
self.predicate = predicate
self.filters = CKPredicate(predicate: predicate).filters()
}
public init(recordType: String, filters: [CKQueryFilter]) {
self.recordType = recordType
self.filters = filters
self.predicate = NSPredicate(value: true)
}
public var sortDescriptors: [NSSortDescriptor] = []
// Returns a Dictionary Representation of a Query Dictionary
var dictionary: [String: Any] {
var queryDictionary: [String: Any] = ["recordType": recordType.bridge()]
queryDictionary["filterBy"] = filters.map({ (filter) -> [String: Any] in
return filter.dictionary
}).bridge()
// Create Sort Descriptor Dictionaries
queryDictionary["sortBy"] = sortDescriptors.flatMap { (sortDescriptor) -> [String: Any]? in
if let fieldName = sortDescriptor.key {
var sortDescriptionDictionary: [String: Any] = [CKSortDescriptorDictionary.fieldName: fieldName.bridge(),
CKSortDescriptorDictionary.ascending: NSNumber(value: sortDescriptor.ascending)]
if let locationSortDescriptor = sortDescriptor as? CKLocationSortDescriptor {
sortDescriptionDictionary[CKSortDescriptorDictionary.relativeLocation] = locationSortDescriptor.relativeLocation.recordFieldDictionary.bridge()
}
return sortDescriptionDictionary
} else {
return nil
}
}.bridge()
return queryDictionary
}
}
| mit | 393acd84fa728500dab53d49953e5e2b | 31.465753 | 163 | 0.617722 | 5.576471 | false | false | false | false |
iException/garage | Garage/Sources/VehicleListViewController.swift | 1 | 8808 | //
// VehicleListViewController.swift
// Garage
//
// Created by Xiang Li on 28/10/2017.
// Copyright © 2017 Baixing. All rights reserved.
import UIKit
import RealmSwift
import SKPhotoBrowser
import Photos
class VehicleListViewController: UIViewController {
private static let collectionViewInset: CGFloat = 5.0
private static let numberOfColumns = 2
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
let collectionViewInset = VehicleListViewController.collectionViewInset
layout.minimumInteritemSpacing = collectionViewInset
layout.minimumLineSpacing = collectionViewInset
layout.sectionInset = UIEdgeInsetsMake(collectionViewInset, collectionViewInset, collectionViewInset, collectionViewInset)
var collectionView = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(VehicleCollectionViewCell.self, forCellWithReuseIdentifier: String(describing: VehicleCollectionViewCell.self))
return collectionView
}()
lazy var realm: Realm = {
return try! Realm()
}()
var vehicles: [VehicleViewModel]?
// MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
// forgeData()
// removeAllVehicle()
setUpViews()
setUpNavigationItems()
configurePhotoBrowserOptions()
reload()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
self.collectionView.frame = view.bounds
}
// MARK: - Private -
private func setUpNavigationItems() {
let buttonItem = UIBarButtonItem(title: "scan", style: .plain, target: self, action: #selector(scanButtonPressed(_:)))
self.navigationItem.rightBarButtonItems = [ buttonItem ]
}
private func reload() {
loadVehicle()
reloadCollectionView()
}
// MARK: - Event Handler
@objc private func scanButtonPressed(_ sender : Any) {
let viewController = ViewController()
viewController.delegate = self
self.present(viewController, animated: true, completion: nil)
}
// MARK: - Realm
private func forgeData() {
for index in 0...5 {
let imageName = "image\(index)"
let image = UIImage(named:imageName)!
let aVehicle = Vehicle(image: image)
saveVehicle(vehicle: aVehicle, realm: realm)
printVehicleCount(realm)
}
}
private func printVehicleCount(_ realm: Realm) {
print("Vehicle count is \(realm.objects(Vehicle.self).count)")
}
private func saveVehicle(vehicle: Vehicle, realm: Realm) {
realm.beginWrite()
realm.add(vehicle)
try! realm.commitWrite()
}
private func deleteVehicle(vehicle: Vehicle, realm: Realm) {
try! realm.write {
realm.delete(vehicle)
}
}
private func loadVehicle() {
self.vehicles = realm.objects(Vehicle.self).map { (vehicle) -> VehicleViewModel in
guard let image = vehicle.image else { return VehicleViewModel(image: UIImage(), model: vehicle) }
let viewModel = VehicleViewModel(image: image, model: vehicle)
return viewModel
}
}
private func removeAllVehicle() {
try! realm.write {
realm.deleteAll()
}
}
// MARK: - Photo Browser
private func configurePhotoBrowserOptions() {
SKPhotoBrowserOptions.displayStatusbar = true
SKPhotoBrowserOptions.displayDeleteButton = true
SKPhotoBrowserOptions.enableSingleTapDismiss = true
}
// MARK: - CollectionView
private func setUpViews() {
view.addSubview(collectionView)
}
private func reloadCollectionView() {
collectionView.reloadData()
}
// MARK: - Wrapper
private func viewModelAtIndex(index: Int) -> VehicleViewModel? {
guard let vehicles = vehicles else { return nil }
return vehicles[safe: index]
}
private func imageAtIndex(index: Int) -> UIImage? {
guard let vehicle = viewModelAtIndex(index: index) else { return nil }
return vehicle.image
}
}
extension VehicleListViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let vehicles = vehicles else { return 0 }
return vehicles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: VehicleCollectionViewCell.self), for: indexPath) as? VehicleCollectionViewCell else {
return UICollectionViewCell()
}
cell.imageView.image = imageAtIndex(index: indexPath.item)
return cell
}
}
extension VehicleListViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfColumns = Double(VehicleListViewController.numberOfColumns)
let collectionViewWidth = Double(collectionView.frame.size.width)
let collectionViewInset = Double(VehicleListViewController.collectionViewInset)
let width = (collectionViewWidth - (numberOfColumns + 1) * collectionViewInset) / numberOfColumns
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? VehicleCollectionViewCell else {
return
}
guard let image = imageAtIndex(index: indexPath.item) else {
return
}
showPhotoBrowser(image: image, photos: vehicles!, sourceView: cell, index: indexPath.item)
}
private func showPhotoBrowser(image: UIImage, photos: [SKPhotoProtocol], sourceView: UIView, index: Int) {
let browser = SKPhotoBrowser(originImage: image, photos: photos, animatedFromView: sourceView)
browser.initializePageIndex(index)
browser.delegate = self
browser.showDeleteButton(bool: true)
present(browser, animated: true, completion: {})
}
}
extension VehicleListViewController: SKPhotoBrowserDelegate {
func removePhoto(_ browser: SKPhotoBrowser, index: Int, reload: @escaping (() -> Void)) {
guard let vehicle = viewModelAtIndex(index: index) else { return }
deleteVehicle(vehicle: vehicle.model, realm: realm)
self.reload()
reload()
}
func viewForPhoto(_ browser: SKPhotoBrowser, index: Int) -> UIView? {
return collectionView.cellForItem(at: IndexPath(item: index, section: 0))
}
}
extension VehicleListViewController: ViewControllerDelegate {
func viewControllerFinishClassifying(_ viewController: ViewController, assets: [PHAsset]) {
viewController.dismiss(animated: true, completion: nil)
saveAssetsToDatabase(assets)
deleteAssets(assets)
}
}
extension VehicleListViewController {
private func saveAssetsToDatabase(_ assets: [PHAsset]) {
let dispatchGroup = DispatchGroup()
for (index, asset) in assets.enumerated() {
let size = CGSize(width: 500, height: 500)
dispatchGroup.enter()
let options = PHImageRequestOptions()
options.isSynchronous = true
PHImageManager.default().requestImage(for: asset, targetSize: size, contentMode: .aspectFill, options: options, resultHandler: { (image, info) in
defer {
dispatchGroup.leave()
}
guard let image = image else {
return
}
let vehicle = Vehicle(image: image)
if vehicle.imageData != nil {
self.saveVehicle(vehicle: vehicle, realm: self.realm)
}
})
}
dispatchGroup.notify(queue: .main) {
self.reload()
}
}
private func deleteAssets(_ assets: [PHAsset]) {
// TODO:
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.deleteAssets(NSArray(array: assets))
}) { (result, error) in
}
}
}
| mit | fc72dabb7950e28bfc28992946aab405 | 32.743295 | 185 | 0.643238 | 5.504375 | false | false | false | false |
takeo-asai/math-puzzle | problems/06.swift | 1 | 439 | // 2m-1: 3n+1
// 2m: n/2
// 初期値はともに3n+1する
func collatzx(n: Int) -> (Int, [Int]) {
func collatz(n: Int, _ history: [Int]) -> (Int, [Int]) {
let m: Int = n % 2 == 0 ? n/2 : 3*n + 1
if history.contains(m) {
return (m, history+[m])
}
return collatz(m, history+[m])
}
return collatz(3*n+1, [n, 3*n+1])
}
var count = 0
for i in 1 ... 5000 {
if collatzx(2*i).0 == 2*i {
count++
}
}
print("Count: \(count)")
| mit | 4e9145a3c09cc99c3c0e453fc55fcfce | 17.304348 | 57 | 0.522565 | 2.024038 | false | false | false | false |
scottkawai/sendgrid-swift | Sources/SendGrid/Structs/Page.swift | 1 | 872 | import Foundation
/// This struct is used to represent a page via the `limit` and `offset`
/// parameters found in various API calls.
public struct Page {
// MARK: - Properties
/// The limit value for each page of results.
public let limit: Int
/// The offset value for the page.
public let offset: Int
// MARK: - Initialization
/// Initializes the struct with a limit and offset.
///
/// - Parameters:
/// - limit: The number of results per page.
/// - offset: The index to start the page on.
public init(limit: Int, offset: Int) {
self.limit = limit
self.offset = offset
}
}
extension Page: Equatable {
/// :nodoc:
/// Equatable conformance.
public static func ==(lhs: Page, rhs: Page) -> Bool {
lhs.limit == rhs.limit && lhs.offset == rhs.offset
}
}
| mit | db7d0ac2cc5b3648df77aae27e990e89 | 25.424242 | 72 | 0.597477 | 4.172249 | false | false | false | false |
sharplet/five-day-plan | Sources/FiveDayPlan/ViewControllers/PlanOutlineViewController.swift | 1 | 3651 | import CircleProgressView
import CoreData
import UIKit
private let sectionHeaderLabelAdjustment = 18 as CGFloat
final class PlanOutlineViewController: UITableViewController {
let viewModel = PlanOutlineViewModel(plan: .year2017, store: .shared)
private var isFirstLoad = true
override func viewDidLoad() {
super.viewDidLoad()
viewModel.fetchController.delegate = self
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
initialise()
performFetch()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
defer { isFirstLoad = false }
if isFirstLoad, let indexPath = viewModel.indexPathForCurrentWeek() {
tableView.scrollToRow(at: indexPath, at: .top, animated: false)
tableView.contentOffset.y -= sectionHeaderLabelAdjustment
}
}
private func initialise() {
viewModel.initialise { error in
if let error = error {
self.show(error)
}
}
}
private func performFetch() {
do {
try viewModel.performFetch()
} catch {
show(error)
}
}
override func numberOfSections(in _: UITableView) -> Int {
return viewModel.numberOfSections
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(inSection: section)
}
override func tableView(_: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.titleForHeader(inSection: section)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let day = viewModel[indexPath]
let cell = tableView.dequeueReusableCell(withIdentifier: "Day Summary", for: indexPath) as! DaySummaryCell
cell.textLabel?.text = day.name
cell.textLabel?.textColor = day.isComplete ? .lightGray : nil
cell.detailTextLabel?.textColor = day.isComplete ? .lightGray : nil
cell.detailTextLabel?.text = day.formattedSummary
cell.progressView?.isHidden = !day.isInProgress
cell.progressView?.progress = day.percentageRead
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let weekTitle = viewModel.titleForHeader(inSection: indexPath.section)
navigationItem.backBarButtonItem = UIBarButtonItem(title: weekTitle, style: .plain, target: nil, action: nil)
perform(.showDayDetail) {
$0.details = self.viewModel.dayDetails(at: indexPath)
}
}
}
extension PlanOutlineViewController: NSFetchedResultsControllerDelegate {
func controllerWillChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.beginUpdates()
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange _: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch type {
case .update:
tableView.reloadRows(at: [indexPath!], with: .none)
case .insert:
tableView.insertRows(at: [newIndexPath!], with: .fade)
default:
fatalError("unexpected row change type: \(type.rawValue)")
}
}
func controller(_: NSFetchedResultsController<NSFetchRequestResult>, didChange _: NSFetchedResultsSectionInfo, atSectionIndex sectionIndex: Int, for type: NSFetchedResultsChangeType) {
switch type {
case .insert:
tableView.insertSections([sectionIndex], with: .fade)
default:
fatalError("unexpected section change type: \(type.rawValue)")
}
}
func controllerDidChangeContent(_: NSFetchedResultsController<NSFetchRequestResult>) {
tableView.endUpdates()
}
}
| mit | fc3b131e8d6b3cf508d7c5605eeb18d0 | 31.309735 | 186 | 0.727472 | 5.084958 | false | false | false | false |
syoung-smallwisdom/BridgeAppSDK | BridgeAppSDK/SBARegistrationStep.swift | 1 | 5657 | //
// SBARegistrationStep.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import ResearchKit
open class SBARegistrationStep: ORKFormStep, SBAProfileInfoForm {
static let confirmationIdentifier = "confirmation"
static let defaultPasswordMinLength = 4
static let defaultPasswordMaxLength = 16
open var surveyItemType: SBASurveyItemType {
return .account(.registration)
}
open func defaultOptions(_ inputItem: SBASurveyItem?) -> [SBAProfileInfoOption] {
return [.name, .email, .password]
}
public override required init(identifier: String) {
super.init(identifier: identifier)
commonInit(nil)
}
public init(inputItem: SBASurveyItem) {
super.init(identifier: inputItem.identifier)
commonInit(inputItem)
}
open override func validateParameters() {
super.validateParameters()
try! validate(options: self.options)
}
open func validate(options: [SBAProfileInfoOption]?) throws {
guard let options = options else {
throw SBAProfileInfoOptionsError.missingRequiredOptions
}
guard options.contains(.email) && options.contains(.password) else {
throw SBAProfileInfoOptionsError.missingEmail
}
}
open override var isOptional: Bool {
get { return false }
set {}
}
open var passwordAnswerFormat: ORKTextAnswerFormat? {
return self.formItemForIdentifier(SBAProfileInfoOption.password.rawValue)?.answerFormat as? ORKTextAnswerFormat
}
open override func stepViewControllerClass() -> AnyClass {
return SBARegistrationStepViewController.classForCoder()
}
// MARK: NSCoding
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
open class SBARegistrationStepViewController: ORKFormStepViewController, SBAUserRegistrationController {
/**
If there are data groups that were set in a previous step or via a custom onboarding manager,
set them on the view controller using this property.
*/
open var dataGroups: [String]?
// MARK: SBASharedInfoController
lazy open var sharedAppDelegate: SBAAppInfoDelegate = {
return UIApplication.shared.delegate as! SBAAppInfoDelegate
}()
// MARK: SBAUserRegistrationController
open var failedValidationMessage = Localization.localizedString("SBA_REGISTRATION_UNKNOWN_FAILED")
open var failedRegistrationTitle = Localization.localizedString("SBA_REGISTRATION_FAILED_TITLE")
// MARK: Navigation overrides - cannot go back and override go forward to register
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// set the back and cancel buttons to empty items
self.cancelButtonItem = UIBarButtonItem()
self.backButtonItem = UIBarButtonItem()
}
// Override the default method for goForward and attempt user registration. Do not allow subclasses
// to override this method
final public override func goForward() {
showLoadingView()
sharedUser.registerUser(email: email!, password: password!, externalId: externalID, dataGroups: dataGroups) { [weak self] error in
if let error = error {
self?.handleFailedRegistration(error)
}
else {
self?.goNext()
}
}
}
func goNext() {
// successfully registered. Set the other values from this form.
if let gender = self.gender {
sharedUser.gender = gender
}
if let birthdate = self.birthdate {
sharedUser.birthdate = birthdate
}
// Then call super to go forward
super.goForward()
}
override open func goBackward() {
// Do nothing
}
}
| bsd-3-clause | f35db3992044050c156f8bbb85fc525b | 34.130435 | 138 | 0.68529 | 5.366224 | false | false | false | false |
erlandranvinge/swift-mini-json | Json.swift | 1 | 1416 | import Foundation
class Json: Sequence {
private let data:AnyObject?
init(data:AnyObject?) {
if (data is NSData) {
self.data = try? JSONSerialization.jsonObject(
with: (data as! NSData) as Data,
options: .allowFragments) as AnyObject
} else {
self.data = data
}
}
func string() -> String { return data as? String ?? "" }
func int() -> Int { return data as? Int ?? 0 }
func float() -> Float { return data as? Float ?? 0.0 }
func double() -> Double { return data as? Double ?? 0.0 }
func bool() -> Bool { return data as? Bool ?? false }
subscript(name:String) -> Json {
let hash = data as? NSDictionary
return Json(data: hash?.value(forKey: name) as AnyObject)
}
subscript(index:Int) -> Json {
guard let items = data as? [AnyObject] else { return Json(data: nil) }
guard index >= 0 && index < items.count else { return Json(data: nil) }
return Json(data: items[index])
}
func makeIterator() -> AnyIterator<Json> {
guard let items = data as? [AnyObject] else {
return AnyIterator { return .none }
}
var current = -1
return AnyIterator {
current = current + 1
return current < items.count ? Json(data: items[current]) : .none
}
}
}
| mit | 843ecb3c2fcc7a2177cd7f7b18eaecf8 | 30.466667 | 79 | 0.543785 | 4.26506 | false | false | false | false |
wtrumler/FluentSwiftAssertions | FluentSwiftAssertions/OptionalExtension.swift | 1 | 3232 | //
// OptionalExtension.swift
// FluentSwiftAssertions
//
// Created by Wolfgang Trumler on 19.03.17.
// Copyright © 2017 Wolfgang Trumler. All rights reserved.
//
import Foundation
import XCTest
extension Optional {
public var should: Optional {
return self
}
public func beNil(_ message: @autoclosure () -> String = "",
file: StaticString = #file,
line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNil) {
assertionFunction(self, message, file, line)
}
public func notBeNil(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotNil)
{
assertionFunction(self, message, file, line)
}
public func notBeNilToExecute(_ message: @autoclosure () -> String = "", file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression: @autoclosure () throws -> Any?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotNil,
_ block: () -> Void) {
if self != nil {
block()
}
else {
// "Optional expected to be non nil."
assertionFunction(self, message, file, line)
}
}
//
// compare optional with other (non)optional
//
public func beEqualTo<T : Equatable>(_ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertEqual)
{
do {
let result = try expression2()
assertionFunction(self as! Optional<T>, result, message, file, line)
} catch {
// if the evaluation fails an exception is thrown anyway.
// so no need to do something here
}
}
public func notBeEqualTo<T : Equatable>(_ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String = "",
file: StaticString = #file, line: UInt = #line,
assertionFunction: @escaping (_ expression1: @autoclosure () throws -> T?, _ expression2: @autoclosure () throws -> T?, _ message: @autoclosure () -> String, _ file: StaticString, _ line: UInt) -> Void = XCTAssertNotEqual)
{
do {
let result = try expression2()
assertionFunction(self as! Optional<T>, result, message, file, line)
} catch {
// if the evaluation fails an exception is thrown anyway.
// so no need to do something here
}
}
}
| mit | 3fd505dfafbd742971e4175b8744de3d | 43.260274 | 248 | 0.564222 | 4.723684 | false | false | false | false |
ashfurrow/Moya | Tests/MoyaTests/SignalProducer+MoyaSpec.swift | 1 | 25062 | import Quick
import Moya
import ReactiveSwift
import Nimble
import Foundation
private func signalSendingData(_ data: Data, statusCode: Int = 200) -> SignalProducer<Response, MoyaError> {
return SignalProducer(value: Response(statusCode: statusCode, data: data as Data, response: nil))
}
final class SignalProducerMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes closed range upperbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filter(statusCodes: 0...9).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes closed range lowerbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: -1)
var errored = false
signal.filter(statusCodes: 0...9).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes range upperbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filter(statusCodes: 0..<10).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out unrequested status codes range lowerbound") {
let data = Data()
let signal = signalSendingData(data, statusCode: -1)
var errored = false
signal.filter(statusCodes: 0..<10).startWithResult { event in
switch event {
case .success(let object):
fail("called on non-correct status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = Data()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("knows how to filter individual status codes") {
let data = Data()
let signal = signalSendingData(data, statusCode: 42)
var called = false
signal.filter(statusCode: 42).startWithResult { _ in
called = true
}
expect(called).to(beTruthy())
}
it("filters out different individual status code") {
let data = Data()
let signal = signalSendingData(data, statusCode: 43)
var errored = false
signal.filter(statusCode: 42).startWithResult { result in
switch result {
case .success(let object):
fail("called on non-success status code: \(object)")
case .failure:
errored = true
}
}
expect(errored).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testImage
let data = image.asJPEGRepresentation(0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().startWithResult { _ in
size = image.size
}
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = Data()
let signal = signalSendingData(data)
var receivedError: MoyaError?
signal.mapImage().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.imageMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().startWithResult { result in
if case .success(let response) = result,
let json = response as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedError: MoyaError?
signal.mapJSON().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
switch receivedError {
case .some(.jsonMapping):
break
default:
fail("expected NSError with \(NSCocoaErrorDomain) domain")
}
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.data(using: String.Encoding.utf8)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().startWithResult { result in
receivedString = try? result.get()
}
expect(receivedString).to(equal(string))
}
it("maps data representing a string at a key path to a string") {
let string = "You have the rights to the remains of a silent attorney."
let json = ["words_to_live_by": string]
let data = try! JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let signal = signalSendingData(data)
var receivedString: String?
signal.mapString(atKeyPath: "words_to_live_by").startWithResult { result in
receivedString = try? result.get()
}
expect(receivedString).to(equal(string))
}
it("ignores invalid data") {
let data = Data(bytes: [0x11FFFF] as [UInt32], count: 1) //Byte exceeding UTF8
let signal = signalSendingData(data as Data)
var receivedError: MoyaError?
signal.mapString().startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
expect(receivedError).toNot(beNil())
let expectedError = MoyaError.stringMapping(Response(statusCode: 200, data: Data(), response: nil))
expect(receivedError).to(beOfSameErrorType(expectedError))
}
}
describe("object mapping") {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(formatter)
let json: [String: Any] = [
"title": "Hello, Moya!",
"createdAt": "1995-01-14T12:34:56"
]
it("maps data representing a json to a decodable object") {
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObject: Issue?
_ = signal.map(Issue.self, using: decoder).startWithResult { result in
receivedObject = try? result.get()
}
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to an array of decodable objects") {
let jsonArray = [json, json, json]
guard let data = try? JSONSerialization.data(withJSONObject: jsonArray, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObjects: [Issue]?
_ = signal.map([Issue].self, using: decoder).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 3
expect(receivedObjects?.map { $0.title }) == ["Hello, Moya!", "Hello, Moya!", "Hello, Moya!"]
}
it("maps empty data to a decodable object with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: OptionalIssue?
_ = signal.map(OptionalIssue.self, using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: [OptionalIssue]?
_ = signal.map([OptionalIssue].self, using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
context("when using key path mapping") {
it("maps data representing a json to a decodable object") {
let json: [String: Any] = ["issue": json] // nested json
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObject: Issue?
_ = signal.map(Issue.self, atKeyPath: "issue", using: decoder).startWithResult { result in
receivedObject = try? result.get()
}
expect(receivedObject).notTo(beNil())
expect(receivedObject?.title) == "Hello, Moya!"
expect(receivedObject?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps data representing a json array to a decodable object (#1311)") {
let json: [String: Any] = ["issues": [json]] // nested json array
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedObjects: [Issue]?
_ = signal.map([Issue].self, atKeyPath: "issues", using: decoder).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title) == "Hello, Moya!"
expect(receivedObjects?.first?.createdAt) == formatter.date(from: "1995-01-14T12:34:56")!
}
it("maps empty data to a decodable object with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: OptionalIssue?
_ = signal.map(OptionalIssue.self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.title).to(beNil())
expect(receivedObjects?.createdAt).to(beNil())
}
it("maps empty data to a decodable array with optional properties") {
let signal = signalSendingData(Data())
var receivedObjects: [OptionalIssue]?
_ = signal.map([OptionalIssue].self, atKeyPath: "issue", using: decoder, failsOnEmptyData: false).startWithResult { result in
receivedObjects = try? result.get()
}
expect(receivedObjects).notTo(beNil())
expect(receivedObjects?.count) == 1
expect(receivedObjects?.first?.title).to(beNil())
expect(receivedObjects?.first?.createdAt).to(beNil())
}
it("map Int data to an Int value") {
let json: [String: Any] = ["count": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var count: Int?
_ = signal.map(Int.self, atKeyPath: "count", using: decoder).startWithResult { result in
count = try? result.get()
}
expect(count).notTo(beNil())
expect(count) == 1
}
it("map Bool data to a Bool value") {
let json: [String: Any] = ["isNew": true]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var isNew: Bool?
_ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in
isNew = try? result.get()
}
expect(isNew).notTo(beNil())
expect(isNew) == true
}
it("map String data to a String value") {
let json: [String: Any] = ["description": "Something interesting"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var description: String?
_ = signal.map(String.self, atKeyPath: "description", using: decoder).startWithResult { result in
description = try? result.get()
}
expect(description).notTo(beNil())
expect(description) == "Something interesting"
}
it("map String data to a URL value") {
let json: [String: Any] = ["url": "http://www.example.com/test"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var url: URL?
_ = signal.map(URL.self, atKeyPath: "url", using: decoder).startWithResult { result in
url = try? result.get()
}
expect(url).notTo(beNil())
expect(url) == URL(string: "http://www.example.com/test")
}
it("shouldn't map Int data to a Bool value") {
let json: [String: Any] = ["isNew": 1]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var isNew: Bool?
_ = signal.map(Bool.self, atKeyPath: "isNew", using: decoder).startWithResult { result in
isNew = try? result.get()
}
expect(isNew).to(beNil())
}
it("shouldn't map String data to an Int value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: Int?
_ = signal.map(Int.self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
it("shouldn't map Array<String> data to an String value") {
let json: [String: Any] = ["test": ["123", "456"]]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: String?
_ = signal.map(String.self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
it("shouldn't map String data to an Array<String> value") {
let json: [String: Any] = ["test": "123"]
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var test: [String]?
_ = signal.map([String].self, atKeyPath: "test", using: decoder).startWithResult { result in
test = try? result.get()
}
expect(test).to(beNil())
}
}
it("ignores invalid data") {
var json = json
json["createdAt"] = "Hahaha" // invalid date string
guard let data = try? JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) else {
preconditionFailure("Failed creating Data from JSON dictionary")
}
let signal = signalSendingData(data)
var receivedError: Error?
_ = signal.map(Issue.self, using: decoder).startWithResult { result in
switch result {
case .success:
fail("next called for invalid data")
case .failure(let error):
receivedError = error
}
}
if case let MoyaError.objectMapping(nestedError, _)? = receivedError {
expect(nestedError).to(beAKindOf(DecodingError.self))
} else {
fail("expected <MoyaError.objectMapping>, got <\(String(describing: receivedError))>")
}
}
}
}
}
| mit | 0d94cffa7c9cab60f49c282a16254e17 | 42.510417 | 145 | 0.497127 | 5.844683 | false | false | false | false |
iceman201/NZAirQuality | Pods/ScrollableGraphView/Classes/Drawing/LineDrawingLayer.swift | 3 | 6008 |
import UIKit
internal class LineDrawingLayer : ScrollableGraphViewDrawingLayer {
private var currentLinePath = UIBezierPath()
private var lineStyle: ScrollableGraphViewLineStyle
private var shouldFill: Bool
private var lineCurviness: CGFloat
init(frame: CGRect, lineWidth: CGFloat, lineColor: UIColor, lineStyle: ScrollableGraphViewLineStyle, lineJoin: String, lineCap: String, shouldFill: Bool, lineCurviness: CGFloat) {
self.lineStyle = lineStyle
self.shouldFill = shouldFill
self.lineCurviness = lineCurviness
super.init(viewportWidth: frame.size.width, viewportHeight: frame.size.height)
self.lineWidth = lineWidth
self.strokeColor = lineColor.cgColor
self.lineJoin = convertToCAShapeLayerLineJoin(lineJoin)
self.lineCap = convertToCAShapeLayerLineCap(lineCap)
// Setup
self.fillColor = UIColor.clear.cgColor // This is handled by the fill drawing layer.
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal func createLinePath() -> UIBezierPath {
guard let owner = owner else {
return UIBezierPath()
}
// Can't really do anything without the delegate.
guard let delegate = self.owner?.graphViewDrawingDelegate else {
return currentLinePath
}
currentLinePath.removeAllPoints()
let pathSegmentAdder = lineStyle == .straight ? addStraightLineSegment : addCurvedLineSegment
let activePointsInterval = delegate.intervalForActivePoints()
let pointPadding = delegate.paddingForPoints()
let min = delegate.rangeForActivePoints().min
zeroYPosition = delegate.calculatePosition(atIndex: 0, value: min).y
let viewport = delegate.currentViewport()
let viewportWidth = viewport.width
let viewportHeight = viewport.height
// Connect the line to the starting edge if we are filling it.
if(shouldFill) {
// Add a line from the base of the graph to the first data point.
let firstDataPoint = owner.graphPoint(forIndex: activePointsInterval.lowerBound)
let viewportLeftZero = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding), y: zeroYPosition)
let leftFarEdgeTop = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding + viewportWidth), y: zeroYPosition)
let leftFarEdgeBottom = CGPoint(x: firstDataPoint.location.x - (pointPadding.leftmostPointPadding + viewportWidth), y: viewportHeight)
currentLinePath.move(to: leftFarEdgeBottom)
pathSegmentAdder(leftFarEdgeBottom, leftFarEdgeTop, currentLinePath)
pathSegmentAdder(leftFarEdgeTop, viewportLeftZero, currentLinePath)
pathSegmentAdder(viewportLeftZero, CGPoint(x: firstDataPoint.location.x, y: firstDataPoint.location.y), currentLinePath)
}
else {
let firstDataPoint = owner.graphPoint(forIndex: activePointsInterval.lowerBound)
currentLinePath.move(to: firstDataPoint.location)
}
// Connect each point on the graph with a segment.
for i in activePointsInterval.lowerBound ..< activePointsInterval.upperBound - 1 {
let startPoint = owner.graphPoint(forIndex: i).location
let endPoint = owner.graphPoint(forIndex: i+1).location
pathSegmentAdder(startPoint, endPoint, currentLinePath)
}
// Connect the line to the ending edge if we are filling it.
if(shouldFill) {
// Add a line from the last data point to the base of the graph.
let lastDataPoint = owner.graphPoint(forIndex: activePointsInterval.upperBound - 1).location
let viewportRightZero = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding), y: zeroYPosition)
let rightFarEdgeTop = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding + viewportWidth), y: zeroYPosition)
let rightFarEdgeBottom = CGPoint(x: lastDataPoint.x + (pointPadding.rightmostPointPadding + viewportWidth), y: viewportHeight)
pathSegmentAdder(lastDataPoint, viewportRightZero, currentLinePath)
pathSegmentAdder(viewportRightZero, rightFarEdgeTop, currentLinePath)
pathSegmentAdder(rightFarEdgeTop, rightFarEdgeBottom, currentLinePath)
}
return currentLinePath
}
private func addStraightLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
path.addLine(to: endPoint)
}
private func addCurvedLineSegment(startPoint: CGPoint, endPoint: CGPoint, inPath path: UIBezierPath) {
// calculate control points
let difference = endPoint.x - startPoint.x
var x = startPoint.x + (difference * lineCurviness)
var y = startPoint.y
let controlPointOne = CGPoint(x: x, y: y)
x = endPoint.x - (difference * lineCurviness)
y = endPoint.y
let controlPointTwo = CGPoint(x: x, y: y)
// add curve from start to end
currentLinePath.addCurve(to: endPoint, controlPoint1: controlPointOne, controlPoint2: controlPointTwo)
}
override func updatePath() {
self.path = createLinePath().cgPath
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToCAShapeLayerLineJoin(_ input: String) -> CAShapeLayerLineJoin {
return CAShapeLayerLineJoin(rawValue: input)
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToCAShapeLayerLineCap(_ input: String) -> CAShapeLayerLineCap {
return CAShapeLayerLineCap(rawValue: input)
}
| mit | 6cf671960b2c03c2c799a13ad897a2b7 | 42.536232 | 183 | 0.670273 | 5.511927 | false | false | false | false |
robertofrontado/RxGcm-iOS | iOS/Pods/Nimble/Sources/Nimble/Matchers/AsyncMatcherWrapper.swift | 43 | 6438 | import Foundation
#if _runtime(_ObjC)
public struct AsyncDefaults {
public static var Timeout: TimeInterval = 1
public static var PollInterval: TimeInterval = 0.01
}
internal struct AsyncMatcherWrapper<T, U>: Matcher
where U: Matcher, U.ValueType == T
{
let fullMatcher: U
let timeoutInterval: TimeInterval
let pollInterval: TimeInterval
init(fullMatcher: U, timeoutInterval: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval) {
self.fullMatcher = fullMatcher
self.timeoutInterval = timeoutInterval
self.pollInterval = pollInterval
}
func matches(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let fnName = "expect(...).toEventually(...)"
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: fnName) {
try self.fullMatcher.matches(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventually(...).")
}
}
func doesNotMatch(_ actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let uncachedExpression = actualExpression.withoutCaching()
let result = pollBlock(
pollInterval: pollInterval,
timeoutInterval: timeoutInterval,
file: actualExpression.location.file,
line: actualExpression.location.line,
fnName: "expect(...).toEventuallyNot(...)") {
try self.fullMatcher.doesNotMatch(uncachedExpression, failureMessage: failureMessage)
}
switch (result) {
case let .completed(isSuccessful): return isSuccessful
case .timedOut: return false
case let .errorThrown(error):
failureMessage.actualValue = "an unexpected error thrown: <\(error)>"
return false
case let .raisedException(exception):
failureMessage.actualValue = "an unexpected exception thrown: <\(exception)>"
return false
case .blockedRunLoop:
failureMessage.postfixMessage += " (timed out, but main thread was unresponsive)."
return false
case .incomplete:
internalError("Reached .incomplete state for toEventuallyNot(...).")
}
}
}
private let toEventuallyRequiresClosureError = FailureMessage(stringValue: "expect(...).toEventually(...) requires an explicit closure (eg - expect { ... }.toEventually(...) )\nSwift 1.2 @autoclosure behavior has changed in an incompatible way for Nimble to function")
extension Expectation {
/// Tests the actual value using a matcher to match by checking continuously
/// at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionMatches(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
to: "to eventually",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toEventuallyNot<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
if expression.isClosure {
let (pass, msg) = expressionDoesNotMatch(
expression,
matcher: AsyncMatcherWrapper(
fullMatcher: matcher,
timeoutInterval: timeout,
pollInterval: pollInterval),
toNot: "to eventually not",
description: description
)
verify(pass, msg)
} else {
verify(false, toEventuallyRequiresClosureError)
}
}
/// Tests the actual value using a matcher to not match by checking
/// continuously at each pollInterval until the timeout is reached.
///
/// Alias of toEventuallyNot()
///
/// @discussion
/// This function manages the main run loop (`NSRunLoop.mainRunLoop()`) while this function
/// is executing. Any attempts to touch the run loop may cause non-deterministic behavior.
public func toNotEventually<U>(_ matcher: U, timeout: TimeInterval = AsyncDefaults.Timeout, pollInterval: TimeInterval = AsyncDefaults.PollInterval, description: String? = nil)
where U: Matcher, U.ValueType == T
{
return toEventuallyNot(matcher, timeout: timeout, pollInterval: pollInterval, description: description)
}
}
#endif
| apache-2.0 | a65ef39d2050c1eb4dc87338cd707cf5 | 42.5 | 268 | 0.646474 | 5.712511 | false | false | false | false |
AndreMuis/Algorithms | StairClimbing.playground/Contents.swift | 1 | 700 | //
// A child can climb a set of stairs by takinbg 1, 2 or 3 steps at a time.
// How man ways can the child climb the stairs?
//
func countPaths(stair stair : Int, stairs : Int) -> Int
{
var paths : Int
if stair > stairs
{
paths = 0
}
else if stair == stairs
{
paths = 1
}
else
{
paths = countPaths(stair: stair + 1, stairs: stairs) +
countPaths(stair: stair + 2, stairs: stairs) +
countPaths(stair: stair + 3, stairs: stairs)
}
return paths
}
let startStair : Int = 1
countPaths(stair: startStair, stairs: 2)
countPaths(stair: startStair, stairs: 3)
countPaths(stair: startStair, stairs: 4)
| mit | c4b3adb3b91724578de58b17c3fdf9e8 | 19 | 74 | 0.587143 | 3.553299 | false | false | false | false |
Fenrikur/ef-app_ios | Domain Model/EurofurenceModelTests/EurofurenceSessionTestBuilder.swift | 1 | 13205 | import EurofurenceModel
import EurofurenceModelTestDoubles
import Foundation
class EurofurenceSessionTestBuilder {
class Context {
var session: EurofurenceSession
var clock: StubClock
var notificationTokenRegistration: CapturingRemoteNotificationsTokenRegistration
var credentialStore: CapturingCredentialStore
var api: FakeAPI
var dataStore: InMemoryDataStore
var conventionStartDateRepository: StubConventionStartDateRepository
var imageRepository: CapturingImageRepository
var significantTimeChangeAdapter: CapturingSignificantTimeChangeAdapter
var urlOpener: CapturingURLOpener
var longRunningTaskManager: FakeLongRunningTaskManager
var mapCoordinateRender: CapturingMapCoordinateRender
var refreshObserver: CapturingRefreshServiceObserver
private(set) var lastRefreshError: RefreshServiceError?
fileprivate init(session: EurofurenceSession,
clock: StubClock,
notificationTokenRegistration: CapturingRemoteNotificationsTokenRegistration,
credentialStore: CapturingCredentialStore,
api: FakeAPI,
dataStore: InMemoryDataStore,
conventionStartDateRepository: StubConventionStartDateRepository,
imageRepository: CapturingImageRepository,
significantTimeChangeAdapter: CapturingSignificantTimeChangeAdapter,
urlOpener: CapturingURLOpener,
longRunningTaskManager: FakeLongRunningTaskManager,
mapCoordinateRender: CapturingMapCoordinateRender,
refreshObserver: CapturingRefreshServiceObserver) {
self.session = session
self.clock = clock
self.notificationTokenRegistration = notificationTokenRegistration
self.credentialStore = credentialStore
self.api = api
self.dataStore = dataStore
self.conventionStartDateRepository = conventionStartDateRepository
self.imageRepository = imageRepository
self.significantTimeChangeAdapter = significantTimeChangeAdapter
self.urlOpener = urlOpener
self.longRunningTaskManager = longRunningTaskManager
self.mapCoordinateRender = mapCoordinateRender
self.refreshObserver = refreshObserver
}
var services: Services {
return session.services
}
var additionalServicesRepository: AdditionalServicesRepository {
return session.repositories.additionalServices
}
var notificationsService: NotificationService {
return services.notifications
}
var refreshService: RefreshService {
return services.refresh
}
var announcementsService: AnnouncementsService {
return services.announcements
}
var authenticationService: AuthenticationService {
return services.authentication
}
var eventsService: EventsService {
return services.events
}
var dealersService: DealersService {
return services.dealers
}
var knowledgeService: KnowledgeService {
return services.knowledge
}
var contentLinksService: ContentLinksService {
return services.contentLinks
}
var conventionCountdownService: ConventionCountdownService {
return services.conventionCountdown
}
var collectThemAllService: CollectThemAllService {
return services.collectThemAll
}
var mapsService: MapsService {
return services.maps
}
var sessionStateService: SessionStateService {
return services.sessionState
}
var privateMessagesService: PrivateMessagesService {
return services.privateMessages
}
var authenticationToken: String? {
return credentialStore.persistedCredential?.authenticationToken
}
func tickTime(to time: Date) {
clock.tickTime(to: time)
}
func registerForRemoteNotifications(_ deviceToken: Data = Data()) {
notificationsService.storeRemoteNotificationsToken(deviceToken)
}
func login(registrationNumber: Int = 0,
username: String = "",
password: String = "",
completionHandler: @escaping (LoginResult) -> Void = { _ in }) {
let arguments = LoginArguments(registrationNumber: registrationNumber, username: username, password: password)
authenticationService.login(arguments, completionHandler: completionHandler)
}
func loginSuccessfully() {
login()
api.simulateLoginResponse(LoginResponse(userIdentifier: .random, username: .random, token: .random, tokenValidUntil: Date(timeIntervalSinceNow: 1)))
}
func logoutSuccessfully() {
authenticationService.logout(completionHandler: { (_) in })
notificationTokenRegistration.succeedLastRequest()
}
@discardableResult
func refreshLocalStore(completionHandler: ((RefreshServiceError?) -> Void)? = nil) -> Progress {
return session.services.refresh.refreshLocalStore { (error) in
self.lastRefreshError = error
completionHandler?(error)
}
}
func performSuccessfulSync(response: ModelCharacteristics) {
refreshLocalStore()
simulateSyncSuccess(response)
}
func simulateSyncSuccess(_ response: ModelCharacteristics) {
api.simulateSuccessfulSync(response)
}
func simulateSyncAPIError() {
api.simulateUnsuccessfulSync()
}
func simulateSignificantTimeChange() {
significantTimeChangeAdapter.simulateSignificantTimeChange()
}
}
private var api = FakeAPI()
private var credentialStore = CapturingCredentialStore()
private var clock = StubClock()
private var dataStore = InMemoryDataStore()
private var userPreferences: UserPreferences = StubUserPreferences()
private var timeIntervalForUpcomingEventsSinceNow: TimeInterval = .greatestFiniteMagnitude
private var imageRepository = CapturingImageRepository()
private var urlOpener: CapturingURLOpener = CapturingURLOpener()
private var collectThemAllRequestFactory: CollectThemAllRequestFactory = StubCollectThemAllRequestFactory()
private var companionAppURLRequestFactory: CompanionAppURLRequestFactory = StubCompanionAppURLRequestFactory()
private var forceUpgradeRequired: ForceRefreshRequired = StubForceRefreshRequired(isForceRefreshRequired: false)
private var longRunningTaskManager: FakeLongRunningTaskManager = FakeLongRunningTaskManager()
private var conventionStartDateRepository = StubConventionStartDateRepository()
private var refreshCollaboration: RefreshCollaboration?
func with(_ currentDate: Date) -> EurofurenceSessionTestBuilder {
clock = StubClock(currentDate: currentDate)
return self
}
func with(_ persistedCredential: Credential?) -> EurofurenceSessionTestBuilder {
credentialStore = CapturingCredentialStore(persistedCredential: persistedCredential)
return self
}
@discardableResult
func with(_ dataStore: InMemoryDataStore) -> EurofurenceSessionTestBuilder {
self.dataStore = dataStore
return self
}
@discardableResult
func with(_ userPreferences: UserPreferences) -> EurofurenceSessionTestBuilder {
self.userPreferences = userPreferences
return self
}
@discardableResult
func with(timeIntervalForUpcomingEventsSinceNow: TimeInterval) -> EurofurenceSessionTestBuilder {
self.timeIntervalForUpcomingEventsSinceNow = timeIntervalForUpcomingEventsSinceNow
return self
}
@discardableResult
func with(_ api: FakeAPI) -> EurofurenceSessionTestBuilder {
self.api = api
return self
}
@discardableResult
func with(_ imageRepository: CapturingImageRepository) -> EurofurenceSessionTestBuilder {
self.imageRepository = imageRepository
return self
}
@discardableResult
func with(_ urlOpener: CapturingURLOpener) -> EurofurenceSessionTestBuilder {
self.urlOpener = urlOpener
return self
}
@discardableResult
func with(_ collectThemAllRequestFactory: CollectThemAllRequestFactory) -> EurofurenceSessionTestBuilder {
self.collectThemAllRequestFactory = collectThemAllRequestFactory
return self
}
@discardableResult
func with(_ companionAppURLRequestFactory: CompanionAppURLRequestFactory) -> EurofurenceSessionTestBuilder {
self.companionAppURLRequestFactory = companionAppURLRequestFactory
return self
}
@discardableResult
func with(_ longRunningTaskManager: FakeLongRunningTaskManager) -> EurofurenceSessionTestBuilder {
self.longRunningTaskManager = longRunningTaskManager
return self
}
func loggedInWithValidCredential() -> EurofurenceSessionTestBuilder {
let credential = Credential(username: "User",
registrationNumber: 42,
authenticationToken: "Token",
tokenExpiryDate: .distantFuture)
return with(credential)
}
@discardableResult
func with(_ forceUpgradeRequired: ForceRefreshRequired) -> EurofurenceSessionTestBuilder {
self.forceUpgradeRequired = forceUpgradeRequired
return self
}
@discardableResult
func with(_ conventionStartDateRepository: StubConventionStartDateRepository) -> EurofurenceSessionTestBuilder {
self.conventionStartDateRepository = conventionStartDateRepository
return self
}
@discardableResult
func with(_ refreshCollaboration: RefreshCollaboration) -> EurofurenceSessionTestBuilder {
self.refreshCollaboration = refreshCollaboration
return self
}
@discardableResult
func build() -> Context {
let notificationTokenRegistration = CapturingRemoteNotificationsTokenRegistration()
let significantTimeChangeAdapter = CapturingSignificantTimeChangeAdapter()
let mapCoordinateRender = CapturingMapCoordinateRender()
let builder = makeSessionBuilder()
.with(timeIntervalForUpcomingEventsSinceNow: timeIntervalForUpcomingEventsSinceNow)
.with(significantTimeChangeAdapter)
.with(mapCoordinateRender)
.with(notificationTokenRegistration)
includeRefreshCollaboration(builder)
let session = builder.build()
let refreshObserver = CapturingRefreshServiceObserver()
session.services.refresh.add(refreshObserver)
return Context(session: session,
clock: clock,
notificationTokenRegistration: notificationTokenRegistration,
credentialStore: credentialStore,
api: api,
dataStore: dataStore,
conventionStartDateRepository: conventionStartDateRepository,
imageRepository: imageRepository,
significantTimeChangeAdapter: significantTimeChangeAdapter,
urlOpener: urlOpener,
longRunningTaskManager: longRunningTaskManager,
mapCoordinateRender: mapCoordinateRender,
refreshObserver: refreshObserver)
}
private func makeSessionBuilder() -> EurofurenceSessionBuilder {
let conventionIdentifier = ConventionIdentifier(identifier: ModelCharacteristics.testConventionIdentifier)
let mandatory = EurofurenceSessionBuilder.Mandatory(
conventionIdentifier: conventionIdentifier,
conventionStartDateRepository: conventionStartDateRepository,
shareableURLFactory: FakeShareableURLFactory()
)
return EurofurenceSessionBuilder(mandatory: mandatory)
.with(api)
.with(clock)
.with(credentialStore)
.with(StubDataStoreFactory(conventionIdentifier: conventionIdentifier, dataStore: dataStore))
.with(userPreferences)
.with(imageRepository)
.with(urlOpener)
.with(collectThemAllRequestFactory)
.with(longRunningTaskManager)
.with(forceUpgradeRequired)
.with(companionAppURLRequestFactory)
}
private func includeRefreshCollaboration(_ builder: EurofurenceSessionBuilder) {
if let refreshCollaboration = refreshCollaboration {
builder.with(refreshCollaboration)
}
}
}
| mit | a88a08ef36f491ff6b88eee023c3e34d | 38.300595 | 160 | 0.672321 | 7.418539 | false | true | false | false |
xmartlabs/Swift-Project-Template | Project-iOS/XLProjectName/XLProjectName/Helpers/Opera/Pagination/PaginationRequestType+Rx.swift | 1 | 3056 | //
// PaginationRequestType+Rx.swift
// Opera
//
// Copyright (c) 2019 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// 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 RxSwift
import Alamofire
extension Reactive where Base: PaginationRequestType {
/**
Returns a `Observable` of [Response] for the PaginationRequestType instance.
If something goes wrong a Opera.Error error is propagated through the result sequence.
- returns: An instance of `Observable<Response>`
*/
var collection: Single<Base.Response> {
let myPage = base.page
return Single<Base.Response>.create { single in
let req = NetworkManager.singleton.response(route: self.base) { (response: DataResponse<Base.Response, XLProjectNameError>) in
switch response.result {
case .failure(let error):
single(.error(error))
case .success(let value):
let previousPage = response.response?.linkPagePrameter((self as? WebLinkingSettings)?.prevRelationName ?? Default.prevRelationName,
pageParameterName: (self as? WebLinkingSettings)?
.relationPageParamName ?? Default.relationPageParamName)
let nextPage = response.response?.linkPagePrameter((self as? WebLinkingSettings)?.nextRelationName ?? Default.nextRelationName,
pageParameterName: (self as? WebLinkingSettings)?
.relationPageParamName ?? Default.relationPageParamName)
let baseResponse = Base.Response(elements: value.elements, previousPage: previousPage, nextPage: nextPage, page: myPage)
single(.success(baseResponse))
}
}
return Disposables.create {
req.cancel()
}
}
}
}
| mit | 0b30497350975d030c2a919b785ffab2 | 48.290323 | 151 | 0.646924 | 5.241852 | false | false | false | false |
r4phab/ECAB | ECAB/TestsTableViewController.swift | 1 | 3586 | //
// GamesTableViewController.swift
// ECAB
//
// Created by Boris Yurkevich on 3/9/15.
// Copyright (c) 2015 Oliver Braddick and Jan Atkinson. All rights reserved.
//
import UIKit
class TestsTableViewController: UITableViewController {
let model = Model.sharedInstance
private let reuseIdentifier = "Games Table Cell"
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return model.games.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! SubtestCell
cell.title.text = model.games[indexPath.row].rawValue
switch model.games[indexPath.row].rawValue {
case Game.AuditorySustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
cell.subtitle.text = "Touch when the animal is heared"
case Game.VisualSearch.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSearch.rawValue)
cell.subtitle.text = "Touch the red apples"
case Game.VisualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_visualSustain.rawValue)
cell.subtitle.text = "Touch when the animal is seen"
case Game.BalloonSorting.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_balloonSorting.rawValue)
cell.subtitle.text = "Work out the balloons"
case Game.DualSustain.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_dualTask.rawValue)
cell.subtitle.text = "Touch when animal heard or seen"
case Game.Flanker.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_flanker.rawValue)
cell.subtitle.text = "Touch the side the fish is facing"
case Game.VerbalOpposites.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_verbalOpposites.rawValue)
cell.subtitle.text = "Speak the animal name"
case Game.Counterpointing.rawValue:
cell.icon.image = UIImage(named: Picture.Icon_counterpointing.rawValue)
cell.subtitle.text = "Touch the side of the dog"
default:
cell.icon.image = UIImage(named: Picture.Icon_auditory.rawValue)
}
return cell
}
// Select correct test row when the view is displayed
override func viewWillAppear(animated: Bool) {
if(model.data != nil){
selectRow(model.data.selectedGame.integerValue)
}
}
// MARK: — Table View delegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
model.data.selectedGame = indexPath.row
model.save()
let navVC = splitViewController!.viewControllers.last as! UINavigationController
let detailVC = navVC.topViewController as! TestViewController
detailVC.showTheGame(model.data.selectedGame.integerValue)
}
func selectRow(index:Int) {
let rowToSelect:NSIndexPath = NSIndexPath(forRow: index, inSection: 0)
self.tableView.selectRowAtIndexPath(rowToSelect, animated: false, scrollPosition:UITableViewScrollPosition.None)
}
}
| mit | 9e2582f6f4224078f0fb7fb92962e199 | 38.822222 | 120 | 0.657645 | 4.836707 | false | false | false | false |
NunoAlexandre/broccoli_mobile | ios/Carthage/Checkouts/Eureka/Source/Rows/PickerInlineRow.swift | 2 | 3187 | // PickerInlineRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.com )
//
//
// 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
open class PickerInlineCell<T: Equatable> : Cell<T>, CellType {
required public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override func setup() {
super.setup()
accessoryType = .none
editingAccessoryType = .none
}
open override func update() {
super.update()
selectionStyle = row.isDisabled ? .none : .default
}
open override func didSelect() {
super.didSelect()
row.deselect()
}
}
//MARK: PickerInlineRow
open class _PickerInlineRow<T> : Row<PickerInlineCell<T>>, NoValueDisplayTextConformance where T: Equatable {
public typealias InlineRow = PickerRow<T>
open var options = [T]()
open var noValueDisplayText: String?
required public init(tag: String?) {
super.init(tag: tag)
}
}
/// A generic inline row where the user can pick an option from a picker view which shows and hides itself automatically
public final class PickerInlineRow<T> : _PickerInlineRow<T>, RowType, InlineRowType where T: Equatable {
required public init(tag: String?) {
super.init(tag: tag)
onExpandInlineRow { cell, row, _ in
let color = cell.detailTextLabel?.textColor
row.onCollapseInlineRow { cell, _, _ in
cell.detailTextLabel?.textColor = color
}
cell.detailTextLabel?.textColor = cell.tintColor
}
}
public override func customDidSelect() {
super.customDidSelect()
if !isDisabled {
toggleInlineRow()
}
}
public func setupInlineRow(_ inlineRow: InlineRow) {
inlineRow.options = self.options
inlineRow.displayValueFor = self.displayValueFor
}
}
| mit | d74b414f21134180d7b7c426cf672f8b | 33.268817 | 120 | 0.677753 | 4.799699 | false | false | false | false |
xglofter/PicturePicker | PicturePicker/AlbumTableViewController.swift | 1 | 6340 | //
// AlbumTableViewController.swift
//
// Created by Richard on 2017/4/20.
// Copyright © 2017年 Richard. All rights reserved.
//
import UIKit
import Photos
open class AlbumTableViewController: UITableViewController {
public enum AlbumSection: Int {
case allPhotos = 0
case otherAlbumPhotos
static let count = 2
}
fileprivate(set) var allPhotos: PHFetchResult<PHAsset>!
fileprivate(set) lazy var otherAlbumTitles = [String]()
fileprivate(set) lazy var otherAlbumPhotos = [PHFetchResult<PHAsset>]()
fileprivate(set) var isFirstEnter = true
// MARK: - Lifecycle
public init(with allPhotos: PHFetchResult<PHAsset>) {
super.init(nibName: nil, bundle: nil)
self.allPhotos = allPhotos
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
setup()
fetchAlbums()
// 监测系统相册增加
PHPhotoLibrary.shared().register(self)
// 注册cell
tableView.register(AlbumTableViewCell.self, forCellReuseIdentifier: AlbumTableViewCell.cellIdentity)
tableView.separatorStyle = .none
}
// override open func viewDidAppear(_ animated: Bool) {
// super.viewDidAppear(animated)
//
// if isFirstEnter {
// isFirstEnter = false
// let gridVC = PhotosGridViewController(with: allPhotos)
// gridVC.title = "所有照片"
// self.navigationController?.pushViewController(gridVC, animated: true)
// }
// }
// MARK: - Table view data source
override open func numberOfSections(in tableView: UITableView) -> Int {
return AlbumSection.count
}
override open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch AlbumSection(rawValue: section)! {
case .allPhotos:
return 1
case .otherAlbumPhotos:
return otherAlbumPhotos.count
}
}
override open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return PickerConfig.albumCellHeight
}
override open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AlbumTableViewCell", for: indexPath) as! AlbumTableViewCell
cell.accessoryType = .disclosureIndicator
switch AlbumSection(rawValue: indexPath.section)! {
case .allPhotos:
cell.setAlbumPreview(asset: allPhotos.firstObject)
cell.setAlbumTitle(title: "所有照片", fileCount: allPhotos.count)
case .otherAlbumPhotos:
let photoAssets = otherAlbumPhotos[indexPath.row]
let asset = photoAssets.firstObject
cell.setAlbumPreview(asset: asset)
cell.setAlbumTitle(title: otherAlbumTitles[indexPath.row], fileCount: photoAssets.count)
}
return cell
}
override open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch AlbumSection.init(rawValue: indexPath.section)! {
case .allPhotos:
let gridVC = PhotosGridViewController(with: allPhotos)
gridVC.title = "所有照片"
self.navigationController?.pushViewController(gridVC, animated: true)
case .otherAlbumPhotos:
let gridVC = PhotosGridViewController(with: otherAlbumPhotos[indexPath.row])
gridVC.title = otherAlbumTitles[indexPath.row]
self.navigationController?.pushViewController(gridVC, animated: true)
}
}
}
// MARK: - PHPhotoLibraryChangeObserver
extension AlbumTableViewController: PHPhotoLibraryChangeObserver {
public func photoLibraryDidChange(_ changeInstance: PHChange) {
DispatchQueue.main.sync {
if let _ = changeInstance.changeDetails(for: allPhotos) {
fetchAlbums()
tableView?.reloadData()
}
}
}
}
// MARK: - Private Function
private extension AlbumTableViewController {
func setup() {
navigationItem.title = "照片"
self.view.backgroundColor = PickerConfig.pickerBackgroundColor
let cancelTitle = "取消"
let barItem = UIBarButtonItem(title: cancelTitle, style: .plain, target: self, action: #selector(onDismissAction))
navigationItem.rightBarButtonItem = barItem
}
@objc func onDismissAction() {
self.dismiss(animated: true, completion: {
PickerManager.shared.endChoose(isFinish: false)
})
}
func fetchAlbums() {
// let allPhotoOptions = PHFetchOptions()
// allPhotoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
// allPhotoOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)
// allPhotos = PHAsset.fetchAssets(with: allPhotoOptions)
let smartAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .any, options: nil)
let userCollections = PHCollectionList.fetchTopLevelUserCollections(with: nil)
otherAlbumTitles.removeAll()
otherAlbumPhotos.removeAll()
func getAlbumNotEmpty(from albums: PHFetchResult<PHAssetCollection>) {
let photoOptions = PHFetchOptions()
photoOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
for index in 0 ..< albums.count {
let collection = albums.object(at: index)
let asset = PHAsset.fetchAssets(in: collection, options: photoOptions)
if asset.count != 0 {
self.otherAlbumTitles.append(collection.localizedTitle ?? "")
self.otherAlbumPhotos.append(asset)
}
}
}
getAlbumNotEmpty(from: smartAlbums)
getAlbumNotEmpty(from: userCollections as! PHFetchResult<PHAssetCollection>)
print(otherAlbumPhotos.count)
}
}
| mit | 9c59d9ae39bde0739999b453573c15d4 | 34.508475 | 125 | 0.642482 | 5.330789 | false | false | false | false |
groschovskiy/firebase-for-banking-app | Demo/Pods/CircleMenu/CircleMenuLib/CircleMenu.swift | 2 | 17367 | //
// CircleMenu.swift
// ButtonTest
//
// Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
// MARK: helpers
func Init<Type>(_ value: Type, block: (_ object: Type) -> Void) -> Type {
block(value)
return value
}
// MARK: Protocol
/**
* CircleMenuDelegate
*/
@objc public protocol CircleMenuDelegate {
/**
Tells the delegate the circle menu is about to draw a button for a particular index.
- parameter circleMenu: The circle menu object informing the delegate of this impending event.
- parameter button: A circle menu button object that circle menu is going to use when drawing the row. Don't change button.tag
- parameter atIndex: An button index.
*/
@objc optional func circleMenu(_ circleMenu: CircleMenu, willDisplay button: UIButton, atIndex: Int)
/**
Tells the delegate that a specified index is about to be selected.
- parameter circleMenu: A circle menu object informing the delegate about the impending selection.
- parameter button: A selected circle menu button. Don't change button.tag
- parameter atIndex: Selected button index
*/
@objc optional func circleMenu(_ circleMenu: CircleMenu, buttonWillSelected button: UIButton, atIndex: Int)
/**
Tells the delegate that the specified index is now selected.
- parameter circleMenu: A circle menu object informing the delegate about the new index selection.
- parameter button: A selected circle menu button. Don't change button.tag
- parameter atIndex: Selected button index
*/
@objc optional func circleMenu(_ circleMenu: CircleMenu, buttonDidSelected button: UIButton, atIndex: Int)
/**
Tells the delegate that the menu was collapsed - the cancel action.
- parameter circleMenu: A circle menu object informing the delegate about the new index selection.
*/
@objc optional func menuCollapsed(_ circleMenu: CircleMenu)
}
// MARK: CircleMenu
/// A Button object with pop ups buttons
open class CircleMenu: UIButton {
// MARK: properties
/// Buttons count
@IBInspectable open var buttonsCount: Int = 3
/// Circle animation duration
@IBInspectable open var duration: Double = 2
/// Distance between center button and buttons
@IBInspectable open var distance: Float = 100
/// Delay between show buttons
@IBInspectable open var showDelay: Double = 0
/// The object that acts as the delegate of the circle menu.
@IBOutlet weak open var delegate: AnyObject? //CircleMenuDelegate?
var buttons: [UIButton]?
weak var platform: UIView?
fileprivate var customNormalIconView: UIImageView?
fileprivate var customSelectedIconView: UIImageView?
/**
Initializes and returns a circle menu object.
- parameter frame: A rectangle specifying the initial location and size of the circle menu in its superview’s coordinates.
- parameter normalIcon: The image to use for the specified normal state.
- parameter selectedIcon: The image to use for the specified selected state.
- parameter buttonsCount: The number of buttons.
- parameter duration: The duration, in seconds, of the animation.
- parameter distance: Distance between center button and sub buttons.
- returns: A newly created circle menu.
*/
public init(frame: CGRect,
normalIcon: String?,
selectedIcon: String?,
buttonsCount: Int = 3,
duration: Double = 2,
distance: Float = 100) {
super.init(frame: frame)
if let icon = normalIcon {
setImage(UIImage(named: icon), for: UIControlState())
}
if let icon = selectedIcon {
setImage(UIImage(named: icon), for: .selected)
}
self.buttonsCount = buttonsCount
self.duration = duration
self.distance = distance
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
addActions()
customNormalIconView = addCustomImageView(state: UIControlState())
customSelectedIconView = addCustomImageView(state: .selected)
if customSelectedIconView != nil {
customSelectedIconView?.alpha = 0
}
setImage(UIImage(), for: UIControlState())
setImage(UIImage(), for: .selected)
}
// MARK: methods
/**
Hide button
- parameter duration: The duration, in seconds, of the animation.
- parameter hideDelay: The time to delay, in seconds.
*/
open func hideButtons(_ duration: Double, hideDelay: Double = 0) {
if buttons == nil {
return
}
buttonsAnimationIsShow(isShow: false, duration: duration, hideDelay: hideDelay)
tapBounceAnimation()
tapRotatedAnimation(0.3, isSelected: false)
}
/**
Check is sub buttons showed
*/
open func buttonsIsShown() -> Bool {
guard let buttons = self.buttons else {
return false
}
for button in buttons {
if button.alpha == 0 {
return false
}
}
return true
}
// MARK: create
fileprivate func createButtons(platform: UIView) -> [UIButton] {
var buttons = [UIButton]()
let step: Float = 360.0 / Float(self.buttonsCount)
for index in 0..<self.buttonsCount {
let angle: Float = Float(index) * step
let distance = Float(self.bounds.size.height/2.0)
let button = Init(CircleMenuButton(size: self.bounds.size, platform: platform, distance:distance, angle: angle)) {
$0.tag = index
$0.addTarget(self, action: #selector(CircleMenu.buttonHandler(_:)), for: UIControlEvents.touchUpInside)
$0.alpha = 0
}
buttons.append(button)
}
return buttons
}
fileprivate func addCustomImageView(state: UIControlState) -> UIImageView? {
guard let image = image(for: state) else {
return nil
}
let iconView = Init(UIImageView(image: image)) {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.contentMode = .center
$0.isUserInteractionEnabled = false
}
addSubview(iconView)
// added constraints
iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .height, relatedBy: .equal, toItem: nil,
attribute: .height, multiplier: 1, constant: bounds.size.height))
iconView.addConstraint(NSLayoutConstraint(item: iconView, attribute: .width, relatedBy: .equal, toItem: nil,
attribute: .width, multiplier: 1, constant: bounds.size.width))
addConstraint(NSLayoutConstraint(item: self, attribute: .centerX, relatedBy: .equal, toItem: iconView,
attribute: .centerX, multiplier: 1, constant:0))
addConstraint(NSLayoutConstraint(item: self, attribute: .centerY, relatedBy: .equal, toItem: iconView,
attribute: .centerY, multiplier: 1, constant:0))
return iconView
}
fileprivate func createPlatform() -> UIView {
let platform = Init(UIView(frame: .zero)) {
$0.backgroundColor = .clear
$0.translatesAutoresizingMaskIntoConstraints = false
}
superview?.insertSubview(platform, belowSubview: self)
// constraints
let sizeConstraints = [NSLayoutAttribute.width, .height].map {
NSLayoutConstraint(item: platform,
attribute: $0,
relatedBy: .equal,
toItem: nil,
attribute: $0,
multiplier: 1,
constant: CGFloat(distance * Float(2.0)))
}
platform.addConstraints(sizeConstraints)
let centerConstraints = [NSLayoutAttribute.centerX, .centerY].map {
NSLayoutConstraint(item: self,
attribute: $0,
relatedBy: .equal,
toItem: platform,
attribute: $0,
multiplier: 1,
constant:0)
}
superview?.addConstraints(centerConstraints)
return platform
}
// MARK: configure
fileprivate func addActions() {
self.addTarget(self, action: #selector(CircleMenu.onTap), for: UIControlEvents.touchUpInside)
}
// MARK: actions
func onTap() {
if buttonsIsShown() == false {
let platform = createPlatform()
buttons = createButtons(platform: platform)
self.platform = platform
}
let isShow = !buttonsIsShown()
let duration = isShow ? 0.5 : 0.2
buttonsAnimationIsShow(isShow: isShow, duration: duration)
tapBounceAnimation()
tapRotatedAnimation(0.3, isSelected: isShow)
}
func buttonHandler(_ sender: CircleMenuButton) {
guard let platform = self.platform else { return }
delegate?.circleMenu?(self, buttonWillSelected: sender, atIndex: sender.tag)
let circle = CircleMenuLoader(radius: CGFloat(distance),
strokeWidth: bounds.size.height,
platform: platform,
color: sender.backgroundColor)
if let container = sender.container { // rotation animation
sender.rotationAnimation(container.angleZ + 360, duration: duration)
container.superview?.bringSubview(toFront: container)
}
if let buttons = buttons {
circle.fillAnimation(duration, startAngle: -90 + Float(360 / buttons.count) * Float(sender.tag)) { [weak self] _ in
self?.buttons?.forEach { $0.alpha = 0 }
}
circle.hideAnimation(0.5, delay: duration) { [weak self] _ in
if self?.platform?.superview != nil { self?.platform?.removeFromSuperview() }
}
hideCenterButton(duration: 0.3)
showCenterButton(duration: 0.525, delay: duration)
if customNormalIconView != nil && customSelectedIconView != nil {
DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: {
self.delegate?.circleMenu?(self, buttonDidSelected: sender, atIndex: sender.tag)
})
}
}
}
// MARK: animations
fileprivate func buttonsAnimationIsShow(isShow: Bool, duration: Double, hideDelay: Double = 0) {
guard let buttons = self.buttons else {
return
}
let step: Float = 360.0 / Float(self.buttonsCount)
for index in 0..<self.buttonsCount {
guard case let button as CircleMenuButton = buttons[index] else { continue }
let angle: Float = Float(index) * step
if isShow == true {
delegate?.circleMenu?(self, willDisplay: button, atIndex: index)
button.rotatedZ(angle: angle, animated: false, delay: Double(index) * showDelay)
button.showAnimation(distance: distance, duration: duration, delay: Double(index) * showDelay)
} else {
button.hideAnimation(
distance: Float(self.bounds.size.height / 2.0),
duration: duration, delay: hideDelay)
self.delegate?.menuCollapsed?(self)
}
}
if isShow == false { // hide buttons and remove
self.buttons = nil
}
}
fileprivate func tapBounceAnimation() {
self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.3, initialSpringVelocity: 5,
options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 1, y: 1)
},
completion: nil)
}
fileprivate func tapRotatedAnimation(_ duration: Float, isSelected: Bool) {
let addAnimations: (_ view: UIImageView, _ isShow: Bool) -> () = { (view, isShow) in
var toAngle: Float = 180.0
var fromAngle: Float = 0
var fromScale = 1.0
var toScale = 0.2
var fromOpacity = 1
var toOpacity = 0
if isShow == true {
toAngle = 0
fromAngle = -180
fromScale = 0.2
toScale = 1.0
fromOpacity = 0
toOpacity = 1
}
let rotation = Init(CABasicAnimation(keyPath: "transform.rotation")) {
$0.duration = TimeInterval(duration)
$0.toValue = (toAngle.degrees)
$0.fromValue = (fromAngle.degrees)
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
let fade = Init(CABasicAnimation(keyPath: "opacity")) {
$0.duration = TimeInterval(duration)
$0.fromValue = fromOpacity
$0.toValue = toOpacity
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
$0.fillMode = kCAFillModeForwards
$0.isRemovedOnCompletion = false
}
let scale = Init(CABasicAnimation(keyPath: "transform.scale")) {
$0.duration = TimeInterval(duration)
$0.toValue = toScale
$0.fromValue = fromScale
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
}
view.layer.add(rotation, forKey: nil)
view.layer.add(fade, forKey: nil)
view.layer.add(scale, forKey: nil)
}
if let customNormalIconView = self.customNormalIconView {
addAnimations(customNormalIconView, !isSelected)
}
if let customSelectedIconView = self.customSelectedIconView {
addAnimations(customSelectedIconView, isSelected)
}
self.isSelected = isSelected
self.alpha = isSelected ? 0.3 : 1
}
fileprivate func hideCenterButton(duration: Double, delay: Double = 0) {
UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay),
options: UIViewAnimationOptions.curveEaseOut,
animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 0.001, y: 0.001)
}, completion: nil)
}
fileprivate func showCenterButton(duration: Float, delay: Double) {
UIView.animate( withDuration: TimeInterval(duration), delay: TimeInterval(delay), usingSpringWithDamping: 0.78,
initialSpringVelocity: 0, options: UIViewAnimationOptions.curveLinear,
animations: { () -> Void in
self.transform = CGAffineTransform(scaleX: 1, y: 1)
self.alpha = 1
},
completion: nil)
let rotation = Init(CASpringAnimation(keyPath: "transform.rotation")) {
$0.duration = TimeInterval(1.5)
$0.toValue = (0)
$0.fromValue = (Float(-180).degrees)
$0.damping = 10
$0.initialVelocity = 0
$0.beginTime = CACurrentMediaTime() + delay
}
let fade = Init(CABasicAnimation(keyPath: "opacity")) {
$0.duration = TimeInterval(0.01)
$0.toValue = 0
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
$0.fillMode = kCAFillModeForwards
$0.isRemovedOnCompletion = false
$0.beginTime = CACurrentMediaTime() + delay
}
let show = Init(CABasicAnimation(keyPath: "opacity")) {
$0.duration = TimeInterval(duration)
$0.toValue = 1
$0.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)
$0.fillMode = kCAFillModeForwards
$0.isRemovedOnCompletion = false
$0.beginTime = CACurrentMediaTime() + delay
}
customNormalIconView?.layer.add(rotation, forKey: nil)
customNormalIconView?.layer.add(show, forKey: nil)
customSelectedIconView?.layer.add(fade, forKey: nil)
}
}
// MARK: extension
internal extension Float {
var radians: Float {
return self * (Float(180) / Float(M_PI))
}
var degrees: Float {
return self * Float(M_PI) / 180.0
}
}
internal extension UIView {
var angleZ: Float {
return atan2(Float(self.transform.b), Float(self.transform.a)).radians
}
}
| apache-2.0 | 302190c53dc65ff005d2a4abe95660a8 | 34.579918 | 134 | 0.633473 | 4.783196 | false | false | false | false |
TinyCrayon/TinyCrayon-iOS-SDK | Examples/swift/TCMaskCustomization/TCMaskCustomization/ViewController.swift | 1 | 3538 | //
// The MIT License
//
// Copyright (C) 2016 TinyCrayon.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
import UIKit
import TCMask
class ViewController: UIViewController, TCMaskViewDelegate {
@IBOutlet weak var imageView: UIImageView!
override func viewDidAppear(_ animated: Bool) {
if (imageView.image == nil) {
presentTCMaskView()
}
}
@IBAction func editButtonTapped(_ sender: Any) {
presentTCMaskView()
}
func presentTCMaskView() {
let image = UIImage(named: "Balloon.JPEG")!
let maskView = TCMaskView(image: image)
maskView.delegate = self
// Change status bar style
maskView.statusBarStyle = UIStatusBarStyle.lightContent
// Change UI components style
maskView.topBar.backgroundColor = UIColor(white: 0.1, alpha: 1)
maskView.topBar.tintColor = UIColor.white
maskView.imageView.backgroundColor = UIColor(white: 0.2, alpha: 1)
maskView.bottomBar.backgroundColor = UIColor(white: 0.1, alpha: 1)
maskView.bottomBar.tintColor = UIColor.white
maskView.bottomBar.textColor = UIColor.white
maskView.settingView.backgroundColor = UIColor(white: 0.8, alpha: 0.9)
maskView.settingView.textColor = UIColor(white: 0.33, alpha: 1)
// Create a customized view mode with gray scale image
let grayScaleImage = image.convertToGrayScaleNoAlpha()
let viewMode = TCMaskViewMode(foregroundImage: grayScaleImage, backgroundImage: nil, isInverted: true)
// set customized viewMode to be the only view mode in TCMaskView
maskView.viewModes = [viewMode]
maskView.presentFrom(rootViewController: self, animated: true)
}
func tcMaskViewDidComplete(mask: TCMask, image: UIImage) {
imageView.image = mask.cutout(image: image, resize: true)
}
}
extension UIImage {
func convertToGrayScaleNoAlpha() -> UIImage {
let colorSpace = CGColorSpaceCreateDeviceGray();
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue)
let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)
context?.draw(self.cgImage!, in: CGRect(origin: CGPoint(), size: size))
return UIImage(cgImage: context!.makeImage()!)
}
}
| mit | 72456ceb4a08cd367303164b944df1eb | 39.666667 | 181 | 0.688807 | 4.618799 | false | false | false | false |
kiritantan/iQONTweetDisplay | iQONTweetDisplay/Tweet.swift | 1 | 1121 | //
// Tweet.swift
// iQONTweetDisplay
//
// Created by kiri on 2016/06/14.
// Copyright © 2016年 kiri. All rights reserved.
//
import UIKit
import SwiftyJSON
class Tweet {
let fullname: String
let username: String
let tweetText: String
let timeStamp: String
var avatar = UIImage()
init(jsonData: JSON) {
self.fullname = jsonData["user"]["name"].stringValue
self.username = jsonData["user"]["screen_name"].stringValue
self.tweetText = jsonData["text"].stringValue
self.timeStamp = jsonData["created_at"].stringValue
self.avatar = downloadImageFromURL(jsonData["user"]["profile_image_url_https"].stringValue)
}
private func downloadImageFromURL(imageURLString: String) -> UIImage {
let url = NSURL(string: imageURLString.stringByReplacingOccurrencesOfString("\\", withString: ""))
let imageData = NSData(contentsOfURL: url!)
var image = UIImage()
if let data = imageData {
if let img = UIImage(data: data) {
image = img
}
}
return image;
}
} | mit | 6f85284aa061a5cdab983a381ebf06d3 | 28.447368 | 106 | 0.627013 | 4.544715 | false | false | false | false |
ben-ng/swift | stdlib/private/StdlibCollectionUnittest/RangeSelection.swift | 1 | 3344 | //===--- RangeSelection.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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import StdlibUnittest
public enum RangeSelection {
case emptyRange
case leftEdge
case rightEdge
case middle
case leftHalf
case rightHalf
case full
case offsets(Int, Int)
public var isEmpty: Bool {
switch self {
case .emptyRange: return true
default: return false
}
}
public func range<C : Collection>(in c: C) -> Range<C.Index> {
switch self {
case .emptyRange: return c.endIndex..<c.endIndex
case .leftEdge: return c.startIndex..<c.startIndex
case .rightEdge: return c.endIndex..<c.endIndex
case .middle:
let start = c.index(c.startIndex, offsetBy: c.count / 4)
let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4 + 1)
return start..<end
case .leftHalf:
let start = c.startIndex
let end = c.index(start, offsetBy: c.count / 2)
return start..<end
case .rightHalf:
let start = c.index(c.startIndex, offsetBy: c.count / 2)
let end = c.endIndex
return start..<end
case .full:
return c.startIndex..<c.endIndex
case let .offsets(lowerBound, upperBound):
let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound))
let end = c.index(c.startIndex, offsetBy: numericCast(upperBound))
return start..<end
}
}
public func countableRange<C : Collection>(in c: C) -> CountableRange<C.Index> {
return CountableRange(range(in: c))
}
public func closedRange<C : Collection>(in c: C) -> ClosedRange<C.Index> {
switch self {
case .emptyRange: fatalError("Closed range cannot be empty")
case .leftEdge: return c.startIndex...c.startIndex
case .rightEdge:
let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1)
return beforeEnd...beforeEnd
case .middle:
let start = c.index(c.startIndex, offsetBy: c.count / 4)
let end = c.index(c.startIndex, offsetBy: 3 * c.count / 4)
return start...end
case .leftHalf:
let start = c.startIndex
let end = c.index(start, offsetBy: c.count / 2 - 1)
return start...end
case .rightHalf:
let start = c.index(c.startIndex, offsetBy: c.count / 2)
let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1)
return start...beforeEnd
case .full:
let beforeEnd = c.index(c.startIndex, offsetBy: c.count - 1)
return c.startIndex...beforeEnd
case let .offsets(lowerBound, upperBound):
let start = c.index(c.startIndex, offsetBy: numericCast(lowerBound))
let end = c.index(c.startIndex, offsetBy: numericCast(upperBound))
return start...end
}
}
public func countableClosedRange<C : Collection>(in c: C) -> CountableClosedRange<C.Index> {
return CountableClosedRange(closedRange(in: c))
}
}
| apache-2.0 | 31e9bb3d294af1947f0263c180bbc719 | 34.574468 | 94 | 0.621112 | 4.118227 | false | false | false | false |
relayr/apple-iot-smartphone | IoT/ios/sources/DeviceController.swift | 1 | 3369 | import UIKit
/// View Controller managing the "device data" screen.
///
/// It is in charge of arranging the meaning cells, and it manages the display shared objects.
class DeviceController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
/// The cell identifying each meaning graph.
private enum CellID : String {
case SimpleGraph = "SimpleGraphCellID"
case Map = "MapCellID"
}
/// Collection view holding the meaning cells
@IBOutlet private(set) weak var collectionView : UICollectionView!
/// The Metal device in charge of rendering all the graph in this collection controller.
static let device = MTLCreateSystemDefaultDevice()!
/// Inmutable instance containing reusable data for rendering graphs (of any type).
let sharedRenderState : GraphRenderState = GraphRenderState(withDevice: DeviceController.device, numTrianglesPerDot: 20)!
/// Instance containing all the data to be shown on the display.
let sharedRenderData : GraphRenderData = GraphRenderData(withDevice: DeviceController.device, supportedMeanings: [.Location, .Accelerometer, .Gyroscope, .Magnetometer])
// MARK: UICollectionViewDataSource
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if indexPath.row == 0 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellID.SimpleGraph.rawValue, forIndexPath: indexPath) as! SimpleGraphCellView
cell.graphView.renderData(withState: sharedRenderState, samplerType: .Accelerometer, graphMeaning: sharedRenderData[.Accelerometer]!)
return cell
} else {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellID.Map.rawValue, forIndexPath: indexPath) as! MapCellView
return cell
}
}
// MARK: UICollectionViewDelegateFlowLayout
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let bounds = self.collectionView.bounds
return CGSize(width: bounds.width, height: 0.4*bounds.height)
}
// MARK: UIViewController
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(animated: Bool) {
sharedRenderState.displayRefresh.paused = false
}
override func viewDidDisappear(animated: Bool) {
sharedRenderState.displayRefresh.paused = true
}
}
class SimpleGraphCellView : UICollectionViewCell {
@IBOutlet private(set) weak var meaningLabel : UILabel!
@IBOutlet private(set) weak var settingsIconView : UIView!
@IBOutlet private(set) weak var graphView : GraphView!
}
class MapCellView : UICollectionViewCell {
@IBOutlet private(set) weak var meaningLabel : UILabel!
@IBOutlet private(set) weak var settingsIconView : UIView!
@IBOutlet private(set) weak var mapView : UIImageView!
}
| mit | 7d4a99a734aec2ca317989dbe1aaee2f | 40.592593 | 169 | 0.744731 | 5.322275 | false | false | false | false |
rnystrom/GitHawk | FreetimeWatch Extension/Utility/V3Repository+HashableEquatable.swift | 1 | 623 | //
// V3Repository+HashableEquatable.swift
// FreetimeWatch Extension
//
// Created by Ryan Nystrom on 4/28/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import GitHubAPI
extension V3Repository: Hashable, Equatable {
public func hash(into hasher: inout Hasher) {
hasher.combine(fullName.hashValue)
}
public static func ==(lhs: V3Repository, rhs: V3Repository) -> Bool {
// a little bit lazy, but fast & cheap for the watch app's purpose
return lhs.id == rhs.id
&& lhs.fork == rhs.fork
&& lhs.isPrivate == rhs.isPrivate
}
}
| mit | 813c383494bc41914514d67e2ed4fb5e | 23.88 | 74 | 0.659164 | 3.8875 | false | false | false | false |
frootloops/swift | test/Parse/recovery.swift | 1 | 31387 | // RUN: %target-typecheck-verify-swift
//===--- Helper types used in this file.
protocol FooProtocol {}
//===--- Tests.
func garbage() -> () {
var a : Int
] this line is invalid, but we will stop at the keyword below... // expected-error{{expected expression}}
return a + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
func moreGarbage() -> () {
) this line is invalid, but we will stop at the declaration... // expected-error{{expected expression}}
func a() -> Int { return 4 }
return a() + "a" // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
class Container<T> {
func exists() -> Bool { return true }
}
func useContainer() -> () {
var a : Container<not a type [skip this greater: >] >, b : Int // expected-error{{expected '>' to complete generic argument list}} expected-note{{to match this opening '<'}}
b = 5 // no-warning
a.exists()
}
@xyz class BadAttributes { // expected-error{{unknown attribute 'xyz'}}
func exists() -> Bool { return true }
}
func test(a: BadAttributes) -> () { // expected-note * {{did you mean 'test'?}}
_ = a.exists() // no-warning
}
// Here is an extra random close-brace!
} // expected-error{{extraneous '}' at top level}} {{1-3=}}
//===--- Recovery for braced blocks.
func braceStmt1() {
{ braceStmt1(); } // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
func braceStmt2() {
{ () in braceStmt2(); } // expected-error {{closure expression is unused}}
}
func braceStmt3() {
{ // expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
undefinedIdentifier {} // expected-error {{use of unresolved identifier 'undefinedIdentifier'}}
}
}
//===--- Recovery for misplaced 'static'.
static func toplevelStaticFunc() {} // expected-error {{static methods may only be declared on a type}} {{1-8=}}
static struct StaticStruct {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static class StaticClass {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static protocol StaticProtocol {} // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
static typealias StaticTypealias = Int // expected-error {{declaration cannot be marked 'static'}} {{1-8=}}
class ClassWithStaticDecls {
class var a = 42 // expected-error {{class stored properties not supported}}
}
//===--- Recovery for missing controlling expression in statements.
func missingControllingExprInIf() {
if // expected-error {{expected expression, var, or let in 'if' condition}}
if { // expected-error {{missing condition in an 'if' statement}}
}
if // expected-error {{missing condition in an 'if' statement}}
{
}
if true {
} else if { // expected-error {{missing condition in an 'if' statement}}
}
// It is debatable if we should do recovery here and parse { true } as the
// body, but the error message should be sensible.
if { true } { // expected-error {{missing condition in an 'if' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{14-14=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{15-15=do }} expected-warning {{boolean literal is unused}}
}
if { true }() { // expected-error {{missing condition in an 'if' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{17-17=do }} expected-warning {{boolean literal is unused}}
}
// <rdar://problem/18940198>
if { { } } // expected-error{{missing condition in an 'if' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{8-8=do }}
}
func missingControllingExprInWhile() {
while // expected-error {{expected expression, var, or let in 'while' condition}}
while { // expected-error {{missing condition in a 'while' statement}}
}
while // expected-error {{missing condition in a 'while' statement}}
{
}
// It is debatable if we should do recovery here and parse { true } as the
// body, but the error message should be sensible.
while { true } { // expected-error {{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{17-17=;}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{18-18=do }} expected-warning {{boolean literal is unused}}
}
while { true }() { // expected-error {{missing condition in a 'while' statement}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error {{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{20-20=do }} expected-warning {{boolean literal is unused}}
}
// <rdar://problem/18940198>
while { { } } // expected-error{{missing condition in a 'while' statement}} expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{11-11=do }}
}
func missingControllingExprInRepeatWhile() {
repeat {
} while // expected-error {{missing condition in a 'while' statement}}
{ // expected-error{{closure expression is unused}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
missingControllingExprInRepeatWhile();
}
repeat {
} while { true }() // expected-error{{missing condition in a 'while' statement}} expected-error{{consecutive statements on a line must be separated by ';'}} {{10-10=;}} expected-warning {{result of call is unused, but produces 'Bool'}}
}
// SR-165
func missingWhileInRepeat() {
repeat {
} // expected-error {{expected 'while' after body of 'repeat' statement}}
}
func acceptsClosure<T>(t: T) -> Bool { return true }
func missingControllingExprInFor() {
for ; { // expected-error {{C-style for statement has been removed in Swift 3}}
}
for ; // expected-error {{C-style for statement has been removed in Swift 3}}
{
}
for ; true { // expected-error {{C-style for statement has been removed in Swift 3}}
}
for var i = 0; true { // expected-error {{C-style for statement has been removed in Swift 3}}
i += 1
}
}
func missingControllingExprInForEach() {
// expected-error @+3 {{expected pattern}}
// expected-error @+2 {{expected Sequence expression for for-each loop}}
// expected-error @+1 {{expected '{' to start the body of for-each loop}}
for
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for {
}
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for
{
}
// expected-error @+2 {{expected 'in' after for-each pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for i {
}
// expected-error @+2 {{expected 'in' after for-each pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for var i {
}
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for in {
}
// expected-error @+1 {{expected pattern}}
for 0..<12 {
}
// expected-error @+3 {{expected pattern}}
// expected-error @+2 {{expected Sequence expression for for-each loop}}
// expected-error @+1 {{expected '{' to start the body of for-each loop}}
for for in {
}
for i in { // expected-error {{expected Sequence expression for for-each loop}}
}
// The #if block is used to provide a scope for the for stmt to force it to end
// where necessary to provoke the crash.
#if true // <rdar://problem/21679557> compiler crashes on "for{{"
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for{{ // expected-note 2 {{to match this opening '{'}}
#endif // expected-error {{expected '}' at end of closure}} expected-error {{expected '}' at end of brace statement}}
#if true
// expected-error @+2 {{expected pattern}}
// expected-error @+1 {{expected Sequence expression for for-each loop}}
for{
var x = 42
}
#endif
// SR-5943
struct User { let name: String? }
let users = [User]()
for user in users whe { // expected-error {{expected '{' to start the body of for-each loop}}
if let name = user.name {
let key = "\(name)"
}
}
for // expected-error {{expected pattern}} expected-error {{Sequence expression for for-each loop}}
; // expected-error {{expected '{' to start the body of for-each loop}}
}
func missingControllingExprInSwitch() {
switch // expected-error {{expected expression in 'switch' statement}} expected-error {{expected '{' after 'switch' subject expression}}
switch { // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}}
}
switch // expected-error {{expected expression in 'switch' statement}} expected-error {{'switch' statement body must have at least one 'case' or 'default' block}}
{
}
switch { // expected-error {{expected expression in 'switch' statement}}
case _: return
}
switch { // expected-error {{expected expression in 'switch' statement}}
case Int: return // expected-error {{'is' keyword required to pattern match against type name}} {{10-10=is }}
case _: return
}
switch { 42 } { // expected-error {{expected expression in 'switch' statement}} expected-error{{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error{{consecutive statements on a line must be separated by ';'}} {{16-16=;}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{17-17=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}}
}
switch { 42 }() { // expected-error {{expected expression in 'switch' statement}} expected-error {{all statements inside a switch must be covered by a 'case' or 'default'}} expected-error 2 {{consecutive statements on a line must be separated by ';'}} expected-error{{closure expression is unused}} expected-note{{did you mean to use a 'do' statement?}} {{19-19=do }} // expected-error{{'switch' statement body must have at least one 'case' or 'default' block}}
case _: return // expected-error{{'case' label can only appear inside a 'switch' statement}}
}
}
//===--- Recovery for missing braces in nominal type decls.
struct NoBracesStruct1() // expected-error {{expected '{' in struct}}
enum NoBracesUnion1() // expected-error {{expected '{' in enum}}
class NoBracesClass1() // expected-error {{expected '{' in class}}
protocol NoBracesProtocol1() // expected-error {{expected '{' in protocol type}}
extension NoBracesStruct1() // expected-error {{expected '{' in extension}}
struct NoBracesStruct2 // expected-error {{expected '{' in struct}}
enum NoBracesUnion2 // expected-error {{expected '{' in enum}}
class NoBracesClass2 // expected-error {{expected '{' in class}}
protocol NoBracesProtocol2 // expected-error {{expected '{' in protocol type}}
extension NoBracesStruct2 // expected-error {{expected '{' in extension}}
//===--- Recovery for multiple identifiers in decls
protocol Multi ident {}
// expected-error @-1 {{found an unexpected second identifier in protocol declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{10-21=Multiident}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{10-21=MultiIdent}}
class CCC CCC<T> {}
// expected-error @-1 {{found an unexpected second identifier in class declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{7-14=CCCCCC}}
enum EE EE<T> where T : Multi {
// expected-error @-1 {{found an unexpected second identifier in enum declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{6-11=EEEE}}
case a a
// expected-error @-1 {{found an unexpected second identifier in enum 'case' declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{8-11=aa}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{8-11=aA}}
case b
}
struct SS SS : Multi {
// expected-error @-1 {{found an unexpected second identifier in struct declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{8-13=SSSS}}
private var a b : Int = ""
// expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{15-18=ab}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{15-18=aB}}
// expected-error @-4 {{cannot convert value of type 'String' to specified type 'Int'}}
func f() {
var c d = 5
// expected-error @-1 {{found an unexpected second identifier in variable declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{9-12=cd}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{9-12=cD}}
// expected-warning @-4 {{initialization of variable 'c' was never used; consider replacing with assignment to '_' or removing it}}
let _ = 0
}
}
let (efg hij, foobar) = (5, 6)
// expected-error @-1 {{found an unexpected second identifier in constant declaration; is there an accidental break?}}
// expected-note @-2 {{join the identifiers together}} {{6-13=efghij}}
// expected-note @-3 {{join the identifiers together with camel-case}} {{6-13=efgHij}}
_ = foobar // OK.
//===--- Recovery for parse errors in types.
struct ErrorTypeInVarDecl1 {
var v1 : // expected-error {{expected type}} {{11-11= <#type#>}}
}
struct ErrorTypeInVarDecl2 {
var v1 : Int. // expected-error {{expected member name following '.'}}
var v2 : Int
}
struct ErrorTypeInVarDecl3 {
var v1 : Int< // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl4 {
var v1 : Int<, // expected-error {{expected type}} {{16-16= <#type#>}}
var v2 : Int
}
struct ErrorTypeInVarDecl5 {
var v1 : Int<Int // expected-error {{expected '>' to complete generic argument list}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl6 {
var v1 : Int<Int, // expected-note {{to match this opening '<'}}
Int // expected-error {{expected '>' to complete generic argument list}}
var v2 : Int
}
struct ErrorTypeInVarDecl7 {
var v1 : Int<Int, // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl8 {
var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl9 {
var v1 : protocol // expected-error {{expected type}}
var v2 : Int
}
struct ErrorTypeInVarDecl10 {
var v1 : protocol<FooProtocol // expected-error {{expected '>' to complete protocol-constrained type}} expected-note {{to match this opening '<'}}
var v2 : Int
}
struct ErrorTypeInVarDecl11 {
var v1 : protocol<FooProtocol, // expected-error {{expected identifier for type name}}
var v2 : Int
}
func ErrorTypeInPattern1(_: protocol<) { } // expected-error {{expected identifier for type name}}
func ErrorTypeInPattern2(_: protocol<F) { } // expected-error {{expected '>' to complete protocol-constrained type}}
// expected-note@-1 {{to match this opening '<'}}
// expected-error@-2 {{use of undeclared type 'F'}}
func ErrorTypeInPattern3(_: protocol<F,) { } // expected-error {{expected identifier for type name}}
// expected-error@-1 {{use of undeclared type 'F'}}
struct ErrorTypeInVarDecl12 {
var v1 : FooProtocol & // expected-error{{expected identifier for type name}}
var v2 : Int
}
struct ErrorTypeInVarDecl13 { // expected-note {{in declaration of 'ErrorTypeInVarDecl13'}}
var v1 : & FooProtocol // expected-error {{expected type}} expected-error {{consecutive declarations on a line must be separated by ';'}} expected-error{{expected declaration}}
var v2 : Int
}
struct ErrorTypeInVarDecl16 {
var v1 : FooProtocol & // expected-error {{expected identifier for type name}}
var v2 : Int
}
func ErrorTypeInPattern4(_: FooProtocol & ) { } // expected-error {{expected identifier for type name}}
struct ErrorGenericParameterList1< // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}}
struct ErrorGenericParameterList2<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}} expected-error {{expected '{' in struct}}
struct ErrorGenericParameterList3<T, // expected-error {{expected an identifier to name generic parameter}} expected-error {{expected '{' in struct}}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList4< // expected-error {{expected an identifier to name generic parameter}}
{
}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList5<T // expected-error {{expected '>' to complete generic parameter list}} expected-note {{to match this opening '<'}}
{
}
// Note: Don't move braces to a different line here.
struct ErrorGenericParameterList6<T, // expected-error {{expected an identifier to name generic parameter}}
{
}
struct ErrorTypeInVarDeclFunctionType1 {
var v1 : () -> // expected-error {{expected type for function result}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType1 { // expected-note{{in declaration of 'ErrorTypeInVarDeclArrayType1'}}
var v1 : Int[+] // expected-error {{expected declaration}} expected-error {{consecutive declarations on a line must be separated by ';'}}
// expected-error @-1 {{expected expression after unary operator}}
// expected-error @-2 {{expected expression}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType2 {
var v1 : Int[+ // expected-error {{unary operator cannot be separated from its operand}}
var v2 : Int // expected-error {{expected expression}}
}
struct ErrorTypeInVarDeclArrayType3 {
var v1 : Int[
; // expected-error {{expected expression}}
var v2 : Int
}
struct ErrorTypeInVarDeclArrayType4 {
var v1 : Int[1 // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
}
struct ErrorInFunctionSignatureResultArrayType1 {
func foo() -> Int[ { // expected-error {{expected '{' in body of function declaration}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType2 {
func foo() -> Int[0 { // expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}}
return [0] // expected-error {{cannot convert return expression of type '[Int]' to return type 'Int'}}
}
}
struct ErrorInFunctionSignatureResultArrayType3 {
func foo() -> Int[0] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType4 {
func foo() -> Int[0_1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType5 {
func foo() -> Int[0b1] { // expected-error {{array types are now written with the brackets around the element type}} {{17-17=[}} {{20-21=}}
return [0]
}
}
struct ErrorInFunctionSignatureResultArrayType11 { // expected-note{{in declaration of 'ErrorInFunctionSignatureResultArrayType11'}}
func foo() -> Int[(a){a++}] { // expected-error {{consecutive declarations on a line must be separated by ';'}} {{29-29=;}} expected-error {{expected ']' in array type}} expected-note {{to match this opening '['}} expected-error {{use of unresolved identifier 'a'}} expected-error {{expected declaration}}
}
}
//===--- Recovery for missing initial value in var decls.
struct MissingInitializer1 {
var v1 : Int = // expected-error {{expected initial value after '='}}
}
//===--- Recovery for expr-postfix.
func exprPostfix1(x : Int) {
x. // expected-error {{expected member name following '.'}}
}
func exprPostfix2() {
_ = .42 // expected-error {{'.42' is not a valid floating point literal; it must be written '0.42'}} {{7-7=0}}
}
//===--- Recovery for expr-super.
class Base {}
class ExprSuper1 {
init() {
super // expected-error {{expected '.' or '[' after 'super'}}
}
}
class ExprSuper2 {
init() {
super. // expected-error {{expected member name following '.'}}
}
}
//===--- Recovery for braces inside a nominal decl.
struct BracesInsideNominalDecl1 { // expected-note{{in declaration of 'BracesInsideNominalDecl1'}}
{ // expected-error {{expected declaration}}
aaa
}
typealias A = Int
}
func use_BracesInsideNominalDecl1() {
// Ensure that the typealias decl is not skipped.
var _ : BracesInsideNominalDecl1.A // no-error
}
class SR771 { // expected-note {{in declaration of 'SR771'}}
print("No one else was in the room where it happened") // expected-error {{expected declaration}}
}
extension SR771 { // expected-note {{in extension of 'SR771'}}
print("The room where it happened, the room where it happened") // expected-error {{expected declaration}}
}
//===--- Recovery for wrong decl introducer keyword.
class WrongDeclIntroducerKeyword1 { // expected-note{{in declaration of 'WrongDeclIntroducerKeyword1'}}
notAKeyword() {} // expected-error {{expected declaration}}
func foo() {}
class func bar() {}
}
// <rdar://problem/18502220> [swift-crashes 078] parser crash on invalid cast in sequence expr
Base=1 as Base=1 // expected-error {{cannot assign to immutable expression of type 'Base'}}
// <rdar://problem/18634543> Parser hangs at swift::Parser::parseType
public enum TestA {
// expected-error @+1{{expected '{' in body of function declaration}}
public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}}
// expected-error@+1{{expected parameter name followed by ':'}}
s._core.count != 0, "Can't form a Character from an empty String")
}
public enum TestB {
// expected-error@+1{{expected '{' in body of function declaration}}
public static func convertFromExtenndition( // expected-error {{expected parameter name followed by ':'}}
// expected-error@+1 {{expected parameter name followed by ':'}}
s._core.count ?= 0, "Can't form a Character from an empty String")
}
// <rdar://problem/18634543> Infinite loop and unbounded memory consumption in parser
class bar {}
var baz: bar
// expected-error@+1{{unnamed parameters must be written with the empty name '_'}}
func foo1(bar!=baz) {} // expected-note {{did you mean 'foo1'?}}
// expected-error@+1{{unnamed parameters must be written with the empty name '_'}}
func foo2(bar! = baz) {}// expected-note {{did you mean 'foo2'?}}
// rdar://19605567
// expected-error@+1{{use of unresolved identifier 'esp'}}
switch esp {
case let (jeb):
// expected-error@+5{{operator with postfix spacing cannot start a subexpression}}
// expected-error@+4{{consecutive statements on a line must be separated by ';'}} {{15-15=;}}
// expected-error@+3{{'>' is not a prefix unary operator}}
// expected-error@+2{{expected an identifier to name generic parameter}}
// expected-error@+1{{expected '{' in class}}
class Ceac<}> {}
// expected-error@+1{{extraneous '}' at top level}} {{1-2=}}
}
#if true
// rdar://19605164
// expected-error@+2{{use of undeclared type 'S'}}
struct Foo19605164 {
func a(s: S[{{g) -> Int {}
// expected-error@+2 {{expected parameter name followed by ':'}}
// expected-error@+1 {{expected ',' separator}}
}}}
#endif
// rdar://19605567
// expected-error@+3{{expected '(' for initializer parameters}}
// expected-error@+2{{initializers may only be declared within a type}}
// expected-error@+1{{expected an identifier to name generic parameter}}
func F() { init<( } )} // expected-note {{did you mean 'F'?}}
struct InitializerWithName {
init x() {} // expected-error {{initializers cannot have a name}} {{8-9=}}
}
struct InitializerWithNameAndParam {
init a(b: Int) {} // expected-error {{initializers cannot have a name}} {{8-9=}}
}
struct InitializerWithLabels {
init c d: Int {}
// expected-error @-1 {{expected '(' for initializer parameters}}
// expected-error @-2 {{expected declaration}}
// expected-error @-3 {{consecutive declarations on a line must be separated by ';'}}
// expected-note @-5 {{in declaration of 'InitializerWithLabels'}}
}
// rdar://20337695
func f1() {
// expected-error @+6 {{use of unresolved identifier 'C'}}
// expected-note @+5 {{did you mean 'n'?}}
// expected-error @+4 {{unary operator cannot be separated from its operand}} {{11-12=}}
// expected-error @+3 {{'==' is not a prefix unary operator}}
// expected-error @+2 {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// expected-error@+1 {{type annotation missing in pattern}}
let n == C { get {} // expected-error {{use of unresolved identifier 'get'}}
}
}
// <rdar://problem/20489838> QoI: Nonsensical error and fixit if "let" is missing between 'if let ... where' clauses
func testMultiPatternConditionRecovery(x: Int?) {
// expected-error@+1 {{expected ',' joining parts of a multi-clause condition}} {{15-21=,}}
if let y = x where y == 0, let z = x {
_ = y
_ = z
}
if var y = x, y == 0, var z = x {
z = y; y = z
}
if var y = x, z = x { // expected-error {{expected 'var' in conditional}} {{17-17=var }}
z = y; y = z
}
// <rdar://problem/20883210> QoI: Following a "let" condition with boolean condition spouts nonsensical errors
guard let x: Int? = 1, x == 1 else { }
// expected-warning @-1 {{explicitly specified type 'Int?' adds an additional level of optional to the initializer, making the optional check always succeed}} {{16-20=Int}}
}
// rdar://20866942
func testRefutableLet() {
var e : Int?
let x? = e // expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// expected-error @-1 {{expected expression}}
// expected-error @-2 {{type annotation missing in pattern}}
}
// <rdar://problem/19833424> QoI: Bad error message when using Objective-C literals (@"Hello") in Swift files
let myString = @"foo" // expected-error {{string literals in Swift are not preceded by an '@' sign}} {{16-17=}}
// <rdar://problem/16990885> support curly quotes for string literals
// expected-error @+1 {{unicode curly quote found, replace with '"'}} {{35-38="}}
let curlyQuotes1 = “hello world!” // expected-error {{unicode curly quote found, replace with '"'}} {{20-23="}}
// expected-error @+1 {{unicode curly quote found, replace with '"'}} {{20-23="}}
let curlyQuotes2 = “hello world!"
// <rdar://problem/21196171> compiler should recover better from "unicode Specials" characters
let tryx = 123 // expected-error 2 {{invalid character in source file}} {{5-8= }}
// <rdar://problem/21369926> Malformed Swift Enums crash playground service
enum Rank: Int { // expected-error {{'Rank' declares raw type 'Int', but does not conform to RawRepresentable and conformance could not be synthesized}}
case Ace = 1
case Two = 2.1 // expected-error {{cannot convert value of type 'Double' to raw type 'Int'}}
}
// rdar://22240342 - Crash in diagRecursivePropertyAccess
class r22240342 {
lazy var xx: Int = {
foo { // expected-error {{use of unresolved identifier 'foo'}}
let issueView = 42
issueView.delegate = 12
}
return 42
}()
}
// <rdar://problem/22387625> QoI: Common errors: 'let x= 5' and 'let x =5' could use Fix-its
func r22387625() {
let _= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{8-8= }}
let _ =5 // expected-error{{'=' must have consistent whitespace on both sides}} {{10-10= }}
}
// <https://bugs.swift.org/browse/SR-3135>
func SR3135() {
let _: Int= 5 // expected-error{{'=' must have consistent whitespace on both sides}} {{13-13= }}
let _: Array<Int>= [] // expected-error{{'=' must have consistent whitespace on both sides}} {{20-20= }}
}
// <rdar://problem/23086402> Swift compiler crash in CSDiag
protocol A23086402 {
var b: B23086402 { get }
}
protocol B23086402 {
var c: [String] { get }
}
func test23086402(a: A23086402) {
print(a.b.c + "") // should not crash but: expected-error {{}}
}
// <rdar://problem/23550816> QoI: Poor diagnostic in argument list of "print" (varargs related)
// The situation has changed. String now conforms to the RangeReplaceableCollection protocol
// and `ss + s` becomes ambiguous. Diambiguation is provided with the unavailable overload
// in order to produce a meaningful diagnostics. (Related: <rdar://problem/31763930>)
func test23550816(ss: [String], s: String) {
print(ss + s) // expected-error {{'+' is unavailable: Operator '+' cannot be used to append a String to a sequence of strings}}
}
// <rdar://problem/23719432> [practicalswift] Compiler crashes on &(Int:_)
func test23719432() {
var x = 42
&(Int:x) // expected-error {{expression type 'inout _' is ambiguous without more context}}
}
// <rdar://problem/19911096> QoI: terrible recovery when using '·' for an operator
infix operator · { // expected-error {{'·' is considered to be an identifier, not an operator}}
associativity none precedence 150
}
// <rdar://problem/21712891> Swift Compiler bug: String subscripts with range should require closing bracket.
func r21712891(s : String) -> String {
let a = s.startIndex..<s.startIndex
_ = a
// The specific errors produced don't actually matter, but we need to reject this.
return "\(s[a)" // expected-error {{expected ']' in expression list}} expected-note {{to match this opening '['}}
}
// <rdar://problem/24029542> "Postfix '.' is reserved" error message" isn't helpful
func postfixDot(a : String) {
_ = a.utf8
_ = a. utf8 // expected-error {{extraneous whitespace after '.' is not permitted}} {{9-12=}}
_ = a. // expected-error {{expected member name following '.'}}
a. // expected-error {{expected member name following '.'}}
}
// <rdar://problem/22290244> QoI: "UIColor." gives two issues, should only give one
func f() {
_ = ClassWithStaticDecls. // expected-error {{expected member name following '.'}}
}
| apache-2.0 | edb10a6632fdba2a37afd76c420b1db2 | 39.225641 | 469 | 0.679691 | 3.99898 | false | false | false | false |
avito-tech/Paparazzo | Paparazzo/Core/VIPER/ImageCropping/View/RotationSliderView.swift | 1 | 5344 | import UIKit
final class RotationSliderView: UIView, UIScrollViewDelegate {
// MARK: - Subviews
private let scrollView = UIScrollView()
private let scaleView = SliderScaleView()
private let thumbView = UIView()
private let alphaMaskLayer = CAGradientLayer()
// MARK: - Properties
private var minimumValue: Float = 0
private var maximumValue: Float = 1
private var currentValue: Float = 0
// MARK: - UIView
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
contentMode = .redraw
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.bounces = false
scrollView.delegate = self
thumbView.backgroundColor = .black
thumbView.layer.cornerRadius = scaleView.divisionWidth / 2
alphaMaskLayer.startPoint = CGPoint(x: 0, y: 0)
alphaMaskLayer.endPoint = CGPoint(x: 1, y: 0)
alphaMaskLayer.locations = [0, 0.2, 0.8, 1]
alphaMaskLayer.colors = [
UIColor.clear.cgColor,
UIColor.white.cgColor,
UIColor.white.cgColor,
UIColor.clear.cgColor
]
layer.mask = alphaMaskLayer
scrollView.addSubview(scaleView)
addSubview(scrollView)
addSubview(thumbView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
// Высчитываем этот inset, чтобы в случаях, когда слайдер находится в крайних положениях,
// метки на шкале и указатель текущего значения совпадали
let sideInset = ((bounds.size.width - scaleView.divisionWidth) / 2).truncatingRemainder(dividingBy: scaleView.divisionWidth + scaleView.divisionsSpacing)
scaleView.contentInsets = UIEdgeInsets(top: 0, left: sideInset, bottom: 0, right: sideInset)
scaleView.frame = CGRect(origin: .zero, size: scaleView.sizeThatFits(bounds.size))
scrollView.frame = bounds
scrollView.contentSize = scaleView.frame.size
thumbView.size = CGSize(width: scaleView.divisionWidth, height: scaleView.height)
thumbView.center = bounds.center
alphaMaskLayer.frame = bounds
adjustScrollViewOffset()
}
// MARK: - RotationSliderView
var onSliderValueChange: ((Float) -> ())?
func setMiminumValue(_ value: Float) {
minimumValue = value
}
func setMaximumValue(_ value: Float) {
maximumValue = value
}
func setValue(_ value: Float) {
currentValue = max(minimumValue, min(maximumValue, value))
adjustScrollViewOffset()
}
// MARK: - UIScrollViewDelegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset.x
let significantWidth = scrollView.contentSize.width - bounds.size.width
let percentage = offset / significantWidth
let value = minimumValue + (maximumValue - minimumValue) * Float(percentage)
onSliderValueChange?(value)
}
// Это отключает deceleration у scroll view
func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollView.setContentOffset(scrollView.contentOffset, animated: true)
}
// MARK: - Private
private func adjustScrollViewOffset() {
let percentage = (currentValue - minimumValue) / (maximumValue - minimumValue)
scrollView.contentOffset = CGPoint(
x: CGFloat(percentage) * (scrollView.contentSize.width - bounds.size.width),
y: 0
)
}
}
private final class SliderScaleView: UIView {
var contentInsets = UIEdgeInsets.zero
let divisionsSpacing = CGFloat(14)
let divisionsCount = 51
let divisionWidth = CGFloat(2)
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
var width = CGFloat(divisionsCount) * divisionWidth
width += CGFloat(divisionsCount - 1) * divisionsSpacing
width += contentInsets.left + contentInsets.right
return CGSize(width: width, height: size.height)
}
override func draw(_ rect: CGRect) {
super.draw(rect)
for i in 0 ..< divisionsCount {
let rect = CGRect(
x: bounds.left + contentInsets.left + CGFloat(i) * (divisionWidth + divisionsSpacing),
y: bounds.top,
width: divisionWidth,
height: bounds.size.height
)
UIColor.RGBS(rgb: 217).setFill()
UIBezierPath(roundedRect: rect, cornerRadius: divisionWidth / 2).fill()
}
}
}
| mit | 52fd78c45bc0ca0137e2b53c451666c2 | 30.239521 | 161 | 0.612613 | 5.079844 | false | false | false | false |
Staance/Swell | Swell/Swell.swift | 1 | 18621 | //
// Swell.swift
// Swell
//
// Created by Hubert Rabago on 6/26/14.
// Copyright (c) 2014 Minute Apps LLC. All rights reserved.
//
import Foundation
struct LoggerConfiguration {
var name: String
var level: LogLevel?
var formatter: LogFormatter?
var locations: [LogLocation]
init(name: String) {
self.name = name
self.locations = [LogLocation]()
}
func description() -> String {
var locationsDesc = ""
for loc in locations {
locationsDesc += loc.description()
}
return "\(name) \(level?.desciption()) \(formatter?.description()) \(locationsDesc)"
}
}
// We declare this here because there isn't any support yet for class var / class let
let globalSwell = Swell();
public class Swell {
lazy var swellLogger: Logger = {
let result = getLogger("Shared")
return result
}()
var selector = LogSelector()
var allLoggers = Dictionary<String, Logger>()
var rootConfiguration = LoggerConfiguration(name: "ROOT")
var sharedConfiguration = LoggerConfiguration(name: "Shared")
var allConfigurations = Dictionary<String, LoggerConfiguration>()
var enabled = true;
init() {
// This configuration is used by the shared logger
sharedConfiguration.formatter = QuickFormatter(format: .LevelMessage)
sharedConfiguration.level = LogLevel.TRACE
sharedConfiguration.locations += [ConsoleLocation.getInstance()]
// The root configuration is where all other configurations are based off of
rootConfiguration.formatter = QuickFormatter(format: .LevelNameMessage)
rootConfiguration.level = LogLevel.TRACE
rootConfiguration.locations += [ConsoleLocation.getInstance()]
readConfigurationFile()
}
//========================================================================================
// Global/convenience log methods used for quick logging
public class func trace<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.trace(message)
}
public class func debug<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.debug(message)
}
public class func info<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.info(message)
}
public class func warn<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.warn(message)
}
public class func error<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.error(message)
}
public class func severe<T>(@autoclosure message: () -> T) {
globalSwell.swellLogger.severe(message)
}
public class func trace(fn: () -> String) {
globalSwell.swellLogger.trace(fn())
}
public class func debug(fn: () -> String) {
globalSwell.swellLogger.debug(fn())
}
public class func info(fn: () -> String) {
globalSwell.swellLogger.info(fn())
}
public class func warn(fn: () -> String) {
globalSwell.swellLogger.warn(fn())
}
public class func error(fn: () -> String) {
globalSwell.swellLogger.error(fn())
}
public class func severe(fn: () -> String) {
globalSwell.swellLogger.severe(fn())
}
//====================================================================================================
// Public methods
/// Returns the logger configured for the given name.
/// This is the recommended way of retrieving a Swell logger.
public class func getLogger(name: String) -> Logger {
return globalSwell.getLogger(name);
}
/// Turns off all logging.
public class func disableLogging() {
globalSwell.disableLogging()
}
//====================================================================================================
// Internal methods serving the public methods
func disableLogging() {
enabled = false
for (_, value) in allLoggers {
value.enabled = false
}
}
func enableLogging() {
enabled = true
for (_, value) in allLoggers {
value.enabled = selector.shouldEnable(value)
}
}
// Register the given logger. This method should be called
// for ALL loggers created. This facilitates enabling/disabling of
// loggers based on user configuration.
class func registerLogger(logger: Logger) {
globalSwell.registerLogger(logger);
}
func registerLogger(logger: Logger) {
allLoggers[logger.name] = logger;
evaluateLoggerEnabled(logger);
}
func evaluateLoggerEnabled(logger: Logger) {
logger.enabled = self.enabled && selector.shouldEnable(logger);
}
/// Returns the Logger instance configured for a given logger name.
/// Use this to get Logger instances for use in classes.
func getLogger(name: String) -> Logger {
let logger = allLoggers[name]
if (logger != nil) {
return logger!
} else {
let result: Logger = createLogger(name)
allLoggers[name] = result
return result
}
}
/// Creates a new Logger instance based on configuration returned by getConfigurationForLoggerName()
/// This is intended to be in an internal method and should not be called by other classes.
/// Use getLogger(name) to get a logger for normal use.
func createLogger(name: String) -> Logger {
let config = getConfigurationForLoggerName(name)
let result = Logger(name: name, level: config.level!, formatter: config.formatter!, logLocation: config.locations[0])
// Now we need to handle potentially > 1 locations
if config.locations.count > 1 {
for (index,location) in config.locations.enumerate() {
if (index > 0) {
result.locations += [location]
}
}
}
return result
}
//====================================================================================================
// Methods for managing the configurations from the plist file
/// Returns the current configuration for a given logger name based on Swell.plist
/// and the root configuration.
func getConfigurationForLoggerName(name: String) -> LoggerConfiguration {
var config: LoggerConfiguration = LoggerConfiguration(name: name);
// first, populate it with values from the root config
config.formatter = rootConfiguration.formatter
config.level = rootConfiguration.level
config.locations += rootConfiguration.locations
if (name == "Shared") {
if let level = sharedConfiguration.level {
config.level = level
}
if let formatter = sharedConfiguration.formatter {
config.formatter = formatter
}
if sharedConfiguration.locations.count > 0 {
config.locations = sharedConfiguration.locations
}
}
// Now see if there's a config specifically for this logger
// In later versions, we can consider tree structures similar to Log4j
// For now, let's require an exact match for the name
let keys = allConfigurations.keys
for key in keys {
// Look for the entry with the same name
if (key == name) {
let temp = allConfigurations[key]
if let spec = temp {
if let formatter = spec.formatter {
config.formatter = formatter
}
if let level = spec.level {
config.level = level
}
if spec.locations.count > 0 {
config.locations = spec.locations
}
}
}
}
return config;
}
//====================================================================================================
// Methods for reading the Swell.plist file
func readConfigurationFile() {
let filename: String? = NSBundle.mainBundle().pathForResource("Swell", ofType: "plist");
var dict: NSDictionary? = nil;
if let bundleFilename = filename {
dict = NSDictionary(contentsOfFile: bundleFilename)
}
if let map: Dictionary<String, AnyObject> = dict as? Dictionary<String, AnyObject> {
//-----------------------------------------------------------------
// Read the root configuration
let configuration = readLoggerPList("ROOT", map: map);
//Swell.info("map: \(map)");
// Now any values configured, we put in our root configuration
if let formatter = configuration.formatter {
rootConfiguration.formatter = formatter
}
if let level = configuration.level {
rootConfiguration.level = level
}
if configuration.locations.count > 0 {
rootConfiguration.locations = configuration.locations
}
//-----------------------------------------------------------------
// Now look for any keys that don't start with SWL, and if it contains a dictionary value, let's read it
let keys = map.keys
for key in keys {
if (!key.hasPrefix("SWL")) {
let value: AnyObject? = map[key]
if let submap: Dictionary<String, AnyObject> = value as? Dictionary<String, AnyObject> {
let subconfig = readLoggerPList(key, map: submap)
applyLoggerConfiguration(key, configuration: subconfig)
}
}
}
//-----------------------------------------------------------------
// Now check if there is an enabled/disabled rule specified
var item: AnyObject? = nil
// Set the LogLevel
item = map["SWLEnable"]
if let value: AnyObject = item {
if let rule: String = value as? String {
selector.enableRule = rule
}
}
item = map["SWLDisable"]
if let value: AnyObject = item {
if let rule: String = value as? String {
selector.disableRule = rule
}
}
}
}
/// Specifies or modifies the configuration of a logger.
/// If any aspect of the configuration was not provided, and there is a pre-existing value for it,
/// the pre-existing value will be used for it.
/// For example, if two consecutive calls were made:
/// configureLogger("MyClass", level: LogLevel.DEBUG, formatter: MyCustomFormatter())
/// configureLogger("MyClass", level: LogLevel.INFO, location: ConsoleLocation())
/// then the resulting configuration for MyClass would have MyCustomFormatter, ConsoleLocation, and LogLevel.INFO.
func configureLogger(loggerName: String,
level givenLevel: LogLevel? = nil,
formatter givenFormatter: LogFormatter? = nil,
location givenLocation: LogLocation? = nil) {
var oldConfiguration: LoggerConfiguration?
if allConfigurations.indexForKey(loggerName) != nil {
oldConfiguration = allConfigurations[loggerName]
}
var newConfiguration = LoggerConfiguration(name: loggerName)
if let level = givenLevel {
newConfiguration.level = level
} else if let level = oldConfiguration?.level {
newConfiguration.level = level
}
if let formatter = givenFormatter {
newConfiguration.formatter = formatter
} else if let formatter = oldConfiguration?.formatter {
newConfiguration.formatter = formatter
}
if let location = givenLocation {
newConfiguration.locations += [location]
} else if oldConfiguration?.locations.count > 0 {
newConfiguration.locations = oldConfiguration!.locations
}
applyLoggerConfiguration(loggerName, configuration: newConfiguration)
}
/// Store the configuration given for the specified logger.
/// If the logger already exists, update its configuration to reflect what's in the logger.
func applyLoggerConfiguration(loggerName: String, configuration: LoggerConfiguration) {
// Record this custom config in our map
allConfigurations[loggerName] = configuration
// See if the logger with the given name already exists.
// If so, update the configuration it's using.
if let logger = allLoggers[loggerName] {
// TODO - There should be a way to keep calls to logger.log while this is executing
if let level = configuration.level {
logger.level = level
}
if let formatter = configuration.formatter {
logger.formatter = formatter
}
if configuration.locations.count > 0 {
logger.locations.removeAll(keepCapacity: false)
logger.locations += configuration.locations
}
}
}
func readLoggerPList(loggerName: String, map: Dictionary<String, AnyObject>) -> LoggerConfiguration {
var configuration = LoggerConfiguration(name: loggerName)
var item: AnyObject? = nil
// Set the LogLevel
item = map["SWLLevel"]
if let value: AnyObject = item {
if let level: String = value as? String {
configuration.level = LogLevel.getLevel(level)
}
}
// Set the formatter; First, look for a QuickFormat spec
item = map["SWLQuickFormat"]
if let value: AnyObject = item {
configuration.formatter = getConfiguredQuickFormatter(configuration, item: value);
} else {
// If no QuickFormat was given, look for a FlexFormat spec
item = map["SWLFlexFormat"]
if let value: AnyObject = item {
configuration.formatter = getConfiguredFlexFormatter(configuration, item: value);
} else {
let formatKey = getFormatKey(map)
print("formatKey=\(formatKey)")
}
}
// Set the location for the logs
item = map["SWLLocation"]
if let value: AnyObject = item {
configuration.locations = getConfiguredLocations(configuration, item: value, map: map);
}
return configuration
}
func getConfiguredQuickFormatter(configuration: LoggerConfiguration, item: AnyObject) -> LogFormatter? {
if let formatString: String = item as? String {
let formatter = QuickFormatter.logFormatterForString(formatString)
return formatter
}
return nil
}
func getConfiguredFlexFormatter(configuration: LoggerConfiguration, item: AnyObject) -> LogFormatter? {
if let formatString: String = item as? String {
let formatter = FlexFormatter.logFormatterForString(formatString);
return formatter
}
return nil
}
func getConfiguredFileLocation(configuration: LoggerConfiguration, item: AnyObject) -> LogLocation? {
if let filename: String = item as? String {
let logLocation = FileLocation.getInstance(filename);
return logLocation
}
return nil
}
func getConfiguredLocations(configuration: LoggerConfiguration, item: AnyObject,
map: Dictionary<String, AnyObject>) -> [LogLocation] {
var results = [LogLocation]()
if let configuredValue: String = item as? String {
// configuredValue is the raw value in the plist
// values is the array from configuredValue
let values = configuredValue.lowercaseString.componentsSeparatedByCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
for value in values {
if (value == "file") {
// handle file name
let filenameValue: AnyObject? = map["SWLLocationFilename"]
if let filename: AnyObject = filenameValue {
let fileLocation = getConfiguredFileLocation(configuration, item: filename);
if fileLocation != nil {
results += [fileLocation!]
}
}
} else if (value == "console") {
results += [ConsoleLocation.getInstance()]
} else {
print("Unrecognized location value in Swell.plist: '\(value)'")
}
}
}
return results
}
func getFormatKey(map: Dictionary<String, AnyObject>) -> String? {
for (key, _) in map {
if ((key.hasPrefix("SWL")) && (key.hasSuffix("Format"))) {
let start = key.startIndex.advancedBy(3)
let end = key.startIndex.advancedBy(-6)
let result: String = key[start..<end]
return result
}
}
return nil;
}
func getFunctionFormat(function: String) -> String {
var result = function;
if (result.hasPrefix("Optional(")) {
let len = "Optional(".characters.count
let start = result.startIndex.advancedBy(len)
let end = result.endIndex.advancedBy(-len)
let range = start..<end
result = result[range]
}
if (!result.hasSuffix(")")) {
result = result + "()"
}
return result
}
}
| apache-2.0 | bf834c6575dae5ad04bcf4f5f742492d | 35.369141 | 138 | 0.545245 | 5.692755 | false | true | false | false |
sweepforswift/sweep | Sweep/AttributedStrings.swift | 1 | 4803 | //
// AttributedStrings.swift
// Sweep
//
// Created by Will Mock on 2/24/17.
// Copyright © 2017 Michael Smith Jr. All rights reserved.
//
import Foundation
public enum Style{
case bold
case italic
}
public extension NSMutableAttributedString {
/**
Changes the font type of the NSMutableAttributedString to the font matching the parameter
- parameter fontName: Takes in the name of the font that is desired
- returns: an NSMutableAttributedString with the font applied
*/
public func changeFontType(fontName: String)->NSMutableAttributedString{
let fonts: [String] = UIFont.familyNames
let myAttribute = [ NSFontAttributeName: UIFont.fontNames(forFamilyName: fontName) ]
if fonts.contains(fontName) {
print("success")
self.addAttribute(self.string, value: myAttribute, range: NSMakeRange(0, self.length))
}else{
print("failed to change font")
}
return self
}
/**
Changes the font color of the NSMutableAttributedString to the color matching the parameter color. This function also has the option to select only a subset of the original NSMutableAttributedString to change the font color of.
- parameter fontName: Takes in the String name of the font that is desired
- parameter range: Takes in an NSRange? object that specifies the range on which the color will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified
- returns: an NSMutableAttributedString with the font color applied
*/
public func changeFontColor(color: UIColor, range: NSRange? = nil)->NSMutableAttributedString{
let attributedString = NSMutableAttributedString(string: self.string)
var trueRange: NSRange
if let range = range{
trueRange = range
}else{
trueRange = (self.string as NSString).range(of: self.string)
}
attributedString.addAttribute(NSForegroundColorAttributeName, value: color , range: trueRange)
return attributedString
}
/**
Changes the NSBackgroundColorAttributeName of the NSMutableAttributedString to the color yellow (i.e highlighting). This function has the optionional parameter called range that takes in an NSRange? to select only a subset of the original NSMutableAttributedString to highlight.
- parameter range: Takes in an NSRange? object that specifies the range on which the highlighting will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified
- returns: an NSMutableAttributedString with the highlighting applied
*/
public func highlight(range: NSRange? = nil)->NSMutableAttributedString{
let attributedString = NSMutableAttributedString(string: self.string)
var trueRange: NSRange
if let range = range{
trueRange = range
}else{
trueRange = (self.string as NSString).range(of: self.string)
}
attributedString.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellow , range: trueRange)
return attributedString
}
/**
Adding a constraint of bold or italic to an NSMutableAttributedString based on the style parameter. This function also takes in an Int for size and an optional NSRange? to change a subset of the original NSMutableAttributedString.
- parameter style: enum of type Style
- parameter fontSize: Int that specifies the desired system size of the font
- parameter range: Takes in an NSRange? object that specifies the range on which the color will be applied. This will apply to the entire NSMutableAttributedString if no NSrange? is specified
- returns: an NSMutableAttributedString with the font style applied
*/
public func addConstraints(style: Style, fontSize: Int = 17, range: NSRange? = nil)->NSMutableAttributedString{
var trueRange: NSRange
if let range = range{
trueRange = range
}else{
trueRange = NSMakeRange(0, self.length)
}
switch style {
case .bold:
let myAttribute = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: CGFloat(fontSize)) ]
self.addAttribute(self.string, value: myAttribute, range: trueRange)
case .italic:
let myAttribute = [ NSFontAttributeName: UIFont.italicSystemFont(ofSize: CGFloat(fontSize)) ]
self.addAttribute(self.string, value: myAttribute, range: trueRange)
}
return self
}
}
| mit | cbab9d65915c26277fce5f8776d9797e | 38.68595 | 283 | 0.67222 | 5.622951 | false | false | false | false |
SFantasy/swift-tour | Protocols&&Extensions.playground/section-1.swift | 1 | 1420 | // Experiments in Swift Programming Language
//
// Protocols and Extensions
//
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
// Write an enumeration that conforms the protocol
enum SimpleEnum: ExampleProtocol {
case a, b
var simpleDescription: String{
get {
return self.getDescription()
}
}
func getDescription() -> String {
switch self {
case .a: return "it is a"
case .b: return "it is b"
}
}
mutating func adjust() {
self = SimpleEnum.b
}
}
var c = SimpleEnum.a
c.simpleDescription
c.adjust()
c.simpleDescription
// Write an extension for Double type that adds an absoluteValue property.
extension Double {
var absoluteValue: Double {
return abs(self)
}
}
7.3.absoluteValue
(-7.0).absoluteValue
| mit | aa0b5f0bb8f06b06c37afa6382b334ae | 20.19403 | 74 | 0.65493 | 4.423676 | false | false | false | false |
jdarowski/RGSnackBar | RGSnackBar/Classes/RGMessageSnackBarAnimation.swift | 1 | 3749 | //
// RGMessageSnackBarAnimation.swift
// RGSnackBar
//
// Created by Jakub Darowski on 04/09/2017.
//
//
import UIKit
import Stevia
public typealias RGSnackBarAnimationBlock =
((RGMessageSnackBarView, UIView, Bool) -> Void)
/**
* This is where the fun begins. Instantiate (or extend)this class to define
* your very own buttery smooth, candy-like animations for the snackbar.
*/
open class RGMessageSnackBarAnimation: NSObject {
/// The block that will be executed before animating
open var preAnimationBlock: RGSnackBarAnimationBlock?
/// The animation block - will be executed inside UIView.animate(...)
open var animationBlock: RGSnackBarAnimationBlock
/// The block that will be executed in the completion block of animate(...)
open var postAnimationBlock: RGSnackBarAnimationBlock?
/// The duration of the animation
open var animationDuration: TimeInterval
/// States whether the snackbar is off-screen
open var beginsOffscreen: Bool
/**
* The only constructor you'll need.
*
* - Parameter preBlock: duh
* - Parameter animationBlock: double duh
* - Parameter postBlock: duh
* - Parameter animationDuration: the duration of just the animation itself.
* - Parameter beginsOffscreen: whether the snackbar starts offscreen
*/
public init(preBlock: RGSnackBarAnimationBlock?,
animationBlock: @escaping RGSnackBarAnimationBlock,
postBlock: RGSnackBarAnimationBlock?,
animationDuration: TimeInterval=0.4,
beginsOffscreen: Bool=false) {
self.preAnimationBlock = preBlock
self.animationBlock = animationBlock
self.postAnimationBlock = postBlock
self.animationDuration = animationDuration
self.beginsOffscreen = beginsOffscreen
super.init()
}
/// A predefined zoom-in animation, UIAlertView style
public static let zoomIn: RGMessageSnackBarAnimation =
RGMessageSnackBarAnimation(preBlock: { (snackBarView, _, isPresenting)
in
if isPresenting {
snackBarView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}
}, animationBlock: { (snackBarView, parentView, isPresenting) in
if isPresenting {
snackBarView.alpha = 1.0
snackBarView.transform = CGAffineTransform.identity
} else {
snackBarView.alpha = 0.0
snackBarView.transform = CGAffineTransform(scaleX: 1.2, y: 1.2)
}
}, postBlock: nil, animationDuration: 0.2, beginsOffscreen: false)
/// A predefined slide up animation, system banner style (just opposite)
public static let slideUp: RGMessageSnackBarAnimation =
RGMessageSnackBarAnimation(preBlock:
{ (snackBarView, parentView, isPresenting) in
if isPresenting {
let height = snackBarView.frame.size.height
snackBarView.bottomConstraint?.constant =
height + snackBarView.bottomMargin
snackBarView.alpha = 1.0
parentView.layoutIfNeeded()
snackBarView.bottomConstraint?.constant =
-(snackBarView.bottomMargin)
} else {
snackBarView.bottomConstraint?.constant =
snackBarView.frame.size.height
}
}, animationBlock: { (snackBarView, parentView, isPresenting) in
parentView.layoutIfNeeded()
}, postBlock: { (snackBarView, parentView, isPresenting) in
if !isPresenting {
snackBarView.alpha = 0.0
}
}, animationDuration: 0.2, beginsOffscreen: true)
}
| mit | 697c338988e5c8e7fd81cc8268bc0df8 | 36.49 | 80 | 0.645505 | 5.680303 | false | false | false | false |
tomtclai/swift-algorithm-club | Brute-Force String Search/BruteForceStringSearch.swift | 9 | 532 | /*
Brute-force string search
*/
extension String {
func indexOf(_ pattern: String) -> String.Index? {
for i in self.characters.indices {
var j = i
var found = true
for p in pattern.characters.indices {
if j == self.characters.endIndex || self[j] != pattern[p] {
found = false
break
} else {
j = self.characters.index(after: j)
}
}
if found {
return i
}
}
return nil
}
}
| mit | f8db815ef65b700fa153d89ad819dd72 | 22.130435 | 71 | 0.473684 | 4.290323 | false | false | false | false |
TouchInstinct/LeadKit | TISwiftUtils/Sources/Helpers/Typealias.swift | 1 | 3472 | //
// Copyright (c) 2020 Touch Instinct
//
// 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.
//
/// Closure with custom arguments and return value.
public typealias Closure<Input, Output> = (Input) -> Output
/// Closure with no arguments and custom return value.
public typealias ResultClosure<Output> = () -> Output
/// Closure that takes custom arguments and returns Void.
public typealias ParameterClosure<Input> = Closure<Input, Void>
// MARK: Throwable versions
/// Closure with custom arguments and return value, may throw an error.
public typealias ThrowableClosure<Input, Output> = (Input) throws -> Output
/// Closure with no arguments and custom return value, may throw an error.
public typealias ThrowableResultClosure<Output> = () throws -> Output
/// Closure that takes custom arguments and returns Void, may throw an error.
public typealias ThrowableParameterClosure<Input> = ThrowableClosure<Input, Void>
// MARK: Concrete closures
/// Closure that takes no arguments and returns Void.
public typealias VoidClosure = ResultClosure<Void>
/// Closure that takes no arguments, may throw an error and returns Void.
public typealias ThrowableVoidClosure = () throws -> Void
/// Async closure with custom arguments and return value.
public typealias AsyncClosure<Input, Output> = (Input) async -> Output
/// Async closure with no arguments and custom return value.
public typealias AsyncResultClosure<Output> = () async -> Output
/// Async closure that takes custom arguments and returns Void.
public typealias AsyncParameterClosure<Input> = AsyncClosure<Input, Void>
// MARK: Async throwable versions
/// Async closure with custom arguments and return value, may throw an error.
public typealias ThrowableAsyncClosure<Input, Output> = (Input) async throws -> Output
/// Async closure with no arguments and custom return value, may throw an error.
public typealias ThrowableAsyncResultClosure<Output> = () async throws -> Output
/// Async closure that takes custom arguments and returns Void, may throw an error.
public typealias ThrowableAsyncParameterClosure<Input> = ThrowableAsyncClosure<Input, Void>
// MARK: Async concrete closures
/// Async closure that takes no arguments and returns Void.
public typealias AsyncVoidClosure = AsyncResultClosure<Void>
/// Async closure that takes no arguments, may throw an error and returns Void.
public typealias ThrowableAsyncVoidClosure = () async throws -> Void
| apache-2.0 | 83f11b4657d524d67c33d1bcf31ce95c | 43.512821 | 91 | 0.769873 | 4.598675 | false | false | false | false |
SiddharthChopra/KahunaSocialMedia | KahunaSocialMedia/Classes/Instagram/JsonClasses/IGDimension.swift | 1 | 1013 | //
// IGDimension.swift
//
// Create by Kahuna on 13/11/2017
// Copyright © 2017. All rights reserved.
// Model file generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
class IGDimension: NSObject {
var height: Int!
var width: Int!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary) {
height = dictionary["height"] as? Int
width = dictionary["width"] as? Int
}
/**
* Returns all the available property values in the form of [String:Any] object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> NSDictionary
{
let dictionary = NSMutableDictionary()
if height != nil {
dictionary["height"] = height
}
if width != nil {
dictionary["width"] = width
}
return dictionary
}
}
| mit | cc17707772f68a7cf4512544e06707ee | 24.3 | 180 | 0.641304 | 4.538117 | false | false | false | false |
rellermeyer/99tsp | swift/gen/main.swift | 1 | 7354 | //
// main.swift
// pl
//
// Created by Michael Scaria on 11/28/16.
// Copyright © 2016 michaelscaria. All rights reserved.
//
import Foundation
struct City {
var x = 0.0
var y = 0.0
init() {
}
init(x: Double, y: Double) {
self.x = x
self.y = y
}
func distance(from city: City) -> Double {
let x_delta = x - city.x
let y_delta = y - city.y
return sqrt(pow(x_delta, 2) + pow(y_delta, 2))
}
}
extension City: Equatable {
static func ==(lhs: City, rhs: City) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
var allCities = [City]()
struct Tour {
var cities = [City]() {
didSet {
fitness = 0.0
distance = 0.0
}
}
var size: Int {
get {
return cities.count
}
}
var fitness = 0.0
var distance = 0.0
init() {
for _ in 0..<allCities.count {
cities.append(City())
}
}
subscript(index: Int) -> City {
get {
return cities[index]
}
set {
cities[index] = newValue
}
}
func contains(city: City) -> Bool {
return cities.contains(city)
}
mutating func getFitness() -> Double {
if fitness == 0 {
fitness = 1/getDistance()
}
return fitness
}
mutating func getDistance() -> Double {
if distance == 0 {
for (index, city) in cities.enumerated() {
if index < cities.count - 1 {
distance += city.distance(from: cities[index + 1])
}
}
}
return distance
}
mutating func generateIndividual() {
cities = allCities
cities.sort { _,_ in arc4random_uniform(2) == 0 }
}
}
struct Population {
private var tours = [Tour]()
var size: Int {
get {
return tours.count
}
}
init(size: Int, initialize: Bool) {
for _ in 0..<size {
if initialize {
var tour = Tour()
tour.generateIndividual()
tours.append(tour)
} else {
tours.append(Tour())
}
}
}
subscript(index: Int) -> Tour {
get {
return tours[index]
}
set {
tours[index] = newValue
}
}
func getFittest() -> Tour {
var fittest = tours.first!
for i in 0..<tours.count {
var tour = tours[i]
if fittest.getFitness() < tour.getFitness() {
fittest = tour
}
}
return fittest
}
}
let backgroundQueue: DispatchQueue!
if #available(OSX 10.10, *) {
backgroundQueue = DispatchQueue.global(qos: .background)
} else {
backgroundQueue = DispatchQueue.global(priority: .default)
}
let breedSemaphore = DispatchSemaphore(value: 0)
var breedQueues = [DispatchQueue]()
for i in 0..<5 {
breedQueues.append(DispatchQueue(label: "Breed Queue \(i)"))
}
struct Genetic {
let mutationRate = 0.015
let tournamentSize = 5
let elitism = true
// this should only be called in one place to reduce race condition-related bugs
func evolve(population: Population) -> Population {
var newPop = Population(size: population.size, initialize: false)
var offset = 0
if elitism {
newPop[0] = population.getFittest()
offset = 1
}
// BREED
let breedGroup = DispatchGroup()
for i in offset..<population.size {
breedQueues[i % breedQueues.count].async(group: breedGroup, execute: {
let parent1 = self.select(from: population)
let parent2 = self.select(from: population)
let child = self.crossover(parent1: parent1, parent2: parent2)
newPop[i] = child
})
}
breedGroup.notify(queue: DispatchQueue(label: "Breed Completion"), execute: {
breedSemaphore.signal()
})
breedSemaphore.wait()
// MUTATE
for i in offset..<population.size {
newPop[i] = mutate(tour: newPop[i])
}
return newPop
}
func crossover(parent1: Tour, parent2: Tour) -> Tour {
var child = Tour()
var start = Int(arc4random_uniform(UInt32(parent1.size)))
var end = Int(arc4random_uniform(UInt32(parent1.size)))
// make sure start is less than end
if start > end {
let oldEnd = end
end = start
start = oldEnd
}
var takenSlots = [Int]()
if start < end {
for i in (start+1)..<end {
child[i] = parent1[i]
takenSlots.append(i)
}
}
// this part is very inefficent
for i in 0..<allCities.count {
if !child.contains(city: parent2[i]) {
for j in 0..<allCities.count {
if !takenSlots.contains(j) {
child[j] = parent2[j]
takenSlots.append(j)
}
}
}
}
return child
}
func mutate(tour t: Tour) -> Tour {
var tour = t
for pos1 in 0..<tour.size {
if Double(arc4random_uniform(1000))/1000.0 < mutationRate {
let pos2 = Int(arc4random_uniform(UInt32(tour.size)))
let city1 = tour[pos1]
let city2 = tour[pos2]
tour[pos2] = city1
tour[pos1] = city2
}
}
return tour
}
func select(from population: Population) -> Tour {
var tournamentPop = Population(size: tournamentSize, initialize: false)
for i in 0..<tournamentSize {
let random = Int(arc4random_uniform(UInt32(population.size)))
tournamentPop[i] = population[random]
}
return tournamentPop.getFittest()
}
}
let programSemaphore = DispatchSemaphore(value: 0)
func parse(file: [String]) {
var i = 0
for line in file {
if (i > 5) {
let comps = line.components(separatedBy: " ").filter { return $0 != "" }
if comps.count == 3 {
let city = City(x: Double(comps[1])!, y: Double(comps[2])!)
allCities.append(city)
}
}
i += 1
}
backgroundQueue.async {
let genetic = Genetic()
var pop = Population(size: allCities.count, initialize: true)
var tour = pop.getFittest()
print("Start: \(tour.getDistance())")
for i in 0..<50 {
pop = genetic.evolve(population: pop)
if i % 1 == 0 {
tour = pop.getFittest()
print("\(i + 1). \(tour.getDistance())")
}
}
tour = pop.getFittest()
print("End: \(tour.getDistance())")
programSemaphore.signal()
}
programSemaphore.wait()
}
let arguments = CommandLine.arguments
if arguments.count > 1 {
let file = arguments[1]
do {
let content = try String(contentsOfFile:file, encoding: String.Encoding.utf8)
parse(file: content.components(separatedBy: "\n"))
} catch _ as NSError {}
}
| bsd-3-clause | 9303145e4d76d2fbbfe2e136776f0a01 | 22.796117 | 85 | 0.50714 | 4.135546 | false | false | false | false |
ytakzk/Swift-Alamofire-For-Qiita | swift-qiita/ViewController.swift | 1 | 2808 | //
// ViewController.swift
// swift-qiita
//
// Created by Yuta Akizuki on 2014/09/20.
// Copyright (c) 2014年 ytakzk.me. All rights reserved.
//
import UIKit
import Alamofire
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
var articles: Array<Article>?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
articles = Array()
// Get articles
var result: NSArray?
Alamofire.request(.GET, "https://qiita.com/api/v1/search?q=swift",parameters: nil, encoding: .JSON)
.responseJSON { (request, response, JSON, error) in
result = (JSON as NSArray)
// Make models from Json data
for (var i = 0; i < result?.count; i++) {
let dic: NSDictionary = result![i] as NSDictionary
var article: Article = Article(
title: dic["title"] as String,
userName: dic["user"]!["url_name"] as String,
linkURL: dic["url"] as String,
imageURL:dic["user"]!["profile_image_url"] as String
)
self.articles?.append(article)
}
self.tableView.reloadData()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return articles!.count
}
func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath:NSIndexPath!) -> UITableViewCell! {
let cell: MyTableViewCell = tableView?.dequeueReusableCellWithIdentifier("Cell") as MyTableViewCell
cell.article = articles?[indexPath.row]
return cell;
}
func tableView(tableView: UITableView?, didSelectRowAtIndexPath indexPath:NSIndexPath!) {
// When a cell has selected, open WebViewController.
let cell: MyTableViewCell = tableView?.cellForRowAtIndexPath(indexPath) as MyTableViewCell
self.performSegueWithIdentifier("WebViewController", sender: cell)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
// Assign a model to WebViewController
if segue.identifier == "WebViewController" {
var cell : MyTableViewCell = sender as MyTableViewCell
let vc: WebViewController = segue.destinationViewController as WebViewController
vc.article = cell.article
}
}
}
| mit | 9120c337c7d9af97b5e67e3c88ea04bc | 36.413333 | 111 | 0.607627 | 5.406551 | false | false | false | false |
stephentyrone/swift | validation-test/Reflection/reflect_Enum_TwoCaseOneStructPayload.swift | 3 | 15751 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift -g -lswiftSwiftReflectionTest %s -o %t/reflect_Enum_TwoCaseOneStructPayload
// RUN: %target-codesign %t/reflect_Enum_TwoCaseOneStructPayload
// RUN: %target-run %target-swift-reflection-test %t/reflect_Enum_TwoCaseOneStructPayload | %FileCheck %s --check-prefix=CHECK-%target-ptrsize --check-prefix=CHECK-ALL
// REQUIRES: objc_interop
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
import SwiftReflectionTest
// Note: struct Marker has no extra inhabitants, so the enum will use a separate tag
struct Marker {
let value = 1
}
enum TwoCaseOneStructPayloadEnum {
case valid(Marker)
case invalid
}
class ClassWithTwoCaseOneStructPayloadEnum {
var e1: TwoCaseOneStructPayloadEnum?
var e2: TwoCaseOneStructPayloadEnum = .valid(Marker())
var e3: TwoCaseOneStructPayloadEnum = .invalid
var e4: TwoCaseOneStructPayloadEnum? = .valid(Marker())
var e5: TwoCaseOneStructPayloadEnum? = .invalid
var e6: TwoCaseOneStructPayloadEnum??
}
reflect(object: ClassWithTwoCaseOneStructPayloadEnum())
// CHECK-64: Reflecting an object.
// CHECK-64: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-64: Type reference:
// CHECK-64: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum)
// CHECK-64: Type info:
// CHECK-64: (class_instance size=107 alignment=8 stride=112 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=e1 offset=16
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e2 offset=32
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (field name=e3 offset=48
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (field name=e4 offset=64
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e5 offset=80
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (field name=e6 offset=96
// CHECK-64: (single_payload_enum size=11 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=10 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=some index=0 offset=0
// CHECK-64: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (case name=valid index=0 offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=value offset=0
// CHECK-64: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64: (field name=_value offset=0
// CHECK-64: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64: (case name=invalid index=1)))
// CHECK-64: (case name=none index=1)))
// CHECK-64: (case name=none index=1))))
// CHECK-32: Reflecting an object.
// CHECK-32: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-32: Type reference:
// CHECK-32: (class reflect_Enum_TwoCaseOneStructPayload.ClassWithTwoCaseOneStructPayloadEnum)
// CHECK-32: Type info:
// CHECK-32: (class_instance size=55 alignment=4 stride=56 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=e1 offset=8
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e2 offset=16
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (field name=e3 offset=24
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (field name=e4 offset=32
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e5 offset=40
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (field name=e6 offset=48
// CHECK-32: (single_payload_enum size=7 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=6 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=some index=0 offset=0
// CHECK-32: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (case name=valid index=0 offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=value offset=0
// CHECK-32: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32: (field name=_value offset=0
// CHECK-32: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32: (case name=invalid index=1)))
// CHECK-32: (case name=none index=1)))
// CHECK-32: (case name=none index=1))))
reflect(enum: TwoCaseOneStructPayloadEnum.valid(Marker()))
// CHECK-ALL: Reflecting an enum.
// CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-ALL-NEXT: Type reference:
// CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum)
// CHECK-ALL: Type info:
// CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (case name=valid index=0 offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64-NEXT: (case name=invalid index=1))
// CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (case name=valid index=0 offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32-NEXT: (case name=invalid index=1))
// CHECK-ALL: Enum value:
// CHECK-ALL-NEXT: (enum_value name=valid index=0
// CHECK-ALL-NEXT: (struct reflect_Enum_TwoCaseOneStructPayload.Marker)
// CHECK-ALL-NEXT: )
reflect(enum: TwoCaseOneStructPayloadEnum.invalid)
// CHECK-ALL: Reflecting an enum.
// CHECK-ALL-NEXT: Instance pointer in child address space: 0x{{[0-9a-fA-F]+}}
// CHECK-ALL-NEXT: Type reference:
// CHECK-ALL-NEXT: (enum reflect_Enum_TwoCaseOneStructPayload.TwoCaseOneStructPayloadEnum)
// CHECK-ALL: Type info:
// CHECK-64-NEXT: (single_payload_enum size=9 alignment=8 stride=16 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (case name=valid index=0 offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=value offset=0
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-64-NEXT: (case name=invalid index=1))
// CHECK-32-NEXT: (single_payload_enum size=5 alignment=4 stride=8 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (case name=valid index=0 offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=value offset=0
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0 bitwise_takable=1))))))
// CHECK-32-NEXT: (case name=invalid index=1))
// CHECK-ALL: Enum value:
// CHECK-ALL-NEXT: (enum_value name=invalid index=1)
doneReflecting()
// CHECK-ALL: Done.
| apache-2.0 | 1307f1760496f05115bdea629e885678 | 62.004 | 167 | 0.663069 | 3.356991 | false | false | false | false |
bracken-dev/Readability-Swift | Readability-Swift/Classes/Readability.swift | 1 | 7599 | //
// Readability.swift
// Readability-Swift
//
// Created by brackendev.
// Copyright (c) 2014-2019 brackendev. All rights reserved.
//
// Automated Readability Index: automatedReadabilityIndexForString
// Coleman–Liau Index: colemanLiauIndexForString
// Flesch-Kincaid Grade Level: fleschKincaidGradeLevelForString
// Flesch Reading Ease: fleschReadingEaseForString
// Gunning Fog Index: gunningFogScoreForString
// SMOG Grade: smogGradeForString
import Foundation
public class Readability {
// MARK: - Automated Readability Index
// http://en.wikipedia.org/wiki/Automated_Readability_Index
public class func automatedReadabilityIndexForString(_ string: String) -> [String: Any] {
let score = automatedReadabilityIndexScoreForString(string)
let dict = ["Score": score,
"Ages": automatedReadabilityIndexAgesForScore(score),
"USA School Level": automatedReadabilityIndexUSASchoolLevelForScore(score)] as [String: Any]
return dict
}
public class func automatedReadabilityIndexScoreForString(_ string: String) -> Float {
let totalWords = Float(string.wordCount())
let totalSentences = Float(string.sentenceCount())
let totalAlphanumericCharacters = Float(string.alphanumericCount())
let score = 4.71 * (totalAlphanumericCharacters / totalWords) + 0.5 * (totalWords / totalSentences) - 21.43
return score.round(to: 1)
}
public class func automatedReadabilityIndexAgesForScore(_ score: Float) -> String {
if score >= 15 {
return "23+"
} else if score >= 14 {
return "18-22"
} else if score >= 13 {
return "17-18"
} else if score >= 12 {
return "16-17"
} else if score >= 11 {
return "15-16"
} else if score >= 10 {
return "14-15"
} else if score >= 9 {
return "13-14"
} else if score >= 8 {
return "12-13"
} else if score >= 7 {
return "11-12"
} else if score >= 6 {
return "10-11"
} else if score >= 5 {
return "9-10"
} else if score >= 4 {
return "8-9"
} else if score >= 3 {
return "7-8"
} else if score >= 2 {
return "6-7"
} else {
return "5-6"
}
}
public class func automatedReadabilityIndexUSASchoolLevelForScore(_ score: Float) -> String {
if score >= 14 {
return "College"
} else if score >= 13 {
return "12"
} else if score >= 12 {
return "11"
} else if score >= 11 {
return "10"
} else if score >= 10 {
return "9"
} else if score >= 9 {
return "8"
} else if score >= 8 {
return "7"
} else if score >= 7 {
return "6"
} else if score >= 6 {
return "5"
} else if score >= 5 {
return "4"
} else if score >= 4 {
return "3"
} else if score >= 3 {
return "2"
} else if score >= 2 {
return "1"
} else {
return "Kindergarten"
}
}
// MARK: - Coleman-Liau Index
// http://en.wikipedia.org/wiki/Coleman–Liau_index
public class func colemanLiauIndexForString(_ string: String) -> Float {
let totalWords = Float(string.wordCount())
let totalSentences = Float(string.sentenceCount())
let totalAlphanumericCharacters = Float(string.alphanumericCount())
let score = 5.88 * (totalAlphanumericCharacters / totalWords) - 0.296 * (totalSentences / totalWords) - 15.8
return score.round(to: 1)
}
// MARK: - Flesch-Kincaid Grade Level
// http://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests
public class func fleschKincaidGradeLevelForString(_ string: String) -> Float {
let totalWords = Float(string.wordCount())
let totalSentences = Float(string.sentenceCount())
let alphaNumeric = string.alphanumeric()
let totalSyllables = Float(SyllableCounter.syllableCount(forWords: alphaNumeric))
let score = 0.39 * (totalWords / totalSentences) + 11.8 * (totalSyllables / totalWords) - 15.59
return score.round(to: 1)
}
// MARK: - Flesch Reading Ease
// http://en.wikipedia.org/wiki/Flesch–Kincaid_readability_tests
public class func fleschReadingEaseForString(_ string: String) -> [String: Any] {
let score = fleschReadingEaseScoreForString(string)
let dict = ["Score": score,
"USA School Level": fleschReadingEaseUSASchoolLevelForScore(score),
"Notes": fleschReadingEaseNotesForScore(score)] as [String: Any]
return dict
}
public class func fleschReadingEaseScoreForString(_ string: String) -> Float {
let totalWords = Float(string.wordCount())
let totalSentences = Float(string.sentenceCount())
let alphaNumeric = string.alphanumeric()
let totalSyllables = Float(SyllableCounter.syllableCount(forWords: alphaNumeric))
let score = 206.835 - (1.015 * (totalWords / totalSentences)) - (84.6 * (totalSyllables / totalWords))
return score.round(to: 1)
}
public class func fleschReadingEaseUSASchoolLevelForScore(_ score: Float) -> String {
if score >= 90 {
return "5"
} else if score >= 80 {
return "6"
} else if score >= 70 {
return "7"
} else if score >= 60 {
return "8-9"
} else if score >= 50 {
return "10-12"
} else if score >= 30 {
return "College"
} else {
return "College Graduate"
}
}
public class func fleschReadingEaseNotesForScore(_ score: Float) -> String {
if score >= 90 {
return "Very easy to read. Easily understood by an average 11-year-old student."
} else if score >= 80 {
return "Easy to read. Conversational English for consumers."
} else if score >= 70 {
return "Fairly easy to read."
} else if score >= 60 {
return "Plain English. Easily understood by 13- to 15-year-old students."
} else if score >= 50 {
return "Fairly difficult to read."
} else if score >= 30 {
return "Difficult to read."
} else {
return "Very difficult to read. Best understood by university graduates."
}
}
// MARK: - Gunning Fog Score
// http://en.wikipedia.org/wiki/Gunning_fog_index
public class func gunningFogScoreForString(_ string: String) -> Float {
let totalWords = Float(string.wordCount())
let totalSentences = Float(string.sentenceCount())
let totalComplexWords = Float(string.complexWordCount())
let score = 0.4 * ((totalWords / totalSentences) + 100.0 * (totalComplexWords / totalWords))
return score.round(to: 1)
}
// MARK: - SMOG Grade
// http://en.wikipedia.org/wiki/Gunning_fog_index
public class func smogGradeForString(_ string: String) -> Float {
let totalPolysyllables = Float(string.polysyllableWords(excludeCommonSuffixes: false))
let totalSentences = Float(string.sentenceCount())
let score = 1.043 * sqrtf(totalPolysyllables * (30.0 / totalSentences) + 3.1291)
return score.round(to: 1)
}
}
| mit | 66a6cf69af5d2bf19723146e5e68f067 | 34.976303 | 116 | 0.585562 | 4.380265 | false | false | false | false |
mnisn/zhangchu | zhangchu/zhangchu/classes/recipe/recommend/main/view/RecommendWidgetBtnHeaderView.swift | 1 | 1121 | //
// RecommendWidgetBtnHeaderView.swift
// zhangchu
//
// Created by 苏宁 on 2016/10/26.
// Copyright © 2016年 suning. All rights reserved.
//
import UIKit
class RecommendWidgetBtnHeaderView: UIView {
var textField:UITextField!
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor(red: 243 / 255, green: 243 / 255, blue: 244 / 255, alpha: 1)
//
textField = UITextField(frame: CGRect(x: 35, y: 8, width: bounds.size.width - 30 * 2, height: 30))
textField.placeholder = "输入菜名或食材搜索"
textField.textAlignment = .Center
textField.borderStyle = .RoundedRect
addSubview(textField)
//
let imgView = UIImageView(image: UIImage(named: "search1"))
imgView.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
imgView.backgroundColor = UIColor.cyanColor()
textField.leftView = imgView
textField.leftViewMode = .Always
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 389086592f8e1300667bcb42febdc51c | 28.621622 | 106 | 0.62865 | 4.029412 | false | false | false | false |
HabitRPG/habitrpg-ios | Habitica Database/Habitica Database/Models/Content/RealmCustomization.swift | 1 | 1332 | //
// RealmCustomization.swift
// Habitica Database
//
// Created by Phillip Thelen on 20.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import RealmSwift
class RealmCustomization: Object, CustomizationProtocol {
@objc dynamic var combinedKey: String?
@objc dynamic var key: String?
@objc dynamic var type: String?
@objc dynamic var group: String?
@objc dynamic var price: Float = 0
var set: CustomizationSetProtocol? {
get {
return realmSet
}
set {
if let newSet = newValue as? RealmCustomizationSet {
realmSet = newSet
} else if let newSet = newValue {
realmSet = RealmCustomizationSet(newSet)
}
}
}
@objc dynamic var realmSet: RealmCustomizationSet?
override static func primaryKey() -> String {
return "combinedKey"
}
convenience init(_ customizationProtocol: CustomizationProtocol) {
self.init()
key = customizationProtocol.key
type = customizationProtocol.type
group = customizationProtocol.group
combinedKey = (key ?? "") + (type ?? "") + (group ?? "")
price = customizationProtocol.price
set = customizationProtocol.set
}
}
| gpl-3.0 | c2416b7e7740e1b80f88ed3cfbe936af | 27.934783 | 70 | 0.624343 | 4.92963 | false | false | false | false |
Driftt/drift-sdk-ios | Drift/Managers/PresentationManager.swift | 1 | 3703 | //
// PresentationManager.swift
// Drift
//
// Created by Eoin O'Connell on 26/01/2016.
// Copyright © 2016 Drift. All rights reserved.
//
import UIKit
protocol PresentationManagerDelegate:class {
func messageViewDidFinish(_ view: CampaignView)
}
///Responsible for showing a campaign
class PresentationManager: PresentationManagerDelegate {
static var sharedInstance: PresentationManager = PresentationManager()
weak var currentShownView: CampaignView?
private var shouldShowMessagePopup = true
init () {}
func shouldShowMessagePopup(show: Bool) {
shouldShowMessagePopup = show
}
func didRecieveNewMessages(_ enrichedConversations: [EnrichedConversation]) {
guard shouldShowMessagePopup else { return }
if let newMessageView = NewMessageView.drift_fromNib() as? NewMessageView , currentShownView == nil && !conversationIsPresenting() && !enrichedConversations.isEmpty{
if let window = UIApplication.shared.keyWindow {
currentShownView = newMessageView
if let currentConversation = enrichedConversations.first, let lastMessage = currentConversation.lastMessage {
let otherConversations = enrichedConversations.filter({ $0.conversation.id != currentConversation.conversation.id })
newMessageView.otherConversations = otherConversations
newMessageView.message = lastMessage
newMessageView.delegate = self
newMessageView.showOnWindow(window)
}
}
}
}
func didRecieveNewMessage(_ message: Message) {
guard shouldShowMessagePopup else { return }
if let newMessageView = NewMessageView.drift_fromNib() as? NewMessageView , currentShownView == nil && !conversationIsPresenting() {
if let window = UIApplication.shared.keyWindow {
currentShownView = newMessageView
newMessageView.message = message
newMessageView.delegate = self
newMessageView.showOnWindow(window)
}
}
}
func conversationIsPresenting() -> Bool{
if let topVC = TopController.viewController() , topVC.classForCoder == ConversationListViewController.classForCoder() || topVC.classForCoder == ConversationViewController.classForCoder(){
return true
}
return false
}
func showConversationList(endUserId: Int64?){
let conversationListController = ConversationListViewController.navigationController(endUserId: endUserId)
TopController.viewController()?.present(conversationListController, animated: true, completion: nil)
}
func showConversationVC(_ conversationId: Int64) {
if let topVC = TopController.viewController() {
let navVC = ConversationViewController.navigationController(ConversationViewController.ConversationType.continueConversation(conversationId: conversationId))
topVC.present(navVC, animated: true, completion: nil)
}
}
func showNewConversationVC(initialMessage: String? = nil) {
if let topVC = TopController.viewController() {
let navVC = ConversationViewController.navigationController(ConversationViewController.ConversationType.createConversation, initialMessage: initialMessage)
topVC.present(navVC, animated: true)
}
}
///Presentation Delegate
func messageViewDidFinish(_ view: CampaignView) {
view.hideFromWindow()
currentShownView = nil
}
}
| mit | 118a0322c214445ee479205fd8bf3aa3 | 36.393939 | 195 | 0.668828 | 6.00974 | false | false | false | false |
Rehsco/StyledAuthenticationView | StyledAuthenticationView/UI/Styling/StyledAuthenticationViewConfiguration.swift | 1 | 3447 | //
// StyledAuthenticationViewConfiguration.swift
// StyledAuthenticationView
//
// Created by Martin Rehder on 16.02.2019.
/*
* Copyright 2017-present Martin Jacob Rehder.
* http://www.rehsco.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import FlexCollections
import FlexControls
public class StyledAuthenticationViewConfiguration {
public init() {
}
// Touch ID
public var touchIDDetailText = "Authentication using Touch ID"
// PIN
public var pinHeaderText = "Enter PIN Code"
public var usePinCodeText = "Use PIN Code"
public var createPinHeaderText = "Enter new PIN Code"
public var verifyPinHeaderText = "Verify PIN Code"
public var expectedPinCodeLength = 6
// Password
public var passwordHeaderText = "Enter Password"
public var createPasswordHeaderText = "Enter new Password"
public var verifyPasswordHeaderText = "Verify Password"
// Options
public var vibrateOnFail = true
public var allowedRetries = 3
public var showCancel = true
// Styling
public var securityViewPreferredSize: CGSize = CGSize(width: 300, height: 480)
public var pinCellPreferredSize: CGSize = CGSize(width: 80, height: 80)
public var microPinViewHeight: CGFloat = 75
public var pinViewFooterHeight: CGFloat = 25
public var passwordViewHeight: CGFloat = 120
public var pinStyle: FlexShapeStyle = FlexShapeStyle(style: .thumb)
public var pinBorderColor: UIColor = .white
public var pinSelectionColor: UIColor = .white
public var pinInnerColor: UIColor = .clear
public var pinBorderWidth: CGFloat = 0.5
public var pinTextColor: UIColor = .white
public var pinFont: UIFont = UIFont.systemFont(ofSize: 36)
public var cancelDeleteButtonFont: UIFont = UIFont.systemFont(ofSize: 18)
public var cancelDeleteButtonTextColor: UIColor = .white
public var headerTextColor: UIColor = .white
public var headerTextFont: UIFont = UIFont.systemFont(ofSize: 18)
public var passwordStyle: FlexShapeStyle = FlexShapeStyle(style: .box)
public var passwordBorderColor: UIColor = .white
public var passwordAcceptButtonIcon: UIImage? = UIImage(named: "Accept_36pt", in: Bundle(for: StyledAuthenticationViewConfiguration.self), compatibleWith: nil)
public var backgroundGradientStartColor: UIColor?
public var backgroundGradientEndColor: UIColor?
}
| mit | 13771573a3a591b34143e0cf07777d71 | 39.081395 | 163 | 0.746736 | 4.689796 | false | false | false | false |
sschiau/swift | test/DebugInfo/enum.swift | 2 | 3312 | // RUN: %target-swift-frontend -primary-file %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend -primary-file %s -emit-ir -gdwarf-types -o - | %FileCheck %s --check-prefix=DWARF
// UNSUPPORTED: OS=watchos
protocol P {}
enum Either {
case First(Int64), Second(P), Neither
// CHECK: !DICompositeType({{.*}}name: "Either",
// CHECK-SAME: line: [[@LINE-3]],
// CHECK-SAME: size: {{328|168}},
}
// CHECK: ![[EMPTY:.*]] = !{}
// DWARF: ![[INT:.*]] = !DICompositeType({{.*}}identifier: "$sSiD"
let E : Either = .Neither;
// CHECK: !DICompositeType({{.*}}name: "Color",
// CHECK-SAME: line: [[@LINE+3]]
// CHECK-SAME: size: 8,
// CHECK-SAME: identifier: "$s4enum5ColorOD"
enum Color : UInt64 {
// This is effectively a 2-bit bitfield:
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "Red"
// DWARF-SAME: baseType: ![[UINT64:[0-9]+]]
// DWARF-SAME: size: 8{{[,)]}}
// DWARF: ![[UINT64]] = !DICompositeType({{.*}}identifier: "$ss6UInt64VD"
case Red, Green, Blue
}
// CHECK: !DICompositeType({{.*}}name: "MaybeIntPair",
// CHECK-SAME: line: [[@LINE+3]],
// CHECK-SAME: size: 136{{[,)]}}
// CHECK-SAME: identifier: "$s4enum12MaybeIntPairOD"
enum MaybeIntPair {
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "none"
// DWARF-SAME: baseType: ![[INT]]{{[,)]}}
case none
// DWARF: !DIDerivedType(tag: DW_TAG_member, name: "just"
// DWARF-SAME: baseType: ![[INTTUP:[0-9]+]]
// DWARF-SAME: size: 128{{[,)]}}
// DWARF: ![[INTTUP]] = !DICompositeType({{.*}}identifier: "$ss5Int64V_ABtD"
case just(Int64, Int64)
}
enum Maybe<T> {
case none
case just(T)
}
let r = Color.Red
let c = MaybeIntPair.just(74, 75)
// CHECK: !DICompositeType({{.*}}name: "Maybe",
// CHECK-SAME: line: [[@LINE-8]],
// CHECK-SAME: size: 8{{[,)]}}
// CHECK-SAME: identifier: "$s4enum5MaybeOyAA5ColorOGD"
let movie : Maybe<Color> = .none
public enum Nothing { }
public func foo(_ empty : Nothing) { }
// CHECK: !DICompositeType({{.*}}name: "Nothing", {{.*}}elements: ![[EMPTY]]
// CHECK: !DICompositeType({{.*}}name: "Rose", {{.*}}elements: ![[ELTS:[0-9]+]],
// CHECK-SAME: {{.*}}identifier: "$s4enum4RoseOyxG{{z?}}D")
enum Rose<A> {
case MkRose(() -> A, () -> [Rose<A>])
// DWARF: !DICompositeType({{.*}}name: "Rose",{{.*}}identifier: "$s4enum4RoseOyxGD")
case IORose(() -> Rose<A>)
}
func foo<T>(_ x : Rose<T>) -> Rose<T> { return x }
// CHECK: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]], {{.*}}identifier: "$s4enum5TupleOyxGD")
// DWARF: !DICompositeType({{.*}}name: "Tuple", {{.*}}elements: ![[ELTS:[0-9]+]],
// DWARF-SAME: {{.*}}identifier: "$s4enum5TupleOyxG{{z?}}D")
public enum Tuple<P> {
case C(P, () -> Tuple)
}
func bar<T>(_ x : Tuple<T>) -> Tuple<T> { return x }
// CHECK: ![[LIST:.*]] = !DICompositeType({{.*}}identifier: "$s4enum4ListOyxGD"
// CHECK-DAG: ![[LET_LIST:.*]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[LIST]])
// CHECK-DAG: !DILocalVariable(name: "self", arg: 1, {{.*}} line: [[@LINE+4]], type: ![[LET_LIST]], flags: DIFlagArtificial)
public enum List<T> {
indirect case Tail(List, T)
case End
func fooMyList() {}
}
| apache-2.0 | 00bb9f860f57a723bc3623b35bf58093 | 36.213483 | 124 | 0.564312 | 3.22807 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/IncrementalCompilation/Bitcode/BitstreamVisitor.swift | 1 | 1064 | //===----------- BitstreamVisitor.swift - LLVM Bitstream Visitor ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
public protocol BitstreamVisitor {
/// Customization point to validate a bitstream's signature or "magic number".
func validate(signature: Bitcode.Signature) throws
/// Called when a new block is encountered. Return `true` to enter the block
/// and read its contents, or `false` to skip it.
mutating func shouldEnterBlock(id: UInt64) throws -> Bool
/// Called when a block is exited.
mutating func didExitBlock() throws
/// Called whenever a record is encountered.
mutating func visit(record: BitcodeElement.Record) throws
}
| apache-2.0 | 1e2ef4d4002563cf60c5a505aa31742b | 45.26087 | 80 | 0.671053 | 4.687225 | false | false | false | false |
PJayRushton/stats | Stats/NSAttributedString+Helpers.swift | 1 | 1902 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
import UIKit
public extension NSMutableAttributedString {
public func increaseFontSize(by multiplier: CGFloat) {
enumerateAttribute(NSAttributedStringKey.font, in: NSMakeRange(0, length), options: []) { (font, range, stop) in
guard let font = font as? UIFont else { return }
let newFont = font.withSize(font.pointSize * multiplier)
removeAttribute(NSAttributedStringKey.font, range: range)
addAttribute(NSAttributedStringKey.backgroundColor, value: newFont, range: range)
}
}
func highlightStrings(_ stringToHighlight: String?, color: UIColor) {
let textMatches = string.matches(for: stringToHighlight)
for match in textMatches {
addAttribute(NSAttributedStringKey.backgroundColor, value: color, range: match.range)
}
}
}
public extension String {
func matches(for stringToHighlight: String?) -> [NSTextCheckingResult] {
guard let stringToHighlight = stringToHighlight, !stringToHighlight.isEmpty else { return [] }
do {
let expression = try NSRegularExpression(pattern: stringToHighlight, options: [.caseInsensitive, .ignoreMetacharacters])
return expression.matches(in: self, options: [], range: NSRange(location: 0, length: count))
} catch {
print("status=could-not-create-regex error=\(error)")
return []
}
}
}
public extension NSAttributedString {
public func withIncreasedFontSize(by multiplier: CGFloat) -> NSAttributedString {
let mutableCopy = NSMutableAttributedString(attributedString: self)
mutableCopy.increaseFontSize(by: multiplier)
return mutableCopy
}
}
| mit | c777afde2e8cdb7e0637b384bb014879 | 31.842105 | 132 | 0.632479 | 4.952381 | false | false | false | false |
timfuqua/Bourgeoisie | Bourgeoisie/BourgeoisieTests/CardDeckTests.swift | 1 | 17076 | //
// CardDeckTests.swift
// Bourgeoisie
//
// Created by Tim Fuqua on 1/2/16.
// Copyright © 2016 FuquaProductions. All rights reserved.
//
import XCTest
import Buckets
@testable import Bourgeoisie
class CardDeckTests: 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()
}
// MARK: Test init
func testInitEmpty() {
let deck = BourgDeck()
XCTAssert(deck.numberOfCards == 0)
deck.printDeckTopToBottom()
}
func testInitHearts() {
let deck = BourgDeck(cards: SPC.allHearts)
deck.printDeckTopToBottom()
XCTAssert(deck.numberOfCards == 13)
XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Hearts }).count == 13)
}
func testInitDiamonds() {
let deck = BourgDeck(cards: SPC.allDiamonds)
deck.printDeckTopToBottom()
XCTAssert(deck.numberOfCards == 13)
XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Diamonds }).count == 13)
deck.printDeckTopToBottom()
}
func testInitSpades() {
let deck = BourgDeck(cards: SPC.allSpades)
deck.printDeckTopToBottom()
XCTAssert(deck.numberOfCards == 13)
XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Spades }).count == 13)
deck.printDeckTopToBottom()
}
func testInitClubs() {
let deck = BourgDeck(cards: SPC.allClubs)
deck.printDeckTopToBottom()
XCTAssert(deck.numberOfCards == 13)
XCTAssert(deck.dequeCards.filter({ return $0.suit == Suit.Clubs }).count == 13)
deck.printDeckTopToBottom()
}
// MARK: Test has cards
func testHasCard() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
}
func testNumberOfCopiesOfCard() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.addCardToTop(SPC.aceOfHearts)
XCTAssert(acesDeck.numberOfCards == 5)
XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 2)
XCTAssert(acesDeck.hasCard(SPC.twoOfHearts) == false)
XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.twoOfHearts) == 0)
acesDeck.printDeckTopToBottom()
}
// MARK: Test add cards
func testAddCardToTop() {
let initiallyEmptyDeck = BourgDeck()
initiallyEmptyDeck.addCardToTop(SPC.aceOfHearts)
XCTAssert(initiallyEmptyDeck.numberOfCards == 1)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts))
initiallyEmptyDeck.printDeckTopToBottom()
initiallyEmptyDeck.addCardToTop(SPC.aceOfDiamonds)
initiallyEmptyDeck.addCardToTop(SPC.aceOfSpades)
initiallyEmptyDeck.addCardToTop(SPC.aceOfClubs)
XCTAssert(initiallyEmptyDeck.numberOfCards == 4)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts)
&& initiallyEmptyDeck.arrayCards[0] == SPC.aceOfHearts)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfDiamonds)
&& initiallyEmptyDeck.arrayCards[1] == SPC.aceOfDiamonds)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfSpades)
&& initiallyEmptyDeck.arrayCards[2] == SPC.aceOfSpades)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfClubs)
&& initiallyEmptyDeck.arrayCards[3] == SPC.aceOfClubs)
initiallyEmptyDeck.printDeckTopToBottom()
}
func testAddCardToBottom() {
let initiallyEmptyDeck = BourgDeck()
initiallyEmptyDeck.addCardToBottom(SPC.aceOfHearts)
XCTAssert(initiallyEmptyDeck.numberOfCards == 1)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts))
initiallyEmptyDeck.printDeckTopToBottom()
initiallyEmptyDeck.addCardToBottom(SPC.aceOfDiamonds)
initiallyEmptyDeck.addCardToBottom(SPC.aceOfSpades)
initiallyEmptyDeck.addCardToBottom(SPC.aceOfClubs)
XCTAssert(initiallyEmptyDeck.numberOfCards == 4)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfHearts)
&& initiallyEmptyDeck.arrayCards[3] == SPC.aceOfHearts)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfDiamonds)
&& initiallyEmptyDeck.arrayCards[2] == SPC.aceOfDiamonds)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfSpades)
&& initiallyEmptyDeck.arrayCards[1] == SPC.aceOfSpades)
XCTAssert(initiallyEmptyDeck.hasCard(SPC.aceOfClubs)
&& initiallyEmptyDeck.arrayCards[0] == SPC.aceOfClubs)
initiallyEmptyDeck.printDeckTopToBottom()
}
// MARK: Test remove cards
func testRemoveCardFromTop() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromTop()
XCTAssert(acesDeck.numberOfCards == 3)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromTop()
XCTAssert(acesDeck.numberOfCards == 2)
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromTop()
XCTAssert(acesDeck.numberOfCards == 1)
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromTop()
XCTAssert(acesDeck.numberOfCards == 0)
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false)
acesDeck.printDeckTopToBottom()
}
func testRemoveCardFromBottom() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromBottom()
XCTAssert(acesDeck.numberOfCards == 3)
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromBottom()
XCTAssert(acesDeck.numberOfCards == 2)
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromBottom()
XCTAssert(acesDeck.numberOfCards == 1)
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false)
acesDeck.printDeckTopToBottom()
acesDeck.removeCardFromBottom()
XCTAssert(acesDeck.numberOfCards == 0)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false)
acesDeck.printDeckTopToBottom()
}
func testRemoveFirstOccurenceOfCard() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
acesDeck.addCardToBottom(SPC.aceOfHearts)
XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 2)
acesDeck.printDeckTopToBottom()
acesDeck.removeFirstOccurenceOfCard(SPC.aceOfHearts)
XCTAssert(acesDeck.numberOfCopiesOfCard(SPC.aceOfHearts) == 1)
acesDeck.printDeckTopToBottom()
}
func testRemoveAllCards() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
acesDeck.removeAllCards()
XCTAssert(acesDeck.numberOfCards == 0)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == false)
acesDeck.printDeckTopToBottom()
}
// MARK: Test shuffle
func testShuffle() {
let originalHeartsDeck = BourgDeck(cards: SPC.allHearts)
let shuffledHeartsDeck = BourgDeck(cards: SPC.allHearts)
XCTAssert(originalHeartsDeck.numberOfCards == 13)
XCTAssert(shuffledHeartsDeck.numberOfCards == 13)
originalHeartsDeck.printDeckTopToBottom()
shuffledHeartsDeck.shuffle()
shuffledHeartsDeck.printDeckTopToBottom()
XCTAssert(originalHeartsDeck != shuffledHeartsDeck)
}
// MARK: Test peek
func testPeekAtTopCard() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
print(acesDeck.peekAtTopCard() ?? "Empty Deck")
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
}
func testPeekAtCardOffsetFromTop() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
print("Peeking 1 deep: ", terminator: "")
print(acesDeck.peekAtCardOffsetFromTop(1) ?? "Empty Deck or peeking beyond bottom of deck")
print("Peeking 2 deep: ", terminator: "")
print(acesDeck.peekAtCardOffsetFromTop(2) ?? "Empty Deck or peeking beyond bottom of deck")
print("Peeking 3 deep: ", terminator: "")
print(acesDeck.peekAtCardOffsetFromTop(3) ?? "Empty Deck or peeking beyond bottom of deck")
print("Peeking 4 deep: ", terminator: "")
print(acesDeck.peekAtCardOffsetFromTop(4) ?? "Empty Deck or peeking beyond bottom of deck")
print("Peeking 5 deep: ", terminator: "")
print(acesDeck.peekAtCardOffsetFromTop(5) ?? "Empty Deck or peeking beyond bottom of deck")
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
}
// MARK: Test draw cards
func testDrawTopCard() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let acesDeck = BourgDeck(cards: aces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
XCTAssert(acesDeck.numberOfCards == 3)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
}
func testDrawTopCards() {
let acesDeck = BourgDeck(cards: SPC.allAces)
XCTAssert(acesDeck.numberOfCards == 4)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts))
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds))
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades))
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs))
acesDeck.printDeckTopToBottom()
print("Drawing top 2 cards: ", terminator: "")
print(acesDeck.drawTopCards(2) ?? "Empty Deck")
XCTAssert(acesDeck.numberOfCards == 2)
XCTAssert(acesDeck.hasCard(SPC.aceOfHearts) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfDiamonds) == false)
XCTAssert(acesDeck.hasCard(SPC.aceOfSpades) == true)
XCTAssert(acesDeck.hasCard(SPC.aceOfClubs) == true)
acesDeck.printDeckTopToBottom()
print("Drawing top 3 cards: ", terminator: "")
print(acesDeck.drawTopCards(3) ?? "Empty Deck")
acesDeck.printDeckTopToBottom()
print("Drawing top card: ", terminator: "")
print(acesDeck.drawTopCard() ?? "Empty Deck")
}
// MARK: Test move cards
func testMoveTopCards() {
let aces = [SPC.aceOfHearts, SPC.aceOfDiamonds, SPC.aceOfSpades, SPC.aceOfClubs]
let originalDeck = BourgDeck(cards: aces)
let deck = BourgDeck(cards: aces)
let discardPile = BourgDeck()
XCTAssert(deck.numberOfCards == 4)
XCTAssert(deck.hasCard(SPC.aceOfHearts))
XCTAssert(deck.hasCard(SPC.aceOfDiamonds))
XCTAssert(deck.hasCard(SPC.aceOfSpades))
XCTAssert(deck.hasCard(SPC.aceOfClubs))
XCTAssert(discardPile.numberOfCards == 0)
print("\"Deck\" ", terminator: "")
deck.printDeckTopToBottom()
print("\"Discard Pile\" ", terminator: "")
discardPile.printDeckTopToBottom()
print("Attempt to move top 5 cards")
deck.moveTopCards(5, toDeck: discardPile)
XCTAssert(deck.numberOfCards == 4)
XCTAssert(deck.hasCard(SPC.aceOfHearts))
XCTAssert(deck.hasCard(SPC.aceOfDiamonds))
XCTAssert(deck.hasCard(SPC.aceOfSpades))
XCTAssert(deck.hasCard(SPC.aceOfClubs))
XCTAssert(discardPile.numberOfCards == 0)
print("\"Deck\" ", terminator: "")
deck.printDeckTopToBottom()
print("\"Discard Pile\" ", terminator: "")
discardPile.printDeckTopToBottom()
print("Attempt to move top 1 cards")
deck.moveTopCards(1, toDeck: discardPile)
XCTAssert(deck.numberOfCards == 3)
XCTAssert(deck.hasCard(SPC.aceOfHearts) == false)
XCTAssert(deck.hasCard(SPC.aceOfDiamonds))
XCTAssert(deck.hasCard(SPC.aceOfSpades))
XCTAssert(deck.hasCard(SPC.aceOfClubs))
XCTAssert(discardPile.numberOfCards == 1)
XCTAssert(discardPile.hasCard(SPC.aceOfHearts))
print("\"Deck\" ", terminator: "")
deck.printDeckTopToBottom()
print("\"Discard Pile\" ", terminator: "")
discardPile.printDeckTopToBottom()
print("Attempt to move top 3 cards")
deck.moveTopCards(3, toDeck: discardPile)
XCTAssert(deck.numberOfCards == 0)
XCTAssert(deck.hasCard(SPC.aceOfHearts) == false)
XCTAssert(deck.hasCard(SPC.aceOfDiamonds) == false)
XCTAssert(deck.hasCard(SPC.aceOfSpades) == false)
XCTAssert(deck.hasCard(SPC.aceOfClubs) == false)
XCTAssert(discardPile.numberOfCards == 4)
XCTAssert(discardPile.hasCard(SPC.aceOfHearts))
XCTAssert(discardPile.hasCard(SPC.aceOfDiamonds))
XCTAssert(discardPile.hasCard(SPC.aceOfSpades))
XCTAssert(discardPile.hasCard(SPC.aceOfClubs))
print("\"Deck\" ", terminator: "")
deck.printDeckTopToBottom()
print("\"Discard Pile\" ", terminator: "")
discardPile.printDeckTopToBottom()
XCTAssert(discardPile.arrayCards.reverse() == originalDeck.arrayCards)
}
}
| mit | cd6d418cff3a78ee4f3a950fd2099a66 | 32.480392 | 107 | 0.70858 | 4.745692 | false | true | false | false |
GianniCarlo/JSQMessagesViewController | SwiftExample/SwiftExample/ChatViewController.swift | 1 | 26320 | //
// ChatViewController.swift
// SwiftExample
//
// Created by Dan Leonard on 5/11/16.
// Copyright © 2016 MacMeDan. All rights reserved.
//
import UIKit
import JSQMessagesViewController
protocol JSQDemoViewControllerDelegate : NSObjectProtocol {
func didDismissJSQDemoViewController(vc: ChatViewController)
}
/**
* Override point for customization.
*
* Customize your view.
* Look at the properties on `JSQMessagesViewController` and `JSQMessagesCollectionView` to see what is possible.
*
* Customize your layout.
* Look at the properties on `JSQMessagesCollectionViewFlowLayout` to see what is possible.
*/
class ChatViewController: JSQMessagesViewController, JSQMessagesComposerTextViewPasteDelegate {
var conversation: Conversation!
var outgoingBubbleImageData: JSQMessagesBubbleImage!
var incomingBubbleImageData: JSQMessagesBubbleImage!
weak var delegateModal: JSQDemoViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
self.title = self.conversation.name;
/**
* You MUST set your senderId and display name
*/
self.senderId = AvatarIDCarlo;
self.senderDisplayName = DisplayNameCarlo;
self.inputToolbar.contentView.textView.pasteDelegate = self;
/**
* You can set custom avatar sizes
*/
// self.collectionView.collectionViewLayout.incomingAvatarViewSize = .zero;
// self.collectionView.collectionViewLayout.outgoingAvatarViewSize = .zero;
self.showLoadEarlierMessagesHeader = true;
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage.jsq_defaultTypingIndicatorImage(), style: .Plain, target: self, action: #selector(receiveMessagePressed))
/**
* Register custom menu actions for cells.
*/
JSQMessagesCollectionViewCell.registerMenuAction(#selector(customAction))
/**
* OPT-IN: allow cells to be deleted
*/
JSQMessagesCollectionViewCell.registerMenuAction(#selector(delete(_:)))
/**
* Customize your toolbar buttons
*
* self.inputToolbar.contentView.leftBarButtonItem = custom button or nil to remove
* self.inputToolbar.contentView.rightBarButtonItem = custom button or nil to remove
*/
/**
* Set a maximum height for the input toolbar
*
* self.inputToolbar.maximumHeight = 150.0
*/
/**
* Enable/disable springy bubbles, default is NO.
* You must set this from `viewDidAppear:`
* Note: this feature is mostly stable, but still experimental
*
* self.collectionView.collectionViewLayout.springinessEnabled = true
*/
/**
* Create message bubble images objects.
*
* Be sure to create your bubble images one time and reuse them for good performance.
*
*/
let bubbleFactory = JSQMessagesBubbleImageFactory()
self.outgoingBubbleImageData = bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleLightGrayColor())
self.incomingBubbleImageData = bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor.jsq_messageBubbleGreenColor())
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (self.delegateModal) != nil {
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(closePressed))
}
}
/**
* Get random user except me
*/
func getRandomRecipient() -> User {
let members = self.conversation.members.filter({ $0.id != self.senderId })
let user = members[Int(arc4random_uniform(UInt32(members.count)))]
return user
}
//MARK: Custom menu actions for cells
override func didReceiveMenuWillShowNotification(notification: NSNotification!) {
/**
* Display custom menu actions for cells.
*/
let menu = notification.object as! UIMenuController
menu.menuItems = [UIMenuItem(title: "Custom Action", action: #selector(self.customAction(_:)))]
}
//MARK: Actions
func receiveMessagePressed(sender: UIBarButtonItem) {
/**
* DEMO ONLY
*
* The following is simply to simulate received messages for the demo.
* Do not actually do this.
*/
/**
* Show the typing indicator to be shown
*/
self.showTypingIndicator = !self.showTypingIndicator
/**
* Scroll to actually view the indicator
*/
self.scrollToBottomAnimated(true)
/**
* Get random user that isn't me
*/
let user = self.getRandomRecipient()
/**
* Copy last sent message, this will be the new "received" message
*/
var copyMessage = self.conversation.messages.last?.copy()
if (copyMessage == nil) {
copyMessage = JSQMessage(senderId: user.id, displayName: user.name, text: "First received!")
}
/**
* Allow typing indicator to show
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
var newMessage:JSQMessage?
var newMediaData:JSQMessageMediaData?
var newMediaAttachmentCopy:AnyObject?
if copyMessage!.isMediaMessage() {
/**
* Last message was a media message
*/
let copyMediaData = copyMessage!.media
switch copyMediaData {
case is JSQPhotoMediaItem:
let photoItemCopy = (copyMediaData as! JSQPhotoMediaItem).copy() as! JSQPhotoMediaItem
photoItemCopy.appliesMediaViewMaskAsOutgoing = false
newMediaAttachmentCopy = UIImage(CGImage: photoItemCopy.image.CGImage!)
/**
* Set image to nil to simulate "downloading" the image
* and show the placeholder view
*/
photoItemCopy.image = nil;
newMediaData = photoItemCopy
case is JSQLocationMediaItem:
let locationItemCopy = (copyMediaData as! JSQLocationMediaItem).copy() as! JSQLocationMediaItem
locationItemCopy.appliesMediaViewMaskAsOutgoing = false
newMediaAttachmentCopy = locationItemCopy.location.copy()
/**
* Set location to nil to simulate "downloading" the location data
*/
locationItemCopy.location = nil;
newMediaData = locationItemCopy;
case is JSQVideoMediaItem:
let videoItemCopy = (copyMediaData as! JSQVideoMediaItem).copy() as! JSQVideoMediaItem
videoItemCopy.appliesMediaViewMaskAsOutgoing = false
newMediaAttachmentCopy = videoItemCopy.fileURL.copy()
/**
* Reset video item to simulate "downloading" the video
*/
videoItemCopy.fileURL = nil;
videoItemCopy.isReadyToPlay = false;
newMediaData = videoItemCopy;
case is JSQAudioMediaItem:
let audioItemCopy = (copyMediaData as! JSQAudioMediaItem).copy() as! JSQAudioMediaItem
audioItemCopy.appliesMediaViewMaskAsOutgoing = false
newMediaAttachmentCopy = audioItemCopy.audioData?.copy()
/**
* Reset audio item to simulate "downloading" the audio
*/
audioItemCopy.audioData = nil;
newMediaData = audioItemCopy;
default:
print("error: unrecognized media item")
}
newMessage = JSQMessage(senderId: user.id, displayName: user.name, media: newMediaData)
}
else {
/**
* Last message was a text message
*/
newMessage = JSQMessage(senderId: user.id, displayName: user.name, text: copyMessage!.text)
}
/**
* Upon receiving a message, you should:
*
* 1. Play sound (optional)
* 2. Add new JSQMessageData object to your data source
* 3. Call `finishReceivingMessage`
*/
JSQSystemSoundPlayer.jsq_playMessageReceivedSound()
self.conversation.messages.append(newMessage!)
self.finishReceivingMessageAnimated(true)
if newMessage!.isMediaMessage {
/**
* Simulate "downloading" media
*/
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
/**
* Media is "finished downloading", re-display visible cells
*
* If media cell is not visible, the next time it is dequeued the view controller will display its new attachment data
*
* Reload the specific item, or simply call `reloadData`
*/
switch newMediaData {
case is JSQPhotoMediaItem:
(newMediaData as! JSQPhotoMediaItem).image = newMediaAttachmentCopy as! UIImage
self.collectionView.reloadData()
case is JSQLocationMediaItem:
(newMediaData as! JSQLocationMediaItem).setLocation(newMediaAttachmentCopy as! CLLocation, withCompletionHandler: {
self.collectionView.reloadData()
})
case is JSQVideoMediaItem:
(newMediaData as! JSQVideoMediaItem).fileURL = newMediaAttachmentCopy as! NSURL
(newMediaData as! JSQVideoMediaItem).isReadyToPlay = true
self.collectionView.reloadData()
case is JSQAudioMediaItem:
(newMediaData as! JSQAudioMediaItem).audioData = newMediaAttachmentCopy as? NSData
self.collectionView.reloadData()
default:
print("error: unrecognized media item")
}
}
}
}
}
func closePressed(sender:UIBarButtonItem) {
self.delegateModal?.didDismissJSQDemoViewController(self)
}
// MARK: JSQMessagesViewController method overrides
override func didPressSendButton(button: UIButton?, withMessageText text: String?, senderId: String?, senderDisplayName: String?, date: NSDate?) {
/**
* Sending a message. Your implementation of this method should do *at least* the following:
*
* 1. Play sound (optional)
* 2. Add new id<JSQMessageData> object to your data source
* 3. Call `finishSendingMessage`
*/
JSQSystemSoundPlayer.jsq_playMessageSentSound()
let message = JSQMessage(senderId: senderId, senderDisplayName: senderDisplayName, date: date, text: text)
self.conversation.messages.append(message)
self.finishSendingMessageAnimated(true)
}
override func didPressAccessoryButton(sender: UIButton!) {
self.inputToolbar.contentView.textView.resignFirstResponder()
let sheet = UIAlertController(title: "Media messages", message: nil, preferredStyle: .ActionSheet)
let photoButton = UIAlertAction(title: "Send photo", style: .Default) { (action) in
/**
* Add fake photo into conversation messages
*/
let photoItem = JSQPhotoMediaItem(image: UIImage(named: "goldengate"))
let photoMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: photoItem)
self.conversation.messages.append(photoMessage)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.finishSendingMessageAnimated(true)
}
let locationButton = UIAlertAction(title: "Send location", style: .Default) { (action) in
/**
* Add fake location into conversation messages
*/
let ferryBuildingInSF = CLLocation(latitude: 37.795313, longitude: -122.393757)
let locationItem = JSQLocationMediaItem()
locationItem.setLocation(ferryBuildingInSF) {
self.collectionView.reloadData()
}
let locationMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: locationItem)
self.conversation.messages.append(locationMessage)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.finishSendingMessageAnimated(true)
}
let videoButton = UIAlertAction(title: "Send video", style: .Default) { (action) in
/**
* Add fake video into conversation messages
*/
let videoURL = NSURL(fileURLWithPath: "file://")
let videoItem = JSQVideoMediaItem(fileURL: videoURL, isReadyToPlay: true)
let videoMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: videoItem)
self.conversation.messages.append(videoMessage)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.finishSendingMessageAnimated(true)
}
let audioButton = UIAlertAction(title: "Send audio", style: .Default) { (action) in
/**
* Add fake audio into conversation messages
*/
let sample = NSBundle.mainBundle().pathForResource("jsq_messages_sample", ofType: "m4a")
let audioData = NSData(contentsOfFile: sample!)
let audioItem = JSQAudioMediaItem(data: audioData)
let audioMessage = JSQMessage(senderId: self.senderId, displayName: self.senderDisplayName, media: audioItem)
self.conversation.messages.append(audioMessage)
JSQSystemSoundPlayer.jsq_playMessageSentSound()
self.finishSendingMessageAnimated(true)
}
let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
sheet.addAction(photoButton)
sheet.addAction(locationButton)
sheet.addAction(videoButton)
sheet.addAction(audioButton)
sheet.addAction(cancelButton)
self.presentViewController(sheet, animated: true, completion: nil)
}
// MARK: JSQMessages CollectionView DataSource
override func collectionView(collectionView: JSQMessagesCollectionView?, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData? {
return self.conversation.messages[indexPath.item]
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) {
self.conversation.messages.removeAtIndex(indexPath.item)
}
override func collectionView(collectionView: JSQMessagesCollectionView?, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource? {
/**
* You may return nil here if you do not want bubbles.
* In this case, you should set the background color of your collection view cell's textView.
*
* Otherwise, return your previously created bubble image data objects.
*/
let message = self.conversation.messages[indexPath.item]
if message.senderId == self.senderId {
return self.outgoingBubbleImageData
}
return self.incomingBubbleImageData;
}
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource? {
/**
* Return `nil` here if you do not want avatars.
* If you do return `nil`, be sure to do the following in `viewDidLoad`:
*
* self.collectionView.collectionViewLayout.incomingAvatarViewSize = .zero;
* self.collectionView.collectionViewLayout.outgoingAvatarViewSize = .zero;
*
* It is possible to have only outgoing avatars or only incoming avatars, too.
*/
/**
* Return your previously created avatar image data objects.
*
* Note: these the avatars will be sized according to these values:
*
* self.collectionView.collectionViewLayout.incomingAvatarViewSize
* self.collectionView.collectionViewLayout.outgoingAvatarViewSize
*
* Override the defaults in `viewDidLoad`
*/
let message = self.conversation.messages[indexPath.item]
guard let user = self.conversation.getUser(message.senderId) else{
return nil
}
return user.avatar
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
/**
* This logic should be consistent with what you return from `heightForCellTopLabelAtIndexPath:`
* The other label text delegate methods should follow a similar pattern.
*
* Show a timestamp for every 3rd message
*/
if (indexPath.item % 3) == 0 {
let message = self.conversation.messages[indexPath.item]
return JSQMessagesTimestampFormatter.sharedFormatter().attributedTimestampForDate(message.date)
}
return nil;
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
let message = self.conversation.messages[indexPath.item]
/**
* iOS7-style sender name labels
*/
if message.senderId == self.senderId {
return nil;
}
if (indexPath.item - 1) > 0 {
let previousMessage = self.conversation.messages[indexPath.item - 1]
if previousMessage.senderId == message.senderId {
return nil;
}
}
/**
* Don't specify attributes to use the defaults.
*/
return NSAttributedString(string: message.senderDisplayName)
}
override func collectionView(collectionView: JSQMessagesCollectionView!, attributedTextForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> NSAttributedString! {
return nil
}
// MARK: UICollectionView DataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.conversation.messages.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
/**
* Override point for customizing cells
*/
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
/**
* Configure almost *anything* on the cell
*
* Text colors, label text, label colors, etc.
*
*
* DO NOT set `cell.textView.font` !
* Instead, you need to set `self.collectionView.collectionViewLayout.messageBubbleFont` to the font you want in `viewDidLoad`
*
*
* DO NOT manipulate cell layout information!
* Instead, override the properties you want on `self.collectionView.collectionViewLayout` from `viewDidLoad`
*/
let msg = self.conversation.messages[indexPath.item]
if !msg.isMediaMessage {
if msg.senderId == self.senderId {
cell.textView.textColor = UIColor.blackColor()
}
else {
cell.textView.textColor = UIColor.whiteColor()
}
let attributes : [String:AnyObject] = [NSForegroundColorAttributeName:cell.textView.textColor!, NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleSingle.rawValue]
cell.textView.linkTextAttributes = attributes
}
return cell;
}
// MARK: UICollectionView Delegate
// MARK: Custom menu items
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
if action == #selector(customAction) {
return true
}
return super.collectionView(collectionView, canPerformAction: action, forItemAtIndexPath: indexPath, withSender: sender)
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
if action == Selector() {
self.customAction(sender!)
return
}
super.collectionView(collectionView, performAction: action, forItemAtIndexPath: indexPath, withSender: sender)
}
func customAction(sender: AnyObject) {
print("Custom action received! Sender: \(sender)")
}
// MARK: JSQMessages collection view flow layout delegate
// MARK: Adjusting cell label heights
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
/**
* Each label in a cell has a `height` delegate method that corresponds to its text dataSource method
*/
/**
* This logic should be consistent with what you return from `attributedTextForCellTopLabelAtIndexPath:`
* The other label height delegate methods should follow similarly
*
* Show a timestamp for every 3rd message
*/
if (indexPath.item % 3) == 0 {
return kJSQMessagesCollectionViewCellLabelHeightDefault
}
return 0.0
}
override func collectionView(collectionView: JSQMessagesCollectionView?, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout?, heightForMessageBubbleTopLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
/**
* iOS7-style sender name labels
*/
let currentMessage = self.conversation.messages[indexPath.item]
if currentMessage.senderId == self.senderId {
return 0.0
}
if (indexPath.item - 1) > 0 {
let previousMessage = self.conversation.messages[indexPath.item - 1]
if previousMessage.senderId == currentMessage.senderId {
return 0.0
}
}
return kJSQMessagesCollectionViewCellLabelHeightDefault;
}
override func collectionView(collectionView: JSQMessagesCollectionView!, layout collectionViewLayout: JSQMessagesCollectionViewFlowLayout!, heightForCellBottomLabelAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
return 0.0
}
// MARK: Responding to collection view tap events
override func collectionView(collectionView: JSQMessagesCollectionView!, header headerView: JSQMessagesLoadEarlierHeaderView!, didTapLoadEarlierMessagesButton sender: UIButton!) {
print("Load earlier messages!")
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, atIndexPath indexPath: NSIndexPath!) {
print("Tapped avatar!")
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
print("Tapped message bubble!")
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didTapCellAtIndexPath indexPath: NSIndexPath!, touchLocation: CGPoint) {
print("Tapped cell at \(touchLocation)")
}
// MARK: JSQMessagesComposerTextViewPasteDelegate methods
func composerTextView(textView: JSQMessagesComposerTextView!, shouldPasteWithSender sender: AnyObject!) -> Bool {
if (UIPasteboard.generalPasteboard().image != nil) {
// If there's an image in the pasteboard, construct a media item with that image and `send` it.
let item = JSQPhotoMediaItem(image: UIPasteboard.generalPasteboard().image)
let message = JSQMessage(senderId: self.senderId, senderDisplayName: self.senderDisplayName, date: NSDate(), media: item)
self.conversation.messages.append(message)
self.finishSendingMessage()
return false
}
return true
}
} | mit | a06bb36b463c5b0a631504ce83b51383 | 40.189358 | 223 | 0.609598 | 6.132106 | false | false | false | false |
CNKCQ/oschina | Pods/SnapKit/Source/ConstraintAttributes.swift | 1 | 7421 | //
// SnapKit
//
// Copyright (c) 2011-Present SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
internal struct ConstraintAttributes: OptionSet {
internal init(rawValue: UInt) {
self.rawValue = rawValue
}
internal init(_ rawValue: UInt) {
self.init(rawValue: rawValue)
}
internal init(nilLiteral _: ()) {
rawValue = 0
}
private(set) internal var rawValue: UInt
internal static var allZeros: ConstraintAttributes { return self.init(0) }
internal static func convertFromNilLiteral() -> ConstraintAttributes { return self.init(0) }
internal var boolValue: Bool { return rawValue != 0 }
internal func toRaw() -> UInt { return rawValue }
internal static func fromRaw(_ raw: UInt) -> ConstraintAttributes? { return self.init(raw) }
internal static func fromMask(_ raw: UInt) -> ConstraintAttributes { return self.init(raw) }
// normal
internal static var none: ConstraintAttributes { return self.init(0) }
internal static var left: ConstraintAttributes { return self.init(1) }
internal static var top: ConstraintAttributes { return self.init(2) }
internal static var right: ConstraintAttributes { return self.init(4) }
internal static var bottom: ConstraintAttributes { return self.init(8) }
internal static var leading: ConstraintAttributes { return self.init(16) }
internal static var trailing: ConstraintAttributes { return self.init(32) }
internal static var width: ConstraintAttributes { return self.init(64) }
internal static var height: ConstraintAttributes { return self.init(128) }
internal static var centerX: ConstraintAttributes { return self.init(256) }
internal static var centerY: ConstraintAttributes { return self.init(512) }
internal static var lastBaseline: ConstraintAttributes { return self.init(1024) }
@available(iOS 8.0, OSX 10.11, *)
internal static var firstBaseline: ConstraintAttributes { return self.init(2048) }
@available(iOS 8.0, *)
internal static var leftMargin: ConstraintAttributes { return self.init(4096) }
@available(iOS 8.0, *)
internal static var rightMargin: ConstraintAttributes { return self.init(8192) }
@available(iOS 8.0, *)
internal static var topMargin: ConstraintAttributes { return self.init(16384) }
@available(iOS 8.0, *)
internal static var bottomMargin: ConstraintAttributes { return self.init(32768) }
@available(iOS 8.0, *)
internal static var leadingMargin: ConstraintAttributes { return self.init(65536) }
@available(iOS 8.0, *)
internal static var trailingMargin: ConstraintAttributes { return self.init(131_072) }
@available(iOS 8.0, *)
internal static var centerXWithinMargins: ConstraintAttributes { return self.init(262_144) }
@available(iOS 8.0, *)
internal static var centerYWithinMargins: ConstraintAttributes { return self.init(524_288) }
// aggregates
internal static var edges: ConstraintAttributes { return self.init(15) }
internal static var size: ConstraintAttributes { return self.init(192) }
internal static var center: ConstraintAttributes { return self.init(768) }
@available(iOS 8.0, *)
internal static var margins: ConstraintAttributes { return self.init(61440) }
@available(iOS 8.0, *)
internal static var centerWithinMargins: ConstraintAttributes { return self.init(786_432) }
internal var layoutAttributes: [NSLayoutAttribute] {
var attrs = [NSLayoutAttribute]()
if contains(ConstraintAttributes.left) {
attrs.append(.left)
}
if contains(ConstraintAttributes.top) {
attrs.append(.top)
}
if contains(ConstraintAttributes.right) {
attrs.append(.right)
}
if contains(ConstraintAttributes.bottom) {
attrs.append(.bottom)
}
if contains(ConstraintAttributes.leading) {
attrs.append(.leading)
}
if contains(ConstraintAttributes.trailing) {
attrs.append(.trailing)
}
if contains(ConstraintAttributes.width) {
attrs.append(.width)
}
if contains(ConstraintAttributes.height) {
attrs.append(.height)
}
if contains(ConstraintAttributes.centerX) {
attrs.append(.centerX)
}
if contains(ConstraintAttributes.centerY) {
attrs.append(.centerY)
}
if contains(ConstraintAttributes.lastBaseline) {
attrs.append(.lastBaseline)
}
#if os(iOS) || os(tvOS)
if self.contains(ConstraintAttributes.firstBaseline) {
attrs.append(.firstBaseline)
}
if self.contains(ConstraintAttributes.leftMargin) {
attrs.append(.leftMargin)
}
if self.contains(ConstraintAttributes.rightMargin) {
attrs.append(.rightMargin)
}
if self.contains(ConstraintAttributes.topMargin) {
attrs.append(.topMargin)
}
if self.contains(ConstraintAttributes.bottomMargin) {
attrs.append(.bottomMargin)
}
if self.contains(ConstraintAttributes.leadingMargin) {
attrs.append(.leadingMargin)
}
if self.contains(ConstraintAttributes.trailingMargin) {
attrs.append(.trailingMargin)
}
if self.contains(ConstraintAttributes.centerXWithinMargins) {
attrs.append(.centerXWithinMargins)
}
if self.contains(ConstraintAttributes.centerYWithinMargins) {
attrs.append(.centerYWithinMargins)
}
#endif
return attrs
}
}
internal func + (left: ConstraintAttributes, right: ConstraintAttributes) -> ConstraintAttributes {
return left.union(right)
}
internal func +=(left: inout ConstraintAttributes, right: ConstraintAttributes) {
left.formUnion(right)
}
internal func -=(left: inout ConstraintAttributes, right: ConstraintAttributes) {
left.subtract(right)
}
internal func ==(left: ConstraintAttributes, right: ConstraintAttributes) -> Bool {
return left.rawValue == right.rawValue
}
| mit | 528efb7f0358502fcc23035486ab1ae5 | 37.853403 | 99 | 0.674707 | 4.840835 | false | false | false | false |
Danappelxx/MuttonChop | Tests/MuttonChopTests/TemplateCollectionTests.swift | 1 | 2041 | //
// TemplateCollectionTests.swift
// MuttonChop
//
// Created by Dan Appel on 11/1/16.
//
//
import XCTest
import Foundation
@testable import MuttonChop
var currentDirectory: String {
return (NSString(string: #file)).deletingLastPathComponent + "/"
}
func fixture(name: String) throws -> Template? {
let path = currentDirectory + "Fixtures/" + name
guard let handle = FileHandle(forReadingAtPath: path),
let fixture = String(data: handle.readDataToEndOfFile(), encoding: .utf8) else {
return nil
}
return try Template(fixture)
}
class TemplateCollectionTests: XCTestCase {
static var allTests: [(String, (TemplateCollectionTests) -> () throws -> Void)] {
return [
("testBasicCollection", testBasicCollection),
("testFileCollection", testFileCollection)
]
}
func testBasicCollection() throws {
let collection = try TemplateCollection(templates: [
"conversation": fixture(name: "conversation.mustache")!,
"greeting": fixture(name: "greeting.mustache")!
])
try testGetting(for: collection)
try testRendering(for: collection)
}
func testFileCollection() throws {
let collection = try TemplateCollection(directory: currentDirectory + "Fixtures")
try testGetting(for: collection)
try testRendering(for: collection)
}
func testGetting(for collection: TemplateCollection) throws {
try XCTAssertEqual(collection.get(template: "conversation"), fixture(name: "conversation.mustache")!)
try XCTAssertEqual(collection.get(template: "greeting"), fixture(name: "greeting.mustache"))
}
func testRendering(for collection: TemplateCollection) throws {
try XCTAssertEqual("Hey there, Dan!", collection.render(template: "greeting", with: ["your-name": "Dan"]))
try XCTAssertEqual("Hey there, Dan! My name is Billy.", collection.render(template: "conversation", with: ["your-name": "Dan", "my-name": "Billy"]))
}
}
| mit | 43b84a7b94eef3dd85341b9a0ecb95e3 | 33.016667 | 156 | 0.66879 | 4.607223 | false | true | false | false |
paketehq/ios | Pakete/UILabelExtensions.swift | 1 | 1527 | //
// UILabelExtensions.swift
// Pakete
//
// Created by Royce Albert Dy on 11/04/2016.
// Copyright © 2016 Pakete. All rights reserved.
//
import Foundation
extension UILabel {
var adjustFontToRealIPhoneSize: Bool {
set {
if newValue {
let currentFont = self.font
var sizeScale: CGFloat = 1.0
if DeviceType.iPhone6 {
sizeScale = 1.1
} else if DeviceType.iPhone6Plus {
sizeScale = 1.2
}
self.font = currentFont?.withSize((currentFont?.pointSize)! * sizeScale)
}
}
get {
return false
}
}
}
// TO DO: Transfer somewhere
struct ScreenSize {
static let ScreenWidth = UIScreen.main.bounds.size.width
static let ScreenHeight = UIScreen.main.bounds.size.height
static let ScreenMaxLength = max(ScreenSize.ScreenWidth, ScreenSize.ScreenHeight)
static let ScreenMinLength = min(ScreenSize.ScreenHeight, ScreenSize.ScreenHeight)
}
struct DeviceType {
static let iPhone4 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength < 568.0
static let iPhone5 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 568.0
static let iPhone6 = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 667.0
static let iPhone6Plus = UIDevice.current.userInterfaceIdiom == .phone && ScreenSize.ScreenMaxLength == 736.0
}
| mit | 84a2e9b23269180243a24f6997a21670 | 31.468085 | 113 | 0.642857 | 4.652439 | false | false | false | false |
SwiftKit/Reactant | Source/Core/Component/ComponentBase.swift | 2 | 1309 | //
// ComponentBase.swift
// Reactant
//
// Created by Filip Dolnik on 08.11.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import RxSwift
open class ComponentBase<STATE, ACTION>: ComponentWithDelegate {
public typealias StateType = STATE
public typealias ActionType = ACTION
public let lifetimeDisposeBag = DisposeBag()
public let componentDelegate = ComponentDelegate<STATE, ACTION, ComponentBase<STATE, ACTION>>()
open var action: Observable<ACTION> {
return componentDelegate.action
}
/**
* Collection of Component's `Observable`s which are merged into `Component.action`.
* - Note: When listening to Component's actions, using `action` is preferred to `actions`.
*/
open var actions: [Observable<ACTION>] {
return []
}
open func needsUpdate() -> Bool {
return true
}
public init(canUpdate: Bool = true) {
componentDelegate.ownerComponent = self
resetActions()
afterInit()
componentDelegate.canUpdate = canUpdate
}
open func afterInit() {
}
open func update() {
}
public func observeState(_ when: ObservableStateEvent) -> Observable<STATE> {
return componentDelegate.observeState(when)
}
}
| mit | 9aeb58cd95dba3f5627b93ca8e9cc5d8 | 22.781818 | 99 | 0.64526 | 4.808824 | false | false | false | false |
HolidayAdvisorIOS/HolidayAdvisor | HolidayAdvisor/HolidayAdvisor/PlaceDetailsViewController.swift | 1 | 1529 | //
// PlaceDetailsViewController.swift
// HolidayAdvisor
//
// Created by Iliyan Gogov on 4/3/17.
// Copyright © 2017 Iliyan Gogov. All rights reserved.
//
import UIKit
class PlaceDetailsViewController: UIViewController {
@IBOutlet weak var placeImage: UIImageView!
@IBOutlet weak var placeNameLabel: UILabel!
@IBOutlet weak var placeInfoLabel: UILabel!
@IBOutlet weak var placeOwnerLabel: UILabel!
var name : String? = ""
var imageUrl: String? = ""
var info: String? = ""
var owner: String? = ""
var rating: Int? = 0
override func viewDidLoad() {
super.viewDidLoad()
self.placeNameLabel.text = self.name
self.placeOwnerLabel.text = self.owner
self.placeInfoLabel.text = self.info
if let url = NSURL(string: self.imageUrl!) {
if let data = NSData(contentsOf: url as URL) {
self.placeImage?.image = UIImage(data: data as Data)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | b2a03c11efd6406a069dd261207308f7 | 27.296296 | 106 | 0.63678 | 4.547619 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.