repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
na4lapy/na4lapy-ios | Na4Łapy/Model/Listing.swift | 1 | 7564 | //
// Listing.swift
// Na4Łapy
//
// Created by Andrzej Butkiewicz on 19.06.2016.
// Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved.
//
import Foundation
protocol ListingProtocol {
static func get(_ page: Int, size: Int, preferences: UserPreferences?, success: @escaping ([AnyObject], Int) -> Void, failure: @escaping (NSError) -> Void)
init?(dictionary: [String:AnyObject])
}
/**
Obsługa listingu wraz z prefetch'em
Zasada działania.
Dane z API są pobierane stronami. Na stronie znajduje się PAGESIZE elementów, które zostają zwrócone w formie tablicy. Taka tablica (strona) jest wpisywana do słownika localCache pod klucz będący ID danej strony, np:
Strona o id 1 będzie wpisana jako [1, Array<AnyObject>]
Jak działa metoda get(index:)
=============================
Parametrem metody jest index, czyli kolejny numer obiektu. Przykładowo: zwierzaków w bazie jest 120, więc index może przyjąć wartość od 1 do 120.
Przyjmijmy, że metoda get została wywołana z parametrem 56, przy czym rozmiar strony jest ustalony na 10 (stała PAGESIZE)
Oznacza to, że szukany obiekt znajduje się na stronie nr 5 (56/10) i jest to 6-ty element tej strony 56-5*10.
Otrzymujemy więc zmienne:
localCachePage = 5
localCacheIndex = 6
Kolejnym krokiem jest test, czy localCacheIndex wskazuje dokładnie połowę aktualnej strony. Jeśli tak, to należy wykonać prefetch kolejnej strony.
Przy rozmiarze strony 10, index 6 wykracza poza połowę, więc nie należy wykonywać prefetch (gdyż został wykonany przy poprzednim pobieraniu indexu o wartości 5)
Skoro nie trzeba wykonywać prefetch, to metoda get kończy pracę zwracając obiekt nr 6 na stronie nr 5.
------
Rozważmy inny przypadek, gdy prefetch będzie konieczny.
Pytamy o index = 85
localCachePage = 8 (gdyż 85/10)
localCacheIndex = 5 (85 - 8*10)
localCacheIndex wskazuje dokładnie na PAGESIZE/2, więc należy wykonać prefetch kolejnej strony (czyli strona nr 9). Dodatkowo wykonywane są jeszcze 3 inne czynności:
1. prefetch _poprzedniej_ strony, czyli strony nr 7, gdyby użytkownik zechciał się cofnąć.
2. usuwana jest strona oddalona o 2 od aktualnej, czyli 8 + 2 = 10 (bo nie chcemy przechowywać tak wielu stron)
3. usuwana jest strona oddalona o -2 od aktualnej, czyli 8 - 2 = 6 (j.w.)
W wyniku w/w operacji w pamięci urządzenia znajdują się 3 strony: poprzednia, aktualna oraz następna.
(btw. prefetch stron nie jest wykonywany jeśli strony już znajdują się w pamięci)
Uwaga, metody prefetch i clearAndPrefetch wykonywane są asynchronicznie. Oznacza to, że wyjście z metody get może nastąpić _zanim_ te metody zakończą pracę.
Może to się zdarzyć w momencie np. problemów sieciowych, timeoutu na serwerze itp. Możliwe są 2 scenariusze błędów:
1. metoda prefetch zakończyła się błędem (bo np. serwer nie odpowiada)
2. metoda prefetch zakończyła się poprawnie, lecz po długim czasie (np. 10 sek.)
W przypadku wariantu 1, nie zostanie załadowana kolejna strona. Wszystkie obiekty aktualnej strony będą dostępne dla użytkownika
(czyli obiekty o localCacheIndex od 1 do 10), jednak podczas zmiany strony na kolejną użytkownik otrzyma błąd. Metoda get posiada zabezpieczenie i zawsze
próbuje jeszcze raz pobrać aktualną stronę, o ile nie została wcześniej załadowana. Jeśli jednak i to zawiedzie, to oznacza problem sieciowy/serwerowy i należy
oddać inicjatywę użytkownikowi (np. przycisk "spróbuj ponownie")
W przypadku wariantu nr 2, metoda get zakończy się wcześniej niż prefetch. Użytkownik nadal będzie dysponował obiektami aktualnej strony (od 1 do 10) i teraz
mogą się zdarzyć 2 kolejne warianty:
a. użytkownik bardzo szybko "doscrollował" do obiektu nr 10 i przełączył stronę zanim metoda prefetch się zakończyła
b. użytkownik powoli scrolluje i metoda prefetch zdążyła zakończyć się zanim została przełączona strona.
Jeśli wystąpił wariant 'a', to użytkownik dostanie błąd, który jest spowodowany problemami sieciowymi. Należy więc oddać mu inicjatywę jak to opisano wyżej.
Wariant 'b' oznacza, że użytkownik nie zauważy problemu gdyż kolejna strona zdąży zostać załadowana zanim wystąpi potrzeba jej wyświetlenia.
Wszystkie operacje na lokalnym cache MUSZĄ być wykonywane na tym samym wątku, więc w przypadku wprowadzenia wielowątkowości do aplikacji należy to zabezpieczyć.
*/
class Listing {
fileprivate var localCache: [Int: AnyObject] = [:]
fileprivate let listingType: ListingProtocol.Type
func prefetch(_ page: Int, success: (() -> Void)? = nil, failure: (() -> Void)? = nil) {
log.debug("prefetch page: \(page)")
let userPreferences = UserPreferences.init()
listingType.get(page, size: PAGESIZE, preferences: userPreferences,
success: { [weak self] (elements, count) in
guard let strongSelf = self else { return }
strongSelf.localCache[page] = elements as AnyObject?
success?()
},
failure: { (error) in
log.error(error.localizedDescription)
failure?()
}
)
}
init<T: ListingProtocol>(listingType: T.Type) {
self.listingType = listingType
}
private func prefetch( _ success: @escaping () -> Void ) {
self.prefetch(0) {
success()
}
}
// Jeśli aktualny index strony przekroczy połowę wielkości to należy:
// - pobrać kolejną stronę (+1)
// - pobrać wcześniejszą stronę (-1)
// - usunąć (-2)
// - usunąć (+2)
private func clearAndPrefetch(_ page: Int) {
// +1
if self.localCache[page+1] == nil {
self.prefetch(page+1)
}
// -1
if self.localCache[page-1] == nil && page-1 >= 0 {
self.prefetch(page-1)
}
// -2
self.localCache.removeValue(forKey: page-2)
// +2
self.localCache.removeValue(forKey: page+2)
}
func getCount() -> Int {
var result = 0
if let first = self.localCache.first {
result = first.value.count
if let maxKey = self.localCache.keys.max(),
let lastPage = self.localCache[maxKey] {
result = (maxKey)*PAGESIZE + lastPage.count
}
}
return result
}
func get(_ index: Int) -> AnyObject? {
// Aktualna strona musi być dostepna, w przeciwnym wypadku należy ją pobrać
log.debug("index: \(index)")
// Konwersja index -> index/page
let localCachePage = Int(index)/PAGESIZE
let localCacheIndex = Int(index) - localCachePage*PAGESIZE
guard let page = self.localCache[localCachePage] else {
log.debug("Aktualna strona \(localCachePage) nie jest dostępna!")
self.prefetch(localCachePage)
return nil
}
if localCacheIndex == page.count/2 && self.getCount() >= PAGESIZE {
self.clearAndPrefetch(localCachePage)
}
if localCacheIndex > page.count - 1 {
return nil
}
log.debug("===== Strona: \(localCachePage), index: \(localCacheIndex)")
if let returnPage = self.localCache[localCachePage] as? [AnyObject] , returnPage.count > 0 {
return returnPage[localCacheIndex]
} else {
return nil
}
}
}
| apache-2.0 | 51ad9d45429a1550c16221e53e831b1a | 43.343373 | 217 | 0.680342 | 2.821388 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureTransaction/Sources/FeatureTransactionUI/FiatAccountTransactions/Deposit/DepositRoot/DepositRootInteractor.swift | 1 | 7204 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import MoneyKit
import PlatformKit
import PlatformUIKit
import RIBs
import RxSwift
import ToolKit
public protocol DepositRootRouting: Routing {
/// Routes to the `Select a Funding Method` screen
func routeToDepositLanding()
/// Routes to the TransactonFlow with a given `FiatAccount`
func routeToDeposit(target: FiatAccount, sourceAccount: LinkedBankAccount?)
/// Routes to the TransactonFlow with a given `FiatAccount`
/// The user already has at least one linked bank.
/// Does not execute dismissal of top most screen (Link Bank Flow)
func startDeposit(target: FiatAccount, sourceAccount: LinkedBankAccount?)
/// Routes to the wire details flow
func routeToWireInstructions(currency: FiatCurrency)
/// Routes to the wire details flow.
/// Does not execute dismissal of top most screen (Payment Method Selector)
func startWithWireInstructions(currency: FiatCurrency)
/// Routes to the `Link a Bank Account` flow.
/// Does not execute dismissal of top most screen (Payment Method Selector)
func startWithLinkABank()
/// Routes to the `Link a Bank Account` flow
func routeToLinkABank()
/// Exits the bank linking flow
func dismissBankLinkingFlow()
/// Exits the wire instruction flow
func dismissWireInstructionFlow()
/// Exits the payment method selection flow
func dismissPaymentMethodFlow()
/// Exits the TransactonFlow
func dismissTransactionFlow()
/// Starts the deposit flow. This is available as the `DepositRootRIB`
/// does not own a view and we do not want to expose the entire `DepositRootRouter`
/// but rather only `DepositRootRouting`
func start()
}
extension DepositRootRouting where Self: RIBs.Router<DepositRootInteractable> {
func start() {
load()
}
}
protocol DepositRootListener: ViewListener {}
final class DepositRootInteractor: Interactor, DepositRootInteractable, DepositRootListener {
weak var router: DepositRootRouting?
weak var listener: DepositRootListener?
// MARK: - Private Properties
private var paymentMethodTypes: Single<[PaymentMethodPayloadType]> {
Single
.just(targetAccount.fiatCurrency)
.flatMap { [linkedBanksFactory] fiatCurrency -> Single<[PaymentMethodType]> in
linkedBanksFactory.bankPaymentMethods(for: fiatCurrency)
}
.map { $0.map(\.method) }
.map { $0.map(\.rawType) }
}
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let linkedBanksFactory: LinkedBanksFactoryAPI
private let fiatCurrencyService: FiatCurrencyServiceAPI
private let targetAccount: FiatAccount
private let featureFlagsService: FeatureFlagsServiceAPI
init(
targetAccount: FiatAccount,
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
linkedBanksFactory: LinkedBanksFactoryAPI = resolve(),
fiatCurrencyService: FiatCurrencyServiceAPI = resolve(),
featureFlagsService: FeatureFlagsServiceAPI = resolve()
) {
self.targetAccount = targetAccount
self.analyticsRecorder = analyticsRecorder
self.linkedBanksFactory = linkedBanksFactory
self.fiatCurrencyService = fiatCurrencyService
self.featureFlagsService = featureFlagsService
super.init()
}
override func didBecomeActive() {
super.didBecomeActive()
Single.zip(
linkedBanksFactory.linkedBanks,
paymentMethodTypes,
.just(targetAccount.fiatCurrency),
featureFlagsService
.isEnabled(.openBanking)
.asSingle()
)
.observe(on: MainScheduler.asyncInstance)
.subscribe(onSuccess: { [weak self] values in
guard let self = self else { return }
let (linkedBanks, paymentMethodTypes, fiatCurrency, openBanking) = values
// An array of linked bank accounts that can be used for Deposit
let filteredLinkedBanks = linkedBanks.filter { linkedBank in
linkedBank.fiatCurrency == fiatCurrency
&& linkedBank.paymentType == .bankTransfer
&& (linkedBank.partner != .yapily || openBanking)
}
if filteredLinkedBanks.isEmpty {
self.handleNoLinkedBanks(
paymentMethodTypes,
fiatCurrency: fiatCurrency
)
} else {
// If you want the TxFlow to go straight to the
// `Enter Amount` screen, pass in a `sourceAccount`.
// However, if you do this, the user will not be able to
// return to the prior screen to change their source.
self.router?.startDeposit(
target: self.targetAccount,
sourceAccount: nil
)
}
})
.disposeOnDeactivate(interactor: self)
}
func bankLinkingComplete() {
linkedBanksFactory
.linkedBanks
.compactMap(\.first)
.observe(on: MainScheduler.asyncInstance)
.subscribe(onSuccess: { [weak self] linkedBankAccount in
guard let self = self else { return }
self.router?.routeToDeposit(
target: self.targetAccount,
sourceAccount: linkedBankAccount
)
})
.disposeOnDeactivate(interactor: self)
}
func bankLinkingClosed(isInteractive: Bool) {
router?.dismissBankLinkingFlow()
}
func closePaymentMethodScreen() {
router?.dismissPaymentMethodFlow()
}
func routeToWireTransfer() {
fiatCurrencyService
.tradingCurrency
.asSingle()
.observe(on: MainScheduler.asyncInstance)
.subscribe(onSuccess: { [weak self] fiatCurrency in
self?.router?.routeToWireInstructions(currency: fiatCurrency)
})
.disposeOnDeactivate(interactor: self)
}
func routeToLinkedBanks() {
router?.routeToLinkABank()
}
func dismissTransactionFlow() {
router?.dismissTransactionFlow()
}
func presentKYCFlowIfNeeded(from viewController: UIViewController, completion: @escaping (Bool) -> Void) {
unimplemented()
}
func dismissAddNewBankAccount() {
router?.dismissWireInstructionFlow()
}
// MARK: - Private Functions
private func handleNoLinkedBanks(_ paymentMethodTypes: [PaymentMethodPayloadType], fiatCurrency: FiatCurrency) {
if paymentMethodTypes.contains(.bankAccount), paymentMethodTypes.contains(.bankTransfer) {
router?.routeToDepositLanding()
} else if paymentMethodTypes.contains(.bankTransfer) {
router?.startWithLinkABank()
} else if paymentMethodTypes.contains(.bankAccount) {
router?.startWithWireInstructions(currency: fiatCurrency)
} else {
// TODO: Show that deposit is not supported
}
}
}
| lgpl-3.0 | 9d29ede2fe10a6246c10130909bcecad | 33.966019 | 116 | 0.650285 | 5.440332 | false | false | false | false |
bluquar/emoji_keyboard | DecisiveEmojiKeyboard/DEKeyboard/KeyboardViewController.swift | 1 | 1919 | //
// KeyboardViewController.swift
// DEKeyboard
//
// Created by Chris Barker on 11/25/14.
// Copyright (c) 2014 Chris Barker. All rights reserved.
//
import UIKit
class KeyboardViewController: UIInputViewController {
var buttonLayoutManager : ButtonLayoutManager
var emojiSelectionController: EmojiSelectionController
var settings: SettingsManager
override init() {
self.settings = SettingsManager()
self.buttonLayoutManager = ButtonLayoutManager(settings: self.settings)
self.emojiSelectionController = EmojiSelectionController(buttonManager: self.buttonLayoutManager)
super.init()
self.buttonLayoutManager.kbDelegate! = self
}
required init(coder aDecoder: NSCoder) {
self.settings = SettingsManager()
self.buttonLayoutManager = ButtonLayoutManager(settings: self.settings)
self.emojiSelectionController = EmojiSelectionController(buttonManager: self.buttonLayoutManager)
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
self.settings = SettingsManager()
self.buttonLayoutManager = ButtonLayoutManager(settings: self.settings)
self.emojiSelectionController = EmojiSelectionController(buttonManager: self.buttonLayoutManager)
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.buttonLayoutManager.kbDelegate = self
}
override func updateViewConstraints() {
super.updateViewConstraints()
self.buttonLayoutManager.updateViewConstraints()
}
func insertText(emoji: String) -> Void {
(self.textDocumentProxy as UITextDocumentProxy).insertText(emoji)
}
override func viewDidLoad() {
super.viewDidLoad()
self.buttonLayoutManager.viewDidLoad(self.view)
self.emojiSelectionController.viewDidLoad(self)
}
}
| gpl-2.0 | 2e0af6d2ecc437b798acb514af9cf3b9 | 34.537037 | 105 | 0.724336 | 5.330556 | false | false | false | false |
tomlokhorst/Xcode.swift | Sources/XcodeEdit/XCProjectFile+Rswift.swift | 2 | 1954 | //
// XCProjectFile+Rswift.swift
// XcodeEdit
//
// Created by Tom Lokhorst on 2017-12-28.
// Copyright © 2017 nonstrict. All rights reserved.
//
import Foundation
// Mutation functions needed by R.swift
extension XCProjectFile {
public func addReference<Value>(value: Value) -> Reference<Value> {
return allObjects.createReference(value: value)
}
public func createShellScript(name: String, shellScript: String) throws -> PBXShellScriptBuildPhase {
let fields: [String: Any] = [
"isa": "PBXShellScriptBuildPhase",
"files": [],
"name": name,
"runOnlyForDeploymentPostprocessing": 0,
"shellPath": "/bin/sh",
"inputPaths": [],
"outputPaths": [],
"shellScript": shellScript,
"buildActionMask": 0x7FFFFFFF]
let guid = allObjects.createFreshGuid(from: project.id)
let scriptBuildPhase = try PBXShellScriptBuildPhase(id: guid, fields: fields, allObjects: allObjects)
return scriptBuildPhase
}
public func createFileReference(path: String, name: String, sourceTree: SourceTree, lastKnownFileType: String = "sourcecode.swift") throws -> PBXFileReference {
var fields: [String: Any] = [
"isa": "PBXFileReference",
"lastKnownFileType": lastKnownFileType,
"path": path,
"sourceTree": sourceTree.rawValue
]
if name != path {
fields["name"] = name
}
let guid = allObjects.createFreshGuid(from: project.id)
let fileReference = try PBXFileReference(id: guid, fields: fields, allObjects: allObjects)
return fileReference
}
public func createBuildFile(fileReference: Reference<PBXFileReference>) throws -> PBXBuildFile {
let fields: [String: Any] = [
"isa": "PBXBuildFile",
"fileRef": fileReference.id.value
]
let guid = allObjects.createFreshGuid(from: project.id)
let buildFile = try PBXBuildFile(id: guid, fields: fields, allObjects: allObjects)
return buildFile
}
}
| mit | 2c3fcbc1f01aa1d9c1a3632af76256ae | 27.720588 | 162 | 0.684076 | 4.282895 | false | false | false | false |
konduruvijaykumar/ios-sample-apps | GMapsDemo/GMapsDemo/ViewController.swift | 1 | 4532 | //
// ViewController.swift
// GMapsDemo
//
// Created by Vijay Kondurura on 13/02/17.
// Copyright © 2017 PJay. All rights reserved.
//
//https://developers.google.com/maps/documentation/ios-sdk/
//https://developers.google.com/maps/documentation/ios-sdk/start
//http://blog.swilliams.me/words/2015/03/31/tracking-down-an-exc-bad-access-with-swift/
//http://stackoverflow.com/questions/25353790/swift-project-crashing-with-thread-1-exc-bad-access-code-1-address-0x0
//https://developers.google.com/maps/documentation/ios-sdk/marker
//https://developers.google.com/maps/documentation/ios-sdk/map
//https://github.com/github/gitignore/blob/master/Objective-C.gitignore
//https://github.com/konduruvijaykumar/maps-sdk-for-ios-samples/blob/master/tutorials/current-places-on-map/.gitignore
//http://stackoverflow.com/questions/11197249/show-system-files-show-git-ignore-in-osx
import UIKit
import GoogleMaps
class ViewController: UIViewController {
//@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadView() {
/**
navigationItem.title = "Hello Map"
let camera = GMSCameraPosition.camera(withLatitude: -33.868,
longitude: 151.2086,
zoom: 14)
let mapView = GMSMapView.map(withFrame: .zero, camera: camera)
let marker = GMSMarker()
marker.position = camera.target
marker.snippet = "Hello World"
marker.appearAnimation = kGMSMarkerAnimationPop
marker.map = mapView
view = mapView
*/
/**
// Create a GMSCameraPosition that tells the map to display the
// coordinate -33.86,151.20 at zoom level 6.
let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0)
let mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
view = mapView
// Creates a marker in the center of the map.
let marker = GMSMarker()
marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20)
marker.title = "Sydney"
marker.snippet = "Australia"
marker.map = mapView
*/
//let camera = GMSCameraPosition.camera(withLatitude: -33.868,longitude: 151.2086, zoom: 14);//Sydney, Australia
//let camera = GMSCameraPosition.camera(withLatitude: 12.94982,longitude: 77.64302, zoom: 18);//EGL, Bangalore
let camera = GMSCameraPosition.camera(withLatitude: 37.331837,longitude: -122.029586, zoom: 18);//Apple Inc, Cupertino, CA 95014, USA
let mapView = GMSMapView.map(withFrame: .zero, camera: camera);
//mapView.mapType = kGMSTypeNone;//kGMSTypeTerrain;//kGMSTypeHybrid;//kGMSTypeNormal;//kGMSTypeSatellite;
let marker = GMSMarker();
marker.position = camera.target;
marker.title = "Apple Inc";//marker.title = "Embassy Golf Links";//marker.title = "Sydney";
marker.snippet = "Cupertino, CA 95014, USA";//marker.snippet = "Bengaluru, KA, India";//marker.snippet = "Australia";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = mapView;
self.view = mapView;
/**
// Adding Many markers or nearby locations in map
let camera = GMSCameraPosition.camera(withLatitude: 12.971891,longitude: 77.641154, zoom: 18);
let mapView = GMSMapView.map(withFrame: .zero, camera: camera);
let marker = GMSMarker();
marker.position = camera.target;
marker.title = "Indiranagar";
marker.snippet = "Bengaluru, KA, India";
marker.appearAnimation = kGMSMarkerAnimationPop;
marker.map = mapView;
view = mapView;
let marker1 = GMSMarker();
marker1.position = CLLocationCoordinate2D(latitude: 12.972249, longitude: 77.640746);
marker1.appearAnimation = kGMSMarkerAnimationPop;
marker1.map = mapView;
let marker2 = GMSMarker();
marker2.position = CLLocationCoordinate2D(latitude: 12.971964, longitude: 77.642140);
marker2.appearAnimation = kGMSMarkerAnimationPop;
marker2.map = mapView;
*/
}
}
| apache-2.0 | 4794aa976172133c6012fcfbd137f48c | 39.81982 | 141 | 0.652836 | 4.130356 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | v2.x/Tutorials/Swift/Tutorial06c/HavingFunWithSciChart/ViewController.swift | 1 | 4230 | //
// ViewController.swift
// HavingFunWithSciChart
//
// Created by Yaroslav Pelyukh on 31/01/2017.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import UIKit
import SciChart
class ViewController: UIViewController {
var sciChartSurface: SCIChartSurface?
var lineDataSeries: SCIXyDataSeries!
var scatterDataSeries: SCIXyDataSeries!
var lineRenderableSeries: SCIFastLineRenderableSeries!
var scatterRenderableSeries: SCIXyScatterRenderableSeries!
var timer: Timer?
var phase = 0.0
var i = 0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
sciChartSurface = SCIChartSurface(frame: self.view.bounds)
sciChartSurface?.autoresizingMask = [.flexibleHeight, .flexibleWidth]
sciChartSurface?.translatesAutoresizingMaskIntoConstraints = true
self.view.addSubview(sciChartSurface!)
let xAxis = SCINumericAxis()
xAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
sciChartSurface?.xAxes.add(xAxis)
let yAxis = SCINumericAxis()
yAxis.growBy = SCIDoubleRange(min: SCIGeneric(0.1), max: SCIGeneric(0.1))
sciChartSurface?.yAxes.add(yAxis)
createDataSeries()
createRenderableSeries()
addModifiers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if nil == timer{
timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: updatingDataPoints)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if nil != timer{
timer?.invalidate()
timer = nil
}
}
func updatingDataPoints(timer:Timer){
i += 1
lineDataSeries.appendX(SCIGeneric(i), y: SCIGeneric(sin(Double(i)*0.1 + phase)))
scatterDataSeries.appendX(SCIGeneric(i), y: SCIGeneric(cos(Double(i)*0.1 + phase)))
phase += 0.01
sciChartSurface?.zoomExtents()
sciChartSurface?.invalidateElement()
}
func createDataSeries(){
// Init line data series
lineDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
lineDataSeries.fifoCapacity = 500
lineDataSeries.seriesName = "line series"
// Init scatter data series
scatterDataSeries = SCIXyDataSeries(xType: .double, yType: .double)
scatterDataSeries.fifoCapacity = 500
scatterDataSeries.seriesName = "scatter series"
for i in 0...500{
lineDataSeries.appendX(SCIGeneric(i), y: SCIGeneric(sin(Double(i)*0.1)))
scatterDataSeries.appendX(SCIGeneric(i), y: SCIGeneric(cos(Double(i)*0.1)))
}
i = Int(lineDataSeries.count())
}
func createRenderableSeries(){
lineRenderableSeries = SCIFastLineRenderableSeries()
lineRenderableSeries.dataSeries = lineDataSeries
scatterRenderableSeries = SCIXyScatterRenderableSeries()
scatterRenderableSeries.dataSeries = scatterDataSeries
sciChartSurface?.renderableSeries.add(lineRenderableSeries)
sciChartSurface?.renderableSeries.add(scatterRenderableSeries)
}
func addModifiers(){
let xAxisDragmodifier = SCIXAxisDragModifier()
xAxisDragmodifier.dragMode = .pan
xAxisDragmodifier.clipModeX = .none
let yAxisDragmodifier = SCIYAxisDragModifier()
yAxisDragmodifier.dragMode = .pan
let extendZoomModifier = SCIZoomExtentsModifier()
let pinchZoomModifier = SCIPinchZoomModifier()
let rolloverModifier = SCIRolloverModifier()
let legend = SCILegendModifier()
let groupModifier = SCIChartModifierCollection(childModifiers: [xAxisDragmodifier, yAxisDragmodifier, pinchZoomModifier, extendZoomModifier, legend, rolloverModifier])
sciChartSurface?.chartModifiers = groupModifier
}
}
| mit | 25f07a2104a7c5aa4f908244b9f40a15 | 32.039063 | 175 | 0.646252 | 4.889017 | false | false | false | false |
guumeyer/InspirationMessages | Inspiration/Services/DataService.swift | 1 | 1605 | //
// DataService.swift
// Inspiration
//
// Created by gustavo r meyer on 1/22/17.
// Copyright © 2017 gustavo r meyer. All rights reserved.
//
import UIKit
class DataService: NSObject {
func getQuoteData(completion: @escaping (_ quote: String,_ author:String) -> (),fail: @escaping () -> () ){
let quoteEndPoint = "http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json"
guard let url = URL(string: quoteEndPoint) else {
print("Error: cannot create URL")
return
}
// make the request
let task = URLSession.shared.dataTask(with: url) { data, response, error in
guard error == nil else {
print(error ?? "")
return
}
guard let data = data else {
print("Data is empty")
return
}
do{
if let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject] {
print(json)
let aQuota = (json["quoteText"] as! String)
let aAuthor = (json["quoteAuthor"] as! String)
DispatchQueue.main.sync {
completion(aQuota,aAuthor)
}
}
} catch {
DispatchQueue.main.sync {
fail()
}
print("Error to parse")
}
}
task.resume()
}
}
| mit | 7844f2401b03dcf00a9ca253dcc1e8ee | 26.186441 | 111 | 0.453242 | 4.802395 | false | false | false | false |
Darkkrye/DKDetailsParallax | DKDetailsParallax/Cells/FlatDarkTheme/FlatDarkSimpleLabelCell.swift | 1 | 2651 | //
// FlatDarkSimpleLabelCell.swift
// iOSeries
//
// Created by Pierre on 15/01/2017.
// Copyright © 2017 Pierre Boudon. All rights reserved.
//
import UIKit
/// FlatDarkSimpleLabelCell class
open class FlatDarkSimpleLabelCell: UITableViewCell {
/// MARK: - Private Constants
/// Cell default height
public static let defaultHeight: CGFloat = 44
/// MARK: - Private Variables
/// Cell primary color
public var primaryColor = UIColor.white
/// Cell secondary color
public var secondaryColor = UIColor.gray
/// MARK: - IBOutlets
/// Content Label
@IBOutlet public weak var contentLabel: UILabel!
/// MARK: - IBActions
/// MARK: - "Default" Methods
/// Override function awakeFromNib
override open func awakeFromNib() {
super.awakeFromNib()
/* Initialization code */
}
/// MARK: - Delegates
/// MARK: - Personnal Delegates
/// MARK: - Personnal Methods
/// Default constructor for the cell
///
/// - Parameters:
/// - withPrimaryColor: UIColor? - The primary color
/// - andSecondaryColor: UIColor? - The secondary color
/// - Returns: FlatDarkSimpleLabelCell - The created cell
open static func simpleCell(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?) -> FlatDarkSimpleLabelCell {
/* Call other constructor with default value */
return simpleCell(withPrimaryColor: withPrimaryColor, andSecondaryColor: andSecondaryColor, wantsEmptyCell: false)
}
/// Complex constructor for the cell
///
/// - Parameters:
/// - withPrimaryColor: UIColor? - The primary color
/// - andSecondaryColor: UIColor? - The secondary color
/// - wantsEmptyCell: Bool - If you want this item
/// - Returns: FlatDarkSimpleLabelCell
open static func simpleCell(withPrimaryColor: UIColor?, andSecondaryColor: UIColor?, wantsEmptyCell: Bool) -> FlatDarkSimpleLabelCell {
/* Retrieve cell */
let nibs = DKDetailsParallax.bundle()?.loadNibNamed("FlatDarkSimpleLabelCell", owner: self, options: nil)
let cell: FlatDarkSimpleLabelCell = nibs![0] as! FlatDarkSimpleLabelCell
cell.selectionStyle = .none
/* Set colors */
if let p = withPrimaryColor {
cell.primaryColor = p
}
if let s = andSecondaryColor {
cell.secondaryColor = s
}
if wantsEmptyCell {
/* Hide content label */
cell.contentLabel.isHidden = true
}
return cell
}
}
| bsd-3-clause | caad68ff78305ed07e9b26d039161103 | 28.775281 | 139 | 0.622642 | 4.925651 | false | false | false | false |
siong1987/TSSafariViewController | TSSafariViewController/TSSafariViewController.swift | 1 | 4811 | //
// TSSafariViewController.swift
// TSSafariViewControllerDemo
//
// Created by Teng Siong Ong on 10/18/15.
// Copyright © 2015 Siong Inc. All rights reserved.
//
import UIKit
import SafariServices
protocol TSSafariViewControllerDelegate {
func safariViewController(controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool)
func safariViewController(controller: SFSafariViewController, activityItemsForURL URL: NSURL, title: String?) -> [UIActivity]
func safariViewControllerDidFinish(controller: SFSafariViewController)
}
extension TSSafariViewController {
}
public class TSSafariViewController: SFSafariViewController, SFSafariViewControllerDelegate, UIViewControllerTransitioningDelegate {
var safariDelegate: TSSafariViewControllerDelegate?
let animator = TSEdgeSwipeBackAnimator()
var edgeView: UIView? {
get {
if (_edgeView == nil && isViewLoaded()) {
_edgeView = UIView()
_edgeView?.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(_edgeView!)
_edgeView?.backgroundColor = UIColor(white: 1.0, alpha: 0.005)
let bindings = ["edgeView": _edgeView!]
let options = NSLayoutFormatOptions(rawValue: 0)
let hConstraints = NSLayoutConstraint.constraintsWithVisualFormat("|-0-[edgeView(5)]", options: options, metrics: nil, views: bindings)
let vConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[edgeView]-0-|", options: options, metrics: nil, views: bindings)
view?.addConstraints(hConstraints)
view?.addConstraints(vConstraints)
}
return _edgeView
}
}
private var _edgeView: UIView?
private var _superView: UIView?
init(URL: NSURL) {
super.init(URL: URL, entersReaderIfAvailable: false)
self.initialize()
}
override init(URL: NSURL, entersReaderIfAvailable: Bool) {
super.init(URL: URL, entersReaderIfAvailable: entersReaderIfAvailable)
self.initialize()
}
func initialize() {
self.delegate = self;
self.transitioningDelegate = self
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let recognizer = UIScreenEdgePanGestureRecognizer(target: self, action: "handleGesture:")
recognizer.edges = .Left
self.edgeView?.addGestureRecognizer(recognizer)
}
func handleGesture(recognizer:UIScreenEdgePanGestureRecognizer) {
self.animator.percentageDriven = true
let percentComplete = recognizer.locationInView(self._superView!).x / self._superView!.bounds.size.width / 2.0
switch recognizer.state {
case .Began: dismissViewControllerAnimated(true, completion: nil)
case .Changed: animator.updateInteractiveTransition(percentComplete > 0.99 ? 0.99 : percentComplete)
case .Ended, .Cancelled:
(recognizer.velocityInView(self._superView!).x < 0) ? animator.cancelInteractiveTransition() : animator.finishInteractiveTransition()
self.animator.percentageDriven = false
default: ()
}
}
// MARK: - Safari view controller delegate
public func safariViewControllerDidFinish(controller: SFSafariViewController) {
self.dismissViewControllerAnimated(true, completion: nil)
self.safariDelegate?.safariViewControllerDidFinish(self)
}
public func safariViewController(controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) {
self.safariDelegate?.safariViewController(self, didCompleteInitialLoad: didLoadSuccessfully)
}
public func safariViewController(controller: SFSafariViewController, activityItemsForURL URL: NSURL, title: String?) -> [UIActivity] {
return (self.safariDelegate?.safariViewController(self, activityItemsForURL: URL, title: title))!
}
// MARK: - View controller transition delegate
public func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
self._superView = presenting.view
animator.dismissing = false
return animator
}
public func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
animator.dismissing = true
return animator
}
public func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
return self.animator.percentageDriven ? self.animator : nil
}
}
| mit | c70bb5913cbbbb25db34d0b7d54ad698 | 39.420168 | 224 | 0.715593 | 5.699052 | false | false | false | false |
ppraveentr/MobileCore | Sources/CoreComponents/LoadingIndicator/LoadingIndicator.swift | 1 | 10557 | //
// LoadingIndicator.swift
// MobileCore-CoreComponents
//
// Created by Praveen Prabhakar on 24/09/18.
// Copyright © 2018 Praveen Prabhakar. All rights reserved.
//
import CoreGraphics
import Foundation
import QuartzCore
import UIKit
let loaderSpinnerMarginSide: CGFloat = 35.0
let loaderSpinnerMarginTop: CGFloat = 20.0
let loaderTitleMargin: CGFloat = 5.0
// MARK: Loader config
public struct LoaderConfig {
/// Size of loader
public var size: CGFloat = 120.0
/// Color of spinner view
public var spinnerColor = UIColor.black
/// SpinnerLine Width
public var spinnerLineWidth: Float = 1.0
/// Speed of the spinner
public var speed: Int = 1
/// Size of loader
public var title: String?
/// Font for title text in loader
public var titleTextFont = UIFont.boldSystemFont(ofSize: 16.0)
/// Color of title text
public var titleTextColor = UIColor.black
/// Background color for loader
public var backgroundColor = UIColor.white
/// Foreground color
public var foregroundColor = UIColor.clear
/// Foreground alpha CGFloat, between 0.0 and 1.0
public var foregroundAlpha: CGFloat = 0.0
/// Corner radius for loader
public var cornerRadius: CGFloat = 10.0
/// Corner radius for loader
public var customConfig: [String: Any]?
public init(_ customConfig: [String: Any]? = nil) {
self.customConfig = customConfig
}
}
public class LoadingIndicator: UIView {
static let sharedInstance = LoadingIndicator(frame: CGRect(x: 0, y: 0, width: 120, height: 120))
public typealias CompletionBlock = (_ isCompleted: Bool) -> Void
private var baseView: UIView?
private var titleLabel: UILabel?
private var loadingView: LoadingView?
private var (animated, canUpdated) = (true, false)
private var title: String?
private var speed = 1
private var config = LoaderConfig() {
didSet {
self.loadingView?.config = config
}
}
@objc func rotated(notification: NSNotification) {
let loader = LoadingIndicator.sharedInstance
let height: CGFloat = UIScreen.main.bounds.size.height
let width: CGFloat = UIScreen.main.bounds.size.width
let center = CGPoint(x: width / 2.0, y: height / 2.0)
loader.center = center
loader.baseView?.frame = UIScreen.main.bounds
}
override public var frame: CGRect {
didSet {
self.update()
}
}
public static func show(_ animated: Bool = true) {
self.show(title: self.sharedInstance.config.title, animated: animated)
}
public static func show(title: String?, animated: Bool = true) {
// Will fail if window is not allocated
guard let currentWindow: UIWindow = UIApplication.shared.keyWindow else { return }
let loader = LoadingIndicator.sharedInstance
loader.canUpdated = true
loader.animated = animated
loader.title = title
loader.update()
NotificationCenter.default.addObserver(
loader,
selector: #selector( loader.rotated(notification:) ),
name: UIDevice.orientationDidChangeNotification,
object: nil
)
let height: CGFloat = UIScreen.main.bounds.size.height
let width: CGFloat = UIScreen.main.bounds.size.width
let center = CGPoint(x: width / 2.0, y: height / 2.0)
loader.center = center
if loader.superview == nil {
loader.baseView = UIView(frame: currentWindow.bounds)
loader.baseView?.backgroundColor = loader.config.foregroundColor.withAlphaComponent(loader.config.foregroundAlpha)
currentWindow.addSubview(loader.baseView!)
currentWindow.addSubview(loader)
loader.start()
}
}
public static func hide(_ completion: CompletionBlock? = nil) {
let loader = LoadingIndicator.sharedInstance
NotificationCenter.default.removeObserver(loader)
loader.stop(completion)
}
public static func setConfig(config: LoaderConfig) {
let loader = LoadingIndicator.sharedInstance
loader.config = config
}
func frameForSpinner() -> CGRect {
let loadingViewSize = self.frame.size.width - (loaderSpinnerMarginSide * 2)
if self.title == nil {
let yOffset = (self.frame.size.height - loadingViewSize) / 2
return CGRect(origin: CGPoint(x: loaderSpinnerMarginSide, y: yOffset), size: CGSize(width: loadingViewSize, height: loadingViewSize))
}
return CGRect(origin: CGPoint(x: loaderSpinnerMarginSide, y: loaderSpinnerMarginTop), size: CGSize(width: loadingViewSize, height: loadingViewSize))
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: Private methods
private extension LoadingIndicator {
func setup() {
self.alpha = 0
self.update()
}
func start() {
self.loadingView?.start()
if self.animated {
UIView.animate(withDuration: 0.3) {
self.alpha = 1
}
}
else {
self.alpha = 1
}
}
func stop(_ completion: CompletionBlock? = nil) {
if self.animated {
UIView.animate(
withDuration: 0.3,
animations: { self.alpha = 0 },
completion: { _ in
self.removeFromSuperview()
self.baseView?.removeFromSuperview()
self.loadingView?.stop(completion)
}
)
}
else {
self.alpha = 0
self.removeFromSuperview()
self.baseView?.removeFromSuperview()
self.loadingView?.stop(completion)
}
}
func update() {
self.backgroundColor = self.config.backgroundColor
self.layer.cornerRadius = self.config.cornerRadius
let loadingViewSize = self.frame.size.width - (loaderSpinnerMarginSide * 2)
if self.loadingView == nil {
self.loadingView = LoadingView(frame: self.frameForSpinner())
self.addSubview(self.loadingView!)
}
else {
self.loadingView?.frame = self.frameForSpinner()
}
let labelFrame = CGRect(
origin: CGPoint(x: loaderTitleMargin, y: loaderSpinnerMarginTop + loadingViewSize),
size: CGSize(width: self.frame.width - loaderTitleMargin * 2, height: 42.0)
)
if self.titleLabel == nil {
self.titleLabel = UILabel(frame: labelFrame)
self.addSubview(self.titleLabel!)
self.titleLabel?.numberOfLines = 1
self.titleLabel?.textAlignment = NSTextAlignment.center
self.titleLabel?.adjustsFontSizeToFitWidth = true
}
else {
self.titleLabel?.frame = labelFrame
}
self.titleLabel?.font = self.config.titleTextFont
self.titleLabel?.textColor = self.config.titleTextColor
self.titleLabel?.text = self.title
self.titleLabel?.isHidden = self.title == nil
}
}
// MARK: LoadingView
private class LoadingView: UIView {
private var speed: Int?
private var lineWidth: Float?
private var lineTintColor: UIColor?
private var backgroundLayer: CAShapeLayer?
private var isSpinning: Bool?
var config = LoaderConfig() {
didSet {
self.update()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: Setup loading view
func setup() {
self.backgroundColor = UIColor.clear
self.lineWidth = fmaxf(Float(self.frame.size.width) * 0.025, 1)
self.backgroundLayer = CAShapeLayer()
self.backgroundLayer?.strokeColor = self.config.spinnerColor.cgColor
self.backgroundLayer?.fillColor = self.backgroundColor?.cgColor
self.backgroundLayer?.lineCap = CAShapeLayerLineCap.round
self.backgroundLayer?.lineWidth = CGFloat(self.lineWidth!)
self.layer.addSublayer(self.backgroundLayer!)
}
func update() {
self.frame = CGRect(x: 0, y: 0, width: config.size, height: config.size)
self.lineWidth = self.config.spinnerLineWidth
self.speed = self.config.speed
self.backgroundLayer?.lineWidth = CGFloat(self.lineWidth!)
self.backgroundLayer?.strokeColor = self.config.spinnerColor.cgColor
}
// MARK: Draw Circle
override func draw(_ rect: CGRect) {
self.backgroundLayer?.frame = self.bounds
}
func drawBackgroundCircle(partial: Bool) {
let startAngle = CGFloat.pi / CGFloat(2.0)
var endAngle: CGFloat = (2.0 * CGFloat.pi) + startAngle
let center = CGPoint(x: self.bounds.size.width / 2, y: self.bounds.size.height / 2)
let radius = (CGFloat(self.bounds.size.width) - CGFloat(self.lineWidth!)) / CGFloat(2.0)
let processBackgroundPath = UIBezierPath()
processBackgroundPath.lineWidth = CGFloat(self.lineWidth!)
if partial {
endAngle = (1.8 * CGFloat.pi) + startAngle
}
processBackgroundPath.addArc(withCenter: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
self.backgroundLayer?.path = processBackgroundPath.cgPath
}
// MARK: Start and stop spinning
func start() {
self.isSpinning? = true
self.drawBackgroundCircle(partial: true)
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
rotationAnimation.toValue = NSNumber(value: Double.pi * 2.0)
rotationAnimation.duration = 1
rotationAnimation.isCumulative = true
rotationAnimation.repeatCount = HUGE
self.backgroundLayer?.add(rotationAnimation, forKey: "rotationAnimation")
}
func stop(_ completion: LoadingIndicator.CompletionBlock? = nil) {
self.drawBackgroundCircle(partial: false)
self.backgroundLayer?.removeAllAnimations()
self.isSpinning? = false
completion?(true)
}
}
| mit | 69b3e03171b90ec917c1c3ccbc8d227f | 32.72524 | 156 | 0.623153 | 4.782963 | false | true | false | false |
imobilize/Molib | Molib/Classes/ViewControllers/FetchedResultsDataSourceProvider.swift | 1 | 5702 | import Foundation
import CoreData
public class FetchedResultsDataSourceProvider<ObjectType: NSManagedObject, Delegate: DataSourceProviderDelegate> : DataSourceProvider where Delegate.ItemType == ObjectType {
private var headerItems: [Int: [String: Any]]
public weak var delegate: Delegate? { didSet {
fetchedResultsControllerDelegate = FetchedResultsControllerDelegate<ObjectType, Delegate>(delegate: delegate!)
fetchedResultsController.delegate = fetchedResultsControllerDelegate
}
}
public let fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>
var fetchedResultsControllerDelegate: FetchedResultsControllerDelegate<ObjectType, Delegate>?
public init(fetchedResultsController: NSFetchedResultsController<NSFetchRequestResult>) {
self.fetchedResultsController = fetchedResultsController
self.headerItems = [Int: [String: Any]]()
}
public func reload() {
do {
try self.fetchedResultsController.performFetch()
} catch {}
}
public func isEmpty() -> Bool {
var empty = true
if let count = self.fetchedResultsController.fetchedObjects?.count {
empty = (count == 0)
}
return empty
}
public func numberOfSections() -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
public func numberOfRowsInSection(section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections?[section]
return sectionInfo?.numberOfObjects ?? 0
}
public func itemAtIndexPath(indexPath: IndexPath) -> ObjectType {
return self.fetchedResultsController.object(at: indexPath) as! ObjectType
}
public func deleteItemAtIndexPath(indexPath: IndexPath) {
let context = self.fetchedResultsController.managedObjectContext
context.delete(self.fetchedResultsController.object(at: indexPath) as! ObjectType)
do {
try context.save()
} catch _ {
}
}
public func insertItem(item: ObjectType, atIndexPath: IndexPath) {
let context = self.fetchedResultsController.managedObjectContext
context.insert(item)
do {
try context.save()
} catch _ {
}
}
public func updateItem(item: ObjectType, atIndexPath: IndexPath) {
let context = self.fetchedResultsController.managedObjectContext
//MARK: TODO update the item here
do {
try context.save()
} catch _ {
}
}
public func deleteAllInSection(section: Int) {
let context = self.fetchedResultsController.managedObjectContext
let sectionInfo = self.fetchedResultsController.sections![section]
if let objects = sectionInfo.objects {
for object in objects {
context.delete(object as! NSManagedObject)
}
}
}
public func titleForHeaderAtSection(section: Int) -> String? {
return self.fetchedResultsController.sections?[section].name
}
//MARK:- Header
public func insertHeaderDetails(details: [String : Any], atSection: Int) {
headerItems[atSection] = details
}
public func headerDetailsAtSection(index: Int) -> [String : Any]? {
return headerItems[index]
}
deinit {
debugPrint("FetchedResultsDataSourceProvider dying")
}
}
class FetchedResultsControllerDelegate<ObjectType: NSManagedObject, Delegate: DataSourceProviderDelegate>: NSObject, NSFetchedResultsControllerDelegate where Delegate.ItemType == ObjectType {
unowned var delegate: Delegate
init(delegate: Delegate) {
self.delegate = delegate
}
// MARK: - Fetched results controller
func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.delegate.providerWillChangeContent()
}
func controller(controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .insert:
self.delegate.providerDidInsertSectionAtIndex(index: sectionIndex)
case .delete:
self.delegate.providerDidDeleteSectionAtIndex(index: sectionIndex)
default:
return
}
}
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
let obj = anObject as! ObjectType
switch type {
case .insert:
self.delegate.providerDidInsertItemsAtIndexPaths(items: [obj], atIndexPaths: [newIndexPath!])
case .delete:
self.delegate.providerDidDeleteItemsAtIndexPaths(items: [obj], atIndexPaths: [indexPath!])
case .update:
self.delegate.providerDidUpdateItemsAtIndexPaths(items: [obj], atIndexPaths: [indexPath!])
case .move:
if let initiaIndexPath = indexPath, let finalIndexPath = newIndexPath {
if initiaIndexPath != finalIndexPath {
self.delegate.providerDidMoveItem(item: anObject as! ObjectType, atIndexPath: indexPath!, toIndexPath: newIndexPath!)
}
}
}
}
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
self.delegate.providerDidEndChangeContent {}
}
deinit {
debugPrint("FetchedResultsControllerDelegate dying")
}
}
| apache-2.0 | 938c3ae447644336751345f6158ef052 | 27.653266 | 217 | 0.67906 | 5.842213 | false | false | false | false |
aidenluo177/GitHubber | GitHubber/Pods/CoreStore/CoreStore/Logging/CoreStore+Logging.swift | 4 | 2711 | //
// CoreStore+Logging.swift
// CoreStore
//
// Copyright (c) 2015 John Rommel Estropia
//
// 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
// MARK: - CoreStore
public extension CoreStore {
// MARK: Public
/**
The `CoreStoreLogger` instance to be used. The default logger is an instance of a `DefaultLogger`.
*/
public static var logger: CoreStoreLogger = DefaultLogger()
// MARK: Internal
internal static func log(level: LogLevel, message: String, fileName: StaticString = __FILE__, lineNumber: Int = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.log(
level: level,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName
)
}
internal static func handleError(error: NSError, _ message: String, fileName: StaticString = __FILE__, lineNumber: Int = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.handleError(
error: error,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName
)
}
internal static func assert(@autoclosure condition: () -> Bool, _ message: String, fileName: StaticString = __FILE__, lineNumber: Int = __LINE__, functionName: StaticString = __FUNCTION__) {
self.logger.assert(
condition,
message: message,
fileName: fileName,
lineNumber: lineNumber,
functionName: functionName
)
}
}
| mit | 1d62933940e9929adb082ac2aee7c858 | 35.146667 | 194 | 0.653633 | 4.875899 | false | false | false | false |
oneCup/MyWeiBo | MyWeiBoo/MyWeiBoo/Class/Module/Proflie/YFProfileController.swift | 1 | 3102 | //
// YFProfileController.swift
// MyWiBo
//
// Created by 李永方 on 15/10/7.
// Copyright © 2015年 李永方. All rights reserved.
//
import UIKit
class YFProfileController: YFBaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
VisitorView?.setUpViewInfo(false, imageNamed: "visitordiscover_image_profile", messageText: "登录后,你的微博、相册、个人资料会显示在这里,展示给别人")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 195e14aab4b4bd50125547756e2f873a | 31.945652 | 157 | 0.681623 | 5.336268 | false | false | false | false |
hollance/swift-algorithm-club | B-Tree/Tests/Tests/BTreeNodeTests.swift | 4 | 1440 | //
// BTreeNodeTests.swift
// BTree
//
// Created by Viktor Szilárd Simkó on 13/06/16.
// Copyright © 2016 Viktor Szilárd Simkó. All rights reserved.
//
import XCTest
class BTreeNodeTests: XCTestCase {
let owner = BTree<Int, Int>(order: 2)!
var root: BTreeNode<Int, Int>!
var leftChild: BTreeNode<Int, Int>!
var rightChild: BTreeNode<Int, Int>!
func testSwift4() {
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
}
override func setUp() {
super.setUp()
root = BTreeNode(owner: owner)
leftChild = BTreeNode(owner: owner)
rightChild = BTreeNode(owner: owner)
root.insert(1, for: 1)
root.children = [leftChild, rightChild]
}
func testIsLeafRoot() {
XCTAssertFalse(root.isLeaf)
}
func testIsLeafLeaf() {
XCTAssertTrue(leftChild.isLeaf)
XCTAssertTrue(rightChild.isLeaf)
}
func testOwner() {
XCTAssert(root.owner === owner)
XCTAssert(leftChild.owner === owner)
XCTAssert(rightChild.owner === owner)
}
func testNumberOfKeys() {
XCTAssertEqual(root.numberOfKeys, 1)
XCTAssertEqual(leftChild.numberOfKeys, 0)
XCTAssertEqual(rightChild.numberOfKeys, 0)
}
func testChildren() {
XCTAssertEqual(root.children!.count, 2)
}
}
| mit | 02d6cc700197a51c5673681f13c73f92 | 23.741379 | 63 | 0.594425 | 4.042254 | false | true | false | false |
STShenZhaoliang/Swift2Guide | Swift2Guide/Swift100Tips/Swift100Tips/CurryingController.swift | 1 | 2103 | //
// CurryingController.swift
// Swift100Tips
//
// Created by ST on 16/5/25.
// Copyright © 2016年 ST. All rights reserved.
//
import UIKit
class CurryingController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let addToFour = addTwoNumbers(4)
let result = addToFour(num: 6)
print(result)
let addTwo = addTo(2) // addTwo: Int -> Int
let result1 = addTwo(6) // result = 8
print(result1)
let greaterThan10 = greaterThan(10);
print( greaterThan10(13) ) // => true
print( greaterThan10(9) ) // => false
let greater1 = greaterThan1(10)
print(greater1(input: 13))
print(greater1(input: 9))
}
func addTwoNumbers(a: Int)(num: Int) -> Int {
return a + num
}
func addTo(adder: Int) -> Int -> Int {
return {
num in
return num + adder
}
}
func greaterThan(comparer: Int) -> Int -> Bool {
return { $0 > comparer }
}
func greaterThan1(comparer: Int) (input: Int) -> Bool {
return input > comparer
}
}
protocol TargetAction {
func performAction()
}
struct TargetActionWrapper<T: AnyObject>:
TargetAction {
weak var target: T?
let action: (T) -> () -> ()
func performAction() -> () {
if let t = target {
action(t)()
}
}
}
enum ControlEvent {
case TouchUpInside
case ValueChanged
// ...
}
class Control {
var actions = [ControlEvent: TargetAction]()
func setTarget<T: AnyObject>(target: T,
action: (T) -> () -> (),
controlEvent: ControlEvent) {
actions[controlEvent] = TargetActionWrapper(
target: target, action: action)
}
func removeTargetForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent] = nil
}
func performActionForControlEvent(controlEvent: ControlEvent) {
actions[controlEvent]?.performAction()
}
}
| mit | ce704f72370d94c8f00f81c4bfee2b9c | 20.649485 | 67 | 0.551905 | 4.259635 | false | false | false | false |
nodes-ios/Serpent | Serpent/SerpentTests/Models/NilTestModel.swift | 2 | 2554 | //
// NilTestModel.swift
// Serializable
//
// Created by Chris on 24/09/2016.
// Copyright © 2016 Nodes. All rights reserved.
//
import Foundation
import Serpent
public struct NilModel {
public enum NilModelType: Int {
case first = 0
case second = 1
}
var id: Int = 0
var name = SimpleModel()
var names = [SimpleModel]()
var url = URL(string: "http://www.google.com")!
var someEnum: NilModelType = .first
var someEnumArray: [NilModelType] = []
var somePrimitiveArray: [String] = []
var optionalId: Int?
var optionalName: SimpleModel?
var optionalNames: [SimpleModel]?
var optionalUrl: URL?
var optionalEnum: NilModelType?
var optionalEnumArray: [NilModelType]?
var optionalPrimitiveArray: [String]?
}
extension NilModel: Serializable {
public init(dictionary: NSDictionary?) {
id <== (self, dictionary, "id")
name <== (self, dictionary, "name")
names <== (self, dictionary, "names")
url <== (self, dictionary, "url")
someEnum <== (self, dictionary, "some_enum")
someEnumArray <== (self, dictionary, "some_enum_array")
somePrimitiveArray <== (self, dictionary, "some_primitive_array")
optionalId <== (self, dictionary, "optional_id")
optionalName <== (self, dictionary, "optional_name")
optionalNames <== (self, dictionary, "optional_names")
optionalUrl <== (self, dictionary, "optional_url")
optionalEnum <== (self, dictionary, "optional_enum")
optionalEnumArray <== (self, dictionary, "optional_enum_array")
optionalPrimitiveArray <== (self, dictionary, "optional_primitive_array")
}
public func encodableRepresentation() -> NSCoding {
let dict = NSMutableDictionary()
(dict, "id") <== id
(dict, "name") <== name
(dict, "names") <== names
(dict, "url") <== url
(dict, "some_enum") <== someEnum
(dict, "some_enum_array") <== someEnumArray
(dict, "some_primitive_array") <== somePrimitiveArray
(dict, "optional_id") <== optionalId
(dict, "optional_name") <== optionalName
(dict, "optional_names") <== optionalNames
(dict, "optional_url") <== optionalUrl
(dict, "optional_enum") <== optionalEnum
(dict, "optional_enum_array") <== optionalEnumArray
(dict, "optional_primitive_array") <== optionalPrimitiveArray
return dict
}
}
| mit | 285cf1073aa99d7fd6a341aed671b435 | 34.957746 | 75 | 0.591069 | 3.748899 | false | false | false | false |
justinmakaila/Moya | Tests/MoyaProvider+RxSpec.swift | 1 | 12296 | import Quick
import Nimble
import RxSwift
import OHHTTPStubs
@testable import Moya
@testable import RxMoya
final class MoyaProviderRxSpec: QuickSpec {
override func spec() {
describe("provider with Single") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub)
}
it("emits a Response object") {
var called = false
_ = provider.rx.request(.zen).subscribe { event in
switch event {
case .success: called = true
case .error(let error): fail("errored: \(error)")
}
}
expect(called).to(beTrue())
}
it("emits stubbed data for zen request") {
var responseData: Data?
let target: GitHub = .zen
_ = provider.rx.request(target).subscribe { event in
switch event {
case .success(let response): responseData = response.data
case .error(let error): fail("errored: \(error)")
}
}
expect(responseData).to(equal(target.sampleData))
}
it("maps JSON data correctly for user profile request") {
var receivedResponse: [String: Any]?
let target: GitHub = .userProfile("ashfurrow")
_ = provider.rx.request(target).asObservable().mapJSON().subscribe(onNext: { response in
receivedResponse = response as? [String: Any]
})
expect(receivedResponse).toNot(beNil())
}
}
describe("failing") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(endpointClosure: failureEndpointClosure, stubClosure: MoyaProvider.immediatelyStub)
}
it("emits the correct error message") {
var receivedError: MoyaError?
_ = provider.rx.request(.zen).subscribe { event in
switch event {
case .success: fail("should have errored")
case .error(let error): receivedError = error as? MoyaError
}
}
switch receivedError {
case .some(.underlying(let error, _)):
expect(error.localizedDescription) == "Houston, we have a problem"
default:
fail("expected an Underlying error that Houston has a problem")
}
}
it("emits an error") {
var errored = false
let target: GitHub = .zen
_ = provider.rx.request(target).subscribe { event in
switch event {
case .success: fail("we should have errored")
case .error: errored = true
}
}
expect(errored).to(beTrue())
}
}
describe("a reactive provider") {
var provider: MoyaProvider<GitHub>!
beforeEach {
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in
return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil)
})
provider = MoyaProvider<GitHub>(trackInflights: true)
}
it("emits identical response for inflight requests") {
let target: GitHub = .zen
let signalProducer1 = provider.rx.request(target)
let signalProducer2 = provider.rx.request(target)
expect(provider.inflightRequests.keys.count).to(equal(0))
var receivedResponse: Moya.Response!
_ = signalProducer1.subscribe { event in
switch event {
case .success(let response):
receivedResponse = response
expect(provider.inflightRequests.count).to(equal(1))
case .error(let error):
fail("errored: \(error)")
}
}
_ = signalProducer2.subscribe { event in
switch event {
case .success(let response):
expect(receivedResponse).toNot(beNil())
expect(receivedResponse).to(beIdenticalToResponse(response))
expect(provider.inflightRequests.count).to(equal(1))
case .error(let error):
fail("errored: \(error)")
}
}
// Allow for network request to complete
expect(provider.inflightRequests.count).toEventually(equal(0))
}
}
describe("a provider with progress tracking") {
var provider: MoyaProvider<GitHubUserContent>!
beforeEach {
//delete downloaded filed before each test
let directoryURLs = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
let file = directoryURLs.first!.appendingPathComponent("logo_github.png")
try? FileManager.default.removeItem(at: file)
//`responseTime(-4)` equals to 1000 bytes at a time. The sample data is 4000 bytes.
OHHTTPStubs.stubRequests(passingTest: {$0.url!.path.hasSuffix("logo_github.png")}, withStubResponse: { _ in
return OHHTTPStubsResponse(data: GitHubUserContent.downloadMoyaWebContent("logo_github.png").sampleData, statusCode: 200, headers: nil).responseTime(-4)
})
provider = MoyaProvider<GitHubUserContent>()
}
it("tracks progress of request") {
let target: GitHubUserContent = .downloadMoyaWebContent("logo_github.png")
let expectedNextProgressValues = [0.25, 0.5, 0.75, 1.0, 1.0]
let expectedNextResponseCount = 1
let expectedErrorEventsCount = 0
let expectedCompletedEventsCount = 1
let timeout = 5.0
var nextProgressValues: [Double] = []
var nextResponseCount = 0
var errorEventsCount = 0
var completedEventsCount = 0
_ = provider.rx.requestWithProgress(target)
.subscribe({ event in
switch event {
case let .next(element):
nextProgressValues.append(element.progress)
if element.response != nil { nextResponseCount += 1 }
case .error: errorEventsCount += 1
case .completed: completedEventsCount += 1
}
})
expect(completedEventsCount).toEventually(equal(expectedCompletedEventsCount), timeout: timeout)
expect(errorEventsCount).toEventually(equal(expectedErrorEventsCount), timeout: timeout)
expect(nextResponseCount).toEventually(equal(expectedNextResponseCount), timeout: timeout)
expect(nextProgressValues).toEventually(equal(expectedNextProgressValues), timeout: timeout)
}
describe("a custom callback queue") {
var stubDescriptor: OHHTTPStubsDescriptor!
beforeEach {
stubDescriptor = OHHTTPStubs.stubRequests(passingTest: {$0.url!.path == "/zen"}, withStubResponse: { _ in
return OHHTTPStubsResponse(data: GitHub.zen.sampleData, statusCode: 200, headers: nil)
})
}
afterEach {
OHHTTPStubs.removeStub(stubDescriptor)
}
describe("a provider with a predefined callback queue") {
var provider: MoyaProvider<GitHub>!
var callbackQueue: DispatchQueue!
var disposeBag: DisposeBag!
beforeEach {
disposeBag = DisposeBag()
callbackQueue = DispatchQueue(label: UUID().uuidString)
provider = MoyaProvider<GitHub>(callbackQueue: callbackQueue)
}
context("the callback queue is provided with the request") {
it("invokes the callback on the request queue") {
let requestQueue = DispatchQueue(label: UUID().uuidString)
var callbackQueueLabel: String?
waitUntil(action: { completion in
provider.rx.request(.zen, callbackQueue: requestQueue)
.subscribe(onSuccess: { _ in
callbackQueueLabel = DispatchQueue.currentLabel
completion()
}).disposed(by: disposeBag)
})
expect(callbackQueueLabel) == requestQueue.label
}
}
context("the queueless request method is invoked") {
it("invokes the callback on the provider queue") {
var callbackQueueLabel: String?
waitUntil(action: { completion in
provider.rx.request(.zen)
.subscribe(onSuccess: { _ in
callbackQueueLabel = DispatchQueue.currentLabel
completion()
}).disposed(by: disposeBag)
})
expect(callbackQueueLabel) == callbackQueue.label
}
}
}
describe("a provider without a predefined queue") {
var provider: MoyaProvider<GitHub>!
var disposeBag: DisposeBag!
beforeEach {
disposeBag = DisposeBag()
provider = MoyaProvider<GitHub>()
}
context("the queue is provided with the request") {
it("invokes the callback on the specified queue") {
let requestQueue = DispatchQueue(label: UUID().uuidString)
var callbackQueueLabel: String?
waitUntil(action: { completion in
provider.rx.request(.zen, callbackQueue: requestQueue)
.subscribe(onSuccess: { _ in
callbackQueueLabel = DispatchQueue.currentLabel
completion()
}).disposed(by: disposeBag)
})
expect(callbackQueueLabel) == requestQueue.label
}
}
context("the queue is not provided with the request") {
it("invokes the callback on the main queue") {
var callbackQueueLabel: String?
waitUntil(action: { completion in
provider.rx.request(.zen)
.subscribe(onSuccess: { _ in
callbackQueueLabel = DispatchQueue.currentLabel
completion()
}).disposed(by: disposeBag)
})
expect(callbackQueueLabel) == DispatchQueue.main.label
}
}
}
}
}
}
}
| mit | ae29e3dd6ecdbbee70eaec3b613d967f | 40.540541 | 172 | 0.482433 | 6.468175 | false | false | false | false |
everald/JetPack | Sources/Extensions/UIKit/CornerRadii.swift | 1 | 1442 | import CoreGraphics
public struct CornerRadii {
public var bottomLeft: CGFloat
public var bottomRight: CGFloat
public var topLeft: CGFloat
public var topRight: CGFloat
public static let zero = CornerRadii()
public init(all: CGFloat) {
self.init(topLeft: all, topRight: all, bottomRight: all, bottomLeft: all)
}
public init(bottom: CGFloat) {
self.init(top: 0, bottom: bottom)
}
public init(left: CGFloat) {
self.init(left: left, right: 0)
}
public init(left: CGFloat, right: CGFloat) {
self.init(topLeft: left, topRight: right, bottomRight: right, bottomLeft: left)
}
public init(right: CGFloat) {
self.init(left: 0, right: right)
}
public init(top: CGFloat) {
self.init(top: top, bottom: 0)
}
public init(top: CGFloat, bottom: CGFloat) {
self.init(topLeft: top, topRight: top, bottomRight: bottom, bottomLeft: bottom)
}
public init(topLeft: CGFloat = 0, topRight: CGFloat = 0, bottomRight: CGFloat = 0, bottomLeft: CGFloat = 0) {
self.bottomLeft = bottomLeft
self.bottomRight = bottomRight
self.topLeft = topLeft
self.topRight = topRight
}
public var isZero: Bool {
return bottomLeft == 0 && bottomRight == 0 && topLeft == 0 && topRight == 0
}
}
extension CornerRadii: Equatable {}
public func == (a: CornerRadii, b: CornerRadii) -> Bool {
return a.bottomLeft == b.bottomLeft && a.bottomRight == b.bottomRight && a.topLeft == b.topLeft && a.topRight == b.topRight
}
| mit | f528ee1c97c4191df6b66ac32dd53dd9 | 19.898551 | 124 | 0.691401 | 3.400943 | false | false | false | false |
douweh/RedditWallpaper | Wallpaper.swift | 1 | 2694 | //
// Wallpaper.swift
//
//
// Created by Douwe Homans on 12/6/15.
//
//
import Foundation
import CoreData
import UIKit
import Alamofire
class Wallpaper: NSManagedObject {
func loadImage(callback: (image: UIImage) -> Void){
// Check if we have a local path
if let localPath = path, let localImage = UIImage(contentsOfFile: localPath) {
print("returning local image")
callback(image: localImage)
return
}
// else download from server
else {
print("trying to fetch from server")
Alamofire.request(.GET, remoteUrl!)
.responseImage { response in
print("On main thread? \(NSThread.isMainThread())")
let localImage = response.result.value!
// callback with the downloaded image
callback(image:localImage)
// store file locally
let fileManager = NSFileManager();
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
print("Saving: On main thread? \(NSThread.isMainThread())")
do {
let cacheDir = try fileManager.URLForDirectory(NSSearchPathDirectory.CachesDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true)
let uuid = NSUUID().UUIDString
let filename = cacheDir.URLByAppendingPathComponent(uuid)
let localImageData = UIImagePNGRepresentation(localImage)
let saveCall = try localImageData?.writeToURL(filename, atomically: true)
// Let save happen on mainthread
dispatch_async(dispatch_get_main_queue(), {
do {
if let _ = saveCall {
self.path = filename.path
try self.managedObjectContext?.save()
}
} catch {
print(error)
}
});
} catch {
print(error)
}
})
}
return
}
// else callback with new empty UIImage
callback(image: UIImage())
}
}
| mit | eac7091e6f14279a0359940d60de7054 | 35.405405 | 200 | 0.454343 | 6.507246 | false | false | false | false |
gewill/Feeyue | Feeyue/Main/GWMainTabBarControllerConfig.swift | 1 | 3401 | //
// GWMainTabBarControllerConfig.swift
// Feeyue
//
// Created by BlaTrip on 16/10/2017.
// Copyright © 2017 Will. All rights reserved.
//
import UIKit
import CYLTabBarController
import QMUIKit
class JLXMainTabBarControllerConfig: NSObject {
lazy var aTabBarController: CYLTabBarController = {
var tabBarController = CYLTabBarController()
// 配置图片
let dict1: [AnyHashable: Any] = [
CYLTabBarItemTitle: "Weibo TL",
CYLTabBarItemImage: "Timeline",
CYLTabBarItemSelectedImage: "Timeline"
]
let dict2: [AnyHashable: Any] = [
CYLTabBarItemTitle: "Twitter TL",
CYLTabBarItemImage: "Twitter",
CYLTabBarItemSelectedImage: "Twitter"
]
let dict3: [AnyHashable: Any] = [
CYLTabBarItemTitle: "Lists",
CYLTabBarItemImage: "Lists",
CYLTabBarItemSelectedImage: "Lists"
]
let dict4: [AnyHashable: Any] = [
CYLTabBarItemTitle: "Me",
CYLTabBarItemImage: "Me",
CYLTabBarItemSelectedImage: "Me"
]
let tabBarItemsAttributes = [
dict1,
dict2,
dict3,
dict4
]
tabBarController.tabBarItemsAttributes = tabBarItemsAttributes
// 配置控制器
let vc1 = HomeViewController.create()
let vc2 = TwitterTimelineViewController.create()
let vc3 = ListsViewController.create()
let vc4 = MeViewController()
// Fix: QMUIKit hidesBottomBarWhenPushed default value is true
[vc1, vc2, vc3, vc4].forEach {
$0.hidesBottomBarWhenPushed = false
}
let nav1 = GWNavigationController(rootViewController: vc1)
let nav2 = GWNavigationController(rootViewController: vc2)
let nav3 = GWNavigationController(rootViewController: vc3)
let nav4 = GWNavigationController(rootViewController: vc4)
tabBarController.viewControllers = [nav1, nav2, nav3, nav4]
// 配置 tab bar 颜色
tabBarController.tabBar.barTintColor = themeColor()
tabBarController.tabBar.isHidden = false
// tabBarController.tabBar.tintColor = themeColor()
tabBarController.setTintColor(themeColor())
// 透明
// tabBarController.tabBar.backgroundImage = UIImage()
// let frost = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
// frost.frame = tabBarController.tabBar.bounds
// tabBarController.tabBar.insertSubview(frost, at: 0)
// 普通状态下的文字属性
let normalAttrs = [NSAttributedString.Key.foregroundColor: UIColor.init(hexString: "999999")]
// 选中状态下的文字属性
let selectedAttrs = [NSAttributedString.Key.foregroundColor: themeColor()]
var tabBar = UITabBarItem.appearance()
tabBar.setTitleTextAttributes(normalAttrs, for: .normal)
tabBar.setTitleTextAttributes(selectedAttrs, for: .selected)
return tabBarController
}()
}
extension CYLTabBarController {
// MARK: - orientation
override open var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .portrait
}
override open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
return .portrait
}
}
| mit | b43bf946c888f7f71daeeac3158a44aa | 32.979592 | 101 | 0.644144 | 4.98503 | false | false | false | false |
zwaldowski/ParksAndRecreation | Latest/NSView Layout Margins.playground/Contents.swift | 1 | 4896 | import Cocoa
import PlaygroundSupport
class InitialLiveViewController: NSViewController {
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: 120, height: 120))
let butt = NSButton(title: "Show Sheet", target: self, action: #selector(showSheet))
butt.frame = view.bounds
view.addSubview(butt)
}
@objc func showSheet(_ sender: Any) {
let vc = LayoutGuidesSheetViewController()
presentAsSheet(vc)
}
}
class LayoutGuidesSheetViewController: NSViewController {
override func loadView() {
view = NSView(frame: NSRect(x: 0, y: 0, width: 320, height: 480))
view.layoutMargins = NSEdgeInsets(top: 0, left: 120, bottom: 0, right: 120)
let redView = NSBox()
redView.translatesAutoresizingMaskIntoConstraints = false
redView.boxType = .custom
redView.fillColor = .red
redView.borderWidth = 0
view.addSubview(redView)
let redLabel = NSTextField(labelWithString: "Safe Area")
redLabel.translatesAutoresizingMaskIntoConstraints = false
redLabel.textColor = .white
redView.addSubview(redLabel)
let blueView = NSBox()
blueView.translatesAutoresizingMaskIntoConstraints = false
blueView.boxType = .custom
blueView.fillColor = .blue
blueView.borderWidth = 0
view.addSubview(blueView)
let blueLabel = NSTextField(labelWithString: "Layout Margins")
blueLabel.translatesAutoresizingMaskIntoConstraints = false
blueLabel.textColor = .white
blueView.addSubview(blueLabel)
let yellowView = NSBox()
yellowView.translatesAutoresizingMaskIntoConstraints = false
yellowView.boxType = .custom
yellowView.fillColor = .yellow
yellowView.borderWidth = 0
view.addSubview(yellowView)
let yellowLabel = NSTextField(wrappingLabelWithString: """
Readable Content
""")
yellowLabel.translatesAutoresizingMaskIntoConstraints = false
yellowLabel.textColor = .black
yellowLabel.alignment = .center
yellowView.addSubview(yellowLabel)
NSLayoutConstraint.activate([
// Bind the red view to the edges of the safe area.
redView.topAnchor.constraint(equalTo: view.windowContentLayoutGuide.topAnchor),
redView.leadingAnchor.constraint(equalTo: view.windowContentLayoutGuide.leadingAnchor),
view.windowContentLayoutGuide.bottomAnchor.constraint(equalTo: redView.bottomAnchor),
view.windowContentLayoutGuide.trailingAnchor.constraint(equalTo: redView.trailingAnchor),
// Bind the red view's label to the left, vertically centered.
redLabel.leadingAnchor.constraint(equalTo: redView.leadingAnchor, constant: 8),
redLabel.topAnchor.constraint(greaterThanOrEqualTo: redView.topAnchor, constant: 8),
redLabel.centerYAnchor.constraint(equalTo: redView.centerYAnchor),
// Bind the blue view to the edges of the layout margins.
blueView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor),
blueView.leadingAnchor.constraint(equalTo: view.layoutMarginsGuide.leadingAnchor),
view.layoutMarginsGuide.bottomAnchor.constraint(equalTo: blueView.bottomAnchor),
view.layoutMarginsGuide.trailingAnchor.constraint(equalTo: blueView.trailingAnchor),
// Bind the blue view's label to the left, vertically centered.
blueLabel.leadingAnchor.constraint(equalTo: blueView.leadingAnchor, constant: 8),
blueLabel.topAnchor.constraint(greaterThanOrEqualTo: blueView.topAnchor, constant: 8),
blueLabel.centerYAnchor.constraint(equalTo: blueView.centerYAnchor),
// Bind the yellow view to the edges of the readable content.
yellowView.topAnchor.constraint(equalTo: view.readableContentGuide.topAnchor),
yellowView.leadingAnchor.constraint(equalTo: view.readableContentGuide.leadingAnchor),
view.readableContentGuide.bottomAnchor.constraint(equalTo: yellowView.bottomAnchor),
view.readableContentGuide.trailingAnchor.constraint(equalTo: yellowView.trailingAnchor),
// Bind the yellow view's label to the center.
yellowLabel.leadingAnchor.constraint(greaterThanOrEqualTo: yellowView.leadingAnchor, constant: 8),
yellowLabel.topAnchor.constraint(greaterThanOrEqualTo: yellowView.topAnchor, constant: 8),
yellowLabel.centerXAnchor.constraint(equalTo: yellowView.centerXAnchor),
yellowLabel.centerYAnchor.constraint(equalTo: yellowView.centerYAnchor),
])
}
@objc func cancel(_ sender: Any?) {
presentingViewController?.dismiss(self)
}
}
PlaygroundPage.current.liveView = InitialLiveViewController()
| mit | bd73335429e32502f72728b3d0338c82 | 43.917431 | 110 | 0.701593 | 5.452116 | false | false | false | false |
longminxiang/MixCache | MixCacheDemo/ViewController.swift | 1 | 1613 | //
// ViewController.swift
// MixCacheDemo
//
// Created by Eric Long on 2021/9/15.
// Copyright © 2021 Eric Lung. All rights reserved.
//
import UIKit
import MixCache
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.view.backgroundColor = UIColor.white
MixKeychainCache.shared.debug = true
var key = "intkey"
MixCache.keychain.set(123, key: key)
let obj: Int? = MixCache.keychain.get(key)
if (obj == nil) {
print("obj faild")
}
MixCache.keychain.set(234, key: key)
let obj11: Int? = MixCache.keychain.get(key)
if (obj11 == nil) {
print("obj11 faild")
}
let obj1: Float? = MixCache.keychain.get(key)
if (obj1 == nil) {
print("obj1 faild")
}
MixCache.keychain.remove(key)
let obj12: Int? = MixCache.keychain.get(key)
if (obj12 == nil) {
print("obj12 nil")
}
key = "stringkey"
MixCache.keychain.set("123", key: key)
let obj2: String? = MixCache.keychain.get(key)
if (obj2 == nil) {
print("obj2 faild")
}
key = "arraykey"
MixCache.keychain.set(["123", "ddd", Date(), NSUUID(), NSURL(string: "https://baidu.com")!], key: key)
if let obj3: [Any] = MixCache.keychain.get(key) {
print(obj3)
}
else {
print("obj3 faild")
}
}
}
| mit | d77238b4843810227fea4536e6e8ad08 | 25 | 110 | 0.527295 | 3.748837 | false | false | false | false |
lieonCX/Live | Live/View/Main/TabBar.swift | 1 | 1419 | //
// TabBar.swift
// Live
//
// Created by lieon on 2017/6/22.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import UIKit
class TabBar: UITabBar {
lazy var centerBtn: UIButton = {
let centerBtn = UIButton()
centerBtn.setImage(UIImage(named: "tab_launch"), for: .normal)
centerBtn.setImage(UIImage(named: "tab_launch"), for: .highlighted)
centerBtn.imageView?.contentMode = .center
centerBtn.sizeToFit()
return centerBtn
}()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(centerBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
centerBtn.frame.origin.x = frame.width / 3
centerBtn.frame.origin.y = frame.height - centerBtn.frame.height - 10
centerBtn.frame.size.width = frame.width / 3
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if !isHidden {
let pointInCenter = self.convert(point, to: centerBtn)
if centerBtn.point(inside: pointInCenter, with: event) {
return centerBtn
}
return super.hitTest(point, with: event)
}
return super.hitTest(point, with: event)
}
}
| mit | 62eaf33054cbd25adc38ca58de8a1cc1 | 27.897959 | 78 | 0.602401 | 4.356923 | false | true | false | false |
Colormark/BLButton | BLButton.swift | 1 | 4847 | //
// BLButton.swift
//
// Created by FangYan on 15/12/14.
// Copyright © 2015年 yousi.inc. All rights reserved.
//
import UIKit
//主题
enum YSButtonTheme:Int {
case Primary = 0
case PrimaryLight = 1
case LineDark = 2
case Disabled = 3
case Warning = 4
}
//大小
enum YSButtonSize:Int {
case Large = 0
case Normal = 1
case Small = 2
}
//模型
enum YSButtonModal:Int {
case Hollow = 0
case Solid = 1
}
//圆角
enum YSButtonRadius:Int {
case None = 0
case Tiny = 1
case Normal = 2
case Half = 3
case All = 4
}
@IBDesignable
public class BLButton: UIButton {
@IBInspectable var theme : Int = 0 {
didSet {
commonInit()
}
}
@IBInspectable var size : Int = 0 {
didSet {
commonInit()
}
}
@IBInspectable var modal : Int = 0 {
didSet {
commonInit()
}
}
@IBInspectable var radius : Int = 0 {
didSet {
commonInit()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func initWith (theme:YSButtonTheme , size:YSButtonSize , modal:YSButtonModal , radius:YSButtonRadius){
if theme.rawValue > -1 {
self.theme = theme.rawValue
}
}
func commonInit (){
if self.size == 0 {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - (UI.ButtonSize["SM"]! - self.frame.size.height)/2, self.frame.size.width, UI.ButtonSize["SM"]!)
self.titleLabel?.font = UIFont.systemFontOfSize(UI.TextSize["XS"]!)
} else if self.size == 1 {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - (UI.ButtonSize["Normal"]! - self.frame.size.height)/2, self.frame.size.width, UI.ButtonSize["Normal"]!)
self.titleLabel?.font = UIFont.systemFontOfSize(UI.TextSize["Normal"]!)
} else if self.size == 2 {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y - (UI.ButtonSize["LG"]! - self.frame.size.height)/2, self.frame.size.width, UI.ButtonSize["LG"]!)
self.titleLabel?.font = UIFont.systemFontOfSize(UI.TextSize["XL"]!)
}
if self.modal == 0 {
self.layer.borderWidth = 1
self.layer.backgroundColor = UIColor.clearColor().CGColor
if self.theme == 0 {
self.layer.borderColor = UI.Color["primary"]?.CGColor
self.setTitleColor(UI.Color["primary"]!, forState:.Normal)
}else if self.theme == 1 {
self.layer.borderColor = UI.Color["primaryLight"]?.CGColor
self.setTitleColor(UI.Color["primaryLight"]!, forState:.Normal)
}else if self.theme == 2 {
self.layer.borderColor = UI.Color["lineDark"]?.CGColor
self.setTitleColor(UI.Color["lineDark"]!, forState:.Normal)
}else if self.theme == 3 {
self.layer.borderColor = UI.Color["black3"]?.CGColor
self.setTitleColor(UI.Color["black3"]!, forState:.Normal)
}else if self.theme == 4 {
self.layer.borderColor = UI.Color["warning"]?.CGColor
self.setTitleColor(UI.Color["warning"]!, forState:.Normal)
}
}else if self.modal == 1 {
self.layer.borderWidth = 0
self.setTitleColor(UI.Color["white"]!, forState:.Normal)
if self.theme == 0 {
self.layer.backgroundColor = UI.Color["primary"]?.CGColor
}else if self.theme == 1 {
self.layer.backgroundColor = UI.Color["primaryLight"]?.CGColor
}else if self.theme == 2 {
self.layer.backgroundColor = UI.Color["lineDark"]?.CGColor
}else if self.theme == 3 {
self.layer.backgroundColor = UI.Color["black3"]?.CGColor
}else if self.theme == 4 {
self.layer.borderColor = UI.Color["warning"]?.CGColor
self.setTitleColor(UI.Color["warning"]!, forState:.Normal)
}
}
if self.radius == 0 {
self.layer.cornerRadius = 0
}else if self.radius == 1 {
self.layer.cornerRadius = self.frame.size.height / 8
}else if self.radius == 2 {
self.layer.cornerRadius = self.frame.size.height / 5
}else if self.radius == 3 {
self.layer.cornerRadius = self.frame.size.height / 2
}else if self.radius == 4 {
self.layer.cornerRadius = self.frame.size.height
}
}
}
| mit | b06db423bbe7eebf2a11dd280971ebc1 | 30.97351 | 182 | 0.549089 | 4.212914 | false | false | false | false |
lorentey/swift | test/IRGen/weak_import_native.swift | 5 | 10256 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path %t/weak_import_native_helper.swiftmodule -parse-as-library %S/Inputs/weak_import_native_helper.swift -enable-library-evolution
//
// RUN: %target-swift-frontend -primary-file %s -I %t -emit-ir | %FileCheck %s
// UNSUPPORTED: OS=windows-msvc
import weak_import_native_helper
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper23ProtocolWithWeakMembersP1TAC_AA05OtherE0Tn" = extern_weak global %swift.protocol_requirement
// CHECK-DAG-LABEL: @"$s1T25weak_import_native_helper23ProtocolWithWeakMembersPTl" = extern_weak global %swift.protocol_requirement
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper23ProtocolWithWeakMembersP1fyyFTq" = extern_weak global %swift.method_descriptor
// CHECK-DAG-LABEL: declare extern_weak swiftcc void @"$s25weak_import_native_helper23ProtocolWithWeakMembersPAAE1fyyF"(%swift.type*, i8**, %swift.opaque* noalias nocapture swiftself)
struct ConformsToProtocolWithWeakMembers : ProtocolWithWeakMembers {}
func testTopLevel() {
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper2fnyyF"()
fn()
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper12globalStoredSivg"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper12globalStoredSivs"
let x = globalStored
globalStored = x
globalStored += 1
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper14globalComputedSivg"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper14globalComputedSivs"
let y = globalComputed
globalComputed = y
globalComputed += 1
}
func testStruct() {
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SVACycfC"
var s = S()
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV2fnyyF"
s.fn()
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV10storedPropSivg"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV10storedPropSivs"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV10storedPropSivM"
let x = s.storedProp
s.storedProp = x
s.storedProp += 1
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV12computedPropSivg"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV12computedPropSivs"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SV12computedPropSivM"
let y = s.computedProp
s.computedProp = y
s.computedProp += 1
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SVyS2icig"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SVyS2icis"
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1SVyS2iciM"
let z = s[0]
s[0] = z
s[0] += 1
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper5WeakSV0A6MemberyyF"
let w = WeakS()
w.weakMember()
}
func testEnum() {
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper1EO6strongyA2CmFWC" = external constant i32
_ = E.strong
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper1EO0A0yA2CmFWC" = extern_weak constant i32
_ = E.weak
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper1EO11strongAssocyACSicACmFWC" = external constant i32
_ = E.strongAssoc(0)
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper1EO0A5AssocyACSicACmFWC" = extern_weak constant i32
_ = E.weakAssoc(0)
}
func testClass() {
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1CCACycfC"
let c = C()
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1CC2fnyyFTj"
c.fn()
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC10storedPropSivgTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC10storedPropSivsTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC10storedPropSivMTj"
let x = c.storedProp
c.storedProp = x
c.storedProp += 1
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC12computedPropSivgTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC12computedPropSivsTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CC12computedPropSivMTj"
let y = c.computedProp
c.computedProp = y
c.computedProp += 1
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CCyS2icigTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CCyS2icisTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1CCyS2iciMTj"
let z = c[0]
c[0] = z
c[0] += 1
}
class Sub : C {
deinit {
// This is correctly a strong symbol reference; the class is not declared
// weak.
// CHECK-DAG-LABEL: declare swiftcc {{.+}} @"$s25weak_import_native_helper1CCfd"
}
}
func testProtocolExistential(_ p: P) {
var mutP = p
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1PP2fnyyFTj"
p.fn()
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PP4propSivgTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PP4propSivsTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PP4propSivMTj"
let x = p.prop
mutP.prop = x
mutP.prop += 1
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PPyS2icigTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PPyS2icisTj"
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper1PPyS2iciMTj"
let z = p[0]
mutP[0] = z
mutP[0] += 1
}
func testProtocolGeneric<Impl: P>(_ type: Impl.Type) {
// CHECK-DAG-LABEL: declare extern_weak {{.+}} @"$s25weak_import_native_helper1PPxycfCTj"
var mutP = type.init()
mutP.fn()
let x = mutP.prop
mutP.prop = x
mutP.prop += 1
let z = mutP[0]
mutP[0] = z
mutP[0] += 1
}
func testWeakTypes() -> [Any.Type] {
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper5WeakSVMa"
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper5WeakEOMa"
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper5WeakCCMa"
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper5WeakPMp" = extern_weak global %swift.protocol
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper8GenericSVMa"
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper8GenericEOMa"
// CHECK-DAG-LABEL: declare extern_weak swiftcc %swift.metadata_response @"$s25weak_import_native_helper8GenericCCMa"
return [WeakS.self, WeakE.self, WeakC.self, WeakP.self, GenericS<Int>.self, GenericE<Int>.self, GenericC<Int>.self]
}
class WeakSub: WeakC {
deinit {
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper5WeakCCfd"
}
}
class WeakGenericSub: GenericC<Int> {
deinit {
// CHECK-DAG-LABEL: declare extern_weak swiftcc {{.+}} @"$s25weak_import_native_helper8GenericCCfd"
}
}
protocol RefinesP : BaseP {}
// CHECK-DAG-LABEL: @"$s25weak_import_native_helper1SVAA5BasePAAWP" = extern_weak global i8*
extension S : RefinesP {}
// We should not hoist the metadata accessor accross the version check.
// CHECK-LABEL: define{{.*}} void @"$s18weak_import_native28test_not_hoist_weakly_linkedyyF"()
// CHECK-NOT: 15ResilientStructVMa
// CHECK: getVersion
// CHECK: br
// CHECK: 15ResilientStructVMa
// CHECK: ret
public func test_not_hoist_weakly_linked() {
if getVersion() == 1 {
var _ = ResilientStruct()
}
}
// CHECK-LABEL: define{{.*}} void @"$s18weak_import_native29test_not_hoist_weakly_linked2yyF"()
// CHECK-NOT: 15ResilientStructVMa
// CHECK: getVersion
// CHECK: br
// CHECK: 15ResilientStructVMa
// CHECK: ret
public func test_not_hoist_weakly_linked2() {
if getVersion() == 1 {
var _ = (ResilientStruct(), 1)
}
}
struct One<T> {
var elt : T?
}
// CHECK-LABEL: define{{.*}} void @"$s18weak_import_native29test_not_hoist_weakly_linked3yyF"()
// CHECK-NOT: 15ResilientStructVMa
// CHECK: getVersion
// CHECK: br
// CHECK: 15ResilientStructVMa
// CHECK: ret
public func test_not_hoist_weakly_linked3() {
if getVersion() == 1 {
var _ = One(elt:ResilientStruct())
}
}
// CHECK-LABEL: define{{.*}} void @"$s18weak_import_native29test_not_hoist_weakly_linked4yyF"()
// CHECK-NOT: 15ResilientStructVMa
// CHECK: getVersion
// CHECK: br
// CHECK: 15ResilientStructVMa
// CHECK: ret
public func test_not_hoist_weakly_linked4() {
if getVersion() == 1 {
var _ = One(elt:(ResilientStruct(), 1))
}
}
// CHECK-LABEL: define{{.*}} @"$s18weak_import_native29test_weakly_linked_enum_cases1eSi0a1_b1_C7_helper1EO_t
// CHECK: [[TAG:%.*]] = call i32 %getEnumTag(
// CHECK: [[STRONG_CASE:%.*]] = load i32, i32* @"$s25weak_import_native_helper1EO6strongyA2CmFWC"
// CHECK: [[IS_STRONG:%.*]] = icmp eq i32 [[TAG]], [[STRONG_CASE]]
// CHECK: br i1 [[IS_STRONG]], label %[[BB0:[0-9]+]], label %[[BB1:[0-9]+]]
//
// CHECK: [[BB1]]:
// CHECK: br i1 icmp eq ({{.*}} ptrtoint (i32* @"$s25weak_import_native_helper1EO0A0yA2CmFWC" to {{.*}}), {{.*}} 0), label %[[BB2:[0-9]+]], label %[[BB3:[0-9]+]]
//
// CHECK: [[BB3]]:
// CHECK: [[WEAK_CASE:%.*]] = load i32, i32* @"$s25weak_import_native_helper1EO0A0yA2CmFWC"
// CHECK: [[IS_WEAK:%.*]] = icmp eq i32 [[TAG]], [[WEAK_CASE]]
// CHECK: br label %[[BB2]]
//
// CHECK: [[BB2]]:
// CHECK: = phi i1 [ false, %[[BB1]] ], [ [[IS_WEAK]], %[[BB3]] ]
public func test_weakly_linked_enum_cases(e: E) -> Int {
switch e {
case .strong:
return 1
case .weak:
return 2
default:
return 3
}
}
| apache-2.0 | fa695f03c8cfd79045727a6db1ec6788 | 38.295019 | 188 | 0.69452 | 3.180155 | false | true | false | false |
lorentey/swift | test/SILGen/Inputs/vtables_multifile_2.swift | 4 | 9000 | open class OtherDerived : Derived {
internal override func privateMethod1() {
super.privateMethod1()
}
internal override func privateMethod2(_ arg: AnyObject?) {
super.privateMethod2(arg)
}
internal override func privateMethod3(_ arg: Int?) {
super.privateMethod3(arg)
}
internal override func privateMethod4(_ arg: Int) {
super.privateMethod4(arg)
}
}
// --
// Super method calls directly reference the superclass method
// --
// CHECK-LABEL: sil hidden [ossa] @$s17vtables_multifile12OtherDerivedC14privateMethod1yyF : $@convention(method) (@guaranteed OtherDerived) -> () {
// CHECK: bb0(%0 : @guaranteed $OtherDerived):
// CHECK: [[SELF:%.*]] = copy_value %0 : $OtherDerived
// CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF]] : $OtherDerived to $Derived
// CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile7DerivedC14privateMethod1yyF : $@convention(method) (@guaranteed Derived) -> () // user: %5
// CHECK-NEXT: apply [[METHOD:%.*]]([[SUPER]]) : $@convention(method) (@guaranteed Derived) -> ()
// CHECK-NEXT: destroy_value [[SUPER]] : $Derived
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT:}
// CHECK-LABEL: sil hidden_external @$s17vtables_multifile7DerivedC14privateMethod1yyF : $@convention(method) (@guaranteed Derived) -> ()
// CHECK-LABEL: sil hidden [ossa] @$s17vtables_multifile12OtherDerivedC14privateMethod2yyyXlSgF : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed OtherDerived) -> () {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $OtherDerived):
// CHECK: [[SELF:%.*]] = copy_value %1 : $OtherDerived
// CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF]] : $OtherDerived to $Derived
// CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgF : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT: apply [[METHOD]](%0, [[SUPER]]) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT: destroy_value [[SUPER]] : $Derived
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden_external @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgF : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK: bb0(%0 : $Optional<Int>, %1 : @guaranteed $OtherDerived):
// CHECK: [[SELF:%.*]] = copy_value %1 : $OtherDerived
// CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF]] : $OtherDerived to $Derived
// CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile7DerivedC14privateMethod3yySiSgF : $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT: apply [[METHOD]](%0, [[SUPER]]) : $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT: destroy_value [[SUPER]] : $Derived
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden_external @$s17vtables_multifile7DerivedC14privateMethod3yySiSgF : $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $OtherDerived):
// CHECK: [[SELF:%.*]] = copy_value %1 : $OtherDerived
// CHECK-NEXT: [[SUPER:%.*]] = upcast [[SELF]] : $OtherDerived to $Derived
// CHECK: [[METHOD:%.*]] = function_ref @$s17vtables_multifile7DerivedC14privateMethod4yySiF : $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT: apply [[METHOD]](%0, [[SUPER]]) : $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT: destroy_value [[SUPER]] : $Derived
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil hidden_external @$s17vtables_multifile7DerivedC14privateMethod4yySiF : $@convention(method) (Int, @guaranteed Derived) -> ()
// --
// VTable thunks for methods of Base redispatch to methods of Derived
// --
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV : $@convention(method) (@guaranteed Derived) -> () {
// CHECK: bb0(%0 : @guaranteed $Derived):
// CHECK-NEXT: [[METHOD:%.*]] = class_method %0 : $Derived, #Derived.privateMethod1!1 : (Derived) -> () -> (), $@convention(method) (@guaranteed Derived) -> ()
// CHECK-NEXT: apply [[METHOD]](%0) : $@convention(method) (@guaranteed Derived) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : @guaranteed $Optional<AnyObject>, %1 : @guaranteed $Derived):
// CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod2!1 : (Derived) -> (AnyObject?) -> (), $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT: apply [[METHOD]](%0, %1) : $@convention(method) (@guaranteed Optional<AnyObject>, @guaranteed Derived) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV : $@convention(method) (Int, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : $Int, %1 : @guaranteed $Derived):
// CHECK-NEXT: [[ARG:%.*]] = enum $Optional<Int>, #Optional.some!enumelt.1, %0 : $Int
// CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod3!1 : (Derived) -> (Int?) -> (), $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Optional<Int>, @guaranteed Derived) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil private [thunk] [ossa] @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV : $@convention(method) (@in_guaranteed Int, @guaranteed Derived) -> () {
// CHECK: bb0(%0 : $*Int, %1 : @guaranteed $Derived):
// CHECK-NEXT: [[ARG:%.*]] = load [trivial] %0 : $*Int
// CHECK-NEXT: [[METHOD:%.*]] = class_method %1 : $Derived, #Derived.privateMethod4!1 : (Derived) -> (Int) -> (), $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT: apply %3(%2, %1) : $@convention(method) (Int, @guaranteed Derived) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
// CHECK-LABEL: sil_vtable [serialized] OtherDerived {
// CHECK-NEXT: #Base.privateMethod1!1: <T> (Base<T>) -> () -> () : @$s17vtables_multifile7DerivedC14privateMethod1yyFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyFTV [inherited] // vtable thunk for Base.privateMethod1() dispatching to Derived.privateMethod1()
// CHECK-NEXT: #Base.privateMethod2!1: <T> (Base<T>) -> (AnyObject) -> () : @$s17vtables_multifile7DerivedC14privateMethod2yyyXlSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyyXlFTV [inherited] // vtable thunk for Base.privateMethod2(_:) dispatching to Derived.privateMethod2(_:)
// CHECK-NEXT: #Base.privateMethod3!1: <T> (Base<T>) -> (Int) -> () : @$s17vtables_multifile7DerivedC14privateMethod3yySiSgFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyySiFTV [inherited] // vtable thunk for Base.privateMethod3(_:) dispatching to Derived.privateMethod3(_:)
// CHECK-NEXT: #Base.privateMethod4!1: <T> (Base<T>) -> (T) -> () : @$s17vtables_multifile7DerivedC14privateMethod4yySiFAA4BaseCAD33_63E5F2521A3C787F5F9EFD57FB9237EALLyyxFTV [inherited] // vtable thunk for Base.privateMethod4(_:) dispatching to Derived.privateMethod4(_:)
// CHECK-NEXT: #Base.init!allocator.1: <T> (Base<T>.Type) -> () -> Base<T> : @$s17vtables_multifile12OtherDerivedCACycfC [override] // OtherDerived.__allocating_init()
// CHECK-NEXT: #Derived.privateMethod1!1: (Derived) -> () -> () : @$s17vtables_multifile12OtherDerivedC14privateMethod1yyF [override] // OtherDerived.privateMethod1()
// CHECK-NEXT: #Derived.privateMethod2!1: (Derived) -> (AnyObject?) -> () : @$s17vtables_multifile12OtherDerivedC14privateMethod2yyyXlSgF [override] // OtherDerived.privateMethod2(_:)
// CHECK-NEXT: #Derived.privateMethod3!1: (Derived) -> (Int?) -> () : @$s17vtables_multifile12OtherDerivedC14privateMethod3yySiSgF [override] // OtherDerived.privateMethod3(_:)
// CHECK-NEXT: #Derived.privateMethod4!1: (Derived) -> (Int) -> () : @$s17vtables_multifile12OtherDerivedC14privateMethod4yySiF [override] // OtherDerived.privateMethod4(_:)
// CHECK-NEXT: #OtherDerived.deinit!deallocator.1: @$s17vtables_multifile12OtherDerivedCfD // OtherDerived.__deallocating_deinit
// CHECK-NEXT:}
| apache-2.0 | af16b21d4bf50812f42da030cbbadf04 | 75.923077 | 292 | 0.681222 | 3.469545 | false | false | false | false |
rexmas/Crust | CrustTests/Company.swift | 1 | 3955 | import Crust
import Foundation
class Company {
required init() { }
var employees = [Employee]()
var uuid: String = ""
var name: String = ""
var foundingDate: Date = Date()
var founder: Employee?
var pendingLawsuits: Int = 0
}
extension Company: AnyMappable { }
enum CompanyCodingKey: MappingKey {
case uuid
case employees(Set<EmployeeCodingKey>)
case founder
case name
case foundingDate
case pendingLawsuits
var keyPath: String {
switch self {
case .uuid: return "data.uuid"
case .employees(_): return "employees"
case .founder: return "founder"
case .name: return "name"
case .foundingDate: return "data.founding_date"
case .pendingLawsuits: return "data.lawsuits.pending"
}
}
func nestedMappingKeys<Key: MappingKey>() -> AnyKeyCollection<Key>? {
switch self {
case .employees(let employeeKeys):
return employeeKeys.anyKeyCollection()
default:
return nil
}
}
}
class CompanyMapping: Mapping {
var adapter: MockAdapter<Company>
var primaryKeys: [Mapping.PrimaryKeyDescriptor]? {
return [ ("uuid", "data.uuid", nil) ]
}
required init(adapter: MockAdapter<Company>) {
self.adapter = adapter
}
func mapping(toMap: inout Company, payload: MappingPayload<CompanyCodingKey>) {
let employeeMapping = EmployeeMapping(adapter: MockAdapter<Employee>())
toMap.employees <- (.mapping(.employees([]), employeeMapping), payload)
toMap.founder <- (.mapping(.founder, employeeMapping), payload)
toMap.uuid <- (.uuid, payload)
toMap.name <- (.name, payload)
toMap.foundingDate <- (.foundingDate, payload)
toMap.pendingLawsuits <- (.pendingLawsuits, payload)
}
}
class CompanyMappingWithDupes: CompanyMapping {
override func mapping(toMap: inout Company, payload: MappingPayload<CompanyCodingKey>) {
let employeeMapping = EmployeeMapping(adapter: MockAdapter<Employee>())
toMap.employees <- (.collectionMapping(.employees([]), employeeMapping, (.append, true, true)), payload)
toMap.founder <- (.mapping(.founder, employeeMapping), payload)
toMap.uuid <- (.uuid, payload)
toMap.name <- (.name, payload)
toMap.foundingDate <- (.foundingDate, payload)
toMap.pendingLawsuits <- (.pendingLawsuits, payload)
}
}
class CompanyWithOptionalEmployees {
required init() { }
var employees: [Employee]? = nil
var uuid: String = ""
var name: String = ""
var foundingDate: Date = Date()
var founder: Employee?
var pendingLawsuits: Int = 0
}
extension CompanyWithOptionalEmployees: AnyMappable { }
class CompanyWithOptionalEmployeesMapping: Mapping {
var adapter: MockAdapter<CompanyWithOptionalEmployees>
var primaryKeys: [Mapping.PrimaryKeyDescriptor]? {
return [ ("uuid", "data.uuid", nil) ]
}
required init(adapter: MockAdapter<CompanyWithOptionalEmployees>) {
self.adapter = adapter
}
func mapping(toMap: inout CompanyWithOptionalEmployees, payload: MappingPayload<CompanyCodingKey>) {
let employeeMapping = EmployeeMapping(adapter: MockAdapter<Employee>())
toMap.employees <- (.mapping(.employees([]), employeeMapping), payload)
toMap.founder <- (.mapping(.founder, employeeMapping), payload)
toMap.uuid <- (.uuid, payload)
toMap.name <- (.name, payload)
toMap.foundingDate <- (.foundingDate, payload)
toMap.pendingLawsuits <- (.pendingLawsuits, payload)
}
}
| mit | 6275c30f364f0b242edfecec0cb6f6f2 | 32.235294 | 124 | 0.602781 | 4.463883 | false | false | false | false |
pietrocaselani/Trakt-Swift | Trakt/Trakt+Constants.swift | 1 | 700 | import Foundation
extension Trakt {
public static let baseURL = URL(string: "https://\(Trakt.apiHost)")!
public static let siteURL = URL(string: "https://trakt.tv")!
static let OAuth2AuthorizationPath = "/oauth/authorize"
static let OAuth2TokenPath = "/oauth/token"
static let headerAuthorization = "Authorization"
static let headerContentType = "Content-type"
static let headerTraktAPIKey = "trakt-api-key"
static let headerTraktAPIVersion = "trakt-api-version"
static let contentTypeJSON = "application/json"
static let apiVersion = "2"
static let apiHost = "api.trakt.tv"
static let accessTokenKey = "trakt_token"
static let accessTokenDateKey = "trakt_token_date"
}
| unlicense | 865bd9c794dd02390014fb63cc01ff03 | 32.333333 | 70 | 0.742857 | 4.022989 | false | false | false | false |
duck57/Swift-Euchre | Swift Euchre/Table.swift | 1 | 3118 | //
// Table.swift
// Swift Euchre
//
// Created by Chris Matlak on 12/15/15.
// Copyright © 2015 Euchre US!. All rights reserved.
//
import Foundation
class Table {
var Players: [Player] = []
var score: [Int] = []
var deck: Deck
var trick: Trick?
var kitty: Hand?
var trumpSuit: Suit?
let winningScore: Int
let losingScore: Int
let terminalScore: Int
var dealerPos: Int = 0
var leadPos: Int = 0
var winningBid: [Int] = []
var scoringMethod: Int = 5 // default to Hi-No
init(gameType: deckType, winningScore wScore: Int, losingScore lScore: Int, terminalScore tScore: Int) {
deck = gameType.makeDeck()
winningScore = wScore
losingScore = lScore
terminalScore = tScore
score = [0, 0] // replace this with something better (that can handle 3-player games) later
trick = Trick.init()
}
func deal() {
deck.deal(Players)
for var player in Players {
player.sort()
}
}
func callTrump(lead: Player?=nil) {
//replace the beginning with the player calling trump
let trump = Int(arc4random_uniform(6))
scoringMethod = trump
trumpSuit = Suit(rawValue: trump)
for var player in self.Players {
player.hand.convertToTrump(trumpSuit!)
player.sort()
}
}
func playGame() {
dealerPos = randomPlayer()
while scoreInRange() {
playHand(dealerPos)
scoreHand()
nextDealer()
}
}
func scoreHand() {
let biddingTeam = winningBid[1] % 2
if Players[biddingTeam].tricks + Players[biddingTeam+2].tricks < winningBid[0] {
score[biddingTeam] = score[biddingTeam] - winningBid[0]
} else {
score[biddingTeam] = score[biddingTeam] + winningBid[0] + 2
}
}
func playHand(dealerPos: Int) {
deal()
biddingSequence(dealerPos)
for _ in Players[leadPos].hand {
playTrick()
}
}
func playTrick() {
for loc in 0..<Players.count {
trick!.append(Players[(leadPos+loc)%Players.count].playCard())
}
let winPos = trick!.score(scoringMethod == 0)
leadPos = (leadPos + winPos) % Players.count
Players[leadPos].tricks += 1
trick!.empty(deck)
}
func biddingSequence(dealerPos: Int) {
leadPos = randomPlayer() // replace this later
callTrump()
winningBid = [Int(arc4random_uniform(12)), leadPos]
if winningBid[0] < 6 {
winningBid[0] = 6
}
}
func nextDealer() {
dealerPos = nextPlayer(currentPlayer: dealerPos)
}
func randomPlayer() -> Int {
return Int(arc4random_uniform(UInt32(Players.count)))
}
func nextPlayer(currentPlayer cp: Int) -> Int {
return (cp + 1) % Players.count
}
func scoreInRange() -> Bool {
if score.maxElement() > winningScore {
return false // end game if someone won
}
if score.minElement() < losingScore {
return false // end game if someone lost
}
for teamScore in score {
if teamScore > terminalScore {
return true
}
}
return false // end game if all teams have significant negative scores
}
}
extension Array {
func forEach(doThis: (element: Element) -> Void) {
for e in self {
doThis(element: e)
}
}
}
protocol TrickTakingCardGame {
//implement protocol-based thinking later
}
protocol TrickTakingCardSetup {
//see above
} | isc | ff12c004cc6a006ef2018d0a9f2248a3 | 21.113475 | 105 | 0.675329 | 3.023278 | false | false | false | false |
mobgeek/swift | Swift em 4 Semanas/Desafios/Desafios Semana 4.playground/Contents.swift | 2 | 3352 | // Playground - noun: a place where people can play
import UIKit
/*
__ __
__ \ / __
/ \ | / \
\|/ Mobgeek
_,.---v---._
/\__/\ / \ Curso Swift em 4 semanas
\_ _/ / \
\ \_| @ __|
\ \_
\ ,__/ /
~~~`~~~~~~~~~~~~~~/~~~~
*/
/*:
# **Exercícios práticos - Semana 04**
1 - Parâmetros de funções e métodos podem tanto ter um nome local para usar dentro do corpo da função, como um nome externo para usar quando as funções são chamadas. Com os parâmetros de inicialização não será diferente, porém inicializadores não possuem nomes que os identificam como funções e métodos. Por isso, Swift irá fornecer um nome externo automático para todo parâmetro de um initializer mesmo que você mesmo não de um nome externo.
**Desafio 01:** Defina uma estrutura chamada `Cor` com três propriedades constantes chamadas `red`, `green` e `blue`. Essas propriedades devem armazenar valores entre `0.0` e `1.0`, que representam a quantidade de vermelho, verde e azul em uma cor (Para saber mais sobre o sistema RGB, consulte o nosso último desafio prático :-)
Resposta:
*/
/*:
**Desafio 02:** Forneça um initializer com três parâmetros com nomes e tipos apropriados para os seus componentes de cor.
Resposta:
*/
/*:
**Desafio 03:** Use o initializer de `Cor` para criar uma cor branca.
Resposta:
*/
/*:
---
2 - Use extensões (extensions) para adicionar funcionalidades à tipos existentes, tais como novos métodos de instância e propriedades computadas, entre outras. Você também pode usar uma extensão para adicionar conformidade de protocolo para um tipo que foi declarado em outros lugares, ou até para um tipo que tenha sido importado de uma biblioteca ou de um framework.
Veja o exemplo a seguir:
*/
protocol ProtocoloSimples {
var descriçãoSimples: String { get }
mutating func ajuste()
}
extension Int: ProtocoloSimples {
var descriçãoSimples: String {
return "O número \(self)"
}
mutating func ajuste() {
self += 18
}
}
7.descriçãoSimples
/*:
**Desafio 04:** Escreva um extension para o tipo Double que adicione uma propriedade `valorAbsoluto`.(De uma forma simplificada, o valor absoluto é o valor numérico desconsiderando o seu sinal)
Resposta:
*/
/*:
---
3 - Use o operador `where` após o tipo de nome para especificar uma lista de condições - por exemplo, para que o tipo de nome implemente um protocolo, para que dois tipos sejam iguais, ou para que uma classe contenha uma superclasse especial.
Analise o seguinte exemplo, que também traz um pouco de Generics:
*/
func qualquerElementoComum <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
qualquerElementoComum([1, 2, 3], [3])
/*:
**Desafio 05:** Modifique a função `qualquerElementoComum` para fazer uma função que retorne uma array de elementos que quaisquer duas sequências tenham em comum.
Resposta:
*/
| mit | dd40a5a5fe473f0e558de8601501d43a | 26.45 | 443 | 0.655131 | 3.251728 | false | false | false | false |
wireapp/wire-ios-sync-engine | Source/Notifications/Push notifications/Notification Types/LocalNotificationContentType.swift | 1 | 4714 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
public enum LocalNotificationEventType {
case connectionRequestAccepted, connectionRequestPending, newConnection, conversationCreated, conversationDeleted
}
public enum LocalNotificationContentType: Equatable {
case text(String, isMention: Bool, isReply: Bool)
case image
case video
case audio
case location
case fileUpload
case knock
case reaction(emoji: String)
case hidden
case ephemeral(isMention: Bool, isReply: Bool)
case participantsRemoved(reason: ZMParticipantsRemovedReason)
case participantsAdded
case messageTimerUpdate(String?)
init?(event: ZMUpdateEvent, conversation: ZMConversation?, in moc: NSManagedObjectContext) {
switch event.type {
case .conversationMemberJoin:
self = .participantsAdded
case .conversationMemberLeave:
self = .participantsRemoved(reason: event.participantsRemovedReason)
case .conversationMessageTimerUpdate:
guard let payload = event.payload["data"] as? [String: AnyHashable] else { return nil }
let timeoutIntegerValue = (payload["message_timer"] as? Int64) ?? 0
let timeoutValue = MessageDestructionTimeoutValue(rawValue: TimeInterval(timeoutIntegerValue))
self = timeoutValue == .none ? .messageTimerUpdate(nil) : .messageTimerUpdate(timeoutValue.displayString)
case .conversationOtrMessageAdd:
guard let message = GenericMessage(from: event) else { return nil }
self.init(message: message, conversation: conversation, in: moc)
default:
return nil
}
}
init?(message: GenericMessage, conversation: ZMConversation?, in moc: NSManagedObjectContext) {
let selfUser = ZMUser.selfUser(in: moc)
func getQuotedMessage(_ textMessageData: Text, conversation: ZMConversation?, in moc: NSManagedObjectContext) -> ZMOTRMessage? {
guard let conversation = conversation else { return nil }
let quotedMessageId = UUID(uuidString: textMessageData.quote.quotedMessageID)
return ZMOTRMessage.fetch(withNonce: quotedMessageId, for: conversation, in: moc)
}
switch message.content {
case .location:
self = .location
case .knock:
self = .knock
case .image:
self = .image
case .ephemeral:
if message.ephemeral.hasText {
let textMessageData = message.ephemeral.text
let quotedMessage = getQuotedMessage(textMessageData, conversation: conversation, in: moc)
self = .ephemeral(isMention: textMessageData.isMentioningSelf(selfUser), isReply: textMessageData.isQuotingSelf(quotedMessage))
} else {
self = .ephemeral(isMention: false, isReply: false)
}
case .text:
guard
let textMessageData = message.textData,
let text = message.textData?.content.removingExtremeCombiningCharacters, !text.isEmpty
else {
return nil
}
let quotedMessage = getQuotedMessage(textMessageData, conversation: conversation, in: moc)
self = .text(text, isMention: textMessageData.isMentioningSelf(selfUser), isReply: textMessageData.isQuotingSelf(quotedMessage))
case .composite:
guard let textData = message.composite.items.compactMap({ $0.text }).first else { return nil }
self = .text(textData.content, isMention: textData.isMentioningSelf(selfUser), isReply: false)
case .asset(let assetData):
switch assetData.original.metaData {
case .audio?:
self = .audio
case .video?:
self = .video
case .image:
self = .image
default:
self = .fileUpload
}
default:
return nil
}
}
}
| gpl-3.0 | c74e30ab1cd93e3de3bfec4a0451cff1 | 36.712 | 143 | 0.655919 | 4.900208 | false | false | false | false |
googlecast/CastVideos-ios | CastVideos-swift/Classes/MediaItem.swift | 1 | 2220 | // Copyright 2022 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
import GoogleCast
/**
* An object representing a media item (or a container group of media items).
*/
class MediaItem: NSObject {
fileprivate(set) var title: String?
fileprivate(set) var imageURL: URL?
var children: [Any]!
fileprivate(set) var mediaInfo: GCKMediaInformation?
fileprivate(set) var parent: MediaItem?
var isNowPlaying: Bool = false
/** Initializer for constructing a group item.
*
* @param title The title of the item.
* @param imageURL The URL of the image for this item.
* @param parent The parent item of this item, if any.
*/
init(title: String?, imageURL: URL?, parent: MediaItem?) {
self.title = title
children = [Any]()
self.imageURL = imageURL
self.parent = parent
}
/** Initializer for constructing a media item.
*
* @param mediaInfo The media information for this item.
* @param parent The parent item of this item, if any.
*/
convenience init(mediaInformation mediaInfo: GCKMediaInformation, parent: MediaItem) {
let title = mediaInfo.metadata?.string(forKey: kGCKMetadataKeyTitle) ?? ""
let imageURL = (mediaInfo.metadata?.images()[0] as? GCKImage)?.url
self.init(title: title, imageURL: imageURL, parent: parent)
self.mediaInfo = mediaInfo
}
/**
* Factory method for constructing the special "now playing" item.
*
* @param parent The parent item of this item.
*/
class func nowPlayingItem(withParent parent: MediaItem) -> MediaItem {
let item = MediaItem(title: "Now Playing", imageURL: nil, parent: parent)
item.isNowPlaying = true
return item
}
}
| apache-2.0 | 7e693f6c54eb284b67ce046fce4a436f | 33.6875 | 88 | 0.70991 | 4.196597 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Notifications/Controllers/NotificationsViewController+PushPrimer.swift | 1 | 5200 | // MARK: - Push Notification Primer
//
extension NotificationsViewController {
private struct Analytics {
static let locationKey = "location"
static let inlineKey = "inline"
}
var shouldShowPrimeForPush: Bool {
get {
return !UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged
}
}
func setupNotificationPrompt() {
PushNotificationsManager.shared.loadAuthorizationStatus { [weak self] (status) in
switch status {
case .notDetermined:
self?.setupPrimeForPush()
case .denied:
self?.setupWinback()
default:
break
}
}
}
private func setupPrimeForPush() {
defer {
WPAnalytics.track(.pushNotificationPrimerSeen, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
inlinePromptView.setupHeading(NSLocalizedString("We'll notify you when you get followers, comments, and likes.",
comment: "This is the string we display when asking the user to approve push notifications"))
let yesTitle = NSLocalizedString("Allow notifications",
comment: "Button label for approving our request to allow push notifications")
let noTitle = NSLocalizedString("Not now",
comment: "Button label for denying our request to allow push notifications")
inlinePromptView.setupYesButton(title: yesTitle) { [weak self] button in
defer {
WPAnalytics.track(.pushNotificationPrimerAllowTapped, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
InteractiveNotificationsManager.shared.requestAuthorization { _ in
DispatchQueue.main.async {
self?.hideInlinePrompt(delay: 0.0)
UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged = true
}
}
}
inlinePromptView.setupNoButton(title: noTitle) { [weak self] button in
defer {
WPAnalytics.track(.pushNotificationPrimerNoTapped, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
self?.hideInlinePrompt(delay: 0.0)
UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged = true
}
// We _seriously_ need to call the following method at last.
// Why I: Because you must first set the Heading (at least), so that the InlinePrompt's height can be properly calculated.
// Why II: UITableView's Header inability to deal with Autolayout was never, ever addressed by AAPL.
showInlinePrompt()
}
private func setupWinback() {
// only show the winback for folks that denied without seeing the post-login primer: aka users of a previous version
guard !UserPersistentStoreFactory.instance().notificationPrimerAlertWasDisplayed else {
// they saw the primer, and denied us. they aren't coming back, we aren't bothering them anymore.
UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged = true
return
}
defer {
WPAnalytics.track(.pushNotificationWinbackShown, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
showInlinePrompt()
inlinePromptView.setupHeading(NSLocalizedString("Push notifications have been turned off in iOS settings. Toggle “Allow Notifications” to turn them back on.",
comment: "This is the string we display when asking the user to approve push notifications in the settings app after previously having denied them."))
let yesTitle = NSLocalizedString("Go to iOS Settings",
comment: "Button label for going to settings to approve push notifications")
let noTitle = NSLocalizedString("No thanks",
comment: "Button label for denying our request to re-allow push notifications")
inlinePromptView.setupYesButton(title: yesTitle) { [weak self] button in
defer {
WPAnalytics.track(.pushNotificationWinbackSettingsTapped, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
self?.hideInlinePrompt(delay: 0.0)
let targetURL = URL(string: UIApplication.openSettingsURLString)
UIApplication.shared.open(targetURL!)
UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged = true
}
inlinePromptView.setupNoButton(title: noTitle) { [weak self] button in
defer {
WPAnalytics.track(.pushNotificationWinbackNoTapped, withProperties: [Analytics.locationKey: Analytics.inlineKey])
}
self?.hideInlinePrompt(delay: 0.0)
UserPersistentStoreFactory.instance().notificationPrimerInlineWasAcknowledged = true
}
}
}
| gpl-2.0 | 0e24576cc64af321f606ec2462925c47 | 48.485714 | 206 | 0.6403 | 5.660131 | false | false | false | false |
zarghol/documentation-provider | Sources/DocumentationProvider/LeafWrapper.swift | 1 | 5208 | //
// LeafWrapper.swift
// DocumentationProvider
//
// Created by Clément NONN on 30/07/2017.
//
// This is a workaround for embedding the resources in the library
// MARK: - raw content
let cssContent = """
/** Regular */
@font-face {
font-family: "San Francisco";
font-weight: 200;
src: url("https://applesocial.s3.amazonaws.com/assets/styles/fonts/sanfrancisco/sanfranciscodisplay-thin-webfont.woff");
}
@font-face {
font-family: "SF Mono";
font-weight: 200;
src: url("SFMono-Regular.otf");
}
* {
box-sizing: border-box;
}
body, html {
padding: 0;
margin: 0;
height: 100%;
}
#droplet {
width: 50px;
display: inline-block;
margin-right: 12px;
float: left;
}
.vapor {
font-weight: 500;
font-size: 38px;
vertical-align: middle;
font-family: 'Quicksand';
}
h1, h2, h3, h4 {
font-family: -apple-system-headline, "San Franscisco", "Helvetica Neue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
.code {
font-family: "SF Mono", -apple-system-body, "San Franscisco", "Helvetica Neue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
}
body {
font-family: -apple-system-body, "San Franscisco", "Helvetica Neue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
background-image: -webkit-linear-gradient(top, #92a8d1 20%, #f6cbca 100%);
background-color: black;
background-repeat: no-repeat;
background-attachment: fixed;
position: relative;
}
.panel {
background-color: rgb(255, 255, 255);
background-color: rgba(255, 255, 255, 0.5);
width: 60%;
margin: auto;
margin-top: 20px;
margin-bottom: 20px;
padding: 20px;
float: center;
}
header {
width: 100%;
padding: 10px;
height: 80px;
background-color: rgba(255, 255, 255, 0.7);
}
footer {
width: 100%;
position:absolute;
padding: 10px;
text-align: right;
background-color: rgba(255, 255, 255, 0.7);
}
a {
text-decoration: none;
}
.title {
text-align: center;
font-size: 42px;
vertical-align: middle;
}
"""
let structure = """
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#(title)</title>
<link href="https://fonts.googleapis.com/css?family=Quicksand:400,700,300" rel="stylesheet">
<style>#raw() { %@ }</style>
<meta name="viewport" content="user-scalable=no, initial-scale = 1, minimum-scale = 1, maximum-scale = 1, width=device-width">
</head>
<body>
<header>
#raw() {
<svg xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 -5 48 60" enable-background="new 0 0 48 48" xml:space="preserve" id="droplet">
<defs>
<linearGradient id="linear" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" stop-color="#F7CAC9"/>
<stop offset="100%" stop-color="#92A8D1"/>
</linearGradient>
</defs>
<path stroke="url(#linear)" fill="white" fill-opacity="0" stroke-width="3" d="M24.8,0.9c-0.4-0.5-1.2-0.5-1.6,0C19.8,5.3,7.1,22.5,7.1,30.6c0,9.3,7.6,16.9,16.9,16.9s16.9-7.6,16.9-16.9 C40.9,22.5,28.2,5.3,24.8,0.9z"/>
</svg>
<span class="title">Documentation</span>
}
</header>
%@
<footer>
HTML powered by <a href="https://github.com/vapor/leaf">🍃Leaf</a>.
</footer>
</body>
</html>
"""
let docsBody = """
<div class="panel">
<h2>API</h2>
#loop(definitions, "definition") {
<p>
<h3>#(definition.method) - <span class="code"> #(definition.path)</span></h3>
#(definition.description)<br/>
#if(definition.hasParameter) {
#empty(definition.parameters.path) {
} ##else() {
<h4>Path Parameters</h4>
#loop(definition.parameters.path, "parameter") {
<span class="code"> #(parameter.key) </span> : #(parameter.value)<br/>
}
}
#empty(definition.parameters.query) {
} ##else() {
<br/>
<h4>Query Parameters</h4>
#loop(definition.parameters.query, "parameter") {
<span class="code"> #(parameter.key) </span> : #(parameter.value)<br/>
}
}
}
</p>
<hr/>
}
</div>
"""
| mit | ea3e2899d0ebbb35d5a5030729e862ad | 30.349398 | 239 | 0.489431 | 3.623955 | false | false | false | false |
radazzouz/firefox-ios | Client/Frontend/Browser/Tab.swift | 1 | 17911 | /* 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 WebKit
import Storage
import Shared
import SwiftyJSON
import XCGLogger
private let log = Logger.browserLogger
protocol TabHelper {
static func name() -> String
func scriptMessageHandlerName() -> String?
func userContentController(_ userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage)
}
@objc
protocol TabDelegate {
func tab(_ tab: Tab, didAddSnackbar bar: SnackBar)
func tab(_ tab: Tab, didRemoveSnackbar bar: SnackBar)
func tab(_ tab: Tab, didSelectFindInPageForSelection selection: String)
@objc optional func tab(_ tab: Tab, didCreateWebView webView: WKWebView)
@objc optional func tab(_ tab: Tab, willDeleteWebView webView: WKWebView)
}
struct TabState {
var isPrivate: Bool = false
var desktopSite: Bool = false
var isBookmarked: Bool = false
var url: URL?
var title: String?
var favicon: Favicon?
}
class Tab: NSObject {
fileprivate var _isPrivate: Bool = false
internal fileprivate(set) var isPrivate: Bool {
get {
return _isPrivate
}
set {
if _isPrivate != newValue {
_isPrivate = newValue
self.updateAppState()
}
}
}
var tabState: TabState {
return TabState(isPrivate: _isPrivate, desktopSite: desktopSite, isBookmarked: isBookmarked, url: url, title: displayTitle, favicon: displayFavicon)
}
var webView: WKWebView?
var tabDelegate: TabDelegate?
weak var appStateDelegate: AppStateDelegate?
var bars = [SnackBar]()
var favicons = [Favicon]()
var lastExecutedTime: Timestamp?
var sessionData: SessionData?
fileprivate var lastRequest: URLRequest?
var restoring: Bool = false
var pendingScreenshot = false
var url: URL?
/// The last title shown by this tab. Used by the tab tray to show titles for zombie tabs.
var lastTitle: String?
/// Whether or not the desktop site was requested with the last request, reload or navigation. Note that this property needs to
/// be managed by the web view's navigation delegate.
var desktopSite: Bool = false {
didSet {
if oldValue != desktopSite {
self.updateAppState()
}
}
}
var isBookmarked: Bool = false {
didSet {
if oldValue != isBookmarked {
self.updateAppState()
}
}
}
fileprivate(set) var screenshot: UIImage?
var screenshotUUID: UUID?
// If this tab has been opened from another, its parent will point to the tab from which it was opened
var parent: Tab?
fileprivate var helperManager: HelperManager?
fileprivate var configuration: WKWebViewConfiguration?
/// Any time a tab tries to make requests to display a Javascript Alert and we are not the active
/// tab instance, queue it for later until we become foregrounded.
fileprivate var alertQueue = [JSAlertInfo]()
init(configuration: WKWebViewConfiguration) {
self.configuration = configuration
}
init(configuration: WKWebViewConfiguration, isPrivate: Bool) {
self.configuration = configuration
super.init()
self.isPrivate = isPrivate
}
class func toTab(_ tab: Tab) -> RemoteTab? {
if let displayURL = tab.url?.displayURL, RemoteTab.shouldIncludeURL(displayURL) {
let history = Array(tab.historyList.filter(RemoteTab.shouldIncludeURL).reversed())
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: Date.now(),
icon: nil)
} else if let sessionData = tab.sessionData, !sessionData.urls.isEmpty {
let history = Array(sessionData.urls.filter(RemoteTab.shouldIncludeURL).reversed())
if let displayURL = history.first {
return RemoteTab(clientGUID: nil,
URL: displayURL,
title: tab.displayTitle,
history: history,
lastUsed: sessionData.lastUsedTime,
icon: nil)
}
}
return nil
}
fileprivate func updateAppState() {
let state = mainStore.updateState(.tab(tabState: self.tabState))
self.appStateDelegate?.appDidUpdateState(state)
}
weak var navigationDelegate: WKNavigationDelegate? {
didSet {
if let webView = webView {
webView.navigationDelegate = navigationDelegate
}
}
}
func createWebview() {
if webView == nil {
assert(configuration != nil, "Create webview can only be called once")
configuration!.userContentController = WKUserContentController()
configuration!.preferences = WKPreferences()
configuration!.preferences.javaScriptCanOpenWindowsAutomatically = false
let webView = TabWebView(frame: CGRect.zero, configuration: configuration!)
webView.delegate = self
configuration = nil
webView.accessibilityLabel = NSLocalizedString("Web content", comment: "Accessibility label for the main web content view")
webView.allowsBackForwardNavigationGestures = true
webView.backgroundColor = UIColor.lightGray
// Turning off masking allows the web content to flow outside of the scrollView's frame
// which allows the content appear beneath the toolbars in the BrowserViewController
webView.scrollView.layer.masksToBounds = false
webView.navigationDelegate = navigationDelegate
helperManager = HelperManager(webView: webView)
restore(webView)
self.webView = webView
self.webView?.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
tabDelegate?.tab?(self, didCreateWebView: webView)
}
}
func restore(_ webView: WKWebView) {
// Pulls restored session data from a previous SavedTab to load into the Tab. If it's nil, a session restore
// has already been triggered via custom URL, so we use the last request to trigger it again; otherwise,
// we extract the information needed to restore the tabs and create a NSURLRequest with the custom session restore URL
// to trigger the session restore via custom handlers
if let sessionData = self.sessionData {
restoring = true
var urls = [String]()
for url in sessionData.urls {
urls.append(url.absoluteString)
}
let currentPage = sessionData.currentPage
self.sessionData = nil
var jsonDict = [String: AnyObject]()
jsonDict["history"] = urls as AnyObject?
jsonDict["currentPage"] = currentPage as AnyObject?
guard let json = JSON(jsonDict).rawString(.utf8, options: []) else {
return
}
let escapedJSON = json.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
let restoreURL = URL(string: "\(WebServer.sharedInstance.base)/about/sessionrestore?history=\(escapedJSON)")
lastRequest = PrivilegedRequest(url: restoreURL!) as URLRequest
webView.load(lastRequest!)
} else if let request = lastRequest {
webView.load(request)
} else {
log.error("creating webview with no lastRequest and no session data: \(self.url)")
}
}
deinit {
if let webView = webView {
tabDelegate?.tab?(self, willDeleteWebView: webView)
webView.removeObserver(self, forKeyPath: "URL")
}
}
var loading: Bool {
return webView?.isLoading ?? false
}
var estimatedProgress: Double {
return webView?.estimatedProgress ?? 0
}
var backList: [WKBackForwardListItem]? {
return webView?.backForwardList.backList
}
var forwardList: [WKBackForwardListItem]? {
return webView?.backForwardList.forwardList
}
var historyList: [URL] {
func listToUrl(_ item: WKBackForwardListItem) -> URL { return item.url }
var tabs = self.backList?.map(listToUrl) ?? [URL]()
tabs.append(self.url!)
return tabs
}
var title: String? {
return webView?.title
}
var displayTitle: String {
if let title = webView?.title {
if !title.isEmpty {
return title
}
}
// When picking a display title. Tabs with sessionData are pending a restore so show their old title.
// To prevent flickering of the display title. If a tab is restoring make sure to use its lastTitle.
if let url = self.url, url.isAboutHomeURL, sessionData == nil, !restoring {
return ""
}
guard let lastTitle = lastTitle, !lastTitle.isEmpty else {
return self.url?.displayURL?.absoluteString ?? ""
}
return lastTitle
}
var currentInitialURL: URL? {
get {
let initalURL = self.webView?.backForwardList.currentItem?.initialURL
return initalURL
}
}
var displayFavicon: Favicon? {
var width = 0
var largest: Favicon?
for icon in favicons {
if icon.width! > width {
width = icon.width!
largest = icon
}
}
return largest
}
var canGoBack: Bool {
return webView?.canGoBack ?? false
}
var canGoForward: Bool {
return webView?.canGoForward ?? false
}
func goBack() {
let _ = webView?.goBack()
}
func goForward() {
let _ = webView?.goForward()
}
func goToBackForwardListItem(_ item: WKBackForwardListItem) {
let _ = webView?.go(to: item)
}
@discardableResult func loadRequest(_ request: URLRequest) -> WKNavigation? {
if let webView = webView {
lastRequest = request
return webView.load(request)
}
return nil
}
func stop() {
webView?.stopLoading()
}
func reload() {
let userAgent: String? = desktopSite ? UserAgent.desktopUserAgent() : nil
if (userAgent ?? "") != webView?.customUserAgent,
let currentItem = webView?.backForwardList.currentItem {
webView?.customUserAgent = userAgent
// Reload the initial URL to avoid UA specific redirection
loadRequest(PrivilegedRequest(url: currentItem.initialURL, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60) as URLRequest)
return
}
if let _ = webView?.reloadFromOrigin() {
log.info("reloaded zombified tab from origin")
return
}
if let webView = self.webView {
log.info("restoring webView from scratch")
restore(webView)
}
}
func addHelper(_ helper: TabHelper, name: String) {
helperManager!.addHelper(helper, name: name)
}
func getHelper(name: String) -> TabHelper? {
return helperManager?.getHelper(name)
}
func hideContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = false
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 0.0
})
} else {
webView?.alpha = 0.0
}
}
func showContent(_ animated: Bool = false) {
webView?.isUserInteractionEnabled = true
if animated {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.webView?.alpha = 1.0
})
} else {
webView?.alpha = 1.0
}
}
func addSnackbar(_ bar: SnackBar) {
bars.append(bar)
tabDelegate?.tab(self, didAddSnackbar: bar)
}
func removeSnackbar(_ bar: SnackBar) {
if let index = bars.index(of: bar) {
bars.remove(at: index)
tabDelegate?.tab(self, didRemoveSnackbar: bar)
}
}
func removeAllSnackbars() {
// Enumerate backwards here because we'll remove items from the list as we go.
for i in (0..<bars.count).reversed() {
let bar = bars[i]
removeSnackbar(bar)
}
}
func expireSnackbars() {
// Enumerate backwards here because we may remove items from the list as we go.
for i in (0..<bars.count).reversed() {
let bar = bars[i]
if !bar.shouldPersist(self) {
removeSnackbar(bar)
}
}
}
func setScreenshot(_ screenshot: UIImage?, revUUID: Bool = true) {
self.screenshot = screenshot
if revUUID {
self.screenshotUUID = UUID()
}
}
func toggleDesktopSite() {
desktopSite = !desktopSite
reload()
}
func queueJavascriptAlertPrompt(_ alert: JSAlertInfo) {
alertQueue.append(alert)
}
func dequeueJavascriptAlertPrompt() -> JSAlertInfo? {
guard !alertQueue.isEmpty else {
return nil
}
return alertQueue.removeFirst()
}
func cancelQueuedAlerts() {
alertQueue.forEach { alert in
alert.cancel()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer?) {
guard let webView = object as? WKWebView, webView == self.webView,
let path = keyPath, path == "URL" else {
return assertionFailure("Unhandled KVO key: \(keyPath)")
}
updateAppState()
}
func isDescendentOf(_ ancestor: Tab) -> Bool {
var tab = parent
while tab != nil {
if tab! == ancestor {
return true
}
tab = tab?.parent
}
return false
}
func setNoImageMode(_ enabled: Bool = false, force: Bool) {
if enabled || force {
webView?.evaluateJavaScript("window.__firefox__.NoImageMode.setEnabled(\(enabled))", completionHandler: nil)
}
}
func setNightMode(_ enabled: Bool) {
webView?.evaluateJavaScript("window.__firefox__.NightMode.setEnabled(\(enabled))", completionHandler: nil)
}
func injectUserScriptWith(fileName: String, type: String = "js", injectionTime: WKUserScriptInjectionTime = .atDocumentEnd, mainFrameOnly: Bool = true) {
guard let webView = self.webView else {
return
}
if let path = Bundle.main.path(forResource: fileName, ofType: type),
let source = try? String(contentsOfFile: path) {
let userScript = WKUserScript(source: source, injectionTime: injectionTime, forMainFrameOnly: mainFrameOnly)
webView.configuration.userContentController.addUserScript(userScript)
}
}
}
extension Tab: TabWebViewDelegate {
fileprivate func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String) {
tabDelegate?.tab(self, didSelectFindInPageForSelection: selection)
}
}
private class HelperManager: NSObject, WKScriptMessageHandler {
fileprivate var helpers = [String: TabHelper]()
fileprivate weak var webView: WKWebView?
init(webView: WKWebView) {
self.webView = webView
}
@objc func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
for helper in helpers.values {
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
if scriptMessageHandlerName == message.name {
helper.userContentController(userContentController, didReceiveScriptMessage: message)
return
}
}
}
}
func addHelper(_ helper: TabHelper, name: String) {
if let _ = helpers[name] {
assertionFailure("Duplicate helper added: \(name)")
}
helpers[name] = helper
// If this helper handles script messages, then get the handler name and register it. The Browser
// receives all messages and then dispatches them to the right TabHelper.
if let scriptMessageHandlerName = helper.scriptMessageHandlerName() {
webView?.configuration.userContentController.add(self, name: scriptMessageHandlerName)
}
}
func getHelper(_ name: String) -> TabHelper? {
return helpers[name]
}
}
private protocol TabWebViewDelegate: class {
func tabWebView(_ tabWebView: TabWebView, didSelectFindInPageForSelection selection: String)
}
private class TabWebView: WKWebView, MenuHelperInterface {
fileprivate weak var delegate: TabWebViewDelegate?
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == MenuHelper.SelectorFindInPage
}
@objc func menuHelperFindInPage() {
evaluateJavaScript("getSelection().toString()") { result, _ in
let selection = result as? String ?? ""
self.delegate?.tabWebView(self, didSelectFindInPageForSelection: selection)
}
}
fileprivate override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// The find-in-page selection menu only appears if the webview is the first responder.
becomeFirstResponder()
return super.hitTest(point, with: event)
}
}
| mpl-2.0 | 6aba4e4f52ace3f0c68106249c4c7e6b | 32.541199 | 157 | 0.618391 | 5.317993 | false | false | false | false |
Mindera/Alicerce | Sources/Persistence/CoreData/SiblingContextCoreDataStack.swift | 1 | 3687 | import CoreData
public final class SiblingContextCoreDataStack: CoreDataStack {
fileprivate let workContext: NSManagedObjectContext
fileprivate let backgroundContext: NSManagedObjectContext
public required convenience init(
storeType: CoreDataStackStoreType,
storeName: String,
managedObjectModel: NSManagedObjectModel
) {
self.init(
storeType: storeType,
storeName: storeName,
managedObjectModel: managedObjectModel,
// use parameter to avoid infinite loop since Swift won't use the designated initializer below 🤷♂️
shouldAddStoreAsynchronously: false)
}
public init(
storeType: CoreDataStackStoreType,
storeName: String,
managedObjectModel: NSManagedObjectModel,
shouldAddStoreAsynchronously: Bool = false,
shouldMigrateStoreAutomatically: Bool = true,
shouldInferMappingModelAutomatically: Bool = true,
storeLoadCompletionHandler: @escaping (Any, Error?) -> Void = { store, error in
if let error = error {
fatalError("Failed to load persistent store \(store)! Error: \(error)")
}
},
mergePolicy: NSMergePolicy = NSMergePolicy(merge: .errorMergePolicyType)
) {
(workContext, backgroundContext) = SiblingContextCoreDataStack.makeContexts(
storeType: storeType,
storeName: storeName,
managedObjectModel: managedObjectModel,
shouldAddStoreAsynchronously: shouldAddStoreAsynchronously,
shouldMigrateStoreAutomatically: shouldMigrateStoreAutomatically,
shouldInferMappingModelAutomatically: shouldInferMappingModelAutomatically,
storeLoadCompletionHandler: storeLoadCompletionHandler)
workContext.mergePolicy = mergePolicy
backgroundContext.mergePolicy = mergePolicy
}
public func context(withType type: CoreDataStackContextType) -> NSManagedObjectContext {
switch type {
case .work: return workContext
case .background: return backgroundContext
}
}
}
// MARK: Helpers
extension SiblingContextCoreDataStack {
// swiftlint:disable:next function_parameter_count
static func makeContexts(
storeType: CoreDataStackStoreType,
storeName: String,
managedObjectModel: NSManagedObjectModel,
shouldAddStoreAsynchronously: Bool,
shouldMigrateStoreAutomatically: Bool,
shouldInferMappingModelAutomatically: Bool,
storeLoadCompletionHandler: @escaping (Any, Error?) -> Void
) -> (work: NSManagedObjectContext, background: NSManagedObjectContext) {
let container = NestedContextCoreDataStack.persistentContainer(
withType: storeType,
name: storeName,
managedObjectModel: managedObjectModel,
shouldAddStoreAsynchronously: shouldAddStoreAsynchronously,
shouldMigrateStoreAutomatically: shouldMigrateStoreAutomatically,
shouldInferMappingModelAutomatically: shouldInferMappingModelAutomatically,
storeLoadCompletionHandler: storeLoadCompletionHandler)
let workContext = container.viewContext
workContext.automaticallyMergesChangesFromParent = true // merge changes made on sibling contexts
let backgroundContext = container.newBackgroundContext()
backgroundContext.automaticallyMergesChangesFromParent = true // merge changes made on sibling contexts
return (workContext, backgroundContext)
}
}
// MARK: MainQueue
typealias MainQueueSiblingContextCoreDataStack = SiblingContextCoreDataStack
| mit | f2d8c28da6c86233759abb6ce07d26e8 | 37.715789 | 111 | 0.712616 | 6.452632 | false | true | false | false |
Desgard/Calendouer-iOS | Calendouer/Calendouer/App/Tools/AnimatedEnhance.swift | 1 | 2851 | //
// AnimatedEnhance.swift
// Calendouer
//
// Created by 段昊宇 on 2017/4/21.
// Copyright © 2017年 Desgard_Duan. All rights reserved.
//
import UIKit
let Animated = AnimatedEnhance.shared
class AnimatedEnhance: NSObject {
static let shared = AnimatedEnhance()
public func getExplosion(view: UIView) {
if view.subviews.count > 1 {
if view.subviews.first?.classForCoder == ExplodeAnimationView.self {
let explodeView = view.subviews.first as! ExplodeAnimationView
explodeView.animate {}
return
}
}
let explodeView = ExplodeAnimationView(frame: view.bounds)
view.insertSubview(explodeView, at: 0)
explodeView.animate {}
}
public func getExplosionOnPoint(point: CGPoint, superView: UIView) {
let view = UIView.init(frame: CGRect.init(origin: point, size: CGSize.init(width: 20, height: 20)))
view.isUserInteractionEnabled = false
superView.addSubview(view)
getExplosion(view: view)
}
}
class ExplodeAnimationView: UIView {
private var emitterLayer: CAEmitterLayer! = nil
private func ready() {
self.clipsToBounds = false
self.isUserInteractionEnabled = false
let emitter = CAEmitterCell()
emitter.contents = UIImage(named: "spark")?.cgImage
emitter.name = "explosion"
emitter.alphaRange = 0.2
emitter.alphaSpeed = -1
emitter.lifetime = 0.7
emitter.birthRate = 0
emitter.velocity = 40
emitter.velocityRange = 10
emitter.emissionRange = CGFloat(Double.pi / 4)
emitter.scale = 0.05
emitter.scaleRange = 0.02
emitterLayer = CAEmitterLayer()
emitterLayer.name = "emitterLayer"
emitterLayer.emitterShape = kCAEmitterLayerCircle
emitterLayer.emitterMode = kCAEmitterLayerOutline
emitterLayer.emitterPosition = self.center
emitterLayer.emitterSize = CGSize(width: 25, height: 0)
emitterLayer.renderMode = kCAEmitterLayerOldestFirst
emitterLayer.masksToBounds = false
emitterLayer.emitterCells = [emitter]
emitterLayer.frame = UIScreen.main.bounds
self.layer.addSublayer(emitterLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
ready()
}
public func animate(handle: @escaping () -> Void) {
let delayTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.emitterLayer.beginTime = CACurrentMediaTime()
let ani = CABasicAnimation(keyPath: "emitterCells.explosion.birthRate")
ani.fromValue = 0
ani.toValue = 500
self.emitterLayer.add(ani, forKey: nil)
}
}
}
| mit | 5009695c7ec9e9c5692121918387ad7c | 32.046512 | 107 | 0.636172 | 4.72093 | false | false | false | false |
Ethenyl/JAMFKit | JamfKit/Sources/Models/ConfigurationProfile/ConfigurationProfileGeneral.swift | 1 | 2377 | //
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
@objc(JMFKConfigurationProfileGeneral)
public class ConfigurationProfileGeneral: BaseObject {
// MARK: - Constants
static let DescriptionKey = "description"
static let SiteKey = "site"
static let CategoryKey = "category"
static let UuidKey = "uuid"
static let RedeployOnUpdateKey = "redeploy_on_update"
static let PayloadsKey = "payloads"
// MARK: - Properties
@objc
public var desc: String = ""
@objc
public var site: Site?
@objc
public var category: Category?
@objc
public var uuid: String = ""
@objc
public var redeployOnUpdate: String = ""
@objc
public var payloads: String = ""
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
desc = json[ConfigurationProfileGeneral.DescriptionKey] as? String ?? ""
if let siteNode = json[ConfigurationProfileGeneral.SiteKey] as? [String: Any] {
site = Site(json: siteNode)
}
if let categoryNode = json[ConfigurationProfileGeneral.CategoryKey] as? [String: Any] {
category = Category(json: categoryNode)
}
uuid = json[ConfigurationProfileGeneral.UuidKey] as? String ?? ""
redeployOnUpdate = json[ConfigurationProfileGeneral.RedeployOnUpdateKey] as? String ?? ""
payloads = json[ConfigurationProfileGeneral.PayloadsKey] as? String ?? ""
super.init(json: json)
}
override init?(identifier: UInt, name: String) {
super.init(identifier: identifier, name: name)
}
// MARK: - Functions
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[ConfigurationProfileGeneral.DescriptionKey] = desc
if let site = site {
json[ConfigurationProfileGeneral.SiteKey] = site.toJSON()
}
if let category = category {
json[ConfigurationProfileGeneral.CategoryKey] = category.toJSON()
}
json[ConfigurationProfileGeneral.UuidKey] = uuid
json[ConfigurationProfileGeneral.RedeployOnUpdateKey] = redeployOnUpdate
json[ConfigurationProfileGeneral.PayloadsKey] = payloads
return json
}
}
| mit | f355449ad94b167a56883a5685ef7bae | 27.626506 | 102 | 0.655724 | 4.424581 | false | true | false | false |
goRestart/restart-backend-app | Sources/FluentStorage/Model/Game/GameCompanyDiskModel.swift | 1 | 1388 | import FluentProvider
extension GameCompanyDiskModel {
public static var name: String = "game_company"
public struct Field {
public static let name = "name"
public static let description = "description"
}
}
public final class GameCompanyDiskModel: Entity {
public let storage = Storage()
public var name: String
public var description: String?
public init(name: String, description: String?) {
self.name = name
self.description = description
}
public init(row: Row) throws {
name = try row.get(Field.name)
description = try row.get(Field.description)
id = try row.get(idKey)
}
public func makeRow() throws -> Row {
var row = Row()
try row.set(Field.name, name)
try row.set(Field.description, description)
try row.set(idKey, id)
return row
}
}
// MARK: - Preparations
extension GameCompanyDiskModel: Preparation {
public static func prepare(_ database: Fluent.Database) throws {
try database.create(self) { creator in
creator.id()
creator.string(Field.name)
creator.string(Field.description, length: 2000, optional: true)
}
}
public static func revert(_ database: Fluent.Database) throws {
try database.delete(self)
}
}
| gpl-3.0 | 5c11f56c27e721f85f409b9b4141e076 | 24.236364 | 75 | 0.613112 | 4.392405 | false | false | false | false |
a497500306/MLSideslipView | MLSideslipViewDome/MLSideslipViewDome/ViewController.swift | 1 | 4871 | //
// ViewController.swift
// MLSideslipViewDome
//
// Created by 洛耳 on 16/1/5.
// Copyright © 2016年 workorz. All rights reserved.
import UIKit
//第一步继承--MLViewController
class ViewController: MLViewController , UITableViewDelegate , UITableViewDataSource {
/// 侧滑栏图片数组
var images : NSArray!
/// 侧滑栏文字数组
var texts : NSArray!
override func viewDidLoad() {
super.viewDidLoad()
//设置左上角的放回按钮
let righBtn = UIButton(frame: CGRectMake(0, 0, 24, 24))
righBtn.setBackgroundImage(UIImage(named: "椭圆-19"), forState: UIControlState.Normal)
righBtn.setBackgroundImage(UIImage(named: "椭圆-19" ), forState: UIControlState.Highlighted)
righBtn.addTarget(self, action: "dianjiNavZuoshangjiao", forControlEvents: UIControlEvents.TouchUpInside)
let rightBarItem = UIBarButtonItem(customView: righBtn)
self.navigationItem.leftBarButtonItem = rightBarItem
//第二步创建侧滑栏中需要添加的控件
添加控件()
}
func 添加控件(){
self.images = ["二维码","手势密码","指纹图标","我的收藏","设置"]
self.texts = ["我的二维码","手势解锁","指纹解锁","我的收藏","设置"]
let imageView = UIImageView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height))
imageView.userInteractionEnabled = true
imageView.image = UIImage(named: "我的—背景图")
let table = UITableView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width * 2 / 3 , UIScreen.mainScreen().bounds.height))
table.backgroundColor = UIColor.clearColor()
table.tag = 1000
table.separatorStyle = UITableViewCellSeparatorStyle.None
//1添加头部控件
let touView : UIView = UIView()
//1.1头像
let btn : UIButton = UIButton()
let w : CGFloat = 75
btn.frame = CGRectMake(((UIScreen.mainScreen().bounds.width * 2 / 3)-w)/2, w/2, w, w)
//圆角
btn.layer.cornerRadius = 10
btn.layer.masksToBounds = true
btn.setImage(UIImage(named: "IMG_1251.JPG"), forState: UIControlState.Normal)
touView.addSubview(btn)
//1.2名字
let nameText : UILabel = UILabel()
let WH : CGSize = MLGongju().计算文字宽高("2131231", sizeMake: CGSizeMake(10000, 10000), font: UIFont.systemFontOfSize(15))
nameText.frame = CGRectMake(0, btn.frame.height + btn.frame.origin.y+10, table.frame.width, WH.height)
nameText.font = UIFont.systemFontOfSize(15)
nameText.textAlignment = NSTextAlignment.Center
nameText.text = "毛哥哥是神"
touView.addSubview(nameText)
//1.3线
let xian : UIView = UIView()
xian.frame = CGRectMake(25, nameText.frame.height + nameText.frame.origin.y + 10, table.frame.width - 50, 0.5)
xian.backgroundColor = UIColor(red: 149/255.0, green: 149/255.0, blue: 149/255.0, alpha: 1)
touView.addSubview(xian)
touView.frame = CGRectMake(0, 0, table.frame.width, xian.frame.origin.y + xian.frame.height + 10)
table.tableHeaderView = touView
//设置代理数据源
table.dataSource = self
table.delegate = self
super.sideslipView.contentView.addSubview(imageView)
super.sideslipView.contentView.addSubview(table)
}//MARK: - tableView代理和数据源方法
//多少行
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.images.count
}
//点击每行做什么
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
//取消选择
tableView.deselectRowAtIndexPath(indexPath, animated: true)
//关闭侧滑栏
super.down()
print("在这里做跳转")
}
//MARK: - tableView代理数据源
//每行cell张什么样子
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let ID = "cell"
var cell : UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(ID)
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: ID)
}
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = self.texts[indexPath.row] as? String
cell.imageView?.image = UIImage(named: (self.images[indexPath.row] as? String)!)
return cell
}
//cell的高度
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 55
}
//MARK: - 点击左上角按钮
func dianjiNavZuoshangjiao(){
super.show()
}
}
| apache-2.0 | 30629a059b2b2342aebb7a06b3c02b87 | 41.396226 | 144 | 0.654651 | 4.023277 | false | false | false | false |
iEdric/SwiftWeiboDemo | SwiftDemo/SwiftDemo/AppDelegate.swift | 1 | 6287 | //
// AppDelegate.swift
// SwiftDemo
//
// Created by Edric on 16/6/6.
// Copyright © 2016年 edric. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds);
window?.backgroundColor = UIColor.whiteColor();
window?.rootViewController = ViewController();
window?.makeKeyAndVisible();
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "CL.SwiftDemo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SwiftDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| apache-2.0 | 6ab143a1f4f959ae9ad2b764eb512076 | 53.643478 | 291 | 0.717377 | 5.917137 | false | false | false | false |
dorentus/bna-swift | bna/MainViewController.swift | 1 | 4617 | //
// MainViewController.swift
// bna
//
// Created by Rox Dorentus on 14-6-5.
// Copyright (c) 2014年 rubyist.today. All rights reserved.
//
import UIKit
import Padlock
import MMProgressHUD
class MainViewController: UITableViewController {
let SegueDetail = "authenticator_detail"
let SegueRestore = "authenticator_restore"
let authenticators: AuthenticatorStorage = AuthenticatorStorage.sharedStorage
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
@IBAction func addButtonTapped(sender: AnyObject) {
let alert = UIAlertController(title: "Choose Region", message: nil, preferredStyle: .ActionSheet)
alert.addAction(UIAlertAction(title: "Restore", style: UIAlertActionStyle.Default) {
[weak self] _ in
self!.performSegueWithIdentifier(self!.SegueRestore, sender: sender)
})
for region in Region.allValues {
alert.addAction(UIAlertAction(title: region.rawValue, style: .Default) {
[weak self] _ in
MMProgressHUD.show()
Authenticator.request(region: region) {
authenticator, error in
if let a = authenticator {
if self!.authenticators.add(a) {
self!.reloadAndScrollToBottom()
}
MMProgressHUD.dismissWithSuccess("success!")
}
else {
let message = error?.localizedDescription ?? "unknown error"
MMProgressHUD.dismissWithError(message)
}
}
})
}
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == SegueDetail {
let dest = segue.destinationViewController as! DetailViewController
dest.authenticator = (sender as! AuthenticatorCell).authenticator
}
}
func reloadAndScrollToBottom() {
tableView.reloadData()
let last = NSIndexPath(forRow: authenticators.count - 1, inSection: 0)
tableView.scrollToRowAtIndexPath(last, atScrollPosition: .Bottom, animated: true)
}
}
extension MainViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return authenticators.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("AUTHENTICATOR_CELL", forIndexPath: indexPath) as! AuthenticatorCell
cell.authenticator = authenticators[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 88
}
override func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
if tableView.editing {
return .Delete
}
else {
return .None
}
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
if let authenticator = (tableView.cellForRowAtIndexPath(indexPath) as! AuthenticatorCell).authenticator {
if authenticators.del(authenticator) {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}
}
override func tableView(tableView: UITableView, moveRowAtIndexPath sourceIndexPath: NSIndexPath, toIndexPath destinationIndexPath: NSIndexPath) {
authenticators.move(from: sourceIndexPath.row, to: destinationIndexPath.row)
}
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
if let cell = cell as? AuthenticatorCell {
cell.start_timer()
}
}
override func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath)
{
if let cell = cell as? AuthenticatorCell {
cell.stop_timer()
}
}
}
| mit | 92ff8a24d8eb5396d49af05e7e6c6bc9 | 37.458333 | 157 | 0.652004 | 5.628049 | false | false | false | false |
atereshkov/EXPLogger | EXPLogger/ConsoleTarget.swift | 1 | 1232 | //
// ConsoleTarget.swift
// EXPLogger
//
// Created by Alex Tereshkov on 8/20/17.
// Copyright © 2017 Alex Tereshkov. All rights reserved.
//
import Foundation
public class ConsoleTarget: BaseTarget {
override public var defaultHashValue: Int { return 1 }
public override init() {
super.init()
// setting up colors
/*
reset = "\u{001B}[0m"
escape = "\u{001B}[0;"
logColor.verbose = "251m"
logColor.debug = "35m"
logColor.info = "38m"
logColor.warning = "178m"
logColor.error = "197m"
logColor.critical = "35m"
*/
if enableColors {
logColor.verbose = ""
logColor.debug = "➡ "
logColor.info = "❕ "
logColor.warning = "⚡ "
logColor.error = "❗ "
logColor.critical = "❌ "
}
}
override public func send(_ level: EXPLogger.LogLevel, msg: String, thread: String, file: String, function: String, line: Int) {
let formattedLog = formatMessage(level: level, msg: msg, thread: thread, file: file, function: function, line: line)
Swift.print(formattedLog)
}
}
| mit | 83c9a369d123fbd00714bc476d7d9dbe | 25.543478 | 132 | 0.546274 | 3.851735 | false | false | false | false |
netguru/inbbbox-ios | Unit Tests/ManagedShotsProviderSpec.swift | 1 | 1762 | //
// ManagedProjectsProviderSpec.swift
// Inbbbox
//
// Created by Lukasz Wolanczyk on 2/29/16.
// Copyright © 2016 Netguru Sp. z o.o. All rights reserved.
//
import Quick
import Nimble
import CoreData
import PromiseKit
@testable import Inbbbox
class ManagedShotsProviderSpec: QuickSpec {
override func spec() {
var sut: ManagedShotsProvider!
beforeEach {
sut = ManagedShotsProvider()
}
afterEach {
sut = nil
}
it("should have managed object context") {
expect(sut.managedObjectContext).toNot(beNil())
}
describe("provide my liked shots") {
var inMemoryManagedObjectContext: NSManagedObjectContext!
var likedShot: ManagedShot!
var returnedShots: [ManagedShot]!
beforeEach {
inMemoryManagedObjectContext = setUpInMemoryManagedObjectContext()
let managedObjectsProvider = ManagedObjectsProvider(managedObjectContext: inMemoryManagedObjectContext)
likedShot = managedObjectsProvider.managedShot(Shot.fixtureShot())
likedShot.liked = true
sut.managedObjectContext = inMemoryManagedObjectContext
firstly {
sut.provideMyLikedShots()
}.then { shots in
returnedShots = shots!.map { $0 as! ManagedShot }
}.catch { _ in }
}
it("should return 1 liked shot") {
expect(returnedShots.count).toEventually(equal(1))
let returnedLikedShot = returnedShots[0]
expect(returnedLikedShot.identifier).toEventually(equal(likedShot.identifier))
}
}
}
}
| gpl-3.0 | 65e637fd371cd118d47d79b65fcf3090 | 28.35 | 119 | 0.600795 | 5.418462 | false | false | false | false |
kemalenver/SwiftHackerRank | Tutorials/30 Days.playground/Pages/30 Days - Day 20 Sorting.xcplaygroundpage/Contents.swift | 1 | 917 |
import Foundation
var inputs = [ "3", "1 2 3"]
func readLine() -> String? {
let next = inputs.first
inputs.removeFirst()
return next
}
var n = Int(readLine()!)!
var arr = readLine()!.characters.split(separator: " ").map{ Int(String($0))! }
var totalSwaps = 0
for i in 0 ..< n {
// Track number of elements swapped during a single array traversal
var numberOfSwaps = 0
for j in 0 ..< n-1 {
// Swap adjacent elements if they are in decreasing order
if arr[j] > arr[j+1] {
swap(&arr[j], &arr[j+1])
numberOfSwaps += 1
}
}
totalSwaps += numberOfSwaps
// If no elements were swapped during a traversal, array is sorted
if numberOfSwaps == 0 {
break;
}
}
print("Array is sorted in \(totalSwaps) swaps.")
print("First Element: \(arr.first!)")
print("Last Element: \(arr.last!)") | mit | 5176d8e5b651cd0f63dffb979259fc00 | 19.863636 | 78 | 0.571429 | 3.852941 | false | false | false | false |
brentdax/swift | test/SILGen/guaranteed_normal_args_curry_thunks.swift | 1 | 16889 | // RUN: %target-swift-emit-silgen -parse-as-library -module-name Swift -parse-stdlib -enable-sil-ownership %s | %FileCheck %s
// This test checks specific codegen related to converting curry thunks to
// canonical representations when we are emitting guaranteed normal
// arguments. Eventually it will be merged into the normal SILGen tests.
//////////////////
// Declarations //
//////////////////
precedencegroup AssignmentPrecedence {
assignment: true
}
enum Optional<T> {
case none
case some(T)
}
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word) {
// This would usually contain an assert, but we don't need one since we are
// just emitting SILGen.
}
class Klass {
init() {}
}
typealias AnyObject = Builtin.AnyObject
protocol ProtocolInitNoArg {
init()
}
protocol ClassProtocolInitNoArg : class {
init()
}
protocol ProtocolInitAddressOnly {
associatedtype SubType : ProtocolInitNoArg
init(t: SubType)
init(t2: AddrOnlyStructInitGeneric<Klass>)
init(t3: AddrOnlyStructInitGeneric<SubType>)
}
protocol ProtocolInitClassProtocol {
associatedtype SubType : ClassProtocolInitNoArg
init(t: SubType)
}
protocol ProtocolInitLoadable {
init(t: Klass)
}
protocol ClassProtocolInitAddressOnly : class {
associatedtype SubType : ProtocolInitNoArg
init(t: SubType)
}
protocol ClassProtocolInitClassProtocol : class {
associatedtype SubType : ClassProtocolInitNoArg
init(t: SubType)
}
protocol ClassProtocolInitLoadable : class {
init(t: Klass)
}
class LoadableClassInitLoadable {
init(_ k: Klass) {}
}
struct LoadableStructInitLoadable {
var k: Klass
init(_ newK: Klass) {
k = newK
}
}
struct AddrOnlyStructInitGeneric<T> {
var k: T
init(_ newK: T) {
k = newK
}
}
///////////
// Tests //
///////////
// CHECK-LABEL: sil hidden @$ss021testLoadableClassInitB0yyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[THUNK_REF:%.*]] = function_ref @$ss017LoadableClassInitA0CyABs5KlassCcfCTcTd : $@convention(thin) (@thick LoadableClassInitLoadable.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @owned LoadableClassInitLoadable
// CHECK: [[CANONICAL_THUNK:%.*]] = apply [[THUNK_REF]](
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[CANONICAL_THUNK]]
// CHECK: [[BORROWED_CANONICAL_THUNK_COPY:%.*]] = copy_value [[BORROWED_CANONICAL_THUNK]]
// CHECK: [[ALLOCATING_INIT:%.*]] = function_ref @$ss5KlassCABycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[SELF:%.*]] = apply [[ALLOCATING_INIT]](
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[BORROWED_CANONICAL_THUNK_COPY]]
// CHECK: apply [[BORROWED_CANONICAL_THUNK]]([[BORROWED_SELF]])
// CHECK: } // end sil function '$ss021testLoadableClassInitB0yyF'
// Curry thunk.
//
// CHECK-LABEL: sil shared [thunk] @$ss017LoadableClassInitA0CyABs5KlassCcfCTcTd : $@convention(thin) (@thick LoadableClassInitLoadable.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @owned LoadableClassInitLoadable {
// CHECK: [[ALLOCATING_INIT_FN:%.*]] = function_ref @$ss017LoadableClassInitA0CyABs5KlassCcfC :
// CHECK: [[METATYPE_PA_ALLOCATING_INIT_FN:%.*]] = partial_apply [callee_guaranteed] [[ALLOCATING_INIT_FN]](
// CHECK: [[THUNK_FN:%.*]] = function_ref @$ss5KlassCs017LoadableClassInitB0CIegxo_AbDIeggo_TR :
// CHECK: [[THUNK_PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[METATYPE_PA_ALLOCATING_INIT_FN]]) : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @owned LoadableClassInitLoadable) -> @owned LoadableClassInitLoadable
// CHECK: return [[THUNK_PA]]
// CHECK: } // end sil function '$ss017LoadableClassInitA0CyABs5KlassCcfCTcTd'
// Canonical Thunk.
//
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$ss5KlassCs017LoadableClassInitB0CIegxo_AbDIeggo_TR : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @owned LoadableClassInitLoadable) -> @owned LoadableClassInitLoadable {
// CHECK: bb0([[CLASS:%.*]] : @guaranteed $Klass, [[PA:%.*]] : @guaranteed $@callee_guaranteed (@owned Klass) -> @owned LoadableClassInitLoadable):
// CHECK: [[CLASS_COPY:%.*]] = copy_value [[CLASS]]
// CHECK: [[RESULT:%.*]] = apply [[PA]]([[CLASS_COPY]])
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$ss5KlassCs017LoadableClassInitB0CIegxo_AbDIeggo_TR'
func testLoadableClassInitLoadable() {
let x = LoadableClassInitLoadable.init
let y = x(Klass())
}
// CHECK-LABEL: sil hidden @$ss022testLoadableStructInitB0yyF : $@convention(thin) () -> () {
// CHECK: [[THUNK_REF:%.*]] = function_ref @$ss018LoadableStructInitA0VyABs5KlassCcfCTc : $@convention(thin) (@thin LoadableStructInitLoadable.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @owned LoadableStructInitLoadable
// CHECK: [[CANONICAL_THUNK:%.*]] = apply [[THUNK_REF]](
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[CANONICAL_THUNK]]
// CHECK: [[BORROWED_CANONICAL_THUNK_COPY:%.*]] = copy_value [[BORROWED_CANONICAL_THUNK]]
// CHECK: [[ALLOCATING_INIT:%.*]] = function_ref @$ss5KlassCABycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[SELF:%.*]] = apply [[ALLOCATING_INIT]](
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[BORROWED_CANONICAL_THUNK_COPY]]
// CHECK: apply [[BORROWED_CANONICAL_THUNK]]([[BORROWED_SELF]])
// CHECK: } // end sil function '$ss022testLoadableStructInitB0yyF'
// Curry thunk.
//
// CHECK-LABEL: sil shared [thunk] @$ss018LoadableStructInitA0VyABs5KlassCcfCTc : $@convention(thin) (@thin LoadableStructInitLoadable.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @owned LoadableStructInitLoadable {
// CHECK: [[ALLOCATING_INIT_FN:%.*]] = function_ref @$ss018LoadableStructInitA0VyABs5KlassCcfC :
// CHECK: [[METATYPE_PA_ALLOCATING_INIT_FN:%.*]] = partial_apply [callee_guaranteed] [[ALLOCATING_INIT_FN]](
// CHECK: [[THUNK_FN:%.*]] = function_ref @$ss5KlassCs018LoadableStructInitB0VIegxo_AbDIeggo_TR : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @owned LoadableStructInitLoadable) -> @owned LoadableStructInitLoadable
// CHECK: [[THUNK_PA:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]([[METATYPE_PA_ALLOCATING_INIT_FN]])
// CHECK: return [[THUNK_PA]]
// CHECK: } // end sil function '$ss018LoadableStructInitA0VyABs5KlassCcfCTc'
// Canonical Thunk.
//
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$ss5KlassCs018LoadableStructInitB0VIegxo_AbDIeggo_TR : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @owned LoadableStructInitLoadable) -> @owned LoadableStructInitLoadable {
// CHECK: bb0([[CLASS:%.*]] : @guaranteed $Klass, [[PA:%.*]] : @guaranteed $@callee_guaranteed (@owned Klass) -> @owned LoadableStructInitLoadable):
// CHECK: [[CLASS_COPY:%.*]] = copy_value [[CLASS]]
// CHECK: [[RESULT:%.*]] = apply [[PA]]([[CLASS_COPY]])
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$ss5KlassCs018LoadableStructInitB0VIegxo_AbDIeggo_TR'
func testLoadableStructInitLoadable() {
let x = LoadableStructInitLoadable.init
let y = x(Klass())
}
// In this case we have a generic type that due to type lowering introduces an
// extra thunk.
//
// CHECK-LABEL: sil hidden @$ss37testAddrOnlyStructInitGenericConcreteyyF : $@convention(thin) () -> () {
// CHECK: [[THUNK_REF:%.*]] = function_ref @$ss25AddrOnlyStructInitGenericVyAByxGxcfCTc : $@convention(thin) <τ_0_0> (@thin AddrOnlyStructInitGeneric<τ_0_0>.Type) -> @owned @callee_guaranteed (@in_guaranteed τ_0_0) -> @out AddrOnlyStructInitGeneric<τ_0_0>
// CHECK: [[CURRY_THUNK:%.*]] = apply [[THUNK_REF]]<Klass>(
// CHECK: [[CANONICAL_THUNK_REF:%.*]] = function_ref @$ss5KlassCs25AddrOnlyStructInitGenericVyABGIegnr_AbEIeggo_TR : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@in_guaranteed Klass) -> @out AddrOnlyStructInitGeneric<Klass>) -> @owned AddrOnlyStructInitGeneric<Klass>
// CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_REF]]([[CURRY_THUNK]]) :
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[CANONICAL_THUNK]]
// CHECK: [[BORROWED_CANONICAL_THUNK_COPY:%.*]] = copy_value [[BORROWED_CANONICAL_THUNK]]
// CHECK: [[ALLOCATING_INIT:%.*]] = function_ref @$ss5KlassCABycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[SELF:%.*]] = apply [[ALLOCATING_INIT]](
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[BORROWED_CANONICAL_THUNK:%.*]] = begin_borrow [[BORROWED_CANONICAL_THUNK_COPY]]
// CHECK: apply [[BORROWED_CANONICAL_THUNK]]([[BORROWED_SELF]])
// Curry thunk
//
// CHECK-LABEL: sil shared [thunk] @$ss25AddrOnlyStructInitGenericVyAByxGxcfCTc : $@convention(thin) <T> (@thin AddrOnlyStructInitGeneric<T>.Type) -> @owned @callee_guaranteed (@in_guaranteed T) -> @out AddrOnlyStructInitGeneric<T> {
// CHECK: [[ALLOCATING_INIT_REF:%.*]] = function_ref @$ss25AddrOnlyStructInitGenericVyAByxGxcfC : $@convention(method) <τ_0_0> (@in τ_0_0, @thin AddrOnlyStructInitGeneric<τ_0_0>.Type) -> @out AddrOnlyStructInitGeneric<τ_0_0>
// CHECK: [[ALLOCATING_INIT:%.*]] = partial_apply [callee_guaranteed] [[ALLOCATING_INIT_REF]]<T>(
// CHECK: [[THUNK_REF:%.*]] = function_ref @$sxs25AddrOnlyStructInitGenericVyxGIegir_xACIegnr_lTR : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0, @guaranteed @callee_guaranteed (@in τ_0_0) -> @out AddrOnlyStructInitGeneric<τ_0_0>) -> @out AddrOnlyStructInitGeneric<τ_0_0>
// CHECK: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_REF]]<T>([[ALLOCATING_INIT]])
// CHECK: return [[THUNK]]
// CHECK: } // end sil function '$ss25AddrOnlyStructInitGenericVyAByxGxcfCTc'
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$sxs25AddrOnlyStructInitGenericVyxGIegir_xACIegnr_lTR : $@convention(thin) <T> (@in_guaranteed T, @guaranteed @callee_guaranteed (@in T) -> @out AddrOnlyStructInitGeneric<T>) -> @out AddrOnlyStructInitGeneric<T> {
// CHECK: bb0([[ARG0:%.*]] : @trivial $*AddrOnlyStructInitGeneric<T>, [[ARG1:%.*]] : @trivial $*T, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed (@in T) -> @out AddrOnlyStructInitGeneric<T>):
// CHECK: [[STACK:%.*]] = alloc_stack $T
// CHECK: copy_addr [[ARG1]] to [initialization] [[STACK]] : $*T
// CHECK: apply [[ARG2]]([[ARG0]], [[STACK]]) : $@callee_guaranteed (@in T) -> @out AddrOnlyStructInitGeneric<T>
// CHECK: } // end sil function '$sxs25AddrOnlyStructInitGenericVyxGIegir_xACIegnr_lTR'
// CHECK_LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @$ss5KlassCs25AddrOnlyStructInitGenericVyABGIegnr_AbEIeggo_TR : $@convention(thin) (@guaranteed Klass, @guaranteed @callee_guaranteed (@in_guaranteed Klass) -> @out AddrOnlyStructInitGeneric<Klass>) -> @owned AddrOnlyStructInitGeneric<Klass> {
// CHECK: bb0([[ARG0:%.*]] : @guaranteed $Klass, [[ARG1:%.*]] : @guaranteed $@callee_guaranteed (@in_guaranteed Klass) -> @out AddrOnlyStructInitGeneric<Klass>):
// CHECK: [[STACK:%.*]] = alloc_stack $Klass
// CHECK: [[ARG0_COPY:%.*]] = copy_value [[ARG0]]
// CHECK: store [[ARG0_COPY]] to [init] [[STACK]]
// CHECK: [[STACK2:%.*]] = alloc_stack $AddrOnlyStructInitGeneric<Klass>
// CHECK: apply [[ARG1]]([[STACK2]], [[STACK]]) : $@callee_guaranteed (@in_guaranteed Klass) -> @out AddrOnlyStructInitGeneric<Klass>
// CHECK: [[RESULT:%.*]] = load [take] [[STACK2]]
// CHECK: destroy_addr [[STACK]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '$ss5KlassCs25AddrOnlyStructInitGenericVyABGIegnr_AbEIeggo_TR'
func testAddrOnlyStructInitGenericConcrete() {
let x = AddrOnlyStructInitGeneric<Klass>.init
let y = x(Klass())
}
// CHECK-LABEL: sil hidden @$ss029testAddrOnlyStructInitGenericbC01tyx_ts08Protocole7AddressC0RzlF : $@convention(thin) <T where T : ProtocolInitAddressOnly> (@in_guaranteed T) -> () {
// CHECK: [[CURRY_THUNK_REF:%.*]] = function_ref @$ss25AddrOnlyStructInitGenericVyAByxGxcfCTc : $@convention(thin) <τ_0_0> (@thin AddrOnlyStructInitGeneric<τ_0_0>.Type) -> @owned @callee_guaranteed (@in_guaranteed τ_0_0) -> @out AddrOnlyStructInitGeneric<τ_0_0>
// CHECK: [[CURRY_THUNK:%.*]] = apply [[CURRY_THUNK_REF]]<T.SubType>(
// CHECK: [[Y:%.*]] = alloc_stack $AddrOnlyStructInitGeneric<T.SubType>, let, name "y"
// CHECK: [[BORROWED_CURRY_THUNK:%.*]] = begin_borrow [[CURRY_THUNK]]
// CHECK: [[COPY_BORROWED_CURRY_THUNK:%.*]] = copy_value [[BORROWED_CURRY_THUNK]]
// CHECK: [[TMP:%.*]] = alloc_stack $T.SubType
// CHECK: [[WITNESS_METHOD:%.*]] = witness_method $T.SubType, #ProtocolInitNoArg.init!allocator.1 : <Self where Self : ProtocolInitNoArg> (Self.Type) -> () -> Self : $@convention(witness_method: ProtocolInitNoArg) <τ_0_0 where τ_0_0 : ProtocolInitNoArg> (@thick τ_0_0.Type) -> @out τ_0_0
// CHECK: apply [[WITNESS_METHOD]]<T.SubType>([[TMP]],
// CHECK: [[BORROWED_CURRY_THUNK:%.*]] = begin_borrow [[COPY_BORROWED_CURRY_THUNK]]
// CHECK: apply [[BORROWED_CURRY_THUNK]]([[Y]], [[TMP]])
// CHECK: } // end sil function '$ss029testAddrOnlyStructInitGenericbC01tyx_ts08Protocole7AddressC0RzlF'
func testAddrOnlyStructInitGenericAddrOnly<T : ProtocolInitAddressOnly>(t: T) {
let x = AddrOnlyStructInitGeneric<T.SubType>.init
let y = x(T.SubType())
}
// CHECK-LABEL: sil hidden @$ss20testGenericInitClass1tyx_ts08ProtocolC8LoadableRzlF : $@convention(thin) <T where T : ProtocolInitLoadable> (@in_guaranteed T) -> () {
// CHECK: [[CURRY_THUNK_REF:%.*]] = function_ref @$ss20ProtocolInitLoadableP1txs5KlassC_tcfCTc : $@convention(thin) <τ_0_0 where τ_0_0 : ProtocolInitLoadable> (@thick τ_0_0.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @out τ_0_0
// CHECK: [[CURRY_THUNK:%.*]] = apply [[CURRY_THUNK_REF]]<T>(
// CHECK: [[Y:%.*]] = alloc_stack $T, let, name "y"
// CHECK: [[BORROWED_CURRY_THUNK:%.*]] = begin_borrow [[CURRY_THUNK]]
// CHECK: [[COPY_BORROWED_CURRY_THUNK:%.*]] = copy_value [[BORROWED_CURRY_THUNK]]
// CHECK: [[ALLOCATING_INIT:%.*]] = function_ref @$ss5KlassCABycfC : $@convention(method) (@thick Klass.Type) -> @owned Klass
// CHECK: [[SELF:%.*]] = apply [[ALLOCATING_INIT]](
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[BORROWED_CURRY_THUNK:%.*]] = begin_borrow [[COPY_BORROWED_CURRY_THUNK]]
// CHECK: apply [[BORROWED_CURRY_THUNK]]([[Y]], [[BORROWED_SELF]])
// CHECK: } // end sil function '$ss20testGenericInitClass1tyx_ts08ProtocolC8LoadableRzlF'
// Curry thunk.
//
// CHECK-LABEL: sil shared [thunk] @$ss20ProtocolInitLoadableP1txs5KlassC_tcfCTc : $@convention(thin) <Self where Self : ProtocolInitLoadable> (@thick Self.Type) -> @owned @callee_guaranteed (@guaranteed Klass) -> @out Self {
// CHECK: [[WITNESS_METHOD_REF:%.*]] = witness_method $Self, #ProtocolInitLoadable.init!allocator.1 : <Self where Self : ProtocolInitLoadable> (Self.Type) -> (Klass) -> Self : $@convention(witness_method: ProtocolInitLoadable) <τ_0_0 where τ_0_0 : ProtocolInitLoadable> (@owned Klass, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[WITNESS_METHOD:%.*]] = partial_apply [callee_guaranteed] [[WITNESS_METHOD_REF]]<Self>(
// CHECK: [[CANONICAL_THUNK_REF:%.*]] = function_ref @$ss5KlassCxIegxr_ABxIeggr_s20ProtocolInitLoadableRzlTR : $@convention(thin) <τ_0_0 where τ_0_0 : ProtocolInitLoadable> (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @out τ_0_0) -> @out τ_0_0
// CHECK: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] %3<Self>(%2) : $@convention(thin) <τ_0_0 where τ_0_0 : ProtocolInitLoadable> (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @out τ_0_0) -> @out τ_0_0
// CHECK: return [[CANONICAL_THUNK]]
// CHECK: } // end sil function '$ss20ProtocolInitLoadableP1txs5KlassC_tcfCTc'
// Canonical thunk
//
// CHECK-LABEL: sil shared [transparent] [serializable] [thunk] @$ss5KlassCxIegxr_ABxIeggr_s20ProtocolInitLoadableRzlTR : $@convention(thin) <Self where Self : ProtocolInitLoadable> (@guaranteed Klass, @guaranteed @callee_guaranteed (@owned Klass) -> @out Self) -> @out Self {
// CHECK: bb0([[ARG0:%.*]] : @trivial $*Self, [[ARG1:%.*]] : @guaranteed $Klass, [[ARG2:%.*]] : @guaranteed $@callee_guaranteed (@owned Klass) -> @out Self):
// CHECK: [[ARG1_COPY:%.*]] = copy_value [[ARG1]]
// CHECK: apply [[ARG2]]([[ARG0]], [[ARG1_COPY]])
// CHECK: } // end sil function '$ss5KlassCxIegxr_ABxIeggr_s20ProtocolInitLoadableRzlTR'
func testGenericInitClass<T : ProtocolInitLoadable>(t: T) {
let x = T.init
let y = x(Klass())
}
| apache-2.0 | d0928de544ae0b910ac63cadbcaf43cb | 61.414815 | 321 | 0.689651 | 3.444104 | false | true | false | false |
Dachande663/StatusCmd | StatusCmd/AppDelegate.swift | 1 | 3663 | //
// AppDelegate.swift
// StatusCmd
//
// Created by Luke Lanchester on 09/05/2015.
// Copyright (c) 2015 Luke Lanchester. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
let filemanager = NSFileManager.defaultManager()
let filename = ".statuscmd"
var file: String = ""
let resources = NSBundle.mainBundle().resourcePath
let statusBar = NSStatusBar.systemStatusBar()
var statusBarItem = NSStatusItem()
override func awakeFromNib() {
file = NSHomeDirectory() + "/" + filename
if (!filemanager.fileExistsAtPath(file)) {
makeDefaultFile(file)
}
statusBarItem = statusBar.statusItemWithLength(-1)
statusBarItem.highlightMode = true
if resources != nil {
statusBarItem.image = NSImage(contentsOfFile: resources!.stringByAppendingPathComponent("logo.png"))
}
updateMenu()
NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("updateMenu"), userInfo: nil, repeats: true)
}
func makeDefaultFile(file: String) {
if resources == nil {
return
}
let path = resources!.stringByAppendingPathComponent("default.json")
filemanager.copyItemAtPath(path, toPath: file, error: nil)
}
func updateMenu() {
var rootMenu = NSMenu()
if !filemanager.fileExistsAtPath(file) {
var item = NSMenuItem()
item.title = "Unable to open file"
rootMenu.addItem(item)
statusBarItem.menu = rootMenu
return
}
let data = NSData(contentsOfFile: file)!
let json = JSON(data: data)
// statusBarItem.title = json["bar"]["title"].stringValue
if(json["menu"] == nil) {
var item = NSMenuItem()
item.title = "Unable to read JSON"
rootMenu.addItem(item)
} else {
populateMenu(rootMenu, jsonMenu: json["menu"])
}
statusBarItem.menu = rootMenu
}
func populateMenu(menu: NSMenu, jsonMenu: JSON) {
for (key: String, jsonItem: JSON) in jsonMenu {
menu.addItem(makeItem(jsonItem))
}
}
func makeItem(jsonItem: JSON) -> NSMenuItem {
if(jsonItem["separator"].boolValue == true) {
return NSMenuItem.separatorItem()
}
var item = NSMenuItem()
item.title = jsonItem["title"].stringValue
if(jsonItem["enabled"].bool == false) {
item.enabled = false
} else {
item.representedObject = jsonItem.object
item.action = Selector("onClick:")
}
if let jsonMenu = jsonItem["menu"].array {
var submenu = NSMenu()
populateMenu(submenu, jsonMenu: jsonItem["menu"])
item.submenu = submenu
}
return item
}
func onClick(sender: AnyObject) {
let json = JSON(sender.representedObject as! NSDictionary)
if let command = json["command"].string {
if let args = json["arguments"].arrayObject {
let task = NSTask()
task.launchPath = json["command"].stringValue
task.arguments = json["arguments"].arrayObject!
task.launch()
}
}
}
}
| mit | 12258ed5f25c72e7f63620cd7aeb97e6 | 24.615385 | 128 | 0.538903 | 5.25538 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/WalletPayload/Sources/WalletPayloadKit/Services/Repo/WalletRepoCodingAPI.swift | 1 | 1278 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Foundation
public typealias WalletRepoStateEncoding = (_ value: WalletRepoState) -> Result<Data, WalletRepoStateCodingError>
public typealias WalletRepoStateDecoding = (_ data: Data) -> Result<WalletRepoState, WalletRepoStateCodingError>
public enum WalletRepoStateCodingError: LocalizedError, Equatable {
case encodingFailed(Error)
case decodingFailed(Error)
public var errorDescription: String? {
switch self {
case .decodingFailed(let error):
return "Wallet Repo Decoding Failure: \(error.localizedDescription)"
case .encodingFailed(let error):
return "Wallet Repo Encoding Failure: \(error.localizedDescription)"
}
}
public static func == (lhs: WalletRepoStateCodingError, rhs: WalletRepoStateCodingError) -> Bool {
switch (lhs, rhs) {
case (.encodingFailed(let lhsError), .encodingFailed(let rhsError)):
return lhsError.localizedDescription == rhsError.localizedDescription
case (.decodingFailed(let lhsError), .decodingFailed(let rhsError)):
return lhsError.localizedDescription == rhsError.localizedDescription
default:
return false
}
}
}
| lgpl-3.0 | 4dd15f2ebe44d7007c1fd016883bf793 | 40.193548 | 113 | 0.70556 | 4.874046 | false | false | false | false |
yarshure/Surf | Surf/const.swift | 1 | 9595 | //
// const.swift
// Surf
//
// Created by yarshure on 16/1/15.
// Copyright © 2016年 yarshure. All rights reserved.
//
import Foundation
let sampleConfig = "surf.conf"
let DefaultConfig = "Default.conf"
//let kSelect = "kSelectConf"
//var groupIdentifier = ""
#if os(iOS)
let groupIdentifier = "group.com.yarshure.Surf"
#else
let groupIdentifier = "745WQDK4L7.com.yarshure.Surf"
#endif
let configExt = ".conf"
let packetconfig = "group.com.yarshure.config"
let flagconfig = "group.com.yarshure.flag"
let onDemandKey = "com.yarshure.onDemandKey"
let errDomain = "com.abigt.socket"
let fm = FileManager.default
//#if os(iOS)
let proxyIpAddr:String = "240.7.1.10"
let loopbackAddr:String = "127.0.0.1"
let dnsAddr:String = "218.75.4.130"
let proxyHTTPSIpAddr:String = "240.7.1.11"
let xxIpAddr:String = "240.7.1.12"
let tunIP:String = "240.7.1.9"
// #else
//let proxyIpAddr:String = "240.0.0.3"
//let dnsAddr:String = "218.75.4.130"
//let proxyHTTPSIpAddr:String = "240.7.1.11"
//let tunIP:String = "240.200.200.200"
// #endif
let vpnServer:String = "240.89.6.4"
let httpProxyPort = 10080
let httpsocketProxyPort = 10080
let HttpsProxyPort = 10081
let agentsFile = "useragents.plist"
let kProxyGroup = "ProxyGroup"
let kProxyGroupFile = ".ProxyGroup"
var groupContainerURLVPN:String = ""
let iOSAppIden = "com.yarshure.Surf"
let iOSTodayIden = "com.yarshure.Surf.SurfToday"
let MacAppIden = "com.yarshure.Surf.mac"
let MacTunnelIden = "com.yarshure.Surf.mac.extension"
let iOSTunnelIden = "com.yarshure.Surf.PacketTunnel"
let configMacFn = "abigt.conf"
let NOTIFY_SERVER_PROFILES_CHANGED = "NOTIFY_SERVER_PROFILES_CHANGED"
let NOTIFY_ADV_PROXY_CONF_CHANGED = "NOTIFY_ADV_PROXY_CONF_CHANGED"
let NOTIFY_ADV_CONF_CHANGED = "NOTIFY_ADV_CONF_CHANGED"
let NOTIFY_HTTP_CONF_CHANGED = "NOTIFY_HTTP_CONF_CHANGED"
let NOTIFY_INVALIDE_QR = "NOTIFY_INVALIDE_QR"
let bId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String
let applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.yarshuremac.test" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
func groupContainerURL() ->URL{
#if os(macOS)
return fm.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!
#else
if bId == iOSAppIden || bId == iOSTodayIden || bId == MacAppIden {
return fm.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!
}else {
if !groupContainerURLVPN.isEmpty {
let path = readPathFromFile()
return URL.init(fileURLWithPath: path)
}else {
return fm.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!
}
}
#endif
//return URL.init(fileURLWithPath: "")
}
func readPathFromFile() ->String {
let url = applicationDocumentsDirectory.appendingPathComponent("groupContainerURLVPN")
do {
let s = try NSString.init(contentsOf: url, encoding: String.Encoding.utf8.rawValue)
return s as String
}catch _{
}
return ""
}
let supportEmail = "[email protected]"
let KEEP_APPLE_TCP = false
let kPro = "ProEdition"
let kConfig = "Config"
let kPath = "kPath"
let logdirURL = groupContainerURL().appendingPathComponent("Log")
/*
*
* Limit resource feature
*
*
*/
let proxyChangedOK = "select proxy changed"
let proxyChangedErr = "proxy change failure"
enum SFVPNXPSCommand:String{
case HELLO = "HELLO"
case RECNETREQ = "RECNETREQ"
case RULERESULT = "RULERESULT"
case STATUS = "STATUS"
case FLOWS = "FLOWS"
case LOADRULE = "LOADRULE"
case CHANGEPROXY = "CHANGEPROXY"
case UPDATERULE = "UPDATERULE"
var description: String {
switch self {
case .LOADRULE: return "LOADRULE"
case .HELLO: return "HELLO"
case .RECNETREQ : return "RECNETREQ"
case .RULERESULT: return "RULERESULT"
case .STATUS : return "STATUS"
case .FLOWS : return "FLOWS"
case .CHANGEPROXY : return "CHANGEPROXY"
case .UPDATERULE: return "UPDATERULE"
}
}
}
//let directDomains = ["apple.com",
// "icloud.com",
// "lcdn-registration.apple.com",
// "analytics.126.net",
// "baidu.com",
// "taobao.com",
// "alicdn.com",
// "cn",
// "qq.com",
// "jd.com",
// "126.net",
// "163.com",
// "alicdn.com",
// "amap.com",
// "bdimg.com",
// "bdstatic.com",
// "cnbeta.com",
// "cnzz.com",
// "douban.com",
// "gtimg.com",
// "hao123.com",
// "haosou.com",
// "ifeng.com",
// "iqiyi.com",
// "jd.com",
// "netease.com",
// "qhimg.com",
// "qq.com",
// "sogou.com",
// "sohu.com",
// "soso.com",
// "suning.com",
// "tmall.com",
// "tudou.com",
// "weibo.com",
// "youku.com",
// "xunlei.com",
// "zhihu.com",
// "ls.apple.com",
// "weather.com",
// "ykimg.com",
// "medium.com",
// "api.smoot.apple.com",
// "configuration.apple.com",
// "xp.apple.com",
// "smp-device-content.apple.com",
// "guzzoni.apple.com",
// "captive.apple.com",
// "ess.apple.com",
// "push.apple.com",
// "akadns.net",
// "outlook.com"]
//let proxyListDomains = ["cdninstagram.com",
// "twimg.com",
// "t.co",
// "kenengba.com",
// "akamai.net",
// "mzstatic.com",
// "itunes.com",
// "mzstatic.com",
// "me.com",
// "amazonaws.com",
// "android.com",
// "angularjs.org",
// "appspot.com",
// "akamaihd.net",
// "amazon.com",
// "bit.ly",
// "bitbucket.org",
// "blog.com",
// "blogcdn.com",
// "blogger.com",
// "blogsmithmedia.com",
// "box.net",
// "bloomberg.com",
// "chromium.org",
// "cl.ly",
// "cloudfront.net",
// "cloudflare.com",
// "cocoapods.org",
// "crashlytics.com",
// "dribbble.com",
// "dropbox.com",
// "dropboxstatic.com",
// "dropboxusercontent.com",
// "docker.com",
// "duckduckgo.com",
// "digicert.com",
// "dnsimple.com",
// "edgecastcdn.net",
// "engadget.com",
// "eurekavpt.com",
// "fb.me",
// "fbcdn.net",
// "fc2.com",
// "feedburner.com",
// "fabric.io",
// "flickr.com",
// "fastly.net",
// "ggpht.com",
// "github.com",
// "github.io",
// "githubusercontent.com",
// "golang.org",
// "goo.gl",
// "gstatic.com",
// "godaddy.com",
// "gravatar.com",
// "imageshack.us",
// "imgur.com",
// "jshint.com",
// "ift.tt",
// "j.mp",
// "kat.cr",
// "linode.com",
// "linkedin.com",
// "licdn.com",
// "lithium.com",
// "megaupload.com",
// "mobile01.com",
// "modmyi.com",
// "nytimes.com",
// "name.com",
// "openvpn.net",
// "openwrt.org",
// "ow.ly",
// "pinboard.in",
// "ssl-images-amazon.com",
// "sstatic.net",
// "stackoverflow.com",
// "staticflickr.com",
// "squarespace.com",
// "symcd.com",
// "symcb.com",
// "symauth.com",
// "ubnt.com",
// "t.co",
// "thepiratebay.org",
// "tumblr.com",
// "twimg.com",
// "twitch.tv",
// "twitter.com",
// "wikipedia.com",
// "wikipedia.org",
// "wikimedia.org",
// "wordpress.com",
// "wsj.com",
// "wsj.net",
// "wp.com",
// "vimeo.com",
// "youtu.be",
// "ytimg.com",
// "bbc.uk.co",
// "tapbots.com"]
| bsd-3-clause | 6ac7f28ddea3b8098062f6aafd43cf51 | 31.296296 | 194 | 0.471643 | 3.571109 | false | false | false | false |
skibadawid/DS-Stuff | DS Stuff/AppHelper.swift | 1 | 2456 | //
// AppHelper.swift
// DS Stuff
//
// Created by Dawid Skiba on 1/2/17.
// Copyright © 2017 Dawid Skiba. All rights reserved.
//
import Foundation
import UIKit
struct K {
// - - - - - - - - - - - - - - - - -
// MARK: Struct - Images
struct ImageName {
static let deadpool = "deadpool"
static let dog = "bestDogEver"
static let michael = "michael"
static let mugatu = "mugatu"
static let allNames = [deadpool, dog, michael, mugatu]
static var random: String {
let randomIndex = Int(arc4random_uniform(UInt32(allNames.count)))
return allNames[randomIndex]
}
}
// - - - - - - - - - - - - - - - - -
// MARK: Struct - Alert
struct Alert {
struct Button {
static let ok = "Ok"
static let no = "No"
static let yes = "Yaaas Master"
static let cancel = "Cancel"
static let delete = "Delete"
}
struct Title {
static let missing = "Something Wrong"
static let error = "Error"
static let confirm = "Confirm"
static let delete = "Confirm Deletion"
static let conflict = "Conflict"
}
struct Message {
static let networkIssue = "Seems you are not connected to the interweb. Please connect yourself."
}
}
}
extension UIColor {
static var xGreen: UIColor {
return UIColor(red:0.25, green:0.60, blue:0.33, alpha:1.00)
}
static var xYellow: UIColor {
return UIColor(red:1.00, green:0.84, blue:0.28, alpha:1.00)
}
static var xRed: UIColor {
return UIColor(red:0.90, green:0.35, blue:0.33, alpha:1.00)
}
static var xOrange: UIColor {
return UIColor(red:1.00, green:0.57, blue:0.13, alpha:1.00)
}
static var xBlue: UIColor {
return UIColor(red:0.10, green:0.48, blue:0.98, alpha:1.00)
}
static var xPurple: UIColor {
return UIColor(red:0.66, green:0.38, blue:0.84, alpha:1.00)
}
// Grouping
static let appColors = [UIColor.xGreen, UIColor.xYellow, UIColor.xRed, UIColor.xOrange, UIColor.xBlue, UIColor.xPurple]
static var randomAppColor: UIColor {
let randomIndex = Int(arc4random_uniform(UInt32(self.appColors.count)))
return self.appColors[randomIndex]
}
}
| mit | de2dcbf0cc63c0ca26a39fe27821cd39 | 25.978022 | 123 | 0.555193 | 3.669656 | false | false | false | false |
stolycizmus/WowToken | WowToken/GraphView.swift | 1 | 4436 | //
// GraphView.swift
// GraphView
//
// Created by Kadasi Mate on 2015. 11. 06..
// Copyright © 2015. Tairpake Inc. All rights reserved.
//
import UIKit
@IBDesignable class GraphView: UIView {
@IBInspectable var startColor: UIColor = UIColor.red
@IBInspectable var endColor: UIColor = UIColor.green
var graphPoints: [Double] = [4,2,6,4,5,8,3]
var nodata = false
override func draw(_ rect: CGRect) {
let width = rect.width
let height = rect.height
let path = UIBezierPath(roundedRect: rect, cornerRadius: 8.0)
path.addClip()
let context = UIGraphicsGetCurrentContext()
let colors = [startColor.cgColor, endColor.cgColor]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let colorLocation: [CGFloat] = [0.0, 1.0]
let gradient = CGGradient(colorsSpace: colorSpace, colors: colors as CFArray, locations: colorLocation)
var startPoint = CGPoint.zero
var endPoint = CGPoint(x: 0, y: self.bounds.height)
context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions())
//check if graphview should load with or without graph points (data)
if !nodata {
let margin: CGFloat = width*0.15
let columnXPoint = { (column: Int)->CGFloat in
let spacer = (width - margin*2 - 4) / CGFloat(self.graphPoints.count - 1)
var x: CGFloat = CGFloat(column)*spacer
x += margin+2
return x
}
let topBorder: CGFloat = height*0.2
let bottomBorder: CGFloat = height*0.2
let graphHeight = height - topBorder - bottomBorder
let maxValue = graphPoints.max()
let minValue = graphPoints.min()
let columnYPoint = { (graphPoint: Double)->CGFloat in
var y: CGFloat = CGFloat(graphPoint-minValue!) / CGFloat(maxValue!-minValue!) * graphHeight
y = graphHeight + topBorder - y
return y
}
UIColor.white.setFill()
UIColor.white.setStroke()
let graphPath = UIBezierPath()
graphPath.move(to: CGPoint(x: columnXPoint(0), y: columnYPoint(graphPoints[0])))
for i in 1..<graphPoints.count {
let nextPoint = CGPoint(x: columnXPoint(i), y: columnYPoint(graphPoints[i]))
graphPath.addLine(to: nextPoint)
}
context?.saveGState()
let clippingPath = graphPath.copy() as! UIBezierPath
clippingPath.addLine(to: CGPoint(x: columnXPoint(graphPoints.count-1), y: height))
clippingPath.addLine(to: CGPoint(x: columnXPoint(0), y: height))
clippingPath.close()
clippingPath.addClip()
let highestYPoint = columnYPoint(maxValue!)
startPoint = CGPoint(x: margin, y: highestYPoint)
endPoint = CGPoint(x: margin, y: self.bounds.height)
context?.drawLinearGradient(gradient!, start: startPoint, end: endPoint, options: CGGradientDrawingOptions())
context?.restoreGState()
graphPath.lineWidth = 2.0
graphPath.stroke()
let linePath = UIBezierPath()
linePath.move(to: CGPoint(x: margin, y: topBorder))
linePath.addLine(to: CGPoint(x: width - margin, y: topBorder))
linePath.move(to: CGPoint(x: margin, y: topBorder + graphHeight/2))
linePath.addLine(to: CGPoint(x: width - margin, y: topBorder + graphHeight/2))
linePath.move(to: CGPoint(x: margin, y: height - bottomBorder))
linePath.addLine(to: CGPoint(x: width - margin, y: height - bottomBorder))
linePath.move(to: CGPoint(x: margin, y: height - bottomBorder))
linePath.addLine(to: CGPoint(x: margin, y: height - bottomBorder + 8))
linePath.move(to: CGPoint(x: width/2, y: height - bottomBorder))
linePath.addLine(to: CGPoint(x: width/2, y: height - bottomBorder + 8))
linePath.move(to: CGPoint(x: width - margin, y: height - bottomBorder))
linePath.addLine(to: CGPoint(x: width - margin, y: height - bottomBorder + 8))
let color = UIColor(white: 1.0, alpha: 0.3)
color.setStroke()
linePath.lineWidth = 1.0
linePath.stroke()
}
}
}
| gpl-3.0 | 236946d149fe02409c905715073d8dfd | 36.584746 | 117 | 0.600451 | 4.488866 | false | false | false | false |
royhsu/RHGoogleMapsDirections | Sample/RHGoogleMapsDirections/Libraries/Alamofire.swift | 1 | 67042 | // Alamofire.swift
//
// Copyright (c) 2014–2015 Alamofire (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
/// Alamofire errors
public let AlamofireErrorDomain = "com.alamofire.error"
/**
HTTP method definitions.
See http://tools.ietf.org/html/rfc7231#section-4.3
*/
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
/**
Used to specify the way in which a set of parameters are applied to a URL request.
*/
public enum ParameterEncoding {
/**
A query string to be set as or appended to any existing URL query for `GET`, `HEAD`, and `DELETE` requests, or set as the body for requests with any other HTTP method. The `Content-Type` HTTP header field of an encoded request with HTTP body is set to `application/x-www-form-urlencoded`. Since there is no published specification for how to encode collection types, the convention of appending `[]` to the key for array values (`foo[]=1&foo[]=2`), and appending the key surrounded by square brackets for nested dictionary values (`foo[bar]=baz`).
*/
case URL
/**
Uses `NSJSONSerialization` to create a JSON representation of the parameters object, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/json`.
*/
case JSON
/**
Uses `NSPropertyListSerialization` to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The `Content-Type` HTTP header field of an encoded request is set to `application/x-plist`.
*/
case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
/**
Uses the associated closure value to construct a new request given an existing request and parameters.
*/
case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSURLRequest, NSError?))
/**
Creates a URL request by encoding parameters and applying them onto an existing request.
:param: URLRequest The request to have parameters applied
:param: parameters The parameters to apply
:returns: A tuple containing the constructed request and the error that occurred during parameter encoding, if any.
*/
public func encode(URLRequest: URLRequestConvertible, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if parameters == nil {
return (URLRequest.URLRequest, nil)
}
var mutableURLRequest: NSMutableURLRequest! = URLRequest.URLRequest.mutableCopy() as! NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String {
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += self.queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
let method = Method(rawValue: mutableURLRequest.HTTPMethod)
if method != nil && encodesParametersInURL(method!) {
if let URLComponents = NSURLComponents(URL: mutableURLRequest.URL!, resolvingAgainstBaseURL: false) {
URLComponents.percentEncodedQuery = (URLComponents.percentEncodedQuery != nil ? URLComponents.percentEncodedQuery! + "&" : "") + query(parameters!)
mutableURLRequest.URL = URLComponents.URL
}
} else {
if mutableURLRequest.valueForHTTPHeaderField("Content-Type") == nil {
mutableURLRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableURLRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON:
let options = NSJSONWritingOptions.allZeros
if let data = NSJSONSerialization.dataWithJSONObject(parameters!, options: options, error: &error) {
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
if let data = NSPropertyListSerialization.dataWithPropertyList(parameters!, format: format, options: options, error: &error) {
mutableURLRequest.setValue("application/x-plist", forHTTPHeaderField: "Content-Type")
mutableURLRequest.HTTPBody = data
}
case .Custom(let closure):
return closure(mutableURLRequest, parameters)
}
return (mutableURLRequest, error)
}
func queryComponents(key: String, _ value: AnyObject) -> [(String, String)] {
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
} else if let array = value as? [AnyObject] {
for value in array {
components += queryComponents("\(key)[]", value)
}
} else {
components.extend([(escape(key), escape("\(value)"))])
}
return components
}
func escape(string: String) -> String {
let legalURLCharactersToBeEscaped: CFStringRef = ":/?&=;+!@#$()',*"
return CFURLCreateStringByAddingPercentEscapes(nil, string, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as! String
}
}
// MARK: - URLStringConvertible
/**
Types adopting the `URLStringConvertible` protocol can be used to construct URL strings, which are then used to construct URL requests.
*/
public protocol URLStringConvertible {
/// The URL string.
var URLString: String { get }
}
extension String: URLStringConvertible {
public var URLString: String {
return self
}
}
extension NSURL: URLStringConvertible {
public var URLString: String {
return absoluteString!
}
}
extension NSURLComponents: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
extension NSURLRequest: URLStringConvertible {
public var URLString: String {
return URL!.URLString
}
}
// MARK: - URLRequestConvertible
/**
Types adopting the `URLRequestConvertible` protocol can be used to construct URL requests.
*/
public protocol URLRequestConvertible {
/// The URL request.
var URLRequest: NSURLRequest { get }
}
extension NSURLRequest: URLRequestConvertible {
public var URLRequest: NSURLRequest {
return self
}
}
// MARK: -
/**
Responsible for creating and managing `Request` objects, as well as their underlying `NSURLSession`.
When finished with a manager, be sure to call either `session.finishTasksAndInvalidate()` or `session.invalidateAndCancel()` before deinitialization.
*/
public class Manager {
/**
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 = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders
return Manager(configuration: configuration)
}()
/**
Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers.
:returns: The default header values.
*/
public static let defaultHTTPHeaders: [String: String] = {
// Accept-Encoding HTTP Header; see http://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 http://tools.ietf.org/html/rfc7231#section-5.3.5
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as! [String]) {
let q = 1.0 - (Double(index) * 0.1)
components.append("\(languageCode);q=\(q)")
if q <= 0.5 {
break
}
}
return join(",", components)
}()
// User-Agent Header; see http://tools.ietf.org/html/rfc7231#section-5.5.3
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
let os: AnyObject = NSProcessInfo.processInfo().operatingSystemVersionString ?? "Unknown"
var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString as! String
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
private let delegate: SessionDelegate
private let queue = dispatch_queue_create(nil, DISPATCH_QUEUE_SERIAL)
/// The underlying session.
public let session: NSURLSession
/// Whether to start requests immediately after being constructed. `true` by default.
public var startRequestsImmediately: Bool = true
/**
:param: configuration The configuration used to construct the managed session.
*/
required public init(configuration: NSURLSessionConfiguration? = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: delegate, delegateQueue: nil)
}
// MARK: -
/**
Creates a request for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, _ URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(encoding.encode(URLRequest(method, URLString), parameters: parameters).0)
}
/**
Creates a request for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: 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
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private let subdelegateQueue = dispatch_queue_create(nil, DISPATCH_QUEUE_CONCURRENT)
private 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
}
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required override init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
if sessionDidReceiveChallenge != nil {
completionHandler(sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
self[task] = nil
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
var disposition: NSURLSessionResponseDisposition = .Allow
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return (sessionDidBecomeInvalidWithError != nil)
case "URLSession:didReceiveChallenge:completionHandler:":
return (sessionDidReceiveChallenge != nil)
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return (sessionDidFinishEventsForBackgroundURLSession != nil)
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return (taskWillPerformHTTPRedirection != nil)
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return (dataTaskDidReceiveResponse != nil)
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return (dataTaskWillCacheResponse != nil)
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
/**
Responsible for sending a request and receiving the response and associated data from the server, as well as managing its underlying `NSURLSessionTask`.
*/
public class Request {
private let delegate: TaskDelegate
/// The underlying task.
public var task: NSURLSessionTask { return delegate.task }
/// The session belonging to the underlying task.
public let session: NSURLSession
/// The request sent or to be sent to the server.
public var request: NSURLRequest { return task.originalRequest }
/// The response received from the server, if any.
public var response: NSHTTPURLResponse? { return task.response as? NSHTTPURLResponse }
/// The progress of the request lifecycle.
public var progress: NSProgress? { return delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
switch task {
case is NSURLSessionUploadTask:
self.delegate = UploadTaskDelegate(task: task)
case is NSURLSessionDataTask:
self.delegate = DataTaskDelegate(task: task)
case is NSURLSessionDownloadTask:
self.delegate = DownloadTaskDelegate(task: task)
default:
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
/**
Associates an HTTP Basic credential with the request.
:param: user The user.
:param: password The password.
:returns: The request.
*/
public func authenticate(#user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
return authenticate(usingCredential: credential)
}
/**
Associates a specified credential with the request.
:param: credential The credential.
:returns: The request.
*/
public func authenticate(usingCredential credential: NSURLCredential) -> Self {
delegate.credential = credential
return self
}
// MARK: Progress
/**
Sets a closure to be called periodically during the lifecycle of the request as data is written to or read from the server.
- For uploads, the progress closure returns the bytes written, total bytes written, and total bytes expected to write.
- For downloads, the progress closure returns the bytes read, total bytes read, and total bytes expected to write.
:param: closure The code to be executed periodically during the lifecycle of the request.
:returns: The request.
*/
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let dataDelegate = delegate as? DataTaskDelegate {
dataDelegate.dataProgress = closure
} else if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
/**
A closure used by response handlers that takes a request, response, and data and returns a serialized object and any error that occured in the process.
*/
public typealias Serializer = (NSURLRequest, NSHTTPURLResponse?, NSData?) -> (AnyObject?, NSError?)
/**
Creates a response serializer that returns the associated data as-is.
:returns: A data response serializer.
*/
public class func responseDataSerializer() -> Serializer {
return { (request, response, data) in
return (data, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.responseDataSerializer(), completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: queue The queue on which the completion handler is dispatched.
:param: serializer The closure responsible for serializing the request, response, and data.
:param: completionHandler The code to be executed once the request has finished.
:returns: The request.
*/
public func response(queue: dispatch_queue_t? = nil, serializer: Serializer, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(delegate.queue) {
let (responseObject: AnyObject?, serializationError: NSError?) = serializer(self.request, self.response, self.delegate.data)
dispatch_async(queue ?? dispatch_get_main_queue()) {
completionHandler(self.request, self.response, responseObject, self.delegate.error ?? serializationError)
}
}
return self
}
/**
Suspends the request.
*/
public func suspend() {
task.suspend()
}
/**
Resumes the request.
*/
public func resume() {
task.resume()
}
/**
Cancels the request.
*/
public func cancel() {
if let downloadDelegate = delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
task.cancel()
}
}
class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t
let progress: NSProgress
var data: NSData? { return nil }
private(set) var error: NSError?
var credential: NSURLCredential?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
self.queue = {
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create((label as NSString).UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
return queue
}()
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession, task: NSURLSessionTask, willPerformHTTPRedirection response: NSHTTPURLResponse, newRequest request: NSURLRequest, completionHandler: ((NSURLRequest!) -> Void)) {
var redirectRequest = request
if taskWillPerformHTTPRedirection != nil {
redirectRequest = taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if taskDidReceiveChallenge != nil {
(disposition, credential) = taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
switch challenge.protectionSpace.authenticationMethod! {
case NSURLAuthenticationMethodServerTrust:
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
default:
credential = self.credential ?? session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
}
if credential != nil {
disposition = .UseCredential
}
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)) {
var bodyStream: NSInputStream?
if taskNeedNewBodyStream != nil {
bodyStream = taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
if error != nil {
self.error = error
}
dispatch_resume(queue)
}
}
class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return task as! NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData? {
return mutableData
}
private var expectedContentLength: Int64?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var dataProgress: ((bytesReceived: Int64, totalBytesReceived: Int64, totalBytesExpectedToReceive: Int64) -> Void)?
override init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: ((NSURLSessionResponseDisposition) -> Void)) {
var disposition: NSURLSessionResponseDisposition = .Allow
expectedContentLength = response.expectedContentLength
if dataTaskDidReceiveResponse != nil {
disposition = dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
dataTaskDidReceiveData?(session, dataTask, data)
mutableData.appendData(data)
if let expectedContentLength = dataTask.response?.expectedContentLength {
dataProgress?(bytesReceived: Int64(data.length), totalBytesReceived: Int64(mutableData.length), totalBytesExpectedToReceive: expectedContentLength)
}
}
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, willCacheResponse proposedResponse: NSCachedURLResponse, completionHandler: ((NSCachedURLResponse!) -> Void)) {
var cachedResponse = proposedResponse
if dataTaskWillCacheResponse != nil {
cachedResponse = dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
// MARK: - Validation
extension Request {
/**
A closure used to validate a request that takes a URL request and URL response, and returns whether the request was valid.
*/
public typealias Validation = (NSURLRequest, NSHTTPURLResponse) -> (Bool)
/**
Validates the request, using the specified closure.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: validation A closure to validate the request.
:returns: The request.
*/
public func validate(validation: Validation) -> Self {
dispatch_async(delegate.queue) {
if self.response != nil && self.delegate.error == nil {
if !validation(self.request, self.response!) {
self.delegate.error = NSError(domain: AlamofireErrorDomain, code: -1, userInfo: nil)
}
}
}
return self
}
// MARK: Status Code
/**
Validates that the response has a status code in the specified range.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: range The range of acceptable status codes.
:returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == Int>(statusCode acceptableStatusCode: S) -> Self {
return validate { (_, response) in
return contains(acceptableStatusCode, response.statusCode)
}
}
// MARK: Content-Type
private struct MIMEType {
let type: String
let subtype: String
init?(_ string: String) {
let components = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).substringToIndex(string.rangeOfString(";")?.endIndex ?? string.endIndex).componentsSeparatedByString("/")
if let type = components.first,
subtype = components.last
{
self.type = type
self.subtype = subtype
} else {
return nil
}
}
func matches(MIME: MIMEType) -> Bool {
switch (type, subtype) {
case (MIME.type, MIME.subtype), (MIME.type, "*"), ("*", MIME.subtype), ("*", "*"):
return true
default:
return false
}
}
}
/**
Validates that the response has a content type in the specified array.
If validation fails, subsequent calls to response handlers will have an associated error.
:param: contentType The acceptable content types, which may specify wildcard types and/or subtypes.
:returns: The request.
*/
public func validate<S : SequenceType where S.Generator.Element == String>(contentType acceptableContentTypes: S) -> Self {
return validate {(_, response) in
if let responseContentType = response.MIMEType,
responseMIMEType = MIMEType(responseContentType)
{
for contentType in acceptableContentTypes {
if let acceptableMIMEType = MIMEType(contentType)
where acceptableMIMEType.matches(responseMIMEType)
{
return true
}
}
}
return false
}
}
// MARK: Automatic
/**
Validates that the response has a status code in the default acceptable range of 200...299, and that the content type matches any specified in the Accept HTTP header field.
If validation fails, subsequent calls to response handlers will have an associated error.
:returns: The request.
*/
public func validate() -> Self {
let acceptableStatusCodes: Range<Int> = 200..<300
let acceptableContentTypes: [String] = {
if let accept = self.request.valueForHTTPHeaderField("Accept") {
return accept.componentsSeparatedByString(",")
}
return ["*/*"]
}()
return validate(statusCode: acceptableStatusCodes).validate(contentType: acceptableContentTypes)
}
}
// MARK: - Upload
extension Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Request {
var uploadTask: NSURLSessionUploadTask!
var HTTPBodyStream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = session.uploadTaskWithStreamedRequest(request)
HTTPBodyStream = stream
}
let request = Request(session: session, task: uploadTask)
if HTTPBodyStream != nil {
request.delegate.taskNeedNewBodyStream = { _, _ in
return HTTPBodyStream
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: File
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return upload(.File(URLRequest.URLRequest, file))
}
/**
Creates a request for uploading a file to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload
:returns: The created upload request.
*/
public func upload(method: Method, _ URLString: URLStringConvertible, file: NSURL) -> Request {
return upload(URLRequest(method, URLString), file: file)
}
// MARK: Data
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return upload(.Data(URLRequest.URLRequest, data))
}
/**
Creates a request for uploading data to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload
:returns: The created upload request.
*/
public func upload(method: Method, _ URLString: URLStringConvertible, data: NSData) -> Request {
return upload(URLRequest(method, URLString), data: data)
}
// MARK: Stream
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: stream The stream to upload
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return upload(.Stream(URLRequest.URLRequest, stream))
}
/**
Creates a request for uploading a stream to the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, _ URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return upload(URLRequest(method, URLString), stream: stream)
}
}
extension Request {
class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return task as! NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
// MARK: - Download
extension Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: Request.DownloadFileDestination) -> Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = session.downloadTaskWithResumeData(resumeData)
}
let request = Request(session: session, task: downloadTask)
if let downloadDelegate = request.delegate as? Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as! NSHTTPURLResponse)
}
}
delegate[request.delegate.task] = request.delegate
if startRequestsImmediately {
request.resume()
}
return request
}
// MARK: Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, _ URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(URLRequest(method, URLString), destination: destination)
}
/**
Creates a request for downloading from the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return download(.Request(URLRequest.URLRequest), destination: destination)
}
// MARK: Resume Data
/**
Creates a request for downloading from the resume data produced from a previous request cancellation.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData: NSData, destination: Request.DownloadFileDestination) -> Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Request {
/**
A closure executed once a request has successfully completed in order to determine where to move the temporary file written to during the download process. The closure takes two arguments: the temporary file URL and the URL response, and returns a single argument: the file URL where the temporary file should be moved.
*/
public typealias DownloadFileDestination = (NSURL, NSHTTPURLResponse) -> (NSURL)
/**
Creates a download file destination closure which uses the default file manager to move the temporary file to a file URL in the first available directory with the specified search path directory and search path domain mask.
:param: directory The search path directory. `.DocumentDirectory` by default.
:param: domain The search path domain mask. `.UserDomainMask` by default.
:returns: A download file destination closure.
*/
public class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> DownloadFileDestination {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(directory, inDomains: domain)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename!)
}
return temporaryURL
}
}
class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return task as! NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData?
override var data: NSData? { return resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
if downloadTaskDidFinishDownloadingToURL != nil {
let destination = downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
if fileManagerError != nil {
error = fileManagerError
}
}
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
}
}
// MARK: - Printable
extension Request: Printable {
/// The textual representation used when written to an `OutputStreamType`, which includes the HTTP method and URL, as well as the response status code if a response has been received.
public var description: String {
var components: [String] = []
if request.HTTPMethod != nil {
components.append(request.HTTPMethod!)
}
components.append(request.URL!.absoluteString!)
if response != nil {
components.append("(\(response!.statusCode))")
}
return join(" ", components)
}
}
extension Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = request.URL
if request.HTTPMethod != nil && request.HTTPMethod != "GET" {
components.append("-X \(request.HTTPMethod!)")
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL!.host!, port: URL!.port?.integerValue ?? 0, `protocol`: URL!.scheme!, realm: URL!.host!, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
for credential: NSURLCredential in (credentials as! [NSURLCredential]) {
components.append("-u \(credential.user!):\(credential.password!)")
}
} else {
if let credential = delegate.credential {
components.append("-u \(credential.user!):\(credential.password!)")
}
}
}
// Temporarily disabled on OS X due to build failure for CocoaPods
// See https://github.com/CocoaPods/swift/issues/24
#if !os(OSX)
if let cookieStorage = session.configuration.HTTPCookieStorage,
cookies = cookieStorage.cookiesForURL(URL!) as? [NSHTTPCookie]
where !cookies.isEmpty
{
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value ?? String());" }
components.append("-b \"\(string.substringToIndex(string.endIndex.predecessor()))\"")
}
#endif
if request.allHTTPHeaderFields != nil {
for (field, value) in request.allHTTPHeaderFields! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if session.configuration.HTTPAdditionalHeaders != nil {
for (field, value) in session.configuration.HTTPAdditionalHeaders! {
switch field {
case "Cookie":
continue
default:
components.append("-H \"\(field): \(value)\"")
}
}
}
if let HTTPBody = request.HTTPBody,
escapedBody = NSString(data: HTTPBody, encoding: NSUTF8StringEncoding)?.stringByReplacingOccurrencesOfString("\"", withString: "\\\"")
{
components.append("-d \"\(escapedBody)\"")
}
components.append("\"\(URL!.absoluteString!)\"")
return join(" \\\n\t", components)
}
/// The textual representation used when written to an `OutputStreamType`, in the form of a cURL command.
public var debugDescription: String {
return cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Request {
/**
Creates a response serializer that returns a string initialized from the response data with the specified string encoding.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:returns: A string response serializer.
*/
public class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> Serializer {
return { (_, _, data) in
let string = NSString(data: data!, encoding: encoding)
return (string, nil)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: encoding The string encoding. `NSUTF8StringEncoding` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the string, if one could be created from the URL response and data, and any error produced while creating the string.
:returns: The request.
*/
public func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Request {
/**
Creates a response serializer that returns a JSON object constructed from the response data using `NSJSONSerialization` with the specified reading options.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:returns: A JSON object response serializer.
*/
public class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var serializationError: NSError?
let JSON: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: options The JSON serialization reading options. `.AllowFragments` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the JSON object, if one could be created from the URL response and data, and any error produced while creating the JSON object.
:returns: The request.
*/
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Request {
/**
Creates a response serializer that returns an object constructed from the response data using `NSPropertyListSerialization` with the specified reading options.
:param: options The property list reading options. `0` by default.
:returns: A property list object response serializer.
*/
public class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> Serializer {
return { (request, response, data) in
if data == nil || data?.length == 0 {
return (nil, nil)
}
var propertyListSerializationError: NSError?
let plist: AnyObject? = NSPropertyListSerialization.propertyListWithData(data!, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
/**
Adds a handler to be called once the request has finished.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
/**
Adds a handler to be called once the request has finished.
:param: options The property list reading options. `0` by default.
:param: completionHandler A closure to be executed once the request has finished. The closure takes 4 arguments: the URL request, the URL response, if one was received, the property list, if one could be created from the URL response and data, and any error produced while creating the property list.
:returns: The request.
*/
public func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience -
private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
mutableURLRequest.HTTPMethod = method.rawValue
return mutableURLRequest
}
// MARK: - Request
/**
Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method.
:param: URLString The URL string.
:param: parameters The parameters. `nil` by default.
:param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.
*/
public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return Manager.sharedInstance.request(method, URLString, parameters: parameters, encoding: encoding)
}
/**
Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.
*/
public func request(URLRequest: URLRequestConvertible) -> Request {
return Manager.sharedInstance.request(URLRequest.URLRequest)
}
// MARK: - Upload
// MARK: File
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and file.
:param: method The HTTP method.
:param: URLString The URL string.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(method, URLString, file: file)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and file.
:param: URLRequest The URL request.
:param: file The file to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request {
return Manager.sharedInstance.upload(URLRequest, file: file)
}
// MARK: Data
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and data.
:param: method The HTTP method.
:param: URLString The URL string.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(method, URLString, data: data)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and data.
:param: URLRequest The URL request.
:param: data The data to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, data: NSData) -> Request {
return Manager.sharedInstance.upload(URLRequest, data: data)
}
// MARK: Stream
/**
Creates an upload request using the shared manager instance for the specified method, URL string, and stream.
:param: method The HTTP method.
:param: URLString The URL string.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(method: Method, URLString: URLStringConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(method, URLString, stream: stream)
}
/**
Creates an upload request using the shared manager instance for the specified URL request and stream.
:param: URLRequest The URL request.
:param: stream The stream to upload.
:returns: The created upload request.
*/
public func upload(URLRequest: URLRequestConvertible, stream: NSInputStream) -> Request {
return Manager.sharedInstance.upload(URLRequest, stream: stream)
}
// MARK: - Download
// MARK: URL Request
/**
Creates a download request using the shared manager instance for the specified method and URL string.
:param: method The HTTP method.
:param: URLString The URL string.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(method: Method, URLString: URLStringConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(method, URLString, destination: destination)
}
/**
Creates a download request using the shared manager instance for the specified URL request.
:param: URLRequest The URL request.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(URLRequest: URLRequestConvertible, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(URLRequest, destination: destination)
}
// MARK: Resume Data
/**
Creates a request using the shared manager instance for downloading from the resume data produced from a previous request cancellation.
:param: resumeData The resume data. This is an opaque data blob produced by `NSURLSessionDownloadTask` when a task is cancelled. See `NSURLSession -downloadTaskWithResumeData:` for additional information.
:param: destination The closure used to determine the destination of the downloaded file.
:returns: The created download request.
*/
public func download(resumeData data: NSData, destination: Request.DownloadFileDestination) -> Request {
return Manager.sharedInstance.download(data, destination: destination)
}
| mit | 11f8cbfad62c95fe9fb44eec3125f56f | 39.803408 | 555 | 0.668138 | 5.669345 | false | false | false | false |
allbto/WayThere | ios/WayThere/WayThere/Classes/Models/TableViewCells.swift | 2 | 493 | //
// TableViewCells.swift
// WayThere
//
// Created by Allan BARBATO on 5/20/15.
// Copyright (c) 2015 Allan BARBATO. All rights reserved.
//
import Foundation
enum CellType : String
{
case SwitchCell = "SwitchCellIdentifier"
case SelectCell = "SelectCellIdentifier"
case CityWeatherCell = "CityWeatherCellIdentifier"
}
typealias Cell = (title: String, key: String, value: AnyObject?, type: CellType, data: [AnyObject]?)
typealias Section = (title: String, cells: [Cell])
| mit | e907f231dd585047c4c9324229a0be83 | 23.65 | 100 | 0.713996 | 3.679104 | false | false | false | false |
calkinssean/woodshopBMX | WoodshopBMX/Pods/Charts/Charts/Classes/Data/Implementations/Standard/ScatterChartData.swift | 13 | 1453 | //
// ScatterChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class ScatterChartData: BarLineScatterCandleBubbleChartData
{
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [IChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
/// - returns: the maximum shape-size across all DataSets.
public func getGreatestShapeSize() -> CGFloat
{
var max = CGFloat(0.0)
for set in _dataSets
{
let scatterDataSet = set as? IScatterChartDataSet
if (scatterDataSet == nil)
{
print("ScatterChartData: Found a DataSet which is not a ScatterChartDataSet", terminator: "\n")
}
else
{
let size = scatterDataSet!.scatterShapeSize
if (size > max)
{
max = size
}
}
}
return max
}
}
| apache-2.0 | 6851fc2bdd99838f30401d8ffaf45e00 | 23.216667 | 111 | 0.549209 | 4.892256 | false | false | false | false |
banxi1988/BXCityPicker | Pod/Classes/City.swift | 1 | 1089 | //
// City.swift
// Pods
//
// Created by Haizhen Lee on 11/22/16.
//
//
import Foundation
import SwiftyJSON
import BXModel
//City(tos,eq,hash):
//name;code;pinyin;District:[r
public struct City :BXModel,RegionInfo{
public let name : String
public let code : String
public let pinyin : String
public let children : [District]
public init(json:JSON){
self.name = json["name"].stringValue
self.code = json["code"].stringValue
self.pinyin = json["pinyin"].stringValue
self.children = District.arrayFrom(json["children"])
}
public func toDict() -> [String:Any]{
var dict : [String:Any] = [ : ]
dict["name"] = self.name
dict["code"] = self.code
dict["pinyin"] = self.pinyin
dict["children"] = self.children.map{ $0.toDict() }
return dict
}
}
extension City: Equatable{
}
public func ==(lhs:City,rhs:City) -> Bool{
return lhs.code == rhs.code
}
extension City : Hashable{
public var hashValue:Int{ return code.hashValue }
}
extension City : CustomStringConvertible{
public var description:String { return name }
}
| mit | 8a7c956f65cd70374e771042492667b5 | 19.942308 | 56 | 0.662994 | 3.457143 | false | false | false | false |
kaunteya/InfoButton | InfoButton.swift | 1 | 5653 | //
// InfoButton.swift
// InfoButton
//
// Created by Kauntey Suryawanshi on 25/06/15.
// Copyright (c) 2015 Kauntey Suryawanshi. All rights reserved.
//
import Foundation
import Cocoa
@IBDesignable
open class InfoButton : NSControl, NSPopoverDelegate {
var mainSize: CGFloat!
@IBInspectable var showOnHover: Bool = false
@IBInspectable var fillMode: Bool = true
@IBInspectable var animatePopover: Bool = false
@IBInspectable var content: String = ""
@IBInspectable var primaryColor: NSColor = NSColor.scrollBarColor
var secondaryColor: NSColor = NSColor.white
var mouseInside = false {
didSet {
self.needsDisplay = true
if showOnHover {
if popover == nil {
popover = NSPopover(content: self.content, doesAnimate: self.animatePopover)
}
if mouseInside {
popover.show(relativeTo: self.frame, of: self.superview!, preferredEdge: NSRectEdge.maxX)
} else {
popover.close()
}
}
}
}
var trackingArea: NSTrackingArea!
override open func updateTrackingAreas() {
super.updateTrackingAreas()
if trackingArea != nil {
self.removeTrackingArea(trackingArea)
}
trackingArea = NSTrackingArea(rect: self.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil)
self.addTrackingArea(trackingArea)
}
fileprivate var stringAttributeDict = [String: AnyObject]()
fileprivate var circlePath: NSBezierPath!
var popover: NSPopover!
required public init?(coder: NSCoder) {
super.init(coder: coder)
let frameSize = self.frame.size
if frameSize.width != frameSize.height {
self.frame.size.height = self.frame.size.width
}
self.mainSize = self.frame.size.height
stringAttributeDict[convertFromNSAttributedStringKey(NSAttributedString.Key.font)] = NSFont.systemFont(ofSize: mainSize * 0.6)
let inSet: CGFloat = 2
let rect = NSMakeRect(inSet, inSet, mainSize - inSet * 2, mainSize - inSet * 2)
circlePath = NSBezierPath(ovalIn: rect)
}
override open func draw(_ dirtyRect: NSRect) {
var activeColor: NSColor!
if mouseInside || (popover != nil && popover!.isShown){
activeColor = primaryColor
} else {
activeColor = primaryColor.withAlphaComponent(0.35)
}
if fillMode {
activeColor.setFill()
circlePath.fill()
stringAttributeDict[convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)] = secondaryColor
} else {
activeColor.setStroke()
circlePath.stroke()
stringAttributeDict[convertFromNSAttributedStringKey(NSAttributedString.Key.foregroundColor)] = (mouseInside ? primaryColor : primaryColor.withAlphaComponent(0.35))
}
let attributedString = NSAttributedString(string: "?", attributes: convertToOptionalNSAttributedStringKeyDictionary(stringAttributeDict))
let stringLocation = NSMakePoint(mainSize / 2 - attributedString.size().width / 2, mainSize / 2 - attributedString.size().height / 2)
attributedString.draw(at: stringLocation)
}
override open func mouseDown(with theEvent: NSEvent) {
if popover == nil {
popover = NSPopover(content: self.content, doesAnimate: self.animatePopover)
}
if popover.isShown {
popover.close()
} else {
popover.show(relativeTo: self.frame, of: self.superview!, preferredEdge: NSRectEdge.maxX)
}
}
override open func mouseEntered(with theEvent: NSEvent) { mouseInside = true }
override open func mouseExited(with theEvent: NSEvent) { mouseInside = false }
}
//MARK: Extension for making a popover from string
extension NSPopover {
convenience init(content: String, doesAnimate: Bool) {
self.init()
self.behavior = NSPopover.Behavior.transient
self.animates = doesAnimate
self.contentViewController = NSViewController()
self.contentViewController!.view = NSView(frame: NSZeroRect)//remove this ??
let popoverMargin = CGFloat(20)
let textField: NSTextField = {
content in
let textField = NSTextField(frame: NSZeroRect)
textField.isEditable = false
textField.stringValue = content
textField.isBordered = false
textField.drawsBackground = false
textField.sizeToFit()
textField.setFrameOrigin(NSMakePoint(popoverMargin, popoverMargin))
return textField
}(content)
self.contentViewController!.view.addSubview(textField)
var viewSize = textField.frame.size; viewSize.width += (popoverMargin * 2); viewSize.height += (popoverMargin * 2)
self.contentSize = viewSize
}
}
//NSMinXEdge NSMinYEdge NSMaxXEdge NSMaxYEdge
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| mit | 3e7ae92c84a82aa0349bbbea15f75d1f | 36.190789 | 178 | 0.659473 | 5.115837 | false | false | false | false |
onevcat/CotEditor | CotEditor/Sources/MultipleReplacement.swift | 1 | 7083 | //
// MultipleReplacement.swift
//
// CotEditor
// https://coteditor.com
//
// Created by 1024jp on 2017-02-19.
//
// ---------------------------------------------------------------------------
//
// © 2017-2020 1024jp
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
final class MultipleReplacement: Codable {
struct Replacement {
var findString: String
var replacementString: String
var usesRegularExpression: Bool = false
var ignoresCase: Bool = false
var description: String?
var isEnabled = true
}
struct Settings: Equatable {
var textualOptions: String.CompareOptions = []
var regexOptions: NSRegularExpression.Options = [.anchorsMatchLines]
var matchesFullWord: Bool = false
var unescapesReplacementString: Bool = true
}
var replacements: [Replacement] = []
var settings: Settings = .init()
}
extension MultipleReplacement.Replacement {
init() {
self.findString = ""
self.replacementString = ""
}
}
// MARK: - Replacement
extension MultipleReplacement {
struct Result {
var string: String
var selectedRanges: [NSRange]?
var count = 0
}
// MARK: Public Methods
/// Batch-find in given string.
///
/// - Parameters:
/// - string: The string to find in.
/// - ranges: The ranges of selection in the text view.
/// - inSelection: Whether find only in selection.
/// - block: The block enumerates the matches.
/// - stop: A reference to a Bool value. The block can set the value to true to stop further processing.
/// - Returns: The found ranges. This method will return first all search finished.
func find(string: String, ranges: [NSRange], inSelection: Bool, using block: (_ stop: inout Bool) -> Void) -> [NSRange] {
var result: [NSRange] = []
guard !string.isEmpty else { return result }
for replacement in self.replacements where replacement.isEnabled {
let mode = replacement.mode(settings: self.settings)
// -> Invalid replacement rules will just be ignored.
guard let textFind = try? TextFind(for: string, findString: replacement.findString, mode: mode, inSelection: inSelection, selectedRanges: ranges) else { continue }
// process find
var isCancelled = false
textFind.findAll { (ranges, stop) in
block(&stop)
isCancelled = stop
result.append(ranges.first!)
}
guard !isCancelled else { return [] }
}
return result
}
/// Batch-replace matches in given string.
///
/// - Parameters:
/// - string: The string to replace.
/// - ranges: The ranges of selection in the text view.
/// - inSelection: Whether replace only in selection.
/// - block: The block enumerates the matches.
/// - stop: A reference to a Bool value. The block can set the value to true to stop further processing.
/// - Returns: The result of the replacement. This method will return first all replacement finished.
func replace(string: String, ranges: [NSRange], inSelection: Bool, using block: @escaping (_ stop: inout Bool) -> Void) -> Result {
var result = Result(string: string, selectedRanges: ranges)
guard !string.isEmpty else { return result }
for replacement in self.replacements where replacement.isEnabled {
let mode = replacement.mode(settings: self.settings)
let findRanges = result.selectedRanges ?? [result.string.nsRange]
// -> Invalid replacement rules will just be ignored.
guard let textFind = try? TextFind(for: result.string, findString: replacement.findString, mode: mode, inSelection: inSelection, selectedRanges: findRanges) else { continue }
// process replacement
var isCancelled = false
let (replacementItems, selectedRanges) = textFind.replaceAll(with: replacement.replacementString) { (flag, stop) in
switch flag {
case .findProgress, .foundCount:
break
case .replacementProgress:
result.count += 1
block(&stop)
isCancelled = stop
}
}
// finish if cancelled
guard !isCancelled else { return Result(string: string, selectedRanges: ranges) }
// update string
for item in replacementItems.reversed() {
result.string = (result.string as NSString).replacingCharacters(in: item.range, with: item.string)
}
// update selected ranges
result.selectedRanges = selectedRanges
}
return result
}
}
private extension MultipleReplacement.Replacement {
/// create TextFind.Mode with Replacement
func mode(settings: MultipleReplacement.Settings) -> TextFind.Mode {
if self.usesRegularExpression {
let options = settings.regexOptions.union(self.ignoresCase ? [.caseInsensitive] : [])
return .regularExpression(options: options, unescapesReplacement: settings.unescapesReplacementString)
} else {
let options = settings.textualOptions.union(self.ignoresCase ? [.caseInsensitive] : [])
return .textual(options: options, fullWord: settings.matchesFullWord)
}
}
}
// MARK: - Validation
extension MultipleReplacement.Replacement {
/// Check if replacement rule is valid.
///
/// - Throws: `TextFind.Error`
func validate(regexOptions: NSRegularExpression.Options = []) throws {
guard !self.findString.isEmpty else {
throw TextFind.Error.emptyFindString
}
if self.usesRegularExpression {
do {
_ = try NSRegularExpression(pattern: self.findString, options: regexOptions)
} catch {
throw TextFind.Error.regularExpression(reason: error.localizedDescription)
}
}
}
}
| apache-2.0 | f15f98a281cd4d256d24b1a59ab601cc | 31.787037 | 186 | 0.586275 | 5.158048 | false | false | false | false |
alexanderedge/European-Sports | EurosportKit/Models/Router.swift | 1 | 6427 | //
// Router.swift
// EurosportPlayer
//
// Created by Alexander Edge on 14/05/2016.
import Foundation
import CoreData
public protocol URLRequestConvertible {
var request: URLRequest { get }
}
struct Router {
fileprivate static func standardRequest(_ url: URL) -> URLRequest {
var req = URLRequest(url: url)
req.setValue("EurosportPlayer PROD/5.2.2 (iPad; iOS 10.2; Scale/2.00)", forHTTPHeaderField: "User-Agent")
return req
}
enum User: URLRequestConvertible {
case login(email: String, password: String)
fileprivate var baseURL: URL {
return URL(string : "https://crm-partners.eurosportplayer.com/")!
}
var path: String {
return "JsonPlayerCrmApi.svc/login"
}
var request: URLRequest {
switch self {
case .login(let email, let password):
var params = [String: String]()
let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "p": 9, "l": "EN", "d": 2, "mn": "iPad", "v": "5.2.2", "tt": "Pad", "li": 2, "s": 1, "b": 7], options: [])
params["context"] = String(data: contextData, encoding: .utf8)
let identifier = UIDevice.current.identifierForVendor!.uuidString
let data = try! JSONSerialization.data(withJSONObject: ["email": email, "password": password, "udid": identifier], options: [])
params["data"] = String(data: data, encoding: .utf8)
var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)!
URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)})
let url = URLComponents.url!
return Router.standardRequest(url)
}
}
}
enum AuthToken: URLRequestConvertible {
case fetch(userId: String, hkey: String)
fileprivate var baseURL: URL {
return URL(string : "https://videoshop-partners.eurosportplayer.com/")!
}
var path: String {
return "JsonProductService.svc/GetToken"
}
var request: URLRequest {
switch self {
case .fetch(let userId, let hkey):
var params = [String: String]()
let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: [])
params["context"] = String(data: contextData, encoding: String.Encoding.utf8)
let data = try! JSONSerialization.data(withJSONObject: ["userid": userId, "hkey": hkey], options: [])
params["data"] = String(data: data, encoding: String.Encoding.utf8)
var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)!
URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)})
let url = URLComponents.url!
return Router.standardRequest(url)
}
}
}
fileprivate enum Language: String {
case German = "de"
case English = "en"
case French = "fr"
fileprivate var identifier: Int {
switch self {
case .German:
return 1
case .English:
return 2
case .French:
return 3
}
}
static var preferredLanguage: Language {
guard let preferredLanguage = Locale.preferredLanguages.first, let language = Language(rawValue: preferredLanguage) else {
return .English
}
return language
}
}
enum Catchup: URLRequestConvertible {
case fetch
fileprivate var baseURL: URL {
return URL(string : "https://videoshop-partners.eurosportplayer.com/")!
}
var path: String {
return "JsonProductService.svc/GetAllCatchupCache"
}
var request: URLRequest {
switch self {
case .fetch:
var params = [String: String]()
let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: [])
params["context"] = String(data: contextData, encoding: .utf8)
let data = try! JSONSerialization.data(withJSONObject: ["languageid": Language.preferredLanguage.identifier], options: [])
params["data"] = String(data: data, encoding: String.Encoding.utf8)
var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)!
URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)})
let url = URLComponents.url!
return Router.standardRequest(url)
}
}
}
enum Channel: URLRequestConvertible {
case fetch
fileprivate var baseURL: URL {
return URL(string : "https://videoshop-partners.eurosportplayer.com/")!
}
var path: String {
return "JsonProductService.svc/GetAllChannelsCache"
}
var request: URLRequest {
switch self {
case .fetch:
var params = [String: String]()
let contextData = try! JSONSerialization.data(withJSONObject: ["g": "GB", "d": 2], options: [])
params["context"] = String(data: contextData, encoding: .utf8)
let data = try! JSONSerialization.data(withJSONObject:
["languageid": Language.preferredLanguage.identifier,
"isfullaccess": 0,
"withouttvscheduleliveevents": "true",
"groupchannels": "true",
"pictureformatids": "[87]",
"isbroadcasted": 1], options: [])
params["data"] = String(data: data, encoding: .utf8)
var URLComponents = Foundation.URLComponents(url: URL(string: path, relativeTo: baseURL)!, resolvingAgainstBaseURL: true)!
URLComponents.queryItems = params.map({URLQueryItem(name: $0, value: $1)})
let url = URLComponents.url!
return Router.standardRequest(url)
}
}
}
}
| mit | 761b40fa3793c79977b3c4b67043fc38 | 31.958974 | 196 | 0.564027 | 4.750185 | false | false | false | false |
manuelescrig/SwiftAlps2016 | SnowBackground/SnowBackground/UIImageExtension.swift | 1 | 1077 | //
// UIImageExtension.swift
// SnowBackground
//
// Created by Manuel on 11/9/16.
// Copyright © 2016 Liip. All rights reserved.
//
import UIKit
extension UIImage {
func maskWithColor(color: UIColor) -> UIImage? {
let maskImage = cgImage!
let width = size.width
let height = size.height
let bounds = CGRect(x: 0, y: 0, width: width, height: height)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
let context = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
context.clip(to: bounds, mask: maskImage)
context.setFillColor(color.cgColor)
context.fill(bounds)
if let cgImage = context.makeImage() {
let coloredImage = UIImage(cgImage: cgImage)
return coloredImage
} else {
return nil
}
}
}
| mit | b3ca7ad0df8dc04b753594ecf1fcba41 | 28.888889 | 172 | 0.61803 | 4.559322 | false | false | false | false |
damonthecricket/my-utils | Source/UI/Extensions/View/ScrollView+Extensions.swift | 1 | 4021 | //
// UIScrollView+Extensions.swift
// InstaCollage
//
// Created by Optimus Prime on 07.03.17.
// Copyright © 2017 Tren Lab. All rights reserved.
//
#if os(iOS)
import UIKit
#elseif os(tvOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
// MARK: - MYScrollViewType
#if os(iOS)
/**
Platform independet ScrollView type.
*/
public typealias MYScrollViewType = UIScrollView
#elseif os(tvOS)
/**
Platform independet ScrollView type.
*/
public typealias MYScrollViewType = UIScrollView
#elseif os(OSX)
/**
Platform independet ScrollView type.
*/
public typealias MYScrollViewType = NSScrollView
#endif
// MARK: - MYScrollViewPosition
#if os(iOS) || os(tvOS) || os(OSX)
/**
Represents scroll view position.
*/
public enum MYScrollViewPosition: Int {
case top = 0
case right
case bottom
case left
case center
}
// MARK: - ScrollView Scroll Position
public extension MYScrollViewType {
/**
Returns `true` if current scroll view position is in a top of conten view. Otherwise returns `false`.
*/
public var onTop: Bool {
return position == .top
}
/**
Returns `true` if current scroll view position is in a right of content view. Otherwise returns `false`.
*/
public var onRight: Bool {
return position == .right
}
/**
Returns `true` if current scroll view position is in a bottom of content view. Otherwise returns `false`.
*/
public var onBottom: Bool {
return position == .bottom
}
/**
Returns `true` if current scroll view position is in a left of content view. Otherwise returns `false`.
*/
public var onLeft: Bool {
return position == .left
}
/**
Returns `true` if current scroll view position is in a center of content view. Otherwise returns `false`.
*/
public var inCenter: Bool {
return position == .center
}
/**
Returns current scroll view position.
*/
public var position: MYScrollViewPosition {
switch direction {
case .vertical:
if contentOffset.y <= 0.0 {
return .top
} else if contentOffset.y >= (contentSize.height - frame.size.height) {
return .bottom
} else {
return .center
}
case .horizontal:
if contentOffset.x >= (contentSize.width - frame.size.width) {
return .right
} else if contentOffset.x <= 0.0 {
return .left
} else {
return .center
}
}
}
#if os(OSX)
/**
Returns content offset of scroll view.
*/
public var contentOffset: CGPoint {
return documentVisibleRect.origin
}
#endif
}
// MARK: - MYScrollViewDirection
/**
Represents scroll view orientation.
*/
public enum MYScrollViewOrientation: Int {
case vertical = 0
case horizontal
}
// MARK: - ScrollView Scroll Direction
public extension MYScrollViewType {
/**
Returns current scroll view orientation.
*/
public var direction: MYScrollViewOrientation {
return contentSize.height > contentSize.width ? .vertical : .horizontal;
}
/**
Returns `true` if current scroll view orientation is vertical. Otherwise returns `false`.
*/
public var isVertical: Bool {
return direction == .vertical
}
/**
Returns `true` if current scroll view orientation is horizontal. Otherwise returns `false`.
*/
public var isHorizontal: Bool {
return direction == .horizontal
}
}
// MARK: - Size
public extension MYScrollViewType {
/**
Returns actual content size.
*/
public var size: CGSize {
return CGSize(width: contentSize.width - frame.size.width, height: contentSize.height - frame.size.height)
}
}
#endif
| mit | adc702e8914231ff0c83d2bc2f0d3d3a | 21.971429 | 114 | 0.600498 | 4.552661 | false | false | false | false |
RiBj1993/CodeRoute | MultipleChoiceViewController.swift | 1 | 1940 | //
// MultipleChoiceViewController.swift
// LoginForm
//
// Created by SwiftR on 14/03/2017.
// Copyright © 2017 vishalsonawane. All rights reserved.
//
import UIKit
class MultipleChoiceViewController: UIViewController {
// define the views and constraints for the View
private let contentView = UIView()
private var contentViewContstraints: [NSLayoutConstraint]!
private let questionView = UIView()
private var questionViewContstraints: [NSLayoutConstraint]!
private let answerView = UIView()
private var answerViewConstraints: [NSLayoutConstraint]!
private let countdownView = UIView()
private var countdownViewConstraints: [NSLayoutConstraint]!
// the question view's label and next button
private let questionLabel = RoundedLabel()
private var questionLabelConstraints: [NSLayoutConstraint]!
private let questionButton = RoundedButton()
private var questionButtonConstraints: [NSLayoutConstraint]!
// the answer buttons which we'll add later
private var answerButtons = [RoundedButton]()
private var answerButtonContstraints: [NSLayoutConstraint]!
// the progress view
private let progressView = UIProgressView()
private var progressViewConstraints: [NSLayoutConstraint]!
// background and foreground colors
private let backgroundColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
private let foregroundColor = UIColor(red: 52/255, green: 73/255, blue: 94/255, alpha: 1.0)
// MARK: - View Lifecycle and Layout
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = backgroundColor
layoutView()
}
override func viewDidAppear(_ animated: Bool) {
navigationController?.navigationBar.isHidden = false
}
func layoutView() {
}
}
| apache-2.0 | 21e94f8977f89f614884954cc55c1073 | 26.309859 | 95 | 0.682826 | 5.226415 | false | false | false | false |
koher/EasyImagy | Tests/EasyImagyTests/CoreGraphicsTest.swift | 1 | 38941 | import XCTest
import EasyImagy
#if canImport(CoreGraphics)
import CoreGraphics
#if canImport(AppKit)
private let red: CGColor = NSColor.red.cgColor
private let white: CGColor = NSColor.white.cgColor
#else
private let red: CGColor = UIColor.red.cgColor
private let white: CGColor = UIColor.white.cgColor
#endif
class CoreGraphicsTests: XCTestCase {
func testCGImage() {
do {
let image = Image<RGBA<UInt8>>(width: 2, height: 2, pixels: [
RGBA<UInt8>(red: 0, green: 1, blue: 2, alpha: 255),
RGBA<UInt8>(red: 253, green: 254, blue: 255, alpha: 255),
RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 102),
RGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 51),
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<RGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, image.width)
XCTAssertEqual(restored.height, image.height)
XCTAssertEqual(restored[0, 0], image[0, 0])
XCTAssertEqual(restored[1, 0], image[1, 0])
XCTAssertEqual(restored[0, 1], image[0, 1])
XCTAssertEqual(restored[1, 1], image[1, 1])
}
do {
let image = Image<PremultipliedRGBA<UInt8>>(width: 2, height: 2, pixels: [
PremultipliedRGBA<UInt8>(red: 0, green: 1, blue: 2, alpha: 255),
PremultipliedRGBA<UInt8>(red: 253, green: 254, blue: 255, alpha: 255),
PremultipliedRGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 102),
PremultipliedRGBA<UInt8>(red: 10, green: 20, blue: 30, alpha: 51),
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, image.width)
XCTAssertEqual(restored.height, image.height)
XCTAssertEqual(restored[0, 0], image[0, 0])
XCTAssertEqual(restored[1, 0], image[1, 0])
XCTAssertEqual(restored[0, 1], image[0, 1])
XCTAssertEqual(restored[1, 1], image[1, 1])
}
do {
let image = Image<UInt8>(width: 2, height: 2, pixels: [0, 1, 127, 255])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, image.width)
XCTAssertEqual(restored.height, image.height)
XCTAssertEqual(restored[0, 0], image[0, 0])
XCTAssertEqual(restored[1, 0], image[1, 0])
XCTAssertEqual(restored[0, 1], image[0, 1])
XCTAssertEqual(restored[1, 1], image[1, 1])
}
do {
let image = Image<RGBA<Float>>(width: 2, height: 2, pixels: [
RGBA(red: 1.0, green: 0.066666666666666666, blue: 0.13333333333333333, alpha: 1.0),
RGBA(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.066666666666666666),
RGBA(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.0),
RGBA(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0),
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<RGBA<Float>>(cgImage: cgImage)
XCTAssertEqual(restored, image)
}
do {
let image = Image<Float>(width: 2, height: 2, pixels: [
0.0, 0.066666666666666666, 0.13333333333333333, 1.0
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<Float>(cgImage: cgImage)
XCTAssertEqual(restored, image)
}
do {
let image = Image<RGBA<Bool>>(width: 2, height: 2, pixels: [
RGBA(red: true, green: false, blue: false, alpha: true),
RGBA(red: false, green: false, blue: false, alpha: false),
RGBA(red: true, green: true, blue: true, alpha: true),
RGBA(red: false, green: false, blue: true, alpha: true),
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<RGBA<Bool>>(cgImage: cgImage)
XCTAssertEqual(restored, image)
}
do {
let image = Image<Bool>(width: 2, height: 2, pixels: [
true, false, false, true
])
let cgImage = image.cgImage
XCTAssertEqual(cgImage.width, image.width)
XCTAssertEqual(cgImage.height, image.height)
let restored = Image<Bool>(cgImage: cgImage)
XCTAssertEqual(restored, image)
}
do {
let image = Image<UInt8>(width: 3, height: 2, pixels: [
1, 2, 3,
4, 5, 6,
])
let cgImage = image.cgImage
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, 3)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], 1)
XCTAssertEqual(restored[1, 0], 2)
XCTAssertEqual(restored[2, 0], 3)
XCTAssertEqual(restored[0, 1], 4)
XCTAssertEqual(restored[1, 1], 5)
XCTAssertEqual(restored[2, 1], 6)
}
do {
let slice: ImageSlice<UInt8> = Image<UInt8>(width: 5, height: 4, pixels: [
0, 0, 0, 0, 0,
0, 1, 2, 3, 0,
0, 4, 5, 6, 0,
0, 0, 0, 0, 0,
])[1...3, 1...2]
let cgImage = slice.cgImage
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, 3)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], 1)
XCTAssertEqual(restored[1, 0], 2)
XCTAssertEqual(restored[2, 0], 3)
XCTAssertEqual(restored[0, 1], 4)
XCTAssertEqual(restored[1, 1], 5)
XCTAssertEqual(restored[2, 1], 6)
}
do {
let image = Image<PremultipliedRGBA<UInt8>>(width: 1, height: 2, pixels: [
PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127),
PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4),
])
let cgImage = image.cgImage
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, 1)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127))
XCTAssertEqual(restored[0, 1], PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4))
}
do {
let transparent = PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 0)
let slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 3, height: 4, pixels: [
transparent, transparent, transparent,
transparent, PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127), transparent,
transparent, PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4), transparent,
transparent, transparent, transparent,
])[1...1, 1...2]
let cgImage = slice.cgImage
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, 1)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127))
XCTAssertEqual(restored[0, 1], PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4))
}
do { // slices which contains the last row of the original images
let slice: ImageSlice<UInt8> = Image<UInt8>(width: 4, height: 3, pixels: [
0, 0, 0, 0,
0, 1, 2, 3,
0, 4, 5, 6,
])[1...3, 1...2]
let cgImage = slice.cgImage
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, 3)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], 1)
XCTAssertEqual(restored[1, 0], 2)
XCTAssertEqual(restored[2, 0], 3)
XCTAssertEqual(restored[0, 1], 4)
XCTAssertEqual(restored[1, 1], 5)
XCTAssertEqual(restored[2, 1], 6)
}
do { // slices which contains the last row of the original images
let transparent = PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 0)
let slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 2, height: 3, pixels: [
transparent, transparent,
transparent, PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127),
transparent, PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4),
])[1...1, 1...2]
let cgImage = slice.cgImage
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, 1)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127))
XCTAssertEqual(restored[0, 1], PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4))
}
}
func testWithCGImage() {
do {
let image = Image<UInt8>(width: 3, height: 2, pixels: [
1, 2, 3,
4, 5, 6,
])
image.withCGImage { cgImage in
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, 3)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], 1)
XCTAssertEqual(restored[1, 0], 2)
XCTAssertEqual(restored[2, 0], 3)
XCTAssertEqual(restored[0, 1], 4)
XCTAssertEqual(restored[1, 1], 5)
XCTAssertEqual(restored[2, 1], 6)
}
}
do {
let slice: ImageSlice<UInt8> = Image<UInt8>(width: 5, height: 4, pixels: [
0, 0, 0, 0, 0,
0, 1, 2, 3, 0,
0, 4, 5, 6, 0,
0, 0, 0, 0, 0,
])[1...3, 1...2]
slice.withCGImage { cgImage in
let restored = Image<UInt8>(cgImage: cgImage)
XCTAssertEqual(restored.width, 3)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], 1)
XCTAssertEqual(restored[1, 0], 2)
XCTAssertEqual(restored[2, 0], 3)
XCTAssertEqual(restored[0, 1], 4)
XCTAssertEqual(restored[1, 1], 5)
XCTAssertEqual(restored[2, 1], 6)
}
}
do {
let image = Image<PremultipliedRGBA<UInt8>>(width: 1, height: 2, pixels: [
PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127),
PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4),
])
image.withCGImage { cgImage in
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, 1)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127))
XCTAssertEqual(restored[0, 1], PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4))
}
}
do {
let transparent = PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 0)
let slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 3, height: 4, pixels: [
transparent, transparent, transparent,
transparent, PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127), transparent,
transparent, PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4), transparent,
transparent, transparent, transparent,
])[1...1, 1...2]
slice.withCGImage { cgImage in
let restored = Image<PremultipliedRGBA<UInt8>>(cgImage: cgImage)
XCTAssertEqual(restored.width, 1)
XCTAssertEqual(restored.height, 2)
XCTAssertEqual(restored[0, 0], PremultipliedRGBA<UInt8>(red: 24, green: 49, blue: 99, alpha: 127))
XCTAssertEqual(restored[0, 1], PremultipliedRGBA<UInt8>(red: 1, green: 2, blue: 3, alpha: 4))
}
}
}
func testWithCGContext() {
// Draws lines with CoreGraphics as follows:
//
// Before
// ----
// ----
// ----
// ----
//
// After
// -*--
// -*--
// ****
// -*--
do {
var image = Image<PremultipliedRGBA<UInt8>>(width: 4, height: 4, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
image.withCGContext { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 1, y: -1))
context.addLine(to: CGPoint(x: 1, y: 4))
context.move(to: CGPoint(x: -1, y: 2))
context.addLine(to: CGPoint(x: 4, y: 2))
context.strokePath()
}
XCTAssertEqual(image[0, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 0], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var image = Image<UInt8>(width: 4, height: 4, pixel: 0)
image.withCGContext { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 1, y: -1))
context.addLine(to: CGPoint(x: 1, y: 4))
context.move(to: CGPoint(x: -1, y: 2))
context.addLine(to: CGPoint(x: 4, y: 2))
context.strokePath()
}
XCTAssertEqual(image[0, 0], 0)
XCTAssertEqual(image[1, 0], 255)
XCTAssertEqual(image[2, 0], 0)
XCTAssertEqual(image[3, 0], 0)
XCTAssertEqual(image[0, 1], 0)
XCTAssertEqual(image[1, 1], 255)
XCTAssertEqual(image[2, 1], 0)
XCTAssertEqual(image[3, 1], 0)
XCTAssertEqual(image[0, 2], 255)
XCTAssertEqual(image[1, 2], 255)
XCTAssertEqual(image[2, 2], 255)
XCTAssertEqual(image[3, 2], 255)
XCTAssertEqual(image[0, 3], 0)
XCTAssertEqual(image[1, 3], 255)
XCTAssertEqual(image[2, 3], 0)
XCTAssertEqual(image[3, 3], 0)
}
do {
var image = Image<PremultipliedRGBA<UInt8>>(width: 4, height: 4, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
image.withCGContext(coordinates: .natural) { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 1, y: -1))
context.addLine(to: CGPoint(x: 1, y: 4))
context.move(to: CGPoint(x: -1, y: 2))
context.addLine(to: CGPoint(x: 4, y: 2))
context.strokePath()
}
XCTAssertEqual(image[0, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 0], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var image = Image<UInt8>(width: 4, height: 4, pixel: 0)
image.withCGContext(coordinates: .natural) { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 1, y: -1))
context.addLine(to: CGPoint(x: 1, y: 4))
context.move(to: CGPoint(x: -1, y: 2))
context.addLine(to: CGPoint(x: 4, y: 2))
context.strokePath()
}
XCTAssertEqual(image[0, 0], 0)
XCTAssertEqual(image[1, 0], 255)
XCTAssertEqual(image[2, 0], 0)
XCTAssertEqual(image[3, 0], 0)
XCTAssertEqual(image[0, 1], 0)
XCTAssertEqual(image[1, 1], 255)
XCTAssertEqual(image[2, 1], 0)
XCTAssertEqual(image[3, 1], 0)
XCTAssertEqual(image[0, 2], 255)
XCTAssertEqual(image[1, 2], 255)
XCTAssertEqual(image[2, 2], 255)
XCTAssertEqual(image[3, 2], 255)
XCTAssertEqual(image[0, 3], 0)
XCTAssertEqual(image[1, 3], 255)
XCTAssertEqual(image[2, 3], 0)
XCTAssertEqual(image[3, 3], 0)
}
do {
var image = Image<PremultipliedRGBA<UInt8>>(width: 4, height: 4, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
image.withCGContext(coordinates: .original) { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 1.5, y: 4.5))
context.addLine(to: CGPoint(x: 1.5, y: -0.5))
context.move(to: CGPoint(x: -0.5, y: 1.5))
context.addLine(to: CGPoint(x: 4.5, y: 1.5))
context.strokePath()
}
XCTAssertEqual(image[0, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 0], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 0], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[0, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[2, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(image[3, 3], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var image = Image<UInt8>(width: 4, height: 4, pixel: 0)
image.withCGContext(coordinates: .original) { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 1.5, y: 4.5))
context.addLine(to: CGPoint(x: 1.5, y: -0.5))
context.move(to: CGPoint(x: -0.5, y: 1.5))
context.addLine(to: CGPoint(x: 4.5, y: 1.5))
context.strokePath()
}
XCTAssertEqual(image[0, 0], 0)
XCTAssertEqual(image[1, 0], 255)
XCTAssertEqual(image[2, 0], 0)
XCTAssertEqual(image[3, 0], 0)
XCTAssertEqual(image[0, 1], 0)
XCTAssertEqual(image[1, 1], 255)
XCTAssertEqual(image[2, 1], 0)
XCTAssertEqual(image[3, 1], 0)
XCTAssertEqual(image[0, 2], 255)
XCTAssertEqual(image[1, 2], 255)
XCTAssertEqual(image[2, 2], 255)
XCTAssertEqual(image[3, 2], 255)
XCTAssertEqual(image[0, 3], 0)
XCTAssertEqual(image[1, 3], 255)
XCTAssertEqual(image[2, 3], 0)
XCTAssertEqual(image[3, 3], 0)
}
do {
var slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 6, height: 6, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))[1...4, 1...4]
slice.withCGContext { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 2, y: 0))
context.addLine(to: CGPoint(x: 2, y: 5))
context.move(to: CGPoint(x: 0, y: 3))
context.addLine(to: CGPoint(x: 5, y: 3))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 4], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var slice: ImageSlice<UInt8> = Image<UInt8>(width: 6, height: 6, pixel: 0)[1...4, 1...4]
slice.withCGContext { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 2, y: 0))
context.addLine(to: CGPoint(x: 2, y: 5))
context.move(to: CGPoint(x: 0, y: 3))
context.addLine(to: CGPoint(x: 5, y: 3))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], 0)
XCTAssertEqual(slice[2, 1], 255)
XCTAssertEqual(slice[3, 1], 0)
XCTAssertEqual(slice[4, 1], 0)
XCTAssertEqual(slice[1, 2], 0)
XCTAssertEqual(slice[2, 2], 255)
XCTAssertEqual(slice[3, 2], 0)
XCTAssertEqual(slice[4, 2], 0)
XCTAssertEqual(slice[1, 3], 255)
XCTAssertEqual(slice[2, 3], 255)
XCTAssertEqual(slice[3, 3], 255)
XCTAssertEqual(slice[4, 3], 255)
XCTAssertEqual(slice[1, 4], 0)
XCTAssertEqual(slice[2, 4], 255)
XCTAssertEqual(slice[3, 4], 0)
XCTAssertEqual(slice[4, 4], 0)
}
do {
var slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 6, height: 6, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))[1...4, 1...4]
slice.withCGContext(coordinates: .natural) { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 2, y: 0))
context.addLine(to: CGPoint(x: 2, y: 5))
context.move(to: CGPoint(x: 0, y: 3))
context.addLine(to: CGPoint(x: 5, y: 3))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 4], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var slice: ImageSlice<UInt8> = Image<UInt8>(width: 6, height: 6, pixel: 0)[1...4, 1...4]
slice.withCGContext(coordinates: .natural) { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 2, y: 0))
context.addLine(to: CGPoint(x: 2, y: 5))
context.move(to: CGPoint(x: 0, y: 3))
context.addLine(to: CGPoint(x: 5, y: 3))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], 0)
XCTAssertEqual(slice[2, 1], 255)
XCTAssertEqual(slice[3, 1], 0)
XCTAssertEqual(slice[4, 1], 0)
XCTAssertEqual(slice[1, 2], 0)
XCTAssertEqual(slice[2, 2], 255)
XCTAssertEqual(slice[3, 2], 0)
XCTAssertEqual(slice[4, 2], 0)
XCTAssertEqual(slice[1, 3], 255)
XCTAssertEqual(slice[2, 3], 255)
XCTAssertEqual(slice[3, 3], 255)
XCTAssertEqual(slice[4, 3], 255)
XCTAssertEqual(slice[1, 4], 0)
XCTAssertEqual(slice[2, 4], 255)
XCTAssertEqual(slice[3, 4], 0)
XCTAssertEqual(slice[4, 4], 0)
}
do {
var slice: ImageSlice<PremultipliedRGBA<UInt8>> = Image<PremultipliedRGBA<UInt8>>(width: 6, height: 6, pixel: PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))[1...4, 1...4]
slice.withCGContext(coordinates: .original) { context in
context.setLineWidth(1)
context.setStrokeColor(red)
context.move(to: CGPoint(x: 1.5, y: 4.5))
context.addLine(to: CGPoint(x: 1.5, y: -0.5))
context.move(to: CGPoint(x: -0.5, y: 1.5))
context.addLine(to: CGPoint(x: 4.5, y: 1.5))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 1], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 1], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 2], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 2], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 3], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[1, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[2, 4], PremultipliedRGBA<UInt8>(red: 255, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[3, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
XCTAssertEqual(slice[4, 4], PremultipliedRGBA<UInt8>(red: 0, green: 0, blue: 0, alpha: 255))
}
do {
var slice: ImageSlice<UInt8> = Image<UInt8>(width: 6, height: 6, pixel: 0)[1...4, 1...4]
slice.withCGContext(coordinates: .original) { context in
context.setLineWidth(1)
context.setStrokeColor(white)
context.move(to: CGPoint(x: 1.5, y: 4.5))
context.addLine(to: CGPoint(x: 1.5, y: -0.5))
context.move(to: CGPoint(x: -0.5, y: 1.5))
context.addLine(to: CGPoint(x: 4.5, y: 1.5))
context.strokePath()
}
XCTAssertEqual(slice[1, 1], 0)
XCTAssertEqual(slice[2, 1], 255)
XCTAssertEqual(slice[3, 1], 0)
XCTAssertEqual(slice[4, 1], 0)
XCTAssertEqual(slice[1, 2], 0)
XCTAssertEqual(slice[2, 2], 255)
XCTAssertEqual(slice[3, 2], 0)
XCTAssertEqual(slice[4, 2], 0)
XCTAssertEqual(slice[1, 3], 255)
XCTAssertEqual(slice[2, 3], 255)
XCTAssertEqual(slice[3, 3], 255)
XCTAssertEqual(slice[4, 3], 255)
XCTAssertEqual(slice[1, 4], 0)
XCTAssertEqual(slice[2, 4], 255)
XCTAssertEqual(slice[3, 4], 0)
XCTAssertEqual(slice[4, 4], 0)
}
}
}
#endif
| mit | cbd3d56c6fc3bace04c88fa0306fdcd8 | 51.340054 | 204 | 0.50122 | 4.182258 | false | false | false | false |
andrewapperley/WEBD-204-IOS | IOS Helper/IOS Helper/UI/UIHelp-UIView.swift | 1 | 1061 | //
// UIHelp-UIView.swift
// IOS Helper
//
// Created by Andrew Apperley on 2016-11-22.
// Copyright © 2016 Humber College. All rights reserved.
//
import UIKit
class UIHelp_UIView: HelperViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.title = "UIView"
let top = UIView()
top.backgroundColor = UIColor.redColor()
top.layer.borderWidth = 2
top.layer.borderColor = UIColor.blueColor().CGColor
top.layer.cornerRadius = 5
stack.addArrangedSubview(top)
top.translatesAutoresizingMaskIntoConstraints = false
top.heightAnchor.constraintEqualToConstant(100).active = true
let bottom = UIView()
bottom.backgroundColor = UIColor.grayColor()
bottom.layer.borderWidth = 1
bottom.layer.borderColor = UIColor.yellowColor().CGColor
bottom.layer.cornerRadius = 50
stack.addArrangedSubview(bottom)
bottom.translatesAutoresizingMaskIntoConstraints = false
bottom.heightAnchor.constraintEqualToConstant(100).active = true
}
}
| mit | 38898c41ea691536b22950e2215da2dd | 27.648649 | 70 | 0.701887 | 4.732143 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | Example/Pods/Material/Sources/iOS/CollectionViewController.swift | 1 | 4247 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public protocol CollectionViewDelegate: UICollectionViewDelegate {}
public protocol CollectionViewDataSource: UICollectionViewDataSource {
/**
Retrieves the data source items for the collectionView.
- Returns: An Array of CollectionViewDataSourceItem objects.
*/
var dataSourceItems: [CollectionViewDataSourceItem] { get }
}
extension UIViewController {
/**
A convenience property that provides access to the CollectionViewController.
This is the recommended method of accessing the CollectionViewController
through child UIViewControllers.
*/
public var collectionViewController: CollectionViewController? {
var viewController: UIViewController? = self
while nil != viewController {
if viewController is CollectionViewController {
return viewController as? CollectionViewController
}
viewController = viewController?.parent
}
return nil
}
}
open class CollectionViewController: UIViewController {
/// A reference to a Reminder.
open let collectionView = CollectionView()
open var dataSourceItems = [CollectionViewDataSourceItem]()
open override func viewDidLoad() {
super.viewDidLoad()
prepare()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
open func prepare() {
view.clipsToBounds = true
view.backgroundColor = Color.white
view.contentScaleFactor = Screen.scale
prepareCollectionView()
}
}
extension CollectionViewController {
/// Prepares the collectionView.
fileprivate func prepareCollectionView() {
collectionView.delegate = self
collectionView.dataSource = self
view.layout(collectionView).edges()
}
}
extension CollectionViewController: CollectionViewDelegate {}
extension CollectionViewController: CollectionViewDataSource {
@objc
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
@objc
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dataSourceItems.count
}
@objc
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
return UICollectionViewCell()
}
}
| mit | 7e26f06765f4d62de7c2025d44bbdc04 | 36.919643 | 126 | 0.730162 | 5.558901 | false | false | false | false |
dduan/swift | stdlib/public/core/Algorithm.swift | 1 | 4575 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Returns the lesser of `x` and `y`.
///
/// If `x == y`, returns `x`.
@warn_unused_result
public func min<T : Comparable>(x: T, _ y: T) -> T {
// In case `x == y` we pick `x`.
// This preserves any pre-existing order in case `T` has identity,
// which is important for e.g. the stability of sorting algorithms.
// `(min(x, y), max(x, y))` should return `(x, y)` in case `x == y`.
return y < x ? y : x
}
/// Returns the least argument passed.
///
/// If there are multiple equal least arguments, returns the first one.
@warn_unused_result
public func min<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var minValue = min(min(x, y), z)
// In case `value == minValue`, we pick `minValue`. See min(_:_:).
for value in rest where value < minValue {
minValue = value
}
return minValue
}
/// Returns the greater of `x` and `y`.
///
/// If `x == y`, returns `y`.
@warn_unused_result
public func max<T : Comparable>(x: T, _ y: T) -> T {
// In case `x == y`, we pick `y`. See min(_:_:).
return y >= x ? y : x
}
/// Returns the greatest argument passed.
///
/// If there are multiple equal greatest arguments, returns the last one.
@warn_unused_result
public func max<T : Comparable>(x: T, _ y: T, _ z: T, _ rest: T...) -> T {
var maxValue = max(max(x, y), z)
// In case `value == maxValue`, we pick `value`. See min(_:_:).
for value in rest where value >= maxValue {
maxValue = value
}
return maxValue
}
/// The iterator for `EnumeratedSequence`. `EnumeratedIterator`
/// wraps a `Base` iterator and yields successive `Int` values,
/// starting at zero, along with the elements of the underlying
/// `Base`:
///
/// var iterator = ["foo", "bar"].enumerated().makeIterator()
/// iterator.next() // (0, "foo")
/// iterator.next() // (1, "bar")
/// iterator.next() // nil
///
/// - Note: Idiomatic usage is to call `enumerate` instead of
/// constructing an `EnumerateIterator` directly.
public struct EnumeratedIterator<
Base : IteratorProtocol
> : IteratorProtocol, Sequence {
internal var _base: Base
internal var _count: Int
/// Construct from a `Base` iterator.
internal init(_base: Base) {
self._base = _base
self._count = 0
}
/// The type of element returned by `next()`.
public typealias Element = (offset: Int, element: Base.Element)
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: No preceding call to `self.next()` has returned `nil`.
public mutating func next() -> Element? {
guard let b = _base.next() else { return nil }
defer { _count += 1 }
return (offset: _count, element: b)
}
}
/// The type of the `enumerated()` property.
///
/// `EnumeratedSequence` is a sequence of pairs (*n*, *x*), where *n*s
/// are consecutive `Int`s starting at zero, and *x*s are the elements
/// of a `Base` `Sequence`:
///
/// var s = ["foo", "bar"].enumerated()
/// Array(s) // [(0, "foo"), (1, "bar")]
public struct EnumeratedSequence<Base : Sequence> : Sequence {
internal var _base: Base
/// Construct from a `Base` sequence.
internal init(_base: Base) {
self._base = _base
}
/// Returns an iterator over the elements of this sequence.
///
/// - Complexity: O(1).
public func makeIterator() -> EnumeratedIterator<Base.Iterator> {
return EnumeratedIterator(_base: _base.makeIterator())
}
}
@available(*, unavailable, renamed: "EnumeratedIterator")
public struct EnumerateGenerator<Base : IteratorProtocol> { }
@available(*, unavailable, renamed: "EnumeratedSequence")
public struct EnumerateSequence<Base : Sequence> {}
extension EnumeratedIterator {
@available(*, unavailable, message: "use the 'enumerated()' method on the sequence")
public init(_ base: Base) {
fatalError("unavailable function can't be called")
}
}
extension EnumeratedSequence {
@available(*, unavailable, message: "use the 'enumerated()' method on the sequence")
public init(_ base: Base) {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | 27c167e2a41c5c805944a59cfc3aa836 | 31.446809 | 86 | 0.620109 | 3.756158 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | HTWDresden_old/HTWDresden/PSCustomViewFromXib.swift | 1 | 1405 | //
// PSCustomViewFromXib.swift
// HTWDresden
//
// Created by Benjamin Herzog on 22.08.14.
// Copyright (c) 2014 Benjamin Herzog. All rights reserved.
//
import UIKit
public class NibView: UIView {
public weak var proxyView: NibView?
override init(frame: CGRect) {
super.init(frame: frame)
var view = self.loadNib()
view.frame = self.bounds
view.autoresizingMask = .FlexibleWidth | .FlexibleHeight
self.proxyView = view
if let view = proxyView {
self.addSubview(view)
}
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func awakeAfterUsingCoder(aDecoder: NSCoder) -> AnyObject {
if self.subviews.count == 0 {
var view = self.loadNib()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
let contraints = self.constraints()
self.removeConstraints(contraints)
view.addConstraints(contraints)
view.proxyView = view
return view
}
return self
}
private func loadNib() -> NibView {
let bundle = NSBundle(forClass: self.dynamicType)
return bundle.loadNibNamed(self.nibName(), owner: nil, options: nil)[0] as! NibView
}
public func nibName() -> String {
return ""
}
}
| gpl-2.0 | 20ceb7d3fdb20086ec34ba66d4193930 | 26.54902 | 91 | 0.602847 | 4.621711 | false | false | false | false |
vmanot/swift-package-manager | Sources/PackageDescription/Package.swift | 1 | 8014 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
#if os(Linux)
import Glibc
#else
import Darwin.C
#endif
/// The description for a complete package.
public final class Package {
/// The description for a package dependency.
public class Dependency {
public let versionRange: Range<Version>
public let url: String
init(_ url: String, _ versionRange: Range<Version>) {
self.url = url
self.versionRange = versionRange
}
convenience init(_ url: String, _ versionRange: ClosedRange<Version>) {
self.init(url, versionRange.lowerBound..<versionRange.upperBound.successor())
}
public class func Package(url: String, versions: Range<Version>) -> Dependency {
return Dependency(url, versions)
}
public class func Package(url: String, versions: ClosedRange<Version>) -> Dependency {
return Package(url: url, versions: versions.lowerBound..<versions.upperBound.successor())
}
public class func Package(url: String, majorVersion: Int) -> Dependency {
return Dependency(url, Version(majorVersion, 0, 0)..<Version(majorVersion, .max, .max))
}
public class func Package(url: String, majorVersion: Int, minor: Int) -> Dependency {
return Dependency(url, Version(majorVersion, minor, 0)..<Version(majorVersion, minor, .max))
}
public class func Package(url: String, _ version: Version) -> Dependency {
return Dependency(url, version...version)
}
}
/// The name of the package.
public let name: String
/// pkgconfig name to use for C Modules. If present, swiftpm will try to search for
/// <name>.pc file to get the additional flags needed for the system target.
public let pkgConfig: String?
/// Providers array for System target
public let providers: [SystemPackageProvider]?
/// The list of targets.
public var targets: [Target]
/// The list of dependencies.
public var dependencies: [Dependency]
/// The list of swift versions, this package is compatible with.
public var swiftLanguageVersions: [Int]?
/// The list of folders to exclude.
public var exclude: [String]
/// Construct a package.
public init(
name: String,
pkgConfig: String? = nil,
providers: [SystemPackageProvider]? = nil,
targets: [Target] = [],
dependencies: [Dependency] = [],
swiftLanguageVersions: [Int]? = nil,
exclude: [String] = []
) {
self.name = name
self.pkgConfig = pkgConfig
self.providers = providers
self.targets = targets
self.dependencies = dependencies
self.swiftLanguageVersions = swiftLanguageVersions
self.exclude = exclude
// Add custom exit handler to cause package to be dumped at exit, if requested.
//
// FIXME: This doesn't belong here, but for now is the mechanism we use
// to get the interpreter to dump the package when attempting to load a
// manifest.
// FIXME: Additional hackery here to avoid accessing 'arguments' in a
// process whose 'main' isn't generated by Swift.
// See https://bugs.swift.org/browse/SR-1119.
if CommandLine.argc > 0 {
if let fileNoOptIndex = CommandLine.arguments.index(of: "-fileno"),
let fileNo = Int32(CommandLine.arguments[fileNoOptIndex + 1]) {
dumpPackageAtExit(self, fileNo: fileNo)
}
}
}
}
public enum SystemPackageProvider {
case Brew(String)
case Apt(String)
}
extension SystemPackageProvider {
public var nameValue: (String, String) {
switch self {
case .Brew(let name):
return ("Brew", name)
case .Apt(let name):
return ("Apt", name)
}
}
}
// MARK: Equatable
extension Package : Equatable {
public static func == (lhs: Package, rhs: Package) -> Bool {
return (lhs.name == rhs.name &&
lhs.targets == rhs.targets &&
lhs.dependencies == rhs.dependencies)
}
}
extension Package.Dependency : Equatable {
public static func == (lhs: Package.Dependency, rhs: Package.Dependency) -> Bool {
return lhs.url == rhs.url && lhs.versionRange == rhs.versionRange
}
}
// MARK: Package JSON serialization
extension SystemPackageProvider {
func toJSON() -> JSON {
let (name, value) = nameValue
return .dictionary(["name": .string(name),
"value": .string(value),
])
}
}
extension Package.Dependency {
func toJSON() -> JSON {
return .dictionary([
"url": .string(url),
"version": .dictionary([
"lowerBound": .string(versionRange.lowerBound.description),
"upperBound": .string(versionRange.upperBound.description),
]),
])
}
}
extension Package {
func toJSON() -> JSON {
var dict: [String: JSON] = [:]
dict["name"] = .string(name)
if let pkgConfig = self.pkgConfig {
dict["pkgConfig"] = .string(pkgConfig)
}
dict["dependencies"] = .array(dependencies.map({ $0.toJSON() }))
dict["exclude"] = .array(exclude.map({ .string($0) }))
dict["targets"] = .array(targets.map({ $0.toJSON() }))
if let providers = self.providers {
dict["providers"] = .array(providers.map({ $0.toJSON() }))
}
if let swiftLanguageVersions = self.swiftLanguageVersions {
dict["swiftLanguageVersions"] = .array(swiftLanguageVersions.map(JSON.int))
}
return .dictionary(dict)
}
}
extension Target {
func toJSON() -> JSON {
return .dictionary([
"name": .string(name),
"dependencies": .array(dependencies.map({ $0.toJSON() })),
])
}
}
extension Target.Dependency {
func toJSON() -> JSON {
switch self {
case .Target(let name):
return .string(name)
}
}
}
// MARK: Package Dumping
struct Errors {
/// Storage to hold the errors.
private var errors = [String]()
/// Adds error to global error array which will be serialized and dumped in JSON at exit.
mutating func add(_ str: String) {
// FIXME: This will produce invalid JSON if string contains quotes. Assert it for now
// and fix when we have escaping in JSON.
assert(!str.contains("\""), "Error string shouldn't have quotes in it.")
errors += [str]
}
func toJSON() -> JSON {
return .array(errors.map(JSON.string))
}
}
func manifestToJSON(_ package: Package) -> String {
var dict: [String: JSON] = [:]
dict["package"] = package.toJSON()
dict["products"] = .array(products.map({ $0.toJSON() }))
dict["errors"] = errors.toJSON()
return JSON.dictionary(dict).toString()
}
// FIXME: This function is public to let other targets get the JSON representation
// of the package without exposing the enum JSON defined in this target (because that'll
// leak to clients of PackageDescription i.e every Package.swift file).
public func jsonString(package: Package) -> String {
return package.toJSON().toString()
}
var errors = Errors()
private var dumpInfo: (package: Package, fileNo: Int32)?
private func dumpPackageAtExit(_ package: Package, fileNo: Int32) {
func dump() {
guard let dumpInfo = dumpInfo else { return }
let fd = fdopen(dumpInfo.fileNo, "w")
guard fd != nil else { return }
fputs(manifestToJSON(dumpInfo.package), fd)
fclose(fd)
}
dumpInfo = (package, fileNo)
atexit(dump)
}
| apache-2.0 | a9b47e4925e6d1c53e28aafd5df11a57 | 31.577236 | 104 | 0.61692 | 4.355435 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/modules/request-permissions/managers/presenters/dialog/interactive/presenter/SPRequestPermissionDialogInteractivePresenter.swift | 2 | 9704 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// 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
class SPRequestPermissionDialogInteractivePresenter {
var eventsDelegate: SPRequestPermissionEventsDelegate?
private var permissions: [SPRequestPermissionType] = []
private var controls = [SPRequestPermissionTwiceControlInterface]()
private var dataSource: SPRequestPermissionDialogInteractiveDataSourceInterface
private var permissionManager: SPPermissionsManagerInterface = SPPermissionsManager()
weak var viewController: SPRequestPermissionDialogInteractiveViewControllerInterface! {
didSet {
self.configureController()
}
}
//MARK: - init
init(with permissions: [SPRequestPermissionType], dataSource: SPRequestPermissionDialogInteractiveDataSourceInterface) {
self.dataSource = dataSource
self.permissions = permissions
self.permissions.removeDuplicates()
}
private func configureController() {
self.viewController.setHeaderBackgroundView(self.dataSource.headerBackgroundView())
self.viewController.setHeaderTitle(self.dataSource.headerTitle())
self.viewController.setHeaderSubtitle(self.dataSource.headerSubtitle())
self.viewController.setTopTitle(self.dataSource.topAdviceTitle())
self.viewController.setBottomTitle(self.dataSource.bottomAdviceTitle())
self.viewController.setUnderDialogTitle(self.dataSource.underDialogAdviceTitle())
for permission in permissions {
let control = self.createControlForPermission(permission)
controls.append(control)
control.addAction(self, action: #selector(self.actionForControl(sender:)))
self.viewController.addControl(control)
}
self.updatePermissionsStyle()
}
private func createControlForPermission(_ permission: SPRequestPermissionType) -> SPRequestPermissionTwiceControlInterface {
return SPRequestPermissionTwiceControl(
permissionType: permission,
title: self.dataSource.titleForPermissionControl(permission),
normalIconImage: self.dataSource.iconForNormalPermissionControl(permission) ,
selectedIconImage: self.dataSource.iconForAllowedPermissionControl(permission),
normalColor: self.dataSource.secondColor(),
selectedColor: self.dataSource.mainColor()
)
}
var isPresentedNotificationRequest: Bool = false
@objc func actionForControl(sender: AnyObject) {
let control = sender as! SPRequestPermissionTwiceControlInterface
self.eventsDelegate?.didSelectedPermission(permission: control.permission)
permissionManager.requestPermission(control.permission, with: {
if self.permissionManager.isAuthorizedPermission(control.permission) {
self.eventsDelegate?.didAllowPermission(permission: control.permission)
control.setSelectedState(animated: true)
} else {
self.eventsDelegate?.didDeniedPermission(permission: control.permission)
control.setNormalState(animated: true)
if !(control.permission == .notification) {
self.showDialogForProtectPermissionOnViewController()
} else {
self.isPresentedNotificationRequest = true
if #available(iOS 10.0, *){
self.showDialogForProtectPermissionOnViewController(cancelHandler: {
var denidedPermission: [SPRequestPermissionType] = []
for permission in self.permissions {
if !self.permissionManager.isAuthorizedPermission(permission) {
denidedPermission.append(permission)
}
}
if denidedPermission.count == 1 {
if denidedPermission[0] == SPRequestPermissionType.notification {
self.viewController.hide()
}
}
})
} else {
control.setSelectedState(animated: true)
var denidedPermission: [SPRequestPermissionType] = []
for permission in self.permissions {
if !self.permissionManager.isAuthorizedPermission(permission) {
denidedPermission.append(permission)
}
}
if denidedPermission.count == 1 {
if denidedPermission[0] == SPRequestPermissionType.notification {
self.viewController.hide()
}
}
}
return
}
}
var allPermissionAllowed: Bool = true
for permission in self.permissions {
if !self.permissionManager.isAuthorizedPermission(permission) {
allPermissionAllowed = false
break
}
}
if allPermissionAllowed {
delay(0.21, closure: {
self.viewController.hide()
})
} else {
var denidedPermission: [SPRequestPermissionType] = []
for permission in self.permissions {
if !self.permissionManager.isAuthorizedPermission(permission) {
denidedPermission.append(permission)
}
}
if denidedPermission.count == 1 {
if denidedPermission[0] == SPRequestPermissionType.notification {
if self.isPresentedNotificationRequest {
delay(0.21, closure: {
self.viewController.hide()
})
}
}
}
}
})
}
private func showDialogForProtectPermissionOnViewController(cancelHandler: @escaping ()->() = {}) {
let alert = UIAlertController.init(
title: dataSource.titleForAlertDenidPermission(),
message: dataSource.subtitleForAlertDenidPermission(),
preferredStyle: UIAlertControllerStyle.alert
)
alert.addAction(UIAlertAction.init(
title: dataSource.cancelForAlertDenidPermission(),
style: UIAlertActionStyle.cancel,
handler: {
finished in
cancelHandler()
})
)
alert.addAction(UIAlertAction.init(
title: dataSource.settingForAlertDenidPermission(),
style: UIAlertActionStyle.default,
handler: {
finished in
NotificationCenter.default.addObserver(self, selector: #selector(self.updatePermissionsStyle), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
if #available(iOS 10.0, *) {
UIApplication.shared.open(
URL.init(string: UIApplicationOpenSettingsURLString)!,
options: [:],
completionHandler: nil
)
} else {
UIApplication.shared.openURL(URL.init(string: UIApplicationOpenSettingsURLString)!)
}
}))
if let controller = self.viewController as? UIViewController {
controller.present(alert, animated: true, completion: nil)
}
}
@objc private func updatePermissionsStyle() {
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
for control in controls {
if permissionManager.isAuthorizedPermission(control.permission) {
control.setSelectedState(animated: false)
} else {
control.setNormalState(animated: false)
}
}
}
}
extension SPRequestPermissionDialogInteractivePresenter: SPRequestPermissionDialogInteractivePresenterDelegate {
func didHide() {
self.eventsDelegate?.didHide()
}
}
| mit | 9f71065c791e920148d5290ad07bf3ed | 44.341121 | 179 | 0.598269 | 6.083386 | false | false | false | false |
ng28/TidyLog | Sources/TidyLog.swift | 1 | 9601 | //
// Copyright (c) 2017 by ng <[email protected]>
//
// 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 TidyJSON
public struct Level : OptionSet {
public let rawValue : Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let verbose = Level(rawValue: 1 << 0)
public static let info = Level(rawValue: 1 << 1)
public static let debug = Level(rawValue: 1 << 2)
public static let error = Level(rawValue: 1 << 3)
public static let fatal = Level(rawValue: 1 << 4)
public static let VERBOSE: Level = [.verbose, .info, .debug, .error, .fatal]
public static let INFO : Level = [.info, .debug, .error, .fatal]
public static let DEBUG : Level = [.debug, .error, .fatal]
public static let ERROR : Level = [.error, .fatal]
public static let FATAL : Level = [.fatal]
public static let NONE : Level = [] // default
}
private enum Colors: String {
case Black = "\u{001B}[0;30m" //None
case Cyan = "\u{001B}[0;36m" //Fatal
case Red = "\u{001B}[0;31m" //Error
case Green = "\u{001B}[0;32m" //Debug
case Yellow = "\u{001B}[0;33m" //Info
case White = "\u{001B}[0;37m" //verbose
}
public class TidyLog {
private var level : Level = .NONE
private var rootfile : String = ""
fileprivate var tagName : String = "TidyLog"
fileprivate let _rootfiles : [String] = ["main.swift", "AppDelegate.swift"]
public static let _self : TidyLog = TidyLog()
private init() {}
public static func instance() -> TidyLog {
return _self
}
public func markAsRootFile(_ file: String = #file) {
if validateRootfile(file) {
self.rootfile = triggeredFrom(fileName: file)
}
}
public func setLevel(_ _level: Level, file: String = #file) {
if validateRootfile(file) {
self.level = _level
}
}
public func setTag(_ _name: String, file: String = #file) {
if validateRootfile(file) {
self.tagName = _name
}
}
public static func v(_ message: String..., file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
if !_self.level.contains(.verbose) {
return
}
var _formatMessage = Array<String>()
if message.count > 0 {
for _message in message {
_formatMessage.append(_message)
}
}
let _msg = _self.buildMessage(Colors.White.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_formatMessage.joined(separator: " "), mode:"V")
_self.log(message: _msg, mode: .verbose)
}
public static func i(_ message: String..., file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
if !_self.level.contains(.info) {
return
}
var _formatMessage = Array<String>()
if message.count > 0 {
for _message in message {
_formatMessage.append(_message)
}
}
let _msg = _self.buildMessage(Colors.Yellow.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_formatMessage.joined(separator: " "), mode:"I")
_self.log(message: _msg, mode: .info)
}
public static func d(_ message: String..., file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
if !_self.level.contains(.debug) {
return
}
var _formatMessage = Array<String>()
if message.count > 0 {
for _message in message {
_formatMessage.append(_message)
}
}
let _msg = _self.buildMessage(Colors.Green.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_formatMessage.joined(separator: " "), mode:"D")
_self.log(message: _msg, mode: .debug)
}
public static func e(_ message: String..., file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
if !_self.level.contains(.error) {
return
}
var _formatMessage = Array<String>()
if message.count > 0 {
for _message in message {
_formatMessage.append(_message)
}
}
let _msg = _self.buildMessage(Colors.Red.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_formatMessage.joined(separator: " "), mode:"E")
_self.log(message: _msg, mode: .error)
}
public static func f(_ message: String..., file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
if !_self.level.contains(.fatal) {
return
}
var _formatMessage = Array<String>()
if message.count > 0 {
for _message in message {
_formatMessage.append(_message)
}
}
let _msg = _self.buildMessage(Colors.Cyan.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_formatMessage.joined(separator: " "), mode:"F")
_self.log(message: _msg, mode: .fatal)
}
//Use for simple json handling
public static func json(_ message: String, file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") {
//TODO
if !_self.level.contains(.debug) {
return
}
if message.characters.count > 0 {
let json = try! JSON.parse(string: message)
let messages = json.prettify()
for _message in messages {
let _msg = _self.buildMessage(Colors.Green.rawValue, timestamp:_self.timestamp(), fileName:_self.triggeredFrom(fileName: file), lineNumber:line, functionName:function, message:_message, mode:"JSON")
_self.log(message: _msg, mode: .debug)
}
}
}
public static func xml() {
//TODO
}
}
//Mark:- fileprivate alone
extension TidyLog {
fileprivate func validateRootfile(_ file: String = #file, function: String = #function, line : Int = #line, terminator: String = "\n") -> Bool {
let _fromFile = triggeredFrom(fileName: file)
if _rootfiles.contains(_fromFile) == false {
let _msg = buildMessage(Colors.Red.rawValue, timestamp:timestamp(), fileName:_fromFile, lineNumber:line, functionName:function, message:"Please set log level only from main.swift or AppDelegate.swift", mode:"E")
log(message: _msg, mode: .error)
return false
}
if _fromFile.characters.count == 0 {
let _msg = buildMessage(Colors.Red.rawValue, timestamp:timestamp(), fileName:_fromFile, lineNumber:line, functionName:function, message:"Unable to set log level. Please set root file", mode:"E")
log(message: _msg, mode: .error)
return false
}
return true
}
fileprivate func log(message: Any, mode: Level = .NONE, terminator: String = "\n") {
Swift.print(message, separator: " ", terminator: terminator)
}
fileprivate func log(message: Array<String>, mode: Level = .NONE, terminator: String = "\n") {
Swift.print(message.joined(separator: " "), separator: "", terminator: terminator)
}
fileprivate func timestamp() -> String {
let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS"
return formatter.string(from: date)
}
fileprivate func triggeredFrom(fileName : String = #file) -> String {
if let filename = fileName.components(separatedBy: "/").last {
return filename
}
return fileName
}
fileprivate func buildMessage(_ color: String, timestamp: String, fileName: String, lineNumber: Int, functionName: String, message: String..., mode: String) -> Array<String> {
// https://bugs.swift.org/browse/SR-957
//return String(format:"%@%@ %@ [%@:%i/%@] %@", color, timestamp, "TidyLog", fileName, lineNumber, functionName, message)
//return "\(color)\(timestamp) TidyLog [\(fileName):\(lineNumber)/\(functionName)] I> \(message)"
var formatArray = Array<String>()
formatArray.append(color+timestamp)
formatArray.append(tagName)
formatArray.append("[\(fileName):\(lineNumber)/\(functionName)]")
formatArray.append("\(mode)>")
for _message in message {
formatArray.append(_message)
}
return formatArray
}
}
| mit | 4db8665c4708adec70dfe06b3e73fb2d | 40.206009 | 231 | 0.643162 | 3.954283 | false | false | false | false |
64characters/Telephone | UseCasesTestDoubles/RingtoneSpy.swift | 1 | 1130 | //
// RingtoneSpy.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
public final class RingtoneSpy {
public let interval: Double = 0
public private(set) var didCallStartPlaying = false
public private(set) var didCallStopPlaying = false
public private(set) var stopPlayingCallCount = 0
public init() {}
}
extension RingtoneSpy: Ringtone {
public func startPlaying() {
didCallStartPlaying = true
}
public func stopPlaying() {
didCallStopPlaying = true
stopPlayingCallCount += 1
}
}
| gpl-3.0 | c020f7959b601b47cae42d35f5b991bd | 27.2 | 72 | 0.710993 | 4.208955 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Frontend/Browser/HistorySwiper.swift | 2 | 5510 | /* 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/. */
class HistorySwiper : NSObject {
var topLevelView: UIView!
var webViewContainer: UIView!
func setup(_ topLevelView: UIView, webViewContainer: UIView) {
self.topLevelView = topLevelView
self.webViewContainer = webViewContainer
goBackSwipe.delegate = self
goForwardSwipe.delegate = self
}
lazy var goBackSwipe: UIGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenLeftEdgeSwiped(_:)))
self.topLevelView.addGestureRecognizer(pan)
return pan
}()
lazy var goForwardSwipe: UIGestureRecognizer = {
let pan = UIPanGestureRecognizer(target: self, action: #selector(HistorySwiper.screenRightEdgeSwiped(_:)))
self.topLevelView.addGestureRecognizer(pan)
return pan
}()
@objc func updateDetected() {
restoreWebview()
}
func screenWidth() -> CGFloat {
return topLevelView.frame.width
}
fileprivate func handleSwipe(_ recognizer: UIGestureRecognizer) {
if getApp().browserViewController.homePanelController != nil {
return
}
guard let tab = getApp().browserViewController.tabManager.selectedTab, let webview = tab.webView else { return }
let p = recognizer.location(in: recognizer.view)
let shouldReturnToZero = recognizer == goBackSwipe ? p.x < screenWidth() / 2.0 : p.x > screenWidth() / 2.0
if recognizer.state == .ended || recognizer.state == .cancelled || recognizer.state == .failed {
UIView.animate(withDuration: 0.25, animations: {
if shouldReturnToZero {
self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty)
} else {
let x = recognizer == self.goBackSwipe ? self.screenWidth() : -self.screenWidth()
self.webViewContainer.transform = CGAffineTransform(translationX: x, y: self.webViewContainer.transform.ty)
self.webViewContainer.alpha = 0
}
}, completion: { (Bool) -> Void in
if !shouldReturnToZero {
if recognizer == self.goBackSwipe {
getApp().browserViewController.goBack()
} else {
getApp().browserViewController.goForward()
}
self.webViewContainer.transform = CGAffineTransform(translationX: 0, y: self.webViewContainer.transform.ty)
// when content size is updated
postAsyncToMain(3.0) {
self.restoreWebview()
}
NotificationCenter.default.removeObserver(self)
NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationPageInteractive), object: webview)
NotificationCenter.default.addObserver(self, selector: #selector(HistorySwiper.updateDetected), name: NSNotification.Name(rawValue: CliqzWebViewConstants.kNotificationWebViewLoadCompleteOrFailed), object: webview)
}
})
} else {
let tx = recognizer == goBackSwipe ? p.x : p.x - screenWidth()
webViewContainer.transform = CGAffineTransform(translationX: tx, y: self.webViewContainer.transform.ty)
}
}
func restoreWebview() {
NotificationCenter.default.removeObserver(self)
postAsyncToMain(0.4) { // after a render detected, allow ample time for drawing to complete
UIView.animate(withDuration: 0.2, animations: {
self.webViewContainer.alpha = 1.0
})
}
}
@objc func screenRightEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
handleSwipe(recognizer)
}
@objc func screenLeftEdgeSwiped(_ recognizer: UIScreenEdgePanGestureRecognizer) {
handleSwipe(recognizer)
}
}
extension HistorySwiper : UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ recognizer: UIGestureRecognizer) -> Bool {
guard let tab = getApp().browserViewController.tabManager.selectedTab else { return false}
if (recognizer == goBackSwipe && !tab.canGoBack) ||
(recognizer == goForwardSwipe && !tab.canGoForward) {
return false
}
guard let recognizer = recognizer as? UIPanGestureRecognizer else { return false }
let v = recognizer.velocity(in: recognizer.view)
if fabs(v.x) < fabs(v.y) {
return false
}
let tolerance = CGFloat(30.0)
let p = recognizer.location(in: recognizer.view)
return recognizer == goBackSwipe ? p.x < tolerance : p.x > screenWidth() - tolerance
}
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| mpl-2.0 | 518ab3f04c5c9873a55e8ae10e8c1191 | 44.916667 | 237 | 0.615426 | 5.471698 | false | false | false | false |
josefdolezal/fit-cvut | BI-IOS/semester-project/beta01/beta01/ViewController.swift | 1 | 1387 | //
// ViewController.swift
// beta01
//
// Created by Josef Dolezal on 07/11/15.
// Copyright © 2015 Josef Dolezal. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B0702880-A295-A8AB-F734-031A98A512DE")!, identifier: "Mac")
let colors = [
3289: UIColor.redColor()
]
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
if(CLLocationManager.authorizationStatus() != CLAuthorizationStatus.AuthorizedWhenInUse ) {
locationManager.requestWhenInUseAuthorization()
}
locationManager.startRangingBeaconsInRegion(region)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
let knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown }
if( knownBeacons.count > 0) {
let closestBeacon = knownBeacons[0]
view.backgroundColor = colors[closestBeacon.minor.integerValue]
}
}
}
| mit | 41c17024c44ff3415279c4e845eaf5ec | 29.130435 | 126 | 0.681097 | 5.133333 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarButtonState.swift | 1 | 2798 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
import WireSyncEngine
final class ConversationInputBarButtonState {
var sendButtonEnabled: Bool {
let disableSendButton: Bool? = Settings.shared[.sendButtonDisabled]
return hasText || (disableSendButton == false && !markingDown)
}
var hourglassButtonHidden: Bool {
return hasText || editing || ephemeral || isEphemeralSendingDisabled
}
var ephemeralIndicatorButtonHidden: Bool {
return editing || !ephemeral || isEphemeralSendingDisabled
}
var ephemeralIndicatorButtonEnabled: Bool {
return !ephemeralIndicatorButtonHidden && !syncedMessageDestructionTimeout && !isEphemeralTimeoutForced
}
private var hasText: Bool {
return textLength != 0
}
var ephemeral: Bool {
guard let timeout = destructionTimeout else { return false }
return timeout != .none
}
private var textLength = 0
private var editing = false
private var markingDown = false
private var destructionTimeout: MessageDestructionTimeoutValue?
private var mode = ConversationInputBarViewControllerMode.textInput
private var syncedMessageDestructionTimeout = false
private var isEphemeralSendingDisabled = false
private var isEphemeralTimeoutForced = false
func update(textLength: Int,
editing: Bool,
markingDown: Bool,
destructionTimeout: MessageDestructionTimeoutValue?,
mode: ConversationInputBarViewControllerMode,
syncedMessageDestructionTimeout: Bool,
isEphemeralSendingDisabled: Bool,
isEphemeralTimeoutForced: Bool) {
self.textLength = textLength
self.editing = editing
self.markingDown = markingDown
self.destructionTimeout = destructionTimeout
self.mode = mode
self.syncedMessageDestructionTimeout = syncedMessageDestructionTimeout
self.isEphemeralSendingDisabled = isEphemeralSendingDisabled
self.isEphemeralTimeoutForced = isEphemeralTimeoutForced
}
}
| gpl-3.0 | 3078762ce0c30c57eaf532e6d90b4183 | 34.417722 | 111 | 0.713009 | 5.133945 | false | false | false | false |
wireapp/wire-ios | Wire-iOS Tests/PhoneNumberTests.swift | 1 | 1672 | // Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import XCTest
@testable import Wire
final class PhoneNumberTests: XCTestCase {
func testThatPhoneNumberStructWithLeadingZeroCanBeCompared() {
// GIVEN
let phoneNumber1 = PhoneNumber(fullNumber: "+49017612345678")
let phoneNumber2 = PhoneNumber(fullNumber: "+4917612345678")
// WHEN & THEN
XCTAssertEqual(phoneNumber1, phoneNumber2)
}
func testThatDifferentNumbersAreNotEqual() {
// GIVEN
let phoneNumber1 = PhoneNumber(fullNumber: "+4917212345678")
let phoneNumber2 = PhoneNumber(fullNumber: "+4917612345678")
// WHEN & THEN
XCTAssertNotEqual(phoneNumber1, phoneNumber2)
}
func testThatUSnumberAreCamparable() {
// GIVEN
let phoneNumber1 = PhoneNumber(countryCode: 1, numberWithoutCode: "5417543010")
let phoneNumber2 = PhoneNumber(fullNumber: "+1-541-754-3010")
// WHEN & THEN
XCTAssertEqual(phoneNumber1, phoneNumber2)
}
}
| gpl-3.0 | 7dd149a6d80348d2269c1019fb8b2aac | 32.44 | 87 | 0.703947 | 4.518919 | false | true | false | false |
itsthisjustin/HeliumLift | Helium/Helium/Application.swift | 1 | 2335 | //
// Application.swift
// HeliumLift
//
// Created by Niall on 03/09/2015.
// Copyright © 2015-2019 Justin Mitchell. All rights reserved.
//
import Cocoa
@objc(Application)
class Application: NSApplication {
override func sendEvent(_ event: NSEvent) {
if event.type == .keyDown {
if (event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command) {
let appDelegate = NSApplication.shared.delegate as! AppDelegate
let nController = ((NSApplication.shared.windows.first! as NSWindow).contentViewController as! WebViewController)
switch event.keyCode {
case 0: // a
if NSApp.sendAction(#selector(NSResponder.selectAll(_:)), to: nil, from: self) { return }
case 2: // d
appDelegate.webViewController.goToHomepage()
case 6: // z
//if NSApp.sendAction(#selector(NSText.un?(nController.webView).undo()), to:nil, from:self) { return }
//if NSApp.sendAction(#selector(NSText.undoManager?.undo()), to:nil, from:self) { return }
return
case 7: // x
if NSApp.sendAction(#selector(NSText.cut(_:)), to: nil, from: self) {
return
}
case 8: // c
if NSApp.sendAction(#selector(NSText.copy(_:)), to: nil, from: self) {
return
}
case 9: // v
if NSApp.sendAction(#selector(NSText.paste(_:)), to: nil, from: self) { return }
case 12: // q
NSApplication.shared.terminate(self)
case 16: // y
if let nWindow = NSApplication.shared.windows.first {
if (nWindow.isVisible) {
nWindow.setIsVisible(false)
} else {
nWindow.setIsVisible(true)
}
}
return
case 17: // t
appDelegate.toggleTranslucency(nil)
return
case 24: // +
nController.zoomIn()
return
case 27: // -
nController.zoomOut()
return
case 30: // ]
nController.webView.goForward()
return
case 33: // [
nController.webView.goBack()
return
case 37: // l
appDelegate.didRequestLocation()
return
default:
break
}
}
else if (event.modifierFlags.intersection(.deviceIndependentFlagsMask) == (NSEvent.ModifierFlags.command.union(.shift))) {
if event.charactersIgnoringModifiers == "Z" {
if NSApp.sendAction(Selector(("redo:")), to: nil, from: self) { return }
}
}
}
return super.sendEvent(event)
}
}
| mit | 69d28ced0d7f05f828f2d254df37cc09 | 27.463415 | 125 | 0.637104 | 3.557927 | false | false | false | false |
MichaelSelsky/TheBeatingAtTheGates | Carthage/Checkouts/VirtualGameController/Samples/SceneKitDemo_iOS/SceneKitDemo_iOS/SceneKitDemo_iOS/GameViewController.swift | 1 | 10094 | //
// GameViewController.swift
// SceneKitDemo_iOS
//
// Created by Rob Reuss on 11/25/15.
// Copyright (c) 2015 Rob Reuss. All rights reserved.
//
import UIKit
import QuartzCore
import SceneKit
import GameController
import VirtualGameController
var ship: SCNNode!
var lightNode: SCNNode!
var cameraNode: SCNNode!
var scene: SCNScene!
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
VgcManager.startAs(.Central, appIdentifier: "vgc", customElements: CustomElements(), customMappings: CustomMappings())
NSNotificationCenter.defaultCenter().addObserver(self, selector: "controllerDidConnect:", name: VgcControllerDidConnectNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "controllerDidDisconnect:", name: VgcControllerDidDisconnectNotification, object: nil)
// create a new scene
scene = SCNScene(named: "art.scnassets/ship.scn")!
// create and add a camera to the scene
cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
scene.rootNode.addChildNode(cameraNode)
// place the camera
cameraNode.position = SCNVector3(x: 0, y: 0, z: 15)
// create and add a light to the scene
lightNode = SCNNode()
lightNode.light = SCNLight()
lightNode.light!.type = SCNLightTypeOmni
lightNode.position = SCNVector3(x: 0, y: 10, z: 10)
lightNode.eulerAngles = SCNVector3Make(0.0, Float(M_PI)/2.0, 0.0);
scene.rootNode.addChildNode(lightNode)
// create and add an ambient light to the scene
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight()
ambientLightNode.light!.type = SCNLightTypeAmbient
ambientLightNode.light!.color = UIColor.darkGrayColor()
scene.rootNode.addChildNode(ambientLightNode)
// retrieve the ship node
ship = scene.rootNode.childNodeWithName("ship", recursively: true)!
// retrieve the SCNView
let scnView = self.view as! SCNView
// set the scene to the view
scnView.scene = scene
// allows the user to manipulate the camera
scnView.allowsCameraControl = true
// show statistics such as fps and timing information
scnView.showsStatistics = true
// configure the view
scnView.backgroundColor = UIColor.blackColor()
}
func scaleShipByValue(var scaleValue: CGFloat) {
scaleValue = scaleValue + 1
if scaleValue < 0.10 { scaleValue = 0.10 }
ship.runAction(SCNAction.scaleTo(scaleValue, duration: 1.0))
}
@objc func controllerDidConnect(notification: NSNotification) {
// If we're enhancing a hardware controller, we should display the Peripheral UI
// instead of the debug view UI
if VgcManager.appRole == .EnhancementBridge { return }
guard let controller: VgcController = notification.object as? VgcController else {
print("Got nil controller in controllerDidConnect")
return
}
if controller.deviceInfo.controllerType == .MFiHardware { return }
// We only need attitude motion data
VgcManager.peripheralSetup = VgcPeripheralSetup()
VgcManager.peripheralSetup.motionActive = false // Let the user turn this on so they can orient the device, pointing it at the screen
VgcManager.peripheralSetup.enableMotionAttitude = true
VgcManager.peripheralSetup.enableMotionGravity = true
VgcManager.peripheralSetup.enableMotionRotationRate = true
VgcManager.peripheralSetup.enableMotionUserAcceleration = true
VgcManager.peripheralSetup.sendToController(controller)
// Dpad adjusts lighting position
controller.extendedGamepad?.dpad.valueChangedHandler = { (dpad, xValue, yValue) in
lightNode.position = SCNVector3(x: xValue * 10, y: yValue * 20, z: (yValue * 30) + 10)
}
// Left thumbstick controls move the plane left/right and up/down
controller.extendedGamepad?.leftThumbstick.valueChangedHandler = { (dpad, xValue, yValue) in
ship.runAction(SCNAction.moveTo(SCNVector3.init(xValue * 5, yValue * 5, 0.0), duration: 0.3))
}
// Right thumbstick Y axis controls plane scale
controller.extendedGamepad?.rightThumbstick.yAxis.valueChangedHandler = { (input, value) in
self.scaleShipByValue(CGFloat((controller.extendedGamepad?.rightThumbstick.yAxis.value)!))
}
// Right Shoulder pushes the ship away from the user
controller.extendedGamepad?.rightShoulder.valueChangedHandler = { (input, value, pressed) in
self.scaleShipByValue(CGFloat((controller.extendedGamepad?.rightShoulder.value)!))
}
// Left Shoulder resets the reference frame
controller.extendedGamepad?.leftShoulder.valueChangedHandler = { (input, value, pressed) in
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 10.0), count: 1))
}
// Right trigger draws the plane toward the user
controller.extendedGamepad?.rightTrigger.valueChangedHandler = { (input, value, pressed) in
self.scaleShipByValue(-(CGFloat((controller.extendedGamepad?.rightTrigger.value)!)))
}
// Right trigger draws the plane toward the user
controller.extendedGamepad?.rightTrigger.valueChangedHandler = { (input, value, pressed) in
self.scaleShipByValue(-(CGFloat((controller.extendedGamepad?.rightTrigger.value)!)))
}
// Get an image and apply it to the ship (image is set to my dog Digit, you'll see the fur)
controller.elements.custom[CustomElementType.SendImage.rawValue]!.valueChangedHandler = { (controller, element) in
//print("Custom element handler fired for Send Image: \(element.value)")
let image = UIImage(data: element.value as! NSData)
// get its material
let material = ship.childNodeWithName("shipMesh", recursively: true)!.geometry?.firstMaterial!
// highlight it
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
// on completion - unhighlight
SCNTransaction.setCompletionBlock {
SCNTransaction.begin()
SCNTransaction.setAnimationDuration(0.5)
material!.emission.contents = UIColor.blackColor()
SCNTransaction.commit()
}
material!.diffuse.contents = image
SCNTransaction.commit()
}
// Position ship at a solid origin
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 1.3), count: 1))
// Refresh on all motion changes
controller.motion?.valueChangedHandler = { (input: VgcMotion) in
let amplify = 2.75
// Invert these because we want to be able to have the ship display in a way
// that mirrors the position of the iOS device
let x = -(input.attitude.x) * amplify
let y = -(input.attitude.z) * amplify
let z = -(input.attitude.y) * amplify
// Increase the duration value if you want to smooth out the motion of the ship,
// so that hand shake is not reflected
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(CGFloat(x), y: CGFloat(y), z: CGFloat(z), duration: 0.15), count: 1))
//ship.runAction(SCNAction.moveTo(SCNVector3.init(CGFloat(x) * 4.0, CGFloat(y) * 4.0, CGFloat(z) * 4.0), duration: 0.3))
// The following will give the ship a bit of "float" that relates to the up/down motion of the iOS device.
// Disable the following if you want to focus on using the on-screen device input controls instead of motion input.
// If this section is not disabled, and you use the onscreen input controls, the two will "fight" over control
// and create hurky jerky motion.
/*
var xValue = CGFloat(input.gravity.x)
var yValue = CGFloat(input.userAcceleration.y)
xValue = xValue + (xValue * 3.0)
yValue = yValue - (yValue * 20.0)
ship.runAction(SCNAction.moveTo(SCNVector3.init(xValue, yValue, CGFloat( ship.position.z)), duration: 1.6))
*/
}
}
@objc func controllerDidDisconnect(notification: NSNotification) {
//guard let controller: VgcController = notification.object as? VgcController else { return }
ship.runAction(SCNAction.repeatAction(SCNAction.rotateToX(0, y: 0, z: 0, duration: 1.0), count: 1))
}
#if !(os(tvOS))
override func shouldAutorotate() -> Bool {
return true
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
#endif
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
| mit | 76066ef035793cf6b06ac61b5780ffbd | 38.584314 | 159 | 0.610561 | 5.136896 | false | false | false | false |
OscarSwanros/swift | test/SILGen/objc_protocols.swift | 1 | 13479 | // RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -disable-objc-attr-requires-foundation-module -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
import objc_protocols_Bas
@objc protocol NSRuncing {
func runce() -> NSObject
func copyRuncing() -> NSObject
func foo()
static func mince() -> NSObject
}
@objc protocol NSFunging {
func funge()
func foo()
}
protocol Ansible {
func anse()
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A8_generic{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[THIS:%.*]] : @owned $T):
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.runce!1.foreign
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @autoreleased NSObject
// CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]]
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[METHOD:%.*]] = witness_method [volatile] {{\$.*}}, #NSRuncing.copyRuncing!1.foreign
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<T>([[BORROWED_THIS:%.*]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : NSRuncing> (τ_0_0) -> @owned NSObject
// CHECK: end_borrow [[BORROWED_THIS]] from [[THIS]]
// -- Arguments are not consumed by objc calls
// CHECK: destroy_value [[THIS]]
func objc_generic<T : NSRuncing>(_ x: T) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF : $@convention(thin) <T where T : NSRuncing> (@owned T) -> () {
func objc_generic_partial_apply<T : NSRuncing>(_ x: T) {
// CHECK: bb0([[ARG:%.*]] : @owned $T):
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO]] :
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[ARG_COPY]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[METHOD]]
_ = x.runce
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1]] :
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<T>()
// CHECK: destroy_value [[METHOD]]
_ = T.runce
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTcTO]]
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[METHOD:%.*]] = apply [[FN]]<T>([[METATYPE]])
// CHECK: destroy_value [[METHOD:%.*]]
_ = T.mince
// CHECK: destroy_value [[ARG]]
}
// CHECK: } // end sil function '_T014objc_protocols0A22_generic_partial_applyyxAA9NSRuncingRzlF'
// CHECK: sil shared [serializable] [thunk] @[[THUNK1]] :
// CHECK: bb0([[SELF:%.*]] : @owned $Self):
// CHECK: [[FN:%.*]] = function_ref @[[THUNK1_THUNK:_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTO]] :
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>([[SELF]])
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK1]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK1_THUNK]]
// CHECK: bb0([[SELF:%.*]] : @guaranteed $Self):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.runce!1.foreign
// CHECK: [[RESULT:%.*]] = apply [[FN]]<Self>([[SELF_COPY]])
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK1_THUNK]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK2]] :
// CHECK: [[FN:%.*]] = function_ref @[[THUNK2_THUNK:_T014objc_protocols9NSRuncingP5minceSo8NSObjectCyFZTO]]
// CHECK: [[METHOD:%.*]] = partial_apply [[FN]]<Self>(%0)
// CHECK: return [[METHOD]]
// CHECK: } // end sil function '[[THUNK2]]'
// CHECK: sil shared [serializable] [thunk] @[[THUNK2_THUNK]] :
// CHECK: [[FN:%.*]] = witness_method $Self, #NSRuncing.mince!1.foreign
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]<Self>(%0)
// CHECK-NEXT: return [[RESULT]]
// CHECK: } // end sil function '[[THUNK2_THUNK]]'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A9_protocol{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[THIS:%.*]] : @owned $NSRuncing):
// -- Result of runce is autoreleased according to default objc conv
// CHECK: [[BORROWED_THIS_1:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS1:%.*]] = open_existential_ref [[BORROWED_THIS_1]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: [[RESULT1:%.*]] = apply [[METHOD]]<[[OPENED]]>([[THIS1]])
// -- Result of copyRuncing is received copy_valued according to -copy family
// CHECK: [[BORROWED_THIS_2:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS2:%.*]] = open_existential_ref [[BORROWED_THIS_2]] : $NSRuncing to $[[OPENED2:@opened(.*) NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED2]], #NSRuncing.copyRuncing!1.foreign
// CHECK: [[RESULT2:%.*]] = apply [[METHOD]]<[[OPENED2]]>([[THIS2:%.*]])
// -- Arguments are not consumed by objc calls
// CHECK: end_borrow [[BORROWED_THIS_2]] from [[THIS]]
// CHECK: end_borrow [[BORROWED_THIS_1]] from [[THIS]]
// CHECK: destroy_value [[THIS]]
func objc_protocol(_ x: NSRuncing) -> (NSObject, NSObject) {
return (x.runce(), x.copyRuncing())
}
// CHECK-LABEL: sil hidden @_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF : $@convention(thin) (@owned NSRuncing) -> () {
func objc_protocol_partial_apply(_ x: NSRuncing) {
// CHECK: bb0([[ARG:%.*]] : @owned $NSRuncing):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED_ARG:%.*]] = open_existential_ref [[BORROWED_ARG]] : $NSRuncing to $[[OPENED:@opened(.*) NSRuncing]]
// CHECK: [[FN:%.*]] = function_ref @_T014objc_protocols9NSRuncingP5runceSo8NSObjectCyFTcTO
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[RESULT:%.*]] = apply [[FN]]<[[OPENED]]>([[OPENED_ARG_COPY]])
// CHECK: destroy_value [[RESULT]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
_ = x.runce
// FIXME: rdar://21289579
// _ = NSRuncing.runce
}
// CHECK : } // end sil function '_T014objc_protocols0A23_protocol_partial_applyyAA9NSRuncing_pF'
// CHECK-LABEL: sil hidden @_T014objc_protocols0A21_protocol_composition{{[_0-9a-zA-Z]*}}F
func objc_protocol_composition(_ x: NSRuncing & NSFunging) {
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSRuncing.runce!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.runce()
// CHECK: [[THIS:%.*]] = open_existential_ref [[THIS_ORIG:%.*]] : $NSFunging & NSRuncing to $[[OPENED:@opened(.*) NSFunging & NSRuncing]]
// CHECK: [[METHOD:%.*]] = witness_method [volatile] $[[OPENED]], #NSFunging.funge!1.foreign
// CHECK: apply [[METHOD]]<[[OPENED]]>([[THIS]])
x.funge()
}
// -- ObjC thunks get emitted for ObjC protocol conformances
class Foo : NSRuncing, NSFunging, Ansible {
// -- NSRuncing
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc static func mince() -> NSObject { return NSObject() }
// -- NSFunging
@objc func funge() {}
// -- Both NSRuncing and NSFunging
@objc func foo() {}
// -- Ansible
func anse() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3FooC3foo{{[_0-9a-zA-Z]*}}FTo
// CHECK-NOT: sil hidden @_TToF{{.*}}anse{{.*}}
class Bar { }
extension Bar : NSRuncing {
@objc func runce() -> NSObject { return NSObject() }
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC5runce{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3BarC3foo{{[_0-9a-zA-Z]*}}FTo
// class Bas from objc_protocols_Bas module
extension Bas : NSRuncing {
// runce() implementation from the original definition of Bas
@objc func copyRuncing() -> NSObject { return NSObject() }
@objc func foo() {}
@objc static func mince() -> NSObject { return NSObject() }
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E11copyRuncing{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas0C0C0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- Inherited objc protocols
protocol Fungible : NSFunging { }
class Zim : Fungible {
@objc func funge() {}
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC5funge{{[_0-9a-zA-Z]*}}FTo
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols3ZimC3foo{{[_0-9a-zA-Z]*}}FTo
// class Zang from objc_protocols_Bas module
extension Zang : Fungible {
// funge() implementation from the original definition of Zim
@objc func foo() {}
}
// CHECK-LABEL: sil hidden [thunk] @_T018objc_protocols_Bas4ZangC0a1_B0E3foo{{[_0-9a-zA-Z]*}}FTo
// -- objc protocols with property requirements in extensions
// <rdar://problem/16284574>
@objc protocol NSCounting {
var count: Int {get}
}
class StoredPropertyCount {
@objc let count = 0
}
extension StoredPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_T014objc_protocols19StoredPropertyCountC5countSivgTo
class ComputedPropertyCount {
@objc var count: Int { return 0 }
}
extension ComputedPropertyCount: NSCounting {}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols21ComputedPropertyCountC5countSivgTo
// -- adding @objc protocol conformances to native ObjC classes should not
// emit thunks since the methods are already available to ObjC.
// Gizmo declared in Inputs/usr/include/Gizmo.h
extension Gizmo : NSFunging { }
// CHECK-NOT: _TTo{{.*}}5Gizmo{{.*}}
@objc class InformallyFunging {
@objc func funge() {}
@objc func foo() {}
}
extension InformallyFunging: NSFunging { }
@objc protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF : $@convention(thin) (@thick Initializable.Type, Int) -> @owned Initializable {
func testInitializableExistential(_ im: Initializable.Type, i: Int) -> Initializable {
// CHECK: bb0([[META:%[0-9]+]] : @trivial $@thick Initializable.Type, [[I:%[0-9]+]] : @trivial $Int):
// CHECK: [[I2_BOX:%[0-9]+]] = alloc_box ${ var Initializable }
// CHECK: [[PB:%.*]] = project_box [[I2_BOX]]
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[META]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[ARCHETYPE_META_OBJC:%[0-9]+]] = thick_to_objc_metatype [[ARCHETYPE_META]] : $@thick (@opened([[N]]) Initializable).Type to $@objc_metatype (@opened([[N]]) Initializable).Type
// CHECK: [[I2_ALLOC:%[0-9]+]] = alloc_ref_dynamic [objc] [[ARCHETYPE_META_OBJC]] : $@objc_metatype (@opened([[N]]) Initializable).Type, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method [volatile] $@opened([[N]]) Initializable, #Initializable.init!initializer.1.foreign : {{.*}}, [[ARCHETYPE_META]]{{.*}} : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0
// CHECK: [[I2:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[I]], [[I2_ALLOC]]) : $@convention(objc_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @owned τ_0_0) -> @owned τ_0_0
// CHECK: [[I2_EXIST_CONTAINER:%[0-9]+]] = init_existential_ref [[I2]] : $@opened([[N]]) Initializable : $@opened([[N]]) Initializable, $Initializable
// CHECK: store [[I2_EXIST_CONTAINER]] to [init] [[PB]] : $*Initializable
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Initializable
// CHECK: [[I2:%[0-9]+]] = load [copy] [[READ]] : $*Initializable
// CHECK: destroy_value [[I2_BOX]] : ${ var Initializable }
// CHECK: return [[I2]] : $Initializable
var i2 = im.init(int: i)
return i2
}
// CHECK: } // end sil function '_T014objc_protocols28testInitializableExistentialAA0D0_pAaC_pXp_Si1itF'
class InitializableConformer: Initializable {
@objc required init(int: Int) {}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols22InitializableConformerC{{[_0-9a-zA-Z]*}}fcTo
final class InitializableConformerByExtension {
init() {}
}
extension InitializableConformerByExtension: Initializable {
@objc convenience init(int: Int) {
self.init()
}
}
// CHECK-LABEL: sil hidden [thunk] @_T014objc_protocols33InitializableConformerByExtensionC{{[_0-9a-zA-Z]*}}fcTo
// Make sure we're crashing from trying to use materializeForSet here.
@objc protocol SelectionItem {
var time: Double { get set }
}
func incrementTime(contents: SelectionItem) {
contents.time += 1.0
}
| apache-2.0 | 297b0f5137a063c56cb1e3bc12d8795c | 43.147541 | 274 | 0.645748 | 3.406274 | false | false | false | false |
truecaller/ios-sdk | example/TrueSDKSample/HostViewController.swift | 1 | 10983 | //
// ViewController.swift
// SwiftTrueSDKHost
//
// Created by Aleksandar Mihailovski on 16/12/16.
// Copyright © 2016 True Software Scandinavia AB. All rights reserved.
//
import UIKit
import TrueSDK
enum TrueUserProperties: Int {
case name = 0
case phone
case address
case email
case job
case company
case countryCode
case gender
case url
case time
func title() -> String {
switch self {
case .name:
return "Name"
case .phone:
return "Phone"
case .address:
return "Address"
case .email:
return "Email"
case .job:
return "Job"
case .company:
return "Company"
case .countryCode:
return "Country"
case .gender:
return "Gender"
case .url:
return "Url"
case .time:
return "Date-Time"
}
}
}
typealias userDataModelType = [(String, String)] //Used as an ordered key,value store
func dateString(from timeStamp: Double) -> String {
let date = Date(timeIntervalSince1970: timeStamp)
let dateFormatter = DateFormatter()
// dateFormatter.timeZone = TimeZone(abbreviation: "GMT") //Set timezone that you want
dateFormatter.locale = NSLocale.current
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" //Specify your format that you want
let strDate = dateFormatter.string(from: date)
return strDate
}
extension TCTrueProfile {
func tupleList() -> userDataModelType {
var retVal = userDataModelType()
//Parse full name
var fullname = self.firstName ?? ""
fullname = fullname.count > 0 ? "\(self.firstName ?? "") \(self.lastName ?? "")" : (self.lastName ?? "")
//Parse address
var address = self.street ?? ""
var zipcity = self.zipCode ?? ""
let city = self.city ?? ""
zipcity = zipcity.count > 0 ? "\(zipcity)\(city.count > 0 ? " " : "")\(city)" : city
address = zipcity.count > 0 ? "\(address)\(address.count > 0 ? ", " : "")\(zipcity)" : address
//Fill user data model
//Non-optional values for display
retVal.append((TrueUserProperties.name.title(), fullname))
retVal.append((TrueUserProperties.phone.title(), self.phoneNumber ?? ""))
retVal.append((TrueUserProperties.address.title(), address))
retVal.append((TrueUserProperties.email.title(), self.email ?? ""))
retVal.append((TrueUserProperties.job.title(), self.jobTitle ?? ""))
retVal.append((TrueUserProperties.time.title(), dateString(from: self.requestTime)))
//Optional values for display
if let companyName = self.companyName {
retVal.append((TrueUserProperties.company.title(), companyName))
}
if let countryCode = self.countryCode {
retVal.append((TrueUserProperties.countryCode.title(), countryCode.uppercased()))
}
if let gender = self.gender.fullGenderName() {
retVal.append((TrueUserProperties.gender.title(), gender))
}
if let url = self.url {
retVal.append((TrueUserProperties.url.title(), url))
}
return retVal
}
}
extension TCTrueSDKGender {
func fullGenderName() -> String? {
switch self {
case .female:
return "Female"
case .male:
return "Male"
default:
return nil
}
}
}
//MARK: Error display
class ErrorToast: UIView {
@IBOutlet weak var errorCode: UILabel!
@IBOutlet weak var errorDescription: UILabel!
var error: Error? {
didSet {
if let nserror = error as NSError? {
DispatchQueue.main.async { [weak self] in
self?.errorCode.text = "\(nserror.domain): \(nserror.code)"
self?.errorDescription.text = nserror.localizedDescription
self?.isHidden = false
}
} else {
DispatchQueue.main.async { [weak self] in
self?.errorCode.text = ""
self?.errorDescription.text = ""
self?.isHidden = true
}
}
}
}
@IBAction func closeMessage(_ sender: UIButton) {
error = nil
}
}
//MARK: User profile display
class HostViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, TCTrueSDKDelegate, TCTrueSDKViewDelegate, NonTrueCallerDelegate {
@IBOutlet weak var avatarImageView: UIImageView!
@IBOutlet weak var profileRequestButton : TCProfileRequestButton!
@IBOutlet weak var userDataTableView: UITableView!
@IBOutlet weak var userDataHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var errorToast: ErrorToast!
@IBOutlet weak var otpFlowButton: UIButton!
@IBOutlet weak var logOutButton: UIButton!
var isUserLoggedIn: Bool = false {
didSet {
if isUserLoggedIn {
profileRequestButton.isHidden = true
otpFlowButton.isHidden = true
logOutButton.isHidden = false
} else {
profileRequestButton.isHidden = false
otpFlowButton.isHidden = false
logOutButton.isHidden = true
}
}
}
fileprivate var userDataModel: userDataModelType = [] {
didSet {
DispatchQueue.main.async {
self.userDataHeightConstraint.constant = CGFloat(self.userDataModel.count) * self.propertyRowHeight
}
}
}
fileprivate let propertyRowHeight = CGFloat(44.0)
//MARK: - UIViewController
override func viewDidLoad() {
super.viewDidLoad()
avatarImageView.layer.masksToBounds = true
setEmptyUserData()
userDataTableView.dataSource = self
userDataTableView.delegate = self
userDataHeightConstraint.constant = CGFloat(userDataModel.count) * propertyRowHeight
TCTrueSDK.sharedManager().titleType = .default
}
override func viewWillAppear(_ animated: Bool) {
TCTrueSDK.sharedManager().delegate = self
}
override func viewWillLayoutSubviews() {
avatarImageView.layer.cornerRadius = avatarImageView.layer.bounds.height / 2
}
@IBAction func openTitleSelection() {
let controller = TitleSelectionTableViewController()
controller.delegate = self
controller.title = "Select Title"
let navigationControlelr = UINavigationController(rootViewController: controller)
present(navigationControlelr, animated: true, completion: nil)
}
@IBAction func openNonTCFlow(_ sender: Any) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nonTcSignInViewController = storyboard.instantiateViewController(withIdentifier: "NonTruecallerSignInViewController") as! NonTruecallerSignInViewController
nonTcSignInViewController.delegate = self
let navController = UINavigationController(rootViewController: nonTcSignInViewController)
navController.modalPresentationStyle = .fullScreen
present(navController, animated: true, completion: nil)
}
//MARK: - Private
fileprivate func setEmptyUserData() {
userDataModel = TCTrueProfile().tupleList()
if let avatarImage = UIImage.init(named: "Avatar_addImage") {
DispatchQueue.main.async {
self.avatarImageView.image = avatarImage
}
}
}
fileprivate func parseUserData(_ profile: TCTrueProfile) {
//Convert the values to dictionary for presentation
userDataModel = profile.tupleList()
//Load the image if any or show the default one
if let avatarURL = profile.avatarURL {
let url = URL(string: avatarURL)
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url!) {
DispatchQueue.main.async {
self.avatarImageView.image = UIImage(data: data)
}
}
}
} else if let avatarImage = UIImage.init(named: "Avatar_Blue") {
DispatchQueue.main.async {
self.avatarImageView.image = avatarImage
}
}
}
//MARK: - UITableViewDataSource
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: TrueUserPropertyTableViewCell.reuseIdentifier()) as! TrueUserPropertyTableViewCell
let (propertyName, propertyValue) = self.userDataModel[indexPath.row];
cell.propertyNameLabel?.text = propertyName
cell.propertyValueLabel?.text = propertyValue
return cell
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.userDataModel.count
}
//MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return propertyRowHeight
}
//MARK: - TCTrueSDKDelegate
open func didFailToReceiveTrueProfileWithError(_ error: TCError) {
errorToast.error = error
setEmptyUserData()
userDataTableView.reloadData()
HostLogs.sharedInstance.logError(error)
}
open func didReceive(_ profile: TCTrueProfile) {
errorToast.error = nil
parseUserData(profile)
userDataTableView.reloadData()
isUserLoggedIn = true
}
open func willRequestProfile(withNonce nonce: String) {
// You may store the nonce string to verify the response
print("nonce: \(nonce)")
}
open func didReceive(_ profileResponse : TCTrueProfileResponse) {
// Response signature and signature algorithm can be fetched from profileResponse
// Nonce can also be retrieved from response and checked against the one received in willRequestProfile method
print("ProfileResponse payload: \(profileResponse.payload ?? "")")
}
func didReceiveNonTC(profileResponse: TCTrueProfile) {
errorToast.error = nil
parseUserData(profileResponse)
userDataTableView.reloadData()
isUserLoggedIn = true
}
@IBAction func logOut(_ sender: Any) {
isUserLoggedIn = false
setEmptyUserData()
userDataTableView.reloadData()
}
}
extension HostViewController: TitleSelectionTableViewControllerDelegate {
func didSet(title: TitleType) {
TCTrueSDK.sharedManager().titleType = title
}
}
| apache-2.0 | c9da1c410540e452a502145b4209dcb5 | 33.534591 | 167 | 0.612912 | 5.141386 | false | false | false | false |
ErAbhishekChandani/ACProgressHUD | ACProgressHUD/ACProgressHUD/AnimationChoiceViewController.swift | 1 | 3068 | //
// AnimationChoiceViewController.swift
// ACProgressHUD
//
// Created by Er Abhishek Chandani on 03/04/17.
// Copyright © 2017 Abhishek. All rights reserved.
//
import UIKit
class AnimationCell: UITableViewCell {
@IBOutlet weak var labelSelectionIndicator: UILabel!
@IBOutlet weak var labelAnimationName: UILabel!
}
let showAnimations = ["Grow In","Shrink In","Bounce In","Zoom In Out","Slide From Top","Bounce From Top","None"]
let dismissAnimations = ["Grow Out","Shrink Out","Fade Out","Bounce Out","Slide To Top","Slide To Bottom","Bounce To Top","Bounce To Bottom","None"]
class AnimationChoiceViewController: UIViewController {
var selectedAnimation : String = "Grow In"
enum AnimationType {
case show
case dismiss
}
var animationType : AnimationType = .show
//MARK:- UIView Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
if animationType == .show {
selectedAnimation = showAnimations[showHUDAnimation.rawValue]
}else{
selectedAnimation = dismissAnimations[dismissHUDAnimation.rawValue]
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARK:- UIButton Action Methods
@IBAction func actionOnDone(_ sender: AnyObject) {
_ = self.navigationController?.popViewController(animated: true)
}
}
//MARK:- UITableView Datasource & Delegate
extension AnimationChoiceViewController : UITableViewDataSource , UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if animationType == .show {
return showAnimations.count
}else{
return dismissAnimations.count
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AnimationCell") as! AnimationCell
if animationType == .show {
cell.labelAnimationName.text = showAnimations[indexPath.row]
}else{
cell.labelAnimationName.text = dismissAnimations[indexPath.row]
}
if cell.labelAnimationName.text == selectedAnimation {
cell.labelSelectionIndicator.isHidden = false
}else {cell.labelSelectionIndicator.isHidden = true }
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if animationType == .show {
selectedAnimation = showAnimations[indexPath.row]
showHUDAnimation = ACHudShowAnimation(rawValue: indexPath.row) ?? .growIn
}else{
selectedAnimation = dismissAnimations[indexPath.row]
dismissHUDAnimation = ACHudDismissAnimation(rawValue: indexPath.row) ?? .growOut
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
}
| mit | 97107ede97fa09ee3d3c5981cc0a988c | 31.62766 | 151 | 0.664493 | 5.1202 | false | false | false | false |
Nyx0uf/MPDRemote | src/iOS/cells/TrackTableViewCell.swift | 1 | 6105 | // TrackTableViewCell.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
final class TrackTableViewCell : UITableViewCell
{
// MARK: - Public properties
// Track number
@IBOutlet private(set) var lblTrack: UILabel!
// Track title
@IBOutlet private(set) var lblTitle: UILabel!
// Track duration
@IBOutlet private(set) var lblDuration: UILabel!
// Separator
@IBOutlet private(set) var separator: UIView!
// MARK: - Initializers
required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
self.contentView.backgroundColor = self.backgroundColor
self.lblTrack = UILabel()
self.lblTrack.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
self.lblTrack.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
self.lblTrack.font = UIFont(name: "HelveticaNeue-Bold", size: 10.0)
self.lblTrack.textAlignment = .center
self.contentView.addSubview(self.lblTrack)
self.lblTrack.translatesAutoresizingMaskIntoConstraints = false
self.lblTrack.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8.0).isActive = true
self.lblTrack.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 15.0).isActive = true
self.lblTrack.heightAnchor.constraint(equalToConstant: 14.0).isActive = true
self.lblTrack.widthAnchor.constraint(equalToConstant: 18.0).isActive = true
self.lblDuration = UILabel()
self.lblDuration.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
self.lblDuration.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
self.lblDuration.font = UIFont(name: "HelveticaNeue-Light", size: 10.0)
self.lblDuration.textAlignment = .right
self.contentView.addSubview(self.lblDuration)
self.lblDuration.translatesAutoresizingMaskIntoConstraints = false
self.lblDuration.heightAnchor.constraint(equalToConstant: 14.0).isActive = true
self.lblDuration.widthAnchor.constraint(equalToConstant: 32.0).isActive = true
self.lblDuration.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 15.0).isActive = true
self.lblDuration.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8.0).isActive = true
self.lblTitle = UILabel()
self.lblTitle.backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
self.lblTitle.textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
self.lblTitle.font = UIFont(name: "HelveticaNeue-Medium", size: 14.0)
self.lblTitle.textAlignment = .left
self.contentView.addSubview(self.lblTitle)
self.lblTitle.translatesAutoresizingMaskIntoConstraints = false
self.lblTitle.leadingAnchor.constraint(equalTo: self.lblTrack.trailingAnchor, constant: 8.0).isActive = true
self.lblTitle.trailingAnchor.constraint(equalTo: self.lblDuration.leadingAnchor, constant: 8.0).isActive = true
self.lblTitle.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 13.0).isActive = true
self.lblTitle.heightAnchor.constraint(equalToConstant: 18.0).isActive = true
self.separator = UIView()
self.separator.backgroundColor = UIColor(rgb: 0xE4E4E4)
self.contentView.addSubview(self.separator)
self.separator.translatesAutoresizingMaskIntoConstraints = false
self.separator.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 8.0).isActive = true
self.separator.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -8.0).isActive = true
self.separator.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: 0.0).isActive = true
self.separator.heightAnchor.constraint(equalToConstant: 1.0).isActive = true
}
override func setSelected(_ selected: Bool, animated: Bool)
{
super.setSelected(selected, animated: animated)
if selected
{
backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
else
{
backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
}
contentView.backgroundColor = backgroundColor
lblTitle.backgroundColor = backgroundColor
lblDuration.backgroundColor = backgroundColor
lblTrack.backgroundColor = backgroundColor
}
override func setHighlighted(_ highlighted: Bool, animated: Bool)
{
super.setHighlighted(highlighted, animated: animated)
if highlighted
{
backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
}
else
{
backgroundColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
}
contentView.backgroundColor = backgroundColor
lblTitle.backgroundColor = backgroundColor
lblDuration.backgroundColor = backgroundColor
lblTrack.backgroundColor = backgroundColor
}
}
| mit | f5d6e769131611b767086a9966f3ba9b | 45.603053 | 119 | 0.772645 | 3.839623 | false | false | false | false |
tattn/ios-architectures | ios-architectures/CleanArchitecture/DataStore.swift | 1 | 1126 | //
// DataStore.swift
// ios-architectures
//
// Created by 田中 達也 on 2016/12/01.
// Copyright © 2016年 tattn. All rights reserved.
//
import Foundation
import SWXMLHash
protocol CatDataStore {
func getCats()
}
protocol CatDataStoreOutput: class {
func receive(cats: [Cat])
}
class CatDataStoreImpl: CatDataStore {
weak var output: CatDataStoreOutput?
func getCats() {
guard let url = URL(string: "http://thecatapi.com/api/images/get?format=xml&results_per_page=20&size=small") else {
return
}
let session = URLSession(configuration: .default)
session.dataTask(with: url) { [weak self] data, _, _ in
guard let data = data else {
return
}
let xml = SWXMLHash.parse(data)
let cats: [Cat] = xml["response"]["data"]["images"]["image"].all
.flatMap { (id: $0["id"].element?.text ?? "", url: $0["url"].element?.text ?? "") }
.map { Cat(id: $0.id, url: $0.url) }
self?.output?.receive(cats: cats)
}.resume()
}
}
| mit | 65e1c414f57e512acb53f471d705fc75 | 23.23913 | 123 | 0.557848 | 3.704319 | false | false | false | false |
gkye/TheMovieDatabaseSwiftWrapper | Sources/TMDBSwift/OldModels/TVDetailedMDB.swift | 1 | 3002 | //
// TVDetailedMDB.swift
// MDBSwiftWrapper
//
// Created by George Kye on 2016-02-15.
// Copyright © 2016 George Kye. All rights reserved.
//
import Foundation
public struct TVCreatedBy: Decodable {
public var id: Int!
public var name: String!
public var profile_path: String!
}
public struct TVSeasons: Decodable {
public var air_date: String?
public var episode_count: Int!
public var id: Int!
public var poster_path: String!
public var season_number: Int!
}
public class TVDetailedMDB: TVMDB {
public var createdBy: [TVCreatedBy]?
public var episode_run_time: [Int]!
public var homepage: String?
public var in_production: Bool?
public var languages: [String]?
public var last_air_date: String!
public var networks: [KeywordsMDB]?
public var number_of_episodes: Int!
public var number_of_seasons: Int!
public var production_companies: [KeywordsMDB]?
public var seasons: [TVSeasons]?
public var status: String!
public var type: String!
public var nextEpisodeToAir: TVEpisodesMDB?
public var lastEpisodeToAir: TVEpisodesMDB?
enum CodingKeys: String, CodingKey {
case createdBy
case episode_run_time
case homepage
case in_production
case languages
case last_air_date
case networks
case number_of_episodes
case number_of_seasons
case production_companies
case seasons
case status
case type
case next_episode_to_air
case last_episode_to_air
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
createdBy = try? container.decode([TVCreatedBy].self, forKey: .createdBy)
episode_run_time = try? container.decode([Int].self, forKey: .episode_run_time)
homepage = try? container.decode(String.self, forKey: .homepage)
in_production = try? container.decode(Bool.self, forKey: .in_production)
languages = try? container.decode([String].self, forKey: .languages)
last_air_date = try? container.decode(String.self, forKey: .last_air_date)
networks = try? container.decode([KeywordsMDB].self, forKey: .networks)
number_of_episodes = try? container.decode(Int.self, forKey: .number_of_episodes)
number_of_seasons = try? container.decode(Int.self, forKey: .number_of_seasons)
production_companies = try? container.decode([KeywordsMDB].self, forKey: .production_companies)
seasons = try? container.decode([TVSeasons].self, forKey: .seasons)
status = try? container.decode(String.self, forKey: .status)
type = try? container.decode(String.self, forKey: .type)
nextEpisodeToAir = try? container.decode(TVEpisodesMDB.self, forKey: .next_episode_to_air)
lastEpisodeToAir = try? container.decode(TVEpisodesMDB.self, forKey: .last_episode_to_air)
try super.init(from: decoder)
}
}
| mit | 93733a9a9f4c88e71ee5abd4fa7b48a5 | 36.987342 | 103 | 0.679107 | 3.907552 | false | false | false | false |
Integreat/app-ios | Integreat/Integreat/model/Page+JsonMapping.swift | 2 | 1676 | import Foundation
extension Page {
class func pagesWithJson(json: [[String: AnyObject]], inContext context: NSManagedObjectContext) -> [Page] {
return json
.sort {
($0["id"] as? Int) ?? Int.max < ($1["id"] as? Int) ?? Int.max
}
.map { pageWithJson($0, inContext: context) }
}
class func pageWithJson(json: [String: AnyObject], inContext context: NSManagedObjectContext) -> Page {
let identifier = (json["id"] as? Int) ?? 0
if let page = Page.findPageWithIdentifier(identifier, inContext: context) {
updatePage(page, withJson: json)
return page
}
else {
let page = NSEntityDescription.insertNewObjectForEntityForName("Page", inManagedObjectContext: context)
as! Page
page.identifier = identifier
updatePage(page, withJson: json)
return page
}
}
class func updatePage(page: Page, withJson json: [String: AnyObject]) {
page.excerpt = json["excerpt"] as? String
page.content = json["content"] as? String
page.title = json["title"] as? String
page.status = json["status"] as? String
page.order = json["order"] as? String
page.thumbnailImageUrl = (json["thumbnail"] as? String).flatMap(NSURL.init)
page.lastModified = NSDate() // TODO: use modified_gmt
page.parentPage = (json["parent"] as? Int).flatMap { parentId in
if (parentId == 0) { return nil; }
return Page.findPageWithIdentifier(parentId, inContext: page.managedObjectContext!)
}
}
}
| lgpl-3.0 | ab54139f786729c54a23fd8c19692283 | 37.090909 | 115 | 0.585322 | 4.579235 | false | false | false | false |
devroo/onTodo | Swift/ControlFlow.playground/section-1.swift | 1 | 9336 | // Playground - noun: a place where people can play
import UIKit
// For 순환문(For Loops)
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
// 범위내에 값이 필요가 없는 단순 반복일 경우
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
println("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049"
// 배열
let names = ["Anna", "Alex", "Brian", "Jack"]
for name in names {
println("Hello, \(name)!")
}
// Hello, Anna!
// Hello, Alex !
// Hello, Brian!
// Hello, Jack!
// 튜플
let numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
for (animalName, legCount) in numberOfLegs {
println("\(animalName)s have \(legCount) legs")
}
// spiders have 8 legs
// ants have 6 legs
// cats have 4 legs
for character in "Hello" {
println(character)
}
// H
// e
// l
// l
// o
// For-조건부-증가부 (For-Condition-Increment )
for var index = 0; index < 3; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
var index : Int // <= 이 부분에서 선언해 주어야..
for index = 0; index < 3; ++index {
println("index is \(index)")
}
// index is 0
// index is 1
// index is 2
println("The loop statements were executed \(index) times")
// prints "The loop statements were executed 3 times"
// While 루프 (While Loops)
// 사다리게임-
//let finalSquare = 25
//var board = [Int](count : finalSquare + 1, repeatedValue: 0)
//
//board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
//board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
//
//var square = 0
//var diceRoll = 0
//while square < finalSquare {
// // 주사위를 던진다
// if ++diceRoll == 7 { diceRoll = 1 }
// // 주사위를 던져 나온 수 만큼 이동한다
// square += diceRoll
// if square < board.count {
// // 아직 게임판에 있다면, 뱀을 타고 내려가거나 사다리를 타고 올라간다
// //if we're still on the board, move up or down for a snake or a ladder
// square += board[square]
// println("Game over!")
// }
//}
// Do-While
let finalSquare = 25
var board = [Int](count : finalSquare + 1, repeatedValue: 0)
board[03] = +08; board[06] = +11; board[09] = +09; board[10] = +02
board[14] = -10; board[19] = -11; board[22] = -02; board[24] = -08
var square = 0
var diceRoll = 0
do {
// move up or down for a snake or ladder square += board[square]
// 주사위를 던진다
if ++diceRoll == 7 { diceRoll = 1 }
// 주사위를 던져서 나온 수만큼 이동한다
square += diceRoll
} while square < finalSquare
println("Game over!")
// 조건문 (Conditionals Statements)
// IF
var temperatureInFahrenheit = 30
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
}
// prints "It's very cold. Consider wearing a scarf."
temperatureInFahrenheit = 40
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// prints "It's not that cold. Wear a t-shirt."
temperatureInFahrenheit = 90
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
} else {
println("It's not that cold. Wear a t-shirt.")
}
// prints "It's really warm. Don't forget to wear sunscreen."
temperatureInFahrenheit = 72
if temperatureInFahrenheit <= 32 {
println("It's very cold. Consider wearing a scarf.")
} else if temperatureInFahrenheit >= 86 {
println("It's really warm. Don't forget to wear sunscreen.")
}
// Switch
let someCharacter: Character = "e"
switch someCharacter {
case "a", "e", "i", "o", "u":
println("\(someCharacter) is a vowel")
case "b", "c", "d", "f", "g", "h", "j", "k", "l", "m",
"n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z":
println("\(someCharacter) is a consonant")
default :
println("\(someCharacter) is not a vowel or a consonant")
}
// prints "e is a vowel "
let anotherCharacter: Character = "a"
switch anotherCharacter {
//case "a": 콤마로 구분해야함
case "A":
println("T he letter A")
default :
println("Not the letter A")
}
// 컴파일 에러가 납니다.
// 범위로 매치하기(Range Matching)
let count = 3_000_000_000_000
let countedThings = "stars in the Milky Way"
var naturalCount : String
switch count {
case 0:
naturalCount = "no"
case 1...3:
naturalCount = "a few"
case 4...9:
naturalCount = "several"
case 10...99:
naturalCount = "tens of"
case 100...999:
naturalCount = "hundreds of"
case 1000...999_999:
naturalCount = "thousands of"
default:
naturalCount = "millions and millions of"
println("There are \(naturalCount) \(countedThings).")
}
// prints "There are millions and millions of stars in the Milky Way ."
// 튜플 (Tuples)
let somePoint = (1, 1)
switch somePoint {
case (0, 0):
println("(0, 0) 은 원점에 있습니다")
case (_, 0):
println("(\(somePoint.0), 0)은 x축 상에 있습니다. ")
case (0, _):
println("(0, \(somePoint.1))은 y축 상에 있습니다.")
case (-2...2, -2...2):
println("(\(somePoint.0), \(somePoint.1))은 상자 안에 있습니다.")
default :
println("(\(somePoint.0), \(somePoint.1))은 상자 밖에 있습니다.")
}
//prints "(1, 1) is inside the box"
// 값을 상수와 묶기, 상수에 바인딩하기 (Value Bindings)
let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
println("x축 상에 있으며 x의 값은 \(x)값입니다.")
case (0, let y):
println("y축 상에 있으며 y의 값은 \(y)입니다.")
case let (x, y):
println("(\(x), \(y))에 있습니다.")
}
// 다음을 출력합니다: "x축 상에 있으며 x의 값은 2입니다"
// Switch 에 where절을 추가할 수 있다.
let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y :
println("(\(x), \(y)) 는 x==y인 곳에 있습니다.")
case let (x, y) where x == -y :
println("(\(x), \(y)) 는 x==-y인 곳에 있습니다.")
case let (x, y):
println("(\(x), \(y)) 는 기타 구역에 있습니다.")
}
// prints "(1, -1) 은 x==-y인 곳에 있습니다."
// 흐름제어 이동문(Control Transfer Statements)
// Continue
let puzzleInput = "great minds think alike"
var puzzleOutput = ""
for character in puzzleInput {
switch character {
case "a", "e", "i", "o", "u", " ":
continue
default :
puzzleOutput += character
}
println(puzzleOutput)
}
// prints "grtmndsthnklk"
// Break
let numberSymbol: Character = "三" // Simplified Chinese for the number 3
var possibleIntegerValue: Int?
switch numberSymbol {
case "1", "١", "一", "๑":
possibleIntegerValue = 1
case "2", "٢", "二", "๒":
possibleIntegerValue = 2
case "3", "٣", "三", "๓":
possibleIntegerValue = 3
case "4", "٤", "四", "๔":
possibleIntegerValue = 4
default:
break
}
if let integerValue = possibleIntegerValue {
println("The integer value of \(numberSymbol) is \(integerValue).")
} else {
println("An integer value could not be found for \(numberSymbol).")
}
// prints "The integer value of 三 is 3."
// Fallthrough
// fallthrough 키워드를 사용하면 단지, 다음에 나오는 case로 넘어갈 수 있을 뿐
let integerToDescribe = 5
var description = "수 \(integerToDescribe) 는"
switch integerToDescribe {
case 2, 3, 5, 7, 11, 13, 17, 19:
description += "소수이며, 또한"
fallthrough
default :
description += " 정수입니다."
}
println (description)
//prints "수 5는 소수이며, 또한 정수입니다."
// 이름표가 붙은 구문 (Labeled Statements)
gameLoop: while square != finalSquare {
if ++diceRoll == 7 { diceRoll = 1 }
switch square + diceRoll {
case finalSquare:
// 주사위에서 나온 수만 큼 이동해서 마지막 칸에 도달하면, 게임이 끝납니다.
break gameLoop
case let newSquare where newSquare > finalSquare:
// 주사위에서 나온 수만 큼 이동했을 때 마지막 칸을 넘어가면, 게임이 계속되고 주사위를 다시 던집니다.
continue gameLoop
default :
// 주사위에서 나온 수 만큼 이동합니다.
square += diceRoll
square += board[square]
}
println("Game over!")
}
// break문 안에 gameLoop라는 구문 이름표를 쓰지 않으면, while문이 아니라 switch문에서만 빠져나오게 됌
// gameLoop라는 이름표를 사용하였기 때문에 어느 흐름제어문(control statement)가 종료되어야 하는지 명확해짐
// continue를 썼을 때 어느 루프의 다음 이터레이션으로 넘어갈지에 대해 애매모호함이 발생하지 않을 수 있음
| gpl-2.0 | 8e8f2866b54d0e94783bade3925c27b1 | 25.878689 | 80 | 0.595755 | 2.660824 | false | false | false | false |
yannickl/Reactions | Sources/FacebookReactions.swift | 1 | 3324 | /*
* Reactions
*
* Copyright 2016-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
/// Default implementation of the facebook reactions.
extension Reaction {
/// Struct which defines the standard facebook reactions.
public struct facebook {
/// The facebook's "like" reaction.
public static var like: Reaction {
return reactionWithId("like")
}
/// The facebook's "love" reaction.
public static var love: Reaction {
return reactionWithId("love")
}
/// The facebook's "haha" reaction.
public static var haha: Reaction {
return reactionWithId("haha")
}
/// The facebook's "wow" reaction.
public static var wow: Reaction {
return reactionWithId("wow")
}
/// The facebook's "sad" reaction.
public static var sad: Reaction {
return reactionWithId("sad")
}
/// The facebook's "angry" reaction.
public static var angry: Reaction {
return reactionWithId("angry")
}
/// The list of standard facebook reactions in this order: `.like`, `.love`, `.haha`, `.wow`, `.sad`, `.angry`.
public static let all: [Reaction] = [facebook.like, facebook.love, facebook.haha, facebook.wow, facebook.sad, facebook.angry]
// MARK: - Convenience Methods
private static func reactionWithId(_ id: String) -> Reaction {
var color: UIColor = .black
var alternativeIcon: UIImage? = nil
switch id {
case "like":
color = UIColor(red: 0.29, green: 0.54, blue: 0.95, alpha: 1)
alternativeIcon = imageWithName("like-template").withRenderingMode(.alwaysTemplate)
case "love":
color = UIColor(red: 0.93, green: 0.23, blue: 0.33, alpha: 1)
case "angry":
color = UIColor(red: 0.96, green: 0.37, blue: 0.34, alpha: 1)
default:
color = UIColor(red: 0.99, green: 0.84, blue: 0.38, alpha: 1)
}
return Reaction(id: id, title: id.localized(from: "FacebookReactionLocalizable"), color: color, icon: imageWithName(id), alternativeIcon: alternativeIcon)
}
private static func imageWithName(_ name: String) -> UIImage {
return UIImage(named: name, in: .reactionsBundle(), compatibleWith: nil)!
}
}
}
| mit | d5da5cf05c42986798640dce44381274 | 35.527473 | 160 | 0.676294 | 4.212928 | false | false | false | false |
WEzou/weiXIn | swift-zw/AppDelegate.swift | 1 | 2852 | //
// AppDelegate.swift
// swift-zw
//
// Created by ymt on 2017/11/30.
// Copyright © 2017年 ymt. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var backgroundTask:UIBackgroundTaskIdentifier! = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.backgroundColor = UIColor.white
self.window?.makeKeyAndVisible()
UIApplication.shared.statusBarStyle = .lightContent
let mainvc = MainViewController()
self.window?.rootViewController = mainvc
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// 延迟程序静止的时间
DispatchQueue.global().async() {
//如果已存在后台任务,先将其设为完成
if self.backgroundTask != nil {
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
}
}
//如果要后台运行
self.backgroundTask = application.beginBackgroundTask(expirationHandler: {
() -> Void in
//如果没有调用endBackgroundTask,时间耗尽时应用程序将被终止
application.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskInvalid
})
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| apache-2.0 | 51085a78e476d7c6d29b2a754d2ea72f | 37.097222 | 285 | 0.694495 | 5.586558 | false | false | false | false |
Gofake1/Color-Picker | Color Picker/ColorWheelView.swift | 1 | 6365 | //
// ColorWheelView.swift
// Color Picker
//
// Created by David Wu on 5/4/17.
// Copyright © 2017 Gofake1. All rights reserved.
//
import Cocoa
typealias RGB = (r: UInt8, g: UInt8, b: UInt8)
protocol ColorWheelViewDelegate: class {
func colorDidChange(_ newColor: NSColor)
}
@IBDesignable
class ColorWheelView: NSView {
weak var delegate: ColorWheelViewDelegate?
/// The color in the crosshair
private(set) var selectedColor = NSColor(calibratedRed: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
private var blackImage: CGImage!
/// Used in drawing, doesn't affect `selectedColor`
private var brightness: CGFloat = 1.0
private var colorWheelImage: CGImage!
private var crosshairLocation: CGPoint!
required init?(coder: NSCoder) {
super.init(coder: coder)
blackImage = blackImage(rect: frame)
colorWheelImage = colorWheelImage(rect: frame)
crosshairLocation = CGPoint(x: frame.width/2, y: frame.height/2)
}
override func draw(_ dirtyRect: NSRect) {
guard let context = NSGraphicsContext.current?.cgContext else { return }
context.addEllipse(in: dirtyRect)
context.clip()
context.draw(colorWheelImage, in: dirtyRect)
context.setAlpha(1-brightness)
context.draw(blackImage, in: dirtyRect)
context.setAlpha(1.0)
if brightness < 0.5 {
context.setStrokeColor(CGColor.white)
} else {
context.setStrokeColor(CGColor.black)
}
context.addEllipse(in: CGRect(origin: CGPoint(x: crosshairLocation.x-5.5, y: crosshairLocation.y-5.5),
size: CGSize(width: 11, height: 11)))
context.addLines(between: [CGPoint(x: crosshairLocation.x, y: crosshairLocation.y-8),
CGPoint(x: crosshairLocation.x, y: crosshairLocation.y+8)])
context.addLines(between: [CGPoint(x: crosshairLocation.x-8, y: crosshairLocation.y),
CGPoint(x: crosshairLocation.x+8, y: crosshairLocation.y)])
context.strokePath()
}
func setColor(_ newColor: NSColor, _ redrawCrosshair: Bool = true) {
if redrawCrosshair {
let center = CGPoint(x: frame.width/2, y: frame.height/2)
crosshairLocation = point(for: newColor, center: center) ?? center
}
selectedColor = newColor
brightness = newColor.scaledBrightness
needsDisplay = true
}
private func blackImage(rect: NSRect) -> CGImage {
let width = Int(rect.width), height = Int(rect.height)
var imageBytes = [RGB](repeating: RGB(r: 0, g: 0, b: 0), count: width * height)
return cgImage(bytes: &imageBytes, width: width, height: height)
}
private func colorWheelImage(rect: NSRect) -> CGImage {
let width = Int(rect.width), height = Int(rect.height)
var imageBytes = [RGB]()
for j in stride(from: height, to: 0, by: -1) {
for i in 0..<width {
let color = NSColor(coord: (i, j), center: (width/2, height/2), brightness: 1.0)
imageBytes.append(RGB(r: UInt8(color.redComponent*255),
g: UInt8(color.greenComponent*255),
b: UInt8(color.blueComponent*255)))
}
}
return cgImage(bytes: &imageBytes, width: width, height: height)
}
private func cgImage(bytes: inout [RGB], width: Int, height: Int) -> CGImage {
return CGImage(width: width,
height: height,
bitsPerComponent: 8,
bitsPerPixel: 24,
bytesPerRow: width * MemoryLayout<RGB>.size,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.none.rawValue),
provider: CGDataProvider(data: NSData(bytes: &bytes,
length: bytes.count *
MemoryLayout<RGB>.size))!,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent)!
}
private func point(for color: NSColor, center: CGPoint) -> CGPoint? {
let h = color.hueComponent
let s = color.saturationComponent
let angle = h * 2 * CGFloat.pi
let distance = s * center.x
let x = center.x + sin(angle)*distance
let y = center.y + cos(angle)*distance
return CGPoint(x: x, y: y)
}
/// - returns: Clamped point and boolean indicating if the point was clamped
private func clamped(_ point: CGPoint) -> (CGPoint, Bool) {
let centerX = frame.width/2
let centerY = frame.height/2
let vX = point.x - centerX
let vY = point.y - centerY
let distanceFromCenter = sqrt((vX*vX) + (vY*vY))
let radius = frame.width/2
if distanceFromCenter > radius {
return (CGPoint(x: centerX + vX/distanceFromCenter * radius,
y: centerY + vY/distanceFromCenter * radius), true)
} else {
return (point, false)
}
}
/// - postcondition: Calls `delegate`
private func setColor(at point: CGPoint) {
selectedColor = NSColor(coord: (Int(point.x), Int(point.y)),
center: (Int(frame.width/2), Int(frame.height/2)),
brightness: 1.0)
delegate?.colorDidChange(selectedColor)
}
// MARK: - Mouse
/// - postcondition: May call `NSWindow.makeFirstResponder`
override func mouseDown(with event: NSEvent) {
let (clampedPoint, wasClamped) = clamped(convert(event.locationInWindow, from: nil))
if wasClamped {
window?.makeFirstResponder(window?.contentView)
} else {
setColor(at: clampedPoint)
crosshairLocation = clampedPoint
needsDisplay = true
}
}
override func mouseDragged(with event: NSEvent) {
let (clampedPoint, _) = clamped(convert(event.locationInWindow, from: nil))
setColor(at: clampedPoint)
crosshairLocation = clampedPoint
needsDisplay = true
}
}
| mit | 8229e9154b1c37e2ab5c1f700d49bddf | 38.775 | 110 | 0.578253 | 4.388966 | false | false | false | false |
ahoppen/swift | SwiftCompilerSources/Sources/SIL/Instruction.swift | 1 | 22894 | //===--- Instruction.swift - Defines the Instruction classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
//===----------------------------------------------------------------------===//
// Instruction base classes
//===----------------------------------------------------------------------===//
public class Instruction : ListNode, CustomStringConvertible, Hashable {
final public var next: Instruction? {
SILInstruction_next(bridged).instruction
}
final public var previous: Instruction? {
SILInstruction_previous(bridged).instruction
}
// Needed for ReverseList<Instruction>.reversed(). Never use directly.
public var _firstInList: Instruction { SILBasicBlock_firstInst(block.bridged).instruction! }
// Needed for List<Instruction>.reversed(). Never use directly.
public var _lastInList: Instruction { SILBasicBlock_lastInst(block.bridged).instruction! }
final public var block: BasicBlock {
SILInstruction_getParent(bridged).block
}
final public var function: Function { block.function }
final public var description: String {
var s = SILNode_debugDescription(bridgedNode)
return String(cString: s.c_str())
}
final public var operands: OperandArray {
return OperandArray(opArray: SILInstruction_getOperands(bridged))
}
fileprivate var resultCount: Int { 0 }
fileprivate func getResult(index: Int) -> Value { fatalError() }
public struct Results : RandomAccessCollection {
fileprivate let inst: Instruction
fileprivate let numResults: Int
public var startIndex: Int { 0 }
public var endIndex: Int { numResults }
public subscript(_ index: Int) -> Value { inst.getResult(index: index) }
}
final public var results: Results {
Results(inst: self, numResults: resultCount)
}
final public var location: Location {
return Location(bridged: SILInstruction_getLocation(bridged))
}
public var mayTrap: Bool { false }
final public var mayHaveSideEffects: Bool {
return mayTrap || mayWriteToMemory
}
final public var mayReadFromMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayWriteToMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayReadOrWriteMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior,
MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
public final var mayRelease: Bool {
return SILInstruction_mayRelease(bridged)
}
public static func ==(lhs: Instruction, rhs: Instruction) -> Bool {
lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public var bridged: BridgedInstruction {
BridgedInstruction(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedInstruction {
public var instruction: Instruction { obj.getAs(Instruction.self) }
public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) }
public var optional: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: self.obj)
}
}
extension OptionalBridgedInstruction {
var instruction: Instruction? { obj.getAs(Instruction.self) }
public static var none: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: nil)
}
}
public class SingleValueInstruction : Instruction, Value {
final public var definingInstruction: Instruction? { self }
final public var definingBlock: BasicBlock { block }
fileprivate final override var resultCount: Int { 1 }
fileprivate final override func getResult(index: Int) -> Value { self }
}
public final class MultipleValueInstructionResult : Value {
final public var description: String {
var s = SILNode_debugDescription(bridgedNode)
return String(cString: s.c_str())
}
public var instruction: Instruction {
MultiValueInstResult_getParent(bridged).instruction
}
public var definingInstruction: Instruction? { instruction }
public var definingBlock: BasicBlock { instruction.block }
public var index: Int { MultiValueInstResult_getIndex(bridged) }
var bridged: BridgedMultiValueResult {
BridgedMultiValueResult(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedMultiValueResult {
var result: MultipleValueInstructionResult {
obj.getAs(MultipleValueInstructionResult.self)
}
}
public class MultipleValueInstruction : Instruction {
fileprivate final override var resultCount: Int {
return MultipleValueInstruction_getNumResults(bridged)
}
fileprivate final override func getResult(index: Int) -> Value {
MultipleValueInstruction_getResult(bridged, index).result
}
}
/// Instructions, which have a single operand.
public protocol UnaryInstruction : AnyObject {
var operands: OperandArray { get }
var operand: Value { get }
}
extension UnaryInstruction {
public var operand: Value { operands[0].value }
}
//===----------------------------------------------------------------------===//
// no-value instructions
//===----------------------------------------------------------------------===//
/// Used for all non-value instructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedInstruction : Instruction {
}
public protocol StoringInstruction : AnyObject {
var operands: OperandArray { get }
}
extension StoringInstruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
}
final public class StoreInst : Instruction, StoringInstruction {
// must match with enum class StoreOwnershipQualifier
public enum StoreOwnership: Int {
case unqualified = 0, initialize = 1, assign = 2, trivial = 3
}
public var destinationOwnership: StoreOwnership {
StoreOwnership(rawValue: StoreInst_getStoreOwnership(bridged))!
}
}
final public class StoreWeakInst : Instruction, StoringInstruction { }
final public class StoreUnownedInst : Instruction, StoringInstruction { }
final public class CopyAddrInst : Instruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
public var isTakeOfSrc: Bool {
CopyAddrInst_isTakeOfSrc(bridged) != 0
}
public var isInitializationOfDest: Bool {
CopyAddrInst_isInitializationOfDest(bridged) != 0
}
}
final public class EndAccessInst : Instruction, UnaryInstruction {
public var beginAccess: BeginAccessInst {
return operand as! BeginAccessInst
}
}
final public class EndBorrowInst : Instruction, UnaryInstruction {}
final public class DeallocStackInst : Instruction, UnaryInstruction {
public var allocstack: AllocStackInst {
return operand as! AllocStackInst
}
}
final public class DeallocStackRefInst : Instruction, UnaryInstruction {
public var allocRef: AllocRefInstBase { operand as! AllocRefInstBase }
}
final public class CondFailInst : Instruction, UnaryInstruction {
public override var mayTrap: Bool { true }
public var message: String { CondFailInst_getMessage(bridged).string }
}
final public class FixLifetimeInst : Instruction, UnaryInstruction {}
final public class DebugValueInst : Instruction, UnaryInstruction {}
final public class UnconditionalCheckedCastAddrInst : Instruction {
public override var mayTrap: Bool { true }
}
final public class SetDeallocatingInst : Instruction, UnaryInstruction {}
final public class DeallocRefInst : Instruction, UnaryInstruction {}
public class RefCountingInst : Instruction, UnaryInstruction {
public var isAtomic: Bool { RefCountingInst_getIsAtomic(bridged) }
}
final public class StrongRetainInst : RefCountingInst {
}
final public class RetainValueInst : RefCountingInst {
}
final public class StrongReleaseInst : RefCountingInst {
}
final public class ReleaseValueInst : RefCountingInst {
}
final public class DestroyValueInst : Instruction, UnaryInstruction {}
final public class DestroyAddrInst : Instruction, UnaryInstruction {}
final public class InjectEnumAddrInst : Instruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InjectEnumAddrInst_caseIndex(bridged) }
}
final public class UnimplementedRefCountingInst : RefCountingInst {}
//===----------------------------------------------------------------------===//
// single-value instructions
//===----------------------------------------------------------------------===//
/// Used for all SingleValueInstructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedSingleValueInst : SingleValueInstruction {
}
final public class LoadInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadWeakInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class BuiltinInst : SingleValueInstruction {
// TODO: find a way to directly reuse the BuiltinValueKind enum
public enum ID {
case None
case DestroyArray
}
public var id: ID? {
switch BuiltinInst_getID(bridged) {
case DestroyArrayBuiltin: return .DestroyArray
default: return .None
}
}
}
final public class UpcastInst : SingleValueInstruction, UnaryInstruction {}
final public
class UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {}
final public
class RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class AddressToPointerInst : SingleValueInstruction, UnaryInstruction {}
final public
class PointerToAddressInst : SingleValueInstruction, UnaryInstruction {}
final public
class IndexAddrInst : SingleValueInstruction {}
final public
class InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
public class GlobalAccessInst : SingleValueInstruction {
final public var global: GlobalVariable {
GlobalAccessInst_getGlobal(bridged).globalVar
}
}
final public class FunctionRefInst : GlobalAccessInst {
public var referencedFunction: Function {
FunctionRefInst_getReferencedFunction(bridged).function
}
}
final public class GlobalAddrInst : GlobalAccessInst {}
final public class GlobalValueInst : GlobalAccessInst {}
final public class IntegerLiteralInst : SingleValueInstruction {}
final public class StringLiteralInst : SingleValueInstruction {
public var string: String { StringLiteralInst_getValue(bridged).string }
}
final public class TupleInst : SingleValueInstruction {
}
final public class TupleExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleExtractInst_fieldIndex(bridged) }
}
final public
class TupleElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleElementAddrInst_fieldIndex(bridged) }
}
final public class StructInst : SingleValueInstruction {
}
final public class StructExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructExtractInst_fieldIndex(bridged) }
}
final public
class StructElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructElementAddrInst_fieldIndex(bridged) }
}
public protocol EnumInstruction : AnyObject {
var caseIndex: Int { get }
}
final public class EnumInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { EnumInst_caseIndex(bridged) }
public var operand: Value? { operands.first?.value }
}
final public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedEnumDataInst_caseIndex(bridged) }
}
final public class InitEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InitEnumDataAddrInst_caseIndex(bridged) }
}
final public class UncheckedTakeEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedTakeEnumDataAddrInst_caseIndex(bridged) }
}
final public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { RefElementAddrInst_fieldIndex(bridged) }
}
final public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction {
public override var mayTrap: Bool { true }
}
final public
class ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ObjCExistentialMetatypeToObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public
class ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class MarkDependenceInst : SingleValueInstruction {
public var value: Value { return operands[0].value }
public var base: Value { return operands[1].value }
}
final public class RefToBridgeObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToRefInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToWordInst : SingleValueInstruction,
UnaryInstruction {}
final public class BeginAccessInst : SingleValueInstruction, UnaryInstruction {}
final public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class ProjectBoxInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { ProjectBoxInst_fieldIndex(bridged) }
}
final public class CopyValueInst : SingleValueInstruction, UnaryInstruction {}
final public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {}
final public
class ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public class PartialApplyInst : SingleValueInstruction, ApplySite {
public var numArguments: Int { PartialApplyInst_numArguments(bridged) }
public var isOnStack: Bool { PartialApplyInst_isOnStack(bridged) != 0 }
public func calleeArgIndex(callerArgIndex: Int) -> Int {
PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged) + callerArgIndex
}
public func callerArgIndex(calleeArgIndex: Int) -> Int? {
let firstIdx = PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged)
if calleeArgIndex >= firstIdx {
return calleeArgIndex - firstIdx
}
return nil
}
}
final public class ApplyInst : SingleValueInstruction, FullApplySite {
public var numArguments: Int { ApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { self }
}
final public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class WitnessMethodInst : SingleValueInstruction {}
final public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {}
final public class IsEscapingClosureInst : SingleValueInstruction, UnaryInstruction {}
//===----------------------------------------------------------------------===//
// single-value allocation instructions
//===----------------------------------------------------------------------===//
public protocol Allocation : AnyObject { }
final public class AllocStackInst : SingleValueInstruction, Allocation {
}
public class AllocRefInstBase : SingleValueInstruction, Allocation {
final public var isObjC: Bool { AllocRefInstBase_isObjc(bridged) != 0 }
final public var canAllocOnStack: Bool {
AllocRefInstBase_canAllocOnStack(bridged) != 0
}
}
final public class AllocRefInst : AllocRefInstBase {
}
final public class AllocRefDynamicInst : AllocRefInstBase {
}
final public class AllocBoxInst : SingleValueInstruction, Allocation {
}
final public class AllocExistentialBoxInst : SingleValueInstruction, Allocation {
}
//===----------------------------------------------------------------------===//
// multi-value instructions
//===----------------------------------------------------------------------===//
final public class BeginCOWMutationInst : MultipleValueInstruction,
UnaryInstruction {
public var uniquenessResult: Value { return getResult(index: 0) }
public var bufferResult: Value { return getResult(index: 1) }
}
final public class DestructureStructInst : MultipleValueInstruction, UnaryInstruction {
}
final public class DestructureTupleInst : MultipleValueInstruction, UnaryInstruction {
}
final public class BeginApplyInst : MultipleValueInstruction, FullApplySite {
public var numArguments: Int { BeginApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { nil }
}
//===----------------------------------------------------------------------===//
// terminator instructions
//===----------------------------------------------------------------------===//
public class TermInst : Instruction {
final public var successors: SuccessorArray {
SuccessorArray(succArray: TermInst_getSuccessors(bridged))
}
}
final public class UnreachableInst : TermInst {
}
final public class ReturnInst : TermInst, UnaryInstruction {
}
final public class ThrowInst : TermInst, UnaryInstruction {
}
final public class YieldInst : TermInst {
}
final public class UnwindInst : TermInst {
}
final public class TryApplyInst : TermInst, FullApplySite {
public var numArguments: Int { TryApplyInst_numArguments(bridged) }
public var normalBlock: BasicBlock { successors[0] }
public var errorBlock: BasicBlock { successors[1] }
public var singleDirectResult: Value? { normalBlock.arguments[0] }
}
final public class BranchInst : TermInst {
public var targetBlock: BasicBlock { BranchInst_getTargetBlock(bridged).block }
public func getArgument(for operand: Operand) -> Argument {
return targetBlock.arguments[operand.index]
}
}
final public class CondBranchInst : TermInst {
var trueBlock: BasicBlock { successors[0] }
var falseBlock: BasicBlock { successors[1] }
var condition: Value { operands[0].value }
var trueOperands: OperandArray { operands[1...CondBranchInst_getNumTrueArgs(bridged)] }
var falseOperands: OperandArray {
let ops = operands
return ops[(CondBranchInst_getNumTrueArgs(bridged) &+ 1)..<ops.count]
}
public func getArgument(for operand: Operand) -> Argument {
let argIdx = operand.index - 1
let numTrueArgs = CondBranchInst_getNumTrueArgs(bridged)
if (0..<numTrueArgs).contains(argIdx) {
return trueBlock.arguments[argIdx]
} else {
return falseBlock.arguments[argIdx - numTrueArgs]
}
}
}
final public class SwitchValueInst : TermInst {
}
final public class SwitchEnumInst : TermInst {
public var enumOp: Value { operands[0].value }
public struct CaseIndexArray : RandomAccessCollection {
fileprivate let switchEnum: SwitchEnumInst
public var startIndex: Int { return 0 }
public var endIndex: Int { SwitchEnumInst_getNumCases(switchEnum.bridged) }
public subscript(_ index: Int) -> Int {
SwitchEnumInst_getCaseIndex(switchEnum.bridged, index)
}
}
var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) }
var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> {
zip(caseIndices, successors)
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? {
cases.first(where: { $0.0 == forCaseIndex })?.1
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueCase(forSuccessor: BasicBlock) -> Int? {
cases.first(where: { $0.1 == forSuccessor })?.0
}
}
final public class SwitchEnumAddrInst : TermInst {
}
final public class DynamicMethodBranchInst : TermInst {
}
final public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction {
}
final public class CheckedCastBranchInst : TermInst, UnaryInstruction {
}
final public class CheckedCastAddrBranchInst : TermInst, UnaryInstruction {
}
| apache-2.0 | d4af5ddb6dd306ef36fc7b66f72781b3 | 31.24507 | 110 | 0.728007 | 4.834037 | false | false | false | false |
coodly/SlimTimerAPI | Tests/SlimTimerAPITests/Date+TestHelpers.swift | 1 | 1532 | /*
* Copyright 2017 Coodly LLC
*
* 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
internal extension Date {
func isOn(year: Int, month: Int, day: Int) -> Bool {
var gregorian = Calendar(identifier: .gregorian)
gregorian.timeZone = TimeZone(secondsFromGMT: 0)!
let components = gregorian.dateComponents([.year, .month, .day], from: self)
return year == components.year && month == components.month && day == components.day
}
static func dateOn(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconda: Int) -> Date {
var gregorian = Calendar(identifier: .gregorian)
gregorian.timeZone = TimeZone(secondsFromGMT: 0)!
var components = DateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hours
components.minute = minutes
components.second = seconda
return gregorian.date(from: components)!
}
}
| apache-2.0 | a2623f11bf9418dd28bb51d2a9425ea4 | 36.365854 | 105 | 0.672324 | 4.44058 | false | false | false | false |
MattLewin/Interview-Prep | Data Structures.playground/Pages/LRU Cache - Doubly Linked List.xcplaygroundpage/Contents.swift | 1 | 822 | import Foundation
let cache = LRUCache<Int, String>(capacity: 2)
cache.getValue(for: 1)
cache.setValue("one", for: 1)
cache.setValue("two", for: 2)
cache.setValue("forty-two", for: 42)
cache.getValue(for: 1)
cache.getValue(for: 42)
let cap = 100
var start: Date
var end: Date
var delta: TimeInterval
start = Date()
print("beginning cache allocation at \(start)")
let bigCache = LRUCache<Int, String>(capacity: cap)
end = Date()
delta = end.timeIntervalSince(start)
print("it took \(delta) seconds to allocate the cache")
start = Date()
print("beginning value insertion at \(start)")
for index in 0..<(cap*2) {
bigCache.setValue(String(format: "%00000d", index), for: index)
}
end = Date()
delta = end.timeIntervalSince(start)
print("it took \(delta) seconds to insert \(cap*2) values")
//: ---
//: [Next](@next)
| unlicense | a8f7a6d06695c164fca9f5c4131851f9 | 23.176471 | 67 | 0.69708 | 3.249012 | false | false | false | false |
guoc/excerptor | Excerptor/Helpers/string-helper.swift | 1 | 1555 | //
// string-helper.swift
// excerptor
//
// Created by Chen Guo on 17/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
let URIUnreservedCharacterSet = CharacterSet(charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~")
// swiftlint:enable variable_name
extension String {
func stringByRemovingPrefix(_ prefix: String) -> String {
if let r = prefix.range(of: prefix, options: .anchored, range: nil, locale: nil) {
return String(self[r.upperBound...])
}
return self
}
func stringByReplacingWithDictionary(_ stringGettersByPlaceholder: [String: () -> String]) -> String {
var string = self
for (placeholder, stringGetter) in stringGettersByPlaceholder {
if string.range(of: placeholder, options: [], range: nil, locale: nil) == nil {
continue
} else {
string = string.replacingOccurrences(of: placeholder, with: stringGetter(), options: [], range: nil)
}
}
return string
}
var isDNtpUUID: Bool {
let regex = try! NSRegularExpression(pattern: "^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$", options: [.caseInsensitive]) // swiftlint:disable:this force_try
let range = NSRange(location: 0, length: count)
guard let firstMatch = regex.firstMatch(in: self, options: [.anchored], range: range)?.range else {
return false
}
return NSEqualRanges(firstMatch, range)
}
}
| mit | c92dbd42863f6c731b605bfde55a0e30 | 36.926829 | 199 | 0.625723 | 3.997429 | false | false | false | false |
ruslanskorb/CoreStore | Sources/CoreStoreManagedObject.swift | 1 | 2147 | //
// CoreStoreManagedObject.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - CoreStoreManagedObject
@objc internal class CoreStoreManagedObject: NSManagedObject {
internal typealias CustomGetter = @convention(block) (_ rawObject: Any) -> Any?
internal typealias CustomSetter = @convention(block) (_ rawObject: Any, _ newValue: Any?) -> Void
internal typealias CustomGetterSetter = (getter: CustomGetter?, setter: CustomSetter?)
@nonobjc @inline(__always)
internal static func cs_subclassName(for entity: DynamicEntity, in modelVersion: ModelVersion) -> String {
return "_\(NSStringFromClass(CoreStoreManagedObject.self))__\(modelVersion)__\(NSStringFromClass(entity.type))__\(entity.entityName)"
}
}
// MARK: - Private
private enum Static {
static let queue = DispatchQueue.concurrent("com.coreStore.coreStoreManagerObjectBarrierQueue")
static var cache: [ObjectIdentifier: [KeyPathString: Set<KeyPathString>]] = [:]
}
| mit | a0be4d278e77fa2981b5a93290f7ef34 | 40.269231 | 141 | 0.737651 | 4.60515 | false | false | false | false |
curia007/UserSample | UserSample/UserSample/AppDelegate.swift | 1 | 4784 | //
// AppDelegate.swift
// UserSample
//
// Created by Carmelo Uria on 7/17/17.
// Copyright © 2017 Carmelo Uria. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let locationProcessor: LocationProcessor = LocationProcessor()
let jsonProcessor: JSONProcessor = JSONProcessor()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
locationProcessor.startProcessor()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "UserSample")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| apache-2.0 | da4b345395069a32840d5e1eb116ab31 | 47.806122 | 285 | 0.685762 | 5.840049 | false | false | false | false |
nossipova/SwiftDemo | Expressions.playground/section-1.swift | 1 | 267 | // Expressions
var someVariable = 3
let value1 = someVariable < 10 ? 7 : 14
var value2: Int
switch someVariable {
case 10: value2 = 14
case 15: value2 = 28
default: value2 = 7
}
//
//let value3 = switch someVariable {
//case 10: 14
//case 15: 28
//default: 7
//}
| mit | 91acdb17d59df1f936c88313e3817fcc | 13.052632 | 39 | 0.659176 | 2.870968 | false | false | false | false |
Tulakshana/FileCache | FileCache/Example/FileCache/Users/UserPicVC.swift | 1 | 1408 | //
// UserPicVC.swift
// FileCacheExample
//
// Created by Weerasooriya, Tulakshana on 5/14/17.
// Copyright © 2017 Tulakshana. All rights reserved.
//
import UIKit
import SVProgressHUD
class UserPicVC: UIViewController {
@IBOutlet var imageView: UIImageView!
var imageURL: NSString?
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(didReceiveFileCacheDidDownloadFile(notification:)), name: Notification.Name.init(rawValue: notificationFileCacheDidDownloadFile), object: nil)
self.loadImage()
}
override func viewWillDisappear(_ animated: Bool) {
SVProgressHUD.dismiss()
super.viewWillDisappear(animated)
}
//MARK:-
func loadImage() {
if let url: NSString = imageURL {
SVProgressHUD.show()
FileCache.sharedInstance.fetchFileForURL(urlString: url)
}
}
@objc func didReceiveFileCacheDidDownloadFile(notification: Notification) {
if let cachedFile: FCFile = notification.object as? FCFile {
if cachedFile.urlString == imageURL {
if let data: NSData = cachedFile.fileData {
imageView.image = UIImage.init(data: data as Data)
}
SVProgressHUD.dismiss()
}
}
}
}
| mit | 0372c0801a404996105c0b5bfc109ada | 27.714286 | 215 | 0.626866 | 4.902439 | false | false | false | false |
cuappdev/podcast-ios | Recast/Discover/MainSearchDataSourceDelegate.swift | 1 | 2197 | //
// MainSearchDataSourceDelegate.swift
// Recast
//
// Created by Jack Thompson on 9/26/18.
// Copyright © 2018 Cornell AppDev. All rights reserved.
//
import UIKit
import Kingfisher
class MainSearchDataSourceDelegate: NSObject {
// MARK: - Variables
weak var delegate: SearchTableViewDelegate?
var searchResults: [PartialPodcast] = []
// MARK: - Constants
let cellReuseId = PodcastTableViewCell.cellReuseId
func fetchData(query: String) {
SearchEndpoint(parameters: ["term": query, "media": "podcast", "limit": -1]).run()
.success { response in
self.searchResults = response.results
self.delegate?.refreshController()
}
.failure { error in
print(error)
}
}
func resetResults() {
searchResults = []
}
}
// MARK: - UITableViewDataSource
extension MainSearchDataSourceDelegate: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return searchResults.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// swiftlint:disable:next force_cast
let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseId, for: indexPath) as! PodcastTableViewCell
let podcast = searchResults[indexPath.row]
// Set up cell
let artworkURL = podcast.artworkUrl600 ?? podcast.artworkUrl100 ?? podcast.artworkUrl60 ?? podcast.artworkUrl30
cell.podcastImageView.kf.setImage(with: artworkURL)
cell.podcastNameLabel.text = podcast.collectionName
cell.podcastPublisherLabel.text = podcast.artistName
return cell
}
}
// MARK: - UITableViewDelegate
extension MainSearchDataSourceDelegate: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let partialPodcast = searchResults[indexPath.row]
delegate?.didPress(partialPodcast)
}
}
| mit | 438100b58078f1ef644069dc888ac3af | 30.371429 | 119 | 0.684882 | 5.025172 | false | false | false | false |
Pradeepkn/Mysore_App | MysoreApp/HelperClasses/Image.swift | 1 | 2644 | //
// Image.swift
// Todo
//
// Created by Pasin Suriyentrakorn on 2/15/16.
// Copyright © 2016 Couchbase. All rights reserved.
//
import Foundation
extension UIImage {
func square(size: CGFloat) -> UIImage? {
return square()?.resize(newSize: CGSize(width: size, height: size))
}
func square() -> UIImage? {
let oWidth = CGFloat(self.cgImage!.width)
let oHeight = CGFloat(self.cgImage!.height)
let sqSize = min(oWidth, oHeight)
let x = (oWidth - sqSize) / 2.0
let y = (oHeight - sqSize) / 2.0
let rect = CGRect(x: x, y: y, width: sqSize, height: sqSize)
let sqImage = self.cgImage!.cropping(to: rect)
return UIImage(cgImage: sqImage!, scale: self.scale, orientation: self.imageOrientation)
}
func resize(newSize: CGSize) -> UIImage? {
let oWidth = self.size.width
let oHeight = self.size.height
let wRatio = newSize.width / oWidth
let hRatio = newSize.height / oHeight
var nuSize: CGSize
if(wRatio > hRatio) {
nuSize = CGSize(width: oWidth * hRatio, height: oHeight * hRatio)
} else {
nuSize = CGSize(width: oWidth * wRatio, height: oHeight * wRatio)
}
let rect = CGRect(x: 0, y: 0, width: nuSize.width, height: nuSize.height)
UIGraphicsBeginImageContextWithOptions(nuSize, false, self.scale)
self.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
class Image {
private static let cache = NSCache<AnyObject, AnyObject>()
class func square(image: UIImage?, withSize size: CGFloat, withCacheName name: String?,
onComplete action: ((UIImage?) -> Void)?) -> UIImage? {
if (cache.countLimit != 50) {
cache.countLimit = 50
}
guard let oImage = image else {
return nil
}
if let key = name, !key.isEmpty {
if let cachedImage = cache.object(forKey: key as AnyObject) as? UIImage {
return cachedImage
}
}
DispatchQueue.global().async {
let square = oImage.square(size: size)
DispatchQueue.main.async {
if let key = name, let cachedImage = square, !key.isEmpty {
cache.setObject(cachedImage, forKey: key as AnyObject)
}
if let complete = action {
complete(square)
}
}
}
return nil
}
}
| mit | 1bf9d4a4c453f054b18996209aaa77d4 | 31.231707 | 96 | 0.564132 | 4.28363 | false | false | false | false |
sbooth/SFBAudioEngine | Device/AudioSubdevice.swift | 1 | 6078 | //
// Copyright (c) 2020 - 2022 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
import Foundation
import CoreAudio
/// A HAL audio subdevice
/// - remark: This class correponds to objects with base class `kAudioSubDeviceClassID`
public class AudioSubdevice: AudioDevice {
}
extension AudioSubdevice {
/// Returns the extra latency
/// - remark: This corresponds to the property `kAudioSubDevicePropertyExtraLatency`
public func extraLatency() throws -> Double {
return try getProperty(PropertyAddress(kAudioSubDevicePropertyExtraLatency), type: Double.self)
}
/// Returns the drift compensation
/// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensation`
public func driftCompensation() throws -> Bool {
return try getProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensation), type: UInt32.self) != 0
}
/// Sets the drift compensation
/// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensation`
public func setDriftCompensation(_ value: Bool) throws {
try setProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensation), to: UInt32(value ? 1 : 0))
}
/// Returns the drift compensation quality
/// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensationQuality`
public func driftCompensationQuality() throws -> UInt32 {
return try getProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensationQuality), type: UInt32.self)
}
/// Sets the drift compensation quality
/// - remark: This corresponds to the property `kAudioSubDevicePropertyDriftCompensationQuality`
public func setDriftCompensationQuality(_ value: UInt32) throws {
try setProperty(PropertyAddress(kAudioSubDevicePropertyDriftCompensationQuality), to: value)
}
}
extension AudioSubdevice {
/// A thin wrapper around a HAL audio subdevice drift compensation quality setting
public struct DriftCompensationQuality: RawRepresentable, ExpressibleByIntegerLiteral, ExpressibleByStringLiteral {
/// Minimum quality
public static let min = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMinQuality)
/// Low quality
public static let low = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationLowQuality)
/// Medium quality
public static let medium = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMediumQuality)
/// High quality
public static let high = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationHighQuality)
/// Maximum quality
public static let max = DriftCompensationQuality(rawValue: kAudioSubDeviceDriftCompensationMaxQuality)
public let rawValue: UInt32
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
public init(integerLiteral value: UInt32) {
self.rawValue = value
}
public init(stringLiteral value: StringLiteralType) {
self.rawValue = value.fourCC
}
}
}
extension AudioSubdevice.DriftCompensationQuality: CustomDebugStringConvertible {
// A textual representation of this instance, suitable for debugging.
public var debugDescription: String {
switch self.rawValue {
case kAudioSubDeviceDriftCompensationMinQuality: return "Minimum"
case kAudioSubDeviceDriftCompensationLowQuality: return "Low"
case kAudioSubDeviceDriftCompensationMediumQuality: return "Medium"
case kAudioSubDeviceDriftCompensationHighQuality: return "High"
case kAudioSubDeviceDriftCompensationMaxQuality: return "Maximum"
default: return "\(self.rawValue)"
}
}
}
extension AudioSubdevice {
/// Returns `true` if `self` has `selector` in `scope` on `element`
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
public func hasSelector(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) -> Bool {
return hasProperty(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element))
}
/// Returns `true` if `selector` in `scope` on `element` is settable
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
/// - throws: An error if `self` does not have the requested property
public func isSelectorSettable(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master) throws -> Bool {
return try isPropertySettable(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element))
}
/// Registers `block` to be performed when `selector` in `scope` on `element` changes
/// - parameter selector: The selector of the desired property
/// - parameter scope: The desired scope
/// - parameter element: The desired element
/// - parameter block: A closure to invoke when the property changes or `nil` to remove the previous value
/// - throws: An error if the property listener could not be registered
public func whenSelectorChanges(_ selector: AudioObjectSelector<AudioSubdevice>, inScope scope: PropertyScope = .global, onElement element: PropertyElement = .master, perform block: PropertyChangeNotificationBlock?) throws {
try whenPropertyChanges(PropertyAddress(PropertySelector(selector.rawValue), scope: scope, element: element), perform: block)
}
}
extension AudioObjectSelector where T == AudioSubdevice {
/// The property selector `kAudioSubDevicePropertyExtraLatency`
public static let extraLatency = AudioObjectSelector(kAudioSubDevicePropertyExtraLatency)
/// The property selector `kAudioSubDevicePropertyDriftCompensation`
public static let driftCompensation = AudioObjectSelector(kAudioSubDevicePropertyDriftCompensation)
/// The property selector `kAudioSubDevicePropertyDriftCompensationQuality`
public static let driftCompensationQuality = AudioObjectSelector(kAudioSubDevicePropertyDriftCompensationQuality)
}
| mit | 540df69c5674f2da17b784a01607145d | 47.624 | 225 | 0.789898 | 4.027833 | false | false | false | false |
suifengqjn/swiftDemo | Swift基本语法-黑马笔记/Switch/main.swift | 1 | 4191 | //
// main.swift
// Switch
//
// Created by 李南江 on 15/3/17.
// Copyright (c) 2015年 itcast. All rights reserved.
//
import Foundation
/*
Swith
格式: switch(需要匹配的值) case 匹配的值: 需要执行的语句 break;
OC:
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以穿透
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
default:
NSLog(@"没有评级");
break;
}
可以不写default
char rank = 'A';
switch (rank) {
case 'A':
NSLog(@"优");
break;
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
default位置可以随便放
char rank = 'E';
switch (rank) {
default:
NSLog(@"没有评级");
break;
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
在case中定义变量需要加大括号, 否则作用域混乱
char rank = 'A';
switch (rank) {
case 'A':
{
int score = 100;
NSLog(@"优");
break;
}
case 'B':
NSLog(@"良");
break;
case 'C':
NSLog(@"差");
break;
}
不能判断对象类型
NSNumber *num = @100;
switch (num) {
case @100:
NSLog(@"优");
break;
default:
NSLog(@"没有评级");
break;
}
*/
/*
Swift: 可以判断对象类型, OC必须是整数
*/
//不可以穿透
//可以不写break,
var rank = "A"
switch rank{
case "A": //相当于if
print("优")
case "B": // 相当于else if
print("优")
case "C": // 相当于else if
print("优")
default: // 相当于else
print("没有评级")
}
/*
因为不能穿透所以不能这么写
var rank1 = "A"
switch rank1{
case "A":
case "B":
print("优")
case "C":
print("优")
default:
print("没有评级")
}
*/
//只能这么写
var rank1 = "A"
switch rank1{
case "A", "B": // 注意OC不能这样写
print("优")
case "C":
print("差")
default:
print("没有评级")
}
/*
//不能不写default
var rank2 = "A"
switch rank2{
case "A":
print("优")
case "B":
print("良")
case "C":
print("差")
}
*/
/*
//default位置只能在最后
var rank3 = "A"
switch rank3{
default:
print("没有评级")
case "A":
print("优")
case "B":
print("良")
case "C":
print("差")
}
*/
//在case中定义变量不用加大括号
var rank4 = "A"
switch rank4{
case "A":
var num = 10
print("优")
case "B":
print("良")
case "C":
print("差")
default:
print("没有评级")
}
/*
区间和元祖匹配
var num = 10;
switch num{
case 1...9:
print("个位数")
case 10...99:
print("十位数")
default:
print("其它数")
}
var point = (10, 15)
switch point{
case (0, 0):
print("坐标在原点")
case (1...10, 10...20): // 可以在元祖中再加上区间
print("坐标的X和Y在1~10之间")
case (_, 0): // X可以是任意数
print("坐标的X在X轴上")
default:
print("Other")
}
*/
/*
值绑定
var point = (1, 10)
switch point{
case (var x, 10): // 会将point中X的值赋值给X
print("x= \(x)")
case (var x, var y): // 会将point中XY的值赋值给XY
print("x= \(x) y= \(y)")
case var( x, y):
print("x= \(x) y= \(y)")
default:
print("Other")
}
根据条件绑定
var point = (100, 10)
switch point{
// 只有where后面的条件表达式为真才赋值并执行case后的语句
case var(x, y) where x > y:
print("x= \(x) y= \(y)")
default:
print("Other")
}
*/
| apache-2.0 | 9afeb53116fc4e5b63a68eb1dabd892b | 13.375 | 52 | 0.451052 | 2.896019 | false | false | false | false |
JohnSundell/Marathon | Sources/MarathonCore/Install.swift | 1 | 1738 | /**
* Marathon
* Copyright (c) John Sundell 2017
* Licensed under the MIT license. See LICENSE file.
*/
import Foundation
// MARK: - Error
public enum InstallError {
case missingPath
}
extension InstallError: PrintableError {
public var message: String {
switch self {
case .missingPath:
return "No script path given"
}
}
public var hints: [String] {
switch self {
case .missingPath:
return ["Pass the path to a script file to install (for example 'marathon install script.swift')"]
}
}
}
// MARK: - Task
internal class InstallTask: Task, Executable {
private typealias Error = InstallError
func execute() throws {
guard let path = arguments.first else {
throw Error.missingPath
}
let script = try scriptManager.script(atPath: path, allowRemote: true)
let installPath = makeInstallPath(for: script)
printer.reportProgress("Compiling script...")
try script.build(withArguments: ["-c", "release"])
printer.reportProgress("Installing binary...")
let installed = try script.install(at: installPath, confirmBeforeOverwriting: !arguments.contains("--force"))
guard installed else {
return printer.output("✋ Installation cancelled")
}
printer.output("💻 \(path) installed at \(installPath)")
}
private func makeInstallPath(for script: Script) -> String {
if let argument = arguments.element(at: 1) {
if argument != "--force" && argument != "--verbose" {
return argument
}
}
return "/usr/local/bin/\(script.name.lowercased())"
}
}
| mit | 0e01ef9ae4c21e94089ed4580e99c2db | 25.661538 | 117 | 0.607617 | 4.524804 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.