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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mozilla-mobile/firefox-ios | Client/Frontend/Widgets/PhotonActionSheet/PhotonActionSheetContainerCell.swift | 1 | 3037 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/
import Foundation
protocol PhotonActionSheetContainerCellDelegate: AnyObject {
func didClick(item: SingleActionViewModel?)
func layoutChanged(item: SingleActionViewModel)
}
// A PhotonActionSheet cell
class PhotonActionSheetContainerCell: UITableViewCell, ReusableCell {
weak var delegate: PhotonActionSheetContainerCellDelegate?
private lazy var containerStackView: UIStackView = .build { stackView in
stackView.alignment = .fill
stackView.distribution = .fill
stackView.axis = .horizontal
}
// MARK: - init
override func prepareForReuse() {
super.prepareForReuse()
containerStackView.removeAllArrangedViews()
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
backgroundColor = .clear
contentView.addSubview(containerStackView)
setupConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Table view
func configure(actions: PhotonRowActions, viewModel: PhotonActionSheetViewModel) {
for item in actions.items {
item.tintColor = viewModel.tintColor
item.multipleItemsSetup.isMultiItems = actions.items.count > 1
configure(with: item)
}
}
// MARK: - Setup
private func setupConstraints() {
NSLayoutConstraint.activate([
containerStackView.topAnchor.constraint(equalTo: contentView.topAnchor),
containerStackView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
containerStackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
containerStackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
])
}
func configure(with item: SingleActionViewModel) {
let childView = PhotonActionSheetView()
childView.configure(with: item)
childView.addVerticalBorder(ifShouldBeShown: !containerStackView.arrangedSubviews.isEmpty)
childView.delegate = self
containerStackView.addArrangedSubview(childView)
containerStackView.axis = item.multipleItemsSetup.axis
}
func hideBottomBorder(isHidden: Bool) {
containerStackView.arrangedSubviews
.compactMap { $0 as? PhotonActionSheetView }
.forEach { $0.bottomBorder.isHidden = isHidden }
}
}
// MARK: - PhotonActionSheetViewDelegate
extension PhotonActionSheetContainerCell: PhotonActionSheetViewDelegate {
func didClick(item: SingleActionViewModel?) {
delegate?.didClick(item: item)
}
func layoutChanged(item: SingleActionViewModel) {
delegate?.layoutChanged(item: item)
}
}
| mpl-2.0 | 44dbcb03c09330a946c6d6a3e5a08e26 | 33.511364 | 98 | 0.706289 | 5.423214 | false | false | false | false |
iOSTestApps/firefox-ios | Storage/SyncQueue.swift | 11 | 1888 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
public struct SyncCommand: Equatable {
public let value: String
public var commandID: Int?
public var clientGUID: GUID?
let version: String?
public init(value: String) {
self.value = value
self.version = nil
self.commandID = nil
self.clientGUID = nil
}
public init(id: Int, value: String) {
self.value = value
self.version = nil
self.commandID = id
self.clientGUID = nil
}
public init(id: Int?, value: String, clientGUID: GUID?) {
self.value = value
self.version = nil
self.clientGUID = clientGUID
self.commandID = id
}
public static func fromShareItem(shareItem: ShareItem, withAction action: String) -> SyncCommand {
let jsonObj: [String: AnyObject] = [
"command": action,
"args": [shareItem.url, "", shareItem.title ?? ""]
]
return SyncCommand(value: JSON.stringify(jsonObj, pretty: false))
}
public func withClientGUID(clientGUID: String?) -> SyncCommand {
return SyncCommand(id: self.commandID, value: self.value, clientGUID: clientGUID)
}
}
public func ==(lhs: SyncCommand, rhs: SyncCommand) -> Bool {
return lhs.value == rhs.value
}
public protocol SyncCommands {
func deleteCommands() -> Success
func deleteCommands(clientGUID: GUID) -> Success
func getCommands() -> Deferred<Result<[GUID: [SyncCommand]]>>
func insertCommand(command: SyncCommand, forClients clients: [RemoteClient]) -> Deferred<Result<Int>>
func insertCommands(commands: [SyncCommand], forClients clients: [RemoteClient]) -> Deferred<Result<Int>>
} | mpl-2.0 | 112fa5ccf0fa90d7d28307a461a2a316 | 29.967213 | 109 | 0.648305 | 4.360277 | false | false | false | false |
mozilla-mobile/firefox-ios | Shared/Functions.swift | 2 | 6574 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import SwiftyJSON
// Pipelining.
precedencegroup PipelinePrecedence {
associativity: left
}
infix operator |> : PipelinePrecedence
public func |> <T, U>(x: T, f: (T) -> U) -> U {
return f(x)
}
// Basic currying.
public func curry<A, B>(_ f: @escaping (A) -> B) -> (A) -> B {
return { a in
return f(a)
}
}
public func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in
return { b in
return f(a, b)
}
}
}
public func curry<A, B, C, D>(_ f: @escaping (A, B, C) -> D) -> (A) -> (B) -> (C) -> D {
return { a in
return { b in
return { c in
return f(a, b, c)
}
}
}
}
public func curry<A, B, C, D, E>(_ f: @escaping (A, B, C, D) -> E) -> (A, B, C) -> (D) -> E {
return { (a, b, c) in
return { d in
return f(a, b, c, d)
}
}
}
// Function composition.
infix operator •
public func •<T, U, V>(f: @escaping (T) -> U, g: @escaping (U) -> V) -> (T) -> V {
return { t in
return g(f(t))
}
}
public func •<T, V>(f: @escaping (T) -> Void, g: @escaping () -> V) -> (T) -> V {
return { t in
f(t)
return g()
}
}
public func •<V>(f: @escaping () -> Void, g: @escaping () -> V) -> () -> V {
return {
f()
return g()
}
}
// Why not simply provide an override for ==? Well, that's scary, and can accidentally recurse.
// This is enough to catch arrays, which Swift will delegate to element-==.
public func optArrayEqual<T: Equatable>(_ lhs: [T]?, rhs: [T]?) -> Bool {
switch (lhs, rhs) {
case (.none, .none):
return true
case (.none, _):
return false
case (_, .none):
return false
default:
// This delegates to Swift's own array '==', which calls T's == on each element.
return lhs! == rhs!
}
}
/**
* Given an array, return an array of slices of size `by` (possibly excepting the last slice).
*
* If `by` is longer than the input, returns a single chunk.
* If `by` is less than 1, acts as if `by` is 1.
* If the length of the array isn't a multiple of `by`, the final slice will
* be smaller than `by`, but never empty.
*
* If the input array is empty, returns an empty array.
*/
public func chunk<T>(_ arr: [T], by: Int) -> [ArraySlice<T>] {
var result = [ArraySlice<T>]()
var chunk = -1
let size = max(1, by)
for (index, elem) in arr.enumerated() {
if index % size == 0 {
result.append(ArraySlice<T>())
chunk += 1
}
result[chunk].append(elem)
}
return result
}
public func chunkCollection<E, X, T: Collection>(_ items: T, by: Int, f: ([E]) -> [X]) -> [X] where T.Iterator.Element == E {
assert(by >= 0)
let max = by > 0 ? by : 1
var i = 0
var acc: [E] = []
var results: [X] = []
var iter = items.makeIterator()
while let item = iter.next() {
if i >= max {
results.append(contentsOf: f(acc))
acc = []
i = 0
}
acc.append(item)
i += 1
}
if !acc.isEmpty {
results.append(contentsOf: f(acc))
}
return results
}
public extension Sequence {
// [T] -> (T -> K) -> [K: [T]]
// As opposed to `groupWith` (to follow Haskell's naming), which would be
// [T] -> (T -> K) -> [[T]]
func groupBy<Key, Value>(_ selector: (Self.Iterator.Element) -> Key, transformer: (Self.Iterator.Element) -> Value) -> [Key: [Value]] {
var acc: [Key: [Value]] = [:]
for x in self {
let k = selector(x)
var a = acc[k] ?? []
a.append(transformer(x))
acc[k] = a
}
return acc
}
func zip<S: Sequence>(_ elems: S) -> [(Self.Iterator.Element, S.Iterator.Element)] {
var rights = elems.makeIterator()
return self.compactMap { lhs in
guard let rhs = rights.next() else { return nil }
return (lhs, rhs)
}
}
}
public func optDictionaryEqual<K, V: Equatable>(_ lhs: [K: V]?, rhs: [K: V]?) -> Bool {
switch (lhs, rhs) {
case (.none, .none):
return true
case (.none, _):
return false
case (_, .none):
return false
default:
return lhs! == rhs!
}
}
/**
* Return members of `a` that aren't nil, changing the type of the sequence accordingly.
*/
public func optFilter<T>(_ a: [T?]) -> [T] {
return a.compactMap { $0 }
}
/**
* Return a new map with only key-value pairs that have a non-nil value.
*/
public func optFilter<K, V>(_ source: [K: V?]) -> [K: V] {
var m = [K: V]()
for (k, v) in source {
if let v = v {
m[k] = v
}
}
return m
}
/**
* Map a function over the values of a map.
*/
public func mapValues<K, T, U>(_ source: [K: T], f: (T) -> U) -> [K: U] {
var m = [K: U]()
for (k, v) in source {
m[k] = f(v)
}
return m
}
public func findOneValue<K, V>(_ map: [K: V], f: (V) -> Bool) -> V? {
for v in map.values {
if f(v) {
return v
}
}
return nil
}
/**
* Take a JSON array, returning the String elements as an array.
* It's usually convenient for this to accept an optional.
*/
public func jsonsToStrings(_ arr: [JSON]?) -> [String]? {
return arr?.compactMap { $0.stringValue }
}
// Encapsulate a callback in a way that we can use it with NSTimer.
private class Callback {
private let handler: () -> Void
init(handler: @escaping () -> Void) {
self.handler = handler
}
@objc
func go() {
handler()
}
}
/**
* Taken from http://stackoverflow.com/questions/27116684/how-can-i-debounce-a-method-call
* Allows creating a block that will fire after a delay. Resets the timer if called again before the delay expires.
**/
public func debounce(_ delay: TimeInterval, action: @escaping () -> Void) -> () -> Void {
let callback = Callback(handler: action)
var timer: Timer?
return {
// If calling again, invalidate the last timer.
if let timer = timer {
timer.invalidate()
}
timer = Timer(timeInterval: delay, target: callback, selector: #selector(Callback.go), userInfo: nil, repeats: false)
RunLoop.current.add(timer!, forMode: RunLoop.Mode.default)
}
}
| mpl-2.0 | d5be1bcce58062c282a35c4ce6fd4e75 | 25.159363 | 139 | 0.532744 | 3.35171 | false | false | false | false |
Adorkable/StoryboardKit | StoryboardKit/StoryboardInstanceInfo.swift | 1 | 2121 | //
// StoryboardInstanceInfo.swift
// StoryboardKit
//
// Created by Ian on 5/3/15.
// Copyright (c) 2015 Adorkable. All rights reserved.
//
import Foundation
import SWXMLHash
/**
* Represents a Storyboard file instance
*/
public class StoryboardInstanceInfo: NSObject {
/// Use Autolayout
public let useAutolayout : Bool
/// Use Trait Collections
public let useTraitCollections : Bool
/// Initial View Controller Instance
public let initialViewController : ViewControllerInstanceInfo?
/// All scenes in the storyboard
public private(set) var scenes = Array<SceneInfo>()
/**
Default init
- parameter useAutolayout: Use Autolayout
- parameter useTraitCollections: Use Trait Collections
- parameter initialViewController: Initial View Controller Instance
- returns: A new instance.
*/
public required init(useAutolayout : Bool, useTraitCollections : Bool, initialViewController : ViewControllerInstanceInfo?) {
self.useAutolayout = useAutolayout
self.useTraitCollections = useTraitCollections
self.initialViewController = initialViewController
super.init()
}
/**
* Represents a Scene in the storyboard
*/
public class SceneInfo: NSObject {
/// Scene Id
let sceneId : String
// TODO: not optional, use parsing placeholder
/// View Controller
public var controller : ViewControllerInstanceInfo?
/// Placeholder object
public var placeHolder : AnyObject?
/**
Default init
- parameter sceneId: Scene Id
- returns: A new instance.
*/
init(sceneId : String) {
self.sceneId = sceneId
super.init()
}
}
/**
Add a Scene to the storyboard
- parameter scene: Scene to add
*/
func add(scene scene : SceneInfo) {
// TODO: validate that it isn't a dup
self.scenes.append(scene)
}
}
| mit | 50e606ecba95acb90384b469008bc409 | 23.662791 | 129 | 0.605846 | 5.424552 | false | false | false | false |
RnDity/NavigationFlowCoordinator | NavigationFlowCoordinatorExample/NavigationFlowCoordinatorExample/MovieDetailsViewController.swift | 1 | 2666 | //
// MovieDetailsViewController.swift
// NavigationFlowCoordinatorExample
//
// Created and developed by RnDity sp. z o.o. in 2018.
// Copyright © 2018 RnDity sp. z o.o. All rights reserved.
//
import Foundation
import UIKit
protocol MovieDetailsFlowDelegate: class {
func editMovie()
func onMovieUpdated()
}
class MovieDetailsViewController: UIViewController {
weak var flowDelegate: MovieDetailsFlowDelegate?
var connection: Connection!
var movieId: String!
var movie: Movie?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var genreLabel: UILabel!
@IBOutlet weak var isFavouriteSwitch: UISwitch!
public convenience init(connection: Connection, movieId: String){
self.init(nibName: "MovieDetailsViewController", bundle: Bundle.main)
self.connection = connection
self.movieId = movieId
}
override func viewDidLoad() {
edgesForExtendedLayout = []
navigationItem.title = "Movie details"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(editMovie))
isFavouriteSwitch.addTarget(self, action: #selector(onGenreSwitchToggled), for: .valueChanged)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchDataIfNeeded()
}
func fetchDataIfNeeded() {
if movie == nil {
fetchData()
}
}
func fetchData() {
showLoader()
connection.getMovie(withId: movieId) { [weak self] movie, error in
self?.hideLoader()
if error == nil, let movie = movie {
self?.movie = movie
self?.updateView()
}
}
}
func updateView() {
if let movie = movie {
titleLabel.text = movie.title
genreLabel.text = movie.genre.rawValue
isFavouriteSwitch.isOn = movie.isFavourite
}
}
@objc func editMovie() {
flowDelegate?.editMovie()
}
@objc func onGenreSwitchToggled() {
if var movie = movie {
movie.isFavourite = isFavouriteSwitch.isOn
updateMovie(movie: movie)
}
}
func updateMovie(movie: Movie) {
connection.updateMovie(movie: movie) { [weak self] movie, error in
if error == nil, let movie = movie {
self?.movie = movie
self?.flowDelegate?.onMovieUpdated()
}
}
}
func invalidateMovieData() {
movie = nil
}
}
| mit | 59e63fe22b04f355c924c4dcb42b2514 | 25.386139 | 131 | 0.596623 | 4.916974 | false | false | false | false |
jgonfer/JGFLabRoom | JGFLabRoom/Controller/Information Access/OAuth/SGitHubViewController.swift | 1 | 6540 | //
// SGitHubViewController.swift
// JGFLabRoom
//
// Created by Josep González on 25/1/16.
// Copyright © 2016 Josep Gonzalez Fernandez. All rights reserved.
//
/*
* MARK: IMPORTANT: For more information about GitHub API
* go to https://developer.github.com/v3/
*
* and for OAuth info
* go to https://developer.github.com/v3/oauth/
*
*/
import UIKit
class SGitHubViewController: UITableViewController {
var dots = 0
var results: [Repo]?
var indexSelected: NSIndexPath?
var timer: NSTimer?
var timerCheck: NSTimer?
var isOAuthLoginInProcess = false
deinit {
Utils.removeObserverForNotifications(self)
cancelTimers()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !isOAuthLoginInProcess {
loadInitialData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
setupController()
}
private func setupController() {
Utils.registerStandardXibForTableView(tableView, name: "cell")
Utils.cleanBackButtonTitle(navigationController)
Utils.registerNotificationWillEnterForeground(self, selector: "delayCechForAccessToken")
startTimerDownloading()
guard let indexSelected = indexSelected else {
return
}
title = SNetworks.getOptionsArray(.GitHub)[indexSelected.row]
}
func delayCechForAccessToken() {
timerCheck = NSTimer.scheduledTimerWithTimeInterval(2, target: self, selector: "checkForAccessToken", userInfo: nil, repeats: false)
}
func checkForAccessToken() {
guard GitHubAPIManager.sharedInstance.hasOAuthToken() else {
self.navigationController?.popViewControllerAnimated(true)
return
}
}
func loadInitialData() {
// We need to check if we already have an OAuth token, or we need to grab one.
if !GitHubAPIManager.sharedInstance.hasOAuthToken() {
GitHubAPIManager.sharedInstance.OAuthTokenCompletionHandler = {
(error) -> Void in
self.isOAuthLoginInProcess = false
if let _ = error {
print(error)
// TODO: handle error
// Something went wrong, try again
} else {
// If we already have one, we'll get all repositories
self.requestAPICall()
}
}
isOAuthLoginInProcess = true
GitHubAPIManager.sharedInstance.startOAuth2Login()
} else {
requestAPICall()
}
}
private func requestAPICall() {
switch self.indexSelected!.row {
case 0:
ConnectionHelper.sharedInstance.startConnection(kUrlGameApps, method: .GET, params: nil, delegate: self)
case 1:
ConnectionHelper.sharedInstance.startConnection(kUrlGitHubRepos, method: .GET, params: nil, delegate: self)
default:
break
}
}
private func startTimerDownloading() {
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "checkDownloadingState", userInfo: nil, repeats: true)
}
private func cancelTimers() {
timer?.invalidate()
timerCheck?.invalidate()
}
func checkDownloadingState() {
dots++
if dots > 3 {
dots = 0
}
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.None)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
guard let indexSelected = indexSelected else {
return
}
switch segue.identifier! {
case kSegueIdListApps:
if let vcToShow = segue.destinationViewController as? ListAppsViewController {
vcToShow.indexSelected = indexSelected
}
default:
break
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 55
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let results = results else {
return 1
}
return results.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let reuseIdentifier = "cell"
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier)
if (cell != nil) {
cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: reuseIdentifier)
}
var title: String? {
guard let results = results else {
var dotsStr = ""
var counter = 0
while counter < dots {
dotsStr += "."
counter++
}
return "Downloading data" + dotsStr
}
return results[indexPath.row].name
}
cell?.textLabel?.text = title
cell?.accessoryType = .None
guard let results = results else {
return cell!
}
return cell!
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.indexSelected = indexPath
//performSegueWithIdentifier(kSegueIdListApps, sender: tableView)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension SGitHubViewController: ConnectionHelperDelegate {
func connectionReposFinished(repos: [Repo]?, error: NSError?) {
results = repos
tableView.reloadData()
if let error = error {
switch error.code {
case kErrorCodeGitHubBadCredentials:
loadInitialData()
print(error.description)
default:
break
}
}
}
} | mit | e91483d55ad8e88d009db0e45c678775 | 30.138095 | 140 | 0.595442 | 5.503367 | false | false | false | false |
toggl/superday | teferi/UI/Modules/Timeline/EditTimes/EditTimesPresenter.swift | 1 | 982 | import Foundation
import RxSwift
class EditTimesPresenter
{
private weak var viewController : EditTimesViewController!
private let viewModelLocator : ViewModelLocator
private init(viewModelLocator: ViewModelLocator)
{
self.viewModelLocator = viewModelLocator
}
static func create(with viewModelLocator: ViewModelLocator, time: Date, editingStartTime: Bool) -> EditTimesViewController
{
let presenter = EditTimesPresenter(viewModelLocator: viewModelLocator)
let viewModel = viewModelLocator.getEditTimesViewModel(forTimeSlotAt: time, editingStartTime: editingStartTime)
let viewController = StoryboardScene.Main.editTimes.instantiate()
viewController.inject(presenter: presenter, viewModel: viewModel)
presenter.viewController = viewController
return viewController
}
func dismiss()
{
viewController.dismiss(animated: true, completion: nil)
}
}
| bsd-3-clause | e8733e8299f8af3934fb111b578cd0ef | 31.733333 | 126 | 0.726069 | 5.845238 | false | false | false | false |
mokriya/tvos-sample-mokriyans | TVSample/App/TVSample/AppDelegate.swift | 1 | 1374 | //
// AppDelegate.swift
// TVSample
//
// Created by Diogo Brito on 01/10/15.
// Copyright © 2015 Mokriya. All rights reserved.
//
import UIKit
import TVMLKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate {
var window: UIWindow?
var appController: TVApplicationController?
static let BaseURL = "http://localhost:1906/"
static let BootURL = "\(BaseURL)js/application.js"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// Create Controller Context
let appControllerContext = TVApplicationControllerContext()
//Create the NSURL for the landing javascript path
guard let javaScriptURL = NSURL(string: AppDelegate.BootURL) else {
fatalError("unable to create NSURL")
}
//Set the javascript path and base url
appControllerContext.javaScriptApplicationURL = javaScriptURL
appControllerContext.launchOptions["BASEURL"] = AppDelegate.BaseURL
//Create the controller
appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)
return true
}
}
| apache-2.0 | b879edaa639f89dd4353d1c2c858ebae | 30.204545 | 127 | 0.685361 | 5.581301 | false | false | false | false |
JadenGeller/Axiomatic | Sources/Axiomatic/Functor.swift | 1 | 891 | //
// Functor.swift
// Axiomatic
//
// Created by Jaden Geller on 1/18/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
extension Term {
/// The name-arity signature of `self`.
public var functor: Functor<Atom> {
return Functor(name: name, arity: arity)
}
}
/// The name-arity signature of a `Term`. Defines a class of `Term`s that can potentially
/// be unified with each other.
public struct Functor<Atom: Hashable> {
/// The name.
public let name: Atom
/// The number of arguments.
public let arity: Int
}
extension Functor: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(name)
hasher.combine(arity)
}
}
extension Functor: Equatable {
public static func ==(lhs: Functor<Atom>, rhs: Functor<Atom>) -> Bool {
return lhs.name == rhs.name && lhs.arity == rhs.arity
}
}
| mit | 7e515605db2631dbd8ed1f6df3e48c7b | 23.722222 | 89 | 0.640449 | 3.708333 | false | false | false | false |
PureSwift/GATT | Sources/GATT/Peer.swift | 1 | 1294 | //
// Peer.swift
// GATT
//
// Created by Alsey Coleman Miller on 4/2/16.
// Copyright © 2016 PureSwift. All rights reserved.
//
/// Bluetooth LE Peer (Central, Peripheral)
public protocol Peer: Hashable, CustomStringConvertible {
associatedtype ID: Hashable, CustomStringConvertible
/// Unique identifier of the peer.
var id: ID { get }
}
public extension Peer {
static func == (lhs: Self, rhs: Self) -> Bool {
return lhs.id == rhs.id
}
func hash(into hasher: inout Hasher) {
id.hash(into: &hasher)
}
var description: String {
return id.description
}
}
// MARK: - Central
/// Central Peer
///
/// Represents a remote central device that has connected to an app implementing the peripheral role on a local device.
public struct Central: Peer {
public let id: BluetoothAddress
public init(id: BluetoothAddress) {
self.id = id
}
}
extension Central: Identifiable { }
// MARK: - Peripheral
/// Peripheral Peer
///
/// Represents a remote peripheral device that has been discovered.
public struct Peripheral: Peer {
public let id: BluetoothAddress
public init(id: BluetoothAddress) {
self.id = id
}
}
extension Peripheral: Identifiable { }
| mit | ef3999f4f8f5af524dc90e1364e5dea1 | 19.52381 | 119 | 0.641145 | 4.295681 | false | false | false | false |
josephktcheung/watchkit-core-data | Swift-Widget WatchKit Extension/InterfaceController.swift | 1 | 1688 | //
// InterfaceController.swift
// Swift-Widget WatchKit Extension
//
// Created by Joseph Cheung on 21/11/14.
// Copyright (c) 2014 AnyTap. All rights reserved.
//
import WatchKit
import Foundation
import CoreData
import SwiftWidgetKit
class InterfaceController: WKInterfaceController {
@IBOutlet weak var titleLabel: WKInterfaceLabel!
@IBOutlet weak var countLabel: WKInterfaceLabel!
let context = CoreDataStore.mainQueueContext()
var counter: Counter?
override init(context: AnyObject?) {
super.init(context: context)
self.fetchData()
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
NSLog("%@ did deactivate", self)
super.didDeactivate()
}
func fetchData () {
let counter = NSManagedObject.findAllInContext("Counter", context: self.context)
if let last: AnyObject = counter?.last {
let count = last as Counter
self.counter = count
}else{
// Create new one
self.counter = NSEntityDescription.insertNewObjectForEntityForName("Counter", inManagedObjectContext: self.context) as? Counter
self.counter?.name = ""
self.counter?.count = 0
}
self.updateData()
}
func updateData () {
self.titleLabel.setText(self.counter?.name)
self.countLabel.setText(self.counter?.count.stringValue)
}
}
| mit | 4b074930ba3a136bd8a913dfcd315034 | 27.133333 | 139 | 0.635664 | 5.069069 | false | false | false | false |
aloe-kawase/aloeutils | Pod/Classes/AloeDate.swift | 1 | 1707 | //
// AloeDate.swift
// Pods
//
// Created by kawase yu on 2015/09/17.
//
//
import UIKit
// @"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'";
public class AloeDate: NSObject {
private let df = NSDateFormatter()
private let calender = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
public static let instance = AloeDate()
override private init(){
super.init()
}
public func stringFromDate(date:NSDate, format:String)->String{
df.dateFormat = format
return df.stringFromDate(date)
}
public func dateFromString(str:String, format:String)->NSDate{
df.dateFormat = format
if let date = df.dateFromString(str) as NSDate?{
return date
}
return NSDate()
}
public func weekdayDayName(date:NSDate)->String{
let index = weekIndex(date)
return df.shortWeekdaySymbols[index-1]
}
public func weekIndex(date:NSDate)->Int{
let comps: NSDateComponents = calender.components([.Year, .WeekOfMonth, .Day, .Hour, NSCalendarUnit.Weekday], fromDate: date)
return comps.weekday
}
public func timestamp()->Int{
return Int(NSDate().timeIntervalSince1970)
}
public func agoText(date:NSDate)->String{
let sec = Int(NSDate().timeIntervalSinceDate(date))
if sec < 60{
return String(sec) + "秒前"
}else if sec < 60*60{
return String(sec / 60) + "分前"
}else if sec < 60*60*24{
return String(sec / 60 / 60) + "時間前"
}else {
return String(sec / 60 / 60 / 24) + "日前"
}
}
}
| mit | a469380c4f731c398a4a6dc6d697d292 | 24.208955 | 133 | 0.576673 | 4.21197 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/FRP/Functional/Protocols/EitherType.swift | 2 | 2961 | /// A type representing a choice between two values: left and right.
public protocol EitherType {
// swiftlint:disable type_name
associatedtype A
associatedtype B
// swiftlint:enable type_name
/**
Create an `Either` value from a left value.
- parameter left: A left value.
- returns: An `Either` value.
*/
init(left: A)
/**
Create an `Either` value from a right value.
- parameter right: A right value.
- returns: An `Either` value.
*/
init(right: B)
/**
Create an `Either` value from a value. Only works when `A != B`.
- parameter left: A value.
- returns: An `Either` value.
*/
init(_ left: A)
/**
Creates an `Either` value from a value. Only works when `A != B`.
- parameter right: A value.
- returns: An `Either` value
*/
init(_ right: B)
/// Get an optional left value out of an `Either` value.
var left: A? { get }
/// Get an optional right value out of an `Either` value.
var right: B? { get }
}
extension EitherType {
/**
Extracts the `left` value from an either.
- parameter e: An either type.
- returns: A value of type `A` if `e` is a left either, `nil` otherwise.
*/
public static func left(_ e: Self) -> A? {
return e.left
}
/**
Extracts the `right` value from an either.
- parameter e: An either type.
- returns: A value of type `B` if `e` is a right either, `nil` otherwise.
*/
public static func right(_ e: Self) -> B? {
return e.right
}
/// `true` if `self` is a left either, `false` otherwise.
public var isLeft: Bool {
return self.left != nil
}
/// `true` if `self` is a right either, `false` otherwise.
public var isRight: Bool {
return self.right != nil
}
}
public func == <E: EitherType> (lhs: E, rhs: E) -> Bool where E.A: Equatable, E.B: Equatable {
if let lhs = lhs.left, let rhs = rhs.left {
return lhs == rhs
} else if let lhs = lhs.right, let rhs = rhs.right {
return lhs == rhs
}
return false
}
/**
Returns true if the `Either` value is a left value.
- parameter either: An `Either` value.
- returns: A `Bool` value.
*/
public func isLeft <E: EitherType> (_ either: E) -> Bool {
return either.isLeft
}
/**
Returns true if the `Either` value is a right value.
- parameter either: An `Either` value.
- returns: A `Bool` value.
*/
public func isRight <E: EitherType> (_ either: E) -> Bool {
return either.isRight
}
/**
Returns all the left values from an array of `Either`s.
- parameter eithers: An array of `Either`s.
- returns: An array of left values.
*/
public func lefts <E: EitherType> (_ eithers: [E]) -> [E.A] {
return eithers.map { $0.left }.compact()
}
/**
Returns all the right values from an array of `Either`s.
- parameter eithers: An array of `Either`s.
- returns: An array of right values.
*/
public func rights <E: EitherType> (_ eithers: [E]) -> [E.B] {
return eithers.map { $0.right }.compact()
}
| mit | b2c071b8ddcd5ce06fbb9192c8b38810 | 20.613139 | 94 | 0.622087 | 3.435035 | false | false | false | false |
cozkurt/coframework | COFramework/COFramework/Swift/Extentions/UIView+Additions.swift | 1 | 8294 | //
// UIView+Additions.swift
// FuzFuz
//
// Created by Cenker Ozkurt on 10/07/19.
// Copyright © 2019 Cenker Ozkurt, Inc. All rights reserved.
//
import UIKit
extension UIView {
public func removeAllSubviews() {
self.subviews.forEach { $0.removeFromSuperview() }
}
public func showAnimateAlpha(alpha: CGFloat) {
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseOut, animations: {
self.alpha = alpha
}) { _ in
}
}
public func superview<T>(of type: T.Type) -> T? {
return superview as? T ?? superview.flatMap { $0.superview(of: type) }
}
public func subview<T>(of type: T.Type) -> T? {
return subviews.compactMap { $0 as? T ?? $0.subview(of: type) }.first
}
public class func fromNib(_ nibName: String, index: Int?) -> UIView? {
if let views = Bundle.main.loadNibNamed(nibName, owner: nil, options: nil) {
let view: UIView?
if let index = index {
view = views[index] as? UIView
} else {
view = views[0] as? UIView
}
if let view = view {
return view
} else {
return nil
}
}
return nil
}
public class func accessoryViewWithButton(_ nibName: String, label:String, target: AnyObject?, action: Selector) -> UIView? {
if let view = UIView.fromNib(nibName, index: 0) {
if let button: UIButton = view.viewWithTag(100) as? UIButton {
button.addTarget(target, action: action, for: UIControl.Event.touchUpInside)
button.setTitle(label.localize(), for: .normal)
}
return view
}
return nil
}
public class func accessoryViewWithTextView(_ nibName: String, text:String, delegate: UITextViewDelegate) -> UIView? {
if let view = UIView.fromNib(nibName, index: 0) {
if let textView: CustomTextView = view.viewWithTag(100) as? CustomTextView {
textView.delegate = delegate
textView.text = text
}
return view
}
return nil
}
public func setAnchorPoint(_ anchorPoint: CGPoint) {
var newPoint = CGPoint(x: self.bounds.size.width * anchorPoint.x, y: self.bounds.size.height * anchorPoint.y)
var oldPoint = CGPoint(x: self.bounds.size.width * self.layer.anchorPoint.x, y: self.bounds.size.height * self.layer.anchorPoint.y)
newPoint = newPoint.applying(self.transform)
oldPoint = oldPoint.applying(self.transform)
var position : CGPoint = self.layer.position
position.x -= oldPoint.x
position.x += newPoint.x
position.y -= oldPoint.y
position.y += newPoint.y
self.layer.position = position
self.layer.anchorPoint = anchorPoint
}
public func applyDefaultGradient() {
self.applyGradient([UIColor.systemBlue, UIColor.systemBackground ], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 1.0), cornerRadius: 5, opacity: 0.1, animated: false)
}
public func applyDefaultGradient2() {
self.applyGradient([UIColor.systemBlue, UIColor.systemBackground ], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 0.8, y: 1.0), cornerRadius: 5, opacity: 0.2, animated: false)
}
public func applyGradient(_ colours: [UIColor], startPoint: CGPoint, endPoint: CGPoint, cornerRadius: CGFloat, opacity: Float, animated: Bool = false) -> Void {
self.removeGradients()
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = self.bounds
gradient.locations = [0, 1]
gradient.colors = colours.map { $0.cgColor }
gradient.startPoint = startPoint
gradient.endPoint = endPoint
gradient.cornerRadius = cornerRadius
gradient.opacity = opacity
if animated {
let animation = CABasicAnimation(keyPath: "opacity")
animation.fromValue = 0
animation.toValue = opacity
animation.duration = 0.3
gradient.add(animation, forKey: nil)
}
self.layer.insertSublayer(gradient, at: 0)
}
public func removeGradients() -> Void {
if let layers = self.layer.sublayers {
for layer in layers {
if layer.isKind(of: CAGradientLayer.self) {
layer.removeFromSuperlayer()
}
}
}
}
public func removeSublayers() -> Void {
self.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
}
public func removeAll() {
// self.layer.sublayers?.forEach { $0.removeAllAnimations() }
// self.layer.sublayers?.forEach { $0.removeFromSuperlayer() }
//
// self.layer.removeAllAnimations()
self.removeFromSuperview()
}
public func animateTo(frame: CGRect, withDuration duration: TimeInterval, completion: ((Bool) -> Void)? = nil) {
guard let _ = superview else {
return
}
let xScale = frame.size.width / self.frame.size.width
let yScale = frame.size.height / self.frame.size.height
let x = frame.origin.x + (self.frame.width * xScale) * self.layer.anchorPoint.x
let y = frame.origin.y + (self.frame.height * yScale) * self.layer.anchorPoint.y
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
self.layer.position = CGPoint(x: x, y: y)
self.transform = self.transform.scaledBy(x: xScale, y: yScale)
self.layoutIfNeeded()
}, completion: completion)
}
public func scaleTo(scale: CGFloat, withDuration duration: TimeInterval, completion: ((Bool) -> Void)? = nil) {
guard let _ = superview else {
return
}
UIView.animate(withDuration: duration, delay: 0, options: .curveEaseInOut, animations: {
self.transform = self.transform.scaledBy(x: scale, y: scale)
self.layoutIfNeeded()
}, completion: completion)
}
public func resizeToFitSubviews() {
var w: CGFloat = 0
var h: CGFloat = 0
for v in self.subviews {
let fw = v.frame.origin.x + v.frame.size.width
let fh = v.frame.origin.y + v.frame.size.height
w = max(fw, w)
h = max(fh, h)
}
self.frame = CGRect(x: self.frame.origin.x, y: self.frame.origin.y, width: w, height: h)
}
}
// Blur
public protocol Bluring {
func addBlur(_ alpha: CGFloat)
}
extension Bluring where Self: UIView {
public func addBlur(_ alpha: CGFloat = 0.5) {
let isBlurExists = self.subviews.count > 0
if alpha > 0 && !isBlurExists {
// create effect
let effect = UIBlurEffect(style: .dark)
let effectView = UIVisualEffectView(effect: effect)
// set boundry and alpha
effectView.frame = self.bounds
effectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
effectView.alpha = 0
self.addSubview(effectView)
UIView.animate(withDuration: 0.3) {
effectView.alpha = alpha
}
}
}
public func removeBlur() {
self.removeAllSubviews()
}
}
// Conformance
extension UIView: Bluring {}
// Gesture recognizer
extension UIView {
public func userStartedGesture() -> Bool {
guard let view = self.subviews.first, let gestureReconizers = view.gestureRecognizers else {
return false
}
for recognizer in gestureReconizers {
if recognizer.state == UIGestureRecognizer.State.began || recognizer.state == UIGestureRecognizer.State.ended {
return true
}
}
return false
}
}
| gpl-3.0 | 9fa41e1082e62ad7cb684efe28732796 | 32.039841 | 191 | 0.567225 | 4.602109 | false | false | false | false |
flodolo/firefox-ios | Client/Frontend/DefaultBrowserOnboarding/DefaultBrowserOnboardingViewController.swift | 1 | 11603 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import UIKit
import Shared
/*
|----------------|
| X |
|Title Multiline |
| | (Top View)
|Description |
|Multiline |
| |
| |
| |
|----------------|
| [Button] | (Bottom View)
|----------------|
*/
struct DBOnboardingUX {
static let textOffset = 20
static let textOffsetSmall = 13
static let fontSize: CGFloat = 24
static let fontSizeSmall: CGFloat = 20
static let fontSizeXSmall: CGFloat = 16
static let titleSize: CGFloat = 28
static let titleSizeSmall: CGFloat = 24
static let titleSizeLarge: CGFloat = 34
static let containerViewHeight = 350
static let containerViewHeightSmall = 300
static let containerViewHeightXSmall = 250
static let buttonCornerRadius: CGFloat = 10
static let buttonColour = UIColor.Photon.Blue50
}
class DefaultBrowserOnboardingViewController: UIViewController, OnViewDismissable {
// MARK: - Properties
var onViewDismissed: (() -> Void)?
// Public constants
let viewModel = DefaultBrowserOnboardingViewModel()
let theme = LegacyThemeManager.instance
// Private vars
private var fxTextThemeColour: UIColor {
// For dark theme we want to show light colours and for light we want to show dark colours
return theme.currentName == .dark ? .white : .black
}
private var fxBackgroundThemeColour: UIColor = UIColor.theme.onboarding.backgroundColor
private var descriptionFontSize: CGFloat {
return screenSize.height > 1000 ? DBOnboardingUX.fontSizeXSmall :
screenSize.height > 668 ? DBOnboardingUX.fontSize :
screenSize.height > 640 ? DBOnboardingUX.fontSizeSmall : DBOnboardingUX.fontSizeXSmall
}
private var titleFontSize: CGFloat {
return screenSize.height > 1000 ? DBOnboardingUX.titleSizeLarge :
screenSize.height > 640 ? DBOnboardingUX.titleSize : DBOnboardingUX.titleSizeSmall
}
// Orientation independent screen size
private let screenSize = DeviceInfo.screenSizeOrientationIndependent()
// UI
private lazy var closeButton: UIButton = .build { [weak self] button in
button.setImage(UIImage(named: "close-large"), for: .normal)
button.tintColor = .secondaryLabel
button.addTarget(self, action: #selector(self?.dismissAnimated), for: .touchUpInside)
}
private let textView: UIView = .build { view in }
private lazy var titleLabel: UILabel = .build { [weak self] label in
guard let self = self else { return }
label.text = self.viewModel.model?.titleText
label.font = .boldSystemFont(ofSize: self.titleFontSize)
label.textAlignment = .center
label.numberOfLines = 2
}
private lazy var descriptionText: UILabel = .build { [weak self] label in
guard let self = self else { return }
label.text = self.viewModel.model?.descriptionText[0]
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, maxSize: 28)
label.textAlignment = .left
label.numberOfLines = 5
label.adjustsFontSizeToFitWidth = true
}
private lazy var descriptionLabel1: UILabel = .build { [weak self] label in
guard let self = self else { return }
label.text = self.viewModel.model?.descriptionText[1]
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, maxSize: 36)
label.textAlignment = .left
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
}
private lazy var descriptionLabel2: UILabel = .build { [weak self] label in
guard let self = self else { return }
label.text = self.viewModel.model?.descriptionText[2]
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, maxSize: 36)
label.textAlignment = .left
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
}
private lazy var descriptionLabel3: UILabel = .build { [weak self] label in
guard let self = self else { return }
label.text = self.viewModel.model?.descriptionText[3]
label.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .body, maxSize: 36)
label.textAlignment = .left
label.numberOfLines = 0
label.adjustsFontSizeToFitWidth = true
}
private lazy var goToSettingsButton: UIButton = .build { [weak self] button in
guard let self = self else { return }
button.setTitle(.DefaultBrowserOnboardingButton, for: .normal)
button.layer.cornerRadius = DBOnboardingUX.buttonCornerRadius
button.setTitleColor(.white, for: .normal)
button.backgroundColor = DBOnboardingUX.buttonColour
button.accessibilityIdentifier = "HomeTabBanner.goToSettingsButton"
button.addTarget(self, action: #selector(self.goToSettings), for: .touchUpInside)
button.titleLabel?.font = DynamicFontHelper.defaultHelper.preferredFont(withTextStyle: .title3, maxSize: 40)
button.titleLabel?.adjustsFontSizeToFitWidth = true
}
// Used to set the part of text in center
private var containerView = UIView()
// MARK: - Inits
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycles
override func viewDidLoad() {
super.viewDidLoad()
initialViewSetup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Portrait orientation: lock enable
OrientationLockUtility.lockOrientation(UIInterfaceOrientationMask.portrait, andRotateTo: UIInterfaceOrientation.portrait)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Portrait orientation: lock disable
OrientationLockUtility.lockOrientation(UIInterfaceOrientationMask.all)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
onViewDismissed?()
onViewDismissed = nil
}
func initialViewSetup() {
updateTheme()
view.addSubview(closeButton)
textView.addSubview(containerView)
containerView.addSubviews(titleLabel, descriptionText, descriptionLabel1, descriptionLabel2, descriptionLabel3)
view.addSubviews(textView, goToSettingsButton)
// Constraints
setupView()
// Theme change notification
NotificationCenter.default.addObserver(self, selector: #selector(updateTheme), name: .DisplayThemeChanged, object: nil)
}
private func setupView() {
let textOffset = screenSize.height > 668 ? DBOnboardingUX.textOffset : DBOnboardingUX.textOffsetSmall
NSLayoutConstraint.activate([
closeButton.topAnchor.constraint(equalTo: view.topAnchor, constant: 10),
closeButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
closeButton.heightAnchor.constraint(equalToConstant: 44),
textView.topAnchor.constraint(equalTo: closeButton.bottomAnchor, constant: 10),
textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 36),
textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -36),
textView.bottomAnchor.constraint(equalTo: goToSettingsButton.topAnchor),
titleLabel.centerXAnchor.constraint(lessThanOrEqualTo: view.centerXAnchor),
titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8),
titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -8),
descriptionText.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: CGFloat(textOffset)),
descriptionText.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: CGFloat(textOffset)),
descriptionText.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: CGFloat(-textOffset)),
descriptionLabel1.topAnchor.constraint(equalTo: descriptionText.bottomAnchor, constant: CGFloat(textOffset)),
descriptionLabel1.leadingAnchor.constraint(equalTo: descriptionText.leadingAnchor),
descriptionLabel1.trailingAnchor.constraint(equalTo: view.trailingAnchor),
descriptionLabel2.topAnchor.constraint(equalTo: descriptionLabel1.bottomAnchor, constant: CGFloat(textOffset)),
descriptionLabel2.leadingAnchor.constraint(equalTo: descriptionLabel1.leadingAnchor),
descriptionLabel2.trailingAnchor.constraint(equalTo: view.trailingAnchor),
descriptionLabel3.topAnchor.constraint(equalTo: descriptionLabel2.bottomAnchor, constant: CGFloat(textOffset)),
descriptionLabel3.leadingAnchor.constraint(equalTo: descriptionLabel2.leadingAnchor),
descriptionLabel3.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
if screenSize.height > 1000 {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -60),
goToSettingsButton.heightAnchor.constraint(equalToConstant: 50),
goToSettingsButton.widthAnchor.constraint(equalToConstant: 350)
])
} else if screenSize.height > 640 {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -5),
goToSettingsButton.heightAnchor.constraint(equalToConstant: 60),
goToSettingsButton.widthAnchor.constraint(equalToConstant: 350)
])
} else {
NSLayoutConstraint.activate([
goToSettingsButton.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -5),
goToSettingsButton.heightAnchor.constraint(equalToConstant: 50),
goToSettingsButton.widthAnchor.constraint(equalToConstant: 300)
])
}
goToSettingsButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
}
// Button Actions
@objc private func dismissAnimated() {
self.dismiss(animated: true, completion: nil)
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .dismissDefaultBrowserOnboarding)
}
@objc private func goToSettings() {
viewModel.goToSettings?()
UserDefaults.standard.set(true, forKey: PrefsKeys.DidDismissDefaultBrowserMessage) // Don't show default browser card if this button is clicked
TelemetryWrapper.recordEvent(category: .action, method: .tap, object: .goToSettingsDefaultBrowserOnboarding)
}
// Theme
@objc func updateTheme() {
view.backgroundColor = .systemBackground
titleLabel.textColor = fxTextThemeColour
descriptionText.textColor = fxTextThemeColour
descriptionLabel1.textColor = fxTextThemeColour
descriptionLabel2.textColor = fxTextThemeColour
descriptionLabel3.textColor = fxTextThemeColour
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| mpl-2.0 | b98d05642f2be96c05d9dc0cb0763300 | 41.658088 | 151 | 0.692924 | 5.43466 | false | false | false | false |
marhas/ios-video-explorer | AVCaptureDoctor/ViewController.swift | 1 | 9023 | //
// ViewController.swift
// AVCaptureDoctor
//
// Created by Marcel Hasselaar on 03/10/15.
// Copyright © 2015 AgiDev. All rights reserved.
//
import UIKit
import AVFoundation
class ViewController: UIViewController, UIPickerViewDelegate, FormatSelectionDelegate {
@IBOutlet weak var formatButton: UIButton!
@IBOutlet weak var videoPreviewView: UIView!
@IBOutlet weak var focusSlider: UISlider!
@IBOutlet weak var isoSlider: UISlider!
@IBOutlet weak var currentFocusLabel: UILabel!
@IBOutlet weak var currentIsoLabel: UILabel!
@IBOutlet weak var torchModeSwitch: UISwitch!
var session:AVCaptureSession!
var videoDevice:AVCaptureDevice!
var audioDevice:AVCaptureDevice!
var selectedVideoFormat:AVCaptureDeviceFormat?
var previewLayer:AVCaptureVideoPreviewLayer!
override func viewDidLoad() {
super.viewDidLoad()
torchModeSwitch?.on = false
session = AVCaptureSession()
self.initVideo()
var videoFormatLabel = "No video device available"
if (self.selectedVideoFormat != nil) {
videoFormatLabel = (self.selectedVideoFormat?.friendlyShortDescription())!
}
formatButton.setTitle(videoFormatLabel, forState: .Normal)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "formatSelectionSegue" {
let formatSelectionVC = segue.destinationViewController as! FormatSelectionVC
formatSelectionVC.videoFormats = getVideoFormats()
formatSelectionVC.mainViewController = self
}
}
override func viewDidAppear(animated: Bool) {
formatButton.titleLabel?.text = self.selectedVideoFormat?.friendlyShortDescription()
formatButton.titleLabel?.sizeToFit()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
previewLayer?.frame = self.videoPreviewView.bounds
}
@IBAction func flashSwitchToggled(sender: UISwitch) {
if (sender.on) {
enableFlash(true)
} else {
enableFlash(false)
}
}
private func initVideo() {
guard let videoDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) else {
print("No video capture device avaialbe on this hardware")
return
}
self.videoDevice = videoDevice
setVideoFormat(getVideoFormats()[0])
setCameraFocus(0.5)
setCameraIso(0.5)
var videoInput:AVCaptureDeviceInput!
do {
videoInput = try AVCaptureDeviceInput(device: videoDevice)
} catch {
print("Couldn't create video input")
return;
}
if (session.canAddInput(videoInput)) {
session.addInput(videoInput)
}
previewLayer = AVCaptureVideoPreviewLayer(session: session);
self.videoPreviewView.layer.addSublayer(previewLayer)
session.startRunning()
}
private func enableFlash(enable: Bool) {
defer {
videoDevice.unlockForConfiguration()
}
do {
try videoDevice.lockForConfiguration()
videoDevice.torchMode = enable ? .On : .Off
} catch {
print("Error enabling torch mode.");
}
}
private func getVideoFormats() -> [AVCaptureDeviceFormat] {
guard let videoDevice = videoDevice else {
return []
}
return videoDevice.formats as! [AVCaptureDeviceFormat]
}
func setVideoFormat(format: AVCaptureDeviceFormat) {
defer {
enableFlash(torchModeSwitch.on)
videoDevice.unlockForConfiguration()
}
do {
try videoDevice.lockForConfiguration()
videoDevice.activeFormat = format;
self.selectedVideoFormat = format;
videoDevice.focusMode = .Locked
print("Changed video mode to: \(videoDevice.activeFormat.friendlyShortDescription())")
} catch {
print("Error trying to set video capture format to \(format)");
}
}
private func setCameraFocus(focus: Float) {
defer {
videoDevice.unlockForConfiguration()
}
do {
try videoDevice.lockForConfiguration()
videoDevice.setFocusModeLockedWithLensPosition(focus, completionHandler: { [weak self] (time: CMTime) -> Void in
self?.currentFocusLabel.text = String(focus)
})
} catch {
print("Error setting focus to \(focus)");
}
}
private func setCameraIso(relativeIso: Float) {
defer {
videoDevice.unlockForConfiguration()
}
var calculatedIso : Float = 0;
do {
try videoDevice.lockForConfiguration()
calculatedIso = self.videoDevice.activeFormat.minISO + (self.videoDevice.activeFormat.maxISO - self.videoDevice.activeFormat.minISO) * relativeIso;
videoDevice.setExposureModeCustomWithDuration(AVCaptureExposureDurationCurrent, ISO: calculatedIso, completionHandler: { [weak self] (time: CMTime) -> Void in
self?.currentIsoLabel.text = String(calculatedIso)
})
} catch {
print("Error setting iso to \(calculatedIso)");
}
}
//MARK: Focus UISliderView delegate
@IBAction func focusSliderValueChanged(sender: UISlider) {
self.setCameraFocus(sender.value)
}
//MARK: Iso UISliderView delegate
@IBAction func isoSliderValueChanged(sender: UISlider) {
self.setCameraIso(sender.value)
}
//MARK: FormatSelectionDelegate
func didSelectFormat(format: AVCaptureDeviceFormat) {
setVideoFormat(format)
}
}
extension AVCaptureDeviceFormat {
func friendlyDescription() -> String {
let xDimension = CMVideoFormatDescriptionGetDimensions(self.formatDescription).width
let yDimension = CMVideoFormatDescriptionGetDimensions(self.formatDescription).height
let avFrameRateRanges = self.videoSupportedFrameRateRanges
let minFrameRate = (avFrameRateRanges[0] as! AVFrameRateRange).minFrameRate
let maxFrameRate = (avFrameRateRanges[0] as! AVFrameRateRange).maxFrameRate
let avFrameRateRangeString = "\(Int(minFrameRate)) - \(Int(maxFrameRate))"
let isoRange = "\(Int(self.minISO))-\(Int(self.maxISO))"
var friendlyFormatString = "Dimensions: \(xDimension)x\(yDimension)\n"
friendlyFormatString.appendContentsOf("Iso range: \(isoRange)\n")
friendlyFormatString.appendContentsOf("Frame rate range: \(avFrameRateRangeString)\n")
if (self.videoBinned) {
friendlyFormatString.appendContentsOf("Binned\n")
}
if (self.videoHDRSupported) {
friendlyFormatString.appendContentsOf("HDR supported\n")
}
if (self.autoFocusSystem == AVCaptureAutoFocusSystem.ContrastDetection) {
friendlyFormatString.appendContentsOf("AF mode: contrast detection\n")
} else if self.autoFocusSystem == AVCaptureAutoFocusSystem.PhaseDetection {
friendlyFormatString.appendContentsOf("AF mode: phase detection\n")
}
if self.isVideoStabilizationModeSupported(AVCaptureVideoStabilizationMode.Cinematic) {
friendlyFormatString.appendContentsOf("Video stabilization mode: Cinematic\n")
} else if self.isVideoStabilizationModeSupported(AVCaptureVideoStabilizationMode.Standard) {
friendlyFormatString.appendContentsOf("Video stabilization mode: Standard\n")
}
friendlyFormatString.appendContentsOf("Media type: \(self.mediaType)\n")
friendlyFormatString.appendContentsOf("Max zoom factor: \(self.videoMaxZoomFactor)\n")
friendlyFormatString.appendContentsOf("Field of view: \(self.videoFieldOfView)\n")
if (avFrameRateRanges.count > 1) {
print("Warning, format (\(friendlyFormatString)) contains multiple frame rate ranges")
}
return friendlyFormatString
}
func friendlyShortDescription() -> String {
let xDimension = CMVideoFormatDescriptionGetDimensions(self.formatDescription).width
let yDimension = CMVideoFormatDescriptionGetDimensions(self.formatDescription).height
let avFrameRateRanges = self.videoSupportedFrameRateRanges
let minFrameRate = (avFrameRateRanges[0] as! AVFrameRateRange).minFrameRate
let maxFrameRate = (avFrameRateRanges[0] as! AVFrameRateRange).maxFrameRate
let avFrameRateRangeString = "\(Int(minFrameRate)) - \(Int(maxFrameRate))"
let isoRange = "\(Int(self.minISO))-\(Int(self.maxISO))"
let friendlyFormatString = "\(xDimension)x\(yDimension) \(isoRange) \(avFrameRateRangeString)"
return friendlyFormatString
}
} | mit | c5c8205057e45a9f2e43ec73a7ec6173 | 37.233051 | 170 | 0.662603 | 5.363853 | false | false | false | false |
justinmfischer/SwiftyExpandingCells | SwiftyExpandingCells/Libs/SegueHandlerType/SegueHandlerType.swift | 1 | 3059 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Contains types / typealiases for cross-platform utility helpers for working with segues / segue identifiers in a controller.
*/
#if os(iOS)
import UIKit
public typealias StoryboardSegue = UIStoryboardSegue
public typealias ViewController = UIViewController
#elseif os(OSX)
import Cocoa
public typealias StoryboardSegue = NSStoryboardSegue
public typealias ViewController = NSWindowController
#endif
/**
A protocol specific to the Lister sample that represents the segue identifier
constraints in the app. Every view controller provides a segue identifier
enum mapping. This protocol defines that structure.
We also want to provide implementation to each view controller that conforms
to this protocol that helps box / unbox the segue identifier strings to
segue identifier enums. This is provided in an extension of `SegueHandlerType`.
*/
public protocol SegueHandlerType {
/**
Gives structure to what we expect the segue identifiers will be. We expect
the `SegueIdentifier` mapping to be an enum case to `String` mapping.
For example:
enum SegueIdentifier: String {
case ShowAccount
case ShowHelp
...
}
*/
associatedtype SegueIdentifier: RawRepresentable
}
/**
Constrain the implementation for `SegueHandlerType` conforming
types to only work with view controller subclasses whose `SegueIdentifier`
raw values are `String` instances. Practically speaking, the enum that provides
the mapping between the view controller's segue identifier strings should
be backed by a `String`. See the description for `SegueHandlerType` for an example.
*/
public extension SegueHandlerType where Self: ViewController, SegueIdentifier.RawValue == String {
/**
An overload of `UIViewController`'s `performSegueWithIdentifier(_:sender:)`
method that takes in a `SegueIdentifier` enum parameter rather than a
`String`.
*/
func performSegueWithIdentifier(segueIdentifier: SegueIdentifier, sender: AnyObject?) {
performSegue(withIdentifier: segueIdentifier.rawValue, sender: sender)
}
/**
A convenience method to map a `StoryboardSegue` to the segue identifier
enum that it represents.
*/
func segueIdentifierForSegue(segue: StoryboardSegue) -> SegueIdentifier {
/*
Map the segue identifier's string to an enum. It's a programmer error
if a segue identifier string that's provided doesn't map to one of the
raw representable values (most likely enum cases).
*/
guard let identifier = segue.identifier,
let segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Couldn't handle segue identifier \(segue.identifier) for view controller of type \(type(of: self)).")
}
return segueIdentifier
}
}
| mit | 4fbf36a422987e3e78c77a4d726b653a | 38.192308 | 129 | 0.713445 | 5.598901 | false | false | false | false |
codeforgreenville/trolley-tracker-ios-client | TrolleyTracker/Views/Schedule/ScheduleHeaderView.swift | 1 | 1800 | //
// ScheduleHeaderView.swift
// TrolleyTracker
//
// Created by Austin Younts on 10/27/15.
// Copyright © 2015 Code For Greenville. All rights reserved.
//
import UIKit
class ScheduleHeaderView: UITableViewHeaderFooterView {
var tapAction: ScheduleDataSource.DisplayRouteAction?
private var tapGesture: UITapGestureRecognizer!
private var displayedRouteID: Int?
private let titleLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.font = UIFont.boldSystemFont(ofSize: 12)
return label
}()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.backgroundColor = .white
addSubview(titleLabel)
titleLabel.horizontalAnchors == horizontalAnchors + 8
titleLabel.verticalAnchors == verticalAnchors + 4
tapGesture = UITapGestureRecognizer(target: self,
action: #selector(ScheduleHeaderView.handleTap(_:)))
addGestureRecognizer(tapGesture)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func displaySection(_ section: ScheduleSection) {
titleLabel.text = section.title
titleLabel.textColor = section.selectable ? UIColor.ttAlternateTintColor() : UIColor.black
tapGesture.isEnabled = section.selectable
displayedRouteID = section.selectable ? section.items.first?.routeID : nil
}
@objc private func handleTap(_ tap: UITapGestureRecognizer) {
guard let routeID = displayedRouteID else { return }
tapAction?(routeID)
}
}
| mit | 5f0f845ce152f085582b2f1dc4565231 | 31.125 | 98 | 0.661479 | 5.501529 | false | false | false | false |
rnystrom/GitHawk | Classes/Repository/RepositoryImageViewController.swift | 1 | 6375 | //
// RepositoryImageViewController.swift
// Freetime
//
// Created by Ryan Nystrom on 11/17/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import Foundation
import SDWebImage
import SnapKit
import TUSafariActivity
final class RepositoryImageViewController: UIViewController,
EmptyViewDelegate,
UIScrollViewDelegate {
private let branch: String
private let path: FilePath
private let repo: RepositoryDetails
private let client: GithubClient
private let emptyView = EmptyView()
private let scrollView = UIScrollView()
private let imageView = FLAnimatedImageView()
private let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
private var imageUrl: URL? {
let builder = URLBuilder.github()
.add(path: repo.owner)
.add(path: repo.name)
.add(path: "raw")
.add(path: branch)
path.components.forEach { builder.add(path: $0) }
return builder.url
}
private lazy var moreOptionsItem: UIBarButtonItem = {
let barButtonItem = UIBarButtonItem(
image: UIImage(named: "bullets-hollow"),
target: self,
action: #selector(RepositoryImageViewController.onShare(sender:)))
barButtonItem.accessibilityLabel = Constants.Strings.moreOptions
barButtonItem.isEnabled = false
return barButtonItem
}()
init(repo: RepositoryDetails, branch: String, path: FilePath, client: GithubClient) {
self.branch = branch
self.path = path
self.repo = repo
self.client = client
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
configureTitle(filePath: path, target: self, action: #selector(onFileNavigationTitle(sender:)))
makeBackBarItemEmpty()
navigationItem.rightBarButtonItem = moreOptionsItem
emptyView.isHidden = true
emptyView.label.text = NSLocalizedString("Error loading image", comment: "")
view.addSubview(emptyView)
emptyView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
scrollView.contentInsetAdjustmentBehavior = .never
scrollView.alwaysBounceVertical = true
scrollView.alwaysBounceHorizontal = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.maximumZoomScale = 4
scrollView.delegate = self
view.addSubview(scrollView)
scrollView.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
imageView.contentMode = .scaleAspectFit
scrollView.addSubview(imageView)
view.addSubview(activityIndicator)
activityIndicator.snp.makeConstraints { make in
make.center.equalToSuperview()
}
fetch()
}
// MARK: Private API
@objc func onFileNavigationTitle(sender: UIView) {
showAlert(filePath: path, sender: sender)
}
private func fetch() {
emptyView.isHidden = true
activityIndicator.startAnimating()
imageView.sd_setImage(with: imageUrl) { [weak self] (_, error, _, _) in
self?.handle(success: error == nil)
}
}
private func handle(success: Bool) {
moreOptionsItem.isEnabled = success
emptyView.isHidden = success
activityIndicator.stopAnimating()
if let size = imageView.image?.size {
// centered later in UIScrollViewDelegate
imageView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
scrollView.contentSize = size
let bounds = view.bounds
let scale = min(bounds.width / size.width, bounds.height / size.height)
// min must be set before zoom
scrollView.minimumZoomScale = scale
scrollView.zoomScale = scale
}
}
@objc func onShare(sender: UIButton) {
let alertTitle = "\(repo.owner)/\(repo.name):\(branch)"
let alert = UIAlertController.configured(title: alertTitle, preferredStyle: .actionSheet)
let alertBuilder = AlertActionBuilder { [weak self] in $0.rootViewController = self }
var actions = [
viewHistoryAction(owner: repo.owner, repo: repo.name, branch: branch, client: client, path: path),
AlertAction(alertBuilder).share([path.path], activities: nil, type: .shareFilePath) {
$0.popoverPresentationController?.setSourceView(sender)
}
]
if let image = imageView.image {
actions.append(AlertAction(alertBuilder).share([image], activities: nil, type: .shareContent) {
$0.popoverPresentationController?.setSourceView(sender)
})
}
if let url = imageUrl {
actions.append(AlertAction(alertBuilder).share([url], activities: [TUSafariActivity()], type: .shareUrl) {
$0.popoverPresentationController?.setSourceView(sender)
})
}
actions.append(AlertAction.cancel())
if let name = self.path.components.last {
actions.append(AlertAction(alertBuilder).share([name], activities: nil, type: .shareFileName) {
$0.popoverPresentationController?.setSourceView(sender)
})
}
alert.addActions(actions)
alert.popoverPresentationController?.setSourceView(sender)
present(alert, animated: trueUnlessReduceMotionEnabled)
}
// MARK: EmptyViewDelegate
func didTapRetry(view: EmptyView) {
fetch()
}
// MARK: UIScrollViewDelegate
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) / 2, 0)
let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) / 2, 0)
imageView.center = CGPoint(
x: scrollView.contentSize.width / 2 + offsetX,
y: scrollView.contentSize.height / 2 + offsetY
)
}
}
| mit | a769e6aa29a5eb467533eef8498483b7 | 33.085561 | 118 | 0.644807 | 5.091054 | false | false | false | false |
frootloops/swift | test/Interpreter/protocol_initializers_class.swift | 4 | 10960 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %target-build-swift -swift-version 5 %s -o %t/a.out
//
// RUN: %target-run %t/a.out
// REQUIRES: executable_test
import StdlibUnittest
var ProtocolInitTestSuite = TestSuite("ProtocolInitClass")
func mustThrow<T>(_ f: () throws -> T) {
do {
_ = try f()
preconditionFailure("Didn't throw")
} catch {}
}
func mustFail<T>(f: () -> T?) {
if f() != nil {
preconditionFailure("Didn't fail")
}
}
enum E : Error { case X }
// This is the same as the protocol_initializers.swift test,
// but class-bound
protocol TriviallyConstructible : class {
init(x: LifetimeTracked)
init(x: LifetimeTracked, throwsDuring: Bool) throws
init?(x: LifetimeTracked, failsDuring: Bool)
}
extension TriviallyConstructible {
init(x: LifetimeTracked, throwsBefore: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: x)
}
init(x: LifetimeTracked, throwsAfter: Bool) throws {
self.init(x: x)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: x, throwsDuring: throwsDuring)
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: x)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsDuring: Bool, throwsAfter: Bool) throws {
try self.init(x: x, throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
init(x: LifetimeTracked, throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: x, throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
init?(x: LifetimeTracked, failsBefore: Bool) {
if failsBefore {
return nil
}
self.init(x: x)
}
init?(x: LifetimeTracked, failsAfter: Bool) {
self.init(x: x)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool) {
if failsBefore {
return nil
}
self.init(x: x, failsDuring: failsDuring)
}
init?(x: LifetimeTracked, failsBefore: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: x)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsDuring: Bool, failsAfter: Bool) {
self.init(x: x, failsDuring: failsDuring)
if failsAfter {
return nil
}
}
init?(x: LifetimeTracked, failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: x, failsDuring: failsDuring)
if failsAfter {
return nil
}
}
}
class TrivialClass : TriviallyConstructible {
let tracker: LifetimeTracked
// Protocol requirements
required init(x: LifetimeTracked) {
self.tracker = x
}
required convenience init(x: LifetimeTracked, throwsDuring: Bool) throws {
self.init(x: x)
if throwsDuring {
throw E.X
}
}
required convenience init?(x: LifetimeTracked, failsDuring: Bool) {
self.init(x: x)
if failsDuring {
return nil
}
}
// Class initializers delegating to protocol initializers
convenience init(throwsBefore: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: LifetimeTracked(0))
}
convenience init(throwsAfter: Bool) throws {
self.init(x: LifetimeTracked(0))
if throwsAfter {
throw E.X
}
}
convenience init(throwsBefore: Bool, throwsDuring: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
}
convenience init(throwsBefore: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
self.init(x: LifetimeTracked(0))
if throwsAfter {
throw E.X
}
}
convenience init(throwsDuring: Bool, throwsAfter: Bool) throws {
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
convenience init(throwsBefore: Bool, throwsDuring: Bool, throwsAfter: Bool) throws {
if throwsBefore {
throw E.X
}
try self.init(x: LifetimeTracked(0), throwsDuring: throwsDuring)
if throwsAfter {
throw E.X
}
}
convenience init?(failsBefore: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0))
}
convenience init?(failsAfter: Bool) {
self.init(x: LifetimeTracked(0))
if failsAfter {
return nil
}
}
convenience init?(failsBefore: Bool, failsDuring: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
}
convenience init?(failsBefore: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0))
if failsAfter {
return nil
}
}
convenience init?(failsDuring: Bool, failsAfter: Bool) {
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
if failsAfter {
return nil
}
}
convenience init?(failsBefore: Bool, failsDuring: Bool, failsAfter: Bool) {
if failsBefore {
return nil
}
self.init(x: LifetimeTracked(0), failsDuring: failsDuring)
if failsAfter {
return nil
}
}
}
ProtocolInitTestSuite.test("ExtensionInit_Success") {
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: false)
_ = try! TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: false)
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: false)!
_ = TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: false)!
}
ProtocolInitTestSuite.test("ClassInit_Success") {
_ = try! TrivialClass(throwsBefore: false)
_ = try! TrivialClass(throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsDuring: false)
_ = try! TrivialClass(throwsDuring: false, throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsAfter: false)
_ = try! TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: false)
_ = TrivialClass(failsBefore: false)!
_ = TrivialClass(failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsDuring: false)!
_ = TrivialClass(failsDuring: false, failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsAfter: false)!
_ = TrivialClass(failsBefore: false, failsDuring: false, failsAfter: false)!
}
ProtocolInitTestSuite.test("ExtensionInit_Failure") {
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsDuring: false, throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsAfter: true) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: true, throwsDuring: false, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(x: LifetimeTracked(0), throwsBefore: false, throwsDuring: false, throwsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsDuring: false, failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsAfter: true) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: true, failsDuring: false, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(x: LifetimeTracked(0), failsBefore: false, failsDuring: false, failsAfter: true) }
}
ProtocolInitTestSuite.test("ClassInit_Failure") {
mustThrow { try TrivialClass(throwsBefore: true) }
mustThrow { try TrivialClass(throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true) }
mustThrow { try TrivialClass(throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsDuring: false, throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsAfter: true) }
mustThrow { try TrivialClass(throwsBefore: true, throwsDuring: false, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: true, throwsAfter: false) }
mustThrow { try TrivialClass(throwsBefore: false, throwsDuring: false, throwsAfter: true) }
mustFail { TrivialClass(failsBefore: true) }
mustFail { TrivialClass(failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsDuring: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: true) }
mustFail { TrivialClass(failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(failsDuring: false, failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsAfter: true) }
mustFail { TrivialClass(failsBefore: true, failsDuring: false, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: true, failsAfter: false) }
mustFail { TrivialClass(failsBefore: false, failsDuring: false, failsAfter: true) }
}
runAllTests()
| apache-2.0 | bf2ddfe9ebdc9cc5d1d83532379c3dc9 | 31.522255 | 116 | 0.694799 | 4.210526 | false | false | false | false |
frootloops/swift | test/SILGen/protocol_resilience.swift | 1 | 17439 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-frontend -I %t -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck %s
import resilient_protocol
prefix operator ~~~ {}
infix operator <*> {}
infix operator <**> {}
infix operator <===> {}
public protocol P {}
// Protocol is public -- needs resilient witness table
public protocol ResilientMethods {
associatedtype AssocType : P
func defaultWitness()
func anotherDefaultWitness(_ x: Int) -> Self
func defaultWitnessWithAssociatedType(_ a: AssocType)
func defaultWitnessMoreAbstractThanRequirement(_ a: AssocType, b: Int)
func defaultWitnessMoreAbstractThanGenericRequirement<T>(_ a: AssocType, t: T)
func noDefaultWitness()
func defaultWitnessIsNotPublic()
static func staticDefaultWitness(_ x: Int) -> Self
}
extension ResilientMethods {
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP14defaultWitnessyyF
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE14defaultWitnessyyF
public func defaultWitness() {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessxSiF
public func anotherDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypey05AssocI0QzF
public func defaultWitnessWithAssociatedType(_ a: AssocType) {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirementyqd___qd_0_1btr0_lF
public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirementyqd___qd_0_1ttr0_lF
public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessxSiFZ
public static func staticDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil private @_T019protocol_resilience16ResilientMethodsPAAE25defaultWitnessIsNotPublic{{.*}}F
private func defaultWitnessIsNotPublic() {}
}
public protocol ResilientConstructors {
init(noDefault: ())
init(default: ())
init?(defaultIsOptional: ())
init?(defaultNotOptional: ())
init(optionalityMismatch: ())
}
extension ResilientConstructors {
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC
// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt7default_tcfC
public init(default: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC
// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt17defaultIsOptional_tcfC
public init?(defaultIsOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExyt20defaultIsNotOptional_tcfC
public init(defaultIsNotOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @_T019protocol_resilience21ResilientConstructorsPAAExSgyt19optionalityMismatch_tcfC
public init?(optionalityMismatch: ()) {
self.init(noDefault: ())
}
}
public protocol ResilientStorage {
associatedtype T : ResilientConstructors
var propertyWithDefault: Int { get }
var propertyWithNoDefault: Int { get }
var mutablePropertyWithDefault: Int { get set }
var mutablePropertyNoDefault: Int { get set }
var mutableGenericPropertyWithDefault: T { get set }
subscript(x: T) -> T { get set }
var mutatingGetterWithNonMutatingDefault: Int { mutating get set }
}
extension ResilientStorage {
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP19propertyWithDefaultSivg
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE19propertyWithDefaultSivg
public var propertyWithDefault: Int {
get { return 0 }
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivg
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivs
// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivmytfU_
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivm
public var mutablePropertyWithDefault: Int {
get { return 0 }
set { }
}
public private(set) var mutablePropertyNoDefault: Int {
get { return 0 }
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvg
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvs
// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvmytfU_
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvm
public var mutableGenericPropertyWithDefault: T {
get {
return T(default: ())
}
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcig
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE1TQzAEcig
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcis
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE1TQzAEcis
// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP1TQzAEcimytfU_
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP1TQzAEcim
public subscript(x: T) -> T {
get {
return x
}
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-LABEL: sil @_T019protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-LABEL: sil private [transparent] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivmytfU_
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivm
public var mutatingGetterWithNonMutatingDefault: Int {
get {
return 0
}
set { }
}
}
public protocol ResilientOperators {
associatedtype AssocType : P
static prefix func ~~~(s: Self)
static func <*><T>(s: Self, t: T)
static func <**><T>(t: T, s: Self) -> AssocType
static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ
// CHECK-LABEL: sil @_T019protocol_resilience3tttopyxlF
public prefix func ~~~<S>(s: S) {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ
// CHECK-LABEL: sil @_T019protocol_resilience3lmgoiyq__xtr0_lF
public func <*><T, S>(s: S, t: T) {}
// Swap the generic parameters to make sure we don't mix up our DeclContexts
// when mapping interface types in and out
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ
// CHECK-LABEL: sil @_T019protocol_resilience4lmmgoi9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF
public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ
// CHECK-LABEL: sil @_T019protocol_resilience5leeegoi9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF
public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {}
public protocol ReabstractSelfBase {
// No requirements
}
public protocol ReabstractSelfRefined : class, ReabstractSelfBase {
// A requirement with 'Self' abstracted as a class instance
var callback: (Self) -> Self { get set }
}
func id<T>(_ t: T) -> T {}
extension ReabstractSelfBase {
// A witness for the above requirement, but with 'Self' maximally abstracted
public var callback: (Self) -> Self {
get { return id }
nonmutating set { }
}
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvg : $@convention(witness_method: ReabstractSelfRefined) <τ_0_0 where τ_0_0 : ReabstractSelfRefined> (@guaranteed τ_0_0) -> @owned @callee_guaranteed (@owned τ_0_0) -> @owned τ_0_0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value %0 : $τ_0_0
// CHECK-NEXT: store [[SELF_COPY]] to [init] [[SELF_BOX]] : $*τ_0_0
// CHECK: [[WITNESS:%.*]] = function_ref @_T019protocol_resilience18ReabstractSelfBasePAAE8callbackxxcvg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS]]<τ_0_0>([[SELF_BOX]])
// CHECK: [[THUNK_FN:%.*]] = function_ref @_T0xxIegir_xxIegxo_19protocol_resilience21ReabstractSelfRefinedRzlTR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0>([[RESULT]])
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[THUNK]]
final class X : ReabstractSelfRefined {}
func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocoly010resilient_A005OtherdE0_pzF
func inoutResilientProtocol(_ x: inout OtherResilientProtocol) {
// CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm
inoutFunc(&x.propertyInExtension)
}
struct OtherConformingType : OtherResilientProtocol {}
// CHECK-LABEL: sil hidden @_T019protocol_resilience22inoutResilientProtocolyAA19OtherConformingTypeVzF
func inoutResilientProtocol(_ x: inout OtherConformingType) {
// CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivm
inoutFunc(&x.propertyInExtension)
// CHECK: function_ref @_T018resilient_protocol22OtherResilientProtocolPAAE25staticPropertyInExtensionSivmZ
inoutFunc(&OtherConformingType.staticPropertyInExtension)
}
// CHECK-LABEL: sil_default_witness_table P {
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientMethods {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.defaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP14defaultWitnessyyF
// CHECK-NEXT: method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP21anotherDefaultWitnessxSiF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypey05AssocI0QzF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirementy9AssocTypeQz_Si1btF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirementy9AssocTypeQz_qd__1ttlF
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @_T019protocol_resilience16ResilientMethodsP20staticDefaultWitnessxSiFZ
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientConstructors {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxyt7default_tcfC
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @_T019protocol_resilience21ResilientConstructorsPxSgyt17defaultIsOptional_tcfC
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientStorage {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.propertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP19propertyWithDefaultSivg
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivm
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvm
// CHECK-NEXT: method #ResilientStorage.subscript!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcig
// CHECK-NEXT: method #ResilientStorage.subscript!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcis
// CHECK-NEXT: method #ResilientStorage.subscript!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP1TQzAEcim
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!materializeForSet.1: {{.*}} : @_T019protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivm
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientOperators {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientOperators."~~~"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3tttopyxFZ
// CHECK-NEXT: method #ResilientOperators."<*>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP3lmgoiyx_qd__tlFZ
// CHECK-NEXT: method #ResilientOperators."<**>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP4lmmgoi9AssocTypeQzqd___xtlFZ
// CHECK-NEXT: method #ResilientOperators."<===>"!1: {{.*}} : @_T019protocol_resilience18ResilientOperatorsP5leeegoi9AssocTypeQyd__qd___xtAaBRd__lFZ
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvg
// CHECK-NEXT: method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvs
// CHECK-NEXT: method #ReabstractSelfRefined.callback!materializeForSet.1: {{.*}} : @_T019protocol_resilience21ReabstractSelfRefinedP8callbackxxcvm
// CHECK-NEXT: }
| apache-2.0 | 8e6beee76daa989ed5814a0bc47995a1 | 53.981073 | 291 | 0.78685 | 4.442773 | false | false | false | false |
kiliankoe/DVB | Sources/DVB/Models/RouteChange/RouteChange+Kind.swift | 1 | 1183 | extension RouteChange {
public enum Kind {
case scheduled
case amplifyingTransport
case shortTerm
case unknown(String)
public var rawValue: String {
switch self {
case .scheduled: return "Scheduled"
case .amplifyingTransport: return "AmplifyingTransport"
case .shortTerm: return "ShortTerm"
case .unknown(let value): return value
}
}
static var allCases: [Kind] {
return [.scheduled, .amplifyingTransport, .shortTerm]
}
}
}
extension RouteChange.Kind: Decodable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
if let kind = RouteChange.Kind.allCases.first(where: { $0.rawValue == value }) {
self = kind
} else {
print("Unknown routechange kind '\(value)', please open an issue on https://github.com/kiliankoe/DVB for this, thanks!")
self = .unknown(value)
}
}
}
extension RouteChange.Kind: Equatable {}
extension RouteChange.Kind: Hashable {}
| mit | cd44091e54b90af658cb963d434e46d2 | 30.131579 | 132 | 0.604396 | 4.603113 | false | false | false | false |
nathantannar4/NTComponents | NTComponents/Styling/Font.swift | 1 | 11928 | //
// Font.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 2/12/17.
//
// Typography defaults inspired by https://experience.sap.com/fiori-design-ios/article/typography/
//
import Foundation
import CoreFoundation
public enum NTPreferredFontStyle {
case title, subtitle, body, callout, caption, footnote, headline, subhead, disabled
}
public struct Font {
/// An internal reference to the fonts bundle.
private static var internalBundle: Bundle?
/// A public reference to the font bundle, that aims to detect the correct bundle to use.
public static var bundle: Bundle {
if nil == Font.internalBundle {
Font.internalBundle = Bundle(for: NTView.self)
let url = Font.internalBundle!.resourceURL!
let b = Bundle(url: url)
if let v = b {
Font.internalBundle = v
}
}
return Font.internalBundle!
}
/// Prints the available/loaded fonts
public static func whatIsAvailable() {
for family in UIFont.familyNames {
print("\(family)")
for name in UIFont.fontNames(forFamilyName: family) {
print("== \(name)")
}
}
}
/// Loads a custom font
///
/// - Parameters:
/// - fromBundle: The bundle the font is located under, defaults to Font.bundle
/// - name: The name of the font file
/// - withExtension: The extension of the font file
/// - size: The font size you would like returned, defaults 15
/// - Returns: A UIFont generated from the custom font file
@discardableResult
public static func load(fromBundle: Bundle = bundle, name: String?, withExtension: String = "ttf", withSize size: CGFloat = 15) -> UIFont? {
guard let name = name else {
return nil
}
// Check if font is already loaded
if UIFont.fontNames(forFamilyName: name).count != 0 {
return UIFont(name: name, size: size)
}
// Else try to load the font
guard let url = fromBundle.url(forResource: name, withExtension: withExtension) else {
Log.write(.error, "Failed to find the font: \(name).\(withExtension) in the supplied bundle")
return nil
}
guard let fontDataProvider = CGDataProvider(url: url as CFURL) else {
return nil
}
let font = CGFont(fontDataProvider)
var error: Unmanaged<CFError>?
guard CTFontManagerRegisterGraphicsFont(font!, &error) else {
Log.write(.error, "Failed to register font from file: \(name).\(withExtension)")
Log.write(.error, error.debugDescription)
return nil
}
return UIFont(name: name, size: size)
}
public struct Default {
public static var Title = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)
public static var Subtitle = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
public static var Body = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
public static var Callout = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
public static var Caption = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
public static var Footnote = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
public static var Headline = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
public static var Subhead = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
public static var Disabled = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
}
public struct Roboto {
public static let Regular = Font.load(name: "Roboto-Regular")!
public static let Thin = Font.load(name: "Roboto-Thin")!
public static let ThinItalic = Font.load(name: "Roboto-ThinItalic")!
public static let Italic = Font.load(name: "Roboto-Italic")!
public static let Light = Font.load(name: "Roboto-Light")!
public static let LightItalic = Font.load(name: "Roboto-LightItalic")!
public static let Medium = Font.load(name: "Roboto-Medium")!
public static let MediumItalic = Font.load(name: "Roboto-MediumItalic")!
public static let Bold = Font.load(name: "Roboto-Bold")!
public static let BoldItalic = Font.load(name: "Roboto-BoldItalic")!
public static let Black = Font.load(name: "Roboto-Black")!
public static let BlackItalic = Font.load(name: "Roboto-BlackItalic")!
}
public static let BebasNeue = Font.load(name: "BebasNeue", withExtension: "otf", withSize: 15)
}
public extension UILabel {
/**
Sets the textColor and font to that stored in Color.Default.Text and Font.Default
- parameter to: The style of your preferred font
- returns: Void
*/
func setPreferredFontStyle(to style: NTPreferredFontStyle) {
switch style {
case .title:
self.textColor = Color.Default.Text.Title
self.font = Font.Default.Title
case .subtitle:
self.textColor = Color.Default.Text.Subtitle
self.font = Font.Default.Subtitle
case .body:
self.textColor = Color.Default.Text.Body
self.font = Font.Default.Body
case .callout:
self.textColor = Color.Default.Text.Callout
self.font = Font.Default.Callout
case .caption:
self.textColor = Color.Default.Text.Caption
self.font = Font.Default.Caption
case .footnote:
self.textColor = Color.Default.Text.Footnote
self.font = Font.Default.Footnote
case .headline:
self.textColor = Color.Default.Text.Headline
self.font = Font.Default.Headline
case .subhead:
self.textColor = Color.Default.Text.Subhead
self.font = Font.Default.Subhead
case .disabled:
self.textColor = Color.Default.Text.Disabled
self.font = Font.Default.Disabled
}
}
}
public extension UITextField {
/**
Sets the textColor and font to that stored in Color.Default.Text and Font.Default
- parameter to: The style of your preferred font
- returns: Void
*/
func setPreferredFontStyle(to style: NTPreferredFontStyle) {
switch style {
case .title:
self.textColor = Color.Default.Text.Title
self.font = Font.Default.Title
case .subtitle:
self.textColor = Color.Default.Text.Subtitle
self.font = Font.Default.Subtitle
case .body:
self.textColor = Color.Default.Text.Body
self.font = Font.Default.Body
case .callout:
self.textColor = Color.Default.Text.Callout
self.font = Font.Default.Callout
case .caption:
self.textColor = Color.Default.Text.Caption
self.font = Font.Default.Caption
case .footnote:
self.textColor = Color.Default.Text.Footnote
self.font = Font.Default.Footnote
case .headline:
self.textColor = Color.Default.Text.Headline
self.font = Font.Default.Headline
case .subhead:
self.textColor = Color.Default.Text.Subhead
self.font = Font.Default.Subhead
case .disabled:
self.textColor = Color.Default.Text.Disabled
self.font = Font.Default.Disabled
}
}
}
public extension UITextView {
/**
Sets the textColor and font to that stored in Color.Default.Text and Font.Default
- parameter to: The style of your preferred font
- returns: Void
*/
func setPreferredFontStyle(to style: NTPreferredFontStyle) {
switch style {
case .title:
self.textColor = Color.Default.Text.Title
self.font = Font.Default.Title
case .subtitle:
self.textColor = Color.Default.Text.Subtitle
self.font = Font.Default.Subtitle
case .body:
self.textColor = Color.Default.Text.Body
self.font = Font.Default.Body
case .callout:
self.textColor = Color.Default.Text.Callout
self.font = Font.Default.Callout
case .caption:
self.textColor = Color.Default.Text.Caption
self.font = Font.Default.Caption
case .footnote:
self.textColor = Color.Default.Text.Footnote
self.font = Font.Default.Footnote
case .headline:
self.textColor = Color.Default.Text.Headline
self.font = Font.Default.Headline
case .subhead:
self.textColor = Color.Default.Text.Subhead
self.font = Font.Default.Subhead
case .disabled:
self.textColor = Color.Default.Text.Disabled
self.font = Font.Default.Disabled
}
}
}
public extension UIButton {
/**
Sets the textColor and font to that stored in Color.Default.Text and Font.Default
- parameter to: The style of your preferred font
- returns: Void
*/
func setPreferredFontStyle(to style: NTPreferredFontStyle) {
switch style {
case .title:
self.setTitleColor(Color.Default.Text.Title, for: .normal)
self.titleLabel?.font = Font.Default.Title
case .subtitle:
self.setTitleColor(Color.Default.Text.Subtitle, for: .normal)
self.titleLabel?.font = Font.Default.Subtitle
case .body:
self.setTitleColor(Color.Default.Text.Body, for: .normal)
self.titleLabel?.font = Font.Default.Body
case .callout:
self.setTitleColor(Color.Default.Text.Callout, for: .normal)
self.titleLabel?.font = Font.Default.Callout
case .caption:
self.setTitleColor(Color.Default.Text.Caption, for: .normal)
self.titleLabel?.font = Font.Default.Caption
case .footnote:
self.setTitleColor(Color.Default.Text.Footnote, for: .normal)
self.titleLabel?.font = Font.Default.Footnote
case .headline:
self.setTitleColor(Color.Default.Text.Headline, for: .normal)
self.titleLabel?.font = Font.Default.Headline
case .subhead:
self.setTitleColor(Color.Default.Text.Subhead, for: .normal)
self.titleLabel?.font = Font.Default.Subhead
case .disabled:
self.setTitleColor(Color.Default.Text.Disabled, for: .normal)
self.titleLabel?.font = Font.Default.Disabled
}
}
}
| mit | 171fe45ca057a73e7be74fbaa959e1ee | 39.568027 | 144 | 0.628825 | 4.505856 | false | false | false | false |
omiz/CarBooking | Pods/TRON/Source/DownloadAPIRequest.swift | 1 | 7166 | //
// DownloadAPIRequest.swift
// TRON
//
// Created by Denys Telezhkin on 11.09.16.
// Copyright © 2015 - present MLSDev. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import Alamofire
public enum DownloadRequestType {
/// Will create `NSURLSessionDownloadTask` using `downloadTaskWithRequest(_)` method
case download(DownloadRequest.DownloadFileDestination)
/// Will create `NSURLSessionDownloadTask` using `downloadTaskWithResumeData(_)` method
case downloadResuming(data: Data, destination: DownloadRequest.DownloadFileDestination)
}
/**
`DownloadAPIRequest` encapsulates download request creation logic, stubbing options, and response/error parsing.
*/
open class DownloadAPIRequest<Model, ErrorModel>: BaseRequest<Model,ErrorModel> {
/// DownloadAPIREquest type
let type : DownloadRequestType
/// Serialize download response into `Result<Model>`.
public typealias DownloadResponseParser = (_ request: URLRequest?, _ response: HTTPURLResponse?, _ url: URL?, _ error: Error?) -> Result<Model>
/// Serializes received failed response into APIError<ErrorModel> object
public typealias DownloadErrorParser = (Result<Model>?, _ request: URLRequest?, _ response: HTTPURLResponse?, _ url: URL?, _ error: Error?) -> APIError<ErrorModel>
/// Serializes received response into Result<Model>
open var responseParser : DownloadResponseParser
/// Serializes received error into APIError<ErrorModel>
open var errorParser : DownloadErrorParser
/// Closure that is applied to request before it is sent.
open var validationClosure: (DownloadRequest) -> DownloadRequest = { $0.validate() }
// Creates `DownloadAPIRequest` with specified `type`, `path` and configures it with to be used with `tron`.
public init<Serializer : ErrorHandlingDownloadResponseSerializerProtocol>(type: DownloadRequestType, path: String, tron: TRON, responseSerializer: Serializer)
where Serializer.SerializedObject == Model, Serializer.SerializedError == ErrorModel
{
self.type = type
self.responseParser = { request,response, data, error in
responseSerializer.serializeResponse(request,response,data,error)
}
self.errorParser = { result, request,response, data, error in
return responseSerializer.serializeError(result,request, response, data, error)
}
super.init(path: path, tron: tron)
}
override func alamofireRequest(from manager: SessionManager) -> Request? {
switch type {
case .download(let destination):
return manager.download(urlBuilder.url(forPath: path), method: method, parameters: parameters,
encoding: parameterEncoding,
headers: headerBuilder.headers(forAuthorizationRequirement: authorizationRequirement, including: headers),
to: destination)
case .downloadResuming(let data, let destination):
return manager.download(resumingWith: data, to: destination)
}
}
/**
Perform current request with completion block, that contains Alamofire.Response.
- parameter completion: Alamofire.Response completion block.
- returns: Alamofire.Request or nil if request was stubbed.
*/
@discardableResult
open func performCollectingTimeline(withCompletion completion: @escaping ((Alamofire.DownloadResponse<Model>) -> Void)) -> DownloadRequest? {
if performStub(completion: completion) {
return nil
}
return performAlamofireRequest(completion)
}
private func performAlamofireRequest(_ completion : @escaping (DownloadResponse<Model>) -> Void) -> DownloadRequest
{
guard let manager = tronDelegate?.manager else {
fatalError("Manager cannot be nil while performing APIRequest")
}
willSendRequest()
guard let request = alamofireRequest(from: manager) as? DownloadRequest else {
fatalError("Failed to receive DataRequest")
}
willSendAlamofireRequest(request)
if !tronDelegate!.manager.startRequestsImmediately {
request.resume()
}
didSendAlamofireRequest(request)
return validationClosure(request).response(queue: resultDeliveryQueue, responseSerializer: downloadResponseSerializer(with: request), completionHandler: { downloadResponse in
self.didReceiveDownloadResponse(downloadResponse, forRequest: request)
completion(downloadResponse)
})
}
internal func downloadResponseSerializer(with request: DownloadRequest) -> DownloadResponseSerializer<Model> {
return DownloadResponseSerializer<Model> { urlRequest, response, url, error in
self.willProcessResponse((urlRequest,response,nil,error), for: request)
var result : Alamofire.Result<Model>
var apiError : APIError<ErrorModel>?
var parsedModel : Model?
if let error = error {
apiError = self.errorParser(nil, urlRequest, response, url, error)
result = .failure(apiError!)
} else {
result = self.responseParser(urlRequest, response, url, error)
if let model = result.value {
parsedModel = model
result = .success(model)
} else {
apiError = self.errorParser(result, urlRequest, response, url, error)
result = .failure(apiError!)
}
}
if let error = apiError {
self.didReceiveError(error, for: (urlRequest,response,nil,error), request: request)
} else if let model = parsedModel {
self.didSuccessfullyParseResponse((urlRequest,response,nil,error), creating: model, forRequest: request)
}
return result
}
}
}
| mit | 15d88821cd699027e52efc03cb331dd7 | 45.225806 | 182 | 0.672435 | 5.391272 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxDataSources/Tests/RxDataSourcesTests/NumberSection.swift | 3 | 2189 | //
// NumberSection.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 1/7/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Differentiator
import RxDataSources
// MARK: Data
struct NumberSection {
var header: String
var numbers: [IntItem]
var updated: Date
init(header: String, numbers: [Item], updated: Date) {
self.header = header
self.numbers = numbers
self.updated = updated
}
}
struct IntItem {
let number: Int
let date: Date
}
// MARK: Just extensions to say how to determine identity and how to determine is entity updated
extension NumberSection
: AnimatableSectionModelType {
typealias Item = IntItem
typealias Identity = String
var identity: String {
return header
}
var items: [IntItem] {
return numbers
}
init(original: NumberSection, items: [Item]) {
self = original
self.numbers = items
}
}
extension NumberSection
: CustomDebugStringConvertible {
var debugDescription: String {
let interval = updated.timeIntervalSince1970
let numbersDescription = numbers.map { "\n\($0.debugDescription)" }.joined(separator: "")
return "NumberSection(header: \"\(self.header)\", numbers: \(numbersDescription)\n, updated: \(interval))"
}
}
extension IntItem
: IdentifiableType
, Equatable {
typealias Identity = Int
var identity: Int {
return number
}
}
// equatable, this is needed to detect changes
func == (lhs: IntItem, rhs: IntItem) -> Bool {
return lhs.number == rhs.number && lhs.date == rhs.date
}
// MARK: Some nice extensions
extension IntItem
: CustomDebugStringConvertible {
var debugDescription: String {
return "IntItem(number: \(number), date: \(date.timeIntervalSince1970))"
}
}
extension IntItem
: CustomStringConvertible {
var description: String {
return "\(number)"
}
}
extension NumberSection: Equatable {
}
func == (lhs: NumberSection, rhs: NumberSection) -> Bool {
return lhs.header == rhs.header && lhs.items == rhs.items && lhs.updated == rhs.updated
}
| mit | b40a8879393fb1ee38a420af4f0dbcb6 | 20.663366 | 114 | 0.65585 | 4.447154 | false | false | false | false |
efremidze/Cluster | Example/Extensions.swift | 1 | 1760 | //
// Extensions.swift
// Cluster
//
// Created by Lasha Efremidze on 7/8/17.
// Copyright © 2017 efremidze. All rights reserved.
//
import UIKit
import MapKit
extension UIImage {
func filled(with color: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(size, false, scale)
color.setFill()
guard let context = UIGraphicsGetCurrentContext() else { return self }
context.translateBy(x: 0, y: size.height)
context.scaleBy(x: 1.0, y: -1.0);
context.setBlendMode(CGBlendMode.normal)
let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
guard let mask = self.cgImage else { return self }
context.clip(to: rect, mask: mask)
context.fill(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
static let pin = UIImage(named: "pin")?.filled(with: .green)
static let pin2 = UIImage(named: "pin2")?.filled(with: .green)
static let me = UIImage(named: "me")?.filled(with: .blue)
}
extension UIColor {
class var green: UIColor { return UIColor(red: 76 / 255, green: 217 / 255, blue: 100 / 255, alpha: 1) }
class var blue: UIColor { return UIColor(red: 0, green: 122 / 255, blue: 1, alpha: 1) }
}
extension MKMapView {
func annotationView<T: MKAnnotationView>(of type: T.Type, annotation: MKAnnotation?, reuseIdentifier: String) -> T {
guard let annotationView = dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? T else {
return type.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
}
annotationView.annotation = annotation
return annotationView
}
}
| mit | 67ebfaef6b6270eedc35523b0d68f362 | 34.897959 | 120 | 0.66174 | 4.198091 | false | false | false | false |
thehung111/visearch-widget-swift | Carthage/Checkouts/visearch-sdk-swift/ViSearchSDK/ViSearchSDK/Classes/ViSearch.swift | 2 | 4758 | import Foundation
/// wrapper for various API calls
/// create shared client
open class ViSearch: NSObject {
public static let sharedInstance = ViSearch()
public var client : ViSearchClient?
private override init(){
super.init()
}
/// Check if search client is setup properly
///
/// - returns: true if client is setup
public func isClientSetup() -> Bool {
return client != nil
}
// MARK: setup
/// Setup API client. Must be called first before various API calls
///
/// - parameter accessKey: application access key
/// - parameter secret: application secret key
public func setup(accessKey: String, secret: String) -> Void {
if client == nil {
client = ViSearchClient(accessKey: accessKey, secret: secret)
}
client?.accessKey = accessKey
client?.secret = secret
client?.isAppKeyEnabled = false
}
/// Setup API client. Must be called first before various API calls
///
/// - parameter appKey: application app key
public func setup(appKey: String) -> Void {
if client == nil {
client = ViSearchClient(appKey: appKey)
}
client?.accessKey = appKey
client?.isAppKeyEnabled = true
}
// MARK: API calls
/// Search by Image API
@discardableResult public func uploadSearch(params: ViUploadSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler) -> URLSessionTask?
{
if let client = client {
return client.uploadSearch(params: params, successHandler: successHandler, failureHandler: failureHandler);
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// Search by Color API
@discardableResult public func colorSearch(params: ViColorSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.colorSearch(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// Find Similar API
@discardableResult public func findSimilar(params: ViSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.findSimilar(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// You may also like API
@discardableResult public func recommendation(params: ViSearchParams,
successHandler: @escaping ViSearchClient.SuccessHandler,
failureHandler: @escaping ViSearchClient.FailureHandler
) -> URLSessionTask?
{
if let client = client {
return client.recommendation(params: params, successHandler: successHandler, failureHandler: failureHandler)
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
return nil
}
/// track the API calls and various actions
/// Tracking API
@discardableResult public func track(params: ViTrackParams,
handler: ( (_ success: Bool, Error?) -> Void )?
) -> Void {
if let client = client {
client.track(params: params, handler: handler)
return
}
print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized. Please call setup(accessKey, secret) before using the API.")
}
}
| mit | dfefa7eb6111667a790be67975bfeb10 | 36.464567 | 157 | 0.578815 | 5.788321 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Banking | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Models/Watson/Problem/TradeoffProblem.swift | 1 | 1693 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
/**
* This class represents a Watson Problem, including columns (TradeoffObjectiveDefinition), a subject (string), and options (TradeoffOption).
*/
class TradeoffProblem{
/// Objectives array of TradeoffObjectiveDefinitions
var columns : [TradeoffObjectiveDefinition]
/// Subject of Problem
var subject : String
/// Options array of TradeoffOptions
var options : [TradeoffOption]
/**
Initializes a TradeoffProblem object with TradeoffObjectiveDefinitions, a subject, and TradeoffOptions
- parameter columns: TradeoffObjectiveDefinitions passed in
- parameter subject: subject string
- parameter options: TradeoffOptions passed in
- returns: TradeoffProblem object
*/
init(columns : [TradeoffObjectiveDefinition], subject : String, options : [TradeoffOption]) {
self.columns = columns
self.subject = subject
self.options = options
}
/**
This method will return a dictionary object of a TradeoffProblem
- returns: Dictionary object
*/
func convertToDictionary() -> [NSObject : AnyObject] {
var columnsDictArr : [[NSObject : AnyObject]] = []
for column in self.columns {
columnsDictArr.append(column.convertToDictionary())
}
var optionsDictArr : [[NSObject : AnyObject]] = []
for option in self.options {
optionsDictArr.append(option.convertToDictionary())
}
return ["columns" : columnsDictArr, "subject" : self.subject, "options" : optionsDictArr]
}
}
| epl-1.0 | 8dc70eaa8f0d2eafe65c08d0929350ac | 30.924528 | 141 | 0.665485 | 5.174312 | false | false | false | false |
mvader/advent-of-code | 2021/21/01.swift | 1 | 752 | struct Dice {
var rolls = 0
mutating func roll() -> Int {
rolls += 1
return rolls
}
mutating func roll(_ n: Int) -> Int {
var result = 0
for _ in 0 ..< n {
result += roll()
}
return result
}
}
struct Player {
var pos: Int
var score = 0
mutating func move(_ steps: Int) {
let n = (pos + steps) % 10
pos = n == 0 ? 10 : n
score += pos
}
}
func play(_ player1: Player, _ player2: Player) -> Int {
var (player1, player2, dice) = (player1, player2, Dice())
while true {
player1.move(dice.roll(3))
if player1.score >= 1000 {
return player2.score * dice.rolls
}
player2.move(dice.roll(3))
if player2.score >= 1000 {
return player1.score * dice.rolls
}
}
}
print(play(Player(pos: 3), Player(pos: 10)))
| mit | 6370f77cd3f796c2f40a962458dd16a2 | 16.090909 | 58 | 0.593085 | 2.676157 | false | false | false | false |
ejeinc/MetalScope | Sources/StereoScene.swift | 1 | 7644 | //
// StereoScene.swift
// MetalScope
//
// Created by Jun Tanaka on 2017/01/23.
// Copyright © 2017 eje Inc. All rights reserved.
//
#if (arch(arm) || arch(arm64)) && os(iOS)
import SceneKit
internal final class StereoScene: SCNScene {
var stereoTexture: MTLTexture? {
didSet {
attachTextureToMesh()
}
}
var stereoParameters: StereoParametersProtocol? {
didSet {
guard let parameters = stereoParameters else {
return
}
updateMesh(with: parameters)
attachTextureToMesh()
}
}
lazy var pointOfView: SCNNode = {
let camera = SCNCamera()
camera.usesOrthographicProjection = true
camera.orthographicScale = 0.5
camera.zNear = 0
let node = SCNNode()
node.camera = camera
node.position = SCNVector3(0, 0, 0.01)
self.rootNode.addChildNode(node)
return node
}()
private lazy var meshNode: SCNNode = {
let node = SCNNode()
self.rootNode.addChildNode(node)
return node
}()
private func attachTextureToMesh() {
meshNode.geometry?.firstMaterial?.diffuse.contents = stereoTexture
}
private func updateMesh(with parameters: StereoParametersProtocol, width: Int = 40, height: Int = 40) {
let (vertices, texcoord) = computeMeshPoints(with: parameters, width: width, height: height)
let colors = computeMeshColors(width: width, height: height)
let indices = computeMeshIndices(width: width, height: height)
let mesh = SCNGeometry(
sources: [
SCNGeometrySource(vertices: vertices, count: vertices.count),
SCNGeometrySource(texcoord: texcoord),
SCNGeometrySource(colors: colors)
],
elements: [
SCNGeometryElement(indices: indices, primitiveType: .triangles)
]
)
let material = SCNMaterial()
material.isDoubleSided = true
mesh.materials = [material]
meshNode.geometry = mesh
}
}
private extension StereoScene {
/// Most of the code in this section was originally ported from Google's Cardboard SDK for Unity
/// https://github.com/googlevr/gvr-unity-sdk/blob/v0.6/Cardboard/Scripts/CardboardPostRender.cs
func computeMeshPoints(with parameters: StereoParametersProtocol, width: Int, height: Int) -> (vertices: [SCNVector3], texcoord: [float2]) {
let viewer = parameters.viewer
let screen = parameters.screen
var lensFrustum = parameters.leftEyeVisibleTanAngles
var noLensFrustum = parameters.leftEyeNoLensVisibleTanAngles
var viewport = parameters.leftEyeVisibleScreenRect
let count = 2 * width * height
var vertices: [SCNVector3] = Array(repeating: SCNVector3Zero, count: count)
var texcoord: [float2] = Array(repeating: float2(), count: count)
var vid = 0
func lerp(_ a: Float, _ b: Float, _ t: Float) -> Float {
return a + t * (b - a)
}
for e in 0..<2 {
for j in 0..<height {
for i in 0..<width {
defer { vid += 1 }
var u = Float(i) / Float(width - 1)
var v = Float(j) / Float(height - 1)
var s = u
var t = v
let x = lerp(lensFrustum[0], lensFrustum[2], u)
let y = lerp(lensFrustum[3], lensFrustum[1], v)
let d = sqrt(x * x + y * y)
let r = viewer.distortion.distortInv(d)
let p = x * r / d
let q = y * r / d
u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0])
v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3])
u = (Float(viewport.origin.x) + u * Float(viewport.size.width) - 0.5) * screen.aspectRatio
v = Float(viewport.origin.y) + v * Float(viewport.size.height) - 0.5
vertices[vid] = SCNVector3(u, v, 0)
s = (s + Float(e)) / 2
t = 1 - t // flip vertically
texcoord[vid] = float2(s, t)
}
}
var w: Float
w = lensFrustum[2] - lensFrustum[0]
lensFrustum[0] = -(w + lensFrustum[0])
lensFrustum[2] = w - lensFrustum[2]
w = noLensFrustum[2] - noLensFrustum[0]
noLensFrustum[0] = -(w + noLensFrustum[0])
noLensFrustum[2] = w - noLensFrustum[2]
viewport.origin.x = 1 - (viewport.origin.x + viewport.size.width)
}
return (vertices, texcoord)
}
func computeMeshColors(width: Int, height: Int) -> [SCNVector3] {
let count = 2 * width * height
var colors: [SCNVector3] = Array(repeating: SCNVector3(1, 1, 1), count: count)
var vid = 0
for _ in 0..<2 {
for j in 0..<height {
for i in 0..<width {
defer { vid += 1 }
if i == 0 || j == 0 || i == (width - 1) || j == (height - 1) {
colors[vid] = SCNVector3Zero
}
}
}
}
return colors
}
func computeMeshIndices(width: Int, height: Int) -> [Int16] {
let halfWidth = width / 2
let halfHeight = height / 2
var indices: [Int16] = []
var vid = 0
for _ in 0..<2 {
for j in 0..<height {
for i in 0..<width {
defer { vid += 1 }
if i == 0 || j == 0 {
// do nothing
} else if (i <= halfWidth) == (j <= halfHeight) {
indices.append(Int16(vid))
indices.append(Int16(vid - width))
indices.append(Int16(vid - width - 1))
indices.append(Int16(vid - width - 1))
indices.append(Int16(vid - 1))
indices.append(Int16(vid))
} else {
indices.append(Int16(vid - 1))
indices.append(Int16(vid))
indices.append(Int16(vid - width))
indices.append(Int16(vid - width))
indices.append(Int16(vid - width - 1))
indices.append(Int16(vid - 1))
}
}
}
}
return indices
}
}
private extension SCNGeometrySource {
convenience init(texcoord vectors: [float2]) {
self.init(
data: Data(bytes: vectors, count: vectors.count * MemoryLayout<float2>.size),
semantic: .texcoord,
vectorCount: vectors.count,
usesFloatComponents: true,
componentsPerVector: 2,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<float2>.size
)
}
convenience init(colors vectors: [SCNVector3]) {
self.init(
data: Data(bytes: vectors, count: vectors.count * MemoryLayout<SCNVector3>.size),
semantic: .color,
vectorCount: vectors.count,
usesFloatComponents: true,
componentsPerVector: 3,
bytesPerComponent: MemoryLayout<Float>.size,
dataOffset: 0,
dataStride: MemoryLayout<SCNVector3>.size
)
}
}
#endif
| mit | c10990c0ef269f62c96f5d189716b06b | 32.375546 | 144 | 0.516813 | 4.490599 | false | false | false | false |
Ribeiro/PapersPlease | Classes/ValidationTypes/ValidatorRegexType.swift | 1 | 1096 | //
// ValidatorRegexType.swift
// PapersPlease
//
// Created by Brett Walker on 7/4/14.
// Copyright (c) 2014 Poet & Mountain, LLC. All rights reserved.
//
import Foundation
class ValidatorRegexType:ValidatorType {
var regexString = ""
override func isTextValid(text: String) -> Bool {
var error:NSError? = nil
self.valid = false
if let regex = NSRegularExpression(pattern: self.regexString, options: .CaseInsensitive, error: &error) {
let num_matches:Int = regex.numberOfMatchesInString(text, options: .ReportProgress, range: NSMakeRange(0, count(text.utf16)))
self.valid = (num_matches == 1)
}
// update states
self.validationStates.removeAll()
(self.valid) ? (self.validationStates.append(self.status.valid))
: (self.validationStates.append(self.status.invalid))
return self.valid
}
class override func type() -> String {
return "ValidationTypeRegex"
}
} | mit | 5f4bed6baa7580d019e7d25867e6721c | 25.756098 | 137 | 0.589416 | 4.491803 | false | false | false | false |
cpageler93/RAML-Swift | Sources/Example.swift | 1 | 3890 | //
// TypeExample.swift
// RAML
//
// Created by Christoph Pageler on 24.06.17.
//
import Foundation
import Yaml
public class Example: HasAnnotations {
public var identifier: String
public var displayName: String?
public var description: String?
public var annotations: [Annotation]?
public var value: [Yaml: Yaml]?
public var strict: Bool?
public init(identifier: String) {
self.identifier = identifier
}
internal init() {
self.identifier = ""
}
}
// MARK: Parsing Example
internal extension RAML {
internal func parseExampleOrExamples(yamlDict: [Yaml: Yaml]?) throws -> [Example]? {
guard let yamlDict = yamlDict else { return nil }
if let examplesYaml = yamlDict["examples"]?.dictionary {
return try parseExamples(dict: examplesYaml)
}
if let yamlDict = yamlDict["example"] {
return try parseExample(yaml: yamlDict)
}
return nil
}
private func parseExample(yaml: Yaml) throws -> [Example]? {
switch yaml {
case .array(let yamlArray):
return try parseExamples(array: yamlArray)
case .dictionary:
return try [parseExample(identifier: "Example 1", yaml: yaml)]
default:
return nil
}
}
private func parseExamples(array: [Yaml]) throws -> [Example] {
var examples: [Example] = []
for (index, exampleYaml) in array.enumerated() {
let example = try parseExample(identifier: "Example \(index+1)", yaml: exampleYaml)
examples.append(example)
}
return examples
}
private func parseExamples(dict: [Yaml: Yaml]) throws -> [Example] {
var examples: [Example] = []
for (key, value) in dict {
guard let keyString = key.string else {
throw RAMLError.ramlParsingError(.invalidDataType(for: "Example Key", mustBeKindOf: "String"))
}
let example = try parseExample(identifier: keyString, yaml: value)
examples.append(example)
}
return examples
}
private func parseExample(identifier: String, yaml: Yaml) throws -> Example {
let example = Example(identifier: identifier)
if let valueDict = yaml["value"].dictionary {
example.displayName = yaml["displayName"].string
example.description = yaml["description"].string
example.annotations = try parseAnnotations(ParseInput(yaml))
example.strict = yaml["strict"].bool
example.value = valueDict
} else {
example.value = yaml.dictionary
}
return example
}
}
public protocol HasExamples {
var examples: [Example]? { get set }
}
public extension HasExamples {
public func exampleWith(identifier: String) -> Example? {
for example in examples ?? [] {
if example.identifier == identifier {
return example
}
}
return nil
}
public func hasExampleWith(identifier: String) -> Bool {
return exampleWith(identifier: identifier) != nil
}
}
// MARK: Default Values
public extension Example {
public convenience init(initWithDefaultsBasedOn example: Example) {
self.init()
self.identifier = example.identifier
self.displayName = example.displayName
self.description = example.description
self.annotations = example.annotations?.map { $0.applyDefaults() }
self.value = example.value
self.strict = example.strict
}
public func applyDefaults() -> Example {
return Example(initWithDefaultsBasedOn: self)
}
}
| mit | 528ecbd3e30129b411976ae884023f50 | 26.588652 | 110 | 0.585861 | 4.838308 | false | false | false | false |
mnisn/zhangchu | zhangchu/Pods/Alamofire/Source/Manager.swift | 12 | 39437 | //
// Manager.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
*/
public class Manager {
// MARK: - Properties
/**
A shared instance of `Manager`, used by top-level Alamofire request methods, and suitable for use directly
for any ad hoc requests.
*/
public static let sharedInstance: Manager = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see https://tools.ietf.org/html/rfc7230#section-4.2.3
let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5"
// Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage = NSLocale.preferredLanguages().prefix(6).enumerate().map { index, languageCode in
let quality = 1.0 - (Double(index) * 0.1)
return "\(languageCode);q=\(quality)"
}.joinWithSeparator(", ")
// User-Agent Header; see https://tools.ietf.org/html/rfc7231#section-5.5.3
// Example: `iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 9.3.0) Alamofire/3.4.2`
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown"
let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown"
let appVersion = info["CFBundleShortVersionString"] as? String ?? "Unknown"
let appBuild = info[kCFBundleVersionKey as String] as? String ?? "Unknown"
let osNameVersion: String = {
let versionString: String
if #available(OSX 10.10, *) {
let version = NSProcessInfo.processInfo().operatingSystemVersion
versionString = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
} else {
versionString = "10.9"
}
let osName: String = {
#if os(iOS)
return "iOS"
#elseif os(watchOS)
return "watchOS"
#elseif os(tvOS)
return "tvOS"
#elseif os(OSX)
return "OS X"
#elseif os(Linux)
return "Linux"
#else
return "Unknown"
#endif
}()
return "\(osName) \(versionString)"
}()
let alamofireVersion: String = {
guard
let afInfo = NSBundle(forClass: Manager.self).infoDictionary,
build = afInfo["CFBundleShortVersionString"]
else { return "Unknown" }
return "Alamofire/\(build)"
}()
return "\(executable)/\(appVersion) (\(bundle); build:\(appBuild); \(osNameVersion)) \(alamofireVersion)"
}
return "Alamofire"
}()
return [
"Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent
]
}()
let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// The session delegate handling all the task and session delegate callbacks.
public let delegate: SessionDelegate
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
The background completion handler closure provided by the UIApplicationDelegate
`application:handleEventsForBackgroundURLSession:completionHandler:` method. By setting the background
completion handler, the SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` closure implementation
will automatically call the handler.
If you need to handle your own events before the handler is called, then you need to override the
SessionDelegate `sessionDidFinishEventsForBackgroundURLSession` and manually call the handler when finished.
`nil` by default.
*/
public var backgroundCompletionHandler: (() -> Void)?
// MARK: - Lifecycle
/**
Initializes the `Manager` instance with the specified configuration, delegate and server trust policy.
- parameter configuration: The configuration used to construct the managed session.
`NSURLSessionConfiguration.defaultSessionConfiguration()` by default.
- parameter delegate: The delegate used when initializing the session. `SessionDelegate()` by
default.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance.
*/
public init(
configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: SessionDelegate = SessionDelegate(),
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
self.delegate = delegate
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
/**
Initializes the `Manager` instance with the specified session, delegate and server trust policy.
- parameter session: The URL session.
- parameter delegate: The delegate of the URL session. Must equal the URL session's delegate.
- parameter serverTrustPolicyManager: The server trust policy manager to use for evaluating all server trust
challenges. `nil` by default.
- returns: The new `Manager` instance if the URL session's delegate matches the delegate parameter.
*/
public init?(
session: NSURLSession,
delegate: SessionDelegate,
serverTrustPolicyManager: ServerTrustPolicyManager? = nil)
{
guard delegate === session.delegate else { return nil }
self.delegate = delegate
self.session = session
commonInit(serverTrustPolicyManager: serverTrustPolicyManager)
}
private func commonInit(serverTrustPolicyManager serverTrustPolicyManager: ServerTrustPolicyManager?) {
session.serverTrustPolicyManager = serverTrustPolicyManager
delegate.sessionDidFinishEventsForBackgroundURLSession = { [weak self] session in
guard let strongSelf = self else { return }
dispatch_async(dispatch_get_main_queue()) { strongSelf.backgroundCompletionHandler?() }
}
}
deinit {
session.invalidateAndCancel()
}
// MARK: - Request
/**
Creates a request for the specified method, URL string, parameters, parameter encoding and headers.
- parameter method: The HTTP method.
- parameter URLString: The URL string.
- parameter parameters: The parameters. `nil` by default.
- parameter encoding: The parameter encoding. `.URL` by default.
- parameter headers: The HTTP headers. `nil` by default.
- returns: The created request.
*/
public func request(
method: Method,
_ URLString: URLStringConvertible,
parameters: [String: AnyObject]? = nil,
encoding: ParameterEncoding = .URL,
headers: [String: String]? = nil)
-> Request
{
let mutableURLRequest = URLRequest(method, URLString, headers: headers)
let encodedURLRequest = encoding.encode(mutableURLRequest, parameters: parameters).0
return request(encodedURLRequest)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
- parameter URLRequest: The URL request
- returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
var dataTask: NSURLSessionDataTask!
dispatch_sync(queue) { dataTask = self.session.dataTaskWithRequest(URLRequest.URLRequest) }
let request = Request(session: session, task: dataTask)
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: - SessionDelegate
/**
Responsible for handling all delegate callbacks for the underlying session.
*/
public class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate] = [:]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
/// Access the task delegate for the specified task in a thread-safe manner.
public subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
var subdelegate: Request.TaskDelegate?
dispatch_sync(subdelegateQueue) { subdelegate = self.subdelegates[task.taskIdentifier] }
return subdelegate
}
set {
dispatch_barrier_async(subdelegateQueue) { self.subdelegates[task.taskIdentifier] = newValue }
}
}
/**
Initializes the `SessionDelegate` instance.
- returns: The new `SessionDelegate` instance.
*/
public override init() {
super.init()
}
// MARK: - NSURLSessionDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didBecomeInvalidWithError:`.
public var sessionDidBecomeInvalidWithError: ((NSURLSession, NSError?) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:`.
public var sessionDidReceiveChallenge: ((NSURLSession, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionDelegate method `URLSession:didReceiveChallenge:completionHandler:` and requires the caller to call the `completionHandler`.
public var sessionDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDelegate method `URLSessionDidFinishEventsForBackgroundURLSession:`.
public var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the session has been invalidated.
- parameter session: The session object that was invalidated.
- parameter error: The error that caused invalidation, or nil if the invalidation was explicit.
*/
public func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
/**
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
- parameter session: The session containing the task that requested authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void))
{
guard sessionDidReceiveChallengeWithCompletion == nil else {
sessionDidReceiveChallengeWithCompletion?(session, challenge, completionHandler)
return
}
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if let sessionDidReceiveChallenge = sessionDidReceiveChallenge {
(disposition, credential) = sessionDidReceiveChallenge(session, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let
serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicyForHost(host),
serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluateServerTrust(serverTrust, isValidForHost: host) {
disposition = .UseCredential
credential = NSURLCredential(forTrust: serverTrust)
} else {
disposition = .CancelAuthenticationChallenge
}
}
}
completionHandler(disposition, credential)
}
/**
Tells the delegate that all messages enqueued for a session have been delivered.
- parameter session: The session that no longer has any outstanding requests.
*/
public func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: - NSURLSessionTaskDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:`.
public var taskWillPerformHTTPRedirection: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest) -> NSURLRequest?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskWillPerformHTTPRedirectionWithCompletion: ((NSURLSession, NSURLSessionTask, NSHTTPURLResponse, NSURLRequest, NSURLRequest? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:`.
public var taskDidReceiveChallenge: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:task:didReceiveChallenge:completionHandler:` and
/// requires the caller to call the `completionHandler`.
public var taskDidReceiveChallengeWithCompletion: ((NSURLSession, NSURLSessionTask, NSURLAuthenticationChallenge, (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:`.
public var taskNeedNewBodyStream: ((NSURLSession, NSURLSessionTask) -> NSInputStream?)?
/// Overrides all behavior for NSURLSessionTaskDelegate method `URLSession:session:task:needNewBodyStream:` and
/// requires the caller to call the `completionHandler`.
public var taskNeedNewBodyStreamWithCompletion: ((NSURLSession, NSURLSessionTask, NSInputStream? -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend:`.
public var taskDidSendBodyData: ((NSURLSession, NSURLSessionTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionTaskDelegate method `URLSession:task:didCompleteWithError:`.
public var taskDidComplete: ((NSURLSession, NSURLSessionTask, NSError?) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the remote server requested an HTTP redirect.
- parameter session: The session containing the task whose request resulted in a redirect.
- parameter task: The task whose request resulted in a redirect.
- parameter response: An object containing the server’s response to the original request.
- parameter request: A URL request object filled out with the new location.
- parameter completionHandler: A closure that your handler should call with either the value of the request
parameter, a modified URL request object, or NULL to refuse the redirect and
return the body of the redirect response.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
willPerformHTTPRedirection response: NSHTTPURLResponse,
newRequest request: NSURLRequest,
completionHandler: NSURLRequest? -> Void)
{
guard taskWillPerformHTTPRedirectionWithCompletion == nil else {
taskWillPerformHTTPRedirectionWithCompletion?(session, task, response, request, completionHandler)
return
}
var redirectRequest: NSURLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
/**
Requests credentials from the delegate in response to an authentication request from the remote server.
- parameter session: The session containing the task whose request requires authentication.
- parameter task: The task whose request requires authentication.
- parameter challenge: An object that contains the request for authentication.
- parameter completionHandler: A handler that your delegate method must call providing the disposition and credential.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)
{
guard taskDidReceiveChallengeWithCompletion == nil else {
taskDidReceiveChallengeWithCompletion?(session, task, challenge, completionHandler)
return
}
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
let result = taskDidReceiveChallenge(session, task, challenge)
completionHandler(result.0, result.1)
} else if let delegate = self[task] {
delegate.URLSession(
session,
task: task,
didReceiveChallenge: challenge,
completionHandler: completionHandler
)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
/**
Tells the delegate when a task requires a new request body stream to send to the remote server.
- parameter session: The session containing the task that needs a new body stream.
- parameter task: The task that needs a new body stream.
- parameter completionHandler: A completion handler that your delegate method should call with the new body stream.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
needNewBodyStream completionHandler: NSInputStream? -> Void)
{
guard taskNeedNewBodyStreamWithCompletion == nil else {
taskNeedNewBodyStreamWithCompletion?(session, task, completionHandler)
return
}
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
completionHandler(taskNeedNewBodyStream(session, task))
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
/**
Periodically informs the delegate of the progress of sending body content to the server.
- parameter session: The session containing the data task.
- parameter task: The data task.
- parameter bytesSent: The number of bytes sent since the last time this delegate method was called.
- parameter totalBytesSent: The total number of bytes sent so far.
- parameter totalBytesExpectedToSend: The expected length of the body data.
*/
public func URLSession(
session: NSURLSession,
task: NSURLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(
session,
task: task,
didSendBodyData: bytesSent,
totalBytesSent: totalBytesSent,
totalBytesExpectedToSend: totalBytesExpectedToSend
)
}
}
/**
Tells the delegate that the task finished transferring data.
- parameter session: The session containing the task whose request finished transferring data.
- parameter task: The task whose request finished transferring data.
- parameter error: If an error occurred, an error object indicating how the transfer failed, otherwise nil.
*/
public func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidComplete = taskDidComplete {
taskDidComplete(session, task, error)
} else if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
NSNotificationCenter.defaultCenter().postNotificationName(Notifications.Task.DidComplete, object: task)
self[task] = nil
}
// MARK: - NSURLSessionDataDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:`.
public var dataTaskDidReceiveResponse: ((NSURLSession, NSURLSessionDataTask, NSURLResponse) -> NSURLSessionResponseDisposition)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskDidReceiveResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSURLResponse, NSURLSessionResponseDisposition -> Void) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didBecomeDownloadTask:`.
public var dataTaskDidBecomeDownloadTask: ((NSURLSession, NSURLSessionDataTask, NSURLSessionDownloadTask) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:didReceiveData:`.
public var dataTaskDidReceiveData: ((NSURLSession, NSURLSessionDataTask, NSData) -> Void)?
/// Overrides default behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:`.
public var dataTaskWillCacheResponse: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse) -> NSCachedURLResponse?)?
/// Overrides all behavior for NSURLSessionDataDelegate method `URLSession:dataTask:willCacheResponse:completionHandler:` and
/// requires caller to call the `completionHandler`.
public var dataTaskWillCacheResponseWithCompletion: ((NSURLSession, NSURLSessionDataTask, NSCachedURLResponse, NSCachedURLResponse? -> Void) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that the data task received the initial reply (headers) from the server.
- parameter session: The session containing the data task that received an initial reply.
- parameter dataTask: The data task that received an initial reply.
- parameter response: A URL response object populated with headers.
- parameter completionHandler: A completion handler that your code calls to continue the transfer, passing a
constant to indicate whether the transfer should continue as a data task or
should become a download task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didReceiveResponse response: NSURLResponse,
completionHandler: NSURLSessionResponseDisposition -> Void)
{
guard dataTaskDidReceiveResponseWithCompletion == nil else {
dataTaskDidReceiveResponseWithCompletion?(session, dataTask, response, completionHandler)
return
}
var disposition: NSURLSessionResponseDisposition = .Allow
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
/**
Tells the delegate that the data task was changed to a download task.
- parameter session: The session containing the task that was replaced by a download task.
- parameter dataTask: The data task that was replaced by a download task.
- parameter downloadTask: The new download task that replaced the data task.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask)
{
if let dataTaskDidBecomeDownloadTask = dataTaskDidBecomeDownloadTask {
dataTaskDidBecomeDownloadTask(session, dataTask, downloadTask)
} else {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
}
/**
Tells the delegate that the data task has received some of the expected data.
- parameter session: The session containing the data task that provided data.
- parameter dataTask: The data task that provided data.
- parameter data: A data object containing the transferred data.
*/
public func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
}
/**
Asks the delegate whether the data (or upload) task should store the response in the cache.
- parameter session: The session containing the data (or upload) task.
- parameter dataTask: The data (or upload) task.
- parameter proposedResponse: The default caching behavior. This behavior is determined based on the current
caching policy and the values of certain received headers, such as the Pragma
and Cache-Control headers.
- parameter completionHandler: A block that your handler must call, providing either the original proposed
response, a modified version of that response, or NULL to prevent caching the
response. If your delegate implements this method, it must call this completion
handler; otherwise, your app leaks memory.
*/
public func URLSession(
session: NSURLSession,
dataTask: NSURLSessionDataTask,
willCacheResponse proposedResponse: NSCachedURLResponse,
completionHandler: NSCachedURLResponse? -> Void)
{
guard dataTaskWillCacheResponseWithCompletion == nil else {
dataTaskWillCacheResponseWithCompletion?(session, dataTask, proposedResponse, completionHandler)
return
}
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
completionHandler(dataTaskWillCacheResponse(session, dataTask, proposedResponse))
} else if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(
session,
dataTask: dataTask,
willCacheResponse: proposedResponse,
completionHandler: completionHandler
)
} else {
completionHandler(proposedResponse)
}
}
// MARK: - NSURLSessionDownloadDelegate
// MARK: Override Closures
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didFinishDownloadingToURL:`.
public var downloadTaskDidFinishDownloadingToURL: ((NSURLSession, NSURLSessionDownloadTask, NSURL) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:`.
public var downloadTaskDidWriteData: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
/// Overrides default behavior for NSURLSessionDownloadDelegate method `URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes:`.
public var downloadTaskDidResumeAtOffset: ((NSURLSession, NSURLSessionDownloadTask, Int64, Int64) -> Void)?
// MARK: Delegate Methods
/**
Tells the delegate that a download task has finished downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that finished.
- parameter location: A file URL for the temporary file. Because the file is temporary, you must either
open the file for reading or move it to a permanent location in your app’s sandbox
container directory before returning from this delegate method.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
}
/**
Periodically informs the delegate about the download’s progress.
- parameter session: The session containing the download task.
- parameter downloadTask: The download task.
- parameter bytesWritten: The number of bytes transferred since the last time this delegate
method was called.
- parameter totalBytesWritten: The total number of bytes transferred so far.
- parameter totalBytesExpectedToWrite: The expected length of the file, as provided by the Content-Length
header. If this header was not provided, the value is
`NSURLSessionTransferSizeUnknown`.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didWriteData: bytesWritten,
totalBytesWritten: totalBytesWritten,
totalBytesExpectedToWrite: totalBytesExpectedToWrite
)
}
}
/**
Tells the delegate that the download task has resumed downloading.
- parameter session: The session containing the download task that finished.
- parameter downloadTask: The download task that resumed. See explanation in the discussion.
- parameter fileOffset: If the file's cache policy or last modified date prevents reuse of the
existing content, then this value is zero. Otherwise, this value is an
integer representing the number of bytes on disk that do not need to be
retrieved again.
- parameter expectedTotalBytes: The expected length of the file, as provided by the Content-Length header.
If this header was not provided, the value is NSURLSessionTransferSizeUnknown.
*/
public func URLSession(
session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(
session,
downloadTask: downloadTask,
didResumeAtOffset: fileOffset,
expectedTotalBytes: expectedTotalBytes
)
}
}
// MARK: - NSURLSessionStreamDelegate
var _streamTaskReadClosed: Any?
var _streamTaskWriteClosed: Any?
var _streamTaskBetterRouteDiscovered: Any?
var _streamTaskDidBecomeInputStream: Any?
// MARK: - NSObject
public override func respondsToSelector(selector: Selector) -> Bool {
#if !os(OSX)
if selector == #selector(NSURLSessionDelegate.URLSessionDidFinishEventsForBackgroundURLSession(_:)) {
return sessionDidFinishEventsForBackgroundURLSession != nil
}
#endif
switch selector {
case #selector(NSURLSessionDelegate.URLSession(_:didBecomeInvalidWithError:)):
return sessionDidBecomeInvalidWithError != nil
case #selector(NSURLSessionDelegate.URLSession(_:didReceiveChallenge:completionHandler:)):
return (sessionDidReceiveChallenge != nil || sessionDidReceiveChallengeWithCompletion != nil)
case #selector(NSURLSessionTaskDelegate.URLSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:)):
return (taskWillPerformHTTPRedirection != nil || taskWillPerformHTTPRedirectionWithCompletion != nil)
case #selector(NSURLSessionDataDelegate.URLSession(_:dataTask:didReceiveResponse:completionHandler:)):
return (dataTaskDidReceiveResponse != nil || dataTaskDidReceiveResponseWithCompletion != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
| mit | 64325984b39423dd1e3a99a37470ed59 | 48.975919 | 197 | 0.64254 | 6.744954 | false | false | false | false |
Mioke/PlanB | PlanB/PlanB/Base/Persistance/Protocols/KMPersistance.swift | 1 | 4227 | //
// KMPersistance.swift
// swiftArchitecture
//
// Created by Klein Mioke on 15/12/1.
// Copyright © 2015年 KleinMioke. All rights reserved.
//
import Foundation
import FMDB
protocol PersistanceManagerProtocol: NSObjectProtocol {
}
// MARK: - Database
protocol DatabaseManagerProtocol: PersistanceManagerProtocol {
var path: String { get }
var database: FMDatabaseQueue { get }
var databaseName: String { get }
// static var instance: protocol<DatabaseManagerProtocol> { get set }
}
class KMPersistanceDatabase: NSObject {
private weak var child: protocol<DatabaseManagerProtocol>?
override init() {
super.init()
if self is protocol<DatabaseManagerProtocol> {
self.child = self as? protocol<DatabaseManagerProtocol>
assert(self.child != nil, "KMPersistanceDatabase's database couldn't be nil")
} else {
assert(false, "KMPersistanceDatabase's subclass must follow the KMPersistanceProtocol")
}
}
deinit {
self.close()
}
func close() -> Void {
self.child!.database.close()
}
/**
Query infomation
- parameter query: query SQL string
- parameter args: the args in SQL string
- returns: result array
*/
func query(query: String, withArgumentsInArray args: [AnyObject]?) -> NSMutableArray {
return DatabaseManager.database(self.child!.database, query: query, withArgumentsInArray: args)
}
/**
Execute operation
- parameter sql: SQL string
- parameter args: The args in sql string
- returns: Whether succeed
*/
func execute(sql: String, withArgumentsInDictionary args: [String: AnyObject]!) -> Bool {
return DatabaseManager.database(self.child!.database, execute: sql, withArgumentsInDictionary: args)
}
/**
Execute operation
- parameter sql: SQL string
- parameter args: The args array in sql string
- returns: Succeed or not
*/
func execute(sql: String, withArgumentsInArray args: [AnyObject]!) -> Bool {
return DatabaseManager.database(self.child!.database, execute: sql, withArgumentsInArray: args)
}
}
// MARK: - Table
protocol TableProtocol: PersistanceManagerProtocol {
weak var database: KMPersistanceDatabase? { get }
var tableName: String { get }
var tableColumnInfo: [String: String] { get }
}
class KMPersistanceTable: NSObject {
private weak var child: TableProtocol?
override init() {
super.init()
if self is TableProtocol {
self.child = (self as! TableProtocol)
DatabaseCommand.createTable(self.child!, inDataBase: self.child!.database!)
} else {
assert(false, "KMPersistanceTable must conform to TableProtocol")
}
}
func replaceRecord(record: RecordProtocol) -> Bool {
guard let params = record.dictionaryRepresentationInTable(self.child!) else {
return false
}
if params.count == 0 {
return false
}
let sql = DatabaseCommand.replaceCommandWithTable(self.child!, record: record)
return self.child!.database!.execute(sql, withArgumentsInDictionary: params)
}
func queryRecordWithSelect(select: String?, condition: DatabaseCommandCondition) -> NSMutableArray {
let sql = DatabaseCommand.queryCommandWithTable(self.child!, select: select, condition: condition)
return self.child!.database!.query(sql, withArgumentsInArray: nil)
}
}
// MARK: - Record
protocol RecordProtocol: PersistanceManagerProtocol {
func dictionaryRepresentationInTable(table: TableProtocol) -> [String: AnyObject]?
static func readFromQueryResultDictionary(dictionary: NSDictionary, table: TableProtocol) -> RecordProtocol?
}
// Default implementation, make this func optional-like
extension RecordProtocol {
static func readFromQueryResultDictionary(dictionary: NSDictionary, table: TableProtocol) -> RecordProtocol? {
return nil
}
}
| gpl-3.0 | 7de49c38a20f49e6f888ab55f69698ec | 23.994083 | 114 | 0.648674 | 4.992908 | false | false | false | false |
Webtrekk/webtrekk-ios-sdk | Source/Internal/Trackers/DefaultMediaTracker.swift | 1 | 980 | import UIKit
internal final class DefaultMediaTracker: MediaTracker {
private let handler: MediaEventHandler
internal var mediaProperties: MediaProperties
internal var pageName: String?
internal var variables: [String: String]
internal var viewControllerType: AnyObject.Type?
internal init(handler: MediaEventHandler, mediaName: String, pageName: String?, mediaProperties: MediaProperties?, variables: [String: String]?) {
checkIsOnMainThread()
self.handler = handler
self.mediaProperties = mediaProperties ?? MediaProperties(name: mediaName)
self.pageName = pageName
self.variables = variables ?? [String: String]()
}
internal func trackAction(_ action: MediaEvent.Action) {
checkIsOnMainThread()
let event = MediaEvent(
action: action,
mediaProperties: mediaProperties,
pageName: pageName,
variables: variables
)
event.viewControllerType = viewControllerType
handler.handleEvent(event)
}
}
| mit | c95ebc7c7b1c9a6dd5a51ccdb20a2b4a | 27.823529 | 150 | 0.739796 | 4.474886 | false | false | false | false |
zjjzmw1/SwiftCodeFragments | SwiftCodeFragments/AnimationResource/WCLLoadingView.swift | 1 | 11156 | //
// WCLLoadingView.swift
// WCL
//
// **************************************************
// * _____ *
// * __ _ __ ___ \ / *
// * \ \/ \/ / / __\ / / *
// * \ _ / | (__ / / *
// * \/ \/ \___/ / /__ *
// * /_____/ *
// * *
// **************************************************
// Github :https://github.com/631106979
// HomePage:https://imwcl.com
// CSDN :http://blog.csdn.net/wang631106979
//
// Created by 王崇磊 on 16/9/14.
// Copyright © 2016年 王崇磊. All rights reserved.
//
// @class WCLLoadingView
// @abstract Slack 的 Loading 动画
// @discussion Slack 的 Loading 动画
//
// 动画步骤解析:http://blog.csdn.net/wang631106979/article/details/52473985
import UIKit
class WCLLoadingView: UIView, CAAnimationDelegate {
//线的宽度
var lineWidth:CGFloat = 0
//线的长度
var lineLength:CGFloat = 0
//边距
var margin:CGFloat = 0
//动画时间
var duration:Double = 2
//动画的间隔时间
var interval:Double = 1
//四条线的颜色
// var colors:[UIColor] = [UIColor.init(rgba: "#9DD4E9") , UIColor.init(rgba: "#F5BD58"), UIColor.init(rgba: "#FF317E") , UIColor.init(rgba: "#6FC9B5")]
var colors:[UIColor] = [UIColor.colorRGB16(value: 0x9DD4E9), UIColor.colorRGB16(value: 0xF5BD58), UIColor.colorRGB16(value: 0xFF317E), UIColor.colorRGB16(value: 0x6FC9B5)]
//动画的状态
private(set) var status:AnimationStatus = .normal
//四条线
private var lines:[CAShapeLayer] = []
enum AnimationStatus {
//普通状态
case normal
//动画中
case animating
//暂停
case pause
}
//MARK: Public Methods
/**
开始动画
*/
func startAnimation() {
angleAnimation()
lineAnimationOne()
lineAnimationTwo()
lineAnimationThree()
}
/**
暂停动画
*/
func pauseAnimation() {
layer.pauseAnimation()
for lineLayer in lines {
lineLayer.pauseAnimation()
}
status = .pause
}
/**
继续动画
*/
func resumeAnimation() {
layer.resumeAnimation()
for lineLayer in lines {
lineLayer.resumeAnimation()
}
status = .animating
}
//MARK: Initial Methods
convenience init(fram: CGRect , colors: [UIColor]) {
self.init()
self.frame = frame
self.colors = colors
config()
}
override init(frame: CGRect) {
super.init(frame: frame)
config()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
config()
}
//MARK: Animation Delegate
func animationDidStart(_ anim: CAAnimation) {
if let animation = anim as? CABasicAnimation {
if animation.keyPath == "transform.rotation.z" {
status = .animating
}
}
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
if let animation = anim as? CABasicAnimation {
if animation.keyPath == "strokeEnd" {
if flag {
status = .normal
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(interval) * Int64(NSEC_PER_SEC)) / Double(NSEC_PER_SEC), execute: {
if self.status != .animating {
self.startAnimation()
}
})
}
}
}
}
//MARK: Privater Methods
//MARK: 绘制线
/**
绘制四条线
*/
private func drawLineShapeLayer() {
//开始点
let startPoint = [point(lineWidth/2, y: margin),
point(lineLength - margin, y: lineWidth/2),
point(lineLength - lineWidth/2, y: lineLength - margin),
point(margin, y: lineLength - lineWidth/2)]
//结束点
let endPoint = [point(lineLength - lineWidth/2, y: margin) ,
point(lineLength - margin, y: lineLength - lineWidth/2) ,
point(lineWidth/2, y: lineLength - margin) ,
point(margin, y: lineWidth/2)]
for i in 0...3 {
let line:CAShapeLayer = CAShapeLayer()
line.lineWidth = lineWidth
line.lineCap = kCALineCapRound
line.opacity = 0.8
line.strokeColor = colors[i].cgColor
line.path = getLinePath(startPoint[i], endPoint: endPoint[i]).cgPath
layer.addSublayer(line)
lines.append(line)
}
}
/**
获取线的路径
- parameter startPoint: 开始点
- parameter endPoint: 结束点
- returns: 线的路径
*/
private func getLinePath(_ startPoint: CGPoint, endPoint: CGPoint) -> UIBezierPath {
let path = UIBezierPath()
path.move(to: startPoint)
path.addLine(to: endPoint)
return path
}
//MARK: 动画步骤
/**
旋转的动画,旋转两圈
*/
func angleAnimation() {
let angleAnimation = CABasicAnimation.init(keyPath: "transform.rotation.z")
angleAnimation.beginTime = CACurrentMediaTime()
angleAnimation.fromValue = angle(-30)
angleAnimation.toValue = angle(690)
angleAnimation.fillMode = kCAFillModeForwards
angleAnimation.isRemovedOnCompletion = false
angleAnimation.duration = duration
angleAnimation.delegate = self
layer.add(angleAnimation, forKey: "angleAnimation")
}
/**
线的第一步动画,线长从长变短
*/
func lineAnimationOne() {
let lineAnimationOne = CABasicAnimation.init(keyPath: "strokeEnd")
lineAnimationOne.beginTime = CACurrentMediaTime()
lineAnimationOne.duration = duration/2
lineAnimationOne.fillMode = kCAFillModeForwards
lineAnimationOne.isRemovedOnCompletion = false
lineAnimationOne.fromValue = 1
lineAnimationOne.toValue = 0
for i in 0...3 {
let lineLayer = lines[i]
lineLayer.add(lineAnimationOne, forKey: "lineAnimationOne")
}
}
/**
线的第二步动画,线向中间平移
*/
func lineAnimationTwo() {
for i in 0...3 {
var keypath = "transform.translation.x"
if i%2 == 1 {
keypath = "transform.translation.y"
}
let lineAnimationTwo = CABasicAnimation.init(keyPath: keypath)
lineAnimationTwo.beginTime = CACurrentMediaTime() + duration/2
lineAnimationTwo.duration = duration/4
lineAnimationTwo.fillMode = kCAFillModeForwards
lineAnimationTwo.isRemovedOnCompletion = false
lineAnimationTwo.autoreverses = true
lineAnimationTwo.fromValue = 0
if i < 2 {
lineAnimationTwo.toValue = lineLength/4
}else {
lineAnimationTwo.toValue = -lineLength/4
}
let lineLayer = lines[i]
lineLayer.add(lineAnimationTwo, forKey: "lineAnimationTwo")
}
//三角形两边的比例
let scale = (lineLength - 2*margin)/(lineLength - lineWidth)
for i in 0...3 {
var keypath = "transform.translation.y"
if i%2 == 1 {
keypath = "transform.translation.x"
}
let lineAnimationTwo = CABasicAnimation.init(keyPath: keypath)
lineAnimationTwo.beginTime = CACurrentMediaTime() + duration/2
lineAnimationTwo.duration = duration/4
lineAnimationTwo.fillMode = kCAFillModeForwards
lineAnimationTwo.isRemovedOnCompletion = false
lineAnimationTwo.autoreverses = true
lineAnimationTwo.fromValue = 0
if i == 0 || i == 3 {
lineAnimationTwo.toValue = lineLength/4 * scale
}else {
lineAnimationTwo.toValue = -lineLength/4 * scale
}
let lineLayer = lines[i]
lineLayer.add(lineAnimationTwo, forKey: "lineAnimationThree")
}
}
/**
线的第三步动画,线由短变长
*/
func lineAnimationThree() {
//线移动的动画
let lineAnimationFour = CABasicAnimation.init(keyPath: "strokeEnd")
lineAnimationFour.beginTime = CACurrentMediaTime() + duration
lineAnimationFour.duration = duration/4
lineAnimationFour.fillMode = kCAFillModeForwards
lineAnimationFour.isRemovedOnCompletion = false
lineAnimationFour.fromValue = 0
lineAnimationFour.toValue = 1
for i in 0...3 {
if i == 3 {
// 可以保证停止后再开始。
// lineAnimationFour.delegate = self
}
let lineLayer = lines[i]
lineLayer.add(lineAnimationFour, forKey: "lineAnimationFour")
}
}
//MARK: Private Methods
private func point(_ x:CGFloat , y:CGFloat) -> CGPoint {
return CGPoint(x: x, y: y)
}
private func angle(_ angle: Double) -> CGFloat {
return CGFloat(angle * (M_PI/180))
}
private func config() {
layoutIfNeeded()
lineLength = max(frame.width, frame.height)
lineWidth = lineLength/6.0
margin = lineLength/4.5 + lineWidth/2
drawLineShapeLayer()
//调整角度
transform = CGAffineTransform.identity.rotated(by: angle(-30))
}
}
extension CALayer {
//暂停动画
func pauseAnimation() {
// 将当前时间CACurrentMediaTime转换为layer上的时间, 即将parent time转换为localtime
let pauseTime = convertTime(CACurrentMediaTime(), from: nil)
// 设置layer的timeOffset, 在继续操作也会使用到
timeOffset = pauseTime
// localtime与parenttime的比例为0, 意味着localtime暂停了
speed = 0
}
//继续动画
func resumeAnimation() {
let pausedTime = timeOffset
speed = 1
timeOffset = 0
beginTime = 0
// 计算暂停时间
let sincePause = convertTime(CACurrentMediaTime(), from: nil) - pausedTime
// local time相对于parent time时间的beginTime
beginTime = sincePause
}
}
| mit | 0c3f2cd961d2c5bd1fa927925d033eba | 31.87963 | 175 | 0.520605 | 4.848885 | false | false | false | false |
EaglesoftZJ/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/ActorCore/Providers/CocoaNetworkRuntime.swift | 1 | 4114 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import Foundation
class CocoaNetworkRuntime : ARManagedNetworkProvider {
override init() {
super.init(factory: CocoaTcpConnectionFactory())
}
}
class CocoaTcpConnectionFactory: NSObject, ARAsyncConnectionFactory {
func createConnection(withConnectionId connectionId: jint,
with endpoint: ARConnectionEndpoint!,
with connectionInterface: ARAsyncConnectionInterface!) -> ARAsyncConnection! {
return CocoaTcpConnection(connectionId: Int(connectionId), endpoint: endpoint, connection: connectionInterface)
}
}
class CocoaTcpConnection: ARAsyncConnection, GCDAsyncSocketDelegate {
static let queue = DispatchQueue(label: "im.actor.network", attributes: [])
let READ_HEADER = 1
let READ_BODY = 2
var TAG: String!
var gcdSocket:GCDAsyncSocket? = nil
var header: Data?
init(connectionId: Int, endpoint: ARConnectionEndpoint!, connection: ARAsyncConnectionInterface!) {
super.init(endpoint: endpoint, with: connection)
TAG = "🎍ConnectionTcp#\(connectionId)"
}
override func doConnect() {
let endpoint = getEndpoint()
gcdSocket = GCDAsyncSocket(delegate: self, delegateQueue: CocoaTcpConnection.queue)
gcdSocket?.isIPv4PreferredOverIPv6 = false
do {
try self.gcdSocket!.connect(toHost: (endpoint?.host!)!, onPort: UInt16((endpoint?.port)!), withTimeout: Double(ARManagedConnection_CONNECTION_TIMEOUT) / 1000.0)
} catch _ {
}
}
// Affer successful connection
func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
if (self.getEndpoint().type == ARConnectionEndpoint.type_TCP_TLS()) {
// NSLog("\(TAG) Starring TLS Session...")
sock.startTLS(nil)
} else {
startConnection()
}
}
// After TLS successful
func socketDidSecure(_ sock: GCDAsyncSocket) {
// NSLog("\(TAG) TLS Session started...")
startConnection()
}
func startConnection() {
gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER)
onConnected()
}
// On connection closed
func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
// NSLog("\(TAG) Connection closed...")
onClosed()
}
func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
if (tag == READ_HEADER) {
// NSLog("\(TAG) Header received")
self.header = data
data.readUInt32(0) // IGNORE: package id
let size = data.readUInt32(5)
gcdSocket?.readData(toLength: UInt(size + 4), withTimeout: -1, tag: READ_BODY)
} else if (tag == READ_BODY) {
// NSLog("\(TAG) Body received")
var package = Data()
package.append(self.header!)
package.append(data)
package.readUInt32(0) // IGNORE: package id
self.header = nil
onReceived(package.toJavaBytes())
gcdSocket?.readData(toLength: UInt(9), withTimeout: -1, tag: READ_HEADER)
} else {
fatalError("Unknown tag in read data")
}
}
override func doClose() {
if (gcdSocket != nil) {
// NSLog("\(TAG) Closing...")
gcdSocket?.disconnect()
gcdSocket = nil
}
}
override func doSend(_ data: IOSByteArray!) {
gcdSocket?.write(data.toNSData(), withTimeout: -1, tag: 0)
}
}
private extension Data {
func readUInt32() -> UInt32 {
var raw: UInt32 = 0;
(self as NSData).getBytes(&raw, length: 4)
return raw.bigEndian
}
func readUInt32(_ offset: Int) -> UInt32 {
var raw: UInt32 = 0;
(self as NSData).getBytes(&raw, range: NSMakeRange(offset, 4))
return raw.bigEndian
}
}
| agpl-3.0 | 2976a8cfb422c08e84ab742f96c45263 | 31.117188 | 172 | 0.586719 | 4.813817 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ColorModel/Model/LuvColorModel.swift | 1 | 7611 | //
// LuvColorModel.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@frozen
public struct LuvColorModel: ColorModel {
public typealias Indices = Range<Int>
public typealias Scalar = Double
@inlinable
@inline(__always)
public static var numberOfComponents: Int {
return 3
}
@inlinable
@inline(__always)
public static func rangeOfComponent(_ i: Int) -> ClosedRange<Double> {
precondition(0..<numberOfComponents ~= i, "Index out of range.")
switch i {
case 0: return 0...100
default: return -128...128
}
}
/// The lightness dimension.
public var lightness: Double
/// The u color component.
public var u: Double
/// The v color component.
public var v: Double
@inlinable
@inline(__always)
public init() {
self.lightness = 0
self.u = 0
self.v = 0
}
@inlinable
@inline(__always)
public init(lightness: Double, u: Double, v: Double) {
self.lightness = lightness
self.u = u
self.v = v
}
@inlinable
@inline(__always)
public init(lightness: Double, chroma: Double, hue: Double) {
self.lightness = lightness
self.u = chroma * cos(2 * .pi * hue)
self.v = chroma * sin(2 * .pi * hue)
}
@inlinable
public subscript(position: Int) -> Double {
get {
return withUnsafeTypePunnedPointer(of: self, to: Double.self) { $0[position] }
}
set {
withUnsafeMutableTypePunnedPointer(of: &self, to: Double.self) { $0[position] = newValue }
}
}
}
extension LuvColorModel {
@inlinable
@inline(__always)
public static var black: LuvColorModel {
return LuvColorModel()
}
}
extension LuvColorModel {
@inlinable
@inline(__always)
public var hue: Double {
get {
return positive_mod(0.5 * atan2(v, u) / .pi, 1)
}
set {
self = LuvColorModel(lightness: lightness, chroma: chroma, hue: newValue)
}
}
@inlinable
@inline(__always)
public var chroma: Double {
get {
return hypot(u, v)
}
set {
self = LuvColorModel(lightness: lightness, chroma: newValue, hue: hue)
}
}
}
extension LuvColorModel {
@inlinable
@inline(__always)
public func map(_ transform: (Double) -> Double) -> LuvColorModel {
return LuvColorModel(lightness: transform(lightness), u: transform(u), v: transform(v))
}
@inlinable
@inline(__always)
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Double) -> Void) -> Result {
var accumulator = initialResult
updateAccumulatingResult(&accumulator, lightness)
updateAccumulatingResult(&accumulator, u)
updateAccumulatingResult(&accumulator, v)
return accumulator
}
@inlinable
@inline(__always)
public func combined(_ other: LuvColorModel, _ transform: (Double, Double) -> Double) -> LuvColorModel {
return LuvColorModel(lightness: transform(self.lightness, other.lightness), u: transform(self.u, other.u), v: transform(self.v, other.v))
}
}
extension LuvColorModel {
public typealias Float16Components = FloatComponents<float16>
public typealias Float32Components = FloatComponents<Float>
@frozen
public struct FloatComponents<Scalar: BinaryFloatingPoint & ScalarProtocol>: ColorComponents {
public typealias Indices = Range<Int>
@inlinable
@inline(__always)
public static var numberOfComponents: Int {
return 3
}
public var lightness: Scalar
public var u: Scalar
public var v: Scalar
@inline(__always)
public init() {
self.lightness = 0
self.u = 0
self.v = 0
}
@inline(__always)
public init(lightness: Scalar, u: Scalar, v: Scalar) {
self.lightness = lightness
self.u = u
self.v = v
}
@inlinable
@inline(__always)
public init(_ color: LuvColorModel) {
self.lightness = Scalar(color.lightness)
self.u = Scalar(color.u)
self.v = Scalar(color.v)
}
@inlinable
@inline(__always)
public init<T>(_ components: FloatComponents<T>) {
self.lightness = Scalar(components.lightness)
self.u = Scalar(components.u)
self.v = Scalar(components.v)
}
@inlinable
public subscript(position: Int) -> Scalar {
get {
return withUnsafeTypePunnedPointer(of: self, to: Scalar.self) { $0[position] }
}
set {
withUnsafeMutableTypePunnedPointer(of: &self, to: Scalar.self) { $0[position] = newValue }
}
}
@inlinable
@inline(__always)
public var model: LuvColorModel {
get {
return LuvColorModel(lightness: Double(lightness), u: Double(u), v: Double(v))
}
set {
self = FloatComponents(newValue)
}
}
}
}
extension LuvColorModel.FloatComponents {
@inlinable
@inline(__always)
public func map(_ transform: (Scalar) -> Scalar) -> LuvColorModel.FloatComponents<Scalar> {
return LuvColorModel.FloatComponents(lightness: transform(lightness), u: transform(u), v: transform(v))
}
@inlinable
@inline(__always)
public func reduce<Result>(into initialResult: Result, _ updateAccumulatingResult: (inout Result, Scalar) -> Void) -> Result {
var accumulator = initialResult
updateAccumulatingResult(&accumulator, lightness)
updateAccumulatingResult(&accumulator, u)
updateAccumulatingResult(&accumulator, v)
return accumulator
}
@inlinable
@inline(__always)
public func combined(_ other: LuvColorModel.FloatComponents<Scalar>, _ transform: (Scalar, Scalar) -> Scalar) -> LuvColorModel.FloatComponents<Scalar> {
return LuvColorModel.FloatComponents(lightness: transform(self.lightness, other.lightness), u: transform(self.u, other.u), v: transform(self.v, other.v))
}
}
| mit | ad4d33db3ecb233752267a3d83cd6825 | 30.065306 | 161 | 0.606228 | 4.6522 | false | false | false | false |
samodom/TestableUIKit | TestableUIKit/UIResponder/UIView/UINavigationBar/UINavigationBarPushItemSpy.swift | 1 | 3590 | //
// UINavigationBarPushItemSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/21/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import UIKit
import TestSwagger
import FoundationSwagger
public extension UINavigationBar {
private static let pushItemCalledKeyString = UUIDKeyString()
private static let pushItemCalledKey =
ObjectAssociationKey(pushItemCalledKeyString)
private static let pushItemCalledReference =
SpyEvidenceReference(key: pushItemCalledKey)
private static let pushItemItemKeyString = UUIDKeyString()
private static let pushItemItemKey =
ObjectAssociationKey(pushItemItemKeyString)
private static let pushItemItemReference =
SpyEvidenceReference(key: pushItemItemKey)
private static let pushItemAnimatedKeyString = UUIDKeyString()
private static let pushItemAnimatedKey =
ObjectAssociationKey(pushItemAnimatedKeyString)
private static let pushItemAnimatedReference =
SpyEvidenceReference(key: pushItemAnimatedKey)
private static let pushItemCoselectors = SpyCoselectors(
methodType: .instance,
original: #selector(UINavigationBar.pushItem(_:animated:)),
spy: #selector(UINavigationBar.spy_pushItem(_:animated:))
)
/// Spy controller for ensuring that a navigation bar has had `pushItem(_:animated:)` called on it.
public enum PushItemSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UINavigationBar.self
public static let vector = SpyVector.direct
public static let coselectors: Set = [pushItemCoselectors]
public static let evidence: Set = [
pushItemCalledReference,
pushItemItemReference,
pushItemAnimatedReference
]
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `pushItem(_:animated)`
dynamic public func spy_pushItem(_ item: UINavigationItem?, animated: Bool) {
pushItemCalled = true
pushItemItem = item
pushItemAnimated = animated
spy_pushItem(item, animated: animated)
}
/// Indicates whether the `pushItem(_:animated:)` method has been called on this object.
public final var pushItemCalled: Bool {
get {
return loadEvidence(with: UINavigationBar.pushItemCalledReference) as? Bool ?? false
}
set {
saveEvidence(newValue, with: UINavigationBar.pushItemCalledReference)
}
}
/// Provides the item passed to `pushItem(_:animated:)` if called.
public final var pushItemItem: UINavigationItem? {
get {
return loadEvidence(with: UINavigationBar.pushItemItemReference) as? UINavigationItem
}
set {
let reference = UINavigationBar.pushItemItemReference
guard let item = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(item, with: reference)
}
}
/// Provides the animation flag passed to `pushItem(_:animated:)` if called.
public final var pushItemAnimated: Bool? {
get {
return loadEvidence(with: UINavigationBar.pushItemAnimatedReference) as? Bool
}
set {
let reference = UINavigationBar.pushItemAnimatedReference
guard let animated = newValue else {
return removeEvidence(with: reference)
}
saveEvidence(animated, with: reference)
}
}
}
| mit | b7cc946e5ee93217c4ed570e744bb885 | 32.231481 | 103 | 0.675118 | 5.816856 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Skip.swift | 38 | 4891 | //
// Skip.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/25/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter count: The number of elements to skip before returning the remaining elements.
- returns: An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
public func skip(_ count: Int)
-> Observable<E> {
return SkipCount(source: asObservable(), count: count)
}
}
extension ObservableType {
/**
Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
- seealso: [skip operator on reactivex.io](http://reactivex.io/documentation/operators/skip.html)
- parameter duration: Duration for skipping elements from the start of the sequence.
- parameter scheduler: Scheduler to run the timer on.
- returns: An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
public func skip(_ duration: RxTimeInterval, scheduler: SchedulerType)
-> Observable<E> {
return SkipTime(source: self.asObservable(), duration: duration, scheduler: scheduler)
}
}
// count version
final fileprivate class SkipCountSink<O: ObserverType> : Sink<O>, ObserverType {
typealias Element = O.E
typealias Parent = SkipCount<Element>
let parent: Parent
var remaining: Int
init(parent: Parent, observer: O, cancel: Cancelable) {
self.parent = parent
self.remaining = parent.count
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if remaining <= 0 {
forwardOn(.next(value))
}
else {
remaining -= 1
}
case .error:
forwardOn(event)
self.dispose()
case .completed:
forwardOn(event)
self.dispose()
}
}
}
final fileprivate class SkipCount<Element>: Producer<Element> {
let source: Observable<Element>
let count: Int
init(source: Observable<Element>, count: Int) {
self.source = source
self.count = count
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = SkipCountSink(parent: self, observer: observer, cancel: cancel)
let subscription = source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
// time version
final fileprivate class SkipTimeSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType {
typealias Parent = SkipTime<ElementType>
typealias Element = ElementType
let parent: Parent
// state
var open = false
init(parent: Parent, observer: O, cancel: Cancelable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
if open {
forwardOn(.next(value))
}
case .error:
forwardOn(event)
self.dispose()
case .completed:
forwardOn(event)
self.dispose()
}
}
func tick() {
open = true
}
func run() -> Disposable {
let disposeTimer = parent.scheduler.scheduleRelative((), dueTime: self.parent.duration) { _ in
self.tick()
return Disposables.create()
}
let disposeSubscription = parent.source.subscribe(self)
return Disposables.create(disposeTimer, disposeSubscription)
}
}
final fileprivate class SkipTime<Element>: Producer<Element> {
let source: Observable<Element>
let duration: RxTimeInterval
let scheduler: SchedulerType
init(source: Observable<Element>, duration: RxTimeInterval, scheduler: SchedulerType) {
self.source = source
self.scheduler = scheduler
self.duration = duration
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = SkipTimeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| mit | 548fc1cfe3fdcbc646417ac3317807ee | 29.754717 | 145 | 0.628834 | 4.784736 | false | false | false | false |
GuiminChu/JianshuExamples | LearnRxSwift/LearnRxSwift/Chocotastic/ChocolatesOfTheWorldViewController.swift | 2 | 2984 | /**
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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 RxSwift
import RxCocoa
class ChocolatesOfTheWorldViewController: UIViewController {
@IBOutlet private var cartButton: UIBarButtonItem!
@IBOutlet private var tableView: UITableView!
// just 只创建包含一个元素的序列
let europeanChocolates = Observable.just(Chocolate.ofEurope)
let disposeBag = DisposeBag()
// MARK: View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
title = "Chocolate!!!"
setupCartObserver()
setupCellConfiguration()
setupCellTapHandling()
}
// MARK: Rx Setup
private func setupCartObserver() {
ShoppingCart.sharedCart.chocolates.asObservable()
.subscribe(onNext: { [weak self] chocolates in
self?.cartButton.title = "\(chocolates.count) \u{1f36b}"
})
.addDisposableTo(disposeBag)
}
private func setupCellConfiguration() {
europeanChocolates.bindTo(tableView.rx.items(cellIdentifier: ChocolateCell.Identifier, cellType: ChocolateCell.self)) { row, chocolate, cell in
cell.configureWithChocolate(chocolate: chocolate)
}.addDisposableTo(disposeBag)
}
private func setupCellTapHandling() {
tableView.rx.modelSelected(Chocolate.self).subscribe(onNext: { chocolate in
ShoppingCart.sharedCart.chocolates.value.append(chocolate)
if let selectedRowIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRow(at: selectedRowIndexPath, animated: true)
}
}).addDisposableTo(disposeBag)
}
// MARK: Imperative methods
}
// MARK: - SegueHandler
extension ChocolatesOfTheWorldViewController: SegueHandler {
enum SegueIdentifier: String {
case
GoToCart
}
}
| mit | fef0255d3588b8798557af158b862b31 | 32.258427 | 151 | 0.698649 | 4.844517 | false | false | false | false |
tomomura/PasscodeField | PasscodeField/Classes/CircleView.swift | 1 | 3106 | //
// CircleView.swift
// Pods
//
// Created by TomomuraRyota on 2016/05/30.
//
//
import UIKit
final class CircleView: UIView {
// MARK: - Properties
var borderHeight: CGFloat {
didSet {
self.setNeedsDisplay()
}
}
var fillColor: UIColor {
didSet {
self.refreshFillColor()
}
}
var fillSize: CGFloat {
didSet {
self.invalidateIntrinsicContentSize()
}
}
var fill: Bool = false {
didSet {
self.refreshFillView()
}
}
private let fillView = UIView(frame: CGRectZero)
// MARK: - Initializers
init(borderHeight: CGFloat, fillSize: CGFloat, fillColor: UIColor) {
self.borderHeight = borderHeight
self.fillSize = fillSize
self.fillColor = fillColor
super.init(frame: CGRectZero)
self.commonInit()
self.setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - LifeCycle
override func drawRect(rect: CGRect) {
if !self.fill {
let line = UIBezierPath()
let x = self.fillView.frame.origin.x
let y = self.bounds.height / 2
let width = self.fillView.bounds.width
line.moveToPoint(CGPointMake(x, y));
line.addLineToPoint(CGPointMake(x + width, y));
line.lineWidth = self.borderHeight
self.fillColor.setStroke()
line.stroke()
}
}
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(self.fillSize, self.fillSize)
}
override func updateConstraints() {
NSLayoutConstraint.activateConstraints([
self.fillView.topAnchor.constraintEqualToAnchor(self.topAnchor),
self.fillView.bottomAnchor.constraintEqualToAnchor(self.bottomAnchor),
self.fillView.leadingAnchor.constraintEqualToAnchor(self.leadingAnchor),
self.fillView.trailingAnchor.constraintEqualToAnchor(self.trailingAnchor),
])
super.updateConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
self.fillView.layer.cornerRadius = self.fillSize / 2
}
// MARK: - Private Methods
private func commonInit() {
self.translatesAutoresizingMaskIntoConstraints = false
self.backgroundColor = UIColor.clearColor()
self.fillView.translatesAutoresizingMaskIntoConstraints = false
}
private func setupView() {
self.addSubview(self.fillView)
self.refreshFillView()
self.refreshFillColor()
}
// MARK: - Helpers
private func refreshFillColor() {
self.fillView.backgroundColor = self.fillColor
self.setNeedsDisplay()
}
private func refreshFillView() {
self.fillView.hidden = !self.fill
}
}
| mit | cbfd1790dcd3309fc8308b8127eca5ad | 23.848 | 86 | 0.577592 | 5.291312 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/TabBarProfileItem.swift | 1 | 2542 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import SnapKit
private struct Constants {
static let ImageSize = 32.0
}
class TabBarProfileItem: TabBarAbstractItem {
override var selected: Bool {
didSet {
imageViewWithStatus.imageView.tintColor = theme.colorForType(selected ? .TabItemActive : .TabItemInactive)
}
}
var userStatus: UserStatus = .offline {
didSet {
imageViewWithStatus.userStatusView.userStatus = userStatus
}
}
var userImage: UIImage? {
didSet {
if let image = userImage {
imageViewWithStatus.imageView.image = image
}
else {
imageViewWithStatus.imageView.image = UIImage.templateNamed("tab-bar-profile")
}
}
}
fileprivate let theme: Theme
fileprivate var imageViewWithStatus: ImageViewWithStatus!
fileprivate var button: UIButton!
init(theme: Theme) {
self.theme = theme
super.init(frame: CGRect.zero)
backgroundColor = .clear
createViews()
installConstraints()
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Accessibility
extension TabBarProfileItem {
override var accessibilityLabel: String? {
get {
return String(localized: "profile_title")
}
set {}
}
override var accessibilityValue: String? {
get {
return userStatus.toString()
}
set {}
}
}
// Actions
extension TabBarProfileItem {
@objc func buttonPressed() {
didTapHandler?()
}
}
private extension TabBarProfileItem {
func createViews() {
imageViewWithStatus = ImageViewWithStatus()
imageViewWithStatus.userStatusView.theme = theme
addSubview(imageViewWithStatus)
button = UIButton()
button.backgroundColor = .clear
button.addTarget(self, action: #selector(TabBarProfileItem.buttonPressed), for: .touchUpInside)
addSubview(button)
}
func installConstraints() {
imageViewWithStatus.snp.makeConstraints {
$0.center.equalTo(self)
$0.size.equalTo(Constants.ImageSize)
}
button.snp.makeConstraints {
$0.edges.equalTo(self)
}
}
}
| mpl-2.0 | d6072ec86475427bf3c4e6688ac6f1e5 | 23.442308 | 118 | 0.619591 | 5.033663 | false | false | false | false |
longsirhero/DinDinShop | DinDinShopDemo/Pods/FSPagerView/Sources/FSPageViewTransformer.swift | 1 | 11418 | //
// FSPagerViewTransformer.swift
// FSPagerView
//
// Created by Wenchao Ding on 05/01/2017.
// Copyright © 2017 Wenchao Ding. All rights reserved.
//
import UIKit
@objc
public enum FSPagerViewTransformerType: Int {
case crossFading
case zoomOut
case depth
case overlap
case linear
case coverFlow
case ferrisWheel
case invertedFerrisWheel
case cubic
}
open class FSPagerViewTransformer: NSObject {
open internal(set) weak var pagerView: FSPagerView?
open internal(set) var type: FSPagerViewTransformerType
open var minimumScale: CGFloat = 0.65
open var minimumAlpha: CGFloat = 0.6
public init(type: FSPagerViewTransformerType) {
self.type = type
switch type {
case .zoomOut:
self.minimumScale = 0.85
case .depth:
self.minimumScale = 0.5
default:
break
}
}
// Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D.
open func applyTransform(to attributes: FSPagerViewLayoutAttributes) {
guard let pagerView = self.pagerView else {
return
}
let position = attributes.position
let scrollDirection = pagerView.scrollDirection
let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing()
switch self.type {
case .crossFading:
var zIndex = 0
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch scrollDirection {
case .horizontal:
transform.tx = -itemSpacing * position
case .vertical:
transform.ty = -itemSpacing * position
}
if (abs(position) < 1) { // [-1,1]
// Use the default slide transition when moving to the left page
alpha = 1 - abs(position)
zIndex = 1
} else { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
zIndex = Int.min
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .zoomOut:
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
case -1 ... 1 : // [-1,1]
// Modify the default slide transition to shrink the page as well
let scaleFactor = max(self.minimumScale, 1 - abs(position))
transform.a = scaleFactor
transform.d = scaleFactor
switch scrollDirection {
case .horizontal:
let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2;
let horzMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.tx = position < 0 ? (horzMargin - vertMargin*2) : (-horzMargin + vertMargin*2)
case .vertical:
let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2;
let vertMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.ty = position < 0 ? (vertMargin - horzMargin*2) : (-vertMargin + horzMargin*2)
}
// Fade the page relative to its size.
alpha = self.minimumAlpha + (scaleFactor-self.minimumScale)/(1-self.minimumScale)*(1-self.minimumAlpha)
case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
case .depth:
var transform = CGAffineTransform.identity
var zIndex = 0
var alpha: CGFloat = 0.0
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
zIndex = 0
case -1 ... 0: // [-1,0]
// Use the default slide transition when moving to the left page
alpha = 1
transform.tx = 0
transform.a = 1
transform.d = 1
zIndex = 1
case 0 ..< 1: // (0,1)
// Fade the page out.
alpha = CGFloat(1.0) - position
// Counteract the default slide transition
switch scrollDirection {
case .horizontal:
transform.tx = itemSpacing * -position
case .vertical:
transform.ty = itemSpacing * -position
}
// Scale the page down (between minimumScale and 1)
let scaleFactor = self.minimumScale
+ (1.0 - self.minimumScale) * (1.0 - abs(position));
transform.a = scaleFactor
transform.d = scaleFactor
zIndex = 0
case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity)
// This page is way off-screen to the right.
alpha = 0
zIndex = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .overlap,.linear:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let scale = max(1 - (1-self.minimumScale) * abs(position), self.minimumScale)
let transform = CGAffineTransform(scaleX: scale, y: scale)
attributes.transform = transform
let alpha = (self.minimumAlpha + (1-abs(position))*(1-self.minimumAlpha))
attributes.alpha = alpha
let zIndex = (1-abs(position)) * 10
attributes.zIndex = Int(zIndex)
case .coverFlow:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let position = min(max(-position,-1) ,1)
let rotation = sin(position*(.pi)*0.5)*(.pi)*0.25*1.5
let translationZ = -itemSpacing * 0.5 * abs(position)
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0)
transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ)
attributes.zIndex = 100 - Int(abs(position))
attributes.transform3D = transform3D
case .ferrisWheel, .invertedFerrisWheel:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
// http://ronnqvi.st/translate-rotate-translate/
var zIndex = 0
var transform = CGAffineTransform.identity
switch position {
case -5 ... 5:
let itemSpacing = attributes.bounds.width+self.proposedInteritemSpacing()
let count: CGFloat = 14
let circle: CGFloat = .pi * 2.0
let radius = itemSpacing * count / circle
let ty = radius * (self.type == .ferrisWheel ? 1 : -1)
let theta = circle / count
let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1)
transform = transform.translatedBy(x: -position*itemSpacing, y: ty)
transform = transform.rotated(by: rotation)
transform = transform.translatedBy(x: 0, y: -ty)
zIndex = Int((4.0-abs(position)*10))
default:
break
}
attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha
attributes.transform = transform
attributes.zIndex = zIndex
case .cubic:
switch position {
case -CGFloat.greatestFiniteMagnitude ... -1:
attributes.alpha = 0
case -1 ..< 1:
attributes.alpha = 1
attributes.zIndex = Int((1-position) * CGFloat(10))
let direction: CGFloat = position < 0 ? 1 : -1
let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1)
let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
switch scrollDirection {
case .horizontal:
// ForwardX -> RotateY -> BackwardX
attributes.center.x += direction*radius*0.5 // ForwardX
transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY
transform3D = CATransform3DTranslate(transform3D,-direction*radius*0.5, 0, 0) // BackwardX
case .vertical:
// ForwardY -> RotateX -> BackwardY
attributes.center.y += direction*radius*0.5 // ForwardY
transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX
transform3D = CATransform3DTranslate(transform3D,0, -direction*radius*0.5, 0) // BackwardY
}
attributes.transform3D = transform3D
case 1 ... CGFloat.greatestFiniteMagnitude:
attributes.alpha = 0
default:
attributes.alpha = 0
attributes.zIndex = 0
}
}
}
// An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view.
open func proposedInteritemSpacing() -> CGFloat {
guard let pagerView = self.pagerView else {
return 0
}
let scrollDirection = pagerView.scrollDirection
switch self.type {
case .overlap:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.6
case .linear:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.2
case .coverFlow:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * sin(.pi*0.25*0.25*3.0)
case .ferrisWheel,.invertedFerrisWheel:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * 0.15
case .cubic:
return 0
default:
break
}
return pagerView.interitemSpacing
}
}
| mit | fe2947dcc6bdd766f6742051e9825198 | 40.974265 | 145 | 0.537707 | 5.069716 | false | false | false | false |
practicalswift/swift | test/ParseableInterface/conformances.swift | 4 | 7518 | // RUN: %target-swift-frontend-typecheck -emit-parseable-module-interface-path %t.swiftinterface %s
// RUN: %FileCheck %s < %t.swiftinterface
// RUN: %FileCheck -check-prefix CHECK-END %s < %t.swiftinterface
// RUN: %FileCheck -check-prefix NEGATIVE %s < %t.swiftinterface
// NEGATIVE-NOT: BAD
// CHECK-LABEL: public protocol SimpleProto {
public protocol SimpleProto {
// CHECK: associatedtype Element
associatedtype Element
// CHECK: associatedtype Inferred
associatedtype Inferred
func inference(_: Inferred)
} // CHECK: {{^}$}}
// CHECK-LABEL: public struct SimpleImpl<Element> : SimpleProto {
public struct SimpleImpl<Element>: SimpleProto {
// NEGATIVE-NOT: typealias Element =
// CHECK: public func inference(_: Int){{$}}
public func inference(_: Int) {}
// CHECK: public typealias Inferred = Swift.Int
} // CHECK: {{^}$}}
public protocol PublicProto {}
private protocol PrivateProto {}
// CHECK: public struct A1 : PublicProto {
// NEGATIVE-NOT: extension conformances.A1
public struct A1: PublicProto, PrivateProto {}
// CHECK: public struct A2 : PublicProto {
// NEGATIVE-NOT: extension conformances.A2
public struct A2: PrivateProto, PublicProto {}
// CHECK: public struct A3 {
// CHECK-END: extension conformances.A3 : PublicProto {}
public struct A3: PublicProto & PrivateProto {}
// CHECK: public struct A4 {
// CHECK-END: extension conformances.A4 : PublicProto {}
public struct A4: PrivateProto & PublicProto {}
public protocol PublicBaseProto {}
private protocol PrivateSubProto: PublicBaseProto {}
// CHECK: public struct B1 {
// CHECK-END: extension conformances.B1 : PublicBaseProto {}
public struct B1: PrivateSubProto {}
// CHECK: public struct B2 : PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B2
public struct B2: PublicBaseProto, PrivateSubProto {}
// CHECK: public struct B3 {
// CHECK-END: extension conformances.B3 : PublicBaseProto {}
public struct B3: PublicBaseProto & PrivateSubProto {}
// CHECK: public struct B4 : PublicBaseProto {
// CHECK: extension B4 {
// NEGATIVE-NOT: extension conformances.B4
public struct B4: PublicBaseProto {}
extension B4: PrivateSubProto {}
// CHECK: public struct B5 {
// CHECK: extension B5 : PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B5
public struct B5: PrivateSubProto {}
extension B5: PublicBaseProto {}
// CHECK: public struct B6 {
// CHECK: extension B6 {
// CHECK: extension B6 : PublicBaseProto {
// NEGATIVE-NOT: extension conformances.B6
public struct B6 {}
extension B6: PrivateSubProto {}
extension B6: PublicBaseProto {}
// CHECK: public struct B7 {
// CHECK: extension B7 : PublicBaseProto {
// CHECK: extension B7 {
// NEGATIVE-NOT: extension conformances.B7
public struct B7 {}
extension B7: PublicBaseProto {}
extension B7: PrivateSubProto {}
// CHECK-LABEL: public struct OuterGeneric<T> {
public struct OuterGeneric<T> {
// CHECK-NEXT: public struct Inner {
public struct Inner: PrivateSubProto {}
// CHECK-NEXT: {{^ }$}}
}
// CHECK-NEXT: {{^}$}}
public protocol ConditionallyConformed {}
public protocol ConditionallyConformedAgain {}
// CHECK-END: extension conformances.OuterGeneric : ConditionallyConformed, ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
extension OuterGeneric: ConditionallyConformed where T: PrivateProto {}
extension OuterGeneric: ConditionallyConformedAgain where T == PrivateProto {}
// CHECK-END: extension conformances.OuterGeneric.Inner : PublicBaseProto {}
// CHECK-END: extension conformances.OuterGeneric.Inner : ConditionallyConformed, ConditionallyConformedAgain where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
extension OuterGeneric.Inner: ConditionallyConformed where T: PrivateProto {}
extension OuterGeneric.Inner: ConditionallyConformedAgain where T == PrivateProto {}
private protocol AnotherPrivateSubProto: PublicBaseProto {}
// CHECK: public struct C1 {
// CHECK-END: extension conformances.C1 : PublicBaseProto {}
public struct C1: PrivateSubProto, AnotherPrivateSubProto {}
// CHECK: public struct C2 {
// CHECK-END: extension conformances.C2 : PublicBaseProto {}
public struct C2: PrivateSubProto & AnotherPrivateSubProto {}
// CHECK: public struct C3 {
// CHECK: extension C3 {
// CHECK-END: extension conformances.C3 : PublicBaseProto {}
public struct C3: PrivateSubProto {}
extension C3: AnotherPrivateSubProto {}
public protocol PublicSubProto: PublicBaseProto {}
public protocol APublicSubProto: PublicBaseProto {}
// CHECK: public struct D1 : PublicSubProto {
// NEGATIVE-NOT: extension conformances.D1
public struct D1: PublicSubProto, PrivateSubProto {}
// CHECK: public struct D2 : PublicSubProto {
// NEGATIVE-NOT: extension conformances.D2
public struct D2: PrivateSubProto, PublicSubProto {}
// CHECK: public struct D3 {
// CHECK-END: extension conformances.D3 : PublicBaseProto, PublicSubProto {}
public struct D3: PrivateSubProto & PublicSubProto {}
// CHECK: public struct D4 {
// CHECK-END: extension conformances.D4 : APublicSubProto, PublicBaseProto {}
public struct D4: APublicSubProto & PrivateSubProto {}
// CHECK: public struct D5 {
// CHECK: extension D5 : PublicSubProto {
// NEGATIVE-NOT: extension conformances.D5
public struct D5: PrivateSubProto {}
extension D5: PublicSubProto {}
// CHECK: public struct D6 : PublicSubProto {
// CHECK: extension D6 {
// NEGATIVE-NOT: extension conformances.D6
public struct D6: PublicSubProto {}
extension D6: PrivateSubProto {}
private typealias PrivateProtoAlias = PublicProto
// CHECK: public struct E1 {
// CHECK-END: extension conformances.E1 : PublicProto {}
public struct E1: PrivateProtoAlias {}
private typealias PrivateSubProtoAlias = PrivateSubProto
// CHECK: public struct F1 {
// CHECK-END: extension conformances.F1 : PublicBaseProto {}
public struct F1: PrivateSubProtoAlias {}
private protocol ClassConstrainedProto: PublicProto, AnyObject {}
public class G1: ClassConstrainedProto {}
// CHECK: public class G1 {
// CHECK-END: extension conformances.G1 : PublicProto {}
public class Base {}
private protocol BaseConstrainedProto: Base, PublicProto {}
public class H1: Base, ClassConstrainedProto {}
// CHECK: public class H1 : Base {
// CHECK-END: extension conformances.H1 : PublicProto {}
public struct MultiGeneric<T, U, V> {}
extension MultiGeneric: PublicProto where U: PrivateProto {}
// CHECK: public struct MultiGeneric<T, U, V> {
// CHECK-END: extension conformances.MultiGeneric : PublicProto where T : _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
internal struct InternalImpl_BAD: PrivateSubProto {}
internal struct InternalImplConstrained_BAD<T> {}
extension InternalImplConstrained_BAD: PublicProto where T: PublicProto {}
internal struct InternalImplConstrained2_BAD<T> {}
extension InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {}
public struct WrapperForInternal {
internal struct InternalImpl_BAD: PrivateSubProto {}
internal struct InternalImplConstrained_BAD<T> {}
internal struct InternalImplConstrained2_BAD<T> {}
}
extension WrapperForInternal.InternalImplConstrained_BAD: PublicProto where T: PublicProto {}
extension WrapperForInternal.InternalImplConstrained2_BAD: PublicProto where T: PrivateProto {}
internal protocol ExtraHashable: Hashable {}
extension Bool: ExtraHashable {}
// NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Hashable
// NEGATIVE-NOT: extension {{(Swift.)?}}Bool{{.+}}Equatable
// CHECK-END: @usableFromInline
// CHECK-END-NEXT: internal protocol _ConstraintThatIsNotPartOfTheAPIOfThisLibrary {}
| apache-2.0 | 9915f2950b6447506cc27ed8b61dd056 | 37.752577 | 168 | 0.765363 | 4.493724 | false | false | false | false |
mohitathwani/swift-corelibs-foundation | Foundation/NSSet.swift | 3 | 16079 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
open class NSSet : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFSetGetTypeID())
internal var _storage: Set<NSObject>
open var count: Int {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
return _storage.count
}
open func member(_ object: Any) -> Any? {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = _SwiftValue.store(object)
guard let idx = _storage.index(of: value) else { return nil }
return _storage[idx]
}
open func objectEnumerator() -> NSEnumerator {
guard type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self || type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
return NSGeneratorEnumerator(_storage.map { _SwiftValue.fetch(nonOptional: $0) }.makeIterator())
}
public convenience override init() {
self.init(objects: [], count: 0)
}
public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
_storage = Set(minimumCapacity: cnt)
super.init()
let buffer = UnsafeBufferPointer(start: objects, count: cnt)
for obj in buffer {
_storage.insert(obj as! NSObject)
}
}
public required convenience init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.objects") {
let objects = aDecoder._decodeArrayOfObjectsForKey("NS.objects")
self.init(array: objects as! [NSObject])
} else {
var objects = [AnyObject]()
var count = 0
while let object = aDecoder.decodeObject(forKey: "NS.object.\(count)") {
objects.append(object as! NSObject)
count += 1
}
self.init(array: objects)
}
}
open func encode(with aCoder: NSCoder) {
// The encoding of a NSSet is identical to the encoding of an NSArray of its contents
self.allObjects._nsObject.encode(with: aCoder)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSSet.self {
// return self for immutable type
return self
} else if type(of: self) === NSMutableSet.self {
let set = NSSet()
set._storage = self._storage
return set
}
return NSSet(array: self.allObjects)
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
// always create and return an NSMutableSet
let mutableSet = NSMutableSet()
mutableSet._storage = self._storage
return mutableSet
}
return NSMutableSet(array: self.allObjects)
}
public static var supportsSecureCoding: Bool {
return true
}
open func description(withLocale locale: Locale?) -> String { NSUnimplemented() }
override open var _cfTypeID: CFTypeID {
return CFSetGetTypeID()
}
open override func isEqual(_ value: Any?) -> Bool {
switch value {
case let other as Set<AnyHashable>:
return isEqual(to: other)
case let other as NSSet:
return isEqual(to: Set._unconditionallyBridgeFromObjectiveC(other))
default:
return false
}
}
open override var hash: Int {
return self.count
}
public convenience init(array: [Any]) {
let buffer = UnsafeMutablePointer<AnyObject>.allocate(capacity: array.count)
for (idx, element) in array.enumerated() {
buffer.advanced(by: idx).initialize(to: _SwiftValue.store(element))
}
self.init(objects: buffer, count: array.count)
buffer.deinitialize(count: array.count)
buffer.deallocate(capacity: array.count)
}
public convenience init(set: Set<AnyHashable>) {
self.init(set: set, copyItems: false)
}
public convenience init(set: Set<AnyHashable>, copyItems flag: Bool) {
if flag {
self.init(array: set.map {
if let item = $0 as? NSObject {
return item.copy()
} else {
return $0
}
})
} else {
self.init(array: Array(set))
}
}
}
extension NSSet {
public convenience init(object: Any) {
self.init(array: [object])
}
}
extension NSSet {
open var allObjects: [Any] {
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
return _storage.map { _SwiftValue.fetch(nonOptional: $0) }
} else {
let enumerator = objectEnumerator()
var items = [Any]()
while let val = enumerator.nextObject() {
items.append(val)
}
return items
}
}
open func anyObject() -> Any? {
return objectEnumerator().nextObject()
}
open func contains(_ anObject: Any) -> Bool {
return member(anObject) != nil
}
open func intersects(_ otherSet: Set<AnyHashable>) -> Bool {
if count < otherSet.count {
for item in self {
if otherSet.contains(item as! AnyHashable) {
return true
}
}
return false
} else {
return otherSet.contains { obj in contains(obj) }
}
}
open func isEqual(to otherSet: Set<AnyHashable>) -> Bool {
return count == otherSet.count && isSubset(of: otherSet)
}
open func isSubset(of otherSet: Set<AnyHashable>) -> Bool {
// `true` if we don't contain any object that `otherSet` doesn't contain.
for item in self {
if !otherSet.contains(item as! AnyHashable) {
return false
}
}
return true
}
open func adding(_ anObject: Any) -> Set<AnyHashable> {
return self.addingObjects(from: [anObject])
}
open func addingObjects(from other: Set<AnyHashable>) -> Set<AnyHashable> {
var result = Set<AnyHashable>(minimumCapacity: Swift.max(count, other.count))
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
result.formUnion(_storage.map { _SwiftValue.fetch(nonOptional: $0) as! AnyHashable })
} else {
for case let obj as NSObject in self {
_ = result.insert(obj)
}
}
return result.union(other)
}
open func addingObjects(from other: [Any]) -> Set<AnyHashable> {
var result = Set<AnyHashable>(minimumCapacity: count)
if type(of: self) === NSSet.self || type(of: self) === NSMutableSet.self {
result.formUnion(_storage.map { _SwiftValue.fetch(nonOptional: $0) as! AnyHashable })
} else {
for case let obj as AnyHashable in self {
result.insert(obj)
}
}
for case let obj as AnyHashable in other {
result.insert(obj)
}
return result
}
open func enumerateObjects(_ block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
enumerateObjects(options: [], using: block)
}
open func enumerateObjects(options opts: NSEnumerationOptions = [], using block: (Any, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
var stop : ObjCBool = false
for obj in self {
withUnsafeMutablePointer(to: &stop) { stop in
block(obj, stop)
}
if stop {
break
}
}
}
open func objects(passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
return objects(options: [], passingTest: predicate)
}
open func objects(options opts: NSEnumerationOptions = [], passingTest predicate: (Any, UnsafeMutablePointer<ObjCBool>) -> Bool) -> Set<AnyHashable> {
var result = Set<AnyHashable>()
enumerateObjects(options: opts) { obj, stopp in
if predicate(obj, stopp) {
result.insert(obj as! AnyHashable)
}
}
return result
}
}
extension NSSet : _CFBridgeable, _SwiftBridgeable {
internal var _cfObject: CFSet { return unsafeBitCast(self, to: CFSet.self) }
internal var _swiftObject: Set<NSObject> { return Set._unconditionallyBridgeFromObjectiveC(self) }
}
extension CFSet : _NSBridgeable, _SwiftBridgeable {
internal var _nsObject: NSSet { return unsafeBitCast(self, to: NSSet.self) }
internal var _swiftObject: Set<NSObject> { return _nsObject._swiftObject }
}
extension NSMutableSet {
internal var _cfMutableObject: CFMutableSet { return unsafeBitCast(self, to: CFMutableSet.self) }
}
extension Set : _NSBridgeable, _CFBridgeable {
internal var _nsObject: NSSet { return _bridgeToObjectiveC() }
internal var _cfObject: CFSet { return _nsObject._cfObject }
}
extension NSSet : Sequence {
public typealias Iterator = NSEnumerator.Iterator
public func makeIterator() -> Iterator {
return self.objectEnumerator().makeIterator()
}
}
extension NSSet : CustomReflectable {
public var customMirror: Mirror { NSUnimplemented() }
}
open class NSMutableSet : NSSet {
open func add(_ object: Any) {
guard type(of: self) === NSMutableSet.self else {
NSRequiresConcreteImplementation()
}
_storage.insert(_SwiftValue.store(object))
}
open func remove(_ object: Any) {
guard type(of: self) === NSMutableSet.self else {
NSRequiresConcreteImplementation()
}
_storage.remove(_SwiftValue.store(object))
}
override public init(objects: UnsafePointer<AnyObject>!, count cnt: Int) {
super.init(objects: objects, count: cnt)
}
public convenience init() {
self.init(capacity: 0)
}
public required init(capacity numItems: Int) {
super.init(objects: [], count: 0)
}
public required convenience init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
open func addObjects(from array: [Any]) {
if type(of: self) === NSMutableSet.self {
for case let obj in array {
_storage.insert(_SwiftValue.store(obj))
}
} else {
array.forEach(add)
}
}
open func intersect(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.formIntersection(otherSet.map { _SwiftValue.store($0) })
} else {
for obj in self {
if !otherSet.contains(obj as! AnyHashable) {
remove(obj)
}
}
}
}
open func minus(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.subtract(otherSet.map { _SwiftValue.store($0) })
} else {
otherSet.forEach(remove)
}
}
open func removeAllObjects() {
if type(of: self) === NSMutableSet.self {
_storage.removeAll()
} else {
forEach(remove)
}
}
open func union(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage.formUnion(otherSet.map { _SwiftValue.store($0) })
} else {
otherSet.forEach(add)
}
}
open func setSet(_ otherSet: Set<AnyHashable>) {
if type(of: self) === NSMutableSet.self {
_storage = Set(otherSet.map { _SwiftValue.store($0) })
} else {
removeAllObjects()
union(otherSet)
}
}
}
/**************** Counted Set ****************/
open class NSCountedSet : NSMutableSet {
internal var _table: Dictionary<NSObject, Int>
public required init(capacity numItems: Int) {
_table = Dictionary<NSObject, Int>()
super.init(capacity: numItems)
}
public convenience init() {
self.init(capacity: 0)
}
public convenience init(array: [Any]) {
self.init(capacity: array.count)
for object in array {
let value = _SwiftValue.store(object)
if let count = _table[value] {
_table[value] = count + 1
} else {
_table[value] = 1
_storage.insert(value)
}
}
}
public convenience init(set: Set<AnyHashable>) {
self.init(array: Array(set))
}
public required convenience init?(coder: NSCoder) { NSUnimplemented() }
open override func copy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSCountedSet.self {
let countedSet = NSCountedSet()
countedSet._storage = self._storage
countedSet._table = self._table
return countedSet
}
return NSCountedSet(array: self.allObjects)
}
open override func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSCountedSet.self {
let countedSet = NSCountedSet()
countedSet._storage = self._storage
countedSet._table = self._table
return countedSet
}
return NSCountedSet(array: self.allObjects)
}
open func count(for object: Any) -> Int {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = _SwiftValue.store(object)
guard let count = _table[value] else {
return 0
}
return count
}
open override func add(_ object: Any) {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = _SwiftValue.store(object)
if let count = _table[value] {
_table[value] = count + 1
} else {
_table[value] = 1
_storage.insert(value)
}
}
open override func remove(_ object: Any) {
guard type(of: self) === NSCountedSet.self else {
NSRequiresConcreteImplementation()
}
let value = _SwiftValue.store(object)
guard let count = _table[value] else {
return
}
if count > 1 {
_table[value] = count - 1
} else {
_table[value] = nil
_storage.remove(value)
}
}
open override func removeAllObjects() {
if type(of: self) === NSCountedSet.self {
_storage.removeAll()
_table.removeAll()
} else {
forEach(remove)
}
}
}
extension NSSet : _StructTypeBridgeable {
public typealias _StructType = Set<AnyHashable>
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 | d659ad5b700e3381e1c811006c5761e4 | 30.651575 | 154 | 0.570931 | 4.664636 | false | false | false | false |
ingresse/ios-sdk | IngresseSDK/Model/User.swift | 1 | 1762 | //
// Copyright © 2017 Ingresse. All rights reserved.
//
public class User: NSObject, Decodable {
@objc public var id: Int = 0
@objc public var name: String = ""
@objc public var email: String = ""
@objc public var type: String = ""
@objc public var username: String = ""
@objc public var ddi: String = ""
@objc public var phone: String = ""
@objc public var cellphone: String = ""
@objc public var pictures: [String: String] = [:]
@objc public var picture: String = ""
@objc public var social: [SocialAccount] = []
enum CodingKeys: String, CodingKey {
case id
case name
case email
case type
case username
case ddi
case phone
case cellphone
case pictures
case picture
case social
}
public override init() {}
public required init(from decoder: Decoder) throws {
guard let container = try? decoder.container(keyedBy: CodingKeys.self) else { return }
id = container.decodeKey(.id, ofType: Int.self)
name = container.decodeKey(.name, ofType: String.self)
email = container.decodeKey(.email, ofType: String.self)
type = container.decodeKey(.type, ofType: String.self)
username = container.decodeKey(.username, ofType: String.self)
ddi = container.decodeKey(.ddi, ofType: String.self)
phone = container.decodeKey(.phone, ofType: String.self)
cellphone = container.decodeKey(.cellphone, ofType: String.self)
pictures = container.decodeKey(.pictures, ofType: [String: String].self)
picture = container.decodeKey(.picture, ofType: String.self)
social = container.decodeKey(.social, ofType: [SocialAccount].self)
}
}
| mit | 4143e648f76ca64ef5678e16842267da | 34.938776 | 94 | 0.634867 | 4.4025 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/View/GuessYouLikeCell.swift | 1 | 1707 | //
// GuessYouLikeCell.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/22.
// Copyright © 2016年 CoderST. All rights reserved.
// 猜你喜欢
import UIKit
class GuessYouLikeCell: UICollectionViewCell {
fileprivate lazy var iconImageView : UIImageView = {
let iconImageView = UIImageView()
iconImageView.contentMode = .scaleAspectFill
return iconImageView
}()
fileprivate lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 12)
titleLabel.numberOfLines = 2
return titleLabel
}()
var guessItem : HotSubModel?{
didSet{
iconImageView.sd_setImage( with: URL(string: guessItem?.albumCoverUrl290 ?? ""), placeholderImage: UIImage(named: "placeholder_image"))
titleLabel.text = guessItem?.title
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(iconImageView)
contentView.addSubview(titleLabel)
titleLabel.preferredMaxLayoutWidth = contentView.bounds.width
iconImageView.snp.makeConstraints { (make) in
make.left.top.right.equalTo(contentView)
make.height.width.equalTo(contentView.snp.width)
}
titleLabel.snp.makeConstraints { (make) in
make.left.equalTo(contentView)
make.right.equalTo(contentView)
make.top.equalTo(iconImageView.snp.bottom)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 9e9872160ddcce9481135b2b22273400 | 27.266667 | 147 | 0.612618 | 5.032641 | false | false | false | false |
huonw/swift | test/Inputs/clang-importer-sdk/swift-modules-without-ns/Darwin.swift | 36 | 1023 | @_exported import Darwin // Clang module
//===----------------------------------------------------------------------===//
// MacTypes.h
//===----------------------------------------------------------------------===//
public let noErr: OSStatus = 0
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
public struct DarwinBoolean : Boolean, ExpressibleByBooleanLiteral {
var value: UInt8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
/// The value of `self`, expressed as a `Bool`.
public var boolValue: Bool {
return value != 0
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
public // COMPILER_INTRINSIC
func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean {
return DarwinBoolean(x)
}
public // COMPILER_INTRINSIC
func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool {
return Bool(x)
}
| apache-2.0 | 2a1ab89916eb2fb5286d21e35b685172 | 25.230769 | 80 | 0.581623 | 4.692661 | false | false | false | false |
colemancda/SwiftMoment | SwiftMoment/SwiftMoment/Duration.swift | 1 | 2034 | //
// Duration.swift
// SwiftMoment
//
// Created by Adrian on 19/01/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
import Foundation
public struct Duration: Equatable {
let interval: NSTimeInterval
public init(value: NSTimeInterval) {
self.interval = value
}
public init(value: Int) {
self.interval = NSTimeInterval(value)
}
public var years: Double {
return interval / 31536000 // 365 days
}
public var quarters: Double {
return interval / 7776000 // 3 months
}
public var months: Double {
return interval / 2592000 // 30 days
}
public var days: Double {
return interval / 86400 // 24 hours
}
public var hours: Double {
return interval / 3600 // 60 minutes
}
public var minutes: Double {
return interval / 60
}
public var seconds: Double {
return interval
}
public func ago() -> Moment {
return moment().substract(self)
}
public func add(duration: Duration) -> Duration {
return Duration(value: self.interval + duration.interval)
}
public func substract(duration: Duration) -> Duration {
return Duration(value: self.interval - duration.interval)
}
public func isEqualTo(duration: Duration) -> Bool {
return self.interval == duration.interval
}
}
extension Duration: CustomStringConvertible {
public var description: String {
let formatter = NSDateComponentsFormatter()
formatter.calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
formatter.calendar?.timeZone = NSTimeZone(abbreviation: "UTC")!
formatter.allowedUnits = [.Year, .Month, .WeekOfMonth, .Day, .Hour, .Minute, .Second]
let referenceDate = NSDate(timeIntervalSinceReferenceDate: 0)
let intervalDate = NSDate(timeInterval: self.interval, sinceDate: referenceDate)
return formatter.stringFromDate(referenceDate, toDate: intervalDate)!
}
}
| bsd-2-clause | c3276fed90769846140e739c43404ce3 | 25.076923 | 93 | 0.651426 | 4.741259 | false | false | false | false |
IBM-Swift/Kitura | Sources/Kitura/staticFileServer/FileServer.swift | 1 | 14816 | /*
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import LoggerAPI
import Foundation
extension StaticFileServer {
// MARK: FileServer
class FileServer {
/// Serve "index.html" files in response to a request on a directory.
private let serveIndexForDirectory: Bool
/// Redirect to trailing "/" when the pathname is a dir.
private let redirect: Bool
/// the path from where the files are served
private let servingFilesPath: String
/// If a file is not found, the given extensions will be added to the file name and searched for.
/// The first that exists will be served.
private let possibleExtensions: [String]
/// A setter for response headers.
private let responseHeadersSetter: ResponseHeadersSetter?
/// Whether accepts range requests or not
let acceptRanges: Bool
/// A default index to be served if the requested path is not found.
/// This is intended to be used by single page applications.
let defaultIndex: String?
init(servingFilesPath: String, options: StaticFileServer.Options,
responseHeadersSetter: ResponseHeadersSetter?) {
self.possibleExtensions = options.possibleExtensions
self.serveIndexForDirectory = options.serveIndexForDirectory
self.redirect = options.redirect
self.acceptRanges = options.acceptRanges
self.servingFilesPath = servingFilesPath
self.responseHeadersSetter = responseHeadersSetter
self.defaultIndex = options.defaultIndex
}
func getFilePath(from request: RouterRequest) -> String? {
var filePath = servingFilesPath
guard let requestPath = request.parsedURLPath.path else {
return nil
}
var matchedPath = request.matchedPath
if matchedPath.hasSuffix("*") {
matchedPath = String(matchedPath.dropLast())
}
if !matchedPath.hasSuffix("/") {
matchedPath += "/"
}
if requestPath.hasPrefix(matchedPath) {
filePath += "/"
let url = String(requestPath.dropFirst(matchedPath.count))
if let decodedURL = url.removingPercentEncoding {
filePath += decodedURL
} else {
Log.warning("unable to decode url \(url)")
filePath += url
}
}
if filePath.hasSuffix("/") {
if serveIndexForDirectory {
filePath += "index.html"
} else {
return nil
}
}
return filePath
}
func serveFile(_ filePath: String, requestPath: String, queryString: String, response: RouterResponse) {
let fileManager = FileManager()
var isDirectory = ObjCBool(false)
if fileManager.fileExists(atPath: filePath, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
serveExistingFile(filePath, requestPath: requestPath, queryString: queryString,
isDirectory: isDirectoryBool, response: response)
return
}
if tryToServeWithExtensions(filePath, response: response) {
return
}
// We haven't been able to find the requested path. For single page applications,
// a default fallback index may be configured. Before we serve the default index
// we make sure that this is a not a direct file request. The best check we could
// run for that is if the requested file contains a '.'. This is inspired by:
// https://github.com/bripkens/connect-history-api-fallback
let isDirectFileAccess = filePath.split(separator: "/").last?.contains(".") ?? false
if isDirectFileAccess == false, let defaultIndex = self.defaultIndex {
serveDefaultIndex(defaultIndex: defaultIndex, response: response)
}
}
fileprivate func serveDefaultIndex(defaultIndex: String, response: RouterResponse) {
do {
try response.send(fileName: servingFilesPath + defaultIndex)
} catch {
response.error = Error.failedToRedirectRequest(path: servingFilesPath + "/", chainedError: error)
}
}
private func tryToServeWithExtensions(_ filePath: String, response: RouterResponse) -> Bool {
var served = false
let filePathWithPossibleExtensions = possibleExtensions.map { filePath + "." + $0 }
for filePathWithExtension in filePathWithPossibleExtensions {
served = served || serveIfNonDirectoryFile(atPath: filePathWithExtension, response: response)
}
return served
}
private func serveExistingFile(_ filePath: String, requestPath: String, queryString: String,
isDirectory: Bool, response: RouterResponse) {
if isDirectory {
if redirect {
do {
try response.redirect(requestPath + "/" + queryString)
} catch {
response.error = Error.failedToRedirectRequest(path: requestPath + "/", chainedError: error)
}
}
} else {
serveNonDirectoryFile(filePath, response: response)
}
}
@discardableResult
private func serveIfNonDirectoryFile(atPath path: String, response: RouterResponse) -> Bool {
var isDirectory = ObjCBool(false)
if FileManager().fileExists(atPath: path, isDirectory: &isDirectory) {
#if !os(Linux) || swift(>=4.1)
let isDirectoryBool = isDirectory.boolValue
#else
let isDirectoryBool = isDirectory
#endif
if !isDirectoryBool {
serveNonDirectoryFile(path, response: response)
return true
}
}
return false
}
private func serveNonDirectoryFile(_ filePath: String, response: RouterResponse) {
if !isValidFilePath(filePath) {
return
}
do {
let fileAttributes = try FileManager().attributesOfItem(atPath: filePath)
// At this point only GET or HEAD are expected
let request = response.request
let method = request.serverRequest.method
response.headers["Accept-Ranges"] = acceptRanges ? "bytes" : "none"
responseHeadersSetter?.setCustomResponseHeaders(response: response,
filePath: filePath,
fileAttributes: fileAttributes)
// Check headers to see if it is a Range request
if acceptRanges,
method == "GET", // As per RFC, Only GET request can be Range Request
let rangeHeader = request.headers["Range"],
RangeHeader.isBytesRangeHeader(rangeHeader),
let fileSize = (fileAttributes[FileAttributeKey.size] as? NSNumber)?.uint64Value {
// At this point it looks like the client requested a Range Request
if let rangeHeaderValue = try? RangeHeader.parse(size: fileSize, headerValue: rangeHeader),
rangeHeaderValue.type == "bytes",
!rangeHeaderValue.ranges.isEmpty {
// At this point range is valid and server is able to serve it
if ifRangeHeaderShouldPreventPartialReponse(requestHeaders: request.headers, fileAttributes: fileAttributes) {
// If-Range header prevented a partial response. Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
} else {
// Send a partial response
serveNonDirectoryPartialFile(filePath, fileSize: fileSize, ranges: rangeHeaderValue.ranges, response: response)
}
} else {
// Send not satisfiable response
serveNotSatisfiable(filePath, fileSize: fileSize, response: response)
}
} else {
// Regular request OR Syntactically invalid range request OR fileSize was not available
if method == "HEAD" {
// Send only headers
_ = response.send(status: .OK)
} else {
if let etag = request.headers["If-None-Match"],
etag == CacheRelatedHeadersSetter.calculateETag(from: fileAttributes) {
response.statusCode = .notModified
} else {
// Send the entire file
try response.send(fileName: filePath)
response.statusCode = .OK
}
}
}
} catch {
Log.error("serving file at path \(filePath), error: \(error)")
}
}
private func isValidFilePath(_ filePath: String) -> Bool {
guard let absoluteBasePath = NSURL(fileURLWithPath: servingFilesPath).standardizingPath?.absoluteString,
let standardisedPath = NSURL(fileURLWithPath: filePath).standardizingPath?.absoluteString else {
return false
}
return standardisedPath.hasPrefix(absoluteBasePath)
}
private func serveNotSatisfiable(_ filePath: String, fileSize: UInt64, response: RouterResponse) {
response.headers["Content-Range"] = "bytes */\(fileSize)"
_ = response.send(status: .requestedRangeNotSatisfiable)
}
private func serveNonDirectoryPartialFile(_ filePath: String, fileSize: UInt64, ranges: [Range<UInt64>], response: RouterResponse) {
let contentType = ContentType.sharedInstance.getContentType(forFileName: filePath)
if ranges.count == 1 {
let data = FileServer.read(contentsOfFile: filePath, inRange: ranges[0])
// Send a single part response
response.headers["Content-Type"] = contentType
response.headers["Content-Range"] = "bytes \(ranges[0].lowerBound)-\(ranges[0].upperBound)/\(fileSize)"
response.send(data: data ?? Data())
response.statusCode = .partialContent
} else {
// Send multi part response
let boundary = "KituraBoundary\(UUID().uuidString)" // Maybe a better boundary can be calculated in the future
response.headers["Content-Type"] = "multipart/byteranges; boundary=\(boundary)"
var data = Data()
ranges.forEach { range in
let fileData = FileServer.read(contentsOfFile: filePath, inRange: range) ?? Data()
var partHeader = "--\(boundary)\r\n"
partHeader += "Content-Range: bytes \(range.lowerBound)-\(range.upperBound)/\(fileSize)\r\n"
partHeader += (contentType == nil ? "" : "Content-Type: \(contentType!)\r\n")
partHeader += "\r\n"
data.append(Data(partHeader.utf8))
data.append(fileData)
data.append(Data("\r\n".utf8))
}
data.append(Data("--\(boundary)--".utf8))
response.send(data: data)
response.statusCode = .partialContent
}
}
private func ifRangeHeaderShouldPreventPartialReponse(requestHeaders headers: Headers, fileAttributes: [FileAttributeKey : Any]) -> Bool {
// If-Range is optional
guard let ifRange = headers["If-Range"], !ifRange.isEmpty else {
return false
}
// If-Range can be one of two values: ETag or Last-Modified but not both.
// If-Range as ETag
if (ifRange.contains("\"")) {
if let etag = CacheRelatedHeadersSetter.calculateETag(from: fileAttributes),
!etag.isEmpty,
ifRange.contains(etag) {
return false
}
return true
}
// If-Range as Last-Modified
if let ifRangeLastModified = FileServer.date(from: ifRange),
let lastModified = fileAttributes[FileAttributeKey.modificationDate] as? Date,
floor(lastModified.timeIntervalSince1970) > floor(ifRangeLastModified.timeIntervalSince1970) {
return true
}
return false
}
/// Helper function to convert http date Strings into Date
static func date(from httpDate: String) -> Date? {
let df = DateFormatter()
df.dateFormat = "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz"
return df.date(from:httpDate)
}
/// Helper function to read bytes (of a given range) of a file into data
static func read(contentsOfFile filePath: String, inRange range: Range<UInt64>) -> Data? {
let file = FileHandle(forReadingAtPath: filePath)
file?.seek(toFileOffset: range.lowerBound)
// range is inclusive to make sure to increate upper bound by 1
let data = file?.readData(ofLength: range.count + 1)
file?.closeFile()
return data
}
}
}
| apache-2.0 | 73a0d59d8a5611ac0adfee37102c20e6 | 45.591195 | 146 | 0.560813 | 5.698462 | false | false | false | false |
sealgair/MusicKit | MusicKit/ScaleQuality.swift | 2 | 1209 | // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
public enum ScaleQuality: String {
case Chromatic = "Chromatic"
case Wholetone = "Wholetone"
case Octatonic1 = "Octatonic mode 1"
case Octatonic2 = "Octatonic mode 2"
case Major = "Major"
case Dorian = "Dorian"
case Phrygian = "Phrygian"
case Lydian = "Lydian"
case Mixolydian = "Mixolydian"
case Minor = "Minor"
case Locrian = "Locrian"
public var intervals: [Float] {
switch self {
case Chromatic: return [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
case Wholetone: return [2, 2, 2, 2, 2, 2]
case Octatonic1: return [2, 1, 2, 1, 2, 1, 2]
case Octatonic2: return [1, 2, 1, 2, 1, 2, 1]
case Major: return [2, 2, 1, 2, 2, 2]
case Dorian: return [2, 1, 2, 2, 2, 1]
case Phrygian: return [1, 2, 2, 2, 1, 2]
case Lydian: return [2, 2, 2, 1, 2, 2]
case Mixolydian: return [2, 2, 1, 2, 2, 1]
case Minor: return [2, 1, 2, 2, 1, 2]
case Locrian: return [1, 2, 2, 1, 2, 2]
}
}
}
extension ScaleQuality: CustomStringConvertible {
public var description: String {
return rawValue
}
}
| mit | 30df520d30f545c290ee25c594f37abf | 30 | 64 | 0.569065 | 3.173228 | false | false | false | false |
mark644873613/Doctor-lives | Doctor lives/Doctor lives/classes/Home首页/CourseWareCell.swift | 1 | 2769 | //
// CourseWareCell.swift
// Doctor lives
//
// Created by qianfeng on 16/11/3.
// Copyright © 2016年 zhb. All rights reserved.
//
import UIKit
class CourseWareCell: UITableViewCell {
@IBOutlet weak var categoriesLabel: UILabel!
@IBOutlet weak var hospitalName: UILabel!
@IBOutlet weak var authorName: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var courseImage: UIImageView!
//点击事件
var jumpClosure:HomeJumpClosure?
//数据下载
var listModel:coursewareList?{
didSet{
showData()
}
}
//显示数据
func showData(){
//图片
let imageData=listModel?.cover
let url=NSURL(string: imageData!)
courseImage.kf_setImageWithURL(url!, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
//title
let titleData=listModel?.title
titleLabel.text=titleData
//医院
let hospitalNameData=listModel?.authorArray?.hospital?.name
hospitalName.text=hospitalNameData
//科室
let categoriesData=listModel?.categoriesArray
let vnt=categoriesData?.count
var ss="#"
for i in 0..<vnt!{
let model=(categoriesData![i].name)
ss = ss + model! + " "
}
//print(ss)
categoriesLabel.text=ss
//姓名
let nameLabelData=listModel?.authorArray?.name
nameLabel.text=nameLabelData
//职称
let authorNameData=listModel?.authorArray?.title
authorName.text=authorNameData
}
//创建cell的方法
class func createCourseCellFor(tableView: UITableView, atIndexPath indexPath: NSIndexPath, listModel: [coursewareList]?) -> CourseWareCell {
let cellId = "courseWareCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CourseWareCell
if nil == cell {
cell = NSBundle.mainBundle().loadNibNamed("CourseWareCell", owner: nil, options: nil).last as? CourseWareCell
}
//显示数据
cell?.listModel = listModel![indexPath.row]
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
//创建点击事件
let g=UITapGestureRecognizer(target: self, action: #selector(tapAction))
addGestureRecognizer(g)
}
//实现手势点击方法
func tapAction(){
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 6913f198d7a96be07d2740566a9da4f5 | 27.168421 | 144 | 0.613976 | 4.83906 | false | false | false | false |
vapor/vapor | Sources/Vapor/Utilities/Base64.swift | 1 | 8602 | /// IMPORTANT:
///
/// These APIs are `internal` rather than `public` on purpose - specifically due to the high risk of name collisions
/// in the extensions and the extreme awkwardness of vendor prefixing for this use case.
import struct Foundation.Data
extension BaseNEncoding {
/// Specialization of ``encode(_:base:pad:using:)`` for Base64.
@inlinable
internal static func encode64<C>(_ decoded: C, pad: UInt8?, using tab: [UInt8]) -> [UInt8] where C: RandomAccessCollection, C.Element == UInt8, C.Index == Int {
assert(tab.count == 64, "Mapping table must have exactly 64 elements.")
guard !decoded.isEmpty else { return [] }
let outlen = sizeEnc(for: 6, count: decoded.count), padding = self.padding(for: 6, count: outlen), inp = decoded
return .init(unsafeUninitializedCapacity: outlen + padding) { p, n in
var idx = inp.startIndex, b00 = 0, b01 = 0; func get(_ offset: Int) -> Int { Int(truncatingIfNeeded: inp[idx &+ offset]) }
while inp.endIndex &- idx >= 3 {
let b0 = get(0), b1 = get(1), b2 = get(2)
p[n &+ 0] = tab[((b0 & 0xfc) &>> 2) ]; p[n &+ 1] = tab[((b0 & 0x03) &<< 4) | (b1 &>> 4)]
p[n &+ 2] = tab[((b1 & 0x0f) &<< 2) | (b2 &>> 6)]; p[n &+ 3] = tab[((b2 & 0x3f) ) ]
(idx, n) = (idx &+ 3, n &+ 4)
}
switch padding {
case 1: b01 = get(1); p[n &+ 2] = tab[((b01 & 0x0f) &<< 2) ]; fallthrough
case 2: b00 = get(0); p[n &+ 1] = tab[((b00 & 0x03) &<< 4) | (b01 &>> 4)]
p[n &+ 0] = tab[((b00 & 0xfc) &>> 2) ]
case 0: return; default: fatalError("unreachable")
}
n &+= 4 &- padding
if let pad = pad, padding > 0 { p.baseAddress!.advanced(by: n).assign(repeating: pad, count: padding); n &+= padding }
}
}
/// Specialization of ``decode(_:base:using:)`` for Base64 with no ignores and optional padding.
@inlinable
internal static func decode64<C>(_ encoded: C, using mapping: [UInt8]) -> [UInt8]?
where C: RandomAccessCollection, C.Element == UInt8, C.Index == Int
{
guard !encoded.isEmpty else { return [] }
let outlen = self.sizeDec(for: 6, count: encoded.count)
return try? [UInt8].init(unsafeUninitializedCapacity: outlen) { p, n in // N.B.: throwing is the only correct way to signal failure
var idx = encoded.startIndex, w = 0 as UInt32
func get(_ offset: Int) -> UInt32 { UInt32(truncatingIfNeeded: mapping[Int(truncatingIfNeeded: encoded[idx &+ offset])]) &<< (24 &- (offset &<< 3)) }
while encoded.endIndex &- idx >= 4 {
w = get(0) | get(1) | get(2) | get(3)
if w & 0b11000000_11000000_11000000_11000000 == 0 {
p[n &+ 0] = UInt8(truncatingIfNeeded: (w &>> 22) | ((w &>> 20) & 0x3))
p[n &+ 1] = UInt8(truncatingIfNeeded: ((w &>> 12) & 0xf0) | ((w &>> 10) & 0x0f))
p[n &+ 2] = UInt8(truncatingIfNeeded: ((w &>> 2) & 0xc0) | (w & 0x3f))
(n, idx) = (n &+ 3, idx &+ 4)
} else if w & 0b11000000_11000000_11000000_11000000 == 0b00000000_00000000_00000000_10000000, idx &+ 4 == encoded.endIndex {
p[n &+ 0] = UInt8(truncatingIfNeeded: (w &>> 22) | ((w &>> 20) & 0x3))
p[n &+ 1] = UInt8(truncatingIfNeeded: ((w &>> 12) & 0xf0) | ((w &>> 10) & 0x0f))
(n, idx) = (n &+ 2, idx &+ 4)
} else if w & 0b11000000_11000000_11000000_11000000 == 0b00000000_00000000_10000000_10000000, idx &+ 4 == encoded.endIndex {
p[n &+ 0] = UInt8(truncatingIfNeeded: (w &>> 22) | ((w &>> 20) & 0x3))
(n, idx) = (n &+ 1, idx &+ 4)
} else {
throw BreakLoopError()
}
}
switch encoded.endIndex &- idx {
case 3:
w = get(0) | get(1) | get(2)
guard w & 0b11000000_11000000_11000000_11111111 == 0 else { throw BreakLoopError() }
p[n &+ 0] = UInt8(truncatingIfNeeded: (w &>> 22) | ((w &>> 20) & 0x3))
p[n &+ 1] = UInt8(truncatingIfNeeded: ((w &>> 12) & 0xf0) | ((w &>> 10) & 0x0f))
n &+= 2
case 2:
w = get(0) | get(1)
guard w & 0b11000000_11000000_11111111_11111111 == 0 else { throw BreakLoopError() }
p[n &+ 0] = UInt8(truncatingIfNeeded: (w &>> 22) | ((w &>> 20) & 0x3))
n &+= 1
case 0:
break
default: throw BreakLoopError()
}
}
}
}
public enum Base64 {
private static let baseAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
/// Canonical Base64 encoding per [RFC 4648 §4](https://datatracker.ietf.org/doc/html/rfc4648#section-4)
public static let canonical: BaseNEncoding = .init(
bits: 6/*64.trailingZeroBitCount*/,
pad: "=",
lookupTable: .init(Self.baseAlphabet)
)
/// Alias for ``canonical``.
public static let `default`: BaseNEncoding = Self.canonical
/// The variant Base64 encoding used by BCrypt, using `.` instead of `/` for value 62 and ignoring padding.
public static let bcrypt: BaseNEncoding = .init(
bits: 6/*64.trailingZeroBitCount*/,
lookupTable: Self.baseAlphabet.map { $0 == "+" ? "." : $0 }
)
}
extension Array where Element == UInt8 {
/// Decode a string in canonical Base32-encoded representation.
@inlinable
public init?(decodingBase64 str: String) {
guard let decoded = str.utf8.withContiguousStorageIfAvailable({ Array(decodingBase64: $0) }) ?? Array(decodingBase64: Array(str.utf8)) else { return nil }
self = decoded
}
/// Decode a string in Bcrypt-flavored Base64-encoded representation.
@inlinable
public init?(decodingBcryptBase64 str: String) {
guard let decoded = str.utf8.withContiguousStorageIfAvailable({ Array(decodingBcryptBase64: $0) }) ?? Array(decodingBcryptBase64: Array(str.utf8)) else { return nil }
self = decoded
}
@inlinable
public init?<C>(decodingBase64 bytes: C) where C: RandomAccessCollection, C.Element == UInt8, C.Index == Int {
guard let decoded = Base64.default.decode(bytes) else { return nil }
self = decoded
}
@inlinable
public init?<C>(decodingBcryptBase64 bytes: C) where C: RandomAccessCollection, C.Element == UInt8, C.Index == Int {
guard let decoded = Base64.bcrypt.decode(bytes) else { return nil }
self = decoded
}
}
extension RandomAccessCollection where Element == UInt8, Index == Int {
@inlinable
public func base64Bytes() -> [UInt8] { Base64.default.encode(self) }
@inlinable
public func base64String() -> String { .init(decoding: self.base64Bytes(), as: Unicode.ASCII.self) }
@inlinable
public func bcryptBase64Bytes() -> [UInt8] { Base64.bcrypt.encode(self) }
@inlinable
public func bcryptBase64String() -> String { .init(decoding: self.bcryptBase64Bytes(), as: Unicode.ASCII.self) }
}
extension String {
@inlinable
public func base64Bytes() -> [UInt8] { self.utf8.withContiguousStorageIfAvailable { $0.base64Bytes() } ?? Array(self.utf8).base64Bytes() }
@inlinable
public func base64String() -> String { .init(decoding: self.base64Bytes(), as: Unicode.ASCII.self) }
@inlinable
public func bcryptBase64Bytes() -> [UInt8] { self.utf8.withContiguousStorageIfAvailable { $0.bcryptBase64Bytes() } ?? Array(self.utf8).bcryptBase64Bytes() }
@inlinable
public func bcryptBase64String() -> String { .init(decoding: self.bcryptBase64Bytes(), as: Unicode.ASCII.self) }
}
extension Substring {
@inlinable
public func base64Bytes() -> [UInt8] { self.utf8.withContiguousStorageIfAvailable { $0.base64Bytes() } ?? Array(self.utf8).base64Bytes() }
@inlinable
public func base64String() -> String { .init(decoding: self.base64Bytes(), as: Unicode.ASCII.self) }
@inlinable
public func bcryptBase64Bytes() -> [UInt8] { self.utf8.withContiguousStorageIfAvailable { $0.bcryptBase64Bytes() } ?? Array(self.utf8).bcryptBase64Bytes() }
@inlinable
public func bcryptBase64String() -> String { .init(decoding: self.bcryptBase64Bytes(), as: Unicode.ASCII.self) }
}
| mit | ff8bee9620fd7f08da2da5b916ca29d6 | 50.813253 | 174 | 0.572259 | 3.822667 | false | false | false | false |
lyp1992/douyu-Swift | YPTV/YPTV/Classes/Tools/YPPageView/YPTitleView.swift | 1 | 11498 | //
// HYTitleView.swift
// HYContentPageView
//
// Created by xiaomage on 2016/10/27.
// Copyright © 2016年 seemygo. All rights reserved.
//
import UIKit
// MARK:- 定义协议
protocol YPTitleViewDelegate : class {
func titleView(_ titleView : YPTitleView, selectedIndex index : Int)
}
class YPTitleView: UIView {
// MARK: 对外属性
weak var delegate : YPTitleViewDelegate?
// MARK: 定义属性
fileprivate var titles : [String]!
fileprivate var style : YPPageStyle!
fileprivate var currentIndex : Int = 0
// MARK: 存储属性
fileprivate lazy var titleLabels : [UILabel] = [UILabel]()
// MARK: 控件属性
fileprivate lazy var scrollView : UIScrollView = {
let scrollV = UIScrollView()
scrollV.frame = self.bounds
scrollV.showsHorizontalScrollIndicator = false
scrollV.scrollsToTop = false
return scrollV
}()
fileprivate lazy var splitLineView : UIView = {
let splitView = UIView()
splitView.backgroundColor = UIColor.lightGray
let h : CGFloat = 0.5
splitView.frame = CGRect(x: 0, y: self.frame.height - h, width: self.frame.width, height: h)
return splitView
}()
fileprivate lazy var bottomLine : UIView = {
let bottomLine = UIView()
bottomLine.backgroundColor = self.style.bottomLineColor
return bottomLine
}()
fileprivate lazy var coverView : UIView = {
let coverView = UIView()
coverView.backgroundColor = self.style.coverBgColor
coverView.alpha = 0.7
return coverView
}()
// MARK: 计算属性
fileprivate lazy var normalColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.normalColor)
fileprivate lazy var selectedColorRGB : (r : CGFloat, g : CGFloat, b : CGFloat) = self.getRGBWithColor(self.style.selectColor)
// MARK: 自定义构造函数
init(frame: CGRect, titles : [String], style : YPPageStyle) {
super.init(frame: frame)
self.titles = titles
self.style = style
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面内容
extension YPTitleView {
fileprivate func setupUI() {
// 1.添加Scrollview
addSubview(scrollView)
// 2.添加底部分割线
addSubview(splitLineView)
// 3.设置所有的标题Label
setupTitleLabels()
// 4.设置Label的位置
setupTitleLabelsPosition()
// 5.设置底部的滚动条
if style.isBottomLineShow {
setupBottomLine()
}
// 6.设置遮盖的View
if style.isShowCoverView {
setupCoverView()
}
}
fileprivate func setupTitleLabels() {
for (index, title) in titles.enumerated() {
let label = UILabel()
label.tag = index
label.text = title
label.textColor = index == 0 ? style.selectColor : style.normalColor
label.font = UIFont.systemFont(ofSize: style.fontSize)
label.textAlignment = .center
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick(_ :)))
label.addGestureRecognizer(tapGes)
titleLabels.append(label)
scrollView.addSubview(label)
}
}
fileprivate func setupTitleLabelsPosition() {
var titleX: CGFloat = 0.0
var titleW: CGFloat = 0.0
let titleY: CGFloat = 0.0
let titleH : CGFloat = frame.height
let count = titles.count
for (index, label) in titleLabels.enumerated() {
if style.isScrollEnable {
let rect = (label.text! as NSString).boundingRect(with: CGSize(width: CGFloat(MAXFLOAT), height: 0.0), options: .usesLineFragmentOrigin, attributes: [NSAttributedStringKey.font : UIFont.systemFont(ofSize: style.fontSize)], context: nil)
titleW = rect.width
if index == 0 {
titleX = style.titleMargin * 0.5
} else {
let preLabel = titleLabels[index - 1]
titleX = preLabel.frame.maxX + style.titleMargin
}
} else {
titleW = frame.width / CGFloat(count)
titleX = titleW * CGFloat(index)
}
label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH)
// 放大的代码
if index == 0 {
let scale = style.isScaleAble ? style.scale : 1.0
label.transform = CGAffineTransform(scaleX: scale, y: scale)
}
}
if style.isScrollEnable {
scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + style.titleMargin * 0.5, height: 0)
}
}
fileprivate func setupBottomLine() {
scrollView.addSubview(bottomLine)
bottomLine.frame = titleLabels.first!.frame
bottomLine.frame.size.height = style.bottomLineHeight
bottomLine.frame.origin.y = bounds.height - style.bottomLineHeight
}
fileprivate func setupCoverView() {
scrollView.insertSubview(coverView, at: 0)
let firstLabel = titleLabels[0]
var coverW = firstLabel.frame.width
let coverH = style.coverHeight
var coverX = firstLabel.frame.origin.x
let coverY = (bounds.height - coverH) * 0.5
if style.isScrollEnable {
coverX -= style.coverMargin
coverW += style.coverMargin * 2
}
coverView.frame = CGRect(x: coverX, y: coverY, width: coverW, height: coverH)
coverView.layer.cornerRadius = style.coverRadius
coverView.layer.masksToBounds = true
}
}
// MARK:- 事件处理
extension YPTitleView {
@objc fileprivate func titleLabelClick(_ tap : UITapGestureRecognizer) {
// 0.获取当前Label
guard let currentLabel = tap.view as? UILabel else { return }
// 1.如果是重复点击同一个Title,那么直接返回
if currentLabel.tag == currentIndex { return }
// 2.获取之前的Label
let oldLabel = titleLabels[currentIndex]
// 3.切换文字的颜色
currentLabel.textColor = style.selectColor
oldLabel.textColor = style.normalColor
// 4.保存最新Label的下标值
currentIndex = currentLabel.tag
// 5.通知代理
delegate?.titleView(self, selectedIndex: currentIndex)
// 6.居中显示
contentViewDidEndScroll()
// 7.调整bottomLine
if style.isBottomLineShow {
UIView.animate(withDuration: 0.15, animations: {
self.bottomLine.frame.origin.x = currentLabel.frame.origin.x
self.bottomLine.frame.size.width = currentLabel.frame.size.width
})
}
// 8.调整比例
if style.isScaleAble {
oldLabel.transform = CGAffineTransform.identity
currentLabel.transform = CGAffineTransform(scaleX: style.scale, y: style.scale)
}
// 9.遮盖移动
if style.isShowCoverView {
let coverX = style.isScrollEnable ? (currentLabel.frame.origin.x - style.coverMargin) : currentLabel.frame.origin.x
let coverW = style.isScrollEnable ? (currentLabel.frame.width + style.coverMargin * 2) : currentLabel.frame.width
UIView.animate(withDuration: 0.15, animations: {
self.coverView.frame.origin.x = coverX
self.coverView.frame.size.width = coverW
})
}
}
}
// MARK:- 获取RGB的值
extension YPTitleView {
fileprivate func getRGBWithColor(_ color : UIColor) -> (CGFloat, CGFloat, CGFloat) {
guard let components = color.cgColor.components else {
fatalError("请使用RGB方式给Title赋值颜色")
}
return (components[0] * 255, components[1] * 255, components[2] * 255)
}
}
// MARK:- 对外暴露的方法
extension YPTitleView {
func setTitleWithProgress(_ progress : CGFloat, sourceIndex : Int, targetIndex : Int) {
// 1.取出sourceLabel/targetLabel
let sourceLabel = titleLabels[sourceIndex]
let targetLabel = titleLabels[targetIndex]
// 3.颜色的渐变(复杂)
// 3.1.取出变化的范围
let colorDelta = (selectedColorRGB.0 - normalColorRGB.0, selectedColorRGB.1 - normalColorRGB.1, selectedColorRGB.2 - normalColorRGB.2)
// 3.2.变化sourceLabel
sourceLabel.textColor = UIColor(r: selectedColorRGB.0 - colorDelta.0 * progress, g: selectedColorRGB.1 - colorDelta.1 * progress, b: selectedColorRGB.2 - colorDelta.2 * progress)
// 3.2.变化targetLabel
targetLabel.textColor = UIColor(r: normalColorRGB.0 + colorDelta.0 * progress, g: normalColorRGB.1 + colorDelta.1 * progress, b: normalColorRGB.2 + colorDelta.2 * progress)
// 4.记录最新的index
currentIndex = targetIndex
let moveTotalX = targetLabel.frame.origin.x - sourceLabel.frame.origin.x
let moveTotalW = targetLabel.frame.width - sourceLabel.frame.width
// 5.计算滚动的范围差值
if style.isBottomLineShow {
bottomLine.frame.size.width = sourceLabel.frame.width + moveTotalW * progress
bottomLine.frame.origin.x = sourceLabel.frame.origin.x + moveTotalX * progress
}
// 6.放大的比例
if style.isScaleAble {
let scaleDelta = (style.scale - 1.0) * progress
sourceLabel.transform = CGAffineTransform(scaleX: style.scale - scaleDelta, y: style.scale - scaleDelta)
targetLabel.transform = CGAffineTransform(scaleX: 1.0 + scaleDelta, y: 1.0 + scaleDelta)
}
// 7.计算cover的滚动
if style.isShowCoverView {
coverView.frame.size.width = style.isScrollEnable ? (sourceLabel.frame.width + 2 * style.coverMargin + moveTotalW * progress) : (sourceLabel.frame.width + moveTotalW * progress)
coverView.frame.origin.x = style.isScrollEnable ? (sourceLabel.frame.origin.x - style.coverMargin + moveTotalX * progress) : (sourceLabel.frame.origin.x + moveTotalX * progress)
}
}
func contentViewDidEndScroll() {
// 0.如果是不需要滚动,则不需要调整中间位置
guard style.isScrollEnable else { return }
// 1.获取获取目标的Label
let targetLabel = titleLabels[currentIndex]
// 2.计算和中间位置的偏移量
var offSetX = targetLabel.center.x - bounds.width * 0.5
if offSetX < 0 {
offSetX = 0
}
let maxOffset = scrollView.contentSize.width - bounds.width
if offSetX > maxOffset {
offSetX = maxOffset
}
// 3.滚动UIScrollView
scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: true)
}
}
| mit | 587fd91c1578cba420f3dd9e0754cf82 | 33.523511 | 252 | 0.595206 | 4.798693 | false | false | false | false |
Caiflower/SwiftWeiBo | 花菜微博/花菜微博/Classes/Tools(工具)/CFAddition(Swift)/CommonView/CFTextLabel.swift | 1 | 9876 | //
// CFTextLabel.swift
// CFTextLable
//
// Created by 花菜 on 2017/1/12.
// Copyright © 2017年 花菜. All rights reserved.
//
import UIKit
@objc public protocol CFTextLabelDelegate: NSObjectProtocol {
/// 选中链接文本
///
/// - Parameters:
/// - textlable: textLabel
/// - text: 选中的文本
@objc optional func textLabelDidSelectedLinkText(textlable: CFTextLabel, text: String)
}
public class CFTextLabel: UILabel {
/// 链接文本颜色
public var linkTextColor = UIColor.blue
/// 选中文本的背景色
public var selectedBackgroundColor = UIColor.lightGray
/// 选中文本代理
public weak var delegate: CFTextLabelDelegate?
// 正则匹配策略
fileprivate let patterns = ["[a-zA-z]+://[a-zA-Z0-9/\\.]*", "#.*?#", "@[\\u4e00-\\u9fa5a-zA-Z0-9_-]*"]
// MARK: lazy properties
fileprivate lazy var linkRanges = [NSRange]()
fileprivate var selectedRange: NSRange?
fileprivate lazy var textStorage = NSTextStorage()
fileprivate lazy var layoutManager = NSLayoutManager()
fileprivate lazy var textContainer = NSTextContainer()
override init(frame: CGRect) {
super.init(frame: frame)
prepareTextLabel()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepareTextLabel()
}
public override func layoutSubviews() {
super.layoutSubviews()
textContainer.size = bounds.size
}
fileprivate func prepareTextLabel() {
// 关联属性
textStorage.addLayoutManager(layoutManager)
layoutManager.addTextContainer(textContainer)
textContainer.lineFragmentPadding = 0
// 开启用户交互
isUserInteractionEnabled = true
}
public override func sizeToFit() {
super.sizeToFit()
layoutIfNeeded()
}
// MARK: - override properties ,
//一但内容变化,需要让 textStorage响应变化!
public override var text: String? {
didSet{
// 重新准备文本内容
updateTextStore()
}
}
public override var attributedText: NSAttributedString? {
didSet {
updateTextStore()
}
}
public override var font: UIFont! {
didSet {
updateTextStore()
}
}
public override var textColor: UIColor! {
didSet {
updateTextStore()
}
}
/// 获取字形区域
fileprivate func glyphsRange()-> NSRange {
return NSRange(location: 0, length: textStorage.length)
}
fileprivate func glyphsOffset(range: NSRange) -> CGPoint {
let rect = layoutManager.boundingRect(forGlyphRange: range, in: textContainer)
let height = (bounds.height - rect.height) * 0.5
return CGPoint(x: 0, y: height)
}
public override func drawText(in rect: CGRect) {
let range = glyphsRange()
// 获取偏移
let offset = glyphsOffset(range: range)
// 绘制背景
layoutManager.drawBackground(forGlyphRange: range, at: offset)
// 绘制字形
layoutManager.drawGlyphs(forGlyphRange: range, at: CGPoint.zero)
}
// MARK: - touches 事件
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
// 获取选中的区域
selectedRange = linkRangeAtLocation(location: location)
// 设置富文本属性
modifySelectedAttribute(isSet: true)
}
// 移动
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let location = touches.first?.location(in: self) else {
return
}
if let range = linkRangeAtLocation(location: location) {
if !(range.location == selectedRange?.location && range.length == selectedRange?.length) {
modifySelectedAttribute(isSet: false)
selectedRange = range
modifySelectedAttribute(isSet: true)
}
} else {
modifySelectedAttribute(isSet: false)
}
}
// 结束触摸
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if selectedRange != nil {
let text = (textStorage.string as NSString).substring(with: selectedRange!)
delegate?.textLabelDidSelectedLinkText?(textlable: self, text: text)
let when = DispatchTime.now() + Double(Int64(0.25 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: when) {
self.modifySelectedAttribute(isSet: false)
}
}
}
// 取消
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
modifySelectedAttribute(isSet: false)
}
}
fileprivate extension CFTextLabel {
func linkRangeAtLocation(location: CGPoint) -> NSRange? {
if textStorage.length == 0 {
return nil
}
let offset = glyphsOffset(range: glyphsRange())
let point = CGPoint(x: offset.x + location.x, y: offset.y + location.y)
let index = layoutManager.glyphIndex(for: point, in: textContainer)
for r in linkRanges {
if index >= r.location && index <= r.location + r.length {
return r
}
}
return nil
}
/// 改变选中区域的富文本属性
///
/// - Parameter isSet: 是否改变
func modifySelectedAttribute(isSet: Bool) {
guard let range = selectedRange else {
return
}
var attributes = textStorage.attributes(at: 0, effectiveRange: nil)
attributes[NSForegroundColorAttributeName] = linkTextColor
if isSet {
attributes[NSBackgroundColorAttributeName] = selectedBackgroundColor
} else {
attributes[NSBackgroundColorAttributeName] = UIColor.clear
selectedRange = nil
}
// 添加富文本属性
textStorage.addAttributes(attributes, range: range)
// 重绘
setNeedsDisplay()
}
}
// MARK: - 更新textStorage
fileprivate extension CFTextLabel {
fileprivate func updateTextStore() {
guard let attributedText = attributedText else {
return
}
// 设置换行模式
let attrStringM = addLineBreakModel(attrString: attributedText)
// 正则匹配
regularLinkRanges(attrString: attrStringM)
// 设置链接的富文本属性
addLinkAttribute(attrString: attrStringM)
// 设置文本内容
textStorage.setAttributedString(attrStringM)
// 重绘
setNeedsDisplay()
}
}
// MARK: - 设置链接富文本属性
fileprivate extension CFTextLabel {
func addLinkAttribute(attrString: NSMutableAttributedString) {
if attrString.length == 0 {
return
}
var range = NSRange(location: 0, length: 0)
var attributes = attrString.attributes(at: 0, effectiveRange: &range)
attributes[NSFontAttributeName] = font
attributes[NSForegroundColorAttributeName] = textColor
// 添加富文本属性
attrString.addAttributes(attributes, range: range)
// 设置链接的文本颜色
attributes[NSForegroundColorAttributeName] = linkTextColor
// 遍历所有的链接数组添加属性
for r in linkRanges {
attrString.setAttributes(attributes, range: r)
}
}
}
// MARK: - 设置换行模式
fileprivate extension CFTextLabel {
func addLineBreakModel(attrString: NSAttributedString) -> NSMutableAttributedString {
let attrStringM = NSMutableAttributedString(attributedString: attrString)
if attrStringM.length == 0 {
return attrStringM
}
var range = NSRange(location: 0, length: 0)
var attributes = attrStringM.attributes(at: 0, effectiveRange: &range)
if let paragraphStyle = attributes[NSParagraphStyleAttributeName] as? NSMutableParagraphStyle {
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
return attrStringM
}
else {
// iOS 8.0 can not get the paragraphStyle directly
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
attributes[NSParagraphStyleAttributeName] = paragraphStyle
attrStringM.setAttributes(attributes, range: range)
return attrStringM
}
}
}
// MARK: - 正则匹配
fileprivate extension CFTextLabel {
/// 使用正则匹配所有的URL, #话题#, @name
///
/// - Parameter attrString: 需要匹配的富文本
func regularLinkRanges(attrString: NSAttributedString) {
// 清空数组
linkRanges.removeAll()
// 获取范围
let regxRange = NSRange(location: 0, length: attrString.string.characters.count)
// 根据匹配策略创建正则表达式
for pattern in patterns {
guard let regx = try? NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators) else {
continue
}
// 获取匹配结果
let matches = regx.matches(in: attrString.string, options: [], range: regxRange)
// 遍历匹配结果数组
for m in matches {
// 添加进数组
linkRanges.append(m.rangeAt(0))
}
}
}
}
| apache-2.0 | d58200d7a2fb3461963ade75fed252a6 | 29.540984 | 114 | 0.604187 | 5.070768 | false | false | false | false |
HarrisHan/Snapseed | Snapseed/Snapseed/SnapPanGestureRecognizer.swift | 1 | 1781 | //
// SnapPanGestureRecognizer.swift
// Snapseed
//
// Created by harris on 08/02/2017.
// Copyright © 2017 harris. All rights reserved.
//
import UIKit
import UIKit.UIGestureRecognizerSubclass
enum snapPanGestureRecognizerDirection {
case snapPanGestureRecognizerDirectionVertical
case snapPanGestureRecognizerDirectionHorizental
}
class SnapPanGestureRecognizer: UIPanGestureRecognizer {
var direction:snapPanGestureRecognizerDirection?
var moveX:CGFloat = 0.0
var moveY:CGFloat = 0.0
var drag:Bool = false
static let kDirectionPanThreshold:Float = 5.0
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
super.touchesMoved(touches, with: event)
if state == .failed { return }
let nowPoint = touches.first?.location(in: self.view)
let prePoint = touches.first?.previousLocation(in: self.view)
moveX += (prePoint?.x)! - (nowPoint?.x)!
moveY += (prePoint?.y)! - (nowPoint?.y)!
if !drag {
if fabsf(Float(moveX)) > SnapPanGestureRecognizer.kDirectionPanThreshold {
if direction! == .snapPanGestureRecognizerDirectionVertical {
self.state = .failed
} else {
drag = true
}
} else if fabsf(Float(moveY)) > SnapPanGestureRecognizer.kDirectionPanThreshold {
if direction! == .snapPanGestureRecognizerDirectionHorizental {
self.state = .failed
} else {
drag = true
}
}
}
}
override func reset() {
super.reset()
drag = false
moveX = 0
moveY = 0
}
}
| mit | 076be8ecb93f2f3712b3db3ce07d442c | 27.709677 | 93 | 0.589326 | 4.985994 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome | Pods/RxSwift/RxSwift/RxSwift/Observables/Implementations/Do.swift | 2 | 1553 | //
// Do.swift
// Rx
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class Do_<O: ObserverType> : Sink<O>, ObserverType, Disposable {
typealias Element = O.Element
typealias DoType = Do<Element>
let parent: DoType
init(parent: DoType, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
parent.eventHandler(event).recoverWith { error in
// catch clause
trySendError(observer, error)
self.dispose()
return SuccessResult
}.flatMap { _ -> RxResult<Void> in
trySend(observer, event)
if event.isStopEvent {
self.dispose()
}
return SuccessResult
}
}
}
class Do<Element> : Producer<Element> {
typealias EventHandler = Event<Element> -> RxResult<Void>
let source: Observable<Element>
let eventHandler: EventHandler
init(source: Observable<Element>, eventHandler: EventHandler) {
self.source = source
self.eventHandler = eventHandler
}
override func run<O: ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = Do_(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return self.source.subscribe(sink)
}
} | mit | 2d7cfa5b7e6fced6bc4a0a7064313127 | 26.75 | 145 | 0.602704 | 4.488439 | false | false | false | false |
vanyaland/Californication | Californication/MapViewController.swift | 1 | 4169 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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 GoogleMaps
// MARK: MapViewController: UIViewController
class MapViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var mapView: GMSMapView!
// MARK: Properties
var didSelect: (Place) -> () = { _ in }
var placeDirector: PlaceDirectorFacade!
private lazy var locationManager: CLLocationManager = {
let locationManager = CLLocationManager()
locationManager.delegate = self
return locationManager
}()
// MARK: View Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
assert(placeDirector != nil)
configureMapView()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
// MARK: Private
private func configureMapView() {
mapView.delegate = self
// Center on California.
let camera = GMSCameraPosition.camera(withLatitude: 37.0, longitude: -120.0, zoom: 6.0)
mapView.camera = camera
checkLocationAuthorizationStatus()
addLocationMarkers()
}
private func checkLocationAuthorizationStatus() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
setAuthorizedWhenInUseState()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
private func addLocationMarkers() {
guard let places = placeDirector.persisted() else { return }
places.forEach { place in
let locationMarker = GMSMarker(position: place.coordinate)
locationMarker.map = mapView
locationMarker.userData = ["id": place.placeID]
locationMarker.title = place.name
locationMarker.appearAnimation = kGMSMarkerAnimationPop
locationMarker.icon = GMSMarker.markerImage(with: .red)
locationMarker.opacity = 0.95
locationMarker.isFlat = true
locationMarker.snippet = place.summary
}
}
}
// MARK: - MapViewController: CLLocationManagerDelegate -
extension MapViewController: CLLocationManagerDelegate {
// MARK: CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.authorizedWhenInUse {
setAuthorizedWhenInUseState()
} else {
setUserNotAuthorizedState()
}
}
// MARK: Helpers
fileprivate func setAuthorizedWhenInUseState() {
mapView.isMyLocationEnabled = true
mapView.settings.myLocationButton = true
}
fileprivate func setUserNotAuthorizedState() {
mapView.isMyLocationEnabled = false
mapView.settings.myLocationButton = false
}
}
// MARK: - MapViewController: GMSMapViewDelegate -
extension MapViewController: GMSMapViewDelegate {
func mapView(_ mapView: GMSMapView, didTapInfoWindowOf marker: GMSMarker) {
guard let dictionary = marker.userData as? [String: String],
let id = dictionary["id"],
let places = placeDirector.persisted(),
let index = places.index(where: { $0.placeID == id }) else { return }
let place = places[index]
didSelect(place)
}
}
| mit | c5470b9750c4d8f90fa21859a9e8d247 | 29.654412 | 108 | 0.720556 | 5.059466 | false | false | false | false |
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/ReusableComponentsSpec.swift | 7 | 1268 | import Quick
import Nimble
import Result
import ReactiveSwift
import ReactiveCocoa
import UIKit
class ReusableComponentsSpec: QuickSpec {
override func spec() {
describe("UITableViewCell") {
it("should send a `value` event when `prepareForReuse` is triggered") {
let cell = UITableViewCell()
var isTriggered = false
cell.reactive.prepareForReuse.observeValues {
isTriggered = true
}
expect(isTriggered) == false
cell.prepareForReuse()
expect(isTriggered) == true
}
}
describe("UITableViewHeaderFooterView") {
it("should send a `value` event when `prepareForReuse` is triggered") {
let cell = UITableViewHeaderFooterView()
var isTriggered = false
cell.reactive.prepareForReuse.observeValues {
isTriggered = true
}
expect(isTriggered) == false
cell.prepareForReuse()
expect(isTriggered) == true
}
}
describe("UICollectionReusableView") {
it("should send a `value` event when `prepareForReuse` is triggered") {
let cell = UICollectionReusableView()
var isTriggered = false
cell.reactive.prepareForReuse.observeValues {
isTriggered = true
}
expect(isTriggered) == false
cell.prepareForReuse()
expect(isTriggered) == true
}
}
}
}
| gpl-3.0 | 1d93e6690c03061840918bd93fa1d82e | 20.862069 | 74 | 0.694006 | 4.312925 | false | false | false | false |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Home/Controller/RecommendViewController.swift | 1 | 3030 | //
// RecommendViewController.swift
// DouYu
//
// Created by 张萌 on 2017/9/18.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
import Alamofire
private let kCycleViewHeight : CGFloat = kScreenW * 3 / 8
private let kGameViewHeight : CGFloat = 90
class RecommendViewController: BaseAnchorViewController {
// 懒加载 RecommengViewModel
lazy var recommendVM : RecommondViewModel = RecommondViewModel()
lazy var cycleView : RecommendClclesView = { () -> RecommendClclesView in
let cycleView = RecommendClclesView.recommendCyclesView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewHeight + kGameViewHeight), width: kScreenW, height: kCycleViewHeight)
return cycleView
}()
lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewHeight, width: kScreenW, height: kGameViewHeight)
return gameView
}()
}
extension RecommendViewController {
override func setupUI() {
super.setupUI()
collectionView.addSubview(cycleView)
collectionView.addSubview(gameView)
collectionView.contentInset = UIEdgeInsetsMake(kCycleViewHeight + kGameViewHeight, 0, 0, 0)
}
}
extension RecommendViewController {
override func loadData() {
recommendVM.requestData {
self.baseVM = self.recommendVM
self.collectionView.reloadData()
var anchorGroups = self.recommendVM.anchorGroups
anchorGroups.removeFirst()
anchorGroups.removeFirst()
self.gameView.groups = anchorGroups
self.finishLoadData()
}
recommendVM.requestCycleData {
self.cycleView.cycleModles = self.recommendVM.CycleModels
}
}
}
// UICollectionView 的 dataSource 协议
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
/// 1.取出模型对象
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchorRooms[indexPath.item]
var cell = BaseCollectionViewCell()
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kBeautifulCellID, for: indexPath) as! BeautifulCollectionViewCell
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! NormalCollectionViewCell
}
cell.anchorRoom = anchor
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemWidth, height: kBeautifulItemHeight)
}
return CGSize(width: kItemWidth, height: kNormalItemHeight)
}
}
| mit | a4d7554cafd71320f6e2e4c9cbe75a71 | 34.282353 | 160 | 0.695899 | 5.364937 | false | false | false | false |
bhajian/raspi-remote | Carthage/Checkouts/ios-sdk/Source/SpeechToTextV1/Models/WordConfidence.swift | 1 | 1340 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** The confidence of a word in a Speech to Text transcription. */
public struct WordConfidence: JSONDecodable {
/// A particular word from the transcription.
public let word: String
/// The confidence of the given word, between 0 and 1.
public let confidence: Double
/// Used internally to initialize a `WordConfidence` model from JSON.
public init(json: JSON) throws {
let array = try json.array()
word = try array[Index.Word.rawValue].string()
confidence = try array[Index.Confidence.rawValue].double()
}
/// The index of each element in the JSON array.
private enum Index: Int {
case Word = 0
case Confidence = 1
}
}
| mit | 30f8b9ec629d9e49be71fec3b548e2b4 | 31.682927 | 75 | 0.697015 | 4.407895 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/Highlightr/Example/Highlightr/SampleCode.swift | 2 | 6183 | //
// SampleCode.swift
// Highlightr
//
// Created by Illanes, J.P. on 5/5/16.
//
import UIKit
import Highlightr
import ActionSheetPicker_3_0
enum pickerSource : Int {
case theme = 0
case language
}
class SampleCode: UIViewController
{
@IBOutlet weak var navBar: UINavigationBar!
@IBOutlet weak var toolBar: UIToolbar!
@IBOutlet weak var viewPlaceholder: UIView!
var textView : UITextView!
@IBOutlet var textToolbar: UIToolbar!
@IBOutlet weak var languageName: UILabel!
@IBOutlet weak var themeName: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var highlightr : Highlightr!
let textStorage = CodeAttributedString()
override func viewDidLoad()
{
super.viewDidLoad()
activityIndicator.isHidden = true
languageName.text = "Swift"
themeName.text = "Pojoaque"
textStorage.language = languageName.text?.lowercased()
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: view.bounds.size)
layoutManager.addTextContainer(textContainer)
textView = UITextView(frame: viewPlaceholder.bounds, textContainer: textContainer)
textView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
textView.autocorrectionType = UITextAutocorrectionType.no
textView.autocapitalizationType = UITextAutocapitalizationType.none
textView.textColor = UIColor(white: 0.8, alpha: 1.0)
textView.inputAccessoryView = textToolbar
viewPlaceholder.addSubview(textView)
let code = try! String.init(contentsOfFile: Bundle.main.path(forResource: "sampleCode", ofType: "txt")!)
textView.text = code
highlightr = textStorage.highlightr
updateColors()
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
@IBAction func pickLanguage(_ sender: AnyObject)
{
let languages = highlightr.supportedLanguages().sorted()
let indexOrNil = languages.index(of: languageName.text!.lowercased())
let index = (indexOrNil == nil) ? 0 : indexOrNil!
ActionSheetStringPicker.show(withTitle: "Pick a Language",
rows: languages,
initialSelection: index,
doneBlock:
{ picker, index, value in
let language = value! as! String
self.textStorage.language = language
self.languageName.text = language.capitalized
let snippetPath = Bundle.main.path(forResource: "default", ofType: "txt", inDirectory: "Samples/\(language)", forLocalization: nil)
let snippet = try! String(contentsOfFile: snippetPath!)
self.textView.text = snippet
},
cancel: nil,
origin: toolBar)
}
@IBAction func performanceTest(_ sender: AnyObject)
{
let code = textStorage.string
let languageName = self.languageName.text
activityIndicator.isHidden = false
activityIndicator.startAnimating()
DispatchQueue.global(qos: .userInteractive).async {
let start = Date()
for _ in 0...100
{
_ = self.highlightr.highlight(code, as: languageName)
}
let end = Date()
let time = Float(end.timeIntervalSince(start));
let avg = String(format:"%0.4f", time/100)
let total = String(format:"%0.3f", time)
let alert = UIAlertController(title: "Performance test", message: "This code was highlighted 100 times. \n It took an average of \(avg) seconds to process each time,\n with a total of \(total) seconds", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alert.addAction(okAction)
DispatchQueue.main.async(execute: {
self.activityIndicator.isHidden = true
self.activityIndicator.stopAnimating()
self.present(alert, animated: true, completion: nil)
})
}
}
@IBAction func pickTheme(_ sender: AnyObject)
{
hideKeyboard(nil)
let themes = highlightr.availableThemes()
let indexOrNil = themes.index(of: themeName.text!.lowercased())
let index = (indexOrNil == nil) ? 0 : indexOrNil!
ActionSheetStringPicker.show(withTitle: "Pick a Theme",
rows: themes,
initialSelection: index,
doneBlock:
{ picker, index, value in
let theme = value! as! String
self.textStorage.highlightr.setTheme(to: theme)
self.themeName.text = theme.capitalized
self.updateColors()
},
cancel: nil,
origin: toolBar)
}
@IBAction func hideKeyboard(_ sender: AnyObject?)
{
textView.resignFirstResponder()
}
func updateColors()
{
textView.backgroundColor = highlightr.theme.themeBackgroundColor
navBar.barTintColor = highlightr.theme.themeBackgroundColor
navBar.tintColor = invertColor(navBar.barTintColor!)
languageName.textColor = navBar.tintColor
themeName.textColor = navBar.tintColor.withAlphaComponent(0.5)
toolBar.barTintColor = navBar.barTintColor
toolBar.tintColor = navBar.tintColor
}
func invertColor(_ color: UIColor) -> UIColor
{
var r:CGFloat = 0, g:CGFloat = 0, b:CGFloat = 0
color.getRed(&r, green: &g, blue: &b, alpha: nil)
return UIColor(red:1.0-r, green: 1.0-g, blue: 1.0-b, alpha: 1)
}
}
| mit | 9aabcded161728bf47ac77ec0c43f5a8 | 35.370588 | 238 | 0.584021 | 5.330172 | false | false | false | false |
honghaoz/UW-Quest-iOS | UW Quest/Main/LeftMenu/MenuTitleCell.swift | 1 | 1175 | //
// MenuTitleCell.swift
// UW Quest
//
// Created by Honghao Zhang on 2014-10-26.
// Copyright (c) 2014 Honghao. All rights reserved.
//
import UIKit
class MenuTitleCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
let kAnimationDuration = 0.4
let titleSelectedColor = UIColor(white: 1.0, alpha: 0.8)
let titleNormalColor = UIColor(white: 1.0, alpha: 0.5)
override func awakeFromNib() {
super.awakeFromNib()
self.backgroundColor = UIColor.clearColor()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
self.titleLabel.textColor = self.titleSelectedColor
self.backgroundColor = UIColor(white: 0.0, alpha: 0.2)
})
} else {
UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
self.titleLabel.textColor = self.titleNormalColor
self.backgroundColor = UIColor.clearColor()
})
}
}
}
| apache-2.0 | c6578a4b8c537222a4956d99931b06e4 | 29.921053 | 86 | 0.625532 | 4.589844 | false | false | false | false |
finngaida/healthpad | Shared/ChartViews/LineView.swift | 1 | 3797 | //
// LineChartView.swift
// HealthPad
//
// Created by Finn Gaida on 16.03.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
import Charts
import ResearchKit
public class LineView: ChartView {
public var chart: LineChartView?
override init(frame: CGRect) {
super.init(frame: frame)
}
public override func setupChart() {
chart = LineChartView(frame: CGRectMake(25, 85, self.frame.width - 40, self.frame.height - 110))
chart?.delegate = self
chart?.setScaleEnabled(false)
chart?.dragEnabled = false
chart?.pinchZoomEnabled = false
chart?.drawGridBackgroundEnabled = false
chart?.leftAxis.enabled = false
chart?.rightAxis.enabled = true
chart?.legend.enabled = false
chart?.descriptionText = ""
chart?.rightAxis.gridColor = UIColor.whiteColor()
chart?.rightAxis.showOnlyMinMaxEnabled = true
chart?.xAxis.enabled = true
chart?.xAxis.labelTextColor = UIColor(white: 1.0, alpha: 0.8)
chart?.rightAxis.labelTextColor = UIColor(white: 1.0, alpha: 0.8)
chart?.xAxis.gridColor = UIColor(white: 1.0, alpha: 0.3)
chart?.rightAxis.axisLineColor = UIColor(white: 1.0, alpha: 0.5)
chart?.rightAxis.zeroLineColor = UIColor(white: 1.0, alpha: 0.5)
chart?.backgroundColor = UIColor.clearColor()
chart?.layer.masksToBounds
chart?.layer.cornerRadius = 10
self.addSubview(Helper.gradientForColor(CGRectMake(0, 0, self.frame.width, self.frame.height), color: self.color))
self.addSubview(chart!)
// test chart
// self.addSubview(ResearchKitGraphHelper.sharedHelper.lineChart((chart?.frame)!))
}
public override func setupLabels() {
super.setupLabels()
titleLabel?.text = self.titleText ?? "Steps"
todayLabel?.text = self.todayText ?? "Daily average: 4,631"
averageLabel?.text = self.averageText ?? "1,261 steps"
dateLabel?.text = self.dateText ?? "Today, 8:18"
}
public override func setData(data:Array<HealthObject>) {
self.data = data
let yVals = data.enumerate().map({ChartDataEntry(value: Double(self.majorValueFromHealthObject($1)) ?? 0, xIndex: $0)})
let set = LineChartDataSet(yVals: yVals, label: "")
set.lineWidth = 2
set.circleRadius = 5
set.setCircleColor(UIColor.whiteColor())
set.circleHoleColor = UIColor.orangeColor()
set.drawCircleHoleEnabled = true
set.setColor(UIColor.whiteColor())
set.drawValuesEnabled = false
set.highlightEnabled = false
set.drawCubicEnabled = false
set.drawFilledEnabled = true
set.drawCirclesEnabled = true
set.fillAlpha = 1.0
set.fill = ChartFill(linearGradient: CGGradientCreateWithColors(nil, [UIColor(white: 1.0, alpha: 0.0).CGColor, UIColor(white: 1.0, alpha: 0.4).CGColor], nil)!, angle: 90.0)
var xVals = (1...data.count).map({"\($0)"})
xVals[0] = "Mar \(xVals[0])" // TODO Real month
let avg = yVals.map({Int($0.value)}).average
let average = ChartLimitLine(limit: avg)
average.lineColor = UIColor(white: 1.0, alpha: 0.5)
average.lineWidth = 1
average.lineDashLengths = [5.0]
chart?.rightAxis.addLimitLine(average)
chart?.data = LineChartData(xVals: xVals, dataSet: set)
// send data to test chart
ResearchKitGraphHelper.sharedHelper.data = data.map({ORKRangedPoint(value: CGFloat(Float(self.majorValueFromHealthObject($0)) ?? 0))})
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| apache-2.0 | f0b8959e062a83ce37d0ad603cfcb801 | 37.734694 | 180 | 0.62961 | 4.25084 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/OrderDetail/Controller/出库单/ShowOutBoundMaterialsViewController.swift | 1 | 2868 | //
// ShowOutBoundMaterialsViewController.swift
// OMS
//
// Created by ___Gwy on 2017/6/16.
// Copyright © 2017年 文羿 顾. All rights reserved.
//
import UIKit
class ShowOutBoundMaterialsViewController: UITableViewController {
var dataSource: [String:AnyObject]?
fileprivate var filterDataSource = [OutBoundMedDetailModel]()
override func viewDidLoad() {
super.viewDidLoad()
reloadMetailView()
let segmentView = OMSSegment(items: ["植入物","工具"], didSelectedIndex: { (index) in
index == 0 ? self.reloadMetailView() : self.reloadToolsView()
})
if filterDataSource.count == 0 {
segmentView.selectedSegmentIndex = 1
reloadToolsView()
}
navigationItem.titleView = segmentView
navigationItem.titleView?.frame = CGRect(x: 0, y: 5, width: 100, height: 27)
tableView.register(OutBoundMedTableViewCell.self)
tableView.separatorStyle = .none
tableView.rowHeight = 155
}
fileprivate func reloadMetailView() {
guard let data = dataSource?["prolns"] as? [OutBoundMedDetailModel] else { return }
//筛选出植入物
filterDataSource = data.filter({ $0.categoryByPlatform == "IMPLANT" })
tableView.reloadData()
}
fileprivate func reloadToolsView() {
guard let data = dataSource?["prolns"] as? [OutBoundMedDetailModel] else { return }
//筛选出工具
filterDataSource = data.filter({ $0.categoryByPlatform != "IMPLANT" })
tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OutBoundMedTableViewCell") as! OutBoundMedTableViewCell
let model = filterDataSource[indexPath.row]
cell.nameLB.text = "名称:\(model.medMIName)"
cell.batchLB.text = "批次/序列号:\(model.lotSerial)"
cell.codeLB.text = "编码:\(model.medMICode)"
cell.specificationLB.text = "规格:\(model.specification)"
cell.supplierLB.text = "供货商:\(model.pOVDOrgCodeName)"
cell.clearingFormLB.text = "结算方式:\(model.pOSettlementTypeName)"
cell.countLB.text = "数量:\(model.reqQty)"
// if isMedDetail!{
// if let req = dataSource?.reqQty{
// cell.countLB.text = "数量:\(req)"
// }
// }else{
// if let act = dataSource?.actQty{
// cell.countLB.text = "数量:\(act)"
// }
// }
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterDataSource.count
}
}
| mit | 603d9b42e790b6d5606fa23a449b2a8d | 35.813333 | 121 | 0.612821 | 4.35489 | false | false | false | false |
kylef/JSONSchema.swift | Tests/JSONSchemaTests/JSONPointerTests.swift | 1 | 3518 | import Foundation
import Spectre
@testable import JSONSchema
// Defined from https://tools.ietf.org/html/rfc6901#section-5
fileprivate let document: [String: Any] = [
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
]
public let testJSONPointer: ((ContextType) -> Void) = {
// Resolution (https://tools.ietf.org/html/rfc6901#section-5)
$0.it("can resoleve entire document") {
let pointer = JSONPointer(path: "")
try expect(pointer.resolve(document: document) as? NSDictionary) == document as NSDictionary
}
$0.it("can resolve object value") {
let pointer = JSONPointer(path: "/foo")
try expect(pointer.resolve(document: document) as? [String]) == ["bar", "baz"]
}
$0.it("can resolve array index") {
let pointer = JSONPointer(path: "/foo/0")
try expect(pointer.resolve(document: document) as? String) == "bar"
let pointer1 = JSONPointer(path: "/foo/1")
try expect(pointer1.resolve(document: document) as? String) == "baz"
}
$0.it("can resolve object value via empty key") {
let pointer = JSONPointer(path: "/")
try expect(pointer.resolve(document: document) as? Int) == 0
}
$0.it("can resolve object value with escaped slash in key") {
let pointer = JSONPointer(path: "/a~1b")
try expect(pointer.resolve(document: document) as? Int) == 1
}
$0.it("can resolve object value with percent in key") {
let pointer = JSONPointer(path: "/c%d")
try expect(pointer.resolve(document: document) as? Int) == 2
}
$0.it("can resolve object value with carot in key") {
let pointer = JSONPointer(path: "/e^f")
try expect(pointer.resolve(document: document) as? Int) == 3
}
$0.it("can resolve object value with pipe in key") {
let pointer = JSONPointer(path: "/g|h")
try expect(pointer.resolve(document: document) as? Int) == 4
}
$0.it("can resolve object value with backslash in key") {
let pointer = JSONPointer(path: "/i\\j")
try expect(pointer.resolve(document: document) as? Int) == 5
}
$0.it("can resolve object value with double quote in key") {
let pointer = JSONPointer(path: "/k\"l")
try expect(pointer.resolve(document: document) as? Int) == 6
}
$0.it("can resolve object value with double space in key") {
let pointer = JSONPointer(path: "/ ")
try expect(pointer.resolve(document: document) as? Int) == 7
}
$0.it("can resolve object value with escaped tilde in key") {
let pointer = JSONPointer(path: "/m~0n")
try expect(pointer.resolve(document: document) as? Int) == 8
}
// Resolve (negative cases)
$0.it("can resolve out of bounds array index") {
let pointer = JSONPointer(path: "/foo/2")
try expect(pointer.resolve(document: document)).to.beNil()
}
$0.it("can resolve negative array index") {
let pointer = JSONPointer(path: "/foo/-1")
try expect(pointer.resolve(document: document)).to.beNil()
}
$0.it("can resolve missing key in object") {
let pointer = JSONPointer(path: "/test")
try expect(pointer.resolve(document: document)).to.beNil()
}
// MARK: - #path
$0.describe("#path") {
$0.it("returns a string representation of path") {
let pointer = JSONPointer(path: "/foo")
try expect(pointer.path) == "/foo"
}
$0.it("returns a string representation of path escaping slashes") {
let pointer = JSONPointer(path: "/a~1b")
try expect(pointer.path) == "/a~1b"
}
}
}
| bsd-3-clause | 0ae875f1bf25544b022b3e61fc35591b | 25.451128 | 96 | 0.634736 | 3.445642 | false | false | false | false |
collinhundley/APCustomBlurView | APCustomBlurView.swift | 1 | 1214 | //
// APCustomBlurView.swift
// Created by Collin Hundley on 1/15/16.
//
import UIKit
public class APCustomBlurView: UIVisualEffectView {
private let blurEffect: UIBlurEffect
public var blurRadius: CGFloat {
return blurEffect.valueForKeyPath("blurRadius") as! CGFloat
}
public convenience init() {
self.init(withRadius: 0)
}
public init(withRadius radius: CGFloat) {
let customBlurClass: AnyObject.Type = NSClassFromString("_UICustomBlurEffect")!
let customBlurObject: NSObject.Type = customBlurClass as! NSObject.Type
self.blurEffect = customBlurObject.init() as! UIBlurEffect
self.blurEffect.setValue(1.0, forKeyPath: "scale")
self.blurEffect.setValue(radius, forKeyPath: "blurRadius")
super.init(effect: radius == 0 ? nil : self.blurEffect)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func setBlurRadius(radius: CGFloat) {
guard radius != blurRadius else {
return
}
blurEffect.setValue(radius, forKeyPath: "blurRadius")
self.effect = blurEffect
}
}
| mit | 60af55c4190c6256b3a3e66c2eb74d97 | 29.35 | 87 | 0.655684 | 4.705426 | false | false | false | false |
atl009/WordPress-iOS | WordPress/Classes/Utility/InteractiveNotificationsManager.swift | 1 | 11614 | import Foundation
import CocoaLumberjack
import UserNotifications
/// In this class, we'll encapsulate all of the code related to UNNotificationCategory and
/// UNNotificationAction instantiation, along with the required handlers.
///
final class InteractiveNotificationsManager: NSObject {
/// Returns the shared InteractiveNotificationsManager instance.
///
static let shared = InteractiveNotificationsManager()
/// Returns the Core Data main context.
///
var context: NSManagedObjectContext {
return ContextManager.sharedInstance().mainContext
}
/// Returns a CommentService instance.
///
var commentService: CommentService {
return CommentService(managedObjectContext: context)
}
/// Returns a NotificationSyncMediator instance.
///
var notificationSyncMediator: NotificationSyncMediator? {
return NotificationSyncMediator()
}
/// Registers the device for User Notifications.
///
/// This method should be called once during the app initialization process.
///
func registerForUserNotifications() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
notificationCenter.setNotificationCategories(supportedNotificationCategories())
}
/// Requests authorization to interact with the user when notifications arrive.
///
/// The first time this method is called it will ask the user for permission to show notifications.
/// Because of this, this should be called only when we know we will need to show notifications (for instance, after login).
///
func requestAuthorization() {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { _ in })
}
/// Handle an action taken from a remote notification
///
/// - Parameters:
/// - identifier: The identifier of the action
/// - userInfo: The notification's Payload
///
/// - Returns: True on success
///
@discardableResult
func handleAction(with identifier: String, userInfo: NSDictionary, responseText: String?) -> Bool {
guard AccountHelper.isDotcomAvailable(),
let noteID = userInfo.object(forKey: "note_id") as? NSNumber,
let siteID = userInfo.object(forKey: "blog_id") as? NSNumber,
let commentID = userInfo.object(forKey: "comment_id") as? NSNumber else {
return false
}
if identifier == UNNotificationDefaultActionIdentifier {
showDetailsWithNoteID(noteID)
return true
}
guard let action = NoteActionDefinition(rawValue: identifier) else {
return false
}
switch action {
case .commentApprove:
approveCommentWithCommentID(commentID, noteID: noteID, siteID: siteID)
case .commentLike:
likeCommentWithCommentID(commentID, noteID: noteID, siteID: siteID)
case .commentReply:
if let responseText = responseText {
replyToCommentWithCommentID(commentID, noteID: noteID, siteID: siteID, content: responseText)
} else {
DDLogError("Tried to reply to a comment notification with no text")
}
}
return true
}
}
// MARK: - Private Helpers
//
private extension InteractiveNotificationsManager {
/// Likes a comment and marks the associated notification as read
///
/// - Parameters:
/// - commentID: The comment identifier
/// - siteID: The site identifier
///
func likeCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber) {
commentService.likeComment(withID: commentID, siteID: siteID, success: {
self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue)
DDLogInfo("Liked comment from push notification")
}, failure: { error in
DDLogInfo("Couldn't like comment from push notification")
})
}
/// Approves a comment and marks the associated notification as read
///
/// - Parameters:
/// - commentID: The comment identifier
/// - siteID: The site identifier
///
func approveCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber) {
commentService.approveComment(withID: commentID, siteID: siteID, success: {
self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue)
DDLogInfo("Successfully moderated comment from push notification")
}, failure: { error in
DDLogInfo("Couldn't moderate comment from push notification")
})
}
/// Opens the details for a given notificationId
///
/// - Parameter noteID: The Notification's Identifier
///
func showDetailsWithNoteID(_ noteId: NSNumber) {
WPTabBarController.sharedInstance().showNotificationsTabForNote(withID: noteId.stringValue)
}
/// Replies to a comment and marks the associated notification as read
///
/// - Parameters:
/// - commentID: The comment identifier
/// - siteID: The site identifier
/// - content: The text for the comment reply
///
func replyToCommentWithCommentID(_ commentID: NSNumber, noteID: NSNumber, siteID: NSNumber, content: String) {
commentService.replyToComment(withID: commentID, siteID: siteID, content: content, success: {
self.notificationSyncMediator?.markAsReadAndSync(noteID.stringValue)
DDLogInfo("Successfully replied comment from push notification")
}, failure: { error in
DDLogInfo("Couldn't reply to comment from push notification")
})
}
/// Returns a collection of *UNNotificationCategory* instances, for each one of the
/// supported NoteCategoryDefinition enum case's.
///
/// - Returns: A set of *UNNotificationCategory* instances.
///
func supportedNotificationCategories() -> Set<UNNotificationCategory> {
let categories: [UNNotificationCategory] = NoteCategoryDefinition.allDefinitions.map({ $0.notificationCategory() })
return Set(categories)
}
}
// MARK: - Nested Types
//
private extension InteractiveNotificationsManager {
/// Describes information about Custom Actions that WPiOS can perform, as a response to
/// a Push Notification event.
///
enum NoteCategoryDefinition: String {
case commentApprove = "approve-comment"
case commentLike = "like-comment"
case commentReply = "replyto-comment"
case commentReplyWithLike = "replyto-like-comment"
var actions: [NoteActionDefinition] {
switch self {
case .commentApprove:
return [.commentApprove]
case .commentLike:
return [.commentLike]
case .commentReply:
return [.commentReply]
case .commentReplyWithLike:
return [.commentReply, .commentLike]
}
}
var identifier: String {
return rawValue
}
func notificationCategory() -> UNNotificationCategory {
return UNNotificationCategory(
identifier: identifier,
actions: actions.map({ $0.notificationAction() }),
intentIdentifiers: [],
options: [])
}
static var allDefinitions = [commentApprove, commentLike, commentReply, commentReplyWithLike]
}
/// Describes the custom actions that WPiOS can perform in response to a Push notification.
///
enum NoteActionDefinition: String {
case commentApprove = "COMMENT_MODERATE_APPROVE"
case commentLike = "COMMENT_LIKE"
case commentReply = "COMMENT_REPLY"
var description: String {
switch self {
case .commentApprove:
return NSLocalizedString("Approve", comment: "Approve comment (verb)")
case .commentLike:
return NSLocalizedString("Like", comment: "Like (verb)")
case .commentReply:
return NSLocalizedString("Reply", comment: "Reply to a comment (verb)")
}
}
var destructive: Bool {
return false
}
var identifier: String {
return rawValue
}
var requiresAuthentication: Bool {
return false
}
var requiresForeground: Bool {
return false
}
var notificationActionOptions: UNNotificationActionOptions {
var options = UNNotificationActionOptions()
if requiresAuthentication {
options.insert(.authenticationRequired)
}
if destructive {
options.insert(.destructive)
}
if requiresForeground {
options.insert(.foreground)
}
return options
}
func notificationAction() -> UNNotificationAction {
switch self {
case .commentReply:
return UNTextInputNotificationAction(identifier: identifier,
title: description,
options: notificationActionOptions,
textInputButtonTitle: NSLocalizedString("Reply", comment: ""),
textInputPlaceholder: NSLocalizedString("Write a reply…", comment: "Placeholder text for inline compose view"))
default:
return UNNotificationAction(identifier: identifier, title: description, options: notificationActionOptions)
}
}
static var allDefinitions = [commentApprove, commentLike, commentReply]
}
}
// MARK: - UNUserNotificationCenterDelegate Conformance
//
extension InteractiveNotificationsManager: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo as NSDictionary
let textInputResponse = response as? UNTextInputNotificationResponse
if handleAction(with: response.actionIdentifier, userInfo: userInfo, responseText: textInputResponse?.userText) {
completionHandler()
return
}
// TODO:
// =====
// Refactor both PushNotificationsManager + InteractiveNotificationsManager:
//
// - InteractiveNotificationsManager should no longer be a singleton. Perhaps we could convert it into a struct.
// Plus int should probably be renamed into something more meaningful (and match the new framework's naming)
// - New `NotificationsManager` class:
// - Would inherit `PushNotificationsManager.handleNotification`
// - Would deal with UserNotifications.framework
// - Would use InteractiveNotificationsManager!
// - Nuke `PushNotificationsManager`
//
//
PushNotificationsManager.shared.handleNotification(userInfo) { _ in
completionHandler()
}
}
}
| gpl-2.0 | 95a2c77be26261d26a26b8452806afa4 | 35.980892 | 164 | 0.629091 | 5.92449 | false | false | false | false |
ataugeron/SpriteKit-Spring | SpriteKit-Spring.swift | 1 | 18029 | ////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2014 Alexis Taugeron
//
// 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 SpriteKit
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Move
@objc public extension SKAction {
@objc class func move(by delta: CGVector, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let moveByX = animate(keyPath: \SKNode.position.x, byValue: delta.dx, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let moveByY = animate(keyPath: \SKNode.position.y, byValue: delta.dy, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([moveByX, moveByY])
}
@objc class func move(to location: CGPoint, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let moveToX = animate(keyPath: \SKNode.position.x, toValue: location.x, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let moveToY = animate(keyPath: \SKNode.position.y, toValue: location.y, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([moveToX, moveToY])
}
@objc class func moveBy(x deltaX: CGFloat, y deltaY: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let moveByX = animate(keyPath: \SKNode.position.x, byValue: deltaX, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let moveByY = animate(keyPath: \SKNode.position.y, byValue: deltaY, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([moveByX, moveByY])
}
@objc class func moveTo(x: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.position.x, toValue: x, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func moveTo(y: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.position.y, toValue: y, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Rotate
@objc public extension SKAction {
@objc class func rotate(byAngle radians: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.zRotation, byValue: radians, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func rotate(toAngle radians: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.zRotation, toValue: radians, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Speed
@objc public extension SKAction {
@objc class func speed(by speed: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.speed, byValue: speed, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func speed(to speed: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.speed, toValue: speed, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Scale
public extension SKAction {
@objc class func scale(by scale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return scaleX(by: scale, y: scale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func scale(to scale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return scaleX(to: scale, y: scale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func scaleX(by xScale: CGFloat, y yScale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let scaleXBy = animate(keyPath: \SKNode.xScale, byValue: xScale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let scaleYBy = animate(keyPath: \SKNode.yScale, byValue: yScale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([scaleXBy, scaleYBy])
}
@objc class func scaleX(to scale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.xScale, toValue: scale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func scaleY(to scale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.yScale, toValue: scale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func scaleX(to xScale: CGFloat, y yScale: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let scaleXTo = self.scaleX(to: xScale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let scaleYTo = self.scaleY(to: yScale, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([scaleXTo, scaleYTo])
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Fade
public extension SKAction {
@objc class func fadeIn(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.alpha, toValue: 1, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func fadeOut(withDuration duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.alpha, toValue: 0, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func fadeAlpha(by factor: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.alpha, byValue: factor, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func fadeAlpha(to factor: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKNode.alpha, toValue: factor, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Resize
@objc public extension SKAction {
@objc class func resize(toWidth width: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKSpriteNode.size.width, toValue: width, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func resize(toHeight height: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKSpriteNode.size.height, toValue: height, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
@objc class func resize(byWidth width: CGFloat, height: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let resizeByWidth = animate(keyPath: \SKSpriteNode.size.width, byValue: width, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let resizeByHeight = animate(keyPath: \SKSpriteNode.size.height, byValue: height, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([resizeByWidth, resizeByHeight])
}
@objc class func resize(toWidth width: CGFloat, height: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
let resizeToWidth = self.resize(toWidth: width, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
let resizeToHeight = self.resize(toHeight: height, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
return SKAction.group([resizeToWidth, resizeToHeight])
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: Colorize
@objc public extension SKAction {
@objc class func colorize(withColorBlendFactor colorBlendFactor: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(keyPath: \SKSpriteNode.colorBlendFactor, toValue: colorBlendFactor, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// MARK: - Damping Logic
public extension SKAction {
class func animate<T>(keyPath: ReferenceWritableKeyPath<T, CGFloat>, byValue initialDistance: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(_keyPath: keyPath, byValue: initialDistance, toValue: nil, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
class func animate<T>(keyPath: ReferenceWritableKeyPath<T, CGFloat>, toValue finalValue: CGFloat, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
return animate(_keyPath: keyPath, byValue: nil, toValue: finalValue, duration: duration, delay: delay, usingSpringWithDamping: dampingRatio, initialSpringVelocity: velocity)
}
private class func animate<T>(_keyPath: ReferenceWritableKeyPath<T, CGFloat>, byValue: CGFloat!, toValue: CGFloat!, duration: TimeInterval, delay: TimeInterval, usingSpringWithDamping dampingRatio: CGFloat, initialSpringVelocity velocity: CGFloat) -> SKAction {
var initialValue: CGFloat!
var naturalFrequency: CGFloat = 0
var dampedFrequency: CGFloat = 0
var t1: CGFloat = 0
var t2: CGFloat = 0
var A: CGFloat = 0
var B: CGFloat = 0
var finalValue: CGFloat! = toValue
var initialDistance: CGFloat! = byValue
let animation = SKAction.customAction(withDuration: duration, actionBlock: {
(node, elapsedTime) in
if let propertyToAnimation = node as? T {
if initialValue == nil {
initialValue = propertyToAnimation[keyPath: _keyPath]
initialDistance = initialDistance ?? finalValue - initialValue!
finalValue = finalValue ?? initialValue! + initialDistance
var magicNumber: CGFloat! // picked manually to visually match the behavior of UIKit
if dampingRatio < 1 { magicNumber = 8 / dampingRatio }
else if dampingRatio == 1 { magicNumber = 10 }
else { magicNumber = 12 * dampingRatio }
naturalFrequency = magicNumber / CGFloat(duration)
dampedFrequency = naturalFrequency * sqrt(1 - pow(dampingRatio, 2))
t1 = 1 / (naturalFrequency * (dampingRatio - sqrt(pow(dampingRatio, 2) - 1)))
t2 = 1 / (naturalFrequency * (dampingRatio + sqrt(pow(dampingRatio, 2) - 1)))
if dampingRatio < 1 {
A = initialDistance
B = (dampingRatio * naturalFrequency - velocity) * initialDistance / dampedFrequency
} else if dampingRatio == 1 {
A = initialDistance
B = (naturalFrequency - velocity) * initialDistance
} else {
A = (t1 * t2 / (t1 - t2))
A *= initialDistance * (1/t2 - velocity)
B = (t1 * t2 / (t2 - t1))
B *= initialDistance * (1/t1 - velocity)
}
}
var currentValue: CGFloat!
if elapsedTime < CGFloat(duration) {
if dampingRatio < 1 {
let dampingExp:CGFloat = exp(-dampingRatio * naturalFrequency * elapsedTime)
let ADamp:CGFloat = A * cos(dampedFrequency * elapsedTime)
let BDamp:CGFloat = B * sin(dampedFrequency * elapsedTime)
currentValue = finalValue - dampingExp * (ADamp + BDamp)
} else if dampingRatio == 1 {
let dampingExp: CGFloat = exp(-dampingRatio * naturalFrequency * elapsedTime)
currentValue = finalValue - dampingExp * (A + B * elapsedTime)
} else {
let ADamp:CGFloat = A * exp(-elapsedTime/t1)
let BDamp:CGFloat = B * exp(-elapsedTime/t2)
currentValue = finalValue - ADamp - BDamp
}
} else {
currentValue = finalValue
}
propertyToAnimation[keyPath: _keyPath] = currentValue
}
})
if delay > 0 {
return SKAction.sequence([SKAction.wait(forDuration: delay), animation])
} else {
return animation
}
}
}
| apache-2.0 | a15221d31ddec1434510cb37762a2c26 | 57.918301 | 265 | 0.647568 | 5.90921 | false | false | false | false |
carambalabs/Paparajote | Paparajote/Classes/Models/OAuth2Event.swift | 1 | 1012 | import Foundation
/**
OAuth2 Event
- Open: The url must be opened in a web browser.
- Error: There was an error during the authentication flow.
- Session: User was authenticated and the session is provided.
*/
public enum OAuth2Event: Equatable {
case open(url: URL)
case error(Error)
case session(OAuth2Session)
}
// MARK: - <Equatable>
public func == (lhs: OAuth2Event, rhs: OAuth2Event) -> Bool {
switch lhs {
case .open(let lhsUrl):
switch rhs {
case .open(let rhsUrl):
return lhsUrl == rhsUrl
default:
return false
}
case .error(let lhsError):
switch rhs {
case .error(let rhsError):
return lhsError as NSError == rhsError as NSError
default:
return false
}
case .session(let lhsSession):
switch rhs {
case .session(let rhsSession):
return lhsSession == rhsSession
default:
return false
}
}
}
| mit | d7c706c828a45c583e0f4068cd47aff1 | 23.095238 | 63 | 0.58498 | 4.216667 | false | false | false | false |
flodolo/firefox-ios | Client/Extensions/UIAlertController+Extension.swift | 1 | 7242 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
import Shared
typealias UIAlertActionCallback = (UIAlertAction) -> Void
// MARK: - Extension methods for building specific UIAlertController instances used across the app
extension UIAlertController {
/**
Builds the Alert view that asks the user if they wish to opt into crash reporting.
- parameter sendReportCallback: Send report option handler
- parameter alwaysSendCallback: Always send option handler
- parameter dontSendCallback: Dont send option handler
- parameter neverSendCallback: Never send option handler
- returns: UIAlertController for opting into crash reporting after a crash occurred
*/
class func crashOptInAlert(
_ sendReportCallback: @escaping UIAlertActionCallback,
alwaysSendCallback: @escaping UIAlertActionCallback,
dontSendCallback: @escaping UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: .CrashOptInAlertTitle,
message: .CrashOptInAlertMessage,
preferredStyle: .alert
)
let sendReport = UIAlertAction(
title: .CrashOptInAlertSend,
style: .default,
handler: sendReportCallback
)
let alwaysSend = UIAlertAction(
title: .CrashOptInAlertAlwaysSend,
style: .default,
handler: alwaysSendCallback
)
let dontSend = UIAlertAction(
title: .CrashOptInAlertDontSend,
style: .default,
handler: dontSendCallback
)
alert.addAction(sendReport)
alert.addAction(alwaysSend)
alert.addAction(dontSend)
return alert
}
/**
Builds the Alert view that asks the user if they wish to restore their tabs after a crash.
- parameter okayCallback: Okay option handler
- parameter noCallback: No option handler
- returns: UIAlertController for asking the user to restore tabs after a crash
*/
class func restoreTabsAlert(okayCallback: @escaping UIAlertActionCallback, noCallback: @escaping UIAlertActionCallback) -> UIAlertController {
let alert = UIAlertController(
title: .RestoreTabsAlertTitle,
message: .RestoreTabsAlertMessage,
preferredStyle: .alert
)
let noOption = UIAlertAction(
title: .RestoreTabsAlertNo,
style: .cancel,
handler: noCallback
)
let okayOption = UIAlertAction(
title: .RestoreTabsAlertOkay,
style: .default,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
class func clearPrivateDataAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: .ClearPrivateDataAlertMessage,
preferredStyle: .alert
)
let noOption = UIAlertAction(
title: .ClearPrivateDataAlertCancel,
style: .cancel,
handler: nil
)
let okayOption = UIAlertAction(
title: .ClearPrivateDataAlertOk,
style: .destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
class func clearSelectedWebsiteDataAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: .ClearSelectedWebsiteDataAlertMessage,
preferredStyle: .alert
)
let noOption = UIAlertAction(
title: .ClearWebsiteDataAlertCancel,
style: .cancel,
handler: nil
)
let okayOption = UIAlertAction(
title: .ClearWebsiteDataAlertOk,
style: .destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
class func clearAllWebsiteDataAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: .ClearAllWebsiteDataAlertMessage,
preferredStyle: .alert
)
let noOption = UIAlertAction(
title: .ClearWebsiteDataAlertCancel,
style: .cancel,
handler: nil
)
let okayOption = UIAlertAction(
title: .ClearWebsiteDataAlertOk,
style: .destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
/**
Builds the Alert view that asks if the users wants to also delete history stored on their other devices.
- parameter okayCallback: Okay option handler.
- returns: UIAlertController for asking the user to restore tabs after a crash
*/
class func clearSyncedHistoryAlert(okayCallback: @escaping (UIAlertAction) -> Void) -> UIAlertController {
let alert = UIAlertController(
title: "",
message: .ClearSyncedHistoryAlertMessage,
preferredStyle: .alert
)
let noOption = UIAlertAction(
title: .ClearSyncedHistoryAlertCancel,
style: .cancel,
handler: nil
)
let okayOption = UIAlertAction(
title: .ClearSyncedHistoryAlertOk,
style: .destructive,
handler: okayCallback
)
alert.addAction(okayOption)
alert.addAction(noOption)
return alert
}
/**
Creates an alert view to warn the user that their logins will either be completely deleted in the
case of local-only logins or deleted across synced devices in synced account logins.
- parameter deleteCallback: Block to run when delete is tapped.
- parameter hasSyncedLogins: Boolean indicating the user has logins that have been synced.
- returns: UIAlertController instance
*/
class func deleteLoginAlertWithDeleteCallback(
_ deleteCallback: @escaping UIAlertActionCallback,
hasSyncedLogins: Bool) -> UIAlertController {
let deleteAlert: UIAlertController
if hasSyncedLogins {
deleteAlert = UIAlertController(title: .DeleteLoginAlertTitle, message: .DeleteLoginAlertSyncedMessage, preferredStyle: .alert)
} else {
deleteAlert = UIAlertController(title: .DeleteLoginAlertTitle, message: .DeleteLoginAlertLocalMessage, preferredStyle: .alert)
}
let cancelAction = UIAlertAction(title: .DeleteLoginAlertCancel, style: .cancel, handler: nil)
let deleteAction = UIAlertAction(title: .DeleteLoginAlertDelete, style: .destructive, handler: deleteCallback)
deleteAlert.addAction(cancelAction)
deleteAlert.addAction(deleteAction)
return deleteAlert
}
}
| mpl-2.0 | 281ca53f7ab6290edbc0e7eb49efb0d1 | 31.475336 | 146 | 0.642226 | 5.715864 | false | false | false | false |
firebase/flutterfire | packages/firebase_ml_model_downloader/firebase_ml_model_downloader/ios/Classes/FirebaseModelDownloaderPlugin.swift | 1 | 6217 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if canImport(FlutterMacOS)
import FlutterMacOS
#else
import Flutter
#endif
import FirebaseCore
import FirebaseMLModelDownloader
import firebase_core
let kFLTFirebaseModelDownloaderChannelName = "plugins.flutter.io/firebase_ml_model_downloader"
public class FirebaseModelDownloaderPluginSwift: FLTFirebasePlugin, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let binaryMessenger: FlutterBinaryMessenger
#if os(macOS)
binaryMessenger = registrar.messenger
#elseif os(iOS)
binaryMessenger = registrar.messenger()
#endif
let channel = FlutterMethodChannel(
name: kFLTFirebaseModelDownloaderChannelName,
binaryMessenger: binaryMessenger
)
let instance = FirebaseModelDownloaderPluginSwift()
registrar.addMethodCallDelegate(instance, channel: channel)
#if os(iOS)
registrar.publish(instance)
#endif
}
internal func mapErrorCodes(error: Error) -> NSString {
switch error {
case DownloadError.notFound:
return "no-existing-model"
case DownloadError.permissionDenied:
return "permission-denied"
case DownloadError.notFound:
return "server-unreachable"
case DownloadError.failedPrecondition:
return "failed-precondition"
case DownloadedModelError.fileIOError:
return "file-io-error"
case DownloadedModelError.internalError:
return "internal-error"
default:
return "unknown"
}
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
let errorBlock: FLTFirebaseMethodCallErrorBlock = { (code, message, details, error: Error?) in
var errorDetails = [String: Any?]()
errorDetails["code"] = code ?? self.mapErrorCodes(error: error! as NSError)
errorDetails["message"] = message ?? error?
.localizedDescription ?? "An unknown error has occurred."
errorDetails["additionalData"] = details ??
["code": errorDetails["code"], "message": errorDetails["message"]]
if code == "unknown" {
NSLog("FLTFirebaseModelDownloader: An error occurred while calling method %@", call.method)
}
result(FLTFirebasePlugin.createFlutterError(fromCode: errorDetails["code"] as! String,
message: errorDetails["message"] as! String,
optionalDetails: errorDetails[
"additionalData"
] as? [AnyHashable: Any],
andOptionalNSError: nil))
}
let result = FLTFirebaseMethodCallResult.create(success: result, andErrorBlock: errorBlock)
if call.method == "FirebaseModelDownloader#getModel" {
getModel(arguments: call.arguments as! [String: Any], result: result)
}
if call.method == "FirebaseModelDownloader#listDownloadedModels" {
listDownloadedModels(arguments: call.arguments as! [String: Any], result: result)
}
if call.method == "FirebaseModelDownloader#deleteDownloadedModel" {
deleteDownloadedModel(arguments: call.arguments as! [String: Any], result: result)
}
}
internal func listDownloadedModels(arguments: [String: Any],
result: FLTFirebaseMethodCallResult) {
let modelDownloader = modelDownloaderFromArguments(arguments: arguments)
modelDownloader?.listDownloadedModels { response in
switch response {
case let .success(customModel):
let responseList: [[String: Any]] = customModel.map {
[
"filePath": $0.path,
"size": $0.size,
"hash": $0.hash,
"name": $0.name,
]
}
result.success(responseList)
case let .failure(error):
result.error(nil, nil, nil, error)
}
}
}
internal func getModel(arguments: [String: Any], result: FLTFirebaseMethodCallResult) {
let modelDownloader = modelDownloaderFromArguments(arguments: arguments)
let modelName = arguments["modelName"] as! String
let downloadType = arguments["downloadType"] as! String
let conditions = arguments["conditions"] as! [String: Bool]
let cellularAccess = conditions["iosAllowsCellularAccess"]!
var downloadTypeEnum = ModelDownloadType.localModel
if downloadType == "local" {
downloadTypeEnum = ModelDownloadType.localModel
} else if downloadType == "local_background" {
downloadTypeEnum = ModelDownloadType.localModelUpdateInBackground
} else if downloadType == "latest" {
downloadTypeEnum = ModelDownloadType.latestModel
}
let modelDownloadConditions = ModelDownloadConditions(allowsCellularAccess: cellularAccess)
modelDownloader?.getModel(
name: modelName,
downloadType: downloadTypeEnum,
conditions: modelDownloadConditions
) { response in
switch response {
case let .success(customModel):
result.success([
"filePath": customModel.path,
"size": customModel.size,
"hash": customModel.hash,
"name": customModel.name,
])
case let .failure(error):
result.error(nil, nil, nil, error)
}
}
}
internal func deleteDownloadedModel(arguments: [String: Any],
result: FLTFirebaseMethodCallResult) {
let modelDownloader = modelDownloaderFromArguments(arguments: arguments)
let modelName = arguments["modelName"]
modelDownloader?.deleteDownloadedModel(name: modelName as! String) { response in
switch response {
case .success():
result.success(nil)
case let .failure(error):
result.error(nil, nil, nil, error)
}
}
}
internal func modelDownloaderFromArguments(arguments: [String: Any]) -> ModelDownloader? {
let app: FirebaseApp = FLTFirebasePlugin.firebaseAppNamed(arguments["appName"] as! String)!
return ModelDownloader.modelDownloader(app: app)
}
}
| bsd-3-clause | 52ea9014e5712a0fbe92d3ef83e16759 | 35.570588 | 99 | 0.664629 | 4.997588 | false | false | false | false |
indisee/ITCiosScreenShotUploader | ItunesScreenshotUploader/Code/Managers/ScreenshotsHandler.swift | 1 | 5702 | //
// ScreenshotsHandler.swift
// ItunesScreenshotUploader
//
// Created by iN on 20/01/16.
// Copyright © 2016 2tickets2dublin. All rights reserved.
//
import Foundation
import Cocoa
class ScreenshotsHandler {
fileprivate let fileManager = FileManager.default
func splitScreenShotByLangs(_ rawScreenShots:[ScreenShot], useLangs:Bool) -> [String:[ScreenShot]] {
var langToScreens = [String:[ScreenShot]]()
for screen in rawScreenShots {
let lang = screen.screenShotLang(useLangs)
var langArray:[ScreenShot]? = langToScreens[lang]
if langArray == nil {
langArray = [ScreenShot]()
}
langArray!.append(screen)
langToScreens[lang] = langArray
}
return langToScreens
}
//Lang -> Platform -> Screenshot
func convertRawScreenShotsToDataSet(_ rawScreenShots:[ScreenShot], useLangs:Bool) -> [String:[[ScreenShot]]] {
let langToScreens = splitScreenShotByLangs(rawScreenShots, useLangs: useLangs)
let langScreenShots:[[ScreenShot]] = Array(langToScreens.values)
var final = [String:[[ScreenShot]]]()
for langScreenShot in langScreenShots {
var langPlatforms = [ScreenShotType:[ScreenShot]]()
for screen in langScreenShot {
var platformArray:[ScreenShot]? = langPlatforms[screen.screenType]
if platformArray == nil {
platformArray = [ScreenShot]()
}
platformArray!.append(screen)
langPlatforms[screen.screenType] = platformArray
}
var platforms = Array(langPlatforms.values)
platforms = platforms.sorted(by: { (sc1, sc2) -> Bool in
let screen1 = sc1[0]
let screen2 = sc2[0]
return screen1.screenType.rawValue < screen2.screenType.rawValue
})
if useLangs {
final[langScreenShot[0].langId] = platforms
} else {
final[NoLangID] = platforms
}
}
return final
}
func getAllScreenshotsFromDirectory(_ pathDir:String) -> [ScreenShot] {
var screens = [ScreenShot]()
let filelist = try? fileManager.contentsOfDirectory(atPath: pathDir)
if filelist != nil {
for filename in filelist! {
if filename == ".DS_Store" {
continue
}
let fullPath = "\(pathDir)/\(filename)"
let (s, isDir) = screenShotForPath(fullPath, name: filename)
if isDir {
screens += getAllScreenshotsFromDirectory(fullPath)
} else if let screen = s {
screens.append(screen)
}
}
} else {
let fullPath = pathDir
let components = pathDir.components(separatedBy: "/")
if let filename = components.last {
let (s, isDir) = screenShotForPath(fullPath, name: filename)
if isDir {
screens += getAllScreenshotsFromDirectory(fullPath)
} else if let screen = s {
screens.append(screen)
}
}
}
return screens
}
func screenShotForPath(_ path:String, name:String) -> (screenshot:ScreenShot?, isDirectory:Bool) {
do{
let attr:[FileAttributeKey : Any] = try FileManager.default.attributesOfItem(atPath: path) as [FileAttributeKey : Any]
let a = attr
let type:String = a[FileAttributeKey.type] as! String
if type == FileAttributeType.typeDirectory.rawValue {
return (nil, true)
} else {
if let i = imageForPath(path) {
let s = ScreenShot()
s.path = path
s.image = i
s.fileSize = a[FileAttributeKey.size] as! Int
s.name = name
return (s, false)
}
}
}catch{
}
return (nil, false)
}
func imageForPath(_ path:String) -> NSImage? {
let image = NSImage(contentsOfFile: path)
return image
}
//MARK: - File management helper -
func copyScreenShotsImagesToITMSP(_ allImagesPlatf:[[[ScreenShot]]]) {
for allImages in allImagesPlatf {
for img in allImages {
for i in img {
if i.screenType != .iUndefinedScreenShotType {
let path = pathForImageOfScreenShot(i)
copyScreenShot(i, toPath: path)
i.md5 = md5(path) //made it here if for some reason md5 would be changed after copying
}
}
}
}
}
fileprivate func copyScreenShot(_ screenShot:ScreenShot, toPath path:String) {
do {
try
fileManager.copyItem(atPath: screenShot.path, toPath: path)
} catch {
assert(false)
}
}
func pathForImageOfScreenShot(_ screenShot:ScreenShot) -> String {
return "\(ItunesConnectHandler.sharedInstance.itmspPath())/\(screenShot.nameForUpload)"
}
}
| mit | 5707ae21611c9ca7eaf26a7b1b2f11f9 | 30.849162 | 130 | 0.507806 | 5.508213 | false | false | false | false |
jiayue198509/SmartTeaGarden_IOS | SmartTeaGarden/SmartTeaGarden/classes/Main/View/TableViewCell/BaseTableViewCell.swift | 5 | 1377 | //
// BaseTableViewCell.swift
// SlideMenuControllerSwift
//
// Created by Yuji Hato on 1/22/15.
// Copyright (c) 2015 Yuji Hato. All rights reserved.
//
import UIKit
open class BaseTableViewCell : UITableViewCell {
class var identifier: String { return String.className(self) }
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
open override func awakeFromNib() {
}
open func setup() {
}
open class func height() -> CGFloat {
return 48
}
open func setData(_ data: Any?) {
self.backgroundColor = UIColor(hex: "F1F8E9")
self.textLabel?.font = UIFont.italicSystemFont(ofSize: 18)
self.textLabel?.textColor = UIColor(hex: "9E9E9E")
if let menuText = data as? String {
self.textLabel?.text = menuText
}
}
override open func setHighlighted(_ highlighted: Bool, animated: Bool) {
if highlighted {
self.alpha = 0.4
} else {
self.alpha = 1.0
}
}
// ignore the default handling
override open func setSelected(_ selected: Bool, animated: Bool) {
}
}
| mit | 0467c4a3eeb0a9695b729ce22d84cd08 | 24.5 | 76 | 0.599129 | 4.413462 | false | false | false | false |
khizkhiz/swift | benchmark/single-source/Hanoi.swift | 2 | 1377 | //===--- Hanoi.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// This test checks performance of Swift hanoi tower.
// <rdar://problem/22151932>
import Foundation
import TestsUtils
struct Move {
var from: String
var to : String
init(from:String, to:String) {
self.from = from
self.to = to
}
}
class TowersOfHanoi {
// Record all moves made.
var moves : [Move] = [Move]()
func solve(n: Int, start: String, auxiliary: String, end: String) {
if (n == 1) {
moves.append(Move(from:start, to:end))
} else {
solve(n - 1, start: start, auxiliary: end, end: auxiliary)
moves.append(Move(from:start, to:end))
solve(n - 1, start: auxiliary, auxiliary: start, end: end)
}
}
}
@inline(never)
public func run_Hanoi(N: Int) {
for _ in 1...100*N {
let hanoi: TowersOfHanoi = TowersOfHanoi()
hanoi.solve(10, start: "A", auxiliary: "B", end: "C")
}
}
| apache-2.0 | 6df6baea34f73c264b0faac231fa539c | 27.6875 | 80 | 0.580973 | 3.672 | false | false | false | false |
ngageoint/fog-machine | Demo/FogViewshed/FogViewshed/Models/Grid/RectangularPerimeter.swift | 1 | 4552 | import Foundation
class RectangularPerimeter : Perimeter {
let dataGrid:DataGrid
let rowSize:Int
let columnSize:Int
var perimeterSize:Int
var perimeterCellIndex:Int
init(dataGrid: DataGrid) {
self.dataGrid = dataGrid
self.rowSize = dataGrid.data[0].count
self.columnSize = dataGrid.data.count
self.perimeterCellIndex = 0
self.perimeterSize = 1
if(rowSize == 1 && columnSize == 1) {
perimeterSize = 1
} else if(rowSize == 1) {
perimeterSize = columnSize
} else if(columnSize == 1) {
perimeterSize = rowSize
} else {
perimeterSize = 2*(rowSize + columnSize - 2)
}
}
func resetPerimeter() {
self.perimeterCellIndex = 0
}
func hasAnotherPerimeterCell() -> Bool {
return (perimeterCellIndex < perimeterSize)
}
func getNextPerimeterCell() -> (x:Int,y:Int) {
var cell:(Int,Int) = (0,0)
if(hasAnotherPerimeterCell()) {
var i:Int = Int(perimeterCellIndex)
if(i >= 0 && i < columnSize - 1) {
cell = (0, i)
} else {
i = i - (columnSize - 1)
if(i >= 0 && i < rowSize - 1) {
cell = (i, columnSize - 1)
} else {
i = i - (rowSize - 1)
if(i >= 0 && i < columnSize - 1) {
cell = (rowSize - 1, columnSize - 1 - i)
} else {
i = i - (columnSize - 1)
if(i >= 0 && i < rowSize - 1) {
cell = (rowSize - 1 - i, 0)
} else {
i = i - (rowSize - 1)
NSLog("Error: Index \(perimeterCellIndex) is out of bounds")
}
}
}
}
}
perimeterCellIndex += 1
return cell
}
func XYToIndex(xy:(Int,Int)) -> Int {
// for the left side and top side, the index is (the row index + the column index)
var index:Int = xy.0 + xy.1
// make sure this is a non-degenerate case
if(rowSize > 1 && columnSize > 1) {
// if the index is on the bottom side or the right side, we need to account for the indexes already seen by the left and right side
if(((xy.1 == 0) && (xy.0 > 0)) || ((xy.0 == rowSize - 1) && (xy.1 < columnSize-1))) {
index = perimeterSize - (xy.0 + xy.1)
}
}
return index
}
// private func getPerimeterCells() -> [(x:Int,y:Int)] {
// // Perimeter goes clockwise from the lower left coordinate
// var perimeter:[(x:Int, y:Int)] = []
//
// let rowSize:Int = dataGrid.data.count
// let columnSize:Int = dataGrid.data[0].count
//
// var perimeterSize:Int
//
// if(rowSize == 1 && columnSize == 1) {
// perimeterSize = 1
// } else if(rowSize == 1) {
// perimeterSize = columnSize
// } else if(columnSize == 1) {
// perimeterSize = rowSize
// } else {
// perimeterSize = 2*(rowSize + columnSize - 2)
// }
//
// if(perimeterSize == 1) {
// perimeter.append((0,0))
// } else {
// // lower left to top left
// var i:Int = 0
// while(i <= columnSize - 1) {
// perimeter.append((0, i))
// i = i + 1
// }
//
// // top left to top right (excludes corners)
// i = 1
// while(i <= rowSize - 2) {
// perimeter.append((i, columnSize - 1))
// i = i + 1
// }
//
// // top right to lower right
// i = columnSize - 1
// while(i >= 0) {
// perimeter.append((rowSize - 1, i))
// i = i - 1
// }
//
// // lower right to lower left (excludes corners)
// i = rowSize - 2
// while(i >= 1) {
// perimeter.append((i, 0))
// i = i - 1
// }
// }
//
// if(perimeterSize != perimeter.count) {
// NSLog("Perimeter was the wrong size! Expected: \(perimeterSize), received: \(perimeter.count)")
// }
//
// return perimeter
// }
} | mit | ce63da1c8128799032d30e9c893e78a2 | 31.521429 | 143 | 0.434754 | 4.191529 | false | false | false | false |
borglab/SwiftFusion | Tests/BeeTrackingTests/AppearanceRAETests.swift | 1 | 2151 | // Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
import XCTest
import BeeTracking
class BeeTrackingTests: XCTestCase {
/// Test that the hand-coded Jacobian for the decode method gives the same results as the
/// AD-generated Jacobian.
func testDecodeJacobian() {
// Size of the images.
let h = 10
let w = 10
let c = 10
// Number of batches to test. (`decodeJacobian` currently only supports one batch at a time).
let batchCount = 1
// Model size parameters.
let latentDimension = 5
let hiddenDimension = 100
// A random model and a random latent code to decode.
let model = DenseRAE(
imageHeight: h, imageWidth: w, imageChannels: c,
hiddenDimension: hiddenDimension, latentDimension: latentDimension)
let latent = Tensor<Double>(randomNormal: [batchCount, latentDimension])
// The hand-coded Jacobian.
let actualJacobian = model.decodeJacobian(latent)
// The AD-generated pullback function.
let pb = pullback(at: latent) { model.decode($0) }
// Pass all the unit vectors throught the AD-generated pullback function and check that the
// results match the hand-coded Jacobian.
for batch in 0..<batchCount {
for i in 0..<h {
for j in 0..<w {
for k in 0..<c {
var unit = Tensor<Double>(zeros: [batchCount, h, w, c])
unit[batch, i, j, k] = Tensor(1)
XCTAssertLessThan(
(actualJacobian[batch, i, j, k] - pb(unit)).squared().sum().scalar!, 1e-6)
}
}
}
}
}
}
| apache-2.0 | 33ee978bf0dc7bb1ad83a2244abc51a1 | 33.142857 | 97 | 0.668526 | 4.15251 | false | true | false | false |
weareyipyip/SwiftStylable | Example/SwiftStylableExample/Classes/View/Style/StyleKit.swift | 1 | 36555 | //
// StyleKit.swift
// StylableTest
//
// Created by Marcel Bloemendaal on 11/08/2017.
// Copyright © 2017 YipYip. All rights reserved.
//
// Generated by PaintCode
// http://www.paintcodeapp.com
//
import UIKit
public class StyleKit : NSObject {
//// Cache
private struct Cache {
static var imageOfWhatsAppIcon: UIImage?
static var whatsAppIconTargets: [AnyObject]?
static var imageOfEMailIcon: UIImage?
static var eMailIconTargets: [AnyObject]?
static var imageOfFacebookIcon: UIImage?
static var facebookIconTargets: [AnyObject]?
static var imageOfTwitterIcon: UIImage?
static var twitterIconTargets: [AnyObject]?
static var imageOfCallIcon: UIImage?
static var callIconTargets: [AnyObject]?
static var imageOfLinkedInIcon: UIImage?
static var linkedInIconTargets: [AnyObject]?
static var imageOfHomeIcon: UIImage?
static var homeIconTargets: [AnyObject]?
}
//// Drawing Methods
@objc public dynamic class func drawWhatsAppIcon() {
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 10.04, y: 18.24))
bezierPath.addLine(to: CGPoint(x: 10.04, y: 18.24))
bezierPath.addCurve(to: CGPoint(x: 5.83, y: 17.09), controlPoint1: CGPoint(x: 8.55, y: 18.24), controlPoint2: CGPoint(x: 7.1, y: 17.84))
bezierPath.addLine(to: CGPoint(x: 5.52, y: 16.91))
bezierPath.addLine(to: CGPoint(x: 2.39, y: 17.73))
bezierPath.addLine(to: CGPoint(x: 3.23, y: 14.68))
bezierPath.addLine(to: CGPoint(x: 3.03, y: 14.36))
bezierPath.addCurve(to: CGPoint(x: 1.76, y: 9.96), controlPoint1: CGPoint(x: 2.2, y: 13.05), controlPoint2: CGPoint(x: 1.76, y: 11.52))
bezierPath.addCurve(to: CGPoint(x: 10.05, y: 1.68), controlPoint1: CGPoint(x: 1.77, y: 5.39), controlPoint2: CGPoint(x: 5.48, y: 1.68))
bezierPath.addCurve(to: CGPoint(x: 15.9, y: 4.11), controlPoint1: CGPoint(x: 12.26, y: 1.68), controlPoint2: CGPoint(x: 14.33, y: 2.54))
bezierPath.addCurve(to: CGPoint(x: 18.32, y: 9.96), controlPoint1: CGPoint(x: 17.46, y: 5.67), controlPoint2: CGPoint(x: 18.32, y: 7.75))
bezierPath.addCurve(to: CGPoint(x: 10.04, y: 18.24), controlPoint1: CGPoint(x: 18.32, y: 14.53), controlPoint2: CGPoint(x: 14.6, y: 18.24))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 17.09, y: 2.92))
bezierPath.addCurve(to: CGPoint(x: 10.04, y: 0), controlPoint1: CGPoint(x: 15.21, y: 1.04), controlPoint2: CGPoint(x: 12.71, y: 0))
bezierPath.addCurve(to: CGPoint(x: 0.08, y: 9.96), controlPoint1: CGPoint(x: 4.55, y: 0), controlPoint2: CGPoint(x: 0.09, y: 4.47))
bezierPath.addCurve(to: CGPoint(x: 1.41, y: 14.94), controlPoint1: CGPoint(x: 0.08, y: 11.71), controlPoint2: CGPoint(x: 0.54, y: 13.43))
bezierPath.addLine(to: CGPoint(x: 0, y: 20.1))
bezierPath.addLine(to: CGPoint(x: 5.28, y: 18.71))
bezierPath.addCurve(to: CGPoint(x: 10.04, y: 19.92), controlPoint1: CGPoint(x: 6.73, y: 19.5), controlPoint2: CGPoint(x: 8.37, y: 19.92))
bezierPath.addLine(to: CGPoint(x: 10.04, y: 19.92))
bezierPath.addCurve(to: CGPoint(x: 20, y: 9.97), controlPoint1: CGPoint(x: 15.53, y: 19.92), controlPoint2: CGPoint(x: 20, y: 15.46))
bezierPath.addCurve(to: CGPoint(x: 17.09, y: 2.92), controlPoint1: CGPoint(x: 20, y: 7.3), controlPoint2: CGPoint(x: 18.97, y: 4.8))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 14.58, y: 12.04))
bezierPath.addCurve(to: CGPoint(x: 12.88, y: 11.23), controlPoint1: CGPoint(x: 14.33, y: 11.92), controlPoint2: CGPoint(x: 13.11, y: 11.32))
bezierPath.addCurve(to: CGPoint(x: 12.32, y: 11.36), controlPoint1: CGPoint(x: 12.65, y: 11.15), controlPoint2: CGPoint(x: 12.49, y: 11.11))
bezierPath.addCurve(to: CGPoint(x: 11.53, y: 12.33), controlPoint1: CGPoint(x: 12.16, y: 11.61), controlPoint2: CGPoint(x: 11.68, y: 12.17))
bezierPath.addCurve(to: CGPoint(x: 10.99, y: 12.4), controlPoint1: CGPoint(x: 11.39, y: 12.5), controlPoint2: CGPoint(x: 11.24, y: 12.52))
bezierPath.addCurve(to: CGPoint(x: 8.99, y: 11.16), controlPoint1: CGPoint(x: 10.75, y: 12.27), controlPoint2: CGPoint(x: 9.94, y: 12.01))
bezierPath.addCurve(to: CGPoint(x: 7.61, y: 9.44), controlPoint1: CGPoint(x: 8.25, y: 10.5), controlPoint2: CGPoint(x: 7.75, y: 9.69))
bezierPath.addCurve(to: CGPoint(x: 7.72, y: 8.93), controlPoint1: CGPoint(x: 7.46, y: 9.19), controlPoint2: CGPoint(x: 7.59, y: 9.05))
bezierPath.addCurve(to: CGPoint(x: 8.09, y: 8.49), controlPoint1: CGPoint(x: 7.83, y: 8.82), controlPoint2: CGPoint(x: 7.97, y: 8.64))
bezierPath.addCurve(to: CGPoint(x: 8.34, y: 8.08), controlPoint1: CGPoint(x: 8.22, y: 8.35), controlPoint2: CGPoint(x: 8.26, y: 8.24))
bezierPath.addCurve(to: CGPoint(x: 8.32, y: 7.64), controlPoint1: CGPoint(x: 8.42, y: 7.91), controlPoint2: CGPoint(x: 8.38, y: 7.77))
bezierPath.addCurve(to: CGPoint(x: 7.55, y: 5.79), controlPoint1: CGPoint(x: 8.26, y: 7.52), controlPoint2: CGPoint(x: 7.76, y: 6.29))
bezierPath.addCurve(to: CGPoint(x: 6.99, y: 5.37), controlPoint1: CGPoint(x: 7.35, y: 5.31), controlPoint2: CGPoint(x: 7.15, y: 5.38))
bezierPath.addCurve(to: CGPoint(x: 6.52, y: 5.36), controlPoint1: CGPoint(x: 6.85, y: 5.36), controlPoint2: CGPoint(x: 6.68, y: 5.36))
bezierPath.addCurve(to: CGPoint(x: 5.85, y: 5.67), controlPoint1: CGPoint(x: 6.35, y: 5.36), controlPoint2: CGPoint(x: 6.08, y: 5.42))
bezierPath.addCurve(to: CGPoint(x: 4.98, y: 7.75), controlPoint1: CGPoint(x: 5.62, y: 5.92), controlPoint2: CGPoint(x: 4.98, y: 6.52))
bezierPath.addCurve(to: CGPoint(x: 6, y: 10.32), controlPoint1: CGPoint(x: 4.98, y: 8.97), controlPoint2: CGPoint(x: 5.87, y: 10.15))
bezierPath.addCurve(to: CGPoint(x: 10.25, y: 14.08), controlPoint1: CGPoint(x: 6.12, y: 10.49), controlPoint2: CGPoint(x: 7.75, y: 13))
bezierPath.addCurve(to: CGPoint(x: 11.67, y: 14.6), controlPoint1: CGPoint(x: 10.84, y: 14.33), controlPoint2: CGPoint(x: 11.31, y: 14.49))
bezierPath.addCurve(to: CGPoint(x: 13.23, y: 14.7), controlPoint1: CGPoint(x: 12.26, y: 14.79), controlPoint2: CGPoint(x: 12.8, y: 14.76))
bezierPath.addCurve(to: CGPoint(x: 14.91, y: 13.52), controlPoint1: CGPoint(x: 13.71, y: 14.63), controlPoint2: CGPoint(x: 14.71, y: 14.1))
bezierPath.addCurve(to: CGPoint(x: 15.06, y: 12.33), controlPoint1: CGPoint(x: 15.12, y: 12.94), controlPoint2: CGPoint(x: 15.12, y: 12.44))
bezierPath.addCurve(to: CGPoint(x: 14.58, y: 12.04), controlPoint1: CGPoint(x: 15, y: 12.23), controlPoint2: CGPoint(x: 14.83, y: 12.17))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
fillColor9.setFill()
bezierPath.fill()
}
@objc public dynamic class func drawEMailIcon() {
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 17.5, y: 12.5))
bezierPath.addLine(to: CGPoint(x: 2.5, y: 12.5))
bezierPath.addLine(to: CGPoint(x: 2.5, y: 3.75))
bezierPath.addLine(to: CGPoint(x: 10, y: 10))
bezierPath.addLine(to: CGPoint(x: 17.5, y: 3.75))
bezierPath.addLine(to: CGPoint(x: 17.5, y: 12.5))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 16.25, y: 2.5))
bezierPath.addLine(to: CGPoint(x: 10, y: 7.5))
bezierPath.addLine(to: CGPoint(x: 3.75, y: 2.5))
bezierPath.addLine(to: CGPoint(x: 16.25, y: 2.5))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 18.75, y: 0))
bezierPath.addLine(to: CGPoint(x: 1.25, y: 0))
bezierPath.addCurve(to: CGPoint(x: 0, y: 1.25), controlPoint1: CGPoint(x: 0.56, y: 0), controlPoint2: CGPoint(x: 0, y: 0.56))
bezierPath.addLine(to: CGPoint(x: 0, y: 13.75))
bezierPath.addCurve(to: CGPoint(x: 1.25, y: 15), controlPoint1: CGPoint(x: 0, y: 14.44), controlPoint2: CGPoint(x: 0.56, y: 15))
bezierPath.addLine(to: CGPoint(x: 18.75, y: 15))
bezierPath.addCurve(to: CGPoint(x: 20, y: 13.75), controlPoint1: CGPoint(x: 19.44, y: 15), controlPoint2: CGPoint(x: 20, y: 14.44))
bezierPath.addLine(to: CGPoint(x: 20, y: 1.25))
bezierPath.addCurve(to: CGPoint(x: 18.75, y: 0), controlPoint1: CGPoint(x: 20, y: 0.56), controlPoint2: CGPoint(x: 19.44, y: 0))
bezierPath.addLine(to: CGPoint(x: 18.75, y: 0))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
fillColor9.setFill()
bezierPath.fill()
}
@objc public dynamic class func drawFacebookIcon() {
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 8.52, y: 3.86))
bezierPath.addCurve(to: CGPoint(x: 6.13, y: 4.3), controlPoint1: CGPoint(x: 7.61, y: 3.86), controlPoint2: CGPoint(x: 6.72, y: 4.01))
bezierPath.addCurve(to: CGPoint(x: 4.88, y: 5.57), controlPoint1: CGPoint(x: 5.53, y: 4.59), controlPoint2: CGPoint(x: 5.1, y: 5.11))
bezierPath.addCurve(to: CGPoint(x: 4.54, y: 7.54), controlPoint1: CGPoint(x: 4.65, y: 6.03), controlPoint2: CGPoint(x: 4.54, y: 6.6))
bezierPath.addLine(to: CGPoint(x: 4.54, y: 8.43))
bezierPath.addLine(to: CGPoint(x: 3.05, y: 8.43))
bezierPath.addLine(to: CGPoint(x: 3.05, y: 10.78))
bezierPath.addLine(to: CGPoint(x: 4.54, y: 10.78))
bezierPath.addLine(to: CGPoint(x: 4.54, y: 18.56))
bezierPath.addLine(to: CGPoint(x: 7.74, y: 18.56))
bezierPath.addLine(to: CGPoint(x: 7.74, y: 10.78))
bezierPath.addLine(to: CGPoint(x: 9.74, y: 10.78))
bezierPath.addLine(to: CGPoint(x: 10.29, y: 8.43))
bezierPath.addLine(to: CGPoint(x: 7.74, y: 8.43))
bezierPath.addLine(to: CGPoint(x: 7.74, y: 7.59))
bezierPath.addCurve(to: CGPoint(x: 8.05, y: 6.44), controlPoint1: CGPoint(x: 7.74, y: 7.02), controlPoint2: CGPoint(x: 7.84, y: 6.64))
bezierPath.addCurve(to: CGPoint(x: 9.14, y: 6.12), controlPoint1: CGPoint(x: 8.26, y: 6.24), controlPoint2: CGPoint(x: 8.67, y: 6.12))
bezierPath.addCurve(to: CGPoint(x: 10.5, y: 6.63), controlPoint1: CGPoint(x: 9.63, y: 6.12), controlPoint2: CGPoint(x: 10.02, y: 6.34))
bezierPath.addLine(to: CGPoint(x: 11.09, y: 4.43))
bezierPath.addCurve(to: CGPoint(x: 8.52, y: 3.86), controlPoint1: CGPoint(x: 10.19, y: 4.17), controlPoint2: CGPoint(x: 9.46, y: 3.86))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 18.46, y: 20.01))
bezierPath.addLine(to: CGPoint(x: 1.54, y: 20.01))
bezierPath.addCurve(to: CGPoint(x: 0, y: 18.54), controlPoint1: CGPoint(x: 0.69, y: 20.01), controlPoint2: CGPoint(x: 0, y: 19.39))
bezierPath.addLine(to: CGPoint(x: 0, y: 1.54))
bezierPath.addCurve(to: CGPoint(x: 1.54, y: -0), controlPoint1: CGPoint(x: 0, y: 0.69), controlPoint2: CGPoint(x: 0.69, y: -0))
bezierPath.addLine(to: CGPoint(x: 18.46, y: -0))
bezierPath.addCurve(to: CGPoint(x: 20, y: 1.54), controlPoint1: CGPoint(x: 19.31, y: -0), controlPoint2: CGPoint(x: 20, y: 0.69))
bezierPath.addLine(to: CGPoint(x: 20, y: 18.54))
bezierPath.addCurve(to: CGPoint(x: 18.46, y: 20.01), controlPoint1: CGPoint(x: 20, y: 19.39), controlPoint2: CGPoint(x: 19.31, y: 20.01))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
fillColor9.setFill()
bezierPath.fill()
}
@objc public dynamic class func drawTwitterIcon() {
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 13.6, y: 0))
bezierPath.addCurve(to: CGPoint(x: 16.85, y: 1.29), controlPoint1: CGPoint(x: 15.19, y: -0.03), controlPoint2: CGPoint(x: 16.04, y: 0.55))
bezierPath.addCurve(to: CGPoint(x: 18.95, y: 0.58), controlPoint1: CGPoint(x: 17.53, y: 1.23), controlPoint2: CGPoint(x: 18.42, y: 0.85))
bezierPath.addCurve(to: CGPoint(x: 19.46, y: 0.3), controlPoint1: CGPoint(x: 19.12, y: 0.49), controlPoint2: CGPoint(x: 19.29, y: 0.39))
bezierPath.addCurve(to: CGPoint(x: 18.13, y: 2.23), controlPoint1: CGPoint(x: 19.16, y: 1.11), controlPoint2: CGPoint(x: 18.75, y: 1.74))
bezierPath.addCurve(to: CGPoint(x: 17.68, y: 2.55), controlPoint1: CGPoint(x: 17.99, y: 2.33), controlPoint2: CGPoint(x: 17.85, y: 2.48))
bezierPath.addLine(to: CGPoint(x: 17.68, y: 2.56))
bezierPath.addCurve(to: CGPoint(x: 20, y: 1.93), controlPoint1: CGPoint(x: 18.57, y: 2.55), controlPoint2: CGPoint(x: 19.3, y: 2.15))
bezierPath.addLine(to: CGPoint(x: 20, y: 1.94))
bezierPath.addCurve(to: CGPoint(x: 18.61, y: 3.53), controlPoint1: CGPoint(x: 19.63, y: 2.52), controlPoint2: CGPoint(x: 19.14, y: 3.11))
bezierPath.addCurve(to: CGPoint(x: 17.97, y: 4.04), controlPoint1: CGPoint(x: 18.4, y: 3.7), controlPoint2: CGPoint(x: 18.18, y: 3.87))
bezierPath.addCurve(to: CGPoint(x: 17.78, y: 6.68), controlPoint1: CGPoint(x: 17.98, y: 4.99), controlPoint2: CGPoint(x: 17.95, y: 5.88))
bezierPath.addCurve(to: CGPoint(x: 9.74, y: 15.75), controlPoint1: CGPoint(x: 16.75, y: 11.28), controlPoint2: CGPoint(x: 14.04, y: 14.41))
bezierPath.addCurve(to: CGPoint(x: 3.93, y: 15.99), controlPoint1: CGPoint(x: 8.2, y: 16.23), controlPoint2: CGPoint(x: 5.7, y: 16.43))
bezierPath.addCurve(to: CGPoint(x: 1.52, y: 15.2), controlPoint1: CGPoint(x: 3.06, y: 15.77), controlPoint2: CGPoint(x: 2.27, y: 15.53))
bezierPath.addCurve(to: CGPoint(x: 0.36, y: 14.6), controlPoint1: CGPoint(x: 1.11, y: 15.02), controlPoint2: CGPoint(x: 0.73, y: 14.82))
bezierPath.addCurve(to: CGPoint(x: 0, y: 14.38), controlPoint1: CGPoint(x: 0.24, y: 14.53), controlPoint2: CGPoint(x: 0.12, y: 14.46))
bezierPath.addCurve(to: CGPoint(x: 1.31, y: 14.43), controlPoint1: CGPoint(x: 0.4, y: 14.39), controlPoint2: CGPoint(x: 0.87, y: 14.5))
bezierPath.addCurve(to: CGPoint(x: 2.48, y: 14.3), controlPoint1: CGPoint(x: 1.72, y: 14.37), controlPoint2: CGPoint(x: 2.11, y: 14.38))
bezierPath.addCurve(to: CGPoint(x: 4.94, y: 13.41), controlPoint1: CGPoint(x: 3.41, y: 14.1), controlPoint2: CGPoint(x: 4.23, y: 13.83))
bezierPath.addCurve(to: CGPoint(x: 6.06, y: 12.69), controlPoint1: CGPoint(x: 5.29, y: 13.21), controlPoint2: CGPoint(x: 5.81, y: 12.98))
bezierPath.addCurve(to: CGPoint(x: 4.84, y: 12.47), controlPoint1: CGPoint(x: 5.6, y: 12.69), controlPoint2: CGPoint(x: 5.18, y: 12.59))
bezierPath.addCurve(to: CGPoint(x: 2.23, y: 9.84), controlPoint1: CGPoint(x: 3.51, y: 12), controlPoint2: CGPoint(x: 2.74, y: 11.14))
bezierPath.addCurve(to: CGPoint(x: 4.06, y: 9.76), controlPoint1: CGPoint(x: 2.63, y: 9.89), controlPoint2: CGPoint(x: 3.79, y: 9.99))
bezierPath.addCurve(to: CGPoint(x: 2.72, y: 9.22), controlPoint1: CGPoint(x: 3.56, y: 9.73), controlPoint2: CGPoint(x: 3.07, y: 9.44))
bezierPath.addCurve(to: CGPoint(x: 0.79, y: 5.71), controlPoint1: CGPoint(x: 1.66, y: 8.55), controlPoint2: CGPoint(x: 0.78, y: 7.43))
bezierPath.addCurve(to: CGPoint(x: 1.21, y: 5.91), controlPoint1: CGPoint(x: 0.93, y: 5.78), controlPoint2: CGPoint(x: 1.07, y: 5.84))
bezierPath.addCurve(to: CGPoint(x: 2.07, y: 6.15), controlPoint1: CGPoint(x: 1.48, y: 6.02), controlPoint2: CGPoint(x: 1.75, y: 6.08))
bezierPath.addCurve(to: CGPoint(x: 2.63, y: 6.2), controlPoint1: CGPoint(x: 2.21, y: 6.18), controlPoint2: CGPoint(x: 2.48, y: 6.26))
bezierPath.addLine(to: CGPoint(x: 2.61, y: 6.2))
bezierPath.addCurve(to: CGPoint(x: 1.86, y: 5.54), controlPoint1: CGPoint(x: 2.41, y: 5.96), controlPoint2: CGPoint(x: 2.07, y: 5.8))
bezierPath.addCurve(to: CGPoint(x: 0.94, y: 1.82), controlPoint1: CGPoint(x: 1.18, y: 4.69), controlPoint2: CGPoint(x: 0.54, y: 3.38))
bezierPath.addCurve(to: CGPoint(x: 1.38, y: 0.75), controlPoint1: CGPoint(x: 1.04, y: 1.42), controlPoint2: CGPoint(x: 1.21, y: 1.07))
bezierPath.addCurve(to: CGPoint(x: 1.4, y: 0.76), controlPoint1: CGPoint(x: 1.39, y: 0.75), controlPoint2: CGPoint(x: 1.4, y: 0.76))
bezierPath.addCurve(to: CGPoint(x: 1.77, y: 1.19), controlPoint1: CGPoint(x: 1.48, y: 0.93), controlPoint2: CGPoint(x: 1.66, y: 1.05))
bezierPath.addCurve(to: CGPoint(x: 2.99, y: 2.36), controlPoint1: CGPoint(x: 2.12, y: 1.62), controlPoint2: CGPoint(x: 2.55, y: 2.01))
bezierPath.addCurve(to: CGPoint(x: 8.01, y: 4.78), controlPoint1: CGPoint(x: 4.49, y: 3.53), controlPoint2: CGPoint(x: 5.84, y: 4.25))
bezierPath.addCurve(to: CGPoint(x: 9.85, y: 5.02), controlPoint1: CGPoint(x: 8.56, y: 4.92), controlPoint2: CGPoint(x: 9.19, y: 5.02))
bezierPath.addCurve(to: CGPoint(x: 9.87, y: 3.09), controlPoint1: CGPoint(x: 9.67, y: 4.48), controlPoint2: CGPoint(x: 9.72, y: 3.61))
bezierPath.addCurve(to: CGPoint(x: 12.19, y: 0.34), controlPoint1: CGPoint(x: 10.24, y: 1.79), controlPoint2: CGPoint(x: 11.03, y: 0.85))
bezierPath.addCurve(to: CGPoint(x: 13.1, y: 0.06), controlPoint1: CGPoint(x: 12.47, y: 0.22), controlPoint2: CGPoint(x: 12.78, y: 0.13))
bezierPath.addCurve(to: CGPoint(x: 13.6, y: 0), controlPoint1: CGPoint(x: 13.27, y: 0.04), controlPoint2: CGPoint(x: 13.44, y: 0.02))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
fillColor9.setFill()
bezierPath.fill()
}
@objc public dynamic class func drawCallIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 18, height: 16), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 18, height: 16), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 18, y: resizedFrame.height / 16)
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// iPhone-6-—-Screens
//// 08e-Contact
//// form
//// cell
//// phone-highlighted Drawing
let phonehighlightedPath = UIBezierPath()
phonehighlightedPath.move(to: CGPoint(x: 13.37, y: 9.94))
phonehighlightedPath.addCurve(to: CGPoint(x: 12.42, y: 10.15), controlPoint1: CGPoint(x: 12.98, y: 9.8), controlPoint2: CGPoint(x: 12.7, y: 9.73))
phonehighlightedPath.addCurve(to: CGPoint(x: 11.09, y: 11.8), controlPoint1: CGPoint(x: 12.14, y: 10.57), controlPoint2: CGPoint(x: 11.33, y: 11.52))
phonehighlightedPath.addCurve(to: CGPoint(x: 10.18, y: 11.91), controlPoint1: CGPoint(x: 10.84, y: 12.08), controlPoint2: CGPoint(x: 10.6, y: 12.12))
phonehighlightedPath.addCurve(to: CGPoint(x: 6.79, y: 9.82), controlPoint1: CGPoint(x: 9.75, y: 11.7), controlPoint2: CGPoint(x: 8.4, y: 11.25))
phonehighlightedPath.addCurve(to: CGPoint(x: 4.45, y: 6.9), controlPoint1: CGPoint(x: 5.54, y: 8.7), controlPoint2: CGPoint(x: 4.69, y: 7.32))
phonehighlightedPath.addCurve(to: CGPoint(x: 4.63, y: 6.04), controlPoint1: CGPoint(x: 4.2, y: 6.48), controlPoint2: CGPoint(x: 4.42, y: 6.25))
phonehighlightedPath.addCurve(to: CGPoint(x: 5.26, y: 5.3), controlPoint1: CGPoint(x: 4.82, y: 5.85), controlPoint2: CGPoint(x: 5.05, y: 5.55))
phonehighlightedPath.addCurve(to: CGPoint(x: 5.68, y: 4.6), controlPoint1: CGPoint(x: 5.47, y: 5.06), controlPoint2: CGPoint(x: 5.54, y: 4.88))
phonehighlightedPath.addCurve(to: CGPoint(x: 5.65, y: 3.86), controlPoint1: CGPoint(x: 5.83, y: 4.32), controlPoint2: CGPoint(x: 5.75, y: 4.07))
phonehighlightedPath.addCurve(to: CGPoint(x: 4.35, y: 0.74), controlPoint1: CGPoint(x: 5.54, y: 3.65), controlPoint2: CGPoint(x: 4.7, y: 1.58))
phonehighlightedPath.addCurve(to: CGPoint(x: 3.4, y: 0.01), controlPoint1: CGPoint(x: 4.01, y: -0.08), controlPoint2: CGPoint(x: 3.66, y: 0.03))
phonehighlightedPath.addCurve(to: CGPoint(x: 2.6, y: -0), controlPoint1: CGPoint(x: 3.16, y: 0), controlPoint2: CGPoint(x: 2.88, y: -0))
phonehighlightedPath.addCurve(to: CGPoint(x: 1.47, y: 0.53), controlPoint1: CGPoint(x: 2.32, y: -0), controlPoint2: CGPoint(x: 1.86, y: 0.11))
phonehighlightedPath.addCurve(to: CGPoint(x: 0, y: 4.04), controlPoint1: CGPoint(x: 1.09, y: 0.95), controlPoint2: CGPoint(x: 0, y: 1.97))
phonehighlightedPath.addCurve(to: CGPoint(x: 1.72, y: 8.39), controlPoint1: CGPoint(x: 0, y: 6.11), controlPoint2: CGPoint(x: 1.51, y: 8.11))
phonehighlightedPath.addCurve(to: CGPoint(x: 8.91, y: 14.75), controlPoint1: CGPoint(x: 1.93, y: 8.68), controlPoint2: CGPoint(x: 4.69, y: 12.93))
phonehighlightedPath.addCurve(to: CGPoint(x: 11.31, y: 15.64), controlPoint1: CGPoint(x: 9.92, y: 15.19), controlPoint2: CGPoint(x: 10.7, y: 15.45))
phonehighlightedPath.addCurve(to: CGPoint(x: 13.96, y: 15.81), controlPoint1: CGPoint(x: 12.32, y: 15.96), controlPoint2: CGPoint(x: 13.24, y: 15.92))
phonehighlightedPath.addCurve(to: CGPoint(x: 16.81, y: 13.8), controlPoint1: CGPoint(x: 14.77, y: 15.69), controlPoint2: CGPoint(x: 16.46, y: 14.79))
phonehighlightedPath.addCurve(to: CGPoint(x: 17.05, y: 11.8), controlPoint1: CGPoint(x: 17.16, y: 12.82), controlPoint2: CGPoint(x: 17.16, y: 11.98))
phonehighlightedPath.addCurve(to: CGPoint(x: 16.25, y: 11.31), controlPoint1: CGPoint(x: 16.95, y: 11.63), controlPoint2: CGPoint(x: 16.67, y: 11.52))
phonehighlightedPath.addCurve(to: CGPoint(x: 13.37, y: 9.94), controlPoint1: CGPoint(x: 15.82, y: 11.1), controlPoint2: CGPoint(x: 13.75, y: 10.08))
phonehighlightedPath.close()
phonehighlightedPath.usesEvenOddFillRule = true
fillColor9.setFill()
phonehighlightedPath.fill()
context.restoreGState()
}
@objc public dynamic class func drawLinkedInIcon() {
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.move(to: CGPoint(x: 0.22, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 4.25, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 4.25, y: 5.73))
bezierPath.addLine(to: CGPoint(x: 0.22, y: 5.73))
bezierPath.addLine(to: CGPoint(x: 0.22, y: 17.15))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 2.24, y: 4.03))
bezierPath.addCurve(to: CGPoint(x: 0, y: 2.02), controlPoint1: CGPoint(x: 1, y: 4.03), controlPoint2: CGPoint(x: 0, y: 3.13))
bezierPath.addCurve(to: CGPoint(x: 2.24, y: 0), controlPoint1: CGPoint(x: 0, y: 0.9), controlPoint2: CGPoint(x: 1, y: 0))
bezierPath.addCurve(to: CGPoint(x: 4.49, y: 2.02), controlPoint1: CGPoint(x: 3.48, y: 0), controlPoint2: CGPoint(x: 4.49, y: 0.9))
bezierPath.addCurve(to: CGPoint(x: 2.24, y: 4.03), controlPoint1: CGPoint(x: 4.49, y: 3.13), controlPoint2: CGPoint(x: 3.48, y: 4.03))
bezierPath.addLine(to: CGPoint(x: 2.24, y: 4.03))
bezierPath.close()
bezierPath.move(to: CGPoint(x: 13.99, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 13.99, y: 10.91))
bezierPath.addCurve(to: CGPoint(x: 12.12, y: 8.35), controlPoint1: CGPoint(x: 13.99, y: 9.63), controlPoint2: CGPoint(x: 13.62, y: 8.35))
bezierPath.addCurve(to: CGPoint(x: 9.98, y: 10.94), controlPoint1: CGPoint(x: 10.61, y: 8.35), controlPoint2: CGPoint(x: 9.98, y: 9.63))
bezierPath.addLine(to: CGPoint(x: 9.98, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 5.96, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 5.96, y: 5.73))
bezierPath.addLine(to: CGPoint(x: 9.98, y: 5.73))
bezierPath.addLine(to: CGPoint(x: 9.98, y: 7.26))
bezierPath.addCurve(to: CGPoint(x: 13.62, y: 5.37), controlPoint1: CGPoint(x: 11.04, y: 5.92), controlPoint2: CGPoint(x: 11.96, y: 5.37))
bezierPath.addCurve(to: CGPoint(x: 18, y: 10.66), controlPoint1: CGPoint(x: 15.29, y: 5.37), controlPoint2: CGPoint(x: 18, y: 6.14))
bezierPath.addLine(to: CGPoint(x: 18, y: 17.15))
bezierPath.addLine(to: CGPoint(x: 13.99, y: 17.15))
bezierPath.close()
bezierPath.usesEvenOddFillRule = true
fillColor9.setFill()
bezierPath.fill()
}
@objc public dynamic class func drawHomeIcon(frame targetFrame: CGRect = CGRect(x: 0, y: 0, width: 22, height: 21), resizing: ResizingBehavior = .aspectFit) {
//// General Declarations
let context = UIGraphicsGetCurrentContext()!
//// Resize to Target Frame
context.saveGState()
let resizedFrame: CGRect = resizing.apply(rect: CGRect(x: 0, y: 0, width: 22, height: 21), target: targetFrame)
context.translateBy(x: resizedFrame.minX, y: resizedFrame.minY)
context.scaleBy(x: resizedFrame.width / 22, y: resizedFrame.height / 21)
//// Color Declarations
let fillColor9 = UIColor(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
//// Bezier 2 Drawing
let bezier2Path = UIBezierPath()
bezier2Path.move(to: CGPoint(x: 10.61, y: 0))
bezier2Path.addCurve(to: CGPoint(x: 21.21, y: 7.5), controlPoint1: CGPoint(x: 10.61, y: -0), controlPoint2: CGPoint(x: 21.21, y: 7.5))
bezier2Path.addCurve(to: CGPoint(x: 19.61, y: 8.63), controlPoint1: CGPoint(x: 21.21, y: 7.5), controlPoint2: CGPoint(x: 20.57, y: 7.95))
bezier2Path.addCurve(to: CGPoint(x: 18.61, y: 7.93), controlPoint1: CGPoint(x: 19.3, y: 8.42), controlPoint2: CGPoint(x: 18.97, y: 8.18))
bezier2Path.addCurve(to: CGPoint(x: 18.61, y: 20.37), controlPoint1: CGPoint(x: 18.61, y: 11.57), controlPoint2: CGPoint(x: 18.61, y: 20.37))
bezier2Path.addLine(to: CGPoint(x: 2.61, y: 20.37))
bezier2Path.addCurve(to: CGPoint(x: 2.61, y: 7.93), controlPoint1: CGPoint(x: 2.61, y: 20.37), controlPoint2: CGPoint(x: 2.61, y: 11.58))
bezier2Path.addCurve(to: CGPoint(x: 1.61, y: 8.63), controlPoint1: CGPoint(x: 2.25, y: 8.18), controlPoint2: CGPoint(x: 1.91, y: 8.42))
bezier2Path.addCurve(to: CGPoint(x: 0, y: 7.5), controlPoint1: CGPoint(x: 0.64, y: 7.95), controlPoint2: CGPoint(x: 0, y: 7.5))
bezier2Path.addCurve(to: CGPoint(x: 5.89, y: 3.33), controlPoint1: CGPoint(x: 0, y: 7.5), controlPoint2: CGPoint(x: 3.06, y: 5.33))
bezier2Path.addCurve(to: CGPoint(x: 9.04, y: 1.11), controlPoint1: CGPoint(x: 7.06, y: 2.51), controlPoint2: CGPoint(x: 8.18, y: 1.71))
bezier2Path.addCurve(to: CGPoint(x: 10.6, y: 0), controlPoint1: CGPoint(x: 9.95, y: 0.47), controlPoint2: CGPoint(x: 10.56, y: 0.03))
bezier2Path.addLine(to: CGPoint(x: 10.61, y: 0))
bezier2Path.close()
bezier2Path.move(to: CGPoint(x: 10.61, y: 2.27))
bezier2Path.addCurve(to: CGPoint(x: 5.89, y: 5.6), controlPoint1: CGPoint(x: 10.53, y: 2.32), controlPoint2: CGPoint(x: 8.29, y: 3.91))
bezier2Path.addCurve(to: CGPoint(x: 4.61, y: 6.51), controlPoint1: CGPoint(x: 5.47, y: 5.91), controlPoint2: CGPoint(x: 5.03, y: 6.21))
bezier2Path.addCurve(to: CGPoint(x: 4.61, y: 18.37), controlPoint1: CGPoint(x: 4.61, y: 10.44), controlPoint2: CGPoint(x: 4.61, y: 18.37))
bezier2Path.addLine(to: CGPoint(x: 10.38, y: 18.37))
bezier2Path.addLine(to: CGPoint(x: 10.38, y: 12.37))
bezier2Path.addLine(to: CGPoint(x: 14.61, y: 12.37))
bezier2Path.addLine(to: CGPoint(x: 14.61, y: 18.37))
bezier2Path.addLine(to: CGPoint(x: 16.61, y: 18.37))
bezier2Path.addCurve(to: CGPoint(x: 16.61, y: 6.51), controlPoint1: CGPoint(x: 16.61, y: 18.37), controlPoint2: CGPoint(x: 16.61, y: 10.44))
bezier2Path.addCurve(to: CGPoint(x: 12.36, y: 3.51), controlPoint1: CGPoint(x: 15.1, y: 5.45), controlPoint2: CGPoint(x: 13.52, y: 4.33))
bezier2Path.addCurve(to: CGPoint(x: 10.61, y: 2.27), controlPoint1: CGPoint(x: 11.31, y: 2.77), controlPoint2: CGPoint(x: 10.61, y: 2.27))
bezier2Path.close()
fillColor9.setFill()
bezier2Path.fill()
context.restoreGState()
}
//// Generated Images
@objc public dynamic class var imageOfWhatsAppIcon: UIImage {
if Cache.imageOfWhatsAppIcon != nil {
return Cache.imageOfWhatsAppIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
StyleKit.drawWhatsAppIcon()
Cache.imageOfWhatsAppIcon = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return Cache.imageOfWhatsAppIcon!
}
@objc public dynamic class var imageOfEMailIcon: UIImage {
if Cache.imageOfEMailIcon != nil {
return Cache.imageOfEMailIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 15), false, 0)
StyleKit.drawEMailIcon()
Cache.imageOfEMailIcon = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return Cache.imageOfEMailIcon!
}
@objc public dynamic class var imageOfFacebookIcon: UIImage {
if Cache.imageOfFacebookIcon != nil {
return Cache.imageOfFacebookIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 20), false, 0)
StyleKit.drawFacebookIcon()
Cache.imageOfFacebookIcon = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return Cache.imageOfFacebookIcon!
}
@objc public dynamic class var imageOfTwitterIcon: UIImage {
if Cache.imageOfTwitterIcon != nil {
return Cache.imageOfTwitterIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 20, height: 16), false, 0)
StyleKit.drawTwitterIcon()
Cache.imageOfTwitterIcon = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return Cache.imageOfTwitterIcon!
}
@objc public dynamic class var imageOfCallIcon: UIImage {
if Cache.imageOfCallIcon != nil {
return Cache.imageOfCallIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 18, height: 16), false, 0)
StyleKit.drawCallIcon()
Cache.imageOfCallIcon = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return Cache.imageOfCallIcon!
}
@objc public dynamic class var imageOfLinkedInIcon: UIImage {
if Cache.imageOfLinkedInIcon != nil {
return Cache.imageOfLinkedInIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 18, height: 17), false, 0)
StyleKit.drawLinkedInIcon()
Cache.imageOfLinkedInIcon = UIGraphicsGetImageFromCurrentImageContext()!.resizableImage(withCapInsets: UIEdgeInsets.zero, resizingMode: .tile)
UIGraphicsEndImageContext()
return Cache.imageOfLinkedInIcon!
}
@objc public dynamic class var imageOfHomeIcon: UIImage {
if Cache.imageOfHomeIcon != nil {
return Cache.imageOfHomeIcon!
}
UIGraphicsBeginImageContextWithOptions(CGSize(width: 22, height: 21), false, 0)
StyleKit.drawHomeIcon()
Cache.imageOfHomeIcon = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return Cache.imageOfHomeIcon!
}
//// Customization Infrastructure
@IBOutlet dynamic var whatsAppIconTargets: [AnyObject]! {
get { return Cache.whatsAppIconTargets }
set {
Cache.whatsAppIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfWhatsAppIcon)
}
}
}
@IBOutlet dynamic var eMailIconTargets: [AnyObject]! {
get { return Cache.eMailIconTargets }
set {
Cache.eMailIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfEMailIcon)
}
}
}
@IBOutlet dynamic var facebookIconTargets: [AnyObject]! {
get { return Cache.facebookIconTargets }
set {
Cache.facebookIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfFacebookIcon)
}
}
}
@IBOutlet dynamic var twitterIconTargets: [AnyObject]! {
get { return Cache.twitterIconTargets }
set {
Cache.twitterIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfTwitterIcon)
}
}
}
@IBOutlet dynamic var callIconTargets: [AnyObject]! {
get { return Cache.callIconTargets }
set {
Cache.callIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfCallIcon)
}
}
}
@IBOutlet dynamic var linkedInIconTargets: [AnyObject]! {
get { return Cache.linkedInIconTargets }
set {
Cache.linkedInIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfLinkedInIcon)
}
}
}
@IBOutlet dynamic var homeIconTargets: [AnyObject]! {
get { return Cache.homeIconTargets }
set {
Cache.homeIconTargets = newValue
for target: AnyObject in newValue {
let _ = target.perform(NSSelectorFromString("setImage:"), with: StyleKit.imageOfHomeIcon)
}
}
}
@objc(StyleKitResizingBehavior)
public enum ResizingBehavior: Int {
case aspectFit /// The content is proportionally resized to fit into the target rectangle.
case aspectFill /// The content is proportionally resized to completely fill the target rectangle.
case stretch /// The content is stretched to match the entire target rectangle.
case center /// The content is centered in the target rectangle, but it is NOT resized.
public func apply(rect: CGRect, target: CGRect) -> CGRect {
if rect == target || target == CGRect.zero {
return rect
}
var scales = CGSize.zero
scales.width = abs(target.width / rect.width)
scales.height = abs(target.height / rect.height)
switch self {
case .aspectFit:
scales.width = min(scales.width, scales.height)
scales.height = scales.width
case .aspectFill:
scales.width = max(scales.width, scales.height)
scales.height = scales.width
case .stretch:
break
case .center:
scales.width = 1
scales.height = 1
}
var result = rect.standardized
result.size.width *= scales.width
result.size.height *= scales.height
result.origin.x = target.minX + (target.width - result.width) / 2
result.origin.y = target.minY + (target.height - result.height) / 2
return result
}
}
}
| mit | bbc6f1b9eafb44964980d3836c7d61c1 | 61.91222 | 162 | 0.631949 | 3.247623 | false | false | false | false |
aschwaighofer/swift | test/Sema/enum_raw_representable.swift | 2 | 10065 | // RUN: %target-typecheck-verify-swift
enum Foo : Int {
case a, b, c
}
var raw1: Int = Foo.a.rawValue
var raw2: Foo.RawValue = raw1
var cooked1: Foo? = Foo(rawValue: 0)
var cooked2: Foo? = Foo(rawValue: 22)
enum Bar : Double {
case a, b, c
}
func localEnum() -> Int {
enum LocalEnum : Int {
case a, b, c
}
return LocalEnum.a.rawValue
}
enum MembersReferenceRawType : Int {
case a, b, c
init?(rawValue: Int) {
self = MembersReferenceRawType(rawValue: rawValue)!
}
func successor() -> MembersReferenceRawType {
return MembersReferenceRawType(rawValue: rawValue + 1)!
}
}
func serialize<T : RawRepresentable>(_ values: [T]) -> [T.RawValue] {
return values.map { $0.rawValue }
}
func deserialize<T : RawRepresentable>(_ serialized: [T.RawValue]) -> [T] {
return serialized.map { T(rawValue: $0)! }
}
var ints: [Int] = serialize([Foo.a, .b, .c])
var doubles: [Double] = serialize([Bar.a, .b, .c])
var foos: [Foo] = deserialize([1, 2, 3])
var bars: [Bar] = deserialize([1.2, 3.4, 5.6])
// Infer RawValue from witnesses.
enum Color : Int {
case red
case blue
init?(rawValue: Double) {
return nil
}
var rawValue: Double {
return 1.0
}
}
var colorRaw: Color.RawValue = 7.5
// Mismatched case types
enum BadPlain : UInt { // expected-error {{'BadPlain' declares raw type 'UInt', but does not conform to RawRepresentable and conformance could not be synthesized}}
case a = "hello" // expected-error {{cannot convert value of type 'String' to raw type 'UInt'}}
}
// Recursive diagnostics issue in tryRawRepresentableFixIts()
class Outer {
// The setup is that we have to trigger the conformance check
// while diagnosing the conversion here. For the purposes of
// the test I'm putting everything inside a class in the right
// order, but the problem can trigger with a multi-file
// scenario too.
let a: Int = E.a // expected-error {{cannot convert value of type 'Outer.E' to specified type 'Int'}}
enum E : Array<Int> {
// expected-error@-1 {{raw type 'Array<Int>' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-2 {{'Outer.E' declares raw type 'Array<Int>', but does not conform to RawRepresentable and conformance could not be synthesized}}
case a
}
}
// rdar://problem/32431736 - Conversion fix-it from String to String raw value enum can't look through optionals
func rdar32431736() {
enum E : String {
case A = "A"
case B = "B"
}
let items1: [String] = ["A", "a"]
let items2: [String]? = ["A"]
let myE1: E = items1.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: }} {{29-29=!)}}
let myE2: E = items2?.first
// expected-error@-1 {{cannot convert value of type 'String?' to specified type 'E'}}
// expected-note@-2 {{construct 'E' from unwrapped 'String' value}} {{17-17=E(rawValue: (}} {{30-30=)!)}}
}
// rdar://problem/32431165 - improve diagnostic for raw representable argument mismatch
enum E_32431165 : String {
case foo = "foo"
case bar = "bar" // expected-note {{'bar' declared here}}
}
func rdar32431165_1(_: E_32431165) {}
func rdar32431165_1(_: Int) {}
func rdar32431165_1(_: Int, _: E_32431165) {}
rdar32431165_1(E_32431165.baz)
// expected-error@-1 {{type 'E_32431165' has no member 'baz'; did you mean 'bar'?}}
rdar32431165_1(.baz)
// expected-error@-1 {{reference to member 'baz' cannot be resolved without a contextual type}}
rdar32431165_1("")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{16-16=E_32431165(rawValue: }} {{18-18=)}}
rdar32431165_1(42, "")
// expected-error@-1 {{cannot convert value of type 'String' to expected argument type 'E_32431165'}} {{20-20=E_32431165(rawValue: }} {{22-22=)}}
func rdar32431165_2(_: String) {}
func rdar32431165_2(_: Int) {}
func rdar32431165_2(_: Int, _: String) {}
rdar32431165_2(E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{16-16=}} {{30-30=.rawValue}}
rdar32431165_2(42, E_32431165.bar)
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{20-20=}} {{34-34=.rawValue}}
E_32431165.bar == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{1-1=}} {{15-15=.rawValue}}
"bar" == E_32431165.bar
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String}} {{10-10=}} {{24-24=.rawValue}}
func rdar32432253(_ condition: Bool = false) {
let choice: E_32431165 = condition ? .foo : .bar
let _ = choice == "bar"
// expected-error@-1 {{cannot convert value of type 'E_32431165' to expected argument type 'String'}} {{11-11=}} {{17-17=.rawValue}}
}
func sr8150_helper1(_: Int) {}
func sr8150_helper1(_: Double) {}
func sr8150_helper2(_: Double) {}
func sr8150_helper2(_: Int) {}
func sr8150_helper3(_: Foo) {}
func sr8150_helper3(_: Bar) {}
func sr8150_helper4(_: Bar) {}
func sr8150_helper4(_: Foo) {}
func sr8150(bar: Bar) {
sr8150_helper1(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
sr8150_helper2(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
sr8150_helper3(0.0)
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
sr8150_helper4(0.0)
// expected-error@-1 {{cannot convert value of type 'Double' to expected argument type 'Bar'}} {{18-18=Bar(rawValue: }} {{21-21=)}}
}
class SR8150Box {
var bar: Bar
init(bar: Bar) { self.bar = bar }
}
// Bonus problem with mutable values being passed.
func sr8150_mutable(obj: SR8150Box) {
sr8150_helper1(obj.bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{25-25=.rawValue}}
var bar = obj.bar
sr8150_helper1(bar)
// expected-error@-1 {{cannot convert value of type 'Bar' to expected argument type 'Double'}} {{18-18=}} {{21-21=.rawValue}}
}
struct NotEquatable { }
enum ArrayOfNewEquatable : Array<NotEquatable> { }
// expected-error@-1{{raw type 'Array<NotEquatable>' is not expressible by a string, integer, or floating-point literal}}
// expected-error@-2{{'ArrayOfNewEquatable' declares raw type 'Array<NotEquatable>', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-3{{RawRepresentable conformance cannot be synthesized because raw type 'Array<NotEquatable>' is not Equatable}}
// expected-error@-4{{an enum with no cases cannot declare a raw type}}
// rdar://58127114
struct NotEquatableInteger : ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
init(integerLiteral: Int) {}
}
enum NotEquatableRawType1 : NotEquatableInteger {
// expected-error@-1 {{'NotEquatableRawType1' declares raw type 'NotEquatableInteger', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'NotEquatableInteger' is not Equatable}}
case a = 123
}
enum NotEquatableRawType2 : NotEquatableInteger {
// expected-error@-1 {{'NotEquatableRawType2' declares raw type 'NotEquatableInteger', but does not conform to RawRepresentable and conformance could not be synthesized}}
// expected-error@-2 {{RawRepresentable conformance cannot be synthesized because raw type 'NotEquatableInteger' is not Equatable}}
typealias RawValue = NotEquatableInteger
case a = 123
}
struct NotEquatableString : ExpressibleByStringLiteral {
init(stringLiteral: String) {}
}
// FIXME: This could be diagnosed a bit better. The notes are disembodied
enum NotEquatableRawType3: NotEquatableString {
// expected-error@-1 {{RawRepresentable conformance cannot be synthesized because raw type 'NotEquatableString' is not Equatable}}
// expected-error@-2 {{'NotEquatableRawType3' declares raw type 'NotEquatableString', but does not conform to RawRepresentable and conformance could not be synthesized}}
case a
typealias RawValue = NotEquatableString
init?(rawValue: Int) { self = .a }
// expected-note@-1 {{candidate has non-matching type '(rawValue: Int)'}}
var rawValue: Int { 0 }
// expected-note@-1 {{candidate has non-matching type 'Int'}}
}
enum MismatchedRawValues {
enum ExistentialBound: Any? {
// expected-error@-1 {{raw type 'Any?' is not expressible}}
// expected-error@-2 {{'MismatchedRawValues.ExistentialBound' declares raw type 'Any?'}}
// expected-error@-3 {{RawRepresentable conformance cannot be synthesized }}
case test = nil
}
public enum StringViaStaticString: StaticString {
// expected-error@-1 {{'MismatchedRawValues.StringViaStaticString' declares raw type 'StaticString', but does not conform to RawRepresentable}}
// expected-error@-2 {{RawRepresentable conformance cannot be synthesized because}}
public typealias RawValue = String
case TRUE = "TRUE"
case FALSE = "FALSE"
}
public enum IntViaString: String {
// expected-error@-1 {{'MismatchedRawValues.IntViaString' declares raw type 'String', but does not conform to RawRepresentable}}
public typealias RawValue = Int
case TRUE = "TRUE"
case FALSE = "FALSE"
}
public enum ViaNested: String {
// expected-error@-1 {{'MismatchedRawValues.ViaNested' declares raw type 'String', but does not conform to RawRepresentable}}
struct RawValue: Equatable {
let x: String
}
case TRUE = "TRUE"
case FALSE = "FALSE"
}
public enum ViaGenericBound<RawValue: Equatable>: String {
// expected-error@-1 {{'MismatchedRawValues.ViaGenericBound<RawValue>' declares raw type 'String'}}
typealias RawValue = RawValue
case TRUE = "TRUE"
case FALSE = "FALSE"
}
}
| apache-2.0 | c7ec6184ad012e477796fdb2dccfcbff | 35.6 | 170 | 0.696672 | 3.754196 | false | false | false | false |
JGiola/swift | test/SILGen/class_bound_protocols.swift | 1 | 12645 |
// RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
enum Optional<T> {
case some(T)
case none
}
precedencegroup AssignmentPrecedence {}
typealias AnyObject = Builtin.AnyObject
// -- Class-bound archetypes and existentials are *not* address-only and can
// be manipulated using normal reference type value semantics.
protocol NotClassBound {
func notClassBoundMethod()
}
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBound2Method()
}
class ConcreteClass : NotClassBound, ClassBound, ClassBound2 {
func notClassBoundMethod() {}
func classBoundMethod() {}
func classBound2Method() {}
}
class ConcreteSubclass : ConcreteClass { }
// CHECK-LABEL: sil hidden [ossa] @$ss19class_bound_generic{{[_0-9a-zA-Z]*}}F
func class_bound_generic<T : ClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T>
// CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X_ADDR]]
// CHECK: [[PB:%.*]] = project_box [[X_LIFETIME]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: end_borrow [[X_LIFETIME]]
// CHECK: destroy_value [[X_ADDR]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden [ossa] @$ss21class_bound_generic_2{{[_0-9a-zA-Z]*}}F
func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T>
// CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X_ADDR]]
// CHECK: [[PB:%.*]] = project_box [[X_LIFETIME]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden [ossa] @$ss20class_bound_protocol{{[_0-9a-zA-Z]*}}F
func class_bound_protocol(x: ClassBound) -> ClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $ClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound }
// CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X_ADDR]]
// CHECK: [[PB:%.*]] = project_box [[X_LIFETIME]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden [ossa] @$ss32class_bound_protocol_composition{{[_0-9a-zA-Z]*}}F
func class_bound_protocol_composition(x: ClassBound & NotClassBound)
-> ClassBound & NotClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : @guaranteed $ClassBound & NotClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound }
// CHECK: [[X_LIFETIME:%[^,]+]] = begin_borrow [lexical] [[X_ADDR]]
// CHECK: [[PB:%.*]] = project_box [[X_LIFETIME]]
// CHECK: [[X_COPY:%.*]] = copy_value [[X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*ClassBound & NotClassBound
// CHECK: [[X1:%.*]] = load [copy] [[READ]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden [ossa] @$ss19class_bound_erasure{{[_0-9a-zA-Z]*}}F
func class_bound_erasure(x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound
// CHECK: return [[PROTO]]
}
// CHECK-LABEL: sil hidden [ossa] @$ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF :
func class_bound_existential_upcast(x: ClassBound & ClassBound2)
-> ClassBound {
return x
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassBound & ClassBound2):
// CHECK: [[OPENED:%.*]] = open_existential_ref [[ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened\(.*, ClassBound & ClassBound2\) Self]]
// CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]]
// CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound
// CHECK: return [[PROTO]]
}
// CHECK: } // end sil function '$ss30class_bound_existential_upcast1xs10ClassBound_psAC_s0E6Bound2p_tF'
// CHECK-LABEL: sil hidden [ossa] @$ss41class_bound_to_unbound_existential_upcast1xs13NotClassBound_ps0hI0_sACp_tF :
// CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : @guaranteed $ClassBound & NotClassBound):
// CHECK: [[X_OPENED:%.*]] = open_existential_ref [[ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened\(.*, ClassBound & NotClassBound\) Self]]
// CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]]
// CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]]
// CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]]
func class_bound_to_unbound_existential_upcast
(x: ClassBound & NotClassBound) -> NotClassBound {
return x
}
// CHECK-LABEL: sil hidden [ossa] @$ss18class_bound_method1xys10ClassBound_p_tF :
// CHECK: bb0([[ARG:%.*]] : @guaranteed $ClassBound):
func class_bound_method(x: ClassBound) {
var x = x
x.classBoundMethod()
// CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x"
// CHECK: [[XLIFETIME:%[^,]+]] = begin_borrow [lexical] [[XBOX]]
// CHECK: [[XBOX_PB:%.*]] = project_box [[XLIFETIME]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[XBOX_PB]] : $*ClassBound
// CHECK: [[X:%.*]] = load [copy] [[READ]] : $*ClassBound
// CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened\(.*, ClassBound\) Self]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod :
// CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]])
// CHECK: destroy_value [[PROJ]]
// CHECK: end_borrow [[XLIFETIME]]
// CHECK: destroy_value [[XBOX]]
}
// CHECK: } // end sil function '$ss18class_bound_method1xys10ClassBound_p_tF'
// rdar://problem/31858378
struct Value {}
protocol HasMutatingMethod {
mutating func mutateMe()
var mutatingCounter: Value { get set }
var nonMutatingCounter: Value { get nonmutating set }
}
protocol InheritsMutatingMethod : class, HasMutatingMethod {}
func takesInOut<T>(_: inout T) {}
// CHECK-LABEL: sil hidden [ossa] @$ss27takesInheritsMutatingMethod1x1yys0bcD0_pz_s5ValueVtF : $@convention(thin) (@inout InheritsMutatingMethod, Value) -> () {
func takesInheritsMutatingMethod(x: inout InheritsMutatingMethod,
y: Value) {
// CHECK: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", InheritsMutatingMethod) Self, #HasMutatingMethod.mutateMe : <Self where Self : HasMutatingMethod> (inout Self) -> () -> (), [[X_PAYLOAD]] : $@opened("{{.*}}", InheritsMutatingMethod) Self : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> ()
// CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}", InheritsMutatingMethod) Self>([[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@inout τ_0_0) -> ()
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}", InheritsMutatingMethod) Self : $@opened("{{.*}}", InheritsMutatingMethod) Self, $InheritsMutatingMethod
// CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
x.mutateMe()
// CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [read] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[X_PAYLOAD_RELOADED:%.*]] = load_borrow [[TEMPORARY]]
//
// ** *NOTE* This extra copy is here since RValue invariants enforce that all
// ** loadable objects are actually loaded. So we form the RValue and
// ** load... only to then need to store the value back in a stack location to
// ** pass to an in_guaranteed method. PredictableMemOpts is able to handle this
// ** type of temporary codegen successfully.
// CHECK-NEXT: [[TEMPORARY_2:%.*]] = alloc_stack $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: store_borrow [[X_PAYLOAD_RELOADED:%.*]] to [[TEMPORARY_2]]
//
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", InheritsMutatingMethod) Self, #HasMutatingMethod.mutatingCounter!getter : <Self where Self : HasMutatingMethod> (Self) -> () -> Value, [[X_PAYLOAD]] : $@opened("{{.*}}", InheritsMutatingMethod) Self : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value
// CHECK-NEXT: [[RESULT_VALUE:%.*]] = apply [[METHOD]]<@opened("{{.*}}", InheritsMutatingMethod) Self>([[TEMPORARY_2]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (@in_guaranteed τ_0_0) -> Value
// CHECK-NEXT: dealloc_stack [[TEMPORARY_2]]
// CHECK-NEXT: end_borrow
// CHECK-NEXT: destroy_addr
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
_ = x.mutatingCounter
// CHECK-NEXT: [[X_ADDR:%.*]] = begin_access [modify] [unknown] %0 : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_VALUE:%.*]] = load [copy] [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = open_existential_ref [[X_VALUE]] : $InheritsMutatingMethod to $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[TEMPORARY:%.*]] = alloc_stack $@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: store [[X_PAYLOAD]] to [init] [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[METHOD:%.*]] = witness_method $@opened("{{.*}}", InheritsMutatingMethod) Self, #HasMutatingMethod.mutatingCounter!setter : <Self where Self : HasMutatingMethod> (inout Self) -> (Value) -> (), [[X_PAYLOAD]] : $@opened("{{.*}}", InheritsMutatingMethod) Self : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> ()
// CHECK-NEXT: apply [[METHOD]]<@opened("{{.*}}", InheritsMutatingMethod) Self>(%1, [[TEMPORARY]]) : $@convention(witness_method: HasMutatingMethod) <τ_0_0 where τ_0_0 : HasMutatingMethod> (Value, @inout τ_0_0) -> ()
// CHECK-NEXT: [[X_PAYLOAD:%.*]] = load [take] [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
// CHECK-NEXT: [[X_VALUE:%.*]] = init_existential_ref [[X_PAYLOAD]] : $@opened("{{.*}}", InheritsMutatingMethod) Self : $@opened("{{.*}}", InheritsMutatingMethod) Self, $InheritsMutatingMethod
// CHECK-NEXT: assign [[X_VALUE]] to [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: end_access [[X_ADDR]] : $*InheritsMutatingMethod
// CHECK-NEXT: dealloc_stack [[TEMPORARY]] : $*@opened("{{.*}}", InheritsMutatingMethod) Self
x.mutatingCounter = y
takesInOut(&x.mutatingCounter)
_ = x.nonMutatingCounter
x.nonMutatingCounter = y
takesInOut(&x.nonMutatingCounter)
}
| apache-2.0 | 2457542f04aead712ee6756d88b701aa | 55.846847 | 392 | 0.628051 | 3.655852 | false | false | false | false |
vhesener/Closures | Xcode/Playground/ClosuresDemo.playground/Pages/UICollectionView.xcplaygroundpage/Contents.swift | 1 | 2847 | import UIKit;import PlaygroundSupport;PlaygroundPage.current.liveView = viewController
import Closures
//: [Go back](@previous)
/*:
# UICollectionView
## Delegate and DataSource
`UICollectionView` closures make it easy to implement `UICollectionViewDelegate` and
`UICollectionViewDataSource` protocol methods in an organized way. The following
is an example of a simple collection view that displays strings in a basic cell.
*/
let collectionView = viewController.collectionView!
let countries = getAllCountries()
func loadCollectionView() {
collectionView.register(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView
.numberOfItemsInSection { _ in
countries.count
}.cellForItemAt { indexPath in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCustomCollectionViewCell
cell.textLabel.text = countries[indexPath.item]
return cell
}.didSelectItemAt {
print("\(countries[$0.item]) selected")
}.reloadData()
}
loadCollectionView()
/*:
## Arrays
These operations are common. Usually, they involve populating the `UICollectionView`
with the values from an array. `Closures` framework gives you a convenient
way to pass your array to the collection view, so that it can perform the boilerplate
operations for you, especially the ones that are required to make the collection
view perform at a basic level.
*/
/*:
Let's setup our segmented control to load the collection view with different options.
When binding to an Array it will show the same countries, but reversed, so
you can visually see the change after tapping the segmented control.
*/
let segmentedControl = viewController.segmentedControl!
segmentedControl.onChange {
switch $0 {
case 1:
loadCollectionView(countries: Array(countries.reversed()))
default:
loadCollectionView()
}
}
/*:
* Important:
Please remember that Swift `Array`s are value types. This means that they
are copied when mutated. When the values or sequence of your array changes, you will
need to call `addFlowElements` again, just before you call reloadData().
*/
func loadCollectionView(countries: [String]) {
collectionView
.addFlowElements(countries, cell: MyCustomCollectionViewCell.self) { country, cell, index in
cell.textLabel.text = country
}.reloadData()
/**
This also allows you to override any default behavior so
you aren't overly committed, even though you're initially binding everything
to the `Array`.
*/
collectionView.didSelectItemAt {
print("\(countries[$0.item]) selected from array")
}
}
//: * * * *
//: [Click here to explore using **UIGestureRecognizer** closures](@next)
//: * * * *
| mit | 3b9cbce3a55fc242d257b13511408932 | 36.96 | 133 | 0.723217 | 5.030035 | false | false | false | false |
Bunn/firefox-ios | Client/Frontend/Library/ReaderPanel.swift | 1 | 20094 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
private struct ReadingListTableViewCellUX {
static let RowHeight: CGFloat = 86
static let ReadIndicatorWidth: CGFloat = 12 // image width
static let ReadIndicatorHeight: CGFloat = 12 // image height
static let ReadIndicatorLeftOffset: CGFloat = 18
static let ReadAccessibilitySpeechPitch: Float = 0.7 // 1.0 default, 0.0 lowest, 2.0 highest
static let TitleLabelTopOffset: CGFloat = 14 - 4
static let TitleLabelLeftOffset: CGFloat = 16 + 16 + 16
static let TitleLabelRightOffset: CGFloat = -40
static let HostnameLabelBottomOffset: CGFloat = 11
static let DeleteButtonTitleColor = UIColor.Photon.White100
static let DeleteButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
static let MarkAsReadButtonBackgroundColor = UIColor.Photon.Blue50
static let MarkAsReadButtonTitleColor = UIColor.Photon.White100
static let MarkAsReadButtonTitleEdgeInsets = UIEdgeInsets(top: 4, left: 4, bottom: 4, right: 4)
// Localizable strings
static let DeleteButtonTitleText = NSLocalizedString("Remove", comment: "Title for the button that removes a reading list item")
static let MarkAsReadButtonTitleText = NSLocalizedString("Mark as Read", comment: "Title for the button that marks a reading list item as read")
static let MarkAsUnreadButtonTitleText = NSLocalizedString("Mark as Unread", comment: "Title for the button that marks a reading list item as unread")
}
private struct ReadingListPanelUX {
// Welcome Screen
static let WelcomeScreenTopPadding: CGFloat = 16
static let WelcomeScreenPadding: CGFloat = 15
static let WelcomeScreenItemWidth = 220
static let WelcomeScreenItemOffset = -20
static let WelcomeScreenCircleWidth = 40
static let WelcomeScreenCircleOffset = 20
static let WelcomeScreenCircleSpacer = 10
}
class ReadingListTableViewCell: UITableViewCell, Themeable {
var title: String = "Example" {
didSet {
titleLabel.text = title
updateAccessibilityLabel()
}
}
var url = URL(string: "http://www.example.com")! {
didSet {
hostnameLabel.text = simplifiedHostnameFromURL(url)
updateAccessibilityLabel()
}
}
var unread: Bool = true {
didSet {
readStatusImageView.image = UIImage(named: unread ? "MarkAsRead" : "MarkAsUnread")
titleLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed
hostnameLabel.textColor = unread ? UIColor.theme.homePanel.readingListActive : UIColor.theme.homePanel.readingListDimmed
updateAccessibilityLabel()
}
}
let readStatusImageView: UIImageView!
let titleLabel: UILabel!
let hostnameLabel: UILabel!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
readStatusImageView = UIImageView()
titleLabel = UILabel()
hostnameLabel = UILabel()
super.init(style: style, reuseIdentifier: reuseIdentifier)
backgroundColor = UIColor.clear
separatorInset = UIEdgeInsets(top: 0, left: 48, bottom: 0, right: 0)
layoutMargins = .zero
preservesSuperviewLayoutMargins = false
contentView.addSubview(readStatusImageView)
readStatusImageView.contentMode = .scaleAspectFit
readStatusImageView.snp.makeConstraints { (make) -> Void in
make.width.equalTo(ReadingListTableViewCellUX.ReadIndicatorWidth)
make.height.equalTo(ReadingListTableViewCellUX.ReadIndicatorHeight)
make.centerY.equalTo(self.contentView)
make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.ReadIndicatorLeftOffset)
}
contentView.addSubview(titleLabel)
contentView.addSubview(hostnameLabel)
titleLabel.numberOfLines = 2
titleLabel.snp.makeConstraints { (make) -> Void in
make.top.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelTopOffset)
make.leading.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelLeftOffset)
make.trailing.equalTo(self.contentView).offset(ReadingListTableViewCellUX.TitleLabelRightOffset) // TODO Not clear from ux spec
make.bottom.lessThanOrEqualTo(hostnameLabel.snp.top).priority(1000)
}
hostnameLabel.numberOfLines = 1
hostnameLabel.snp.makeConstraints { (make) -> Void in
make.bottom.equalTo(self.contentView).offset(-ReadingListTableViewCellUX.HostnameLabelBottomOffset)
make.leading.trailing.equalTo(self.titleLabel)
}
applyTheme()
}
func setupDynamicFonts() {
titleLabel.font = DynamicFontHelper.defaultHelper.DeviceFont
hostnameLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
}
func applyTheme() {
titleLabel.textColor = UIColor.theme.homePanel.readingListActive
hostnameLabel.textColor = UIColor.theme.homePanel.readingListActive
}
override func prepareForReuse() {
super.prepareForReuse()
applyTheme()
setupDynamicFonts()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let prefixesToSimplify = ["www.", "mobile.", "m.", "blog."]
fileprivate func simplifiedHostnameFromURL(_ url: URL) -> String {
let hostname = url.host ?? ""
for prefix in prefixesToSimplify {
if hostname.hasPrefix(prefix) {
return String(hostname[hostname.index(hostname.startIndex, offsetBy: prefix.count)...])
}
}
return hostname
}
fileprivate func updateAccessibilityLabel() {
if let hostname = hostnameLabel.text,
let title = titleLabel.text {
let unreadStatus = unread ? NSLocalizedString("unread", comment: "Accessibility label for unread article in reading list. It's a past participle - functions as an adjective.") : NSLocalizedString("read", comment: "Accessibility label for read article in reading list. It's a past participle - functions as an adjective.")
let string = "\(title), \(unreadStatus), \(hostname)"
var label: AnyObject
if !unread {
// mimic light gray visual dimming by "dimming" the speech by reducing pitch
let lowerPitchString = NSMutableAttributedString(string: string as String)
lowerPitchString.addAttribute(NSAttributedString.Key.accessibilitySpeechPitch, value: NSNumber(value: ReadingListTableViewCellUX.ReadAccessibilitySpeechPitch as Float), range: NSRange(location: 0, length: lowerPitchString.length))
label = NSAttributedString(attributedString: lowerPitchString)
} else {
label = string as AnyObject
}
// need to use KVC as accessibilityLabel is of type String! and cannot be set to NSAttributedString other way than this
// see bottom of page 121 of the PDF slides of WWDC 2012 "Accessibility for iOS" session for indication that this is OK by Apple
// also this combined with Swift's strictness is why we cannot simply override accessibilityLabel and return the label directly...
setValue(label, forKey: "accessibilityLabel")
}
}
}
class ReadingListPanel: UITableViewController, LibraryPanel {
weak var libraryPanelDelegate: LibraryPanelDelegate?
let profile: Profile
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(longPress))
}()
fileprivate var records: [ReadingListItem]?
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
[ Notification.Name.FirefoxAccountChanged,
Notification.Name.DynamicFontChanged,
Notification.Name.DatabaseWasReopened ].forEach {
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived), name: $0, object: nil)
}
}
required init!(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Note this will then call applyTheme() on this class, which reloads the tableview.
(navigationController as? ThemedNavigationController)?.applyTheme()
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "ReadingTable"
tableView.estimatedRowHeight = ReadingListTableViewCellUX.RowHeight
tableView.rowHeight = UITableView.automaticDimension
tableView.cellLayoutMarginsFollowReadableWidth = false
tableView.separatorInset = .zero
tableView.layoutMargins = .zero
tableView.register(ReadingListTableViewCell.self, forCellReuseIdentifier: "ReadingListTableViewCell")
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
tableView.dragDelegate = self
}
@objc func notificationReceived(_ notification: Notification) {
switch notification.name {
case .FirefoxAccountChanged, .DynamicFontChanged:
refreshReadingList()
case .DatabaseWasReopened:
if let dbName = notification.object as? String, dbName == "ReadingList.db" {
refreshReadingList()
}
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
func refreshReadingList() {
let prevNumberOfRecords = records?.count
tableView.tableHeaderView = nil
if let newRecords = profile.readingList.getAvailableRecords().value.successValue {
records = newRecords
if records?.count == 0 {
tableView.isScrollEnabled = false
tableView.tableHeaderView = createEmptyStateOverview()
} else {
if prevNumberOfRecords == 0 {
tableView.isScrollEnabled = true
}
}
self.tableView.reloadData()
}
}
fileprivate func createEmptyStateOverview() -> UIView {
let overlayView = UIView(frame: tableView.bounds)
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = NSLocalizedString("Welcome to your Reading List", comment: "See http://mzl.la/1LXbDOL")
welcomeLabel.textAlignment = .center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallBold
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp.makeConstraints { make in
make.centerX.equalToSuperview()
make.top.equalToSuperview().offset(150)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth + ReadingListPanelUX.WelcomeScreenCircleSpacer + ReadingListPanelUX.WelcomeScreenCircleWidth)
}
let readerModeLabel = UILabel()
overlayView.addSubview(readerModeLabel)
readerModeLabel.text = NSLocalizedString("Open articles in Reader View by tapping the book icon when it appears in the title bar.", comment: "See http://mzl.la/1LXbDOL")
readerModeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
readerModeLabel.numberOfLines = 0
readerModeLabel.snp.makeConstraints { make in
make.top.equalTo(welcomeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.leading.equalTo(welcomeLabel.snp.leading)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
}
let readerModeImageView = UIImageView(image: UIImage(named: "ReaderModeCircle"))
overlayView.addSubview(readerModeImageView)
readerModeImageView.snp.makeConstraints { make in
make.centerY.equalTo(readerModeLabel)
make.trailing.equalTo(welcomeLabel.snp.trailing)
}
let readingListLabel = UILabel()
overlayView.addSubview(readingListLabel)
readingListLabel.text = NSLocalizedString("Save pages to your Reading List by tapping the book plus icon in the Reader View controls.", comment: "See http://mzl.la/1LXbDOL")
readingListLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallLight
readingListLabel.numberOfLines = 0
readingListLabel.snp.makeConstraints { make in
make.top.equalTo(readerModeLabel.snp.bottom).offset(ReadingListPanelUX.WelcomeScreenPadding)
make.leading.equalTo(welcomeLabel.snp.leading)
make.width.equalTo(ReadingListPanelUX.WelcomeScreenItemWidth)
}
let readingListImageView = UIImageView(image: UIImage(named: "AddToReadingListCircle"))
overlayView.addSubview(readingListImageView)
readingListImageView.snp.makeConstraints { make in
make.centerY.equalTo(readingListLabel)
make.trailing.equalTo(welcomeLabel.snp.trailing)
}
[welcomeLabel, readerModeLabel, readingListLabel].forEach {
$0.textColor = UIColor.theme.homePanel.welcomeScreenText
}
return overlayView
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == .began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
presentContextMenu(for: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return records?.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReadingListTableViewCell", for: indexPath) as! ReadingListTableViewCell
if let record = records?[indexPath.row] {
cell.title = record.title
cell.url = URL(string: record.url)!
cell.unread = record.unread
}
return cell
}
override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
guard let record = records?[indexPath.row] else {
return []
}
let delete = UITableViewRowAction(style: .default, title: ReadingListTableViewCellUX.DeleteButtonTitleText) { [weak self] action, index in
self?.deleteItem(atIndex: index)
}
let toggleText = record.unread ? ReadingListTableViewCellUX.MarkAsReadButtonTitleText : ReadingListTableViewCellUX.MarkAsUnreadButtonTitleText
let unreadToggle = UITableViewRowAction(style: .normal, title: toggleText.stringSplitWithNewline()) { [weak self] (action, index) in
self?.toggleItem(atIndex: index)
}
unreadToggle.backgroundColor = ReadingListTableViewCellUX.MarkAsReadButtonBackgroundColor
return [unreadToggle, delete]
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// the cells you would like the actions to appear needs to be editable
return true
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
if let record = records?[indexPath.row], let url = URL(string: record.url), let encodedURL = url.encodeReaderModeURL(WebServer.sharedInstance.baseReaderModeURL()) {
// Mark the item as read
profile.readingList.updateRecord(record, unread: false)
// Reading list items are closest in concept to bookmarks.
let visitType = VisitType.bookmark
libraryPanelDelegate?.libraryPanel(didSelectURL: encodedURL, visitType: visitType)
UnifiedTelemetry.recordEvent(category: .action, method: .open, object: .readingListItem)
}
}
fileprivate func deleteItem(atIndex indexPath: IndexPath) {
if let record = records?[indexPath.row] {
UnifiedTelemetry.recordEvent(category: .action, method: .delete, object: .readingListItem, value: .readingListPanel)
if profile.readingList.deleteRecord(record).value.isSuccess {
records?.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
// reshow empty state if no records left
if records?.count == 0 {
refreshReadingList()
}
}
}
}
fileprivate func toggleItem(atIndex indexPath: IndexPath) {
if let record = records?[indexPath.row] {
UnifiedTelemetry.recordEvent(category: .action, method: .tap, object: .readingListItem, value: !record.unread ? .markAsUnread : .markAsRead, extras: [ "from": "reading-list-panel" ])
if let updatedRecord = profile.readingList.updateRecord(record, unread: !record.unread).value.successValue {
records?[indexPath.row] = updatedRecord
tableView.reloadRows(at: [indexPath], with: .automatic)
}
}
}
}
extension ReadingListPanel: LibraryPanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
guard let record = records?[indexPath.row] else { return nil }
return Site(url: record.url, title: record.title)
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
guard var actions = getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate) else { return nil }
let removeAction = PhotonActionSheetItem(title: Strings.RemoveContextMenuTitle, iconString: "action_remove", handler: { _, _ in
self.deleteItem(atIndex: indexPath)
})
actions.append(removeAction)
return actions
}
}
@available(iOS 11.0, *)
extension ReadingListPanel: UITableViewDragDelegate {
func tableView(_ tableView: UITableView, itemsForBeginning session: UIDragSession, at indexPath: IndexPath) -> [UIDragItem] {
guard let site = getSiteDetails(for: indexPath), let url = URL(string: site.url), let itemProvider = NSItemProvider(contentsOf: url) else {
return []
}
UnifiedTelemetry.recordEvent(category: .action, method: .drag, object: .url, value: .readingListPanel)
let dragItem = UIDragItem(itemProvider: itemProvider)
dragItem.localObject = site
return [dragItem]
}
func tableView(_ tableView: UITableView, dragSessionWillBegin session: UIDragSession) {
presentedViewController?.dismiss(animated: true)
}
}
extension ReadingListPanel: Themeable {
func applyTheme() {
tableView.separatorColor = UIColor.theme.tableView.separator
view.backgroundColor = UIColor.theme.tableView.rowBackground
refreshReadingList()
}
}
| mpl-2.0 | e8adbc9030d59ce9eb52683218db944f | 43.455752 | 333 | 0.690355 | 5.586322 | false | false | false | false |
YoungGary/Sina | Sina/Sina/Classes/Main主要/MainTabbarController.swift | 1 | 1876 | //
// MainTabbarController.swift
// Sina
//
// Created by YOUNG on 16/9/4.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
class MainTabbarController: UITabBarController {
private lazy var imageName = ["tabbar_home_highlighted","tabbar_message_center_highlighted","","tabbar_discover_highlighted","tabbar_profile_highlighted"]
private lazy var composeButton : UIButton = UIButton(imageName: "tabbar_compose_icon_add", bgImageName: "tabbar_compose_button")
override func viewDidLoad() {
super.viewDidLoad()
addComposeButton()
}
//在view will appear中遍历tabbar 改变选中图片
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
tabbarItems()
}
}
extension MainTabbarController{
//MARK: 加发布按钮
private func addComposeButton(){
tabBar.addSubview(composeButton)
composeButton.sizeToFit()
composeButton.center = CGPointMake(tabBar.center.x, tabBar.bounds.size.height*0.5)
composeButton.addTarget(self, action: #selector(MainTabbarController.composeButtonClick), forControlEvents: .TouchUpInside)
}
//MARK:tabbar选中图片
private func tabbarItems(){
for i in 0..<tabBar.items!.count {
let item = tabBar.items![i]
if i == 2 {
item.enabled = false
continue
}
item.selectedImage = UIImage(named:imageName[i])
}
}
}
//MARK: 点击事件的监听
extension MainTabbarController{
func composeButtonClick() {
let composeVC = ComposeViewController()
let composeNavi = UINavigationController(rootViewController: composeVC)
presentViewController(composeNavi, animated: true, completion: nil)
}
}
| apache-2.0 | db8260472a337e9d605667fe3ffb0760 | 27.015385 | 158 | 0.64525 | 4.804749 | false | false | false | false |
BrisyIOS/CustomAlbum | CustomAlbum/CustomAlbum/Album/Controller/PhotoListController.swift | 1 | 5062 | //
// PhotoListController.swift
// CustomAlbum
//
// Created by zhangxu on 2016/12/14.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
import Photos
let ITEM_SIZE = CGSize(width: realValue(value: 93), height: realValue(value: 93));
let IMAGE_SIZE = CGSize(width: realValue(value: 93/2) * scale, height: realValue(value: 93/2) * scale);
let MARGIN: CGFloat = realValue(value: 0.55);
class PhotoListController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
private let photoCellIdentifier = "photoCellIdentifier";
// collectionView
lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout();
layout.itemSize = ITEM_SIZE;
layout.minimumLineSpacing = realValue(value: MARGIN);
layout.minimumInteritemSpacing = realValue(value: MARGIN);
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDRH, height: SCREEN_HEIGHT - CGFloat(64)), collectionViewLayout: layout);
collectionView.backgroundColor = UIColor.clear;
collectionView.dataSource = self;
collectionView.delegate = self;
collectionView.contentInset = UIEdgeInsets(top: MARGIN, left: MARGIN, bottom: MARGIN, right: MARGIN);
return collectionView;
}();
/// 带缓存的图片管理对象
private lazy var imageManager:PHCachingImageManager = PHCachingImageManager();
// 单个相册中存储的图片数组
var assets: [PHAsset]?;
// 存放image的数据
private lazy var imageArray: [UIImage] = [UIImage]();
override func viewDidLoad() {
super.viewDidLoad()
// 添加collectionView
view.addSubview(collectionView);
// 注册cell
collectionView.register(PhotoCell.self, forCellWithReuseIdentifier: photoCellIdentifier);
// 加载assets数组
loadPhotoList();
// Do any additional setup after loading the view.
}
// 加载assets数组
private func loadPhotoList() -> Void {
if assets == nil {
assets = [PHAsset]();
//则获取所有资源
let allPhotosOptions = PHFetchOptions()
//按照创建时间倒序排列
allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate",
ascending: false)]
//只获取图片
allPhotosOptions.predicate = NSPredicate(format: "mediaType = %d",
PHAssetMediaType.image.rawValue)
let assetsFetchResults = PHAsset.fetchAssets(with: PHAssetMediaType.image,
options: allPhotosOptions)
for i in 0..<assetsFetchResults.count {
let asset = assetsFetchResults[i];
assets?.append(asset);
}
}
}
// 返回行数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return assets?.count ?? 0
}
// 返回cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: photoCellIdentifier, for: indexPath) as? PhotoCell;
if let assets = assets {
if indexPath.row < assets.count {
let asset = assets[indexPath.row];
_ = PhotoHandler.shared.getPhotosWithAsset(asset: asset, targetSize: IMAGE_SIZE, isOriginalImage: false, completion: { (result) in
guard let imageData = UIImageJPEGRepresentation(result, 0.3) else {
return;
}
cell?.image = UIImage.init(data: imageData);
})
}
}
return cell!;
}
// 选中cell , 进入照片详情
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false);
let photoDetailVc = PhotoDetailController();
if let assets = assets {
if indexPath.row < assets.count {
photoDetailVc.assets = assets;
photoDetailVc.indexPath = indexPath;
photoDetailVc.transitioningDelegate = ModalAnimationDelegate.shared;
photoDetailVc.modalPresentationStyle = .custom;
present(photoDetailVc, animated: true, completion: nil);
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | a001e24c575789ea29a36c2372ca645f | 34.302158 | 161 | 0.592215 | 5.732477 | false | false | false | false |
cikelengfeng/HTTPIDL | Sources/Runtime/HTTP/HTTPClient.swift | 1 | 15202 | //
// NSClient.swift
// Pods
//
// Created by 徐 东 on 2017/1/29.
//
//
import Foundation
public protocol HTTPClient {
func send(_ request: HTTPRequest, usingOutput outputStream: OutputStream?) -> HTTPRequestFuture
}
public protocol HTTPRequestFuture: class {
var request: HTTPRequest {get}
var progressHandler: ((_ progress: Progress) -> Void)? {get set}
var responseHandler: ((_ response: HTTPResponse) -> Void)? {get set}
var errorHandler: ((_ error: HIError) -> Void)? {get set}
func cancel()
func notify(progress: Progress)
func notify(response: HTTPResponse)
func notify(error: HIError)
}
public enum NSHTTPSessionError: HIError {
case missingResponse(request: HTTPRequest)
case adaptURLRequestFailed(rawError: Error)
case adaptURLResponseFailed(rawError: Error)
case writeToStreamFailed(rawError: Error)
public var errorDescription: String? {
get {
switch self {
case .missingResponse(let request):
return "HTTPURLResponse为空, request: \(request)"
case .adaptURLRequestFailed(let error):
return "生成URLRequest出错, 原始错误: \(error)"
case .adaptURLResponseFailed(let error):
return "请求出错, 原始错误: \(error)"
case .writeToStreamFailed(let error):
return "写response数据出错, 原始错误: \(error)"
}
}
}
}
class NSHTTPRequestFuture: NSObject, HTTPRequestFuture {
let request: HTTPRequest
var task: URLSessionDataTask? {
set {
_task = newValue
}
get { return _task }
}
var progressHandler: ((Progress) -> Void)?
var responseHandler: ((HTTPResponse) -> Void)?
var errorHandler: ((HIError) -> Void)?
let overallProgress: Progress
let sendProgress: Progress
let receiveProgress: Progress
private var _task: URLSessionDataTask? {
willSet {
_task?.removeObserver(self, forKeyPath: "countOfBytesReceived")
_task?.removeObserver(self, forKeyPath: "countOfBytesSent")
_task?.removeObserver(self, forKeyPath: "countOfBytesExpectedToReceive")
_task?.removeObserver(self, forKeyPath: "countOfBytesExpectedToSend")
}
didSet {
guard let t = _task else {
return
}
t.addObserver(self, forKeyPath: "countOfBytesReceived", options: .new, context: nil)
t.addObserver(self, forKeyPath: "countOfBytesSent", options: .new, context: nil)
t.addObserver(self, forKeyPath: "countOfBytesExpectedToReceive", options: .new, context: nil)
t.addObserver(self, forKeyPath: "countOfBytesExpectedToSend", options: .new, context: nil)
}
}
deinit {
_task?.removeObserver(self, forKeyPath: "countOfBytesReceived")
_task?.removeObserver(self, forKeyPath: "countOfBytesSent")
_task?.removeObserver(self, forKeyPath: "countOfBytesExpectedToReceive")
_task?.removeObserver(self, forKeyPath: "countOfBytesExpectedToSend")
}
init(request: HTTPRequest) {
self.request = request
overallProgress = Progress(totalUnitCount: 2)
overallProgress.becomeCurrent(withPendingUnitCount: overallProgress.totalUnitCount / 2)
sendProgress = Progress(totalUnitCount: Int64.max)
overallProgress.resignCurrent()
overallProgress.becomeCurrent(withPendingUnitCount: overallProgress.totalUnitCount / 2)
receiveProgress = Progress(totalUnitCount: Int64.max)
overallProgress.resignCurrent()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard let task = self.task, let keyPath = keyPath else {
return
}
switch keyPath {
case "countOfBytesExpectedToReceive" :
receiveProgress.totalUnitCount = task.countOfBytesExpectedToReceive
case "countOfBytesReceived" :
receiveProgress.completedUnitCount = task.countOfBytesReceived
case "countOfBytesExpectedToSend" :
sendProgress.totalUnitCount = task.countOfBytesExpectedToSend
case "countOfBytesSent" :
sendProgress.completedUnitCount = task.countOfBytesSent
default: break
}
notify(progress: overallProgress)
}
private func resetProgress() {
self.overallProgress.completedUnitCount = 0
self.sendProgress.completedUnitCount = 0
self.receiveProgress.completedUnitCount = 0
}
func notify(progress: Progress) {
self.progressHandler?(progress)
}
func notify(response: HTTPResponse) {
self.responseHandler?(response)
}
func notify(error: HIError) {
self.errorHandler?(error)
}
func cancel() {
task?.cancel()
}
}
fileprivate class TaskManager: NSObject, URLSessionDataDelegate {
let fallthroughDelegate: URLSessionDataDelegate?
private var taskMap: [Int: (future: HTTPRequestFuture, resp: HTTPResponse)]
private let lock = NSLock()
init(fallthroughDelegate: URLSessionDataDelegate?) {
self.fallthroughDelegate = fallthroughDelegate
self.taskMap = [Int: (future: HTTPRequestFuture, resp: HTTPResponse)]()
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
guard let fr = self.task(forKey: dataTask.taskIdentifier) else {
assert(false, "request future is nil, it's impossible!!!")
completionHandler(.cancel)
return
}
let future = fr.future
guard let httpResp = response as? HTTPURLResponse else {
future.notify(error: NSHTTPSessionError.missingResponse(request: future.request))
completionHandler(.cancel)
return
}
let resp = fr.resp
let newResp = HTTPBaseResponse(with: httpResp.statusCode, headers: httpResp.allHeaderFields as? [String: String] ?? [:], bodyStream: resp.bodyStream, request: resp.request)
self.set(task: (future, newResp), key: dataTask.taskIdentifier)
newResp.bodyStream?.open()
guard let method = fallthroughDelegate?.urlSession(_:dataTask:didReceive:completionHandler:) else {
completionHandler(.allow)
return
}
method(session, dataTask, response, completionHandler)
}
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
defer {
fallthroughDelegate?.urlSession?(session, dataTask: dataTask, didReceive: data)
}
guard let fr = self.task(forKey: dataTask.taskIdentifier) else {
return
}
guard let output = fr.resp.bodyStream else {
return
}
do {
try data.writeTo(stream: output)
} catch let error {
let future = fr.future
future.notify(error: NSHTTPSessionError.writeToStreamFailed(rawError: error))
}
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
defer {
fallthroughDelegate?.urlSession?(session, task: task, didCompleteWithError: error)
}
guard let fr = self.task(forKey: task.taskIdentifier) else {
return
}
let future = fr.future
let resp = fr.resp
if let err = error {
future.notify(error: NSHTTPSessionError.adaptURLResponseFailed(rawError: err))
resp.bodyStream?.close()
return
}
resp.bodyStream?.close()
future.notify(response: resp)
self.removeTask(forKey: task.taskIdentifier)
}
// MARK: fallthrough
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
fallthroughDelegate?.urlSession?(session, didBecomeInvalidWithError: error)
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let method = fallthroughDelegate?.urlSession(_:didReceive:completionHandler:) else {
completionHandler(.performDefaultHandling, nil)
return
}
method(session, challenge, completionHandler)
}
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
fallthroughDelegate?.urlSessionDidFinishEvents?(forBackgroundURLSession: session)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome downloadTask: URLSessionDownloadTask) {
fallthroughDelegate?.urlSession?(session, dataTask: dataTask, didBecome: downloadTask)
}
@available(iOS 9.0, *)
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didBecome streamTask: URLSessionStreamTask) {
fallthroughDelegate?.urlSession?(session, dataTask: dataTask, didBecome: streamTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, willCacheResponse proposedResponse: CachedURLResponse, completionHandler: @escaping (CachedURLResponse?) -> Void) {
guard let method = fallthroughDelegate?.urlSession(_:dataTask:willCacheResponse:completionHandler:) else {
completionHandler(proposedResponse)
return
}
method(session, dataTask, proposedResponse, completionHandler)
}
@available(iOS 10.0, *)
func urlSession(_ session: URLSession, task: URLSessionTask, didFinishCollecting metrics: URLSessionTaskMetrics) {
fallthroughDelegate?.urlSession?(session, task: task, didFinishCollecting: metrics)
}
func urlSession(_ session: URLSession, task: URLSessionTask, needNewBodyStream completionHandler: @escaping (InputStream?) -> Void) {
guard let method = fallthroughDelegate?.urlSession(_:task:needNewBodyStream:) else {
completionHandler(nil)
return
}
method(session, task, completionHandler)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
fallthroughDelegate?.urlSession?(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let method = fallthroughDelegate?.urlSession(_:task:didReceive:completionHandler:) else {
completionHandler(.performDefaultHandling, nil)
return
}
method(session, task, challenge, completionHandler)
}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
guard let method = fallthroughDelegate?.urlSession(_:task:willPerformHTTPRedirection:newRequest:completionHandler:) else {
completionHandler(request)
return
}
method(session, task, response, request, completionHandler)
}
fileprivate func set(task: (future: HTTPRequestFuture, resp: HTTPResponse)?, key: Int) {
self.lock.lock()
self.taskMap[key] = task
self.lock.unlock()
}
fileprivate func task(forKey key: Int) -> (future: HTTPRequestFuture, resp: HTTPResponse)? {
var ret: (future: HTTPRequestFuture, resp: HTTPResponse)? = nil
self.lock.lock()
ret = self.taskMap[key]
self.lock.unlock()
return ret;
}
fileprivate func removeTask(forKey key: Int) {
self.lock.lock()
self.taskMap.removeValue(forKey: key)
self.lock.unlock()
}
}
public class NSHTTPSession: NSObject, HTTPClient {
public static let shared = NSHTTPSession()
public let session: URLSession
private let taskManager: TaskManager
private override convenience init() {
let configuration = URLSessionConfiguration.default
let queue = OperationQueue()
queue.name = "org.httpidl.nsclient.default-callback"
self.init(configuration: configuration, delegate: nil, delegateQueue: queue)
}
public init(configuration: URLSessionConfiguration, delegate: URLSessionDataDelegate?, delegateQueue: OperationQueue?) {
self.taskManager = TaskManager(fallthroughDelegate: delegate)
self.session = URLSession(configuration: configuration, delegate: self.taskManager, delegateQueue: delegateQueue)
}
public func send(_ request: HTTPRequest, usingOutput outputStream: OutputStream?) -> HTTPRequestFuture {
let future = NSHTTPRequestFuture(request: request)
do {
let dataRequest: URLRequest = try adapt(request)
let task = session.dataTask(with: dataRequest)
future.task = task
self.taskManager.set(task: (future, HTTPBaseResponse(with: 0, headers: [:], bodyStream: outputStream, request: request)), key: task.taskIdentifier)
task.resume()
} catch let err {
session.delegateQueue.addOperation {
future.notify(error: NSHTTPSessionError.adaptURLRequestFailed(rawError: err))
}
}
return future
}
func adapt(_ request: HTTPRequest) throws -> URLRequest {
var urlRequest = URLRequest(url: request.url)
request.headers.forEach { (kv) in
urlRequest.setValue(kv.value, forHTTPHeaderField: kv.key)
}
urlRequest.httpMethod = request.method
if let ct = request.chunkedTransfer, ct {
urlRequest.httpBodyStream = request.bodyStream
} else {
urlRequest.httpBody = request.bodyStream?.data()
}
if let cachePolicy = request.cachePolicy {
urlRequest.cachePolicy = cachePolicy
}
if let timeout = request.timeoutInterval {
urlRequest.timeoutInterval = timeout
}
if let shouldPipeline = request.shouldUsePipelining {
urlRequest.httpShouldUsePipelining = shouldPipeline
}
if let shoudHandleCookie = request.shouldHandleCookies {
urlRequest.httpShouldHandleCookies = shoudHandleCookie
}
if let networkService = request.networkServiceType {
urlRequest.networkServiceType = networkService
}
if let allowCellar = request.allowsCellularAccess {
urlRequest.allowsCellularAccess = allowCellar
}
return urlRequest
}
}
| mit | c16ede718ad5cf9f8d718b100cfe3f82 | 39.709677 | 208 | 0.662573 | 5.529025 | false | false | false | false |
HiyakashiGroupHoldings/ExtensionCollection | ExtensionCollection/UIColor+Hex.swift | 1 | 767 | //
// UIColor+Hex.swift
// ExtensionCollection
//
// Created by Oka Yuya on 2017/08/01.
// Copyright © 2017年 Oka Yuya. All rights reserved.
//
import UIKit
public extension UIColor {
public class func colorWith(hex: String, alpha: CGFloat) -> UIColor {
let hex = hex.replacingOccurrences(of: "#", with: "")
let scanner = Scanner(string: hex as String)
var color: UInt32 = 0
if scanner.scanHexInt32(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000FF) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: alpha)
} else {
return UIColor.white
}
}
}
| apache-2.0 | e66f70a8d652051a6e023416a44199fe | 28.384615 | 73 | 0.575916 | 3.570093 | false | false | false | false |
dymx101/Gamers | Gamers/Models/Video.swift | 1 | 3376 | //
// VideoItem.swift
// Gamers
//
// Created by 虚空之翼 on 15/7/14.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
class Video: Object {
static let sharedSingleton = Video()
dynamic var id = "" //ID
dynamic var playListId = "" //youtube的播放列表
dynamic var videoId = "" //youtube的视频ID
//dynamic var userId = "" //用户ID
dynamic var imageSource = "" //视频图片
dynamic var videoTitle = "" //视频标题
dynamic var owner = "" //频道名称
dynamic var ownerId = "" //频道ID
dynamic var views = 0 //播放次数
dynamic var comments = 0 //评论次数
dynamic var likes = 0 //分享次数(?)
dynamic var featured = false //是否属于特殊
dynamic var playDate = NSDate()
dynamic var publishedAt = "" //发布时间
class func modelFromJSON(json: JSON) -> Video {
let model = Video()
if let itemId = json["id"].string { model.id = itemId }
if let playListId = json["playlist_id"].string { model.playListId = playListId }
if let videoId = json["video_id"].string { model.videoId = videoId }
//if let userId = json["user_id"].string { model.userId = userId }
if let imageSource = json["image_source"].string { model.imageSource = imageSource }
if let videoTitle = json["video_title"].string { model.videoTitle = videoTitle }
if let owner = json["owner"].string { model.owner = owner }
if let ownerId = json["owner_id"].string { model.ownerId = ownerId }
if let views = json["views"].int { model.views = views }
if let comments = json["comments"].int { model.comments = comments }
if let likes = json["likes"].int { model.likes = likes }
if let featured = json["featured"].bool { model.featured = featured }
if let publishedAt = json["published_at"].string { model.publishedAt = publishedAt }
return model
}
// MARK: - Override
override class func primaryKey() -> String {
return "id"
}
// MARK: - Private
private class func dateFormatter() -> NSDateFormatter {
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(name: "GMT")
// parse.com/docs/rest#objects-classes
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
return dateFormatter
}
// MARK: - ResponseCollectionSerializable
class func collection(#json: JSON) -> [Video] {
var collection = [Video]()
if let items = json.array {
for item in items {
collection.append(Video.modelFromJSON(item))
}
}
return collection
}
class func collectionFollow(#json: JSON) -> [Video] {
var collection = [Video]()
if let items = json.array {
for item in items {
collection.append(Video.modelFromJSON(item["videos"][0]))
}
}
return collection
}
} | apache-2.0 | fe1ea7394852c717f0bcabb256e3e23a | 33.052083 | 92 | 0.5612 | 4.489011 | false | false | false | false |
CPRTeam/CCIP-iOS | OPass/Class+addition/UIViewController+addition.swift | 1 | 1180 | //
// UIViewController+addition.swift
// OPass
//
// Created by 腹黒い茶 on 2018/11/4.
// 2018 OPass.
//
import Foundation
import UIKit
extension UIViewController {
@objc var ViewTopStart: CGFloat {
return self.view.ViewTopStart
}
var topGuideHeight: CGFloat {
var guide: CGFloat = 0.0
if let navController = self.navigationController {
if (navController.navigationBar.isTranslucent) {
if (self.prefersStatusBarHidden == false) {
guide += 20
}
if (navController.isNavigationBarHidden == false) {
guide += navController.navigationBar.bounds.size.height
}
}
}
return guide
}
var bottomGuideHeight: CGFloat {
var guide: CGFloat = 0.0
if let tabBarController = self.tabBarController {
if (tabBarController.tabBar.isHidden == false) {
guide += tabBarController.tabBar.bounds.size.height
}
}
return guide
}
@objc var isVisible: Bool {
return self.isViewLoaded && (self.view?.window != nil)
}
}
| gpl-3.0 | b4d72b6f2c413c655783ee9910874856 | 25.636364 | 75 | 0.569113 | 4.823045 | false | false | false | false |
sp8hmz/Todome | Pods/VHUD/Sources/VHUDView.swift | 1 | 3927 | //
// VHUDView.swift
// VHUD
//
// Created by xxxAIRINxxx on 2016/07/19.
// Copyright © 2016 xxxAIRINxxx. All rights reserved.
//
import UIKit
final class VHUDView: UIView {
private static let size: CGSize = CGSize(width: 180, height: 180)
private static let labelFont: UIFont = UIFont(name: "HelveticaNeue-Thin", size: 26)!
private static let labelInset: CGFloat = 44.0
private let label: UILabel = UILabel()
private let progressView: ProgressView = ProgressView()
private var blurView: UIVisualEffectView?
override public init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
self.bounds.size = VHUDView.size
self.clipsToBounds = true
self.label.textAlignment = .center
self.label.backgroundColor = .clear
self.label.adjustsFontSizeToFitWidth = true
self.label.font = VHUDView.labelFont
self.addSubview(self.label)
_ = self.addPin(withView: self.label, attribute: .top, toView: self, constant: VHUDView.labelInset)
_ = self.addPin(withView: self.label, attribute: .left, toView: self, constant: VHUDView.labelInset)
_ = self.addPin(withView: self.label, attribute: .right, toView: self, constant: -VHUDView.labelInset)
_ = self.addPin(withView: self.label, attribute: .bottom, toView: self, constant: -VHUDView.labelInset)
self.addSubview(self.progressView)
self.allPin(subView: self.progressView)
}
func setContent(_ content: VHUDContent) {
switch content.shape {
case .round:
self.layer.cornerRadius = 8
case .circle:
self.layer.cornerRadius = self.bounds.width * 0.5
case .custom(let closure):
closure(self)
}
switch content.style {
case .dark:
self.backgroundColor = .black
self.label.textColor = .white
self.progressView.defaultColor = content.lineDefaultColor ?? .darkGray
self.progressView.elapsedColor = content.lineElapsedColor ?? .white
case .light:
self.backgroundColor = .white
self.label.textColor = .black
self.progressView.defaultColor = content.lineDefaultColor ?? .lightGray
self.progressView.elapsedColor = content.lineElapsedColor ?? .darkGray
case .blur(let effecType):
self.label.textColor = .white
self.progressView.defaultColor = content.lineDefaultColor ?? .darkGray
self.progressView.elapsedColor = content.lineElapsedColor ?? .white
let v = UIVisualEffectView(effect: UIBlurEffect(style: effecType))
self.insertSubview(v, belowSubview: self.label)
self.allPin(subView: v)
self.blurView = v
}
self.label.font = content.labelFont ?? VHUDView.labelFont
self.progressView.mode = content.mode
}
func updateProgress(_ percentComplete: Double) {
var p = percentComplete
if p < 0.0 { p = 0.0 }
if p > 1.0 { p = 1.0 }
self.progressView.percentComplete = p
}
func setText(text: String?) {
self.label.text = text
}
func updateProgressText(_ percentComplete: Double) {
var p = percentComplete
if p < 0.0 { p = 0.0 }
if p > 1.0 { p = 1.0 }
self.label.text = Int(p * 100).description + "%"
}
func finishAllIfNeeded() {
self.progressView.outsideMargin -= 0.14
}
func finish() {
self.blurView?.removeFromSuperview()
self.backgroundColor = .clear
self.progressView.backgroundColor = .clear
self.progressView.finish()
self.label.text = nil
}
}
| mit | 10d60bff15bc3754980f88268489bf8f | 33.743363 | 111 | 0.615385 | 4.4563 | false | false | false | false |
tomkowz/Swifternalization | Swifternalization/LoadedTranslationsProcessor.swift | 1 | 5861 | //
// LoadedTranslationsProcessor.swift
// Swifternalization
//
// Created by Tomasz Szulc on 30/07/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import Foundation
/**
Translation processor which takes loaded translations and process them to make
them regular translation objects that can be used for further work.
*/
class LoadedTranslationsProcessor {
/**
Method takes base and prefered language translations and also shared
expressions and mix them together. Meaning, It checks which base loaded
translations are not contained in prefered language translations and
allow them to be used by framework later. It fit to the rule of how system
localization mechanism work, that when there is no prefered language
translation it takes base one if exists and return translation.
Shared expressions are used to replace shared-expression-keys from loaded
translations and use resolved full shared expressions from file with
expressions as well as built-in ones. Translations are processed in shared
expressions processor.
:param: baseTranslations An array of base translations.
:param: prerferedLanguageTranslations An array of prefered language translations.
:param: sharedExpressions An array of shared expressions.
*/
class func processTranslations(_ baseTranslations: [LoadedTranslation], preferedLanguageTranslations: [LoadedTranslation], sharedExpressions: [SharedExpression]) -> [Translation] {
/*
Find those base translations that are not contained in prefered language
translations.
*/
var uniqueBaseTranslations = baseTranslations
if preferedLanguageTranslations.count > 0 {
uniqueBaseTranslations = baseTranslations.filter({
let base = $0
return preferedLanguageTranslations.filter({$0.key == base.key}).count == 0
})
}
let translationsReadyToProcess = preferedLanguageTranslations + uniqueBaseTranslations
/*
Create array with translations. Array is just a map created from loaded
translations. There are few types of translations and expressions used
by the framework.
*/
return translationsReadyToProcess.map({
switch $0.type {
case .simple:
// Simple translation with key and value.
let value = $0.content[$0.key] as! String
return Translation(key: $0.key, expressions: [Expression(pattern: $0.key, value: value)])
case .withExpressions:
/*
Translation that contains expression.
Every time when new expressions is about to create, the shared
expressions are filtered to get expression that matches key and
if there is a key it is replaced with real expression pattern.
*/
var expressions = [Expression]()
for (key, value) in $0.content as! [String : String] {
let pattern = sharedExpressions.filter({$0.identifier == key}).first?.pattern ?? key
expressions.append(Expression(pattern: pattern, value: value))
}
return Translation(key: $0.key, expressions: expressions)
case .withLengthVariations:
// Translation contains length expressions like @100, @200, etc.
var lengthVariations = [LengthVariation]()
for (key, value) in $0.content as! [String : String] {
lengthVariations.append(LengthVariation(width: self.parseNumberFromLengthVariation(key), value: value))
}
return Translation(key: $0.key, expressions: [Expression(pattern: $0.key, value: lengthVariations.last!.value, lengthVariations: lengthVariations)])
case .withExpressionsAndLengthVariations:
/*
The most advanced translation type. It contains expressions
that contain length variations or just simple expressions.
THe job done here is similar to the one in .WithExpressions
and .WithLengthVariations cases. key is filtered in shared
expressions to get one of shared expressions and then method
builds array of variations.
*/
var expressions = [Expression]()
for (key, value) in $0.content {
let pattern = sharedExpressions.filter({$0.identifier == key}).first?.pattern ?? key
if value is [String : String] {
var lengthVariations = [LengthVariation]()
for (lvKey, lvValue) in value as! [String : String] {
lengthVariations.append(LengthVariation(width: self.parseNumberFromLengthVariation(lvKey), value: lvValue))
}
expressions.append(Expression(pattern: pattern, value: lengthVariations.last!.value, lengthVariations: lengthVariations))
} else if value is String {
expressions.append(Expression(pattern:pattern, value: value as! String))
}
}
return Translation(key: $0.key, expressions: expressions)
}
})
}
/**
Parses nubmer from length variation key.
:param: string A string that contains length variation string like @100.
:returns: A number parsed from the string.
*/
fileprivate class func parseNumberFromLengthVariation(_ string: String) -> Int {
return (Regex.matchInString(string, pattern: "@(\\d+)", capturingGroupIdx: 1)! as NSString).integerValue
}
}
| mit | c72637dfbb7aa33a40a70eb265bda834 | 48.669492 | 184 | 0.62805 | 5.560721 | false | false | false | false |
tardieu/swift | test/attr/attr_autoclosure.swift | 5 | 6376 | // RUN: %target-typecheck-verify-swift
// Simple case.
var fn : @autoclosure () -> Int = 4 // expected-error {{@autoclosure may only be used on parameters}} expected-error {{cannot convert value of type 'Int' to specified type '() -> Int'}}
@autoclosure func func1() {} // expected-error {{@autoclosure may only be used on 'parameter' declarations}}
func func1a(_ v1 : @autoclosure Int) {} // expected-error {{@autoclosure attribute only applies to function types}}
func func2(_ fp : @autoclosure () -> Int) { func2(4)}
func func3(fp fpx : @autoclosure () -> Int) {func3(fp: 0)}
func func4(fp : @autoclosure () -> Int) {func4(fp: 0)}
func func6(_: @autoclosure () -> Int) {func6(0)}
// autoclosure + inout don't make sense.
func func8(_ x: inout @autoclosure () -> Bool) -> Bool { // expected-error {{@autoclosure may only be used on parameters}}
}
// <rdar://problem/19707366> QoI: @autoclosure declaration change fixit
let migrate4 : (@autoclosure() -> ()) -> ()
struct SomeStruct {
@autoclosure let property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {
}
}
class BaseClass {
@autoclosure var property : () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
init() {}
}
class DerivedClass {
var property : () -> Int { get {} set {} }
}
protocol P1 {
associatedtype Element
}
protocol P2 : P1 {
associatedtype Element
}
func overloadedEach<O: P1>(_ source: O, _ closure: @escaping () -> ()) {
}
func overloadedEach<P: P2>(_ source: P, _ closure: @escaping () -> ()) {
}
struct S : P2 {
typealias Element = Int
func each(_ closure: @autoclosure () -> ()) {
// expected-note@-1{{parameter 'closure' is implicitly non-escaping because it was declared @autoclosure}}
overloadedEach(self, closure) // expected-error {{passing non-escaping parameter 'closure' to function expecting an @escaping closure}}
}
}
struct AutoclosureEscapeTest {
@autoclosure let delayed: () -> Int // expected-error {{@autoclosure may only be used on 'parameter' declarations}} {{3-16=}}
}
// @autoclosure(escaping)
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{13-34=}} {{38-38=@autoclosure @escaping }}
func func10(@autoclosure(escaping _: () -> ()) { } // expected-error{{expected ')' in @autoclosure}}
// expected-note@-1{{to match this opening '('}}
func func11(_: @autoclosure(escaping) @noescape () -> ()) { } // expected-error{{@escaping conflicts with @noescape}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
class Super {
func f1(_ x: @autoclosure(escaping) () -> ()) { }
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f2(_ x: @autoclosure(escaping) () -> ()) { } // expected-note {{potential overridden instance method 'f2' here}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{28-38= @escaping}}
func f3(x: @autoclosure () -> ()) { }
}
class Sub : Super {
override func f1(_ x: @autoclosure(escaping)() -> ()) { }
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping }}
override func f2(_ x: @autoclosure () -> ()) { } // expected-error{{does not override any method}} // expected-note{{type does not match superclass instance method with type '(@autoclosure @escaping () -> ()) -> ()'}}
override func f3(_ x: @autoclosure(escaping) () -> ()) { } // expected-error{{does not override any method}}
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{37-47= @escaping}}
}
func func12_sink(_ x: @escaping () -> Int) { }
func func12a(_ x: @autoclosure () -> Int) {
// expected-note@-1{{parameter 'x' is implicitly non-escaping because it was declared @autoclosure}}
func12_sink(x) // expected-error {{passing non-escaping parameter 'x' to function expecting an @escaping closure}}
}
func func12b(_ x: @autoclosure(escaping) () -> Int) {
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{31-41= @escaping}}
func12_sink(x) // ok
}
func func12c(_ x: @autoclosure @escaping () -> Int) {
func12_sink(x) // ok
}
func func12d(_ x: @escaping @autoclosure () -> Int) {
func12_sink(x) // ok
}
class TestFunc12 {
var x: Int = 5
func foo() -> Int { return 0 }
func test() {
func12a(x + foo()) // okay
func12b(x + foo())
// expected-error@-1{{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{13-13=self.}}
// expected-error@-2{{call to method 'foo' in closure requires explicit 'self.' to make capture semantics explicit}} {{17-17=self.}}
}
}
enum AutoclosureFailableOf<T> {
case Success(@autoclosure () -> T) // expected-error {{@autoclosure may only be used on parameters}}
case Failure()
}
let _ : (@autoclosure () -> ()) -> ()
let _ : (@autoclosure(escaping) () -> ()) -> ()
// expected-warning@-1{{@autoclosure(escaping) is deprecated; use @autoclosure @escaping instead}} {{22-32= @escaping}}
// escaping is the name of param type
let _ : (@autoclosure(escaping) -> ()) -> () // expected-error {{use of undeclared type 'escaping'}}
// Migration
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{16-28=}} {{32-32=@autoclosure }}
func migrateAC(@autoclosure _: () -> ()) { }
// expected-error @+1 {{@autoclosure is now an attribute on a parameter type, instead of on the parameter itself}} {{17-39=}} {{43-43=@autoclosure @escaping }}
func migrateACE(@autoclosure(escaping) _: () -> ()) { }
func takesAutoclosure(_ fn: @autoclosure () -> Int) {}
func callAutoclosureWithNoEscape(_ fn: () -> Int) {
takesAutoclosure(1+1) // ok
}
func callAutoclosureWithNoEscape_2(_ fn: () -> Int) {
takesAutoclosure(fn()) // ok
}
func callAutoclosureWithNoEscape_3(_ fn: @autoclosure () -> Int) {
takesAutoclosure(fn()) // ok
}
// expected-error @+1 {{@autoclosure may not be used on variadic parameters}}
func variadicAutoclosure(_ fn: @autoclosure () -> ()...) {
for _ in fn {}
}
| apache-2.0 | 6536fe96dc1ad9b4d463879cc3f28be1 | 39.100629 | 219 | 0.656524 | 3.746181 | false | false | false | false |
lightsprint09/InTrain-ICE-API | ICEInformationiOS/TrainConnection+JSONSerialization.swift | 1 | 2325 | //
// Copyright (C) 2017 Lukas Schmidt.
//
// 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.
//
//
// TrainConnection+JSONSerialization.swift
// ICEInformation
//
// Created by Lukas Schmidt on 05.04.17.
//
import Foundation
import JSONCodable
extension TrainConnection: JSONDecodable, JSONEncodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
trainType = try decoder.decode("trainType")
vzn = try decoder.decode("vzn")
let lineName: String? = try decoder.decode("lineName")
trainNumber = (try decoder.decode("trainNumber") as String?) ?? lineName ?? ""
schedule = try decoder.decode("timetable")
track = try decoder.decode("track")
destination = try decoder.decode("station")
}
public func toJSON() throws -> Any {
return try JSONEncoder.create({ (encoder) -> Void in
try encoder.encode(trainType, key: "trainType")
try encoder.encode(vzn, key: "vzn")
try encoder.encode(trainNumber, key: "trainNumber")
try encoder.encode(schedule, key: "timetable")
try encoder.encode(track, key: "track")
try encoder.encode(destination, key: "destination")
})
}
}
| mit | 305e587c008045d84b77f98499ed233a | 41.272727 | 86 | 0.686882 | 4.242701 | false | false | false | false |
urbn/URBNSwiftAlert | Example/Pods/URBNSwiftyConvenience/URBNSwiftyConvenience/Classes/QRCodeGenerator.swift | 1 | 1856 | //
// QRCodeGenerator.swift
// Pods
//
// Created by Nick DiStefano on 12/23/15.
//
//
import Foundation
public extension String {
public func qrImage() -> CIImage? {
let data = self.data(using: String.Encoding.isoLatin1, allowLossyConversion: false)
let filter = CIFilter(name: "CIQRCodeGenerator")
filter?.setValue(data, forKey: "inputMessage")
filter?.setValue("Q", forKey: "inputCorrectionLevel")
return filter?.outputImage
}
public func qrImage(foregroundColor: UIColor, backgroundColor: UIColor, size: CGSize) -> UIImage? {
return qrImage()?.scale(size)?.color(foregroundColor: foregroundColor, backgroundColor: backgroundColor)?.mapToUIImage()
}
}
public extension CIImage {
public func mapToUIImage() -> UIImage? {
return UIImage(ciImage: self)
}
public func scale(_ size: CGSize) -> CIImage? {
let scaleX = size.width / extent.size.width
let scaleY = size.height / extent.size.height
return transformed(by: CGAffineTransform(scaleX: scaleX, y: scaleY))
}
public func color(foregroundColor: UIColor, backgroundColor: UIColor) -> CIImage? {
let foregroundCoreColor = CIColor(uiColor: foregroundColor)
let backgroundCoreColor = CIColor(uiColor: backgroundColor)
let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage": self, "inputColor0":foregroundCoreColor, "inputColor1":backgroundCoreColor])
return colorFilter?.outputImage
}
}
extension CIColor {
convenience init(uiColor: UIColor) {
let foregroundColorRef = uiColor.cgColor
let foregroundColorString = CIColor(cgColor: foregroundColorRef).stringRepresentation
self.init(string: foregroundColorString)
}
}
| mit | c7e95b78a78b19f8ef9ff537d0be301a | 31.561404 | 169 | 0.671336 | 4.845953 | false | false | false | false |
DuckDeck/GrandMenu | Sources/GrandMenuTable.swift | 1 | 4865 | //
// GrandMenuTable.swift
// GrandMenuDemo
//
// Created by Tyrant on 1/15/16.
// Copyright © 2016 Qfq. All rights reserved.
//
import UIKit
open class GrandMenuTable: UIView {
let cellId = "GrandCelId"
open var scrollToIndex:((_ index:Int)->Void)?
open var contentViewCurrentIndex = 0{
didSet{
if contentViewCurrentIndex < 0 || contentViewCurrentIndex > self.childViewController!.count-1{
return
}
isSelectBtn = true
let path = IndexPath(row: self.contentViewCurrentIndex, section: 0)
collectionView?.scrollToItem(at: path, at: UICollectionView.ScrollPosition.centeredHorizontally, animated: true)
}
}
open var contentViewCanScroll = true{
didSet{
self.collectionView?.isScrollEnabled = self.contentViewCanScroll
}
}
open var isNeedNearPagePreload = true
weak fileprivate var parentViewController:UIViewController?
fileprivate var childViewController:[UIViewController]?
fileprivate var collectionView:UICollectionView?
fileprivate var startOffsetX:CGFloat = 0.0
fileprivate var isSelectBtn = false
public init(frame: CGRect,childViewControllers:[UIViewController],parentViewController:UIViewController) {
super.init(frame: frame)
self.parentViewController = parentViewController
self.childViewController = childViewControllers
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.itemSize = self.bounds.size
collectionViewFlowLayout.minimumLineSpacing = 0
collectionViewFlowLayout.minimumInteritemSpacing = 0
collectionViewFlowLayout.scrollDirection = .horizontal
self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: collectionViewFlowLayout)
self.collectionView?.showsHorizontalScrollIndicator = false
self.collectionView?.isPagingEnabled = true
self.collectionView?.bounces = false
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
for vc in self.childViewController!{
self.parentViewController?.addChild(vc)
}
addSubview(self.collectionView!)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension GrandMenuTable:UICollectionViewDataSource,UICollectionViewDelegate{
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.childViewController?.count ?? 0
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
cell.contentView.subviews.forEach { (v) in
v.removeFromSuperview()
}
let childVc = self.childViewController![indexPath.item]
if isNeedNearPagePreload{
if let count = self.childViewController?.count{
if count >= 2{
if indexPath.item > 0 && indexPath.item < count - 1{
assert( self.childViewController![indexPath.item - 1].view != nil)
assert( self.childViewController![indexPath.item + 1].view != nil)
}
else if indexPath.item == 0{
assert( self.childViewController![indexPath.item + 1].view != nil)
}
else{
assert( self.childViewController![indexPath.item - 1].view != nil)
}
}
}
}
childVc.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVc.view)
return cell
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isSelectBtn = false
startOffsetX = scrollView.contentOffset.x
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isSelectBtn {
return
}
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let scrollViewWidth = scrollView.bounds.size.width
let currentOffsetX = scrollView.contentOffset.x
// let startIndex = floor(startOffsetX / scrollViewWidth)
let endIndex = floor(currentOffsetX / scrollViewWidth)
if let block = scrollToIndex {
block(Int(endIndex))
}
}
public func reloadData() {
self.collectionView?.reloadData()
}
}
| mit | b37e67b8d8e99981713ed767ac7e96a3 | 36.705426 | 128 | 0.64926 | 5.818182 | false | false | false | false |
borglab/SwiftFusion | Examples/Pose3SLAMG2O/main.swift | 1 | 6069 | // Copyright 2020 The SwiftFusion Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// Loads a g2o file into a factor graph and then runs inference on the factor graph.
///
/// See https://lucacarlone.mit.edu/datasets/ for g2o specification and example datasets.
///
/// Usage: Pose3SLAMG2O [path to .g2o file]
///
/// Missing features:
/// - Does not take g2o information matrix into account.
/// - Does not use a proper general purpose solver.
/// - Has not been compared against other implementations, so it could be wrong.
import _Differentiation
import Foundation
import SwiftFusion
import TensorFlow
import TensorBoardX
import TSCUtility
struct FileHandlerOutputStream: TextOutputStream {
private let fileHandle: FileHandle
let encoding: String.Encoding
init(_ fileHandle: FileHandle, encoding: String.Encoding = .utf8) {
self.fileHandle = fileHandle
self.encoding = encoding
}
mutating func write(_ string: String) {
if let data = string.data(using: encoding) {
fileHandle.write(data)
}
}
}
func main() {
var inputFilename = ""
var outputFilename = ""
var loggingFolder: String? = nil
var useChordal = false
var useChordalInitialization = false
// Parse commandline.
do {
let parser = ArgumentParser(
commandName: "Pose3SLAMG2O",
usage: "[path to .g2o file] [path to output csv file] [path to logging folder]",
overview: "The command is used for argument parsing",
seeAlso: "getopt(1)")
let argsv = Array(CommandLine.arguments.dropFirst())
let input = parser.add(
positional: "input",
kind: String.self,
usage: "Input g2o file",
completion: .filename)
let output = parser.add(
positional: "output",
kind: String.self,
usage: "Output csv file",
completion: .filename)
let logging = parser.add(
option: "--logging",
shortName: "-l",
kind: String.self,
usage: "Tensorboard log folder",
completion: .filename)
let chordal = parser.add(
option: "--chordal",
shortName: "-c",
kind: Bool.self,
usage: "Use Chordal norm in BetweenFactor",
completion: ShellCompletion.none)
let chordal_init = parser.add(
option: "--chordal-init",
shortName: nil,
kind: Bool.self,
usage: "Use Chordal Initialization",
completion: ShellCompletion.none)
let parguments = try parser.parse(argsv)
inputFilename = parguments.get(input)!
outputFilename = parguments.get(output)!
loggingFolder = parguments.get(logging)
if let c = parguments.get(chordal) {
print("Using Chordal norm in BetweenFactor")
useChordal = c
}
if let c = parguments.get(chordal_init) {
print("Using Chordal Initialization")
useChordalInitialization = c
}
} catch ArgumentParserError.expectedValue(let value) {
print("Missing value for argument \(value).")
exit(1)
} catch ArgumentParserError.expectedArguments(let parser, let stringArray) {
print("Parser: \(parser) Missing arguments: \(stringArray.joined()).")
exit(1)
} catch {
print(error.localizedDescription)
exit(1)
}
let doTracing = loggingFolder != nil
let g2oURL = URL(fileURLWithPath: inputFilename)
let fileManager = FileManager.default
let filePath = URL(fileURLWithPath: outputFilename)
print("Storing result at \(filePath.path)")
if fileManager.fileExists(atPath: filePath.path) {
do {
try fileManager.removeItem(atPath: filePath.path)
} catch let error {
print("error occurred, here are the details:\n \(error)")
}
}
var logFileWriter: SummaryWriter? = nil
let datasetName = g2oURL.deletingPathExtension().lastPathComponent
if doTracing {
let fileWriterURL = URL(string: loggingFolder!)
if let _f = fileWriterURL {
logFileWriter = SummaryWriter(logdir: _f, suffix: datasetName)
}
}
// Load .g2o file.
let problem = try! G2OReader.G2OFactorGraph(g2oFile3D: g2oURL, chordal: useChordal)
var val = problem.initialGuess
var graph = problem.graph
graph.store(PriorFactor(TypedID(0), Pose3()))
if useChordalInitialization {
val = ChordalInitialization.GetInitializations(graph: graph, ids: problem.variableId)
}
var optimizer = LM(precision: 1e-6, max_iteration: 100)
optimizer.verbosity = .SUMMARY
optimizer.max_iteration = 100
do {
var hook: ((FactorGraph, VariableAssignments, Double, Int) -> Void)? = nil
if doTracing {
hook = { fg, val, lambda, step in
logFileWriter!.addScalar(tag: "optimizer/loss", scalar: fg.error(at: val), globalStep: step)
logFileWriter!.addScalar(tag: "optimizer/lambda", scalar: lambda, globalStep: step)
logFileWriter!.flush()
}
}
try optimizer.optimize(graph: graph, initial: &val, hook: hook)
} catch let error {
if doTracing {
logFileWriter!.addText(tag: "optimizer/message", text: "The solver gave up, message: \(error.localizedDescription)")
}
print("The solver gave up, message: \(error.localizedDescription)")
}
fileManager.createFile(atPath: filePath.path, contents: nil)
let fileHandle = try! FileHandle(forUpdating: URL(fileURLWithPath: filePath.path))
var output = FileHandlerOutputStream(fileHandle)
for i in problem.variableId {
let t = val[i].t
output.write("\(t.x), \(t.y), \(t.z)\n")
}
}
main()
| apache-2.0 | 7af241e42bc007ae6d6fada6c7d3d0cb | 31.629032 | 122 | 0.670292 | 4.148325 | false | false | false | false |
abertelrud/swift-package-manager | Fixtures/Miscellaneous/Plugins/PluginWithInternalExecutable/Plugins/PluginScriptTarget/Script.swift | 2 | 1069 | import PackagePlugin
@main
struct PluginScript: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
print("Hello from the plugin script!")
guard let target = target as? SourceModuleTarget else { return [] }
return try target.sourceFiles.map{ $0.path }.compactMap {
guard $0.extension == "dat" else { return .none }
let outputName = $0.stem + ".swift"
let outputPath = context.pluginWorkDirectory.appending(outputName)
return .buildCommand(
displayName:
"Generating \(outputName) from \($0.lastComponent)",
executable:
try context.tool(named: "PluginExecutable").path,
arguments: [
"\($0)",
"\(outputPath)"
],
inputFiles: [
$0,
],
outputFiles: [
outputPath
]
)
}
}
}
| apache-2.0 | 7423b0ecc10cf9ab217035d7c625b90d | 33.483871 | 90 | 0.49392 | 5.596859 | false | false | false | false |
snowpunch/AppLove | App Love/Network/AppListEmail.swift | 1 | 1504 | //
// AppListEmail.swift
// App Love
//
// Created by Woodie Dovich on 2016-07-27.
// Copyright © 2016 Snowpunch. All rights reserved.
//
import UIKit
import MessageUI
class AppListEmail: NSObject {
class func generateAppList() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.setSubject("App Links")
let appModels = AppList.sharedInst.appModels
var msgBody = "<small><b>Check out these Apps!</b><br></small>"
for app in appModels {
let appName = truncateAppName(app.appName)
msgBody += "<small><a href='https://itunes.apple.com/app/id\(app.appId)'>\(appName)</a></small><br>"
}
let appLovePlug = "<small><br>List generated by <a href='https://itunes.apple.com/app/id\(Const.appId.AppLove)'>App Love.</a></small>"
msgBody += appLovePlug
mailComposerVC.setMessageBody(msgBody, isHTML: true)
return mailComposerVC
}
// cut off app name at '-' dash, then limit to 30 characters for email.
class func truncateAppName(originalAppName:String?) -> String {
let fullAppName = originalAppName ?? ""
let fullNameArray = fullAppName.characters.split("-").map{ String($0) }
var appName = fullNameArray.first ?? ""
if appName != fullAppName {
appName = appName + "..."
}
let truncatedAppName = appName.truncate(30)
return truncatedAppName
}
} | mit | f1235b0b176d72e7f3dc17c829e5b224 | 33.181818 | 142 | 0.630073 | 4.331412 | false | false | false | false |
JacquesCarette/literate-scientific-software | code/stable/glassbr/src/swift/InputParameters.swift | 1 | 639 | /** InputParameters.swift
Provides the structure for holding input values
- Authors: Nikitha Krithnan and W. Spencer Smith
*/
/** Structure for holding the input values and derived values
*/
class InputParameters {
var a: Double = 0.0
var b: Double = 0.0
var w: Double = 0.0
var P_btol: Double = 0.0
var TNT: Double = 0.0
var g: String = ""
var t: Double = 0.0
var SD_x: Double = 0.0
var SD_y: Double = 0.0
var SD_z: Double = 0.0
var h: Double = 0.0
var LDF: Double = 0.0
var GTF: Double = 0.0
var SD: Double = 0.0
var AR: Double = 0.0
var w_TNT: Double = 0.0
}
| bsd-2-clause | 60dfcbe0262010e52a4d6cd6cdb3fd6d | 24.56 | 61 | 0.593114 | 3.057416 | false | false | false | false |
Karumi/MarvelApiClient | MarvelApiClient/MarvelAPIClient.swift | 1 | 1253 | //
// MarvelAPIClient.swift
// MarvelAPIClient
//
// Created by Pedro Vicente on 14/11/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
import BothamNetworking
public class MarvelAPIClient {
static var publicKey: String = ""
static var privateKey: String = ""
public static func configureCredentials(publicKey: String, privateKey: String) {
MarvelAPIClient.publicKey = publicKey
MarvelAPIClient.privateKey = privateKey
initDefaultHeaders()
initAuthentication()
}
public static let charactersAPIClient = CharactersAPIClient(
apiClient: bothamAPIClient,
parser: CharactersParser())
public static let seriesAPIClient = SeriesAPIClient(
apiClient: bothamAPIClient,
parser: SeriesParser())
private static let bothamAPIClient = BothamAPIClient(
baseEndpoint: MarvelAPIClientConfig.host)
private static func initDefaultHeaders() {
BothamAPIClient.globalRequestInterceptors.append(DefaultHeadersRequestInterceptor())
}
private static func initAuthentication() {
BothamAPIClient.globalRequestInterceptors.append(
MarvelAPIAuthentication(timeProvider: TimeProvider()))
}
}
| apache-2.0 | dfd8aa6df6e584273d09046dee35f44e | 27.454545 | 92 | 0.717252 | 5.350427 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.