repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ahoppen/swift | test/stdlib/RangeDiagnostics.swift | 41 | 6931 | //===--- RangeDiagnostics.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-typecheck-verify-swift
import StdlibUnittest
func typeInference_Comparable<C : Comparable>(v: C) {
do {
var range = v..<v
expectType(Range<C>.self, &range)
}
do {
var range = v...v
expectType(ClosedRange<C>.self, &range)
}
do {
var range = v...
expectType(PartialRangeFrom<C>.self, &range)
}
do {
var range = ..<v
expectType(PartialRangeUpTo<C>.self, &range)
}
do {
var range = ...v
expectType(PartialRangeThrough<C>.self, &range)
}
do {
let _: Range<C> = v...v // expected-error {{cannot convert value of type 'ClosedRange<C>' to specified type 'Range<C>'}}
let _: ClosedRange<C> = v..<v // expected-error {{cannot convert value of type 'Range<C>' to specified type 'ClosedRange<C>'}}
}
}
func typeInference_Strideable<S : Strideable>(v: S) {
do {
var range = v..<v
expectType(Range<S>.self, &range)
}
do {
var range = v...v
expectType(ClosedRange<S>.self, &range)
}
do {
let r1: Range<S> = v...v // expected-error {{cannot convert value of type 'ClosedRange<S>' to specified type 'Range<S>'}}
let r2: ClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'Range<S>' to specified type 'ClosedRange<S>'}}
let r3: PartialRangeUpTo<S> = v... // expected-error {{cannot convert value of type 'PartialRangeFrom<S>' to specified type 'PartialRangeUpTo<S>'}}
let r4: PartialRangeUpTo<S> = v... // expected-error {{cannot convert value of type 'PartialRangeFrom<S>' to specified type 'PartialRangeUpTo<S>'}}
let r5: Range<S> = v..< // expected-error {{'..<' is not a postfix unary operator}}
}
}
func typeInference_StrideableWithSignedIntegerStride<S : Strideable>(v: S)
where S.Stride : SignedInteger {
do {
var range = v..<v
expectType(Range<S>.self, &range)
}
do {
var range = v...v
expectType(ClosedRange<S>.self, &range)
}
do {
var range = v...
expectType(PartialRangeFrom<S>.self, &range)
}
do {
let _: Range<S> = v..<v
}
do {
let _: ClosedRange<S> = v...v
}
do {
let _: Range<S> = v...v // expected-error {{cannot convert value of type 'ClosedRange<S>' to specified type 'Range<S>'}}
let _: ClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'Range<S>' to specified type 'ClosedRange<S>'}}
let _: Range<S> = v...v // expected-error {{cannot convert value of type 'ClosedRange<S>' to specified type 'Range<S>'}}
let _: ClosedRange<S> = v..<v // expected-error {{cannot convert value of type 'Range<S>' to specified type 'ClosedRange<S>'}}
let _: ClosedRange<S> = v... // expected-error {{cannot convert value of type 'PartialRangeFrom<S>' to specified type 'ClosedRange<S>'}}
}
}
// Check how type inference works with a few commonly used types.
func typeInference_commonTypes() {
// ---------------------------------------------
// operator '..<'
// ---------------------------------------------
do {
var range = 1..<10
expectType(Range<Int>.self, &range)
}
do {
var range = 1..< // expected-error {{'..<' is not a postfix unary operator}}
}
do {
var range = ..<10
expectType(PartialRangeUpTo<Int>.self, &range)
}
do {
var range = ..<UInt(10)
expectType(PartialRangeUpTo<UInt>.self, &range)
}
do {
var range = UInt(1)..<10
expectType(Range<UInt>.self, &range)
}
do {
var range = Int8(1)..<10
expectType(Range<Int8>.self, &range)
}
do {
var range = UInt8(1)..<10
expectType(Range<UInt8>.self, &range)
}
do {
var range = 1.0..<10.0
expectType(Range<Double>.self, &range)
}
do {
var range = ..<10.0
expectType(PartialRangeUpTo<Double>.self, &range)
}
do {
var range = Float(1.0)..<10.0
expectType(Range<Float>.self, &range)
}
do {
var range = "a"..<"z"
expectType(Range<String>.self, &range)
}
do {
var range = ..<"z"
expectType(PartialRangeUpTo<String>.self, &range)
}
do {
var range = Character("a")..<"z"
expectType(Range<Character>.self, &range)
}
do {
var range = UnicodeScalar("a")..<"z"
expectType(Range<UnicodeScalar>.self, &range)
}
do {
let s = ""
var range = s.startIndex..<s.endIndex
expectType(Range<String.Index>.self, &range)
}
// ---------------------------------------------
// operator '...'
// ---------------------------------------------
do {
var range = 1...10
expectType(ClosedRange<Int>.self, &range)
}
do {
var range = 1...
expectType(PartialRangeFrom<Int>.self, &range)
}
do {
var range = ...10
expectType(PartialRangeThrough<Int>.self, &range)
}
do {
var range = UInt(1)...10
expectType(ClosedRange<UInt>.self, &range)
}
do {
var range = UInt(1)...
expectType(PartialRangeFrom<UInt>.self, &range)
}
do {
var range = ...UInt(10)
expectType(PartialRangeThrough<UInt>.self, &range)
}
do {
var range = Int8(1)...10
expectType(ClosedRange<Int8>.self, &range)
}
do {
var range = UInt8(1)...10
expectType(ClosedRange<UInt8>.self, &range)
}
do {
var range = UInt8(1)...
expectType(PartialRangeFrom<UInt8>.self, &range)
}
do {
var range = 1.0...10.0
expectType(ClosedRange<Double>.self, &range)
}
do {
var range = 1.0...
expectType(PartialRangeFrom<Double>.self, &range)
}
do {
var range = ...10.0
expectType(PartialRangeThrough<Double>.self, &range)
}
do {
var range = Float(1.0)...10.0
expectType(ClosedRange<Float>.self, &range)
}
do {
var range = "a"..."z"
expectType(ClosedRange<String>.self, &range)
}
do {
var range = "a"...
expectType(PartialRangeFrom<String>.self, &range)
}
do {
var range = "a"...
expectType(PartialRangeFrom<String>.self, &range)
}
do {
var range = Character("a")..."z"
expectType(ClosedRange<Character>.self, &range)
}
do {
var range = UnicodeScalar("a")..."z"
expectType(ClosedRange<UnicodeScalar>.self, &range)
}
do {
let s = ""
var range = s.startIndex...s.endIndex
expectType(ClosedRange<String.Index>.self, &range)
}
do {
let s = ""
var range = s.startIndex...
expectType(PartialRangeFrom<String.Index>.self, &range)
}
do {
let s = ""
var range = ...s.endIndex
expectType(PartialRangeThrough<String.Index>.self, &range)
}
}
| apache-2.0 | 15bcabd303eda74f3d4ea8093be98a21 | 27.174797 | 151 | 0.584908 | 3.647895 | false | false | false | false |
dreamsxin/swift | test/attr/attr_discardableResult.swift | 2 | 2771 | // RUN: %target-parse-verify-swift
// ---------------------------------------------------------------------------
// Mark function's return value as discardable and silence warning
// ---------------------------------------------------------------------------
@discardableResult
func f1() -> [Int] { }
func f2() -> [Int] { }
func f3() { }
func f4<R>(blah: () -> R) -> R { return blah() }
func testGlobalFunctions() -> [Int] {
f1() // okay
f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = f2() // okay
f3() // okay
f4 { 5 } // expected-warning {{result of call to 'f4(blah:)' is unused}}
f4 { } // okay
return f2() // okay
}
class C1 {
@discardableResult
static func f1Static() -> Int { }
static func f2Static() -> Int { }
@discardableResult
class func f1Class() -> Int { }
class func f2Class() -> Int { }
@discardableResult init() { }
init(foo: Int) { }
@discardableResult
func f1() -> Int { }
func f2() -> Int { }
}
func testFunctionsInClass(c1 : C1) {
C1.f1Static() // okay
C1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}}
_ = C1.f2Static() // okay
C1.f1Class() // okay
C1.f2Class() // expected-warning {{result of call to 'f2Class()' is unused}}
_ = C1.f2Class() // okay
C1() // okay, marked @discardableResult
_ = C1() // okay
C1(foo: 5) // expected-warning {{result of 'C1' initializer is unused}}
_ = C1(foo: 5) // okay
c1.f1() // okay
c1.f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = c1.f2() // okay
}
struct S1 {
@discardableResult
static func f1Static() -> Int { }
static func f2Static() -> Int { }
@discardableResult init() { }
init(foo: Int) { }
@discardableResult
func f1() -> Int { }
func f2() -> Int { }
}
func testFunctionsInStruct(s1 : S1) {
S1.f1Static() // okay
S1.f2Static() // expected-warning {{result of call to 'f2Static()' is unused}}
_ = S1.f2Static() // okay
S1() // okay, marked @discardableResult
_ = S1() // okay
S1(foo: 5) // expected-warning {{result of 'S1' initializer is unused}}
_ = S1(foo: 5) // okay
s1.f1() // okay
s1.f2() // expected-warning {{result of call to 'f2()' is unused}}
_ = s1.f2() // okay
}
let x = 4
"Hello \(x+1) world" // expected-warning {{expression of type 'String' is unused}}
func f(a : () -> Int) {
42 // expected-warning {{result of call to 'init(_builtinIntegerLiteral:)' is unused}}
4 + 5 // expected-warning {{result of operator '+' is unused}}
a() // expected-warning {{result of call is unused, but produces 'Int'}}
}
| apache-2.0 | aa8d8fb4a718d74d8408d894b4eaa838 | 24.657407 | 89 | 0.522555 | 3.318563 | false | false | false | false |
steelwheels/KiwiComponents | Source/Components/KMConsoleView.swift | 1 | 2898 | /*
* @file KMConsoleView.h
* @brief Define KMStackView class
* @par Copyright
* Copyright (C) 2017 Steel Wheels Project
*/
import KiwiControls
import KiwiEngine
import KSStdLib
import Canary
import JavaScriptCore
import Foundation
public class KMConsoleView: KCConsoleView, KMComponentProtocol
{
public static let ConsoleItem = "console"
public static let VisibleItem = "visible"
private var mInstanceName : String = ""
private var mPropertyTable : KEPropertyTable? = nil
private var mRootComponent : KMComponentProtocol? = nil
private var mNodeTable : CNNodeTable? = nil
private var mConsole : CNReceiverConsole? = nil
public var notations: Array<CNObjectNotation> = []
public var instanceName: String {
get { return mInstanceName }
set(name) { mInstanceName = name }
}
public var propertyTable: KEPropertyTable {
get {
if let table = mPropertyTable {
return table
} else {
fatalError("Not setupped")
}
}
}
public var nodeTable: CNNodeTable? {
get { return mNodeTable }
set(table) { mNodeTable = table }
}
public var rootComponent: KMComponentProtocol {
set(comp){
mRootComponent = comp
}
get {
if let r = mRootComponent {
return r
}
fatalError("Root component is NOT set")
}
}
public var console: CNConsole {
get {
if let cons = mConsole {
return cons
} else {
fatalError("Call after setup")
}
}
}
public func setup(context ctxt: KEContext){
let table = KEPropertyTable(context: ctxt)
mPropertyTable = table
/* Set visible property */
self.isVisible = true
table.set(KMConsoleView.VisibleItem, JSValue(bool: self.isVisible, in: ctxt))
table.addListener(property: KMConsoleView.VisibleItem, listener: {
(_ any: Any) -> Void in
if let val = any as? JSValue {
if val.isBoolean {
self.isVisible = val.toBool()
return ; /* done setting */
}
}
NSLog("Unexpected parameter: \(any)")
})
/* Set console */
let console = CNReceiverConsole()
console.printCallback = {
(_ str: String) -> Void in
let astr = NSAttributedString(string: str)
CNExecuteInMainThread(doSync: false, execute: {
() -> Void in
self.appendText(string: astr)
})
}
console.errorCallback = {
(_ str: String) -> Void in
let astr = NSAttributedString(string: str)
CNExecuteInMainThread(doSync: false, execute: {
() -> Void in
self.appendText(string: astr)
})
}
console.scanCallback = nil
table.set(KMConsoleView.ConsoleItem, JSValue(object: KSConsole(console: console, context: ctxt), in: ctxt))
mConsole = console
}
public func accessType(propertyName name: String) -> CNAccessType?
{
var result: CNAccessType?
switch name {
case KMConsoleView.VisibleItem:
result = .ReadWriteAccess
case KMConsoleView.ConsoleItem:
result = .ReadOnlyAccess
default:
result = nil
}
return result
}
}
| lgpl-2.1 | 76c4dd4e15f14361b8d8687f245d6874 | 22.184 | 109 | 0.685645 | 3.458234 | false | false | false | false |
Ricky-Choi/AppUIKit | AppUIKit/Navigation/AUIBar.swift | 1 | 2115 | //
// AUIBar.swift
// AppUIKit
//
// Created by Jae Young Choi on 2017. 1. 30..
// Copyright © 2017년 appcid. All rights reserved.
//
import Cocoa
open class AUIBar: AUIView {
let contentView = AUIView()
open var barTintColor: NSColor? {
didSet {
invalidateBackground()
}
}
open var barStyle: AUIBarStyle = .default {
didSet {
invalidateBackground()
}
}
var backgroundEffectColor: VibrantColor {
if let barTintColor = barTintColor {
return VibrantColor.color(barTintColor.darkenColor)
} else if barStyle == .black {
return VibrantColor.vibrantDark
} else {
return VibrantColor.vibrantLight
}
}
func invalidateBackground() {
removeVisualEffectView()
switch backgroundEffectColor {
case .color(let color):
backgroundColor = color
case .vibrantLight:
backgroundColor = NSColor.white.withAlphaComponent(0.75)
let visualEffectView = NSVisualEffectView()
visualEffectView.appearance = NSAppearance(named: NSAppearance.Name.vibrantLight)
visualEffectView.blendingMode = .withinWindow
addSubview(visualEffectView, positioned: .below, relativeTo: contentView)
visualEffectView.fillToSuperview()
case .vibrantDark:
backgroundColor = NSColor.clear
let visualEffectView = NSVisualEffectView()
visualEffectView.appearance = NSAppearance(named: NSAppearance.Name.vibrantDark)
visualEffectView.blendingMode = .withinWindow
visualEffectView.material = .ultraDark
addSubview(visualEffectView, positioned: .below, relativeTo: contentView)
visualEffectView.fillToSuperview()
}
}
func removeVisualEffectView() {
for subview in subviews {
if let vev = subview as? NSVisualEffectView {
vev.removeFromSuperview()
}
}
}
}
| mit | e63704c35b1e081fc6ffbd38329ea03e | 29.171429 | 93 | 0.60464 | 5.543307 | false | false | false | false |
RocketChat/Rocket.Chat.iOS | Rocket.Chat/Managers/ServerManager.swift | 1 | 2239 | //
// ServerManager.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 27/07/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
struct ServerManager {
static var shared = ServerManager()
var timestampOffset = 0.0
/**
This method will get the selected database information
locally and update a few settings that are important to
keep save locally even when database doesn't exist.
- parameter settings: The AuthSettings instance that
have information required.
*/
static func updateServerInformation(from settings: AuthSettings) {
let defaults = UserDefaults.group
let selectedIndex = DatabaseManager.selectedIndex
guard
let serverName = settings.serverName,
let iconURL = settings.serverFaviconURL,
var servers = DatabaseManager.servers,
servers.count > selectedIndex
else {
return
}
servers[selectedIndex][ServerPersistKeys.serverName] = serverName
servers[selectedIndex][ServerPersistKeys.serverIconURL] = iconURL
defaults.set(servers, forKey: ServerPersistKeys.servers)
}
/**
This method is suppose to be executed only once per server
connection. It gets the server timestamp and syncs to the
timestamp of the user that's using the app.
*/
static func timestampSync() {
guard
let auth = AuthManager.isAuthenticated(),
let serverURL = URL(string: auth.serverURL),
let url = serverURL.timestampURL()
else {
return
}
let request = URLRequest(url: url)
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, _, _) in
if let data = data {
if let timestamp = String(data: data, encoding: .utf8) {
if let timestampDouble = Double(timestamp) {
ServerManager.shared.timestampOffset = Date().timeIntervalSince1970 * 1000 - timestampDouble
}
}
}
})
task.resume()
}
}
| mit | fae3638eb0c9233eed0c9dba4698fb35 | 29.657534 | 116 | 0.60992 | 5.278302 | false | false | false | false |
aulas-lab/ads-mobile | swift/Aula2/Calculadora.swift | 1 | 877 | //
// Calculadora.swift
// Aula2
//
// Created by Mobitec on 14/04/16.
// Copyright (c) 2016 Unopar. All rights reserved.
//
import Foundation
class Calculadora {
var valor: Float
init() {
valor = 0
}
func executa(valor: Float, op: EOperacao) -> Float {
switch op {
case EOperacao.Adicao:
self.valor += valor
break
case EOperacao.Divisao:
self.valor /= valor
break
case EOperacao.Multiplicacao:
self.valor *= valor
break
case EOperacao.Subtracao:
self.valor -= valor
break
}
return self.valor
}
func reinicia() -> Void {
valor = 0
}
}
enum EOperacao: Int {
case Adicao = 1
case Subtracao = 2
case Divisao = 3
case Multiplicacao = 4
}
| mit | 594a5b36ddd125afe97f44c6408e658c | 17.659574 | 56 | 0.516534 | 4.022936 | false | false | false | false |
kevinhankens/runalysis | Runalysis/RouteViewController.swift | 1 | 14395 | //
// RouteViewController.swift
// Runalysis
//
// Created by Kevin Hankens on 8/18/14.
// Copyright (c) 2014 Kevin Hankens. All rights reserved.
//
import Foundation
import UIKit
/*!
* The "route" view controller is our method for displaying the results of
* an event. We can use this to scroll through routes and view details via
* RootView objects. In retrospect, "route view" is a terrible name.
*/
class RouteViewController: UIViewController, UIAlertViewDelegate {
// The id of this route, which is a timestamp.
var routeId: NSNumber = 0
// Tracks the RouteStore object.
var routeStore: RouteStore?
// Tracks the RouteSummary object.
var routeSummary: RouteSummary?
// The currently viewed route.
var routeView: RouteView?
// Tracks the RouteAnalysisView object.
var routeAnalysisView: RouteAnalysisView?
// Tracks the label with the current date.
var dateLabel: UILabel?
// Tracks the label with the current distance.
var distLabel: UILabel?
// Tracks a label that denotes a loading route.
var loadingLabel: UILabel?
// Tracks the container for scrolling/zooming.
var scrollContainer: UIScrollView?
// The height of the content to scroll.
var scrollContentHeight = CGFloat(0)
// Tracks the height of the RouteAnalysisView.
var ravHeight = CGFloat(0)
// Tracks that a delete action was triggered.
var deleteTriggered = false
// Tracks the timer that controls the route drawing.
var drawTimer: NSTimer = NSTimer()
// Tracks which step the drawing animation is on.
var drawStep: Int = 0
// Tracks how many steps are in the drawing animation.
var drawSteps: Int = 0
/*!
* Overrides UIViewController::viewDidLoad()
*/
override func viewDidLoad() {
super.viewDidLoad()
let container = UIScrollView(frame: CGRectMake(0, 20, self.view.bounds.width, self.view.bounds.height - 20))
container.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight
self.view.backgroundColor = GlobalTheme.getBackgroundColor()
var ypos = CGFloat(50)
self.routeSummary = RouteSummary.createRouteSummary(self.routeId, routeStore: self.routeStore!)
let routeView = RouteView.createRouteView(0, y: ypos, width: self.view.bounds.width - 5, height: self.view.bounds.width - 5, routeId: self.routeId, routeStore: self.routeStore!, routeSummary: self.routeSummary!)
routeView.autoresizingMask = UIViewAutoresizing.FlexibleWidth
routeView.contentMode = UIViewContentMode.ScaleAspectFill
// Add swipe gestures to change the route.
let routeSwipeLeft = UISwipeGestureRecognizer(target: self, action: "routeSwipeGesture:")
routeSwipeLeft.direction = UISwipeGestureRecognizerDirection.Left
container.addGestureRecognizer(routeSwipeLeft)
let routeSwipeRight = UISwipeGestureRecognizer(target: self, action: "routeSwipeGesture:")
routeSwipeRight.direction = UISwipeGestureRecognizerDirection.Right
container.addGestureRecognizer(routeSwipeRight)
let press = UILongPressGestureRecognizer(target: self, action: "routeDeleteGesture:")
container.addGestureRecognizer(press)
// Scrolling
//container.minimumZoomScale = 1.0
//container.maximumZoomScale = 3.0
//container.contentSize = CGSizeMake(self.view.bounds.width, self.view.bounds.height)
//container.delegate = self
self.drawRoute()
self.routeView = routeView
container.addSubview(routeView)
// Add left/right arrows.
let leftArrowLabel = UILabel(frame: CGRect(x: 10, y: ypos + routeView.frame.minY + 10, width: 20, height: 35))
leftArrowLabel.text = "<"
leftArrowLabel.font = UIFont.systemFontOfSize(30)
leftArrowLabel.textColor = GlobalTheme.getBackButtonTextColor()
leftArrowLabel.textAlignment = NSTextAlignment.Left
container.addSubview(leftArrowLabel)
let rightArrowLabel = UILabel(frame: CGRect(x: container.frame.maxX - 30, y: ypos + routeView.frame.minY + 10, width: 20, height: 35))
rightArrowLabel.text = ">"
rightArrowLabel.font = UIFont.systemFontOfSize(30)
rightArrowLabel.textColor = GlobalTheme.getBackButtonTextColor()
rightArrowLabel.textAlignment = NSTextAlignment.Left
rightArrowLabel.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin
container.addSubview(rightArrowLabel)
//let loadingLabel = UILabel(frame: CGRect(x: container.frame.width/2 - 150, y: ypos + routeView.frame.minY + 10, width: 300, height: 35))
//loadingLabel.text = "Loading"
//loadingLabel.font = UIFont.systemFontOfSize(30)
//loadingLabel.textColor = GlobalTheme.getBackButtonTextColor()
//loadingLabel.textAlignment = NSTextAlignment.Center
//self.loadingLabel = loadingLabel
//container.addSubview(loadingLabel)
ypos = ypos + routeView.frame.height + 10
// @todo what is the height of this view?
let rav = RouteAnalysisView.createRouteAnalysisView(80.0, cellWidth: self.view.bounds.width, x: 0, y: ypos, routeSummary: self.routeSummary!)
rav.autoresizingMask = UIViewAutoresizing.FlexibleWidth
container.addSubview(rav)
self.routeAnalysisView = rav
self.ravHeight = rav.frame.height + 10
self.scrollContentHeight = ypos + 20 // + CGFloat(rav.frame.height)
self.scrollContainer = container
self.view.addSubview(container)
// Add a back button to return to the "root" view.
let backButton = UIButton()
backButton.frame = CGRectMake(10, 30, self.view.bounds.width/2, 20.00)
backButton.setTitle("< Back", forState: UIControlState.Normal)
backButton.titleLabel?.sizeToFit()
backButton.titleLabel?.font = UIFont.systemFontOfSize(30.0)
backButton.titleLabel?.textAlignment = NSTextAlignment.Left
backButton.setTitleColor(GlobalTheme.getBackButtonTextColor(), forState: UIControlState.Normal)
backButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
backButton.backgroundColor = GlobalTheme.getBackButtonBgColor()
backButton.addTarget(self, action: "returnToRootViewButton:", forControlEvents: UIControlEvents.TouchDown)
backButton.sizeToFit()
self.view.addSubview(backButton)
}
/*!
* Prepare the RouteView and RouteAnalysis for the change in size
* before the rotation occurs.
*/
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
if let rv = self.routeView {
if let rav = self.routeAnalysisView {
rv.frame = CGRectMake(0.0, 0.0, self.view.bounds.width, self.view.bounds.height)
rav.frame = CGRectMake(0.0, self.routeView!.bounds.height, self.view.bounds.width, self.ravHeight)
}
}
}
/*!
* After the rotation occurs, we need to redraw and reset the scroll
* container frame.
*/
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
if let rv = self.routeView {
if let sc = self.scrollContainer {
sc.frame = CGRectMake(0.0, 0.0, self.view.frame.width, self.view.frame.height)
self.scrollContentHeight = rv.frame.maxY + 10
self.resetContentHeight()
self.routeView!.displayLatest()
}
}
}
/*!
* Draws the route in the currently loaded summary.
*/
func drawRoute() {
if let points = self.routeSummary?.points {
self.drawSteps = points.count/50
if self.drawSteps < 1 {
self.drawSteps = 1
}
self.drawStep = 0
self.drawTimer = NSTimer.scheduledTimerWithTimeInterval(0.025, target: self, selector: Selector("drawRouteAnimated"), userInfo: nil, repeats: true)
}
}
/*!
* NSTimer callback to draw the route a bit at a time.
*/
func drawRouteAnimated() {
self.drawStep++
self.routeSummary!.animation_length = self.drawStep * self.drawSteps
self.routeView?.setNeedsDisplay()
if self.routeSummary!.animation_length > self.routeSummary!.points!.count {
self.drawTimer.invalidate()
//self.loadingLabel?.text = ""
}
}
/*!
* Implements UIViewController::viewWillAppear:animated
*/
override func viewWillAppear(animated: Bool) {
self.resetContentHeight()
}
// Sets the height of the scrollview container based on the contents.
func resetContentHeight() {
if let container = self.scrollContainer {
container.contentSize = CGSizeMake(self.routeView!.frame.width, self.scrollContentHeight + self.ravHeight + 30)
}
}
/*!
* UIScrollViewDelegate
*/
func viewForZoomingInScrollView(scrollView: UIScrollView!)->UIView! {
return self.routeView
}
/*!
* UIScrollViewDelegate
*/
func scrollViewDidEndZooming(scrollView: UIScrollView!, withView view: UIView!, atScale scale: CGFloat) {
if let rv = self.routeView {
//let newRect = CGRectMake(rv.bounds.minX, rv.bounds.minY, rv.bounds.width, rv.bounds.height)
//rv.setNeedsDisplayInRect(newRect)
//rv.contentScaleFactor = scale
}
// @todo can we redraw at scale?
//self.routeView!.setNeedsDisplay()
}
/**
* Catch a gesture to delete the current route.
*
* @param UILongPressGestureRecognizer gesture
*
* @return void
*/
func routeDeleteGesture(gesture: UILongPressGestureRecognizer) {
if self.routeId == 0 {
return
}
// Long presses can trigger multiple calls.
if (gesture.state == UIGestureRecognizerState.Began) {
self.deleteTriggered = false
}
if !self.deleteTriggered {
self.deleteTriggered = true
let alert = UIAlertView(title: "Delete Route?", message: "You are about to permanently delete this route.", delegate: nil, cancelButtonTitle: "Cancel")
alert.addButtonWithTitle("Delete")
alert.delegate = self
alert.show()
}
}
/**
* UIAlertViewDelegate::alertView(clickedButtonAtIndex: buttonIndex)
*/
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
self.routeStore?.deleteRoute(self.routeId)
self.displayNextRoute(false, force: true)
}
}
/*!
* Handles the swipe gestures on a RouteView.
*
* @param UIGestureRecognizer gesture
*/
func routeSwipeGesture(gesture: UIGestureRecognizer) {
if let g = gesture as? UISwipeGestureRecognizer {
var previous = false
var id = self.routeId
switch g.direction {
case UISwipeGestureRecognizerDirection.Left:
// Left swipes show newer routes.
previous = false
break;
case UISwipeGestureRecognizerDirection.Right:
// Right swipes show older routes.
previous = true
break;
default:
break;
}
//self.loadingLabel?.text = "Loading"
self.displayNextRoute(previous)
}
}
/*!
* Displays the next or previous route.
*
* @param Bool previous
* @param Bool force
*/
func displayNextRoute(previous: Bool, force: Bool = false) {
// Update the ID of the route
let next = self.routeStore!.getNextRouteId(self.routeId, prev: previous)
if let r = next {
if let rv = self.routeView {
if let rav = self.routeAnalysisView {
self.routeId = r
self.routeSummary?.updateRoute(self.routeId)
// @todo set the route id in the summary here.
rv.updateRoute()
rav.updateLabels()
self.ravHeight = rav.frame.height
rav.updateDuration(self.routeSummary!.duration)
self.resetContentHeight()
self.drawRoute()
}
}
}
else {
// If there is no "next" try the other direction. If there is
// nothing, return to the root view.
// @todo make this circular, only return if there are no routes.
let next = self.routeStore!.getNextRouteId(self.routeId, prev: !previous)
if let r = next {
if force {
self.displayNextRoute(!previous, force: force)
}
}
else if force {
self.returnToRootView()
}
}
}
/*!
* Handles the button press to return to the root view.
*/
func returnToRootViewButton(sender: UIButton) {
self.returnToRootView()
}
/*!
* Dismisses this view controller to return to the root view.
*/
func returnToRootView() {
self.dismissViewControllerAnimated(true, completion: nil)
}
/*!
*
*/
override func shouldAutorotate()->Bool {
return true
}
/*!
*
*/
override func supportedInterfaceOrientations()->Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue) |
Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue) |
Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)
}
/*!
*
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | eb1010c328374eec5dee93b97cdb2ba3 | 35.443038 | 219 | 0.623133 | 5.148426 | false | false | false | false |
habr/ChatTaskAPI | IQKeyboardManager/IQKeyboardManagerSwift/IQKeyboardManager.swift | 1 | 91598 | //
// IQKeyboardManager.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 Iftekhar Qurashi.
//
// 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 CoreGraphics
import UIKit
///---------------------
/// MARK: IQToolbar tags
///---------------------
/**
Codeless drop-in universal library allows to prevent issues of keyboard sliding up and cover UITextField/UITextView. Neither need to write any code nor any setup required and much more. A generic version of KeyboardManagement. https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html
*/
public class IQKeyboardManager: NSObject, UIGestureRecognizerDelegate {
/**
Default tag for toolbar with Done button -1002.
*/
private static let kIQDoneButtonToolbarTag = -1002
/**
Default tag for toolbar with Previous/Next buttons -1005.
*/
private static let kIQPreviousNextButtonToolbarTag = -1005
///---------------------------
/// MARK: UIKeyboard handling
///---------------------------
/**
Enable/disable managing distance between keyboard and textField. Default is YES(Enabled when class loads in `+(void)load` method).
*/
public var enable = false {
didSet {
//If not enable, enable it.
if enable == true && oldValue == false {
//If keyboard is currently showing. Sending a fake notification for keyboardWillShow to adjust view according to keyboard.
if _kbShowNotification != nil {
keyboardWillShow(_kbShowNotification)
}
_IQShowLog("enabled")
} else if enable == false && oldValue == true { //If not disable, desable it.
keyboardWillHide(nil)
_IQShowLog("disabled")
}
}
}
/**
To set keyboard distance from textField. can't be less than zero. Default is 10.0.
*/
public var keyboardDistanceFromTextField: CGFloat {
set {
_privateKeyboardDistanceFromTextField = max(0, newValue)
_IQShowLog("keyboardDistanceFromTextField: \(_privateKeyboardDistanceFromTextField)")
}
get {
return _privateKeyboardDistanceFromTextField
}
}
/**
Prevent keyboard manager to slide up the rootView to more than keyboard height. Default is YES.
*/
public var preventShowingBottomBlankSpace = true
/**
Returns the default singleton instance.
*/
public class func sharedManager() -> IQKeyboardManager {
struct Static {
//Singleton instance. Initializing keyboard manger.
static let kbManager = IQKeyboardManager()
}
/** @return Returns the default singleton instance. */
return Static.kbManager
}
///-------------------------
/// MARK: IQToolbar handling
///-------------------------
/**
Automatic add the IQToolbar functionality. Default is YES.
*/
public var enableAutoToolbar = true {
didSet {
enableAutoToolbar ?addToolbarIfRequired():removeToolbarIfRequired()
let enableToolbar = enableAutoToolbar ? "Yes" : "NO"
_IQShowLog("enableAutoToolbar: \(enableToolbar)")
}
}
/**
AutoToolbar managing behaviour. Default is IQAutoToolbarBySubviews.
*/
public var toolbarManageBehaviour = IQAutoToolbarManageBehaviour.BySubviews
/**
If YES, then uses textField's tintColor property for IQToolbar, otherwise tint color is black. Default is NO.
*/
public var shouldToolbarUsesTextFieldTintColor = false
/**
This is used for toolbar.tintColor when textfield.keyboardAppearance is UIKeyboardAppearanceDefault. If shouldToolbarUsesTextFieldTintColor is YES then this property is ignored. Default is nil and uses black color.
*/
public var toolbarTintColor : UIColor?
/**
Toolbar done button icon, If nothing is provided then check toolbarDoneBarButtonItemText to draw done button.
*/
public var toolbarDoneBarButtonItemImage : UIImage?
/**
Toolbar done button text, If nothing is provided then system default 'UIBarButtonSystemItemDone' will be used.
*/
public var toolbarDoneBarButtonItemText : String?
/**
If YES, then it add the textField's placeholder text on IQToolbar. Default is YES.
*/
public var shouldShowTextFieldPlaceholder = true
/**
Placeholder Font. Default is nil.
*/
public var placeholderFont: UIFont?
///--------------------------
/// MARK: UITextView handling
///--------------------------
/**
Adjust textView's frame when it is too big in height. Default is NO.
*/
public var canAdjustTextView = false
/**
Adjust textView's contentInset to fix a bug. for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string Default is YES.
*/
public var shouldFixTextViewClip = true
///---------------------------------------
/// MARK: UIKeyboard appearance overriding
///---------------------------------------
/**
Override the keyboardAppearance for all textField/textView. Default is NO.
*/
public var overrideKeyboardAppearance = false
/**
If overrideKeyboardAppearance is YES, then all the textField keyboardAppearance is set using this property.
*/
public var keyboardAppearance = UIKeyboardAppearance.Default
///-----------------------------------------------------------
/// MARK: UITextField/UITextView Next/Previous/Resign handling
///-----------------------------------------------------------
/**
Resigns Keyboard on touching outside of UITextField/View. Default is NO.
*/
public var shouldResignOnTouchOutside = false {
didSet {
_tapGesture.enabled = shouldResignOnTouchOutside
let shouldResign = shouldResignOnTouchOutside ? "Yes" : "NO"
_IQShowLog("shouldResignOnTouchOutside: \(shouldResign)")
}
}
/**
Resigns currently first responder field.
*/
public func resignFirstResponder()-> Bool {
if let textFieldRetain = _textFieldView {
//Resigning first responder
let isResignFirstResponder = textFieldRetain.resignFirstResponder()
// If it refuses then becoming it as first responder again. (Bug ID: #96)
if isResignFirstResponder == false {
//If it refuses to resign then becoming it first responder again for getting notifications callback.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to resign first responder: \(_textFieldView?._IQDescription())")
}
return isResignFirstResponder
}
return false
}
/**
Returns YES if can navigate to previous responder textField/textView, otherwise NO.
*/
public var canGoPrevious: Bool {
get {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.indexOf(textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index > 0 {
return true
}
}
}
}
return false
}
}
/**
Returns YES if can navigate to next responder textField/textView, otherwise NO.
*/
public var canGoNext: Bool {
get {
//Getting all responder view's.
if let textFields = responderViews() {
if let textFieldRetain = _textFieldView {
//Getting index of current textField.
if let index = textFields.indexOf(textFieldRetain) {
//If it is not first textField. then it's previous object canBecomeFirstResponder.
if index < textFields.count-1 {
return true
}
}
}
}
return false
}
}
/**
Navigate to previous responder textField/textView.
*/
public func goPrevious()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.indexOf(textFieldRetain) {
//If it is not first textField. then it's previous object becomeFirstResponder.
if index > 0 {
let nextTextField = textFields[index-1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/**
Navigate to next responder textField/textView.
*/
public func goNext()-> Bool {
//Getting all responder view's.
if let textFieldRetain = _textFieldView {
if let textFields = responderViews() {
//Getting index of current textField.
if let index = textFields.indexOf(textFieldRetain) {
//If it is not last textField. then it's next object becomeFirstResponder.
if index < textFields.count-1 {
let nextTextField = textFields[index+1]
let isAcceptAsFirstResponder = nextTextField.becomeFirstResponder()
// If it refuses then becoming previous textFieldView as first responder again. (Bug ID: #96)
if isAcceptAsFirstResponder == false {
//If next field refuses to become first responder then restoring old textField as first responder.
textFieldRetain.becomeFirstResponder()
_IQShowLog("Refuses to become first responder: \(nextTextField._IQDescription())")
}
return isAcceptAsFirstResponder
}
}
}
}
return false
}
/** previousAction. */
internal func previousAction (barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
if canGoPrevious == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goPrevious()
if isAcceptAsFirstResponder && textFieldRetain.previousInvocation.target != nil && textFieldRetain.previousInvocation.selector != nil {
UIApplication.sharedApplication().sendAction(textFieldRetain.previousInvocation.selector!, to: textFieldRetain.previousInvocation.target, from: textFieldRetain, forEvent: UIEvent())
}
}
}
}
/** nextAction. */
internal func nextAction (barButton : UIBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
if canGoNext == true {
if let textFieldRetain = _textFieldView {
let isAcceptAsFirstResponder = goNext()
if isAcceptAsFirstResponder && textFieldRetain.nextInvocation.target != nil && textFieldRetain.nextInvocation.selector != nil {
UIApplication.sharedApplication().sendAction(textFieldRetain.nextInvocation.selector!, to: textFieldRetain.nextInvocation.target, from: textFieldRetain, forEvent: UIEvent())
}
}
}
}
/** doneAction. Resigning current textField. */
internal func doneAction (barButton : IQBarButtonItem?) {
//If user wants to play input Click sound.
if shouldPlayInputClicks == true {
//Play Input Click Sound.
UIDevice.currentDevice().playInputClick()
}
if let textFieldRetain = _textFieldView {
//Resign textFieldView.
let isResignedFirstResponder = resignFirstResponder()
if isResignedFirstResponder && textFieldRetain.doneInvocation.target != nil && textFieldRetain.doneInvocation.selector != nil{
UIApplication.sharedApplication().sendAction(textFieldRetain.doneInvocation.selector!, to: textFieldRetain.doneInvocation.target, from: textFieldRetain, forEvent: UIEvent())
}
}
}
/** Resigning on tap gesture. (Enhancement ID: #14)*/
internal func tapRecognized(gesture: UITapGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.Ended {
//Resigning currently responder textField.
resignFirstResponder()
}
}
/** Note: returning YES is guaranteed to allow simultaneous recognition. returning NO is not guaranteed to prevent simultaneous recognition, as the other gesture's delegate may return YES. */
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
/** To not detect touch events in a subclass of UIControl, these may have added their own selector for specific work */
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
// Should not recognize gesture if the clicked view is either UIControl or UINavigationBar(<Back button etc...) (Bug ID: #145)
return (touch.view is UIControl || touch.view is UINavigationBar) ? false : true
}
///-----------------------
/// MARK: UISound handling
///-----------------------
/**
If YES, then it plays inputClick sound on next/previous/done click.
*/
public var shouldPlayInputClicks = false
///---------------------------
/// MARK: UIAnimation handling
///---------------------------
/**
If YES, then uses keyboard default animation curve style to move view, otherwise uses UIViewAnimationOptionCurveEaseInOut animation style. Default is YES.
@warning Sometimes strange animations may be produced if uses default curve style animation in iOS 7 and changing the textFields very frequently.
*/
public var shouldAdoptDefaultKeyboardAnimation = true
/**
If YES, then calls 'setNeedsLayout' and 'layoutIfNeeded' on any frame update of to viewController's view.
*/
public var layoutIfNeededOnUpdate = false
///------------------------------------
/// MARK: Class Level disabling methods
///------------------------------------
/**
Disable adjusting view in disabledClass
@param disabledClass Class in which library should not adjust view to show textField.
*/
public func disableDistanceHandlingInViewControllerClass(disabledClass : AnyClass) {
_disabledClasses.insert(NSStringFromClass(disabledClass))
}
/**
Re-enable adjusting textField in disabledClass
@param disabledClass Class in which library should re-enable adjust view to show textField.
*/
public func removeDisableDistanceHandlingInViewControllerClass(disabledClass : AnyClass) {
_disabledClasses.remove(NSStringFromClass(disabledClass))
}
/**
Returns All disabled classes registered with disableInViewControllerClass.
*/
public func disabledInViewControllerClassesString() -> Set<String> {
return _disabledClasses
}
/**
Disable automatic toolbar creation in in toolbarDisabledClass
@param toolbarDisabledClass Class in which library should not add toolbar over textField.
*/
public func disableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) {
_disabledToolbarClasses.insert(NSStringFromClass(toolbarDisabledClass))
}
/**
Re-enable automatic toolbar creation in in toolbarDisabledClass
@param toolbarDisabledClass Class in which library should re-enable automatic toolbar creation over textField.
*/
public func removeDisableToolbarInViewControllerClass(toolbarDisabledClass : AnyClass) {
_disabledToolbarClasses.remove(NSStringFromClass(toolbarDisabledClass))
}
/**
Returns YES if toolbar is disabled in ViewController class, otherwise returns NO.
@param toolbarDisabledClass Class which is to check for toolbar disability.
*/
public func disabledToolbarInViewControllerClassesString() -> Set<String> {
return _disabledToolbarClasses
}
/**
Consider provided customView class as superView of all inner textField for calculating next/previous button logic.
@param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should consider all inner textField as siblings and add next/previous accordingly.
*/
public func considerToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) {
_toolbarPreviousNextConsideredClass.insert(NSStringFromClass(toolbarPreviousNextConsideredClass))
}
/**
Remove Consideration for provided customView class as superView of all inner textField for calculating next/previous button logic.
@param toolbarPreviousNextConsideredClass Custom UIView subclass Class in which library should remove consideration for all inner textField as superView.
*/
public func removeConsiderToolbarPreviousNextInViewClass(toolbarPreviousNextConsideredClass : AnyClass) {
_toolbarPreviousNextConsideredClass.remove(NSStringFromClass(toolbarPreviousNextConsideredClass))
}
/**
Returns YES if inner hierarchy is considered for previous/next in class, otherwise returns NO.
@param toolbarPreviousNextConsideredClass Class which is to check for previous next consideration
*/
public func consideredToolbarPreviousNextViewClassesString() -> Set<String> {
return _toolbarPreviousNextConsideredClass
}
/**************************************************************************************/
///------------------------
/// MARK: Private variables
///------------------------
/*******************************************/
/** To save UITextField/UITextView object voa textField/textView notifications. */
private weak var _textFieldView: UIView?
/** used with canAdjustTextView boolean. */
private var _textFieldViewIntialFrame = CGRectZero
/** To save rootViewController.view.frame. */
private var _topViewBeginRect = CGRectZero
/** To save rootViewController */
private weak var _rootViewController: UIViewController?
/** To save topBottomLayoutConstraint original constant */
private var _layoutGuideConstraintInitialConstant: CGFloat = 0.25
/*******************************************/
/** Variable to save lastScrollView that was scrolled. */
private weak var _lastScrollView: UIScrollView?
/** LastScrollView's initial contentOffset. */
private var _startingContentOffset = CGPointZero
/** LastScrollView's initial scrollIndicatorInsets. */
private var _startingScrollIndicatorInsets = UIEdgeInsetsZero
/** LastScrollView's initial contentInsets. */
private var _startingContentInsets = UIEdgeInsetsZero
/*******************************************/
/** To save keyboardWillShowNotification. Needed for enable keyboard functionality. */
private var _kbShowNotification: NSNotification?
/** To save keyboard size. */
private var _kbSize = CGSizeZero
/** To save keyboard animation duration. */
private var _animationDuration = 0.25
/** To mimic the keyboard animation */
private var _animationCurve = UIViewAnimationOptions.CurveEaseOut
/*******************************************/
/** TapGesture to resign keyboard on view's touch. */
private var _tapGesture: UITapGestureRecognizer!
/*******************************************/
/** Set of restricted classes for library */
private var _disabledClasses = Set<String>()
/** Set of restricted classes for adding toolbar */
private var _disabledToolbarClasses = Set<String>()
/** Set of permitted classes to add all inner textField as siblings */
private var _toolbarPreviousNextConsideredClass = Set<String>()
/*******************************************/
private struct flags {
/** used with canAdjustTextView to detect a textFieldView frame is changes or not. (Bug ID: #92)*/
var isTextFieldViewFrameChanged = false
/** Boolean to maintain keyboard is showing or it is hide. To solve rootViewController.view.frame calculations. */
var isKeyboardShowing = false
}
/** Private flags to use within the project */
private var _keyboardManagerFlags = flags(isTextFieldViewFrameChanged: false, isKeyboardShowing: false)
/** To use with keyboardDistanceFromTextField. */
private var _privateKeyboardDistanceFromTextField: CGFloat = 10.0
/**************************************************************************************/
///--------------------------------------
/// MARK: Initialization/Deinitialization
///--------------------------------------
/* Singleton Object Initialization. */
override init() {
super.init()
// Registering for keyboard notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidHide:", name: UIKeyboardDidHideNotification, object: nil)
// Registering for textField notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextFieldTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextFieldTextDidEndEditingNotification, object: nil)
// Registering for textView notification.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidBeginEditing:", name: UITextViewTextDidBeginEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidEndEditing:", name: UITextViewTextDidEndEditingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "textFieldViewDidChange:", name: UITextViewTextDidChangeNotification, object: nil)
// Registering for orientation changes notification
NSNotificationCenter.defaultCenter().addObserver(self, selector: "willChangeStatusBarOrientation:", name: UIApplicationWillChangeStatusBarOrientationNotification, object: nil)
//Creating gesture for @shouldResignOnTouchOutside. (Enhancement ID: #14)
_tapGesture = UITapGestureRecognizer(target: self, action: "tapRecognized:")
_tapGesture.cancelsTouchesInView = false
_tapGesture.delegate = self
_tapGesture.enabled = shouldResignOnTouchOutside
disableDistanceHandlingInViewControllerClass(UITableViewController)
considerToolbarPreviousNextInViewClass(UITableView)
considerToolbarPreviousNextInViewClass(UICollectionView)
//Workaround to load all appearance proxies at startup
let barButtonItem2 = IQTitleBarButtonItem()
barButtonItem2.title = ""
let toolbar = IQToolbar()
toolbar.title = ""
}
/** Override +load method to enable KeyboardManager when class loader load IQKeyboardManager. Enabling when app starts (No need to write any code) */
/** It doesn't work from Swift 1.2 */
// override public class func load() {
// super.load()
//
// //Enabling IQKeyboardManager.
// IQKeyboardManager.sharedManager().enable = true
// }
deinit {
// Disable the keyboard manager.
enable = false
//Removing notification observers on dealloc.
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/** Getting keyWindow. */
private func keyWindow() -> UIWindow? {
if let keyWindow = _textFieldView?.window {
return keyWindow
} else {
struct Static {
/** @abstract Save keyWindow object for reuse.
@discussion Sometimes [[UIApplication sharedApplication] keyWindow] is returning nil between the app. */
static var keyWindow : UIWindow?
}
/* (Bug ID: #23, #25, #73) */
let originalKeyWindow = UIApplication.sharedApplication().keyWindow
//If original key window is not nil and the cached keywindow is also not original keywindow then changing keywindow.
if originalKeyWindow != nil && (Static.keyWindow == nil || Static.keyWindow != originalKeyWindow) {
Static.keyWindow = originalKeyWindow
}
//Return KeyWindow
return Static.keyWindow
}
}
///-----------------------
/// MARK: Helper Functions
///-----------------------
/* Helper function to manipulate RootViewController's frame with animation. */
private func setRootViewFrame(var frame: CGRect) {
// Getting topMost ViewController.
var controller = _textFieldView?.topMostController()
if controller == nil {
controller = keyWindow()?.topMostController()
}
if let unwrappedController = controller {
//frame size needs to be adjusted on iOS8 due to orientation structure changes.
frame.size = unwrappedController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
// Setting it's new frame
unwrappedController.view.frame = frame
self._IQShowLog("Set \(controller?._IQDescription()) frame to : \(frame)")
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
unwrappedController.view.setNeedsLayout()
unwrappedController.view.layoutIfNeeded()
}
}) { (animated:Bool) -> Void in}
} else { // If can't get rootViewController then printing warning to user.
_IQShowLog("You must set UIWindow.rootViewController in your AppDelegate to work with IQKeyboardManager")
}
}
/* Adjusting RootViewController's frame according to interface orientation. */
private func adjustFrame() {
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
if _textFieldView == nil {
return
}
let textFieldView = _textFieldView!
_IQShowLog("****** \(__FUNCTION__) %@ started ******")
// Boolean to know keyboard is showing/hiding
_keyboardManagerFlags.isKeyboardShowing = true
// Getting KeyWindow object.
let optionalWindow = keyWindow()
// Getting RootViewController. (Bug ID: #1, #4)
var optionalRootController = _textFieldView?.topMostController()
if optionalRootController == nil {
optionalRootController = keyWindow()?.topMostController()
}
// Converting Rectangle according to window bounds.
let optionalTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: optionalWindow)
if optionalRootController == nil || optionalWindow == nil || optionalTextFieldViewRect == nil {
return
}
let rootController = optionalRootController!
let window = optionalWindow!
let textFieldViewRect = optionalTextFieldViewRect!
// Getting RootViewRect.
var rootViewRect = rootController.view.frame
//Getting statusBarFrame
//Maintain keyboardDistanceFromTextField
let newKeyboardDistanceFromTextField = (textFieldView.keyboardDistanceFromTextField == kIQUseDefaultKeyboardDistance) ? keyboardDistanceFromTextField : textFieldView.keyboardDistanceFromTextField
var kbSize = _kbSize
kbSize.height += newKeyboardDistanceFromTextField
let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
// (Bug ID: #250)
var layoutGuidePosition = IQLayoutGuidePosition.None
if let viewController = textFieldView.viewController() {
if let constraint = viewController.IQLayoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide) //If topLayoutGuide constraint
{
layoutGuidePosition = .Top
}
else if (itemLayoutGuide === viewController.bottomLayoutGuide) //If bottomLayoutGuice constraint
{
layoutGuidePosition = .Bottom
}
}
}
}
let topLayoutGuide : CGFloat = CGRectGetHeight(statusBarFrame)
var move : CGFloat = 0.0
// Move positive = textField is hidden.
// Move negative = textField is showing.
// Checking if there is bottomLayoutGuide attached (Bug ID: #250)
if layoutGuidePosition == .Bottom {
// Calculating move position.
move = CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height)
} else {
// Calculating move position. Common for both normal and special cases.
move = min(CGRectGetMinY(textFieldViewRect)-(topLayoutGuide+5), CGRectGetMaxY(textFieldViewRect)-(CGRectGetHeight(window.frame)-kbSize.height))
}
_IQShowLog("Need to move: \(move)")
// Getting it's superScrollView. // (Enhancement ID: #21, #24)
let superScrollView = textFieldView.superviewOfClassType(UIScrollView) as? UIScrollView
//If there was a lastScrollView. // (Bug ID: #34)
if let lastScrollView = _lastScrollView {
//If we can't find current superScrollView, then setting lastScrollView to it's original form.
if superScrollView == nil {
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_startingContentInsets = UIEdgeInsetsZero
_startingScrollIndicatorInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
_lastScrollView = nil
} else if superScrollView != lastScrollView { //If both scrollView's are different, then reset lastScrollView to it's original frame and setting current scrollView as last scrollView.
_IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(_startingContentInsets) and contentOffset to : \(_startingContentOffset)")
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
}) { (animated:Bool) -> Void in }
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.setContentOffset(_startingContentOffset, animated: true)
}
_lastScrollView = superScrollView
_startingContentInsets = superScrollView!.contentInset
_startingScrollIndicatorInsets = superScrollView!.scrollIndicatorInsets
_startingContentOffset = superScrollView!.contentOffset
_IQShowLog("Saving New \(lastScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
//Else the case where superScrollView == lastScrollView means we are on same scrollView after switching to different textField. So doing nothing, going ahead
} else if let unwrappedSuperScrollView = superScrollView { //If there was no lastScrollView and we found a current scrollView. then setting it as lastScrollView.
_lastScrollView = unwrappedSuperScrollView
_startingContentInsets = unwrappedSuperScrollView.contentInset
_startingScrollIndicatorInsets = unwrappedSuperScrollView.scrollIndicatorInsets
_startingContentOffset = unwrappedSuperScrollView.contentOffset
_IQShowLog("Saving \(unwrappedSuperScrollView._IQDescription()) contentInset : \(_startingContentInsets) and contentOffset : \(_startingContentOffset)")
}
// Special case for ScrollView.
// If we found lastScrollView then setting it's contentOffset to show textField.
if let lastScrollView = _lastScrollView {
//Saving
var lastView = textFieldView
var superScrollView = _lastScrollView
while let scrollView = superScrollView {
//Looping in upper hierarchy until we don't found any scrollView in it's upper hirarchy till UIWindow object.
if move > 0 ? (move > (-scrollView.contentOffset.y - scrollView.contentInset.top)) : scrollView.contentOffset.y>0 {
//Getting lastViewRect.
if let lastViewRect = lastView.superview?.convertRect(lastView.frame, toView: scrollView) {
//Calculating the expected Y offset from move and scrollView's contentOffset.
var shouldOffsetY = scrollView.contentOffset.y - min(scrollView.contentOffset.y,-move)
//Rearranging the expected Y offset according to the view.
shouldOffsetY = min(shouldOffsetY, lastViewRect.origin.y /*-5*/) //-5 is for good UI.//Commenting -5 (Bug ID: #69)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//[superScrollView superviewOfClassType:[UIScrollView class]] == nil If processing scrollView is last scrollView in upper hierarchy (there is no other scrollView upper hierrchy.)
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//shouldOffsetY >= 0 shouldOffsetY must be greater than in order to keep distance from navigationBar (Bug ID: #92)
if textFieldView is UITextView == true && scrollView.superviewOfClassType(UIScrollView) == nil && shouldOffsetY >= 0 {
var maintainTopLayout : CGFloat = 0
if let navigationBarFrame = textFieldView.viewController()?.navigationController?.navigationBar.frame {
maintainTopLayout = CGRectGetMaxY(navigationBarFrame)
}
maintainTopLayout += 10.0 //For good UI
// Converting Rectangle according to window bounds.
if let currentTextFieldViewRect = textFieldView.superview?.convertRect(textFieldView.frame, toView: window) {
//Calculating expected fix distance which needs to be managed from navigation bar
let expectedFixDistance = CGRectGetMinY(currentTextFieldViewRect) - maintainTopLayout
//Now if expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance) is lower than current shouldOffsetY, which means we're in a position where navigationBar up and hide, then reducing shouldOffsetY with expectedOffsetY (superScrollView.contentOffset.y + expectedFixDistance)
shouldOffsetY = min(shouldOffsetY, scrollView.contentOffset.y + expectedFixDistance)
//Setting move to 0 because now we don't want to move any view anymore (All will be managed by our contentInset logic.
move = 0
}
else {
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
}
else
{
//Subtracting the Y offset from the move variable, because we are going to change scrollView's contentOffset.y to shouldOffsetY.
move -= (shouldOffsetY-scrollView.contentOffset.y)
}
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self._IQShowLog("Adjusting \(scrollView.contentOffset.y-shouldOffsetY) to \(scrollView._IQDescription()) ContentOffset")
self._IQShowLog("Remaining Move: \(move)")
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, shouldOffsetY)
}) { (animated:Bool) -> Void in }
}
// Getting next lastView & superScrollView.
lastView = scrollView
superScrollView = lastView.superviewOfClassType(UIScrollView) as? UIScrollView
} else {
break
}
}
//Updating contentInset
if let lastScrollViewRect = lastScrollView.superview?.convertRect(lastScrollView.frame, toView: window) {
let bottom : CGFloat = kbSize.height-(CGRectGetHeight(window.frame)-CGRectGetMaxY(lastScrollViewRect))
// Update the insets so that the scroll vew doesn't shift incorrectly when the offset is near the bottom of the scroll view.
var movedInsets = lastScrollView.contentInset
movedInsets.bottom = max(_startingContentInsets.bottom, bottom)
_IQShowLog("\(lastScrollView._IQDescription()) old ContentInset : \(lastScrollView.contentInset)")
//Getting problem while using `setContentOffset:animated:`, So I used animation API.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = movedInsets
var newInset = lastScrollView.scrollIndicatorInsets
newInset.bottom = movedInsets.bottom - 10
lastScrollView.scrollIndicatorInsets = newInset
}) { (animated:Bool) -> Void in }
//Maintaining contentSize
if lastScrollView.contentSize.height < lastScrollView.frame.size.height {
var contentSize = lastScrollView.contentSize
contentSize.height = lastScrollView.frame.size.height
lastScrollView.contentSize = contentSize
}
_IQShowLog("\(lastScrollView._IQDescription()) new ContentInset : \(lastScrollView.contentInset)")
}
}
//Going ahead. No else if.
if layoutGuidePosition == .Top {
let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint!
let constant = min(_layoutGuideConstraintInitialConstant, constraint.constant-move)
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
} else if layoutGuidePosition == .Bottom {
let constraint = textFieldView.viewController()!.IQLayoutGuideConstraint!
let constant = max(_layoutGuideConstraintInitialConstant, constraint.constant+move)
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in
constraint.constant = constant
self._rootViewController?.view.setNeedsLayout()
self._rootViewController?.view.layoutIfNeeded()
}, completion: { (finished) -> Void in })
} else {
//Special case for UITextView(Readjusting the move variable when textView hight is too big to fit on screen)
//_canAdjustTextView If we have permission to adjust the textView, then let's do it on behalf of user (Enhancement ID: #15)
//_lastScrollView If not having inside any scrollView, (now contentInset manages the full screen textView.
//[_textFieldView isKindOfClass:[UITextView class]] If is a UITextView type
//_isTextFieldViewFrameChanged If frame is not change by library in past (Bug ID: #92)
if canAdjustTextView == true && _lastScrollView == nil && textFieldView is UITextView == true && _keyboardManagerFlags.isTextFieldViewFrameChanged == false {
var textViewHeight = CGRectGetHeight(textFieldView.frame)
textViewHeight = min(textViewHeight, (CGRectGetHeight(window.frame)-kbSize.height-(topLayoutGuide+5)))
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in
self._IQShowLog("\(textFieldView._IQDescription()) Old Frame : \(textFieldView.frame)")
var textFieldViewRect = textFieldView.frame
textFieldViewRect.size.height = textViewHeight
textFieldView.frame = textFieldViewRect
self._keyboardManagerFlags.isTextFieldViewFrameChanged = true
self._IQShowLog("\(textFieldView._IQDescription()) New Frame : \(textFieldView.frame)")
}, completion: { (finished) -> Void in })
}
// Special case for iPad modalPresentationStyle.
if rootController.modalPresentationStyle == UIModalPresentationStyle.FormSheet || rootController.modalPresentationStyle == UIModalPresentationStyle.PageSheet {
_IQShowLog("Found Special case for Model Presentation Style: \(rootController.modalPresentationStyle)")
// +Positive or zero.
if move >= 0 {
// We should only manipulate y.
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
let minimumY: CGFloat = (CGRectGetHeight(window.frame)-rootViewRect.size.height-topLayoutGuide)/2-(kbSize.height-newKeyboardDistanceFromTextField)
rootViewRect.origin.y = max(CGRectGetMinY(rootViewRect), minimumY)
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // -Negative
// Calculating disturbed distance. Pull Request #3
let disturbDistance = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect)
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
// We should only manipulate y.
rootViewRect.origin.y -= max(move, disturbDistance)
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
} else { //If presentation style is neither UIModalPresentationFormSheet nor UIModalPresentationPageSheet then going ahead.(General case)
// +Positive or zero.
if move >= 0 {
rootViewRect.origin.y -= move
// From now prevent keyboard manager to slide up the rootView to more than keyboard height. (Bug ID: #93)
if preventShowingBottomBlankSpace == true {
rootViewRect.origin.y = max(rootViewRect.origin.y, min(0, -kbSize.height+newKeyboardDistanceFromTextField))
}
_IQShowLog("Moving Upward")
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
} else { // -Negative
let disturbDistance : CGFloat = CGRectGetMinY(rootViewRect)-CGRectGetMinY(_topViewBeginRect)
// disturbDistance Negative = frame disturbed.
// disturbDistance positive = frame not disturbed.
if disturbDistance < 0 {
rootViewRect.origin.y -= max(move, disturbDistance)
_IQShowLog("Moving Downward")
// Setting adjusted rootViewRect
// Setting adjusted rootViewRect
setRootViewFrame(rootViewRect)
}
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///-------------------------------
/// MARK: UIKeyboard Notifications
///-------------------------------
/* UIKeyboardWillShowNotification. */
internal func keyboardWillShow(notification : NSNotification?) -> Void {
_kbShowNotification = notification
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Due to orientation callback we need to resave it's original frame. // (Bug ID: #46)
//Added _isTextFieldViewFrameChanged check. Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed. (Bug ID: #92)
if _keyboardManagerFlags.isTextFieldViewFrameChanged == false && _textFieldView != nil {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
// (Bug ID: #5)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == true {
// keyboard is not showing(At the beginning only). We should save rootViewRect.
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let unwrappedRootController = _rootViewController {
_topViewBeginRect = unwrappedRootController.view.frame
_IQShowLog("Saving \(unwrappedRootController._IQDescription()) beginning Frame: \(_topViewBeginRect)")
} else {
_topViewBeginRect = CGRectZero
}
}
let oldKBSize = _kbSize
if let info = notification?.userInfo {
if shouldAdoptDefaultKeyboardAnimation {
// Getting keyboard animation.
if let curve = info[UIKeyboardAnimationCurveUserInfoKey]?.unsignedLongValue {
_animationCurve = UIViewAnimationOptions(rawValue: curve)
}
} else {
_animationCurve = UIViewAnimationOptions.CurveEaseOut
}
// Getting keyboard animation duration
if let duration = info[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
//Saving animation duration
if duration != 0.0 {
_animationDuration = duration
}
}
// Getting UIKeyboardSize.
if let kbFrame = info[UIKeyboardFrameEndUserInfoKey]?.CGRectValue {
_kbSize = kbFrame.size
_IQShowLog("UIKeyboard Size : \(_kbSize)")
}
}
// Getting topMost ViewController.
var topMostController = _textFieldView?.topMostController()
if topMostController == nil {
topMostController = keyWindow()?.topMostController()
}
//If last restored keyboard size is different(any orientation accure), then refresh. otherwise not.
if CGSizeEqualToSize(_kbSize, oldKBSize) == false {
//If _textFieldView is inside UITableViewController then let UITableViewController to handle it (Bug ID: #37) (Bug ID: #76) See note:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false {
//Getting textField viewController
if let textFieldViewController = _textFieldView?.viewController() {
var shouldIgnore = false
for disabledClassString in _disabledClasses {
if let disabledClass = NSClassFromString(disabledClassString) {
//If viewController is kind of disabled viewController class, then ignoring to adjust view.
if textFieldViewController.isKindOfClass(disabledClass) {
shouldIgnore = true
break
}
}
}
//If shouldn't ignore.
if shouldIgnore == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/* UIKeyboardWillHideNotification. So setting rootViewController to it's default frame. */
internal func keyboardWillHide(notification : NSNotification?) -> Void {
//If it's not a fake notification generated by [self setEnable:NO].
if notification != nil {
_kbShowNotification = nil
}
//If not enabled then do nothing.
if enable == false {
return
}
_IQShowLog("****** \(__FUNCTION__) started ******")
//Commented due to #56. Added all the conditions below to handle UIWebView's textFields. (Bug ID: #56)
// We are unable to get textField object while keyboard showing on UIWebView's textField. (Bug ID: #11)
// if (_textFieldView == nil) return
// Boolean to know keyboard is showing/hiding
_keyboardManagerFlags.isKeyboardShowing = false
let info : [NSObject : AnyObject]? = notification?.userInfo
// Getting keyboard animation duration
if let duration = info?[UIKeyboardAnimationDurationUserInfoKey]?.doubleValue {
if duration != 0 {
// Setitng keyboard animation duration
_animationDuration = duration
}
}
//Restoring the contentOffset of the lastScrollView
if let lastScrollView = _lastScrollView {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
lastScrollView.contentInset = self._startingContentInsets
lastScrollView.scrollIndicatorInsets = self._startingScrollIndicatorInsets
if lastScrollView.shouldRestoreScrollViewContentOffset == true {
lastScrollView.contentOffset = self._startingContentOffset
}
self._IQShowLog("Restoring \(lastScrollView._IQDescription()) contentInset to : \(self._startingContentInsets) and contentOffset to : \(self._startingContentOffset)")
// TODO: restore scrollView state
// This is temporary solution. Have to implement the save and restore scrollView state
var superScrollView : UIScrollView? = lastScrollView
while let scrollView = superScrollView {
let contentSize = CGSizeMake(max(scrollView.contentSize.width, CGRectGetWidth(scrollView.frame)), max(scrollView.contentSize.height, CGRectGetHeight(scrollView.frame)))
let minimumY = contentSize.height - CGRectGetHeight(scrollView.frame)
if minimumY < scrollView.contentOffset.y {
scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, minimumY)
self._IQShowLog("Restoring \(scrollView._IQDescription()) contentOffset to : \(self._startingContentOffset)")
}
superScrollView = scrollView.superviewOfClassType(UIScrollView) as? UIScrollView
}
}) { (finished) -> Void in }
}
// Setting rootViewController frame to it's original position. // (Bug ID: #18)
if CGRectEqualToRect(_topViewBeginRect, CGRectZero) == false {
if let rootViewController = _rootViewController {
//frame size needs to be adjusted on iOS8 due to orientation API changes.
_topViewBeginRect.size = rootViewController.view.frame.size
//Used UIViewAnimationOptionBeginFromCurrentState to minimize strange animations.
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
var hasDoneTweakLayoutGuide = false
if let viewController = self._textFieldView?.viewController() {
if let constraint = viewController.IQLayoutGuideConstraint {
var layoutGuide : UILayoutSupport?
if let itemLayoutGuide = constraint.firstItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
} else if let itemLayoutGuide = constraint.secondItem as? UILayoutSupport {
layoutGuide = itemLayoutGuide
}
if let itemLayoutGuide : UILayoutSupport = layoutGuide {
if (itemLayoutGuide === viewController.topLayoutGuide || itemLayoutGuide === viewController.bottomLayoutGuide)
{
constraint.constant = self._layoutGuideConstraintInitialConstant
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
hasDoneTweakLayoutGuide = true
}
}
}
}
if hasDoneTweakLayoutGuide == false {
self._IQShowLog("Restoring \(rootViewController._IQDescription()) frame to : \(self._topViewBeginRect)")
// Setting it's new frame
rootViewController.view.frame = self._topViewBeginRect
//Animating content if needed (Bug ID: #204)
if self.layoutIfNeededOnUpdate == true {
//Animating content (Bug ID: #160)
rootViewController.view.setNeedsLayout()
rootViewController.view.layoutIfNeeded()
}
}
}) { (finished) -> Void in }
_rootViewController = nil
}
}
//Reset all values
_lastScrollView = nil
_kbSize = CGSizeZero
_startingContentInsets = UIEdgeInsetsZero
_startingScrollIndicatorInsets = UIEdgeInsetsZero
_startingContentOffset = CGPointZero
// topViewBeginRect = CGRectZero //Commented due to #82
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
internal func keyboardDidHide(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
_topViewBeginRect = CGRectZero
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///-------------------------------------------
/// MARK: UITextField/UITextView Notifications
///-------------------------------------------
/** UITextFieldTextDidBeginEditingNotification, UITextViewTextDidBeginEditingNotification. Fetching UITextFieldView object. */
internal func textFieldViewDidBeginEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
// Getting object
_textFieldView = notification.object as? UIView
if overrideKeyboardAppearance == true {
if let textFieldView = _textFieldView as? UITextField {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
} else if let textFieldView = _textFieldView as? UITextView {
//If keyboard appearance is not like the provided appearance
if textFieldView.keyboardAppearance != keyboardAppearance {
//Setting textField keyboard appearance and reloading inputViews.
textFieldView.keyboardAppearance = keyboardAppearance
textFieldView.reloadInputViews()
}
}
}
// Saving textFieldView current frame to use it with canAdjustTextView if textViewFrame has already not been changed.
//Added _isTextFieldViewFrameChanged check. (Bug ID: #92)
if _keyboardManagerFlags.isTextFieldViewFrameChanged == false {
if let textFieldView = _textFieldView {
_textFieldViewIntialFrame = textFieldView.frame
_IQShowLog("Saving \(textFieldView._IQDescription()) Initial frame : \(_textFieldViewIntialFrame)")
}
}
//If autoToolbar enable, then add toolbar on all the UITextField/UITextView's if required.
if enableAutoToolbar == true {
_IQShowLog("adding UIToolbars if required")
//UITextView special case. Keyboard Notification is firing before textView notification so we need to resign it first and then again set it as first responder to add toolbar on it.
if _textFieldView is UITextView == true && _textFieldView?.inputAccessoryView == nil {
UIView.animateWithDuration(0.00001, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self.addToolbarIfRequired()
}, completion: { (finished) -> Void in
//RestoringTextView before reloading inputViews
if (self._keyboardManagerFlags.isTextFieldViewFrameChanged)
{
self._keyboardManagerFlags.isTextFieldViewFrameChanged = false
if let textFieldView = self._textFieldView {
textFieldView.frame = self._textFieldViewIntialFrame
}
}
//On textView toolbar didn't appear on first time, so forcing textView to reload it's inputViews.
self._textFieldView?.reloadInputViews()
})
} else {
//Adding toolbar
addToolbarIfRequired()
}
}
if enable == false {
_IQShowLog("****** \(__FUNCTION__) ended ******")
return
}
_textFieldView?.window?.addGestureRecognizer(_tapGesture) // (Enhancement ID: #14)
if _keyboardManagerFlags.isKeyboardShowing == false { // (Bug ID: #5)
// keyboard is not showing(At the beginning only). We should save rootViewRect.
if let constant = _textFieldView?.viewController()?.IQLayoutGuideConstraint?.constant {
_layoutGuideConstraintInitialConstant = constant
}
_rootViewController = _textFieldView?.topMostController()
if _rootViewController == nil {
_rootViewController = keyWindow()?.topMostController()
}
if let rootViewController = _rootViewController {
_topViewBeginRect = rootViewController.view.frame
_IQShowLog("Saving \(rootViewController._IQDescription()) beginning frame : \(_topViewBeginRect)")
}
}
//If _textFieldView is inside ignored responder then do nothing. (Bug ID: #37, #74, #76)
//See notes:- https://developer.apple.com/Library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html. If it is UIAlertView textField then do not affect anything (Bug ID: #70).
if _textFieldView != nil && _textFieldView?.isAlertViewTextField() == false {
//Getting textField viewController
if let textFieldViewController = _textFieldView?.viewController() {
var shouldIgnore = false
for disabledClassString in _disabledClasses {
if let disabledClass = NSClassFromString(disabledClassString) {
//If viewController is kind of disabled viewController class, then ignoring to adjust view.
if textFieldViewController.isKindOfClass(disabledClass) {
shouldIgnore = true
break
}
}
}
//If shouldn't ignore.
if shouldIgnore == false {
// keyboard is already showing. adjust frame.
adjustFrame()
}
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextFieldTextDidEndEditingNotification, UITextViewTextDidEndEditingNotification. Removing fetched object. */
internal func textFieldViewDidEndEditing(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
//Removing gesture recognizer (Enhancement ID: #14)
_textFieldView?.window?.removeGestureRecognizer(_tapGesture)
// We check if there's a change in original frame or not.
if _keyboardManagerFlags.isTextFieldViewFrameChanged == true {
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
self._keyboardManagerFlags.isTextFieldViewFrameChanged = false
self._IQShowLog("Restoring \(self._textFieldView?._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
self._textFieldView?.frame = self._textFieldViewIntialFrame
}, completion: { (finished) -> Void in })
}
//Setting object to nil
_textFieldView = nil
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
/** UITextViewTextDidChangeNotificationBug, fix for iOS 7.0.x - http://stackoverflow.com/questions/18966675/uitextview-in-ios7-clips-the-last-line-of-text-string */
internal func textFieldViewDidChange(notification:NSNotification) { // (Bug ID: #18)
if shouldFixTextViewClip {
let textView = notification.object as! UITextView
let line = textView.caretRectForPosition((textView.selectedTextRange?.start)!)
let overflow = CGRectGetMaxY(line) - (textView.contentOffset.y + CGRectGetHeight(textView.bounds) - textView.contentInset.bottom - textView.contentInset.top)
//Added overflow conditions (Bug ID: 95)
if overflow > 0.0 && overflow < CGFloat(FLT_MAX) {
// We are at the bottom of the visible text and introduced a line feed, scroll down (iOS 7 does not do it)
// Scroll caret to visible area
var offset = textView.contentOffset
offset.y += overflow + 7 // leave 7 pixels margin
// Cannot animate with setContentOffset:animated: or caret will not appear
UIView.animateWithDuration(_animationDuration, delay: 0, options: UIViewAnimationOptions.BeginFromCurrentState.union(_animationCurve), animations: { () -> Void in
textView.contentOffset = offset
}, completion: { (finished) -> Void in })
}
}
}
///------------------------------------------
/// MARK: Interface Orientation Notifications
///------------------------------------------
/** UIApplicationWillChangeStatusBarOrientationNotification. Need to set the textView to it's original position. If any frame changes made. (Bug ID: #92)*/
internal func willChangeStatusBarOrientation(notification:NSNotification) {
_IQShowLog("****** \(__FUNCTION__) started ******")
//If textFieldViewInitialRect is saved then restore it.(UITextView case @canAdjustTextView)
if _keyboardManagerFlags.isTextFieldViewFrameChanged == true {
if let textFieldView = _textFieldView {
//Due to orientation callback we need to set it's original position.
UIView.animateWithDuration(_animationDuration, delay: 0, options: (_animationCurve.union(UIViewAnimationOptions.BeginFromCurrentState)), animations: { () -> Void in
self._keyboardManagerFlags.isTextFieldViewFrameChanged = false
self._IQShowLog("Restoring \(textFieldView._IQDescription()) frame to : \(self._textFieldViewIntialFrame)")
//Setting textField to it's initial frame
textFieldView.frame = self._textFieldViewIntialFrame
}, completion: { (finished) -> Void in })
}
}
_IQShowLog("****** \(__FUNCTION__) ended ******")
}
///------------------
/// MARK: AutoToolbar
///------------------
/** Get all UITextField/UITextView siblings of textFieldView. */
private func responderViews()-> [UIView]? {
var superConsideredView : UIView?
//If find any consider responderView in it's upper hierarchy then will get deepResponderView.
for disabledClassString in _toolbarPreviousNextConsideredClass {
if let disabledClass = NSClassFromString(disabledClassString) {
superConsideredView = _textFieldView?.superviewOfClassType(disabledClass)
if superConsideredView != nil {
break
}
}
}
//If there is a superConsideredView in view's hierarchy, then fetching all it's subview that responds. No sorting for superConsideredView, it's by subView position. (Enhancement ID: #22)
if superConsideredView != nil {
return superConsideredView?.deepResponderViews()
} else { //Otherwise fetching all the siblings
if let textFields = _textFieldView?.responderSiblings() {
//Sorting textFields according to behaviour
switch toolbarManageBehaviour {
//If autoToolbar behaviour is bySubviews, then returning it.
case IQAutoToolbarManageBehaviour.BySubviews: return textFields
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByTag: return textFields.sortedArrayByTag()
//If autoToolbar behaviour is by tag, then sorting it according to tag property.
case IQAutoToolbarManageBehaviour.ByPosition: return textFields.sortedArrayByPosition()
}
} else {
return nil
}
}
}
/** Add toolbar if it is required to add on textFields and it's siblings. */
private func addToolbarIfRequired() {
if let textFieldViewController = _textFieldView?.viewController() {
for disabledClassString in _disabledToolbarClasses {
if let disabledClass = NSClassFromString(disabledClassString) {
if textFieldViewController.isKindOfClass(disabledClass) {
removeToolbarIfRequired()
return
}
}
}
}
// Getting all the sibling textFields.
if let siblings = responderViews() {
// If only one object is found, then adding only Done button.
if siblings.count == 1 {
let textField = siblings[0]
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Previous/Next/Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addRightButtonOnKeyboardWithImage(doneBarButtonItemImage, target: self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addRightButtonOnKeyboardWithText(doneBarButtonItemText, target: self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addDoneOnKeyboardWithTarget(self, action: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQDoneButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
//Setting toolbar tintColor // (Enhancement ID: #30)
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.blackColor()
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.blackColor()
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false {
//Updating placeholder font to toolbar. //(Bug ID: #148)
if let _textField = textField as? UITextField {
if toolbar.title == nil || toolbar.title != _textField.placeholder {
toolbar.title = _textField.placeholder
}
} else if let _textView = textField as? IQTextView {
if toolbar.title == nil || toolbar.title != _textView.placeholder {
toolbar.title = _textView.placeholder
}
} else {
toolbar.title = nil
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
} else {
toolbar.title = nil
}
}
} else if siblings.count != 0 {
// If more than 1 textField is found. then adding previous/next/done buttons on it.
for textField in siblings {
//Either there is no inputAccessoryView or if accessoryView is not appropriate for current situation(There is Done toolbar).
//setInputAccessoryView: check (Bug ID: #307)
if textField.respondsToSelector(Selector("setInputAccessoryView:")) && (textField.inputAccessoryView == nil || textField.inputAccessoryView?.tag == IQKeyboardManager.kIQDoneButtonToolbarTag) {
//Supporting Custom Done button image (Enhancement ID: #366)
if let doneBarButtonItemImage = toolbarDoneBarButtonItemImage {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonImage: doneBarButtonItemImage, previousAction: "previousAction:", nextAction: "nextAction:", rightButtonAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
//Supporting Custom Done button text (Enhancement ID: #209, #411, Bug ID: #376)
else if let doneBarButtonItemText = toolbarDoneBarButtonItemText {
textField.addPreviousNextRightOnKeyboardWithTarget(self, rightButtonTitle: doneBarButtonItemText, previousAction: "previousAction:", nextAction: "nextAction:", rightButtonAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
} else {
//Now adding textField placeholder text as title of IQToolbar (Enhancement ID: #27)
textField.addPreviousNextDoneOnKeyboardWithTarget(self, previousAction: "previousAction:", nextAction: "nextAction:", doneAction: "doneAction:", shouldShowPlaceholder: shouldShowTextFieldPlaceholder)
}
textField.inputAccessoryView?.tag = IQKeyboardManager.kIQPreviousNextButtonToolbarTag // (Bug ID: #78)
}
if textField.inputAccessoryView is IQToolbar && textField.inputAccessoryView?.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag {
let toolbar = textField.inputAccessoryView as! IQToolbar
// Setting toolbar to keyboard.
if let _textField = textField as? UITextField {
//Bar style according to keyboard appearance
switch _textField.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textField.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.blackColor()
}
}
} else if let _textView = textField as? UITextView {
//Bar style according to keyboard appearance
switch _textView.keyboardAppearance {
case UIKeyboardAppearance.Dark:
toolbar.barStyle = UIBarStyle.Black
toolbar.tintColor = UIColor.whiteColor()
default:
toolbar.barStyle = UIBarStyle.Default
if shouldToolbarUsesTextFieldTintColor {
toolbar.tintColor = _textView.tintColor
} else if let tintColor = toolbarTintColor {
toolbar.tintColor = tintColor
} else {
toolbar.tintColor = UIColor.blackColor()
}
}
}
//Setting toolbar title font. // (Enhancement ID: #30)
if shouldShowTextFieldPlaceholder == true && textField.shouldHideTitle == false {
//Updating placeholder font to toolbar. //(Bug ID: #148)
if let _textField = textField as? UITextField {
if toolbar.title == nil || toolbar.title != _textField.placeholder {
toolbar.title = _textField.placeholder
}
} else if let _textView = textField as? IQTextView {
if toolbar.title == nil || toolbar.title != _textView.placeholder {
toolbar.title = _textView.placeholder
}
} else {
toolbar.title = nil
}
//Setting toolbar title font. // (Enhancement ID: #30)
if placeholderFont != nil {
toolbar.titleFont = placeholderFont
}
}
else {
toolbar.title = nil
}
//In case of UITableView (Special), the next/previous buttons has to be refreshed everytime. (Bug ID: #56)
// If firstTextField, then previous should not be enabled.
if siblings[0] == textField {
textField.setEnablePrevious(false, isNextEnabled: true)
} else if siblings.last == textField { // If lastTextField then next should not be enaled.
textField.setEnablePrevious(true, isNextEnabled: false)
} else {
textField.setEnablePrevious(true, isNextEnabled: true)
}
}
}
}
}
}
/** Remove any toolbar if it is IQToolbar. */
private func removeToolbarIfRequired() { // (Bug ID: #18)
// Getting all the sibling textFields.
if let siblings = responderViews() {
for view in siblings {
if let toolbar = view.inputAccessoryView as? IQToolbar {
//setInputAccessoryView: check (Bug ID: #307)
if view.respondsToSelector(Selector("setInputAccessoryView:")) && (toolbar.tag == IQKeyboardManager.kIQDoneButtonToolbarTag || toolbar.tag == IQKeyboardManager.kIQPreviousNextButtonToolbarTag) {
if let textField = view as? UITextField {
textField.inputAccessoryView = nil
} else if let textView = view as? UITextView {
textView.inputAccessoryView = nil
}
}
}
}
}
}
private func _IQShowLog(logString: String) {
#if IQKEYBOARDMANAGER_DEBUG
println("IQKeyboardManager: " + logString)
#endif
}
}
| mit | c800a4473baf734cd4121d325d8836dd | 47.032512 | 370 | 0.566432 | 7.120491 | false | false | false | false |
KrishMunot/swift | test/SILGen/protocols.swift | 6 | 22020 | // RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
//===----------------------------------------------------------------------===//
// Calling Existential Subscripts
//===----------------------------------------------------------------------===//
protocol SubscriptableGet {
subscript(a : Int) -> Int { get }
}
protocol SubscriptableGetSet {
subscript(a : Int) -> Int { get set }
}
var subscriptableGet : SubscriptableGet
var subscriptableGetSet : SubscriptableGetSet
func use_subscript_rvalue_get(_ i : Int) -> Int {
return subscriptableGet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_rvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols16subscriptableGetPS_16SubscriptableGet_ : $*SubscriptableGet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGet to $*[[OPENED:@opened(.*) SubscriptableGet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_get(_ i : Int) -> Int {
return subscriptableGetSet[i]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_get
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols19subscriptableGetSetPS_19SubscriptableGetSet_ : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK: [[ALLOCSTACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[RESULT:%[0-9]+]] = apply [[METH]]<[[OPENED]]>(%0, [[ALLOCSTACK]])
// CHECK-NEXT: destroy_addr [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: dealloc_stack [[ALLOCSTACK]] : $*[[OPENED]]
// CHECK-NEXT: return [[RESULT]]
func use_subscript_lvalue_set(_ i : Int) {
subscriptableGetSet[i] = i
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols19subscriptableGetSetPS_19SubscriptableGetSet_ : $*SubscriptableGetSet
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*SubscriptableGetSet to $*[[OPENED:@opened(.*) SubscriptableGetSet]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, %0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Subscripts
//===----------------------------------------------------------------------===//
func use_subscript_archetype_rvalue_get<T : SubscriptableGet>(_ generic : T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_rvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGet.subscript!getter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK-NEXT: destroy_addr %0
func use_subscript_archetype_lvalue_get<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) -> Int {
return generic[idx]
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_get
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T, var, name "generic"
// CHECK: [[PB:%.*]] = project_box [[INOUTBOX]]
// CHECK: [[GUARANTEEDSTACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr [[PB]] to [initialization]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!getter.1
// CHECK-NEXT: [[APPLYRESULT:%[0-9]+]] = apply [[METH]]<T>(%1, [[GUARANTEEDSTACK]])
// CHECK-NEXT: destroy_addr [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: dealloc_stack [[GUARANTEEDSTACK]] : $*T
// CHECK-NEXT: copy_addr [[PB]] to %0 : $*T
// CHECK-NEXT: strong_release [[INOUTBOX]] : $@box T
// CHECK: return [[APPLYRESULT]]
func use_subscript_archetype_lvalue_set<T : SubscriptableGetSet>(_ generic: inout T, idx : Int) {
generic[idx] = idx
}
// CHECK-LABEL: sil hidden @{{.*}}use_subscript_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T
// CHECK: [[PB:%.*]] = project_box [[INOUTBOX]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #SubscriptableGetSet.subscript!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, %1, [[PB]])
// CHECK: strong_release [[INOUTBOX]]
//===----------------------------------------------------------------------===//
// Calling Existential Properties
//===----------------------------------------------------------------------===//
protocol PropertyWithGetter {
var a : Int { get }
}
protocol PropertyWithGetterSetter {
var b : Int { get set }
}
var propertyGet : PropertyWithGetter
var propertyGetSet : PropertyWithGetterSetter
func use_property_rvalue_get() -> Int {
return propertyGet.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_rvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols11propertyGetPS_18PropertyWithGetter_ : $*PropertyWithGetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetter to $*[[OPENED:@opened(.*) PropertyWithGetter]]
// CHECK: [[COPY:%.*]] = alloc_stack $[[OPENED]]
// CHECK-NEXT: copy_addr [[PROJ]] to [initialization] [[COPY]] : $*[[OPENED]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[COPY]])
func use_property_lvalue_get() -> Int {
return propertyGetSet.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_get
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols14propertyGetSetPS_24PropertyWithGetterSetter_ : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $[[OPENED]]
// CHECK: copy_addr [[PROJ]] to [initialization] [[STACK]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>([[STACK]])
func use_property_lvalue_set(_ x : Int) {
propertyGetSet.b = x
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_lvalue_set
// CHECK: bb0(%0 : $Int):
// CHECK: [[GLOB:%[0-9]+]] = global_addr @_Tv9protocols14propertyGetSetPS_24PropertyWithGetterSetter_ : $*PropertyWithGetterSetter
// CHECK: [[PROJ:%[0-9]+]] = open_existential_addr [[GLOB]] : $*PropertyWithGetterSetter to $*[[OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[METH:%[0-9]+]] = witness_method $[[OPENED]], #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<[[OPENED]]>(%0, [[PROJ]])
//===----------------------------------------------------------------------===//
// Calling Archetype Properties
//===----------------------------------------------------------------------===//
func use_property_archetype_rvalue_get<T : PropertyWithGetter>(_ generic : T) -> Int {
return generic.a
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_rvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetter.a!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]]
// CHECK-NEXT: dealloc_stack [[STACK]]
// CHECK-NEXT: destroy_addr %0
func use_property_archetype_lvalue_get<T : PropertyWithGetterSetter>(_ generic : T) -> Int {
return generic.b
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_get
// CHECK: bb0(%0 : $*T):
// CHECK: [[STACK:%[0-9]+]] = alloc_stack $T
// CHECK: copy_addr %0 to [initialization] [[STACK]] : $*T
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[METH]]<T>([[STACK]])
// CHECK-NEXT: destroy_addr [[STACK]] : $*T
// CHECK-NEXT: dealloc_stack [[STACK]] : $*T
// CHECK-NEXT: destroy_addr %0
func use_property_archetype_lvalue_set<T : PropertyWithGetterSetter>(_ generic: inout T, v : Int) {
generic.b = v
}
// CHECK-LABEL: sil hidden @{{.*}}use_property_archetype_lvalue_set
// CHECK: bb0(%0 : $*T, %1 : $Int):
// CHECK: [[INOUTBOX:%[0-9]+]] = alloc_box $T
// CHECK: [[PB:%.*]] = project_box [[INOUTBOX]]
// CHECK: [[METH:%[0-9]+]] = witness_method $T, #PropertyWithGetterSetter.b!setter.1
// CHECK-NEXT: apply [[METH]]<T>(%1, [[PB]])
// CHECK: strong_release [[INOUTBOX]]
//===----------------------------------------------------------------------===//
// Calling Initializers
//===----------------------------------------------------------------------===//
protocol Initializable {
init(int: Int)
}
// CHECK-LABEL: sil hidden @_TF9protocols27use_initializable_archetype
func use_initializable_archetype<T: Initializable>(_ t: T, i: Int) {
// CHECK: [[T_INIT:%[0-9]+]] = witness_method $T, #Initializable.init!allocator.1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[T_META:%[0-9]+]] = metatype $@thick T.Type
// CHECK: [[T_RESULT:%[0-9]+]] = alloc_stack $T
// CHECK: [[T_RESULT_ADDR:%[0-9]+]] = apply [[T_INIT]]<T>([[T_RESULT]], %1, [[T_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[T_RESULT]] : $*T
// CHECK: dealloc_stack [[T_RESULT]] : $*T
// CHECK: destroy_addr [[VAR_0:%[0-9]+]] : $*T
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
T(int: i)
}
// CHECK: sil hidden @_TF9protocols29use_initializable_existential
func use_initializable_existential(_ im: Initializable.Type, i: Int) {
// CHECK: bb0([[IM:%[0-9]+]] : $@thick Initializable.Type, [[I:%[0-9]+]] : $Int):
// CHECK: [[ARCHETYPE_META:%[0-9]+]] = open_existential_metatype [[IM]] : $@thick Initializable.Type to $@thick (@opened([[N:".*"]]) Initializable).Type
// CHECK: [[TEMP_VALUE:%[0-9]+]] = alloc_stack $Initializable
// CHECK: [[TEMP_ADDR:%[0-9]+]] = init_existential_addr [[TEMP_VALUE]] : $*Initializable, $@opened([[N]]) Initializable
// CHECK: [[INIT_WITNESS:%[0-9]+]] = witness_method $@opened([[N]]) Initializable, #Initializable.init!allocator.1, [[ARCHETYPE_META]]{{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT_WITNESS]]<@opened([[N]]) Initializable>([[TEMP_ADDR]], [[I]], [[ARCHETYPE_META]]) : $@convention(witness_method) <τ_0_0 where τ_0_0 : Initializable> (Int, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: destroy_addr [[TEMP_VALUE]] : $*Initializable
// CHECK: dealloc_stack [[TEMP_VALUE]] : $*Initializable
im.init(int: i)
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
//===----------------------------------------------------------------------===//
// Protocol conformance and witness table generation
//===----------------------------------------------------------------------===//
class ClassWithGetter : PropertyWithGetter {
var a: Int {
get {
return 42
}
}
}
// Make sure we are generating a protocol witness that calls the class method on
// ClassWithGetter.
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9protocols15ClassWithGetterS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed ClassWithGetter) -> Int {
// CHECK: bb0([[C:%.*]] : $*ClassWithGetter):
// CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetter
// CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]]
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]]
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetter, #ClassWithGetter.a!getter.1 : (ClassWithGetter) -> () -> Int , $@convention(method) (@guaranteed ClassWithGetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: strong_release [[CCOPY_LOADED]]
// CHECK-NEXT: dealloc_stack [[CCOPY]]
// CHECK-NEXT: return
class ClassWithGetterSetter : PropertyWithGetterSetter, PropertyWithGetter {
var a: Int {
get {
return 1
}
set {}
}
var b: Int {
get {
return 2
}
set {}
}
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_g1bSi : $@convention(witness_method) (@in_guaranteed ClassWithGetterSetter) -> Int {
// CHECK: bb0([[C:%.*]] : $*ClassWithGetterSetter):
// CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $ClassWithGetterSetter
// CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]]
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]]
// CHECK-NEXT: [[FUN:%.*]] = class_method [[CCOPY_LOADED]] : $ClassWithGetterSetter, #ClassWithGetterSetter.b!getter.1 : (ClassWithGetterSetter) -> () -> Int , $@convention(method) (@guaranteed ClassWithGetterSetter) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: strong_release [[CCOPY_LOADED]]
// CHECK-NEXT: dealloc_stack [[CCOPY]]
// CHECK-NEXT: return
// Stored variables fulfilling property requirements
//
class ClassWithStoredProperty : PropertyWithGetter {
var a : Int = 0
// Make sure that accesses go through the generated accessors for classes.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}ClassWithStoredProperty{{.*}}methodUsingProperty
// CHECK: bb0([[ARG:%.*]] : $ClassWithStoredProperty):
// CHECK-NEXT: debug_value [[ARG]]
// CHECK-NOT: strong_retain
// CHECK-NEXT: [[FUN:%.*]] = class_method [[ARG]] : $ClassWithStoredProperty, #ClassWithStoredProperty.a!getter.1 : (ClassWithStoredProperty) -> () -> Int , $@convention(method) (@guaranteed ClassWithStoredProperty) -> Int
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[ARG]])
// CHECK-NOT: strong_release
// CHECK-NEXT: return [[RESULT]] : $Int
}
struct StructWithStoredProperty : PropertyWithGetter {
var a : Int
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}StructWithStoredProperty{{.*}}methodUsingProperty
// CHECK: bb0(%0 : $StructWithStoredProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredProperty, #StructWithStoredProperty.a
// CHECK-NEXT: return %2 : $Int
}
// Make sure that we generate direct function calls for out struct protocol
// witness since structs don't do virtual calls for methods.
//
// *NOTE* Even though at first glance the copy_addr looks like a leak
// here, StructWithStoredProperty is a trivial struct implying that no
// leak is occurring. See the test with StructWithStoredClassProperty
// that makes sure in such a case we don't leak. This is due to the
// thunking code being too dumb but it is harmless to program
// correctness.
//
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9protocols24StructWithStoredPropertyS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed StructWithStoredProperty) -> Int {
// CHECK: bb0([[C:%.*]] : $*StructWithStoredProperty):
// CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredProperty
// CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]]
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFV9protocols24StructWithStoredPropertyg1aSi : $@convention(method) (StructWithStoredProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: dealloc_stack [[CCOPY]]
// CHECK-NEXT: return
class C {}
// Make sure that if the getter has a class property, we pass it in
// in_guaranteed and don't leak.
struct StructWithStoredClassProperty : PropertyWithGetter {
var a : Int
var c: C = C()
// Make sure that accesses aren't going through the generated accessors.
func methodUsingProperty() -> Int {
return a
}
// CHECK-LABEL: sil hidden @{{.*}}StructWithStoredClassProperty{{.*}}methodUsingProperty
// CHECK: bb0(%0 : $StructWithStoredClassProperty):
// CHECK-NEXT: debug_value %0
// CHECK-NEXT: %2 = struct_extract %0 : $StructWithStoredClassProperty, #StructWithStoredClassProperty.a
// CHECK-NEXT: return %2 : $Int
}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9protocols29StructWithStoredClassPropertyS_18PropertyWithGetterS_FS1_g1aSi : $@convention(witness_method) (@in_guaranteed StructWithStoredClassProperty) -> Int {
// CHECK: bb0([[C:%.*]] : $*StructWithStoredClassProperty):
// CHECK-NEXT: [[CCOPY:%.*]] = alloc_stack $StructWithStoredClassProperty
// CHECK-NEXT: copy_addr [[C]] to [initialization] [[CCOPY]]
// CHECK-NEXT: [[CCOPY_LOADED:%.*]] = load [[CCOPY]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFV9protocols29StructWithStoredClassPropertyg1aSi : $@convention(method) (@guaranteed StructWithStoredClassProperty) -> Int
// CHECK-NEXT: apply [[FUN]]([[CCOPY_LOADED]])
// CHECK-NEXT: release_value [[CCOPY_LOADED]]
// CHECK-NEXT: dealloc_stack [[CCOPY]]
// CHECK-NEXT: return
// rdar://22676810
protocol ExistentialProperty {
var p: PropertyWithGetterSetter { get set }
}
func testExistentialPropertyRead<T: ExistentialProperty>(_ t: inout T) {
let b = t.p.b
}
// CHECK-LABEL: sil hidden @_TF9protocols27testExistentialPropertyRead
// CHECK: [[T:%.*]] = alloc_box $T
// CHECK: [[PB:%.*]] = project_box [[T]]
// CHECK: copy_addr %0 to [initialization] [[PB]] : $*T
// CHECK: [[P_TEMP:%.*]] = alloc_stack $PropertyWithGetterSetter
// CHECK: [[T_TEMP:%.*]] = alloc_stack $T
// CHECK: copy_addr [[PB]] to [initialization] [[T_TEMP]] : $*T
// CHECK: [[P_GETTER:%.*]] = witness_method $T, #ExistentialProperty.p!getter.1 :
// CHECK-NEXT: apply [[P_GETTER]]<T>([[P_TEMP]], [[T_TEMP]])
// CHECK-NEXT: destroy_addr [[T_TEMP]]
// CHECK-NEXT: [[OPEN:%.*]] = open_existential_addr [[P_TEMP]] : $*PropertyWithGetterSetter to $*[[P_OPENED:@opened(.*) PropertyWithGetterSetter]]
// CHECK-NEXT: [[T0:%.*]] = alloc_stack $[[P_OPENED]]
// CHECK-NEXT: copy_addr [[OPEN]] to [initialization] [[T0]]
// CHECK-NEXT: [[B_GETTER:%.*]] = witness_method $[[P_OPENED]], #PropertyWithGetterSetter.b!getter.1
// CHECK-NEXT: apply [[B_GETTER]]<[[P_OPENED]]>([[T0]])
// CHECK-NEXT: destroy_addr [[T0]]
// CHECK-NOT: witness_method
// CHECK: return
func modify(_ x: inout Int) {}
// Make sure we call the materializeForSet callback with the correct
// generic signature.
func modifyProperty<T : PropertyWithGetterSetter>(_ x: inout T) {
modify(&x.b)
}
// CHECK-LABEL: sil hidden @_TF9protocols14modifyPropertyuRxS_24PropertyWithGetterSetterrFRxT_
// CHECK: [[SELF_BOX:%.*]] = alloc_box $T
// CHECK: [[SELF:%.*]] = project_box %1 : $@box T
// CHECK: [[MODIFY_FN:%.*]] = function_ref @_TF9protocols6modifyFRSiT_
// CHECK: [[WITNESS_FN:%.*]] = witness_method $T, #PropertyWithGetterSetter.b!materializeForSet.1
// CHECK: [[RESULT:%.*]] = apply [[WITNESS_FN]]<T>
// CHECK: [[TEMPORARY:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[RESULT]]
// CHECK: [[TEMPORARY_ADDR_TMP:%.*]] = pointer_to_address [[TEMPORARY]] : $Builtin.RawPointer to $*Int
// CHECK: [[TEMPORARY_ADDR:%.*]] = mark_dependence [[TEMPORARY_ADDR_TMP]] : $*Int on [[SELF]] : $*T
// CHECK: apply [[MODIFY_FN]]([[TEMPORARY_ADDR]])
// CHECK: switch_enum [[CALLBACK]] : $Optional<Builtin.RawPointer>, case #Optional.some!enumelt.1: bb1, case #Optional.none!enumelt: bb2
// CHECK: bb1([[CALLBACK_ADDR:%.*]] : $Builtin.RawPointer):
// CHECK: [[CALLBACK:%.*]] = pointer_to_thin_function [[CALLBACK_ADDR]]
// CHECK: [[METATYPE:%.*]] = metatype $@thick T.Type
// CHECK: [[TEMPORARY:%.*]] = address_to_pointer [[TEMPORARY_ADDR]] : $*Int to $Builtin.RawPointer
// CHECK: apply [[CALLBACK]]<T>
// CHECK-LABEL: sil_witness_table hidden ClassWithGetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWC9protocols15ClassWithGetterS_18PropertyWithGetterS_FS1_g1aSi
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetterSetter module protocols {
// CHECK-NEXT: method #PropertyWithGetterSetter.b!getter.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_g1bSi
// CHECK-NEXT: method #PropertyWithGetterSetter.b!setter.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_s1bSi
// CHECK-NEXT: method #PropertyWithGetterSetter.b!materializeForSet.1: @_TTWC9protocols21ClassWithGetterSetterS_24PropertyWithGetterSetterS_FS1_m1bSi
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden ClassWithGetterSetter: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWC9protocols21ClassWithGetterSetterS_18PropertyWithGetterS_FS1_g1aSi
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWV9protocols24StructWithStoredPropertyS_18PropertyWithGetterS_FS1_g1aSi
// CHECK-NEXT: }
// CHECK-LABEL: sil_witness_table hidden StructWithStoredClassProperty: PropertyWithGetter module protocols {
// CHECK-NEXT: method #PropertyWithGetter.a!getter.1: @_TTWV9protocols29StructWithStoredClassPropertyS_18PropertyWithGetterS_FS1_g1aSi
// CHECK-NEXT: }
| apache-2.0 | 269129fcaf7e2eb56dd52b7df2c22d61 | 47.897778 | 248 | 0.637929 | 3.779457 | false | false | false | false |
producthunt/PHImageKit | PHImageKit/PHDownload.swift | 1 | 2545 | //
// PHDownloadObject.swift
// PHImageKit
//
// Copyright (c) 2016 Product Hunt (http://producthunt.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
class PHDownload {
fileprivate var callbacks = [String:PHCallback]()
fileprivate var task : URLSessionDataTask
fileprivate var data = NSMutableData()
init(task: URLSessionDataTask) {
self.task = task
}
func addCallback(_ callback:PHCallback) -> String {
let key = "\(task.currentRequest?.url?.absoluteString ?? "Unknown")-\(Date().timeIntervalSince1970)";
callbacks[key] = callback;
return key;
}
func failure(_ error: NSError) {
for (_, callback) in callbacks {
callback.completion(nil, error)
}
}
func success() {
let imageObject = PHImageObject(data: data as Data)
let error : NSError? = imageObject != nil ? nil : NSError.ik_invalidDataError()
for (_, callback) in callbacks {
callback.completion(imageObject, error)
}
}
func progress(_ newData: Data, contentLenght: UInt) {
data.append(newData as Data)
let percent = CGFloat(UInt(data.length)/contentLenght)
for (_, callback) in callbacks {
callback.progress(percent)
}
}
func cancel(_ key: String) -> Bool {
callbacks.removeValue(forKey: key)
if callbacks.count > 0 {
return false
}
task.cancel()
return true
}
}
| mit | 0b2831ef172d67145d0ff606eca3fdd3 | 29.297619 | 109 | 0.667583 | 4.610507 | false | false | false | false |
jcfausto/transit-app | TransitApp/TransitApp/Segment.swift | 1 | 1923 | //
// Segment.swift
// TransitApp
//
// Created by Julio Cesar Fausto on 24/02/16.
// Copyright © 2016 Julio Cesar Fausto. All rights reserved.
//
import Foundation
import UIKit
import Unbox
struct Segment {
var name: String?
var numStops: Int
var description: String?
var stops: [Stop]
var travelMode: String
var color: UIColor
var iconUrl: String
var polyline: String
init(name: String, numStops: Int, description: String, stops: [Stop],
travelMode: String, color: UIColor, iconUrl: String, polyline: String)
{
self.name = name
self.numStops = numStops
self.description = description
self.stops = stops
self.travelMode = travelMode
self.color = color
self.iconUrl = iconUrl
self.polyline = polyline
}
}
// MARK: extensions
extension Segment: Unboxable {
init(unboxer: Unboxer) {
self.name = unboxer.unbox("name")
self.numStops = unboxer.unbox("num_stops")
self.description = unboxer.unbox("description")
self.stops = unboxer.unbox("stops")
self.travelMode = unboxer.unbox("travel_mode")
self.color = UIColor(hexString: unboxer.unbox("color"))
self.iconUrl = unboxer.unbox("icon_url")
self.polyline = unboxer.unbox("polyline")
}
}
// MARK: segment's helper functions
extension Segment {
/**
Verifies if the segment is a segment where its stops are equal.
This means that this is a segmente where the person will be stopped
doing something like a car setup, bike picking, etc.
*/
func isSetupStop() -> Bool {
var areEqual: Bool = false
if (stops.count == 2) {
let stopOne = stops[0]
let stopTwo = stops[1]
areEqual = stopOne == stopTwo
return areEqual
}
return areEqual
}
} | mit | 2d059de03406cc3391df526659aa0e20 | 24.302632 | 78 | 0.610302 | 4.271111 | false | false | false | false |
Harley-xk/SimpleDataKit | Example/Pods/Comet/Comet/Classes/PinyinIndexer.swift | 1 | 2536 | //
// PinyinIndexer.swift
// Comet
//
// Created by Harley.xk on 16/11/8.
//
//
import UIKit
/// 索引器对象协议,用来告知索引器需要转换为拼音的属性
public protocol PinyinIndexable {
var valueToPinyin: String { get }
}
/// 拼音索引器,将指定的对象数组按照指定属性进行拼音首字母排序并创建索引
open class PinyinIndexer<T: PinyinIndexable> {
private var objectList: [T]
private var propertyName: String
/// 处理完毕的对象数组,按索引分组
open var indexedObjects = [[T]]()
/// 处理完毕的索引数组(拼音首字母)
open var indexedTitles = [String]()
/// 创建索引器实例
///
/// - Parameters:
/// - objects: 需要索引的对象数组
/// - property: 索引依据的属性键值,属性必须为 String 类型
public init(objects: [T], property: String) {
objectList = objects
propertyName = property
self.indexObjects()
}
private func indexObjects() {
// 按索引分组
let theCollation = UILocalizedIndexedCollation.current()
let indexArray = [PinyinIndex<T>]();
for object in self.objectList {
let index = PinyinIndex(fromObject: object, property: propertyName)
let section = theCollation.section(for: index, collationStringSelector: #selector(PinyinIndex<T>.pinyin))
index.sectionNumber = section
}
let sortedIndexArray = indexArray.sorted { (index1, index2) -> Bool in
return index1.name > index2.name
}
let sectionCount = theCollation.sectionTitles.count
for i in 0 ..< sectionCount {
var sectionArray = [T]()
for j in 0 ..< sortedIndexArray.count {
let index = sortedIndexArray[j]
if index.sectionNumber == i {
sectionArray.append(index.object)
}
}
if sectionArray.count > 0 {
indexedObjects.append(sectionArray)
indexedTitles.append(theCollation.sectionTitles[i])
}
}
}
}
class PinyinIndex<T: PinyinIndexable> {
var object: T
var name: String
var sectionNumber: Int = 0
init(fromObject obj: T, property: String) {
object = obj
name = obj.valueToPinyin
}
@objc func pinyin() -> String {
return name.pinyin(.firstLetter)
}
}
| mit | 3f8aef0408559bd7d28cba8b466656cc | 25.206897 | 117 | 0.576754 | 4.230056 | false | false | false | false |
tkremenek/swift | test/diagnostics/educational-notes.swift | 21 | 3401 | // RUN: not %target-swift-frontend -color-diagnostics -diagnostic-style=llvm -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace
// RUN: not %target-swift-frontend -no-color-diagnostics -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --match-full-lines --strict-whitespace --check-prefix=NO-COLOR
// RUN: not %target-swift-frontend -diagnostic-style=swift -print-educational-notes -diagnostic-documentation-path %S/test-docs/ -typecheck %s 2>&1 | %FileCheck %s --check-prefix=CHECK-DESCRIPTIVE
// A diagnostic with no educational notes
let x = 1 +
// CHECK:{{.*}}[0m[0;1;31merror: [0m[1mexpected expression after operator
// CHECK-NOT: {{-+$}}
// NO-COLOR:{{.*}}error: expected expression after operator
// NO-COLOR-NOT: {{-+$}}
// A diagnostic with an educational note using supported markdown features
extension (Int, Int) {}
// CHECK:{{.*}}[0m[0;1;31merror: [0m[1mnon-nominal type '(Int, Int)' cannot be extended
// CHECK-NEXT:[0mextension (Int, Int) {}
// CHECK-NEXT:[0;1;32m^ ~~~~~~~~~~
// CHECK-NEXT:[0m[0m[1mNominal Types[0m
// CHECK-NEXT:--------------
// CHECK-EMPTY:
// CHECK-NEXT:Nominal types documentation content. This is a paragraph
// CHECK-EMPTY:
// CHECK-NEXT: blockquote
// CHECK-NEXT: {{$}}
// CHECK-NEXT: - item 1
// CHECK-NEXT: - item 2
// CHECK-NEXT: - item 3
// CHECK-NEXT: {{$}}
// CHECK-NEXT: let x = 42
// CHECK-NEXT: if x > 0 {
// CHECK-NEXT: print("positive")
// CHECK-NEXT: }
// CHECK-NEXT: {{$}}
// CHECK-NEXT:Type 'MyClass'
// CHECK-EMPTY:
// CHECK-NEXT:[Swift](swift.org)
// CHECK-EMPTY:
// CHECK-NEXT:[0m[1mbold[0m italics
// CHECK-NEXT:--------------
// CHECK-NEXT:[0m[1mHeader 1[0m
// CHECK-NEXT:[0m[1mHeader 3[0m
// NO-COLOR:{{.*}}error: non-nominal type '(Int, Int)' cannot be extended
// NO-COLOR-NEXT:extension (Int, Int) {}
// NO-COLOR-NEXT:^ ~~~~~~~~~~
// NO-COLOR-NEXT:Nominal Types
// NO-COLOR-NEXT:--------------
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:Nominal types documentation content. This is a paragraph
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT: blockquote
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT: - item 1
// NO-COLOR-NEXT: - item 2
// NO-COLOR-NEXT: - item 3
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT: let x = 42
// NO-COLOR-NEXT: if x > 0 {
// NO-COLOR-NEXT: print("positive")
// NO-COLOR-NEXT: }
// NO-COLOR-NEXT: {{$}}
// NO-COLOR-NEXT:Type 'MyClass'
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:[Swift](swift.org)
// NO-COLOR-EMPTY:
// NO-COLOR-NEXT:bold italics
// NO-COLOR-NEXT:--------------
// NO-COLOR-NEXT:Header 1
// NO-COLOR-NEXT:Header 3
// CHECK-DESCRIPTIVE: educational-notes.swift
// CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note
// CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {}
// CHECK-DESCRIPTIVE-NEXT: | ^ error: expected expression after operator
// CHECK-DESCRIPTIVE-NEXT: |
// CHECK-DESCRIPTIVE: educational-notes.swift
// CHECK-DESCRIPTIVE-NEXT: | // A diagnostic with an educational note
// CHECK-DESCRIPTIVE-NEXT: | extension (Int, Int) {}
// CHECK-DESCRIPTIVE-NEXT: | ~~~~~~~~~~
// CHECK-DESCRIPTIVE-NEXT: | ^ error: non-nominal type '(Int, Int)' cannot be extended
// CHECK-DESCRIPTIVE-NEXT: |
// CHECK-DESCRIPTIVE-NEXT: Nominal Types
// CHECK-DESCRIPTIVE-NEXT: -------------
| apache-2.0 | 25250e7de76fc08db2edd24191895fd1 | 39.488095 | 224 | 0.648339 | 3.123049 | false | false | false | false |
xwu/swift | test/SILGen/dynamic_lookup.swift | 13 | 20413 | // RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// RUN: %target-swift-emit-silgen -module-name dynamic_lookup -enable-objc-interop -parse-as-library -disable-objc-attr-requires-foundation-module %s | %FileCheck %s --check-prefix=GUARANTEED
class X {
@objc func f() { }
@objc class func staticF() { }
@objc var value: Int {
return 17
}
@objc subscript (i: Int) -> Int {
get {
return i
}
set {}
}
@objc func hasDefaultParam(_ x: Int = 0) {}
}
@objc protocol P {
func g()
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F
func direct_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #X.f!foreign : (X) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.f!()
}
// CHECK: } // end sil function '$s14dynamic_lookup15direct_to_class{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F
func direct_to_protocol(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
// CHECK: [[OPENED_ARG:%[0-9]+]] = open_existential_ref [[ARG]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[OPENED_ARG_COPY:%.*]] = copy_value [[OPENED_ARG]]
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENED_ARG_COPY]] : $@opened({{.*}}) AnyObject, #P.g!foreign : <Self where Self : P> (Self) -> () -> (), $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: apply [[METHOD]]([[OPENED_ARG_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: destroy_value [[OPENED_ARG_COPY]]
obj.g!()
}
// CHECK: } // end sil function '$s14dynamic_lookup18direct_to_protocol{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup23direct_to_static_method{{[_0-9a-zA-Z]*}}F
func direct_to_static_method(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK-NEXT: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK-NEXT: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: end_access [[READ]]
// CHECK-NEXT: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK-NEXT: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened([[UUID:".*"]]) AnyObject).Type
// CHECK-NEXT: [[METHOD:%[0-9]+]] = objc_method [[OPENMETA]] : $@thick (@opened([[UUID]]) AnyObject).Type, #X.staticF!foreign : (X.Type) -> () -> (), $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: apply [[METHOD]]([[OPENMETA]]) : $@convention(objc_method) (@thick (@opened([[UUID]]) AnyObject).Type) -> ()
// CHECK: destroy_value [[OBJBOX]]
type(of: obj).staticF!()
}
// } // end sil function '_TF14dynamic_lookup23direct_to_static_method{{.*}}'
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup12opt_to_class{{[_0-9a-zA-Z]*}}F
func opt_to_class(_ obj: AnyObject) {
// CHECK: bb0([[ARG:%.*]] : @guaranteed $AnyObject):
var obj = obj
// CHECK: [[EXISTBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[EXISTBOX]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[PBOBJ]]
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBOPT:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[EXISTVAL:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_SELF:%[0-9]*]] = open_existential_ref [[EXISTVAL]]
// CHECK: [[OPT_TMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.f!foreign, [[HASBB:[a-zA-z0-9]+]], [[NOBB:[a-zA-z0-9]+]]
// Has method BB:
// CHECK: [[HASBB]]([[UNCURRIED:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()):
// CHECK: [[OBJ_SELF_COPY:%.*]] = copy_value [[OBJ_SELF]]
// CHECK: [[PARTIAL:%[0-9]+]] = partial_apply [callee_guaranteed] [[UNCURRIED]]([[OBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> ()
// CHECK: [[THUNK_PAYLOAD:%.*]] = init_enum_data_addr [[OPT_TMP]]
// CHECK: store [[PARTIAL]] to [init] [[THUNK_PAYLOAD]]
// CHECK: inject_enum_addr [[OPT_TMP]] : $*Optional<@callee_guaranteed () -> ()>, #Optional.some!enumelt
// CHECK: br [[CONTBB:[a-zA-Z0-9]+]]
// No method BB:
// CHECK: [[NOBB]]:
// CHECK: inject_enum_addr [[OPT_TMP]] : {{.*}}, #Optional.none!enumelt
// CHECK: br [[CONTBB]]
// Continuation block
// CHECK: [[CONTBB]]:
// CHECK: [[OPT:%.*]] = load [take] [[OPT_TMP]]
// CHECK: store [[OPT]] to [init] [[PBOPT]] : $*Optional<@callee_guaranteed () -> ()>
// CHECK: dealloc_stack [[OPT_TMP]]
var of: (() -> ())! = obj.f
// Exit
// CHECK: destroy_value [[OBJ_SELF]] : $@opened({{".*"}}) AnyObject
// CHECK: destroy_value [[OPTBOX]] : ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: destroy_value [[EXISTBOX]] : ${ var AnyObject }
// CHECK: [[RESULT:%[0-9]+]] = tuple ()
// CHECK: return [[RESULT]] : $()
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup20forced_without_outer{{[_0-9a-zA-Z]*}}F
func forced_without_outer(_ obj: AnyObject) {
// CHECK: dynamic_method_br
var f = obj.f!
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup20opt_to_static_method{{[_0-9a-zA-Z]*}}F
func opt_to_static_method(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJBOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJBOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[OPTBOX:%[0-9]+]] = alloc_box ${ var Optional<@callee_guaranteed () -> ()> }
// CHECK: [[PBO:%.*]] = project_box [[OPTBOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJCOPY:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJMETA:%[0-9]+]] = existential_metatype $@thick AnyObject.Type, [[OBJCOPY]] : $AnyObject
// CHECK: [[OPENMETA:%[0-9]+]] = open_existential_metatype [[OBJMETA]] : $@thick AnyObject.Type to $@thick (@opened
// CHECK: [[OBJCMETA:%[0-9]+]] = thick_to_objc_metatype [[OPENMETA]]
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<@callee_guaranteed () -> ()>
// CHECK: dynamic_method_br [[OBJCMETA]] : $@objc_metatype (@opened({{".*"}}) AnyObject).Type, #X.staticF!foreign, [[HASMETHOD:[A-Za-z0-9_]+]], [[NOMETHOD:[A-Za-z0-9_]+]]
var optF: (() -> ())! = type(of: obj).staticF
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
func opt_to_property(_ obj: AnyObject) {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: project_box [[INT_BOX]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.foreign, bb1, bb2
// CHECK: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// CHECK: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// CHECK: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]]) : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[BOUND_METHOD]]
// CHECK: [[VALUE:%[0-9]+]] = apply [[B]]() : $@callee_guaranteed () -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[VALUE]] to [trivial] [[VALUETEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[BOUND_METHOD]]
// CHECK: br bb3
var i: Int = obj.value!
}
// CHECK: } // end sil function '$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden [ossa] @$s14dynamic_lookup15opt_to_property{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[INT_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: project_box [[INT_BOX]]
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[RAWOBJ_SELF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[RAWOBJ_SELF]] : $@opened({{.*}}) AnyObject, #X.value!getter.foreign, bb1, bb2
// GUARANTEED: bb1([[METHOD:%[0-9]+]] : $@convention(objc_method) (@opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[RAWOBJ_SELF_COPY:%.*]] = copy_value [[RAWOBJ_SELF]]
// GUARANTEED: [[BOUND_METHOD:%[0-9]+]] = partial_apply [callee_guaranteed] [[METHOD]]([[RAWOBJ_SELF_COPY]])
// GUARANTEED: [[BEGIN_BORROW:%.*]] = begin_borrow [[BOUND_METHOD]]
// GUARANTEED: [[VALUE:%[0-9]+]] = apply [[BEGIN_BORROW]]
// GUARANTEED: end_borrow [[BEGIN_BORROW]]
// GUARANTEED: [[VALUETEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[VALUE]] to [trivial] [[VALUETEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[BOUND_METHOD]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
func direct_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: alloc_box ${ var Int }
// CHECK: project_box
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]{{.*}}some
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
var x: Int = obj[i]!
}
// CHECK: } // end sil function '$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F'
// GUARANTEED-LABEL: sil hidden [ossa] @$s14dynamic_lookup19direct_to_subscript{{[_0-9a-zA-Z]*}}F
// GUARANTEED: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : $Int):
// GUARANTEED: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// GUARANTEED: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// GUARANTEED: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// GUARANTEED: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// GUARANTEED: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// GUARANTEED: [[PBI:%.*]] = project_box [[I_BOX]]
// GUARANTEED: store [[I]] to [trivial] [[PBI]] : $*Int
// GUARANTEED: alloc_box ${ var Int }
// GUARANTEED: project_box
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// GUARANTEED: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// GUARANTEED: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// GUARANTEED: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// GUARANTEED: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// GUARANTEED: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// GUARANTEED: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.foreign, bb1, bb2
// GUARANTEED: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// GUARANTEED: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// GUARANTEED: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]])
// GUARANTEED: [[BORROW:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// GUARANTEED: [[RESULT:%[0-9]+]] = apply [[BORROW]]([[I]])
// GUARANTEED: end_borrow [[BORROW]]
// GUARANTEED: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// GUARANTEED: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// GUARANTEED: inject_enum_addr [[OPTTEMP]]{{.*}}some
// GUARANTEED: destroy_value [[GETTER_WITH_SELF]]
// GUARANTEED: br bb3
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup16opt_to_subscript{{[_0-9a-zA-Z]*}}F
func opt_to_subscript(_ obj: AnyObject, i: Int) {
var obj = obj
var i = i
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject, [[I:%[0-9]+]] : $Int):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[I_BOX:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PBI:%.*]] = project_box [[I_BOX]]
// CHECK: store [[I]] to [trivial] [[PBI]] : $*Int
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[OBJ_REF:%[0-9]+]] = open_existential_ref [[OBJ]] : $AnyObject to $@opened({{.*}}) AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBI]]
// CHECK: [[I:%[0-9]+]] = load [trivial] [[READ]] : $*Int
// CHECK: [[OPTTEMP:%.*]] = alloc_stack $Optional<Int>
// CHECK: dynamic_method_br [[OBJ_REF]] : $@opened({{.*}}) AnyObject, #X.subscript!getter.foreign, bb1, bb2
// CHECK: bb1([[GETTER:%[0-9]+]] : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int):
// CHECK: [[OBJ_REF_COPY:%.*]] = copy_value [[OBJ_REF]]
// CHECK: [[GETTER_WITH_SELF:%[0-9]+]] = partial_apply [callee_guaranteed] [[GETTER]]([[OBJ_REF_COPY]]) : $@convention(objc_method) (Int, @opened({{.*}}) AnyObject) -> Int
// CHECK: [[B:%.*]] = begin_borrow [[GETTER_WITH_SELF]]
// CHECK: [[RESULT:%[0-9]+]] = apply [[B]]([[I]]) : $@callee_guaranteed (Int) -> Int
// CHECK: end_borrow [[B]]
// CHECK: [[RESULTTEMP:%.*]] = init_enum_data_addr [[OPTTEMP]]
// CHECK: store [[RESULT]] to [trivial] [[RESULTTEMP]]
// CHECK: inject_enum_addr [[OPTTEMP]]
// CHECK: destroy_value [[GETTER_WITH_SELF]]
// CHECK: br bb3
obj[i]
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ obj: AnyObject) -> X {
var obj = obj
// CHECK: bb0([[OBJ:%[0-9]+]] : @guaranteed $AnyObject):
// CHECK: [[OBJ_BOX:%[0-9]+]] = alloc_box ${ var AnyObject }
// CHECK: [[PBOBJ:%[0-9]+]] = project_box [[OBJ_BOX]]
// CHECK: [[OBJ_COPY:%.*]] = copy_value [[OBJ]]
// CHECK: store [[OBJ_COPY]] to [init] [[PBOBJ]] : $*AnyObject
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOBJ]]
// CHECK: [[OBJ:%[0-9]+]] = load [copy] [[READ]] : $*AnyObject
// CHECK: [[X:%[0-9]+]] = unconditional_checked_cast [[OBJ]] : $AnyObject to X
// CHECK: destroy_value [[OBJ_BOX]] : ${ var AnyObject }
// CHECK: return [[X]] : $X
return obj as! X
}
@objc class Juice { }
@objc protocol Fruit {
@objc optional var juice: Juice { get }
}
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup7consumeyyAA5Fruit_pF
// CHECK: bb0(%0 : @guaranteed $Fruit):
// CHECK: [[BOX:%.*]] = alloc_stack $Optional<Juice>
// CHECK: dynamic_method_br [[SELF:%.*]] : $@opened("{{.*}}") Fruit, #Fruit.juice!getter.foreign, bb1, bb2
// CHECK: bb1([[FN:%.*]] : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]]([[SELF_COPY]]) : $@convention(objc_method) (@opened("{{.*}}") Fruit) -> @autoreleased Juice
// CHECK: [[B:%.*]] = begin_borrow [[METHOD]]
// CHECK: [[RESULT:%.*]] = apply [[B]]() : $@callee_guaranteed () -> @owned Juice
// CHECK: end_borrow [[B]]
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt
// CHECK: store [[RESULT]] to [init] [[PAYLOAD]]
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.some!enumelt
// CHECK: destroy_value [[METHOD]]
// CHECK: br bb3
// CHECK: bb2:
// CHECK: inject_enum_addr [[BOX]] : $*Optional<Juice>, #Optional.none!enumelt
// CHECK: br bb3
// CHECK: bb3:
// CHECK: return
func consume(_ fruit: Fruit) {
_ = fruit.juice
}
// rdar://problem/29249513 -- looking up an IUO member through AnyObject
// produces a Foo!? type. The SIL verifier did not correctly consider Optional
// to be the lowering of IUO (which is now eliminated by SIL lowering).
@objc protocol IUORequirement {
var iuoProperty: AnyObject! { get }
}
func getIUOPropertyDynamically(x: AnyObject) -> Any {
return x.iuoProperty
}
// SR-11648
// CHECK-LABEL: sil hidden [ossa] @$s14dynamic_lookup24testAnyObjectWithDefaultyyyXlF
func testAnyObjectWithDefault(_ x: AnyObject) {
// CHECK: function_ref default argument 0 of X.hasDefaultParam(_:)
// CHECK: [[DEFGEN:%[0-9]+]] = function_ref @$s14dynamic_lookup1XC15hasDefaultParamyySiFfA_ : $@convention(thin) () -> Int
// CHECK: [[DEFARG:%[0-9]+]] = apply %4() : $@convention(thin) () -> Int
// CHECK: [[METHOD:%[0-9]+]] = objc_method [[OPENEDX:%[0-9]+]] : $@opened("{{.*}}") AnyObject, #X.hasDefaultParam!foreign : (X) -> (Int) -> (), $@convention(objc_method) (Int, @opened("{{.*}}") AnyObject) -> ()
// CHECK: apply [[METHOD]]([[DEFARG]], [[OPENEDX]])
x.hasDefaultParam()
}
| apache-2.0 | 059151d05d4eaea375ca6cd13fdb45ea | 54.17027 | 227 | 0.571646 | 3.215658 | false | false | false | false |
TakuSemba/DribbbleSwiftApp | DribbbleSwiftApp/Color.swift | 1 | 1310 | //
// Color.swift
// DribbbleSwiftApp
//
// Created by TakuSemba on 2016/05/31.
// Copyright © 2016年 TakuSemba. All rights reserved.
//
import UIKit
import Foundation
extension UIColor {
class func hexStr (hexStr : NSString, alpha : CGFloat) -> UIColor {
var hexStr = hexStr;
hexStr = hexStr.stringByReplacingOccurrencesOfString("#", withString: "")
let scanner = NSScanner(string: hexStr as String)
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat(color & 0x0000FF) / 255.0
return UIColor(red:r,green:g,blue:b,alpha:alpha)
} else {
print("invalid hex string", terminator: "")
return UIColor.whiteColor();
}
}
class func blueishWhiteColor() -> UIColor {
return UIColor.hexStr("ecfafb", alpha: 1)
}
class func blueishBlackColor() -> UIColor {
return UIColor.hexStr("263238", alpha: 1)
}
class func pinkColor() -> UIColor {
return UIColor.hexStr("F06292", alpha: 1)
}
class func blueishDarkerWhiteColor() -> UIColor {
return UIColor.hexStr("bcc8c8", alpha: 1)
}
} | apache-2.0 | 377e90dc7ebd60f80c80a8addaffc070 | 28.727273 | 81 | 0.591431 | 4.021538 | false | false | false | false |
openhab/openhab.ios | openHABWatch Extension/openHABWatch Extension/Model/ObservableOpenHABSitemapPage.swift | 1 | 4006 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import Foundation
import Fuzi
import OpenHABCore
import os.log
class ObservableOpenHABSitemapPage: NSObject {
var sendCommand: ((_ item: OpenHABItem, _ command: String?) -> Void)?
var widgets: [ObservableOpenHABWidget] = []
var pageId = ""
var title = ""
var link = ""
var leaf = false
init(pageId: String, title: String, link: String, leaf: Bool, widgets: [ObservableOpenHABWidget]) {
super.init()
self.pageId = pageId
self.title = title
self.link = link
self.leaf = leaf
var tempWidgets = [ObservableOpenHABWidget]()
tempWidgets.flatten(widgets)
self.widgets = tempWidgets
self.widgets.forEach {
$0.sendCommand = { [weak self] item, command in
self?.sendCommand(item, commandToSend: command)
}
}
}
init(xml xmlElement: XMLElement) {
super.init()
for child in xmlElement.children {
switch child.tag {
case "widget": widgets.append(ObservableOpenHABWidget(xml: child))
case "id": pageId = child.stringValue
case "title": title = child.stringValue
case "link": link = child.stringValue
case "leaf": leaf = child.stringValue == "true" ? true : false
default: break
}
}
var tempWidgets = [ObservableOpenHABWidget]()
tempWidgets.flatten(widgets)
widgets = tempWidgets
widgets.forEach {
$0.sendCommand = { [weak self] item, command in
self?.sendCommand(item, commandToSend: command)
}
}
}
init(pageId: String, title: String, link: String, leaf: Bool, expandedWidgets: [ObservableOpenHABWidget]) {
super.init()
self.pageId = pageId
self.title = title
self.link = link
self.leaf = leaf
widgets = expandedWidgets
widgets.forEach {
$0.sendCommand = { [weak self] item, command in
self?.sendCommand(item, commandToSend: command)
}
}
}
private func sendCommand(_ item: OpenHABItem?, commandToSend command: String?) {
guard let item = item else { return }
os_log("SitemapPage sending command %{PUBLIC}@ to %{PUBLIC}@", log: OSLog.remoteAccess, type: .info, command ?? "", item.name)
sendCommand?(item, command)
}
}
extension ObservableOpenHABSitemapPage {
struct CodingData: Decodable {
let pageId: String?
let title: String?
let link: String?
let leaf: Bool?
let widgets: [ObservableOpenHABWidget.CodingData]?
private enum CodingKeys: String, CodingKey {
case pageId = "id"
case title
case link
case leaf
case widgets
}
}
}
extension ObservableOpenHABSitemapPage.CodingData {
var openHABSitemapPage: ObservableOpenHABSitemapPage {
let mappedWidgets = widgets?.map(\.openHABWidget) ?? []
return ObservableOpenHABSitemapPage(pageId: pageId ?? "", title: title ?? "", link: link ?? "", leaf: leaf ?? false, widgets: mappedWidgets)
}
}
extension ObservableOpenHABSitemapPage {
func filter(_ isIncluded: (ObservableOpenHABWidget) throws -> Bool) rethrows -> ObservableOpenHABSitemapPage {
let filteredOpenHABSitemapPage = ObservableOpenHABSitemapPage(
pageId: pageId,
title: title,
link: link,
leaf: leaf,
expandedWidgets: try widgets.filter(isIncluded)
)
return filteredOpenHABSitemapPage
}
}
| epl-1.0 | a561135d76c137af5fd212693798e4a6 | 32.107438 | 148 | 0.61333 | 4.885366 | false | false | false | false |
DavidSanf0rd/FireRecord-1 | Example/FireRecord/ViewController.swift | 1 | 2062 | //
// ViewController.swift
// FireRecord
//
// Created by [email protected] on 08/09/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import FireRecord
import HandyJSON
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let user = User()
user.name = "Victor"
user.photo = FirebaseImage(#imageLiteral(resourceName: "Image"))
user.save { error in
print(error?.localizedDescription ?? "No type of error")
}
User.findFirst(when: .anyChange) { user in
user.name = "Mangueira"
user.update(completion: { error in
print(error?.localizedDescription ?? "No type of error")
})
}
User.order(by: \User.name).find(when: .anyChange) { users in
users.forEach { print($0.name ?? "Empty") }
}
User.order(by: \User.name)
.start(atValue: "Alisson")
.end(atValue: "Victor")
.find(when: .anyChange) { users in
users.forEach { print($0.name ?? "Empty") }
}
User.findLast(when: .anyChange) { user in
print(user.name ?? "Empty")
}
User.findFirst(when: .propertyAdded) { user in
print(user.name ?? "Empty")
}
User.order(by: \User.name).where(value: "Alisson").observeAll(when: .anyChange) { users in
users.forEach { print($0.name ?? "Empty") }
}
User.order(by: \User.name).observeFindFirst(when: .anyChange) { user in
print(user.name ?? "Empty")
}
User.observeAll(when: .propertyRemoved) { users in
users.forEach { print($0.name ?? "Empty") }
}
}
}
class User: FireRecord {
var name: String?
var photo: FirebaseImage?
init(name: String) { self.name = name }
required public init() {}
}
class Professional: FireRecord {
var name: String?
var phone: String?
}
| mit | d727dc22c1b46f3613b63af588e99d49 | 27.638889 | 98 | 0.560136 | 3.920152 | false | false | false | false |
proversity-org/edx-app-ios | Source/CourseOutline.swift | 1 | 8664 | //
// CourseOutline.swift
// edX
//
// Created by Akiva Leffert on 4/29/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public typealias CourseBlockID = String
public struct CourseOutline {
enum Fields : String, RawStringExtractable {
case Root = "root"
case Blocks = "blocks"
case BlockCounts = "block_counts"
case BlockType = "type"
case Descendants = "descendants"
case DisplayName = "display_name"
case DueDate = "due"
case Format = "format"
case Graded = "graded"
case LMSWebURL = "lms_web_url"
case StudentViewMultiDevice = "student_view_multi_device"
case StudentViewURL = "student_view_url"
case StudentViewData = "student_view_data"
case Summary = "summary"
case MinifiedBlockID = "block_id"
}
public let root : CourseBlockID
public let blocks : [CourseBlockID:CourseBlock]
private let parents : [CourseBlockID:CourseBlockID]
public init(root : CourseBlockID, blocks : [CourseBlockID:CourseBlock]) {
self.root = root
self.blocks = blocks
var parents : [CourseBlockID:CourseBlockID] = [:]
for (blockID, block) in blocks {
for child in block.children {
parents[child] = blockID
}
}
self.parents = parents
}
public init?(json : JSON) {
if let root = json[Fields.Root].string, let blocks = json[Fields.Blocks].dictionaryObject {
var validBlocks : [CourseBlockID:CourseBlock] = [:]
for (blockID, blockBody) in blocks {
let body = JSON(blockBody)
let webURL = NSURL(string: body[Fields.LMSWebURL].stringValue)
let children = body[Fields.Descendants].arrayObject as? [String] ?? []
let name = body[Fields.DisplayName].string
let dueDate = body[Fields.DueDate].string
let blockURL = body[Fields.StudentViewURL].string.flatMap { NSURL(string:$0) }
let format = body[Fields.Format].string
let typeName = body[Fields.BlockType].string ?? ""
let multiDevice = body[Fields.StudentViewMultiDevice].bool ?? false
let blockCounts : [String:Int] = (body[Fields.BlockCounts].object as? NSDictionary)?.mapValues {
$0 as? Int ?? 0
} ?? [:]
let graded = body[Fields.Graded].bool ?? false
let minifiedBlockID = body[Fields.MinifiedBlockID].string
var type : CourseBlockType
if let category = CourseBlock.Category(rawValue: typeName) {
switch category {
case CourseBlock.Category.Course:
type = .Course
case CourseBlock.Category.Chapter:
type = .Chapter
case CourseBlock.Category.Section:
type = .Section
case CourseBlock.Category.Unit:
type = .Unit
case CourseBlock.Category.HTML:
type = .HTML
case CourseBlock.Category.Problem:
type = .Problem
case CourseBlock.Category.Video :
let bodyData = (body[Fields.StudentViewData].object as? NSDictionary).map { [Fields.Summary.rawValue : $0 ] }
let summary = OEXVideoSummary(dictionary: bodyData ?? [:], videoID: blockID, name : name ?? Strings.untitled)
type = .Video(summary)
case CourseBlock.Category.Discussion:
// Inline discussion is in progress feature. Will remove this code when it's ready to ship
type = .Unknown(typeName)
if OEXConfig.shared().discussionsEnabled {
let bodyData = body[Fields.StudentViewData].object as? NSDictionary
let discussionModel = DiscussionModel(dictionary: bodyData ?? [:])
type = .Discussion(discussionModel)
}
}
}
else {
type = .Unknown(typeName)
}
validBlocks[blockID] = CourseBlock(
type: type,
children: children,
blockID: blockID,
minifiedBlockID: minifiedBlockID,
name: name,
dueDate: dueDate,
blockCounts : blockCounts,
blockURL : blockURL,
webURL: webURL,
format : format,
multiDevice : multiDevice,
graded : graded
)
}
self = CourseOutline(root: root, blocks: validBlocks)
}
else {
return nil
}
}
func parentOfBlockWithID(blockID : CourseBlockID) -> CourseBlockID? {
return self.parents[blockID]
}
}
public enum CourseBlockType {
case Unknown(String)
case Course
case Chapter // child of course
case Section // child of chapter
case Unit // child of section
case Video(OEXVideoSummary)
case Problem
case HTML
case Discussion(DiscussionModel)
public var asVideo : OEXVideoSummary? {
switch self {
case let .Video(summary):
return summary
default:
return nil
}
}
}
public class CourseBlock {
/// Simple list of known block categories strings
public enum Category : String {
case Chapter = "chapter"
case Course = "course"
case HTML = "html"
case Problem = "problem"
case Section = "sequential"
case Unit = "vertical"
case Video = "video"
case Discussion = "discussion"
}
public let type : CourseBlockType
public let blockID : CourseBlockID
/// This is the alpha numeric identifier at the end of the blockID above.
public let minifiedBlockID: String?
/// Children in the navigation hierarchy.
/// Note that this may be different than the block's list of children, server side
/// Since we flatten out the hierarchy for display
public let children : [CourseBlockID]
/// Title of block. Keep this private so people don't use it as the displayName by accident
private let name : String?
public let dueDate : String?
/// Actual title of the block. Not meant to be user facing - see displayName
public var internalName : String? {
return name
}
/// User visible name of the block.
public var displayName : String {
guard let name = name, !name.isEmpty else {
return Strings.untitled
}
return name
}
/// TODO: Match final API name
/// The type of graded component
public let format : String?
/// Mapping between block types and number of blocks of that type in this block's
/// descendants (recursively) for example ["video" : 3]
public let blockCounts : [String:Int]
/// Just the block content itself as a web page.
/// Suitable for embedding in a web view.
public let blockURL : NSURL?
/// If this is web content, can we actually display it.
public let multiDevice : Bool
/// A full web page for the block.
/// Suitable for opening in a web browser.
public let webURL : NSURL?
/// Whether or not the block is graded.
/// TODO: Match final API name
public let graded : Bool?
public init(type : CourseBlockType,
children : [CourseBlockID],
blockID : CourseBlockID,
minifiedBlockID: String?,
name : String?,
dueDate : String? = nil,
blockCounts : [String:Int] = [:],
blockURL : NSURL? = nil,
webURL : NSURL? = nil,
format : String? = nil,
multiDevice : Bool,
graded : Bool = false) {
self.type = type
self.children = children
self.name = name
self.dueDate = dueDate
self.blockCounts = blockCounts
self.blockID = blockID
self.minifiedBlockID = minifiedBlockID
self.blockURL = blockURL
self.webURL = webURL
self.graded = graded
self.format = format
self.multiDevice = multiDevice
}
}
| apache-2.0 | 82cfbc901e0d3e6764596cb4bf3ad1f9 | 34.654321 | 133 | 0.555286 | 5.222423 | false | false | false | false |
timd/ProiOSTableCollectionViews | Ch09/InCellDelegate/InCellTV/ViewController.swift | 1 | 2047 | //
// ViewController.swift
// InCellTV
//
// Created by Tim on 07/11/15.
// Copyright © 2015 Tim Duckett. All rights reserved.
//
import UIKit
protocol InCellButtonProtocol {
func didTapButtonInCell(cell: ButtonCell)
}
class ViewController: UIViewController, InCellButtonProtocol {
@IBOutlet var tableView: UITableView!
var tableData = [Int]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
setupData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController {
func setupData() {
for index in 0...125 {
tableData.append(index)
}
}
func didTapButtonInCell(cell: ButtonCell) {
let indexPathAtTap = tableView.indexPathForCell(cell)
let alert = UIAlertController(title: "Something happened!", message: "A button was tapped at row \(indexPathAtTap!.row)", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
}
extension ViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as! ButtonCell
cell.textLabel?.text = "Row \(tableData[indexPath.row])"
if cell.delegate == nil {
cell.delegate = self
}
return cell
}
}
| mit | bfbe67734c7b8649619d28e4d14c5e3a | 23.95122 | 153 | 0.644673 | 5.115 | false | false | false | false |
antonio081014/LeeCode-CodeBase | Swift/valid-palindrome.swift | 2 | 2212 | /**
* https://leetcode.com/problems/valid-palindrome/
*
*
*/
import Foundation
class Solution {
func isPalindrome(_ s: String) -> Bool {
let listofarray = s.lowercased().characters.map({"\($0)"})
var left = 0
var right = listofarray.count-1
while left < right {
// print("Outter: \(left) - \(right)")
if !isalphanumeric(listofarray[left]) {left += 1}
else if !isalphanumeric(listofarray[right]) {right -= 1}
else {
// print("Inner: \(left) - \(right)")
if listofarray[left] != listofarray[right] {return false}
else {
left += 1
right -= 1
}
}
}
return true
}
private func isalphanumeric2(_ s: String) -> Bool {
var characterSet = CharacterSet().union(CharacterSet.alphanumerics)
characterSet.invert()
return s.rangeOfCharacter(from: characterSet) == nil
}
private func isalphanumeric(_ s: String) -> Bool {
let pattern = "0123456789abcdefghijklmnopqrstuvwxyz"
return pattern.contains(s)
}
}
let solution = Solution()
print("\(solution.isPalindrome("race a car"))")
print("\(solution.isPalindrome("A man, a plan, a canal: Panama"))")
/**
* https://leetcode.com/problems/valid-palindrome/
*
*
*/
// Date: Sun May 3 16:00:23 PDT 2020
class Solution {
func isPalindrome(_ s: String) -> Bool {
let dict = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
// O(s.count)
let s = s.uppercased().filter { dict.contains($0) }
if s.isEmpty { return true }
var start = s.startIndex
var end = s.index(before: s.endIndex)
// print("\(s): \(start) - \(end)")
// O(s.count)
while start < end {
if !dict.contains(s[start]) { start = s.index(after: start) }
if !dict.contains(s[end]) { end = s.index(before: end) }
else if s[start] != s[end] { return false }
else {
start = s.index(after: start)
end = s.index(before: end)
}
}
return true
}
}
| mit | 20b8f76a62e5b8ee64f382bab7030e3d | 29.722222 | 75 | 0.529385 | 4.088725 | false | false | false | false |
macshome/cocoaCrypt | CocoaCrypt/CocoaCryptTests/CocoaCipherAnalyzerTests.swift | 1 | 2077 | //
// CocoaCipherAnalyzerTests.swift
// CocoaCipherAnalyzerTests
//
// Created by Josh Wisenbaker on 11/24/14.
// Copyright (c) 2014 Josh Wisenbaker. All rights reserved.
//
import Cocoa
import XCTest
class CocoaCipherAnalyzerTests: XCTestCase {
let cipherText = "Ubty lzm vz dy xzq j kzg dyrtqadtu, D rbdyn j vzzs rbdyv rz jen de dx rbtl tatq oqtee pbjqvte."
var testCryptogram: Cryptogram!
var testAnalyzer: CipherAnalyzer!
override func setUp() {
testCryptogram = Cryptogram(cipherText: cipherText)
testAnalyzer = CipherAnalyzer(cryptogram: testCryptogram)
}
func testCanInitCipherAnalyzer() {
XCTAssertNotNil(testAnalyzer, "Could not init the CipherAnalyzer!")
}
func testFrequencyAnalysis() {
testAnalyzer.frequencyAnalysis()
let qResult = testAnalyzer.cryptogram?.frequencyAnalysis?["Q"]
XCTAssert(qResult == 5, "Found the wrong number of the letter q. Expected: 5, Found: \(qResult!)")
XCTAssert(testAnalyzer.cryptogram?.hasCompletedFrequencyAnalysis == true, "Completion flag not set on frequency analysis.")
if let frequencyResults = testAnalyzer.cryptogram?.frequencyAnalysis? {
for (key, value) in frequencyResults {
if value == 0 {
XCTFail("There shouldn't be any 0 values in the frequency analysis and we found one.")
}
}
}
}
func testFrequencyAnalyzerPerformance() {
self.measureBlock() {
self.testAnalyzer.frequencyAnalysis()
}
}
func testWordList() {
testAnalyzer.generateWordList()
XCTAssertNotNil(testAnalyzer.cryptogram?.wordList, "Word list should not be nil")
let firstResult = testAnalyzer.cryptogram?.wordList?["dyrtqadtu"]
XCTAssert(firstResult == 9, "Found the wrong count of the word dyrtqadtu. Expected: 9, Found: \(firstResult!)")
XCTAssert(testAnalyzer.cryptogram?.hasGeneratedWordList == true, "Completion flag not set on word list generator.")
}
}
| mit | c9ba022d76f65a7a4fe283a949ac3fc2 | 31.453125 | 131 | 0.670679 | 4.564835 | false | true | false | false |
stulevine/firefox-ios | Storage/SQL/SQLiteReadingList.swift | 1 | 2368 | /* 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
/**
* The SQLite-backed implementation of the ReadingList protocol.
*/
public class SQLiteReadingList: ReadingList {
let files: FileAccessor
let db: BrowserDB
let table = ReadingListTable<ReadingListItem>()
required public init(files: FileAccessor) {
self.files = files
self.db = BrowserDB(files: files)!
db.createOrUpdate(table)
}
public func clear(complete: (success: Bool) -> Void) {
var err: NSError? = nil
db.delete(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
if err != nil {
self.debug("Clear failed: \(err!.localizedDescription)")
complete(success: false)
} else {
complete(success: true)
}
}
}
public func get(complete: (data: Cursor) -> Void) {
var err: NSError? = nil
let res = db.query(&err) { (conn: SQLiteDBConnection, inout err: NSError?) -> Cursor in
return self.table.query(conn, options: nil)
}
dispatch_async(dispatch_get_main_queue()) {
complete(data: res)
}
}
public func add(#item: ReadingListItem, complete: (success: Bool) -> Void) {
var err: NSError? = nil
let inserted = db.insert(&err) { (conn, inout err: NSError?) -> Int in
return self.table.insert(conn, item: item, err: &err)
}
dispatch_async(dispatch_get_main_queue()) {
if err != nil {
self.debug("Add failed: \(err!.localizedDescription)")
}
complete(success: err == nil)
}
}
public func shareItem(item: ShareItem) {
add(item: ReadingListItem(url: item.url, title: item.title)) { (success) -> Void in
// Nothing we can do here when items are added from an extension.
}
}
private let debug_enabled = false
private func debug(msg: String) {
if debug_enabled {
println("SQLiteReadingList: " + msg)
}
}
}
| mpl-2.0 | 025b7c0d9d378db0247c0866c390c15b | 31.888889 | 95 | 0.575169 | 4.176367 | false | false | false | false |
myandy/shi_ios | shishi/UI/Search/SearchUserCollectionPoetryVC.swift | 1 | 1379 | //
// SearchUserCollectionPoetryVC.swift
// shishi
//
// Created by tb on 2017/8/28.
// Copyright © 2017年 andymao. All rights reserved.
//
import UIKit
class SearchUserCollectionPoetryVC: SearchPoetryVC {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func loadData() {
let collectionArray = UserCollection.allInstances() as! [UserCollection]
originItems = PoetryDB.getAll().filter({ (poetry) -> Bool in
return collectionArray.contains(where: { (userCollection) -> Bool in
return Int(userCollection.poetryId) == poetry.dNum && userCollection.poetryName == poetry.title
})
})
}
override func getHint() -> String {
return SSStr.Search.SEARCH_COLLECT_HINT
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | c8c4cc1fa66b574e1c42d832fb451848 | 27.666667 | 111 | 0.652616 | 4.482085 | false | false | false | false |
natestedman/LayoutModules | Example/LayoutModulesExample/ModulesViewController.swift | 1 | 2653 | // LayoutModules
// Written in 2015 by Nate Stedman <[email protected]>
//
// To the extent possible under law, the author(s) have dedicated all copyright and
// related and neighboring rights to this software to the public domain worldwide.
// This software is distributed without any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication along with
// this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
import LayoutModules
import UIKit
class ModulesViewController: UIViewController
{
override func loadView()
{
let layout = LayoutModulesCollectionViewLayout(majorAxis: .Vertical, moduleForSection: { [unowned self] section in
return self.modules[section]
})
let collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.whiteColor()
collectionView.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.dataSource = self
self.view = collectionView
}
let modules = [
LayoutModule.table(majorDimension: 44, padding: 1),
LayoutModule.dynamicTable(padding: 1, calculateMajorDimension: { index, _, _ in
CGFloat((index + 1) * 10)
}),
LayoutModule.grid(minimumMinorDimension: 20, padding: Size(major: 10, minor: 10)).inset(minMajor: 10),
LayoutModule.masonry(
minimumMinorDimension: 80,
padding: Size(major: 1, minor: 1),
calculateMajorDimension: { index, _, width in
return round(2 / (CGFloat(index % 4) + 1) * width)
}
).inset(minMajor: 10, maxMajor: 10, minMinor: 10, maxMinor: 10),
LayoutModule.grid(minimumMinorDimension: 50, padding: Size(major: 10, minor: 10), aspectRatio: 4.0 / 3.0)
]
}
extension ModulesViewController: UICollectionViewDataSource
{
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int
{
return modules.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
if section == 3
{
return 30
}
else
{
return 10
}
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath)
-> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath)
cell.backgroundColor = UIColor.grayColor()
return cell
}
}
| cc0-1.0 | 7b3a8b38b5507419a2b53eef84e827c9 | 35.847222 | 122 | 0.669431 | 5.015123 | false | false | false | false |
gaolichuang/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Group/GroupViewController.swift | 1 | 14488 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
class GroupViewController: AATableViewController {
private let GroupInfoCellIdentifier = "GroupInfoCellIdentifier"
private let UserCellIdentifier = "UserCellIdentifier"
private let CellIdentifier = "CellIdentifier"
let gid: Int
var group: ACGroupVM!
var binder = Binder()
private var tableData: ACManagedTable!
private var groupMembers = [ACGroupMember]()
private var groupNameTextField: UITextField?
init (gid: Int) {
self.gid = gid
super.init(style: UITableViewStyle.Plain)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
title = localized("ProfileTitle")
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
group = Actor.getGroupWithGid(jint(gid))
tableData = ACManagedTable(tableView: tableView, controller: self)
tableData.registerClass(AvatarCell.self, forCellReuseIdentifier: GroupInfoCellIdentifier)
tableData.registerClass(GroupMemberCell.self, forCellReuseIdentifier: UserCellIdentifier)
// Banner
var section = tableData.addSection(true)
.setFooterHeight(15)
section.addCustomCell { (tableView, indexPath) -> UITableViewCell in
var cell = tableView.dequeueReusableCellWithIdentifier(self.GroupInfoCellIdentifier, forIndexPath: indexPath) as! AvatarCell
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.subtitleLabel.hidden = true
cell.didTap = { () -> () in
let avatar = self.group!.getAvatarModel().get()
if avatar != nil && avatar.fullImage != nil {
let full = avatar.fullImage.fileReference
let small = avatar.smallImage.fileReference
let size = CGSize(width: Int(avatar.fullImage.width), height: Int(avatar.fullImage.height))
self.presentViewController(PhotoPreviewController(file: full, previewFile: small, size: size, fromView: cell.avatarView), animated: true, completion: nil)
}
}
return cell
}
.setHeight(92)
// Change Photo
section.addActionCell("GroupSetPhoto", actionClosure: { () -> Bool in
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet( hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.group?.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == -2) {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
Actor.removeGroupAvatarWithGid(jint(self.gid))
})
} else if (index >= 0) {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeGroupAvatar(jint(self.gid), image: image)
})
}
})
return true
})
section.addActionCell("GroupSetTitle", actionClosure: { () -> Bool in
self.editName()
return true
})
// adminSection
// .addNavigationCell("GroupIntegrations", actionClosure: { () -> () in
// self.navigateNext(IntegrationViewController(gid: jint(self.gid)), removeCurrent: false)
// })
// Notifications
tableData.addSection(true)
.setHeaderHeight(15)
.addCommonCell()
.setStyle(.Switch)
.setContent("GroupNotifications")
.setModificator { (cell) -> () in
let groupPeer: ACPeer! = ACPeer.groupWithInt(jint(self.gid))
cell.setSwitcherOn(Actor.isNotificationsEnabledWithPeer(groupPeer))
cell.switchBlock = { (on: Bool) -> () in
Actor.changeNotificationsEnabledWithPeer(groupPeer, withValue: on)
}
}
// Members
let membersSection = tableData.addSection(true)
membersSection.addHeaderCell()
.setTitle(localized("GroupMembers"))
membersSection
.addCustomCells(48, countClosure: { () -> Int in
return self.groupMembers.count
}) { (tableView, index, indexPath) -> UITableViewCell in
let cell: GroupMemberCell = tableView.dequeueReusableCellWithIdentifier(self.UserCellIdentifier, forIndexPath: indexPath) as! GroupMemberCell
let groupMember = self.groupMembers[index]
if let user = Actor.getUserWithUid(groupMember.uid) {
cell.bind(user)
// Notify to request onlines
Actor.onUserVisibleWithUid(groupMember.uid)
}
return cell
}.setAction { (index) -> Bool in
let groupMember = self.groupMembers[index]
if let user = Actor.getUserWithUid(groupMember.uid) {
if (user.getId() == Actor.myUid()) {
return true
}
let name = user.getNameModel().get()
self.showActionSheet(name,
buttons: isIPhone ? ["GroupMemberInfo", "GroupMemberWrite", "GroupMemberCall"] : ["GroupMemberInfo", "GroupMemberWrite"],
cancelButton: "Cancel",
destructButton: groupMember.uid != Actor.myUid() && (groupMember.inviterUid == Actor.myUid() || self.group!.creatorId == Actor.myUid()) ? "GroupMemberKick" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == -2) {
self.confirmUser(NSLocalizedString("GroupMemberKickMessage", comment: "Button Title").stringByReplacingOccurrencesOfString("{name}", withString: name, options: NSStringCompareOptions(), range: nil),
action: "GroupMemberKickAction",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.kickMemberCommandWithGid(jint(self.gid), withUid: user.getId()))
})
} else if (index >= 0) {
if (index == 0) {
self.navigateNext(UserViewController(uid: Int(user.getId())), removeCurrent: false)
} else if (index == 1) {
self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(user.getId())))
self.popover?.dismissPopoverAnimated(true)
} else if (index == 2) {
let phones = user.getPhonesModel().get()
if phones.size() == 0 {
self.alertUser("GroupMemberCallNoPhones")
} else if phones.size() == 1 {
let number = phones.getWithInt(0)
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://+\(number.phone)")!)
} else {
var numbers = [String]()
for i in 0..<phones.size() {
let p = phones.getWithInt(i)
numbers.append("\(p.title): +\(p.phone)")
}
self.showActionSheet(numbers,
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index >= 0) {
let number = phones.getWithInt(jint(index))
UIApplication.sharedApplication().openURL(NSURL(string: "telprompt://+\(number.phone)")!)
}
})
}
}
}
})
}
return true
}
// Add member
membersSection
.setFooterHeight(15)
.addActionCell("GroupAddParticipant", actionClosure: { () -> Bool in
let addParticipantController = AddParticipantViewController(gid: self.gid)
let navigationController = AANavigationController(rootViewController: addParticipantController)
if (isIPad) {
navigationController.modalInPopover = true
navigationController.modalPresentationStyle = UIModalPresentationStyle.CurrentContext
}
self.presentViewController(navigationController, animated: true, completion: nil)
return false
})
.setLeftInset(65.0)
// Leave group
tableData.addSection(true)
.setFooterHeight(15)
.setHeaderHeight(15)
.addActionCell("GroupLeave", actionClosure: { () -> Bool in
self.confirmUser("GroupLeaveConfirm", action: "GroupLeaveConfirmAction", cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.leaveGroupCommandWithGid(jint(self.gid)))
})
return true
})
.setStyle(.DestructiveCentered)
// Init table
tableView.reloadData()
// Bind group info
binder.bind(group!.getNameModel()!, closure: { (value: String?) -> () in
let cell: AvatarCell? = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? AvatarCell
if cell != nil {
cell!.titleLabel.text = value!
}
})
binder.bind(group!.getAvatarModel(), closure: { (value: ACAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? AvatarCell {
if (self.group!.isMemberModel().get().booleanValue()) {
cell.avatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: value)
} else {
cell.avatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: nil)
}
}
})
// Bind members
binder.bind(group!.getMembersModel(), closure: { (value: JavaUtilHashSet?) -> () in
if value != nil {
self.groupMembers = value!.toArray().toSwiftArray()
self.groupMembers.sortInPlace({ (left: ACGroupMember, right: ACGroupMember) -> Bool in
let lname = Actor.getUserWithUid(left.uid).getNameModel().get()
let rname = Actor.getUserWithUid(right.uid).getNameModel().get()
return lname < rname
})
self.tableView.reloadData()
}
})
// Bind membership status
binder.bind(group!.isMemberModel(), closure: { (member: JavaLangBoolean?) -> () in
if member != nil {
if Bool(member!.booleanValue()) == true {
self.hidePlaceholder()
} else {
self.showPlaceholderWithImage(
UIImage(named: "contacts_list_placeholder"),
title: NSLocalizedString("Placeholder_Group_Title", comment: "Not a member Title"),
subtitle: NSLocalizedString("Placeholder_Group_Message", comment: "Message Title"))
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? GroupPhotoCell {
cell.groupAvatarView.bind(self.group!.getNameModel().get(), id: jint(self.gid), avatar: nil)
}
}
}
})
}
func editName() {
textInputAlert("GroupEditHeader", content: group!.getNameModel().get(), action: "AlertSave") { (nval) -> () in
if nval.length > 0 {
self.confirmUser("GroupEditConfirm",
action: "GroupEditConfirmAction",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
self.execute(Actor.editGroupTitleCommandWithGid(jint(self.gid), withTitle: nval));
})
}
}
}
}
| mit | eaed2ff0443e46024fa35ccc9b54ada6 | 45.735484 | 226 | 0.503106 | 5.776715 | false | false | false | false |
RevenueCat/purchases-ios | Sources/Error Handling/ErrorUtils.swift | 1 | 28456 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// RCPurchasesErrorUtils.swift
//
// Created by Cesar de la Vega on 7/21/21.
//
import Foundation
import StoreKit
// swiftlint:disable file_length multiline_parameters type_body_length
enum ErrorUtils {
/**
* Constructs an NSError with the ``ErrorCode/networkError`` code and a populated `NSUnderlyingErrorKey` in
* the `NSError.userInfo` dictionary.
*
* - Parameter underlyingError: The value of the `NSUnderlyingErrorKey` key.
*
* - Note: This error is used when there is an error performing network request returns an error or when there
* is an `NSJSONSerialization` error.
*/
static func networkError(
message: String? = nil,
withUnderlyingError underlyingError: Error? = nil,
extraUserInfo: [NSError.UserInfoKey: Any] = [:],
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode: ErrorCode
if case NetworkError.dnsError(_, _, _)? = underlyingError {
errorCode = .apiEndpointBlockedError
} else {
errorCode = .networkError
}
return error(with: errorCode,
message: message,
underlyingError: underlyingError,
extraUserInfo: extraUserInfo,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an NSError with the ``ErrorCode/offlineConnection`` code.
*/
static func offlineConnectionError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: .offlineConnectionError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Maps a ``BackendErrorCode`` code to a ``ErrorCode``. code. Constructs an Error with the mapped code and adds a
* `NSUnderlyingErrorKey` in the `NSError.userInfo` dictionary. The backend error code will be mapped using
* ``BackendErrorCode/toPurchasesErrorCode()``.
*
* - Parameter backendCode: The code of the error.
* - Parameter originalBackendErrorCode: the original numerical value of this error.
* - Parameter backendMessage: The message of the errror contained under the `NSUnderlyingErrorKey` key.
*
* - Note: This error is used when an network request returns an error. The backend error returned is wrapped in
* this internal error code.
*/
static func backendError(
withBackendCode backendCode: BackendErrorCode,
originalBackendErrorCode: Int,
backendMessage: String?,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return backendError(withBackendCode: backendCode,
originalBackendErrorCode: originalBackendErrorCode,
backendMessage: backendMessage,
extraUserInfo: [:],
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/unexpectedBackendResponseError`` code.
*
* - Note: This error is used when a network request returns an unexpected response.
*/
static func unexpectedBackendResponseError(
extraUserInfo: [NSError.UserInfoKey: Any] = [:],
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.unexpectedBackendResponseError, extraUserInfo: extraUserInfo,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/unexpectedBackendResponseError`` code which contains an underlying
* ``UnexpectedBackendResponseSubErrorCode``
*
* - Note: This error is used when a network request returns an unexpected response and we can determine some
* of what went wrong with the response.
*/
static func unexpectedBackendResponse(
withSubError subError: Error?,
extraContext: String? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return backendResponseError(withSubError: subError,
extraContext: extraContext,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/missingReceiptFileError`` code.
*
* - Note: This error is used when the receipt is missing in the device. This can happen if the user is in
* sandbox or if there are no previous purchases.
*/
static func missingReceiptFileError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.missingReceiptFileError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/emptySubscriberAttributes`` code.
*/
static func emptySubscriberAttributesError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: .emptySubscriberAttributes,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/invalidAppUserIdError`` code.
*
* - Note: This error is used when the appUserID can't be found in user defaults. This can happen if user defaults
* are removed manually or if the OS deletes entries when running out of space.
*/
static func missingAppUserIDError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.invalidAppUserIdError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/productDiscountMissingIdentifierError`` code.
*
* - Note: This error code is used when attemping to post data about product discounts but the discount is
* missing an indentifier.
*/
static func productDiscountMissingIdentifierError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.productDiscountMissingIdentifierError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/productDiscountMissingSubscriptionGroupIdentifierError`` code.
*
* - Note: This error code is used when attemping to post data about product discounts but the discount is
* missing a subscriptionGroupIndentifier.
*/
static func productDiscountMissingSubscriptionGroupIdentifierError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.productDiscountMissingSubscriptionGroupIdentifierError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/logOutAnonymousUserError`` code.
*
* - Note: This error is used when logOut is called but the current user is anonymous,
* as noted by ``Purchases/isAnonymous`` property.
*/
static func logOutAnonymousUserError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.logOutAnonymousUserError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/paymentPendingError`` code.
*
* - Note: This error is used during an “ask to buy” flow for a payment. The completion block of the purchasing
* function will get this error to indicate the guardian has to complete the purchase.
*/
static func paymentDeferredError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.paymentPendingError, message: "The payment is deferred.",
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/unknownError`` code and optional message.
*/
static func unknownError(
message: String? = nil, error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: ErrorCode.unknownError, message: message, underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/operationAlreadyInProgressForProductError`` code.
*
* - Note: This error is used when a purchase is initiated for a product, but there's already a purchase for the
* same product in progress.
*/
static func operationAlreadyInProgressError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return error(with: ErrorCode.operationAlreadyInProgressForProductError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/configurationError`` code.
*
* - Note: This error is used when the configuration in App Store Connect doesn't match the configuration
* in the RevenueCat dashboard.
*/
static func configurationError(
message: String? = nil,
underlyingError: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return self.error(with: ErrorCode.configurationError,
message: message, underlyingError: underlyingError,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Maps an `SKError` to a Error with an ``ErrorCode``. Adds a underlying error in the `NSError.userInfo` dictionary.
*
* - Parameter skError: The originating `SKError`.
*/
static func purchasesError(
withSKError error: Error,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
switch error {
case let skError as SKError:
return skError.asPurchasesError
default:
return ErrorUtils.unknownError(
error: error,
fileName: fileName, functionName: functionName, line: line
)
}
}
/**
* Maps a `StoreKitError` or `Product.PurchaseError` to an `Error` with an ``ErrorCode``.
* Adds a underlying error in the `NSError.userInfo` dictionary.
*
* - Parameter storeKitError: The originating `StoreKitError` or `Product.PurchaseError`.
*/
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
static func purchasesError(
withStoreKitError error: Error,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
switch error {
case let storeKitError as StoreKitError:
return storeKitError.asPurchasesError
case let purchasesError as Product.PurchaseError:
return purchasesError.asPurchasesError
default:
return ErrorUtils.unknownError(
error: error,
fileName: fileName, functionName: functionName, line: line
)
}
}
/**
* Maps an untyped `Error` into a `PurchasesError`.
* If the error is already a `PurchasesError`, this simply returns the same value,
* otherwise it wraps it into a ``ErrorCode/unknownError``.
*/
static func purchasesError(
withUntypedError error: Error,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
if #available(iOS 13.0, macOS 10.15, tvOS 13.0, watchOS 6.2, *) {
switch error {
case let purchasesError as PurchasesError:
return purchasesError
// This line crashes on iOS 12.x only (see https://github.com/RevenueCat/purchases-ios/pull/1982).
case let convertible as PurchasesErrorConvertible:
return convertible.asPurchasesError
default:
return ErrorUtils.unknownError(
error: error,
fileName: fileName, functionName: functionName, line: line
)
}
} else {
switch error {
case let purchasesError as PurchasesError:
return purchasesError
// `as PurchasesErrorConvertible` crashes on iOS 12.x, so these explicit casts are a workaround.
// We can't guarantee that these are exhaustive, but at least this covers the most common cases,
// and the `default` below ensures that we don't crash for the rest.
case let backendError as BackendError:
return backendError.asPurchasesError
case let networkError as NetworkError:
return networkError.asPurchasesError
default:
return ErrorUtils.unknownError(
error: error,
fileName: fileName, functionName: functionName, line: line
)
}
}
}
/**
* Constructs an Error with the ``ErrorCode/purchaseCancelledError`` code.
*
* - Note: This error is used when a purchase is cancelled by the user.
*/
static func purchaseCancelledError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = ErrorCode.purchaseCancelledError
return ErrorUtils.error(with: errorCode,
message: errorCode.description,
underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/productNotAvailableForPurchaseError`` code.
*
* #### Related Articles
* - [`StoreKitError.notAvailableInStorefront`](https://rev.cat/storekit-error-not-available-in-storefront)
*/
static func productNotAvailableForPurchaseError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .productNotAvailableForPurchaseError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/productAlreadyPurchasedError`` code.
*/
static func productAlreadyPurchasedError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .productAlreadyPurchasedError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/purchaseNotAllowedError`` code.
*/
static func purchaseNotAllowedError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .purchaseNotAllowedError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/purchaseInvalidError`` code.
*/
static func purchaseInvalidError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .purchaseInvalidError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/ineligibleError`` code.
*/
static func ineligibleError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .ineligibleError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/ineligibleError`` code.
*/
static func invalidPromotionalOfferError(
error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .invalidPromotionalOfferError,
underlyingError: error)
}
/**
* Constructs an Error with the ``ErrorCode/storeProblemError`` code.
*
* - Note: This error is used when there is a problem with the App Store.
*/
static func storeProblemError(
withMessage message: String? = nil, error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = ErrorCode.storeProblemError
return ErrorUtils.error(with: errorCode,
message: message,
underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/customerInfoError`` code.
*
* - Note: This error is used when there is a problem related to the customer info.
*/
static func customerInfoError(
withMessage message: String? = nil, error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = ErrorCode.customerInfoError
return ErrorUtils.error(with: errorCode,
message: message,
underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/systemInfoError`` code.
*
* - Note: This error is used when there is a problem related to the system info.
*/
static func systemInfoError(
withMessage message: String, error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = ErrorCode.systemInfoError
return ErrorUtils.error(with: errorCode,
message: message,
underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/beginRefundRequestError`` code.
*
* - Note: This error is used when there is a problem beginning a refund request.
*/
static func beginRefundRequestError(
withMessage message: String, error: Error? = nil,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = ErrorCode.beginRefundRequestError
return ErrorUtils.error(with: errorCode,
message: message,
underlyingError: error,
fileName: fileName, functionName: functionName, line: line)
}
/**
* Constructs an Error with the ``ErrorCode/productRequestTimedOut`` code.
*
* - Note: This error is used when fetching products times out.
*/
static func productRequestTimedOutError(
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
return ErrorUtils.error(with: .productRequestTimedOut,
fileName: fileName, functionName: functionName, line: line)
}
}
extension ErrorUtils {
static func backendError(withBackendCode backendCode: BackendErrorCode,
originalBackendErrorCode: Int,
message: String? = nil,
backendMessage: String? = nil,
extraUserInfo: [NSError.UserInfoKey: Any] = [:],
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
let errorCode = backendCode.toPurchasesErrorCode()
let underlyingError = self.backendUnderlyingError(backendCode: backendCode,
originalBackendErrorCode: originalBackendErrorCode,
backendMessage: backendMessage)
return error(with: errorCode,
message: message ?? backendMessage,
underlyingError: underlyingError,
extraUserInfo: extraUserInfo + [
.backendErrorCode: originalBackendErrorCode
],
fileName: fileName, functionName: functionName, line: line)
}
}
private extension ErrorUtils {
static func error(with code: ErrorCode,
message: String? = nil,
underlyingError: Error? = nil,
extraUserInfo: [NSError.UserInfoKey: Any] = [:],
fileName: String = #fileID,
functionName: String = #function,
line: UInt = #line) -> PurchasesError {
let localizedDescription: String
if let message = message, message != code.description {
// Print both ErrorCode and message only if they're different
localizedDescription = "\(code.description) \(message)"
} else {
localizedDescription = code.description
}
var userInfo = extraUserInfo
userInfo[NSLocalizedDescriptionKey as NSError.UserInfoKey] = localizedDescription
if let underlyingError = underlyingError {
userInfo[NSUnderlyingErrorKey as NSError.UserInfoKey] = underlyingError
}
userInfo[.readableErrorCode] = code.codeName
userInfo[.file] = "\(fileName):\(line)"
userInfo[.function] = functionName
Self.logErrorIfNeeded(
code,
localizedDescription: localizedDescription,
fileName: fileName, functionName: functionName, line: line
)
return .init(error: code, userInfo: userInfo)
}
static func backendResponseError(
withSubError subError: Error?,
extraContext: String?,
fileName: String = #fileID, functionName: String = #function, line: UInt = #line
) -> PurchasesError {
var userInfo: [NSError.UserInfoKey: Any] = [:]
let describableSubError = subError as? DescribableError
let errorDescription = describableSubError?.description ?? ErrorCode.unexpectedBackendResponseError.description
userInfo[NSLocalizedDescriptionKey as NSError.UserInfoKey] = errorDescription
userInfo[NSUnderlyingErrorKey as NSError.UserInfoKey] = subError
userInfo[.readableErrorCode] = ErrorCode.unexpectedBackendResponseError.codeName
userInfo[.extraContext] = extraContext
userInfo[.file] = "\(fileName):\(line)"
userInfo[.function] = functionName
return .init(error: .unexpectedBackendResponseError, userInfo: userInfo)
}
static func backendUnderlyingError(backendCode: BackendErrorCode,
originalBackendErrorCode: Int,
backendMessage: String?) -> NSError {
return backendCode.addingUserInfo([
NSLocalizedDescriptionKey as NSError.UserInfoKey: backendMessage ?? "",
.backendErrorCode: originalBackendErrorCode
])
}
// swiftlint:disable:next function_body_length
private static func logErrorIfNeeded(_ code: ErrorCode,
localizedDescription: String,
fileName: String = #fileID,
functionName: String = #function,
line: UInt = #line) {
switch code {
case .networkError,
.unknownError,
.receiptAlreadyInUseError,
.unexpectedBackendResponseError,
.invalidReceiptError,
.invalidAppUserIdError,
.invalidCredentialsError,
.operationAlreadyInProgressForProductError,
.unknownBackendError,
.invalidSubscriberAttributesError,
.logOutAnonymousUserError,
.receiptInUseByOtherSubscriberError,
.configurationError,
.unsupportedError,
.emptySubscriberAttributes,
.productDiscountMissingIdentifierError,
.productDiscountMissingSubscriptionGroupIdentifierError,
.customerInfoError,
.systemInfoError,
.beginRefundRequestError,
.apiEndpointBlockedError,
.invalidPromotionalOfferError,
.offlineConnectionError:
Logger.error(
localizedDescription,
fileName: fileName,
functionName: functionName,
line: line
)
case .purchaseCancelledError,
.storeProblemError,
.purchaseNotAllowedError,
.purchaseInvalidError,
.productNotAvailableForPurchaseError,
.productAlreadyPurchasedError,
.missingReceiptFileError,
.invalidAppleSubscriptionKeyError,
.ineligibleError,
.insufficientPermissionsError,
.paymentPendingError,
.productRequestTimedOut:
Logger.appleError(
localizedDescription,
fileName: fileName,
functionName: functionName,
line: line
)
@unknown default:
Logger.error(
localizedDescription,
fileName: fileName,
functionName: functionName,
line: line
)
}
}
}
extension Error {
@_disfavoredOverload
func addingUserInfo<Result: NSError>(_ userInfo: [NSError.UserInfoKey: Any]) -> Result {
return self.addingUserInfo(userInfo as [String: Any])
}
func addingUserInfo<Result: NSError>(_ userInfo: [String: Any]) -> Result {
let nsError = self as NSError
return Result.init(domain: nsError.domain,
code: nsError.code,
userInfo: nsError.userInfo + userInfo)
}
}
/// Represents where an `Error` was created
struct ErrorSource {
let file: String
let function: String
let line: UInt
}
/// `Equatable` conformance allows `Error` types that contain source information
/// to easily conform to `Equatable`.
extension ErrorSource: Equatable {
/// However, for ease of testing, we don't actually care if the source of the errors matches
/// since expectations will be created in the test and therefore will never match.
static func == (lhs: ErrorSource, rhs: ErrorSource) -> Bool {
return true
}
}
| mit | 89a3ec9229089c8e1f9696d9016987a5 | 40.535766 | 120 | 0.612084 | 5.487367 | false | false | false | false |
RevenueCat/purchases-ios | Sources/Networking/Responses/CustomerInfoResponse.swift | 1 | 6481 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// CustomerInfoResponse.swift
//
// Created by Nacho Soto on 4/12/22.
import Foundation
/// The representation of ``CustomerInfo`` as sent by the backend.
/// Thanks to `@IgnoreHashable`, only `subscriber` is used for equality / hash.
struct CustomerInfoResponse {
var subscriber: Subscriber
@IgnoreHashable
var requestDate: Date
@IgnoreEncodable @IgnoreHashable
var rawData: [String: Any]
}
extension CustomerInfoResponse {
struct Subscriber {
var originalAppUserId: String
@IgnoreDecodeErrors<URL?>
var managementUrl: URL?
var originalApplicationVersion: String?
var originalPurchaseDate: Date?
var firstSeen: Date
@DefaultDecodable.EmptyDictionary
var subscriptions: [String: Subscription]
@DefaultDecodable.EmptyDictionary
var nonSubscriptions: [String: [Transaction]]
@DefaultDecodable.EmptyDictionary
var entitlements: [String: Entitlement]
}
struct Subscription {
@IgnoreDecodeErrors<PeriodType>
var periodType: PeriodType
var purchaseDate: Date?
var originalPurchaseDate: Date?
var expiresDate: Date?
@IgnoreDecodeErrors<Store>
var store: Store
@DefaultDecodable.False
var isSandbox: Bool
var unsubscribeDetectedAt: Date?
var billingIssuesDetectedAt: Date?
@IgnoreDecodeErrors<PurchaseOwnershipType>
var ownershipType: PurchaseOwnershipType
}
struct Transaction {
var purchaseDate: Date?
var originalPurchaseDate: Date?
var transactionIdentifier: String?
@IgnoreDecodeErrors<Store>
var store: Store
var isSandbox: Bool
}
struct Entitlement {
var expiresDate: Date?
var productIdentifier: String
var purchaseDate: Date?
@IgnoreEncodable @IgnoreHashable
var rawData: [String: Any]
}
}
// MARK: -
extension CustomerInfoResponse.Subscriber: Codable, Hashable {}
extension CustomerInfoResponse.Subscription: Codable, Hashable {}
extension CustomerInfoResponse.Entitlement: Hashable {}
extension CustomerInfoResponse.Entitlement: Encodable {}
extension CustomerInfoResponse.Entitlement: Decodable {
// Note: this must be manually implemented because of the custom call to `decodeRawData`
// which can't be abstracted as a property wrapper.
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.expiresDate = try container.decodeIfPresent(Date.self, forKey: .expiresDate)
self.productIdentifier = try container.decode(String.self, forKey: .productIdentifier)
self.purchaseDate = try container.decodeIfPresent(Date.self, forKey: .purchaseDate)
self.rawData = decoder.decodeRawData()
}
}
extension CustomerInfoResponse.Transaction: Codable, Hashable {
private enum CodingKeys: String, CodingKey {
case purchaseDate
case originalPurchaseDate
case transactionIdentifier = "id"
case store
case isSandbox
}
}
extension CustomerInfoResponse: Codable {
// Note: this must be manually implemented because of the custom call to `decodeRawData`
// which can't be abstracted as a property wrapper.
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.requestDate = try container.decode(Date.self, forKey: .requestDate)
self.subscriber = try container.decode(Subscriber.self, forKey: .subscriber)
self.rawData = decoder.decodeRawData()
}
}
extension CustomerInfoResponse: Equatable, Hashable {}
extension CustomerInfoResponse.Transaction {
init(
purchaseDate: Date?,
originalPurchaseDate: Date?,
transactionIdentifier: String?,
store: Store,
isSandbox: Bool
) {
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.transactionIdentifier = transactionIdentifier
self.store = store
self.isSandbox = isSandbox
}
var asSubscription: CustomerInfoResponse.Subscription {
return .init(purchaseDate: self.purchaseDate,
originalPurchaseDate: self.originalPurchaseDate,
store: self.store,
isSandbox: self.isSandbox)
}
}
extension CustomerInfoResponse.Subscription {
init(
periodType: PeriodType = .defaultValue,
purchaseDate: Date? = nil,
originalPurchaseDate: Date? = nil,
expiresDate: Date? = nil,
store: Store = .defaultValue,
isSandbox: Bool,
unsubscribeDetectedAt: Date? = nil,
billingIssuesDetectedAt: Date? = nil,
ownershipType: PurchaseOwnershipType = .defaultValue
) {
self.periodType = periodType
self.purchaseDate = purchaseDate
self.originalPurchaseDate = originalPurchaseDate
self.expiresDate = expiresDate
self.store = store
self.isSandbox = isSandbox
self.unsubscribeDetectedAt = unsubscribeDetectedAt
self.billingIssuesDetectedAt = billingIssuesDetectedAt
self.ownershipType = ownershipType
}
var asTransaction: CustomerInfoResponse.Transaction {
return .init(purchaseDate: self.purchaseDate,
originalPurchaseDate: self.originalPurchaseDate,
transactionIdentifier: nil,
store: self.store,
isSandbox: self.isSandbox)
}
}
extension CustomerInfoResponse.Subscriber {
var allTransactionsByProductId: [String: CustomerInfoResponse.Transaction] {
return self.allPurchasesByProductId.mapValues { $0.asTransaction }
}
var allPurchasesByProductId: [String: CustomerInfoResponse.Subscription] {
let subscriptions = self.subscriptions
let latestNonSubscriptionTransactionsByProductId = self.nonSubscriptions
.compactMapValues { $0.last }
.mapValues { $0.asSubscription }
return subscriptions + latestNonSubscriptionTransactionsByProductId
}
}
| mit | c693d09f87e9f1595b39e74ee0cae473 | 28.729358 | 94 | 0.681376 | 5.312295 | false | false | false | false |
jmgc/swift | test/SILOptimizer/infinite_recursion.swift | 1 | 4264 | // RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify
// RUN: %target-swift-frontend -emit-sil %s -o /dev/null -verify
func a() { // expected-warning {{all paths through this function will call itself}}
a()
}
func b(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
if x != 0 {
b(x)
} else {
b(x+1)
}
}
func c(_ x : Int) {
if x != 0 {
c(5)
}
}
func d(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
if x != 0 {
x += 1
}
return d(x)
}
// Doesn't warn on mutually recursive functions
func e() { f() }
func f() { e() }
func g() { // expected-warning {{all paths through this function will call itself}}
while true { // expected-note {{condition always evaluates to true}}
g()
}
g() // expected-warning {{will never be executed}}
}
func h(_ x : Int) {
while (x < 5) {
h(x+1)
}
}
func i(_ x : Int) { // expected-warning {{all paths through this function will call itself}}
var x = x
while (x < 5) {
x -= 1
}
i(0)
}
func j() -> Int { // expected-warning {{all paths through this function will call itself}}
return 5 + j()
}
func k() -> Any { // expected-warning {{all paths through this function will call itself}}
return type(of: k())
}
@_silgen_name("exit") func exit(_: Int32) -> Never
func l() {
guard Bool.random() else {
exit(0) // no warning; calling 'exit' terminates the program
}
l()
}
func m() { // expected-warning {{all paths through this function will call itself}}
guard Bool.random() else {
fatalError() // we _do_ warn here, because fatalError is a programtermination_point
}
m()
}
enum MyNever {}
func blackHole() -> MyNever { // expected-warning {{all paths through this function will call itself}}
blackHole()
}
@_semantics("programtermination_point")
func terminateMe() -> MyNever {
terminateMe() // no warning; terminateMe is a programtermination_point
}
func n() -> MyNever {
if Bool.random() {
blackHole() // no warning; blackHole() will terminate the program
}
n()
}
func o() -> MyNever {
if Bool.random() {
o()
}
blackHole() // no warning; blackHole() will terminate the program
}
func mayHaveSideEffects() {}
func p() { // expected-warning {{all paths through this function will call itself}}
if Bool.random() {
mayHaveSideEffects() // presence of side-effects doesn't alter the check for the programtermination_point apply
fatalError()
}
p()
}
class S {
convenience init(a: Int) { // expected-warning {{all paths through this function will call itself}}
self.init(a: a)
}
init(a: Int?) {}
static func a() { // expected-warning {{all paths through this function will call itself}}
return a()
}
func b() { // No warning - has a known override.
var i = 0
repeat {
i += 1
b()
} while (i > 5)
}
var bar: String = "hi!"
}
class T: S {
// No warning, calls super
override func b() {
var i = 0
repeat {
i += 1
super.b()
} while (i > 5)
}
override var bar: String {
get {
return super.bar
}
set { // expected-warning {{all paths through this function will call itself}}
self.bar = newValue
}
}
}
func == (l: S?, r: S?) -> Bool { // expected-warning {{all paths through this function will call itself}}
if l == nil && r == nil { return true }
guard let l = l, let r = r else { return false }
return l === r
}
public func == <Element>(lhs: Array<Element>, rhs: Array<Element>) -> Bool { // expected-warning {{all paths through this function will call itself}}
return lhs == rhs
}
func factorial(_ n : UInt) -> UInt { // expected-warning {{all paths through this function will call itself}}
return (n != 0) ? factorial(n - 1) * n : factorial(1)
}
func tr(_ key: String) -> String { // expected-warning {{all paths through this function will call itself}}
return tr(key) ?? key // expected-warning {{left side of nil coalescing operator '??' has non-optional type}}
}
class Node {
var parent: Node?
var rootNode: RootNode {
return parent!.rootNode // No warning - has an override.
}
}
class RootNode: Node {
override var rootNode: RootNode { return self }
}
| apache-2.0 | 3dff58e9783cf7af654a81f63193af94 | 22.173913 | 149 | 0.618433 | 3.489362 | false | false | false | false |
andrea-prearo/SwiftExamples | CoreDataCodable/CoreDataCodable/AppDelegate.swift | 1 | 3822 | //
// AppDelegate.swift
// CoreDataCodable
//
// Created by Andrea Prearo on 3/29/18.
// Copyright © 2018 Andrea Prearo. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let _ = NSClassFromString("XCTest") {
return true
}
instantiateMainViewController()
return true
}
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: - CoreData 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: "CoreDataCodable")
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: - CoreData wrapper
lazy var coreDataWrapper: CoreDataWrapper = {
return CoreDataWrapper(persistentContainer: persistentContainer)
}()
// MARK: - CoreData 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)")
}
}
}
// MARK: - Private Methods
private func instantiateMainViewController() {
let mainViewController = MainViewController.create(persistentContainer: persistentContainer,
coreDataWrapper: coreDataWrapper)
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = mainViewController
self.window?.makeKeyAndVisible()
}
}
| mit | ae87a5738031192d7ae59fe2ae9a44a8 | 40.532609 | 199 | 0.643811 | 5.99843 | false | false | false | false |
tad-iizuka/swift-sdk | Source/ConversationV1/Models/MessageRequest.swift | 2 | 4773 | /**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import RestKit
/** A request formatted for the Conversation service. */
public struct MessageRequest: JSONEncodable {
private let input: Input
private let alternateIntents: Bool?
private let context: Context?
private let entities: [Entity]?
private let intents: [Intent]?
private let output: Output?
/**
Create a `MessageRequest`.
- parameter input: An input object that includes the input text.
- parameter alternateIntents: Whether to return more than one intent. Set to `true` to return
all matching intents. For example, return all intents when the confidence is not high
to allow users to choose their intent.
- parameter context: State information for the conversation. Include the context object from
the previous response when you send multiple requests for the same conversation.
- parameter entities: Include the entities from a previous response when they do not need to
change and to prevent Watson from trying to identify them.
- parameter intents: An array of name-confidence pairs for the user input. Include the intents
from the request when they do not need to change so that Watson does not try to identify
them.
- parameter output: System output. Include the output from the request when you have several
requests within the same Dialog turn to pass back in the intermediate information.
*/
public init(
input: Input,
alternateIntents: Bool? = nil,
context: Context? = nil,
entities: [Entity]? = nil,
intents: [Intent]? = nil,
output: Output? = nil)
{
self.input = input
self.alternateIntents = alternateIntents
self.context = context
self.entities = entities
self.intents = intents
self.output = output
}
/**
Create a `MessageRequest`.
- parameter text: The input text.
- parameter alternateIntents: Whether to return more than one intent. Set to `true` to return
all matching intents. For example, return all intents when the confidence is not high
to allow users to choose their intent.
- parameter context: State information for the conversation. Include the context object from
the previous response when you send multiple requests for the same conversation.
- parameter entities: Include the entities from a previous response when they do not need to
change and to prevent Watson from trying to identify them.
- parameter intents: An array of name-confidence pairs for the user input. Include the intents
from the request when they do not need to change so that Watson does not try to identify
them.
- parameter output: System output. Include the output from the request when you have several
requests within the same Dialog turn to pass back in the intermediate information.
*/
public init(
text: String,
alternateIntents: Bool? = nil,
context: Context? = nil,
entities: [Entity]? = nil,
intents: [Intent]? = nil,
output: Output? = nil)
{
self.input = Input(text: text)
self.alternateIntents = alternateIntents
self.context = context
self.entities = entities
self.intents = intents
self.output = output
}
/// Used internally to serialize a `MessageRequest` model to JSON.
public func toJSONObject() -> Any {
var json = [String: Any]()
json["input"] = input.toJSONObject()
if let alternateIntents = alternateIntents {
json["alternate_intents"] = alternateIntents
}
if let context = context {
json["context"] = context.toJSONObject()
}
if let entities = entities {
json["entities"] = entities.map { $0.toJSONObject() }
}
if let intents = intents {
json["intents"] = intents.map { $0.toJSONObject() }
}
if let output = output {
json["output"] = output.toJSONObject()
}
return json
}
}
| apache-2.0 | 23b38cd416aae350492aba9c833f8c67 | 39.794872 | 99 | 0.662686 | 4.982255 | false | false | false | false |
codequest-eu/CQGoogleDirections | Pod/Classes/CQRoutes.swift | 1 | 871 | //
// CQRoutes.swift
// lifthero
//
// Created by Lukasz on 09/11/15.
// Copyright © 2015 Lukasz Solniczek. All rights reserved.
//
public struct CQRoutes {
public var overviewPolylines: CQOverviewPolylines
public var bounds: CQBounds
public var legs: [CQRouteLeg]
public init(value: [String: AnyObject]) {
var legsArr = [CQRouteLeg]()
for leg in value["legs"] as! NSArray {
legsArr.append(CQRouteLeg(value: leg as! [String: AnyObject]))
}
self.legs = legsArr
self.overviewPolylines = CQOverviewPolylines(value: value["overview_polyline"] as! [String: AnyObject])
let mapBound = value["bounds"] as! [String: AnyObject]
self.bounds = CQBounds(northeastDic: mapBound["northeast"] as! [String: AnyObject], southwestDic: mapBound["southwest"] as! [String: AnyObject])
}
} | mit | 43085cd6a01923c86cb52e157d821f41 | 33.84 | 152 | 0.656322 | 3.883929 | false | false | false | false |
rhildreth/Cottontown | Cottontown/StopsModel.swift | 1 | 2008 | //
// StopsModel.swift
// Cottontown
//
// Created by Ron Hildreth on 12/28/15.
// Copyright © 2015 Tappdev.com. All rights reserved.
//
import Foundation
import ImageIO
import UIKit
class StopsModel {
static let sharedInstance = StopsModel()
var plistStops:[[String:AnyObject]]
var allStops = [Stop]()
var path:String
let scale = UIScreen.mainScreen().scale
private init () {
path = NSBundle.mainBundle().pathForResource("Stops", ofType: "plist")!
plistStops = NSArray(contentsOfFile: path)! as! [[String : AnyObject]]
for plistStop in plistStops {
allStops.append(Stop(stop: plistStop))
}
}
class func resizeImage(fileName file: String, type: String, maxPointSize: CGFloat, completionHandler handler: (image: UIImage) -> Void) {
let url = NSBundle.mainBundle().URLForResource(file, withExtension: type)!
let src = CGImageSourceCreateWithURL(url, nil)!
let scale = UIScreen.mainScreen().scale
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0)) {
let dict : [NSObject:AnyObject] = [
kCGImageSourceShouldAllowFloat : true,
kCGImageSourceCreateThumbnailWithTransform : true,
kCGImageSourceCreateThumbnailFromImageAlways : true,
kCGImageSourceThumbnailMaxPixelSize : maxPointSize * scale
]
let imref = CGImageSourceCreateThumbnailAtIndex(src, 0, dict)!
let im = UIImage(CGImage: imref, scale: scale, orientation: .Up)
dispatch_async(dispatch_get_main_queue()) {
// let startTime = CACurrentMediaTime()
handler(image: im)
// let elapsedTime = (CACurrentMediaTime() - startTime) * 1000
// print("image time for row",file,"=", elapsedTime ,"ms")
}
}
}
}
| mit | a8b92b368e1eac1f9c0394368be143c8 | 31.901639 | 141 | 0.594918 | 4.94335 | false | false | false | false |
Antidote-for-Tox/Antidote | Antidote/OCTManagerMock.swift | 1 | 8357 | // 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 MobileCoreServices
private enum Gender {
case male
case female
}
class OCTManagerMock: NSObject, OCTManager {
var bootstrap: OCTSubmanagerBootstrap
var calls: OCTSubmanagerCalls
var chats: OCTSubmanagerChats
var files: OCTSubmanagerFiles
var friends: OCTSubmanagerFriends
var objects: OCTSubmanagerObjects
var user: OCTSubmanagerUser
var realm: RLMRealm
override init() {
let configuration = RLMRealmConfiguration.default()
configuration.inMemoryIdentifier = "test realm"
realm = try! RLMRealm(configuration: configuration)
bootstrap = OCTSubmanagerBootstrapMock()
calls = OCTSubmanagerCallsMock()
chats = OCTSubmanagerChatsMock()
files = OCTSubmanagerFilesMock()
friends = OCTSubmanagerFriendsMock()
objects = OCTSubmanagerObjectsMock(realm: realm)
user = OCTSubmanagerUserMock()
super.init()
populateRealm()
}
func configuration() -> OCTManagerConfiguration {
return OCTManagerConfiguration()
}
func exportToxSaveFile() throws -> String {
return "123"
}
func changeEncryptPassword(_ newPassword: String, oldPassword: String) -> Bool {
return true
}
func isManagerEncrypted(withPassword password: String) -> Bool {
return true
}
}
private extension OCTManagerMock {
func populateRealm() {
realm.beginWriteTransaction()
let f1 = addFriend(gender: .female, number: 1, connectionStatus: .TCP, status: .none)
let f2 = addFriend(gender: .male, number: 1, connectionStatus: .TCP, status: .busy)
let f3 = addFriend(gender: .female, number: 2, connectionStatus: .none, status: .none)
let f4 = addFriend(gender: .male, number: 2, connectionStatus: .TCP, status: .away)
let f5 = addFriend(gender: .male, number: 3, connectionStatus: .TCP, status: .none)
let f6 = addFriend(gender: .female, number: 3, connectionStatus: .TCP, status: .away)
let f7 = addFriend(gender: .male, number: 4, connectionStatus: .TCP, status: .away)
let f8 = addFriend(gender: .female, number: 4, connectionStatus: .none, status: .none)
let f9 = addFriend(gender: .female, number: 5, connectionStatus: .TCP, status: .none)
let f10 = addFriend(gender: .male, number: 5, connectionStatus: .none, status: .none)
let c1 = addChat(friend: f1)
let c2 = addChat(friend: f2)
let c3 = addChat(friend: f3)
let c4 = addChat(friend: f4)
let c5 = addChat(friend: f5)
let c6 = addChat(friend: f6)
let c7 = addChat(friend: f7)
let c8 = addChat(friend: f8)
let c9 = addChat(friend: f9)
let c10 = addChat(friend: f10)
addDemoConversationToChat(c1)
addCallMessage(chat: c2, outgoing: false, answered: false, duration: 0.0)
addTextMessage(chat: c3, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_1"))
addCallMessage(chat: c4, outgoing: true, answered: true, duration: 1473.0)
addTextMessage(chat: c5, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_2"))
addFileMessage(chat: c6, outgoing: false, fileName: "party.png")
addTextMessage(chat: c7, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_3"))
addTextMessage(chat: c8, outgoing: true, text: String(localized: "app_store_screenshot_chat_message_4"))
addFileMessage(chat: c9, outgoing: true, fileName: "presentation_2016.pdf")
addTextMessage(chat: c10, outgoing: false, text: String(localized: "app_store_screenshot_chat_message_5"))
c1.lastReadDateInterval = Date().timeIntervalSince1970
// unread message
// c2.lastReadDateInterval = NSDate().timeIntervalSince1970
c3.lastReadDateInterval = Date().timeIntervalSince1970
c4.lastReadDateInterval = Date().timeIntervalSince1970
c5.lastReadDateInterval = Date().timeIntervalSince1970
c6.lastReadDateInterval = Date().timeIntervalSince1970
c7.lastReadDateInterval = Date().timeIntervalSince1970
c8.lastReadDateInterval = Date().timeIntervalSince1970
c9.lastReadDateInterval = Date().timeIntervalSince1970
c10.lastReadDateInterval = Date().timeIntervalSince1970
try! realm.commitWriteTransaction()
}
func addFriend(gender: Gender,
number: Int,
connectionStatus: OCTToxConnectionStatus,
status: OCTToxUserStatus) -> OCTFriend {
let friend = OCTFriend()
friend.publicKey = "123"
friend.connectionStatus = connectionStatus
friend.isConnected = connectionStatus != .none
friend.status = status
switch gender {
case .male:
friend.nickname = String(localized: "app_store_screenshot_friend_male_\(number)")
friend.avatarData = UIImagePNGRepresentation(UIImage(named: "male-\(number)")!)
case .female:
friend.nickname = String(localized: "app_store_screenshot_friend_female_\(number)")
friend.avatarData = UIImagePNGRepresentation(UIImage(named: "female-\(number)")!)
}
realm.add(friend)
return friend
}
func addChat(friend: OCTFriend) -> OCTChat {
let chat = OCTChat()
realm.add(chat)
chat.friends.add(friend)
return chat
}
func addDemoConversationToChat(_ chat: OCTChat) {
addFileMessage(chat: chat, outgoing: false, fileName: "party.png")
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_1"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_2"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_3"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_4"))
addTextMessage(chat: chat, outgoing: false, text: String(localized: "app_store_screenshot_conversation_5"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_6"))
addTextMessage(chat: chat, outgoing: true, text: String(localized: "app_store_screenshot_conversation_7"))
}
func addTextMessage(chat: OCTChat, outgoing: Bool, text: String) {
let messageText = OCTMessageText()
messageText.text = text
messageText.isDelivered = outgoing
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageText = messageText
}
func addFileMessage(chat: OCTChat, outgoing: Bool, fileName: String) {
let messageFile = OCTMessageFile()
messageFile.fileName = fileName
messageFile.internalFilePath = Bundle.main.path(forResource: "dummy-photo", ofType: "jpg")
messageFile.fileType = .ready
messageFile.fileUTI = kUTTypeImage as String
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageFile = messageFile
}
func addCallMessage(chat: OCTChat, outgoing: Bool, answered: Bool, duration: TimeInterval) {
let messageCall = OCTMessageCall()
messageCall.callDuration = duration
messageCall.callEvent = answered ? .answered : .unanswered
let message = addMessageAbstract(chat: chat, outgoing: outgoing)
message.messageCall = messageCall
}
func addMessageAbstract(chat: OCTChat, outgoing: Bool) -> OCTMessageAbstract {
let message = OCTMessageAbstract()
if !outgoing {
let friend = chat.friends.firstObject() as! OCTFriend
message.senderUniqueIdentifier = friend.uniqueIdentifier
}
message.chatUniqueIdentifier = chat.uniqueIdentifier
message.dateInterval = Date().timeIntervalSince1970
realm.add(message)
chat.lastMessage = message
return message
}
}
| mpl-2.0 | d241c205b95e9d5e51ed950c6429603c | 41.207071 | 115 | 0.6689 | 4.527086 | false | false | false | false |
necrowman/CRLAlamofireFuture | Examples/SimpleTvOSCarthage/Carthage/Checkouts/RunLoop/Package.swift | 111 | 1186 | //===--- Package.swift ----------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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 PackageDescription
let package = Package(
name: "RunLoop",
targets: [Target(name: "RunLoop")],
dependencies: [
.Package(url: "https://github.com/reactive-swift/UV.git", majorVersion: 0, minor: 1),
.Package(url: "https://github.com/crossroadlabs/Foundation3.git", majorVersion: 0, minor: 1),
.Package(url: "https://github.com/crossroadlabs/XCTest3.git", majorVersion: 0, minor: 1)
]
)
| mit | 79cd782960e901c862094556aa374dd4 | 42.925926 | 101 | 0.629848 | 4.312727 | false | false | false | false |
GrandCentralBoard/GrandCentralBoard | Pods/Operations/Sources/Core/Shared/Repeatable.swift | 2 | 3634 | //
// Repeatable.swift
// Operations
//
// Created by Daniel Thorpe on 05/03/2016.
//
//
import Foundation
/**
### Repeatable
`Repeatable` is a very simple protocol, which your `NSOperation` subclasses
can conform to. This allows the previous operation to define whether a new
one should be executed. For this special case, `RepeatedOperation` can be
initialized like this:
```swift
let operation = RepeatedOperation { MyRepeatableOperation() }
```
- see: RepeatedOperation
*/
public protocol Repeatable {
/**
Implement this funtion to return true if a new
instance should be added to a RepeatedOperation.
- parameter count: the number of instances already executed within
the RepeatedOperation.
- returns: a Bool, false will end the RepeatedOperation.
*/
func shouldRepeat(count: Int) -> Bool
}
public class RepeatableGenerator<G: GeneratorType where G.Element: Repeatable>: GeneratorType {
private var generator: G
private var count: Int = 0
private var current: G.Element?
public init(_ generator: G) {
self.generator = generator
}
public func next() -> G.Element? {
if let current = current {
guard current.shouldRepeat(count) else {
return nil
}
}
current = generator.next()
count += 1
return current
}
}
extension RepeatedOperation where T: Repeatable {
/**
Initialize a RepeatedOperation using a closure with NSOperation subclasses
which conform to Repeatable. This is the neatest initializer.
```swift
let operation = RepeatedOperation { MyRepeatableOperation() }
```
*/
public convenience init(maxCount max: Int? = .None, strategy: WaitStrategy = .Fixed(0.1), body: () -> T?) {
self.init(maxCount: max, strategy: strategy, generator: RepeatableGenerator(AnyGenerator(body: body)))
}
}
/**
RepeatableOperation is an Operation subclass which conforms to Repeatable.
It can be used to make an otherwise non-repeatable Operation repeatable. It
does this by accepting, in addition to the operation instance, a closure
shouldRepeat. This closure can be used to capture state (such as errors).
When conforming to Repeatable, the closure is executed, passing in the
current repeat count.
*/
public class RepeatableOperation<T: Operation>: Operation, OperationDidFinishObserver, Repeatable {
let operation: T
let shouldRepeatBlock: Int -> Bool
/**
Initialize the RepeatableOperation with an operation and
shouldRepeat closure.
- parameter [unnamed] operation: the operation instance.
- parameter shouldRepeat: a closure of type Int -> Bool
*/
public init(_ operation: T, shouldRepeat: Int -> Bool) {
self.operation = operation
self.shouldRepeatBlock = shouldRepeat
super.init()
name = "Repeatable<\(operation.operationName)>"
addObserver(CancelledObserver { [weak operation] _ in
(operation as? Operation)?.cancel()
})
}
/// Override implementation of execute
public override func execute() {
if !cancelled {
operation.addObserver(self)
produceOperation(operation)
}
}
/// Implementation for Repeatable
public func shouldRepeat(count: Int) -> Bool {
return shouldRepeatBlock(count)
}
/// Implementation for OperationDidFinishObserver
public func didFinishOperation(operation: Operation, errors: [ErrorType]) {
if self.operation == operation {
finish(errors)
}
}
}
| gpl-3.0 | 7ec0792fba21760ad9fb18d181bc2772 | 27.390625 | 111 | 0.670611 | 4.871314 | false | false | false | false |
apple/swift-corelibs-foundation | Sources/Foundation/NSAttributedString.swift | 1 | 27635 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016, 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
extension NSAttributedString {
public struct Key: RawRepresentable, Equatable, Hashable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
}
}
extension NSAttributedString.Key: _ObjectiveCBridgeable {
public func _bridgeToObjectiveC() -> NSString {
return rawValue as NSString
}
public static func _forceBridgeFromObjectiveC(_ source: NSString, result: inout NSAttributedString.Key?) {
result = NSAttributedString.Key(source as String)
}
public static func _conditionallyBridgeFromObjectiveC(_ source: NSString, result: inout NSAttributedString.Key?) -> Bool {
result = NSAttributedString.Key(source as String)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSString?) -> NSAttributedString.Key {
guard let source = source else { return NSAttributedString.Key("") }
return NSAttributedString.Key(source as String)
}
}
@available(*, unavailable, renamed: "NSAttributedString.Key")
public typealias NSAttributedStringKey = NSAttributedString.Key
open class NSAttributedString: NSObject, NSCopying, NSMutableCopying, NSSecureCoding {
private let _cfinfo = _CFInfo(typeID: CFAttributedStringGetTypeID())
fileprivate var _string: NSString
fileprivate var _attributeArray: OpaquePointer
public required init?(coder aDecoder: NSCoder) {
let mutableAttributedString = NSMutableAttributedString(string: "")
guard _NSReadMutableAttributedStringWithCoder(aDecoder, mutableAttributedString: mutableAttributedString) else {
return nil
}
// use the resulting _string and _attributeArray to initialize a new instance, just like init
_string = mutableAttributedString._string
_attributeArray = mutableAttributedString._attributeArray
}
open func encode(with aCoder: NSCoder) {
guard aCoder.allowsKeyedCoding else { fatalError("We do not support saving to a non-keyed coder.") }
aCoder.encode(string, forKey: "NSString")
let length = self.length
if length > 0 {
var range = NSMakeRange(NSNotFound, NSNotFound)
var loc = 0
var dict = attributes(at: loc, effectiveRange: &range) as NSDictionary
if range.length == length {
// Special single-attribute run case
// If NSAttributeInfo is not written, then NSAttributes is a dictionary
aCoder.encode(dict, forKey: "NSAttributes")
} else {
let attrsArray = NSMutableArray(capacity: 20)
let data = NSMutableData(capacity: 100) ?? NSMutableData()
let attrsTable = NSMutableDictionary()
while true {
var arraySlot = 0
if let cachedSlot = attrsTable.object(forKey: dict) as? Int {
arraySlot = cachedSlot
} else {
arraySlot = attrsArray.count
attrsTable.setObject(arraySlot, forKey: dict)
attrsArray.add(dict)
}
_NSWriteIntToMutableAttributedStringCoding(range.length, data)
_NSWriteIntToMutableAttributedStringCoding(arraySlot, data)
loc += range.length
guard loc < length else { break }
dict = attributes(at: loc, effectiveRange: &range) as NSDictionary
}
aCoder.encode(attrsArray, forKey: "NSAttributes")
aCoder.encode(data, forKey: "NSAttributeInfo")
}
}
}
static public var supportsSecureCoding: Bool {
return true
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableAttributedString(attributedString: self)
}
/// The character contents of the receiver as an NSString object.
open var string: String {
return _string._swiftObject
}
/// Returns the attributes for the character at a given index.
open func attributes(at location: Int, effectiveRange range: NSRangePointer?) -> [NSAttributedString.Key: Any] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attributes(at: location, rangeInfo: rangeInfo)
}
/// The length of the receiver’s string object.
open var length: Int {
return CFAttributedStringGetLength(_cfObject)
}
/// Returns the value for an attribute with a given name of the character at a given index, and by reference the range over which the attribute applies.
open func attribute(_ attrName: NSAttributedString.Key, at location: Int, effectiveRange range: NSRangePointer?) -> Any? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: false,
longestEffectiveRangeSearchRange: nil)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
/// Returns an NSAttributedString object consisting of the characters and attributes within a given range in the receiver.
open func attributedSubstring(from range: NSRange) -> NSAttributedString {
let attributedSubstring = CFAttributedStringCreateWithSubstring(kCFAllocatorDefault, _cfObject, CFRange(range))
return unsafeBitCast(attributedSubstring, to: NSAttributedString.self)
}
/// Returns the attributes for the character at a given index, and by reference the range over which the attributes apply.
open func attributes(at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> [NSAttributedString.Key: Any] {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attributes(at: location, rangeInfo: rangeInfo)
}
/// Returns the value for the attribute with a given name of the character at a given index, and by reference the range over which the attribute applies.
open func attribute(_ attrName: NSAttributedString.Key, at location: Int, longestEffectiveRange range: NSRangePointer?, in rangeLimit: NSRange) -> Any? {
let rangeInfo = RangeInfo(
rangePointer: range,
shouldFetchLongestEffectiveRange: true,
longestEffectiveRangeSearchRange: rangeLimit)
return _attribute(attrName, atIndex: location, rangeInfo: rangeInfo)
}
open override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? NSAttributedString else { return false }
return isEqual(to: other)
}
/// Returns a Boolean value that indicates whether the receiver is equal to another given attributed string.
open func isEqual(to other: NSAttributedString) -> Bool {
guard let runtimeClass = _CFRuntimeGetClassWithTypeID(CFAttributedStringGetTypeID()) else {
fatalError("Could not obtain CFRuntimeClass of CFAttributedString")
}
guard let equalFunction = runtimeClass.pointee.equal else {
fatalError("Could not obtain equal function from CFRuntimeClass of CFAttributedString")
}
return equalFunction(_cfObject, other._cfObject) == true
}
/// Returns an NSAttributedString object initialized with the characters of a given string and no attribute information.
public init(string: String) {
_string = string._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: nil)
}
/// Returns an NSAttributedString object initialized with a given string and attributes.
public init(string: String, attributes attrs: [NSAttributedString.Key: Any]? = nil) {
_string = string._nsObject
_attributeArray = CFRunArrayCreate(kCFAllocatorDefault)
super.init()
addAttributesToAttributeArray(attrs: attrs)
}
/// Returns an NSAttributedString object initialized with the characters and attributes of another given attributed string.
public init(attributedString: NSAttributedString) {
// create an empty mutable attr string then immediately replace all of its contents
let mutableAttributedString = NSMutableAttributedString(string: "")
mutableAttributedString.setAttributedString(attributedString)
// use the resulting _string and _attributeArray to initialize a new instance
_string = mutableAttributedString._string
_attributeArray = mutableAttributedString._attributeArray
}
/// Executes the block for each attribute in the range.
open func enumerateAttributes(in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: ([NSAttributedString.Key: Any], NSRange, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
_enumerate(in: enumerationRange, reversed: opts.contains(.reverse)) { currentIndex, rangeLimit, stop in
var attributesEffectiveRange = NSRange(location: NSNotFound, length: 0)
let attributesInRange: [NSAttributedString.Key: Any]
if opts.contains(.longestEffectiveRangeNotRequired) {
attributesInRange = attributes(at: currentIndex, effectiveRange: &attributesEffectiveRange)
} else {
attributesInRange = attributes(at: currentIndex, longestEffectiveRange: &attributesEffectiveRange, in: rangeLimit)
}
var shouldStop: ObjCBool = false
block(attributesInRange, attributesEffectiveRange, &shouldStop)
stop.pointee = shouldStop
return attributesEffectiveRange
}
}
/// Executes the block for the specified attribute run in the specified range.
open func enumerateAttribute(_ attrName: NSAttributedString.Key, in enumerationRange: NSRange, options opts: NSAttributedString.EnumerationOptions = [], using block: (Any?, NSRange, UnsafeMutablePointer<ObjCBool>) -> Swift.Void) {
_enumerate(in: enumerationRange, reversed: opts.contains(.reverse)) { currentIndex, rangeLimit, stop in
var attributeEffectiveRange = NSRange(location: NSNotFound, length: 0)
let attributeInRange: Any?
if opts.contains(.longestEffectiveRangeNotRequired) {
attributeInRange = attribute(attrName, at: currentIndex, effectiveRange: &attributeEffectiveRange)
} else {
attributeInRange = attribute(attrName, at: currentIndex, longestEffectiveRange: &attributeEffectiveRange, in: rangeLimit)
}
var shouldStop: ObjCBool = false
block(attributeInRange, attributeEffectiveRange, &shouldStop)
stop.pointee = shouldStop
return attributeEffectiveRange
}
}
public override var description: String {
let string = self.string
var description = ""
var lastUpperBound = string.startIndex
enumerateAttributes(in: NSRange(location: 0, length: self.length), options: []) { dict, range, stop in
var attrs = "{\n"
let keys = dict.keys.map({ $0.rawValue }).sorted()
for key in keys {
attrs += " \(key) = \(dict[NSAttributedString.Key(rawValue: key)]!);\n"
}
attrs += "}"
guard let stringRange = Range(NSRange(location: range.lowerBound, length: range.upperBound - range.lowerBound), in: string) else {
stop.pointee = true
return
}
let upperBound = stringRange.upperBound
description += string[lastUpperBound ..< upperBound]
lastUpperBound = upperBound
description += attrs
}
return description
}
}
private extension NSAttributedString {
struct AttributeEnumerationRange {
var startIndex: Int
var endIndex: Int
let reversed: Bool
var currentIndex: Int
var hasMore: Bool {
if reversed {
return currentIndex >= endIndex
} else {
return currentIndex <= endIndex
}
}
init(range: NSRange, reversed: Bool) {
let lowerBound = range.location
let upperBound = range.location + range.length - 1
self.reversed = reversed
startIndex = reversed ? upperBound : lowerBound
endIndex = reversed ? lowerBound : upperBound
currentIndex = startIndex
}
mutating func advance(range: NSRange, oldLength: Int, newLength: Int) {
if reversed {
startIndex = min(startIndex, newLength - 1)
currentIndex = range.lowerBound - 1
} else {
endIndex -= oldLength - newLength
currentIndex = range.upperBound - oldLength + newLength
}
}
var range: NSRange {
if reversed {
return NSRange(location: endIndex, length: startIndex - endIndex + 1)
}
else {
return NSRange(location: startIndex, length: endIndex - startIndex + 1)
}
}
}
struct RangeInfo {
let rangePointer: NSRangePointer?
let shouldFetchLongestEffectiveRange: Bool
let longestEffectiveRangeSearchRange: NSRange?
}
func _attributes(at location: Int, rangeInfo: RangeInfo) -> [NSAttributedString.Key: Any] {
var cfRange = CFRange()
return withUnsafeMutablePointer(to: &cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> [NSAttributedString.Key: Any] in
// Get attributes value using CoreFoundation function
let value: CFDictionary
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
value = CFAttributedStringGetAttributesAndLongestEffectiveRange(_cfObject, location, CFRange(searchRange), cfRangePointer)
} else {
value = CFAttributedStringGetAttributes(_cfObject, location, cfRangePointer)
}
// Convert the value to [String : AnyObject]
let dictionary = unsafeBitCast(value, to: NSDictionary.self)
var results = [NSAttributedString.Key: Any]()
for (key, value) in dictionary {
guard let stringKey = (key as? NSString)?._swiftObject else {
continue
}
results[NSAttributedString.Key(stringKey)] = value
}
// Update effective range and return the results
rangeInfo.rangePointer?.pointee.location = cfRangePointer.pointee.location
rangeInfo.rangePointer?.pointee.length = cfRangePointer.pointee.length
return results
}
}
func _attribute(_ attrName: NSAttributedString.Key, atIndex location: Int, rangeInfo: RangeInfo) -> Any? {
var cfRange = CFRange()
return withUnsafeMutablePointer(to: &cfRange) { (cfRangePointer: UnsafeMutablePointer<CFRange>) -> AnyObject? in
// Get attribute value using CoreFoundation function
let attribute: AnyObject?
if rangeInfo.shouldFetchLongestEffectiveRange, let searchRange = rangeInfo.longestEffectiveRangeSearchRange {
attribute = CFAttributedStringGetAttributeAndLongestEffectiveRange(_cfObject, location, attrName.rawValue._cfObject, CFRange(searchRange), cfRangePointer)
} else {
attribute = CFAttributedStringGetAttribute(_cfObject, location, attrName.rawValue._cfObject, cfRangePointer)
}
// Update effective range and return the result
rangeInfo.rangePointer?.pointee.location = cfRangePointer.pointee.location
rangeInfo.rangePointer?.pointee.length = cfRangePointer.pointee.length
return attribute
}
}
func _enumerate(in enumerationRange: NSRange, reversed: Bool, using block: (Int, NSRange, UnsafeMutablePointer<ObjCBool>) -> NSRange) {
var attributeEnumerationRange = AttributeEnumerationRange(range: enumerationRange, reversed: reversed)
while attributeEnumerationRange.hasMore {
var stop: ObjCBool = false
let oldLength = self.length
let effectiveRange = block(attributeEnumerationRange.currentIndex, attributeEnumerationRange.range, &stop)
attributeEnumerationRange.advance(range: effectiveRange, oldLength: oldLength, newLength: self.length)
if stop.boolValue {
break
}
}
}
func addAttributesToAttributeArray(attrs: [NSAttributedString.Key: Any]?) {
guard _string.length > 0 else {
return
}
let range = CFRange(location: 0, length: _string.length)
var attributes: [String : Any] = [:]
if let attrs = attrs {
attrs.forEach { attributes[$0.rawValue] = $1 }
}
CFRunArrayInsert(_attributeArray, range, attributes._cfObject)
}
}
extension NSAttributedString {
internal var _cfObject: CFAttributedString { return unsafeBitCast(self, to: CFAttributedString.self) }
}
extension NSAttributedString {
public struct EnumerationOptions: OptionSet {
public let rawValue: UInt
public init(rawValue: UInt) {
self.rawValue = rawValue
}
public static let reverse = EnumerationOptions(rawValue: 1 << 1)
public static let longestEffectiveRangeNotRequired = EnumerationOptions(rawValue: 1 << 20)
}
}
open class NSMutableAttributedString : NSAttributedString {
open func replaceCharacters(in range: NSRange, with str: String) {
CFAttributedStringReplaceString(_cfMutableObject, CFRange(range), str._cfObject)
}
open func setAttributes(_ attrs: [NSAttributedString.Key: Any]?, range: NSRange) {
guard let attrs = attrs else {
CFAttributedStringSetAttributes(_cfMutableObject, CFRange(range), nil, true)
return
}
CFAttributedStringSetAttributes(_cfMutableObject, CFRange(range), attributesCFDictionary(from: attrs), true)
}
open var mutableString: NSMutableString {
return _string as! NSMutableString
}
open func addAttribute(_ name: NSAttributedString.Key, value: Any, range: NSRange) {
CFAttributedStringSetAttribute(_cfMutableObject, CFRange(range), name.rawValue._cfObject, __SwiftValue.store(value))
}
open func addAttributes(_ attrs: [NSAttributedString.Key: Any], range: NSRange) {
CFAttributedStringSetAttributes(_cfMutableObject, CFRange(range), attributesCFDictionary(from: attrs), false)
}
open func removeAttribute(_ name: NSAttributedString.Key, range: NSRange) {
CFAttributedStringRemoveAttribute(_cfMutableObject, CFRange(range), name.rawValue._cfObject)
}
open func replaceCharacters(in range: NSRange, with attrString: NSAttributedString) {
CFAttributedStringReplaceAttributedString(_cfMutableObject, CFRange(range), attrString._cfObject)
}
open func insert(_ attrString: NSAttributedString, at loc: Int) {
let insertRange = NSRange(location: loc, length: 0)
replaceCharacters(in: insertRange, with: attrString)
}
open func append(_ attrString: NSAttributedString) {
let appendRange = NSRange(location: length, length: 0)
replaceCharacters(in: appendRange, with: attrString)
}
open func deleteCharacters(in range: NSRange) {
// To delete a range of the attributed string, call CFAttributedStringReplaceString() with empty string and specified range
let emptyString = ""._cfObject
CFAttributedStringReplaceString(_cfMutableObject, CFRange(range), emptyString)
}
open func setAttributedString(_ attrString: NSAttributedString) {
let fullStringRange = NSRange(location: 0, length: length)
replaceCharacters(in: fullStringRange, with: attrString)
}
open func beginEditing() {
CFAttributedStringBeginEditing(_cfMutableObject)
}
open func endEditing() {
CFAttributedStringEndEditing(_cfMutableObject)
}
open override func copy(with zone: NSZone? = nil) -> Any {
return NSAttributedString(attributedString: self)
}
public override init(string: String) {
super.init(string: string)
_string = NSMutableString(string: string)
}
public override init(string: String, attributes attrs: [NSAttributedString.Key: Any]? = nil) {
super.init(string: string, attributes: attrs)
_string = NSMutableString(string: string)
}
public override init(attributedString: NSAttributedString) {
super.init(attributedString: attributedString)
_string = NSMutableString(string: attributedString.string)
}
public required init?(coder aDecoder: NSCoder) {
let mutableAttributedString = NSMutableAttributedString(string: "")
guard _NSReadMutableAttributedStringWithCoder(aDecoder, mutableAttributedString: mutableAttributedString) else {
return nil
}
super.init(attributedString: mutableAttributedString)
_string = NSMutableString(string: mutableAttributedString.string)
}
}
extension NSMutableAttributedString {
internal var _cfMutableObject: CFMutableAttributedString { return unsafeBitCast(self, to: CFMutableAttributedString.self) }
}
private extension NSMutableAttributedString {
func attributesCFDictionary(from attrs: [NSAttributedString.Key: Any]) -> CFDictionary {
var attributesDictionary = [String : Any]()
for (key, value) in attrs {
attributesDictionary[key.rawValue] = value
}
return attributesDictionary._cfObject
}
}
// MARK: Coding
fileprivate let _allowedCodingClasses: [AnyClass] = [
NSNumber.self,
NSArray.self,
NSDictionary.self,
NSURL.self,
NSString.self,
]
internal func _NSReadIntFromMutableAttributedStringCoding(_ data: NSData, _ startingOffset: Int) -> (value: Int, newOffset: Int)? {
var multiplier = 1
var offset = startingOffset
let length = data.length
var value = 0
return withExtendedLifetime(data) { _ -> (Int, Int)? in
while offset < length {
let i = Int(data.bytes.load(fromByteOffset: offset, as: UInt8.self))
offset += 1
let isLast = i < 128
let intermediateValue = multiplier.multipliedReportingOverflow(by: isLast ? i : (i - 128))
guard !intermediateValue.overflow else { return nil }
let newValue = value.addingReportingOverflow(intermediateValue.partialValue)
guard !newValue.overflow else { return nil }
value = newValue.partialValue
if isLast {
return (value: value, newOffset: offset)
}
multiplier *= 128
}
return nil // Getting to the end of the stream indicates error, since we were still expecting more bytes
}
}
internal func _NSWriteIntToMutableAttributedStringCoding(_ i: Int, _ data: NSMutableData) {
if i > 127 {
let byte = UInt8(128 + i % 128);
data.append(Data([byte]))
_NSWriteIntToMutableAttributedStringCoding(i / 128, data)
} else {
data.append(Data([UInt8(i)]))
}
}
internal func _NSReadMutableAttributedStringWithCoder(_ decoder: NSCoder, mutableAttributedString: NSMutableAttributedString) -> Bool {
// NSAttributedString.Key is not currently bridging correctly every time we'd like it to.
// Ensure we manually go through String in the meanwhile. SR-XXXX.
func toAttributesDictionary(_ ns: NSDictionary) -> [NSAttributedString.Key: Any]? {
if let bridged = __SwiftValue.fetch(ns) as? [String: Any] {
return Dictionary(bridged.map { (NSAttributedString.Key($0.key), $0.value) }, uniquingKeysWith: { $1 })
} else {
return nil
}
}
guard decoder.allowsKeyedCoding else { /* Unkeyed unarchiving is not supported. */ return false }
let string = decoder.decodeObject(of: NSString.self, forKey: "NSString") ?? ""
mutableAttributedString.replaceCharacters(in: NSMakeRange(0, 0), with: string as String)
guard string.length > 0 else { return true }
var allowed = _allowedCodingClasses
for aClass in decoder.allowedClasses ?? [] {
if !allowed.contains(where: { $0 === aClass }) {
allowed.append(aClass)
}
}
let attributes = decoder.decodeObject(of: allowed, forKey: "NSAttributes")
// If this is present, 'attributes' should be an array; otherwise, a dictionary:
let attrData = decoder.decodeObject(of: NSData.self, forKey: "NSAttributeInfo")
if attrData == nil, let attributesNS = attributes as? NSDictionary, let attributes = toAttributesDictionary(attributesNS) {
mutableAttributedString.setAttributes(attributes, range: NSMakeRange(0, string.length))
return true
} else if let attrData = attrData, let attributesNS = attributes as? [NSDictionary] {
let attributes = attributesNS.compactMap { toAttributesDictionary($0) }
guard attributes.count == attributesNS.count else { return false }
var loc = 0
var offset = 0
let length = string.length
while loc < length {
var rangeLen = 0, arraySlot = 0
guard let intResult1 = _NSReadIntFromMutableAttributedStringCoding(attrData, offset) else { return false }
rangeLen = intResult1.value
offset = intResult1.newOffset
guard let intResult2 = _NSReadIntFromMutableAttributedStringCoding(attrData, offset) else { return false }
arraySlot = intResult2.value
offset = intResult2.newOffset
guard arraySlot < attributes.count else { return false }
mutableAttributedString.setAttributes(attributes[arraySlot], range: NSMakeRange(loc, rangeLen))
loc += rangeLen
}
return true
}
return false
}
| apache-2.0 | f2cb89086d06ec2d25ea38dc45517a71 | 40.995441 | 234 | 0.651467 | 5.597124 | false | false | false | false |
practicalswift/swift | test/IRGen/class_metadata.swift | 4 | 5872 | // RUN: %empty-directory(%t)
// RUN: %{python} %utils/chex.py < %s > %t/class_metadata.swift
// RUN: %target-swift-frontend -emit-ir %s | %FileCheck %t/class_metadata.swift -check-prefix=CHECK -check-prefix=CHECK-%target-ptrsize
class A {}
// CHECK: [[A_NAME:@.*]] = private constant [2 x i8] c"A\00"
// CHECK-LABEL: @"$s14class_metadata1ACMn" =
// Flags. 0x8000_0050 == HasVTable | Unique | Class
// CHECK-SAME: <i32 0x8000_0050>,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[A_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1ACMa"
// Superclass.
// CHECK-SAME: i32 0,
// Negative size in words.
// CHECK-SAME: i32 2,
// Positive size in words.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 13,
// CHECK-64-SAME: i32 10,
// V-table offset.
// CHECK-32-SAME: i32 13,
// CHECK-64-SAME: i32 10,
// V-table length.
// CHECK-SAME: i32 1,
// CHECK-SMAE: %swift.method_descriptor {
// V-table entry #1: flags.
// CHECK-SAME: i32 1
// V-table entry #1: invocation function.
// CHECK-SAME: @"$s14class_metadata1ACACycfC"
// CHECK-SAME: }>, section
class B : A {}
// CHECK: [[B_NAME:@.*]] = private constant [2 x i8] c"B\00"
// CHECK-LABEL: @"$s14class_metadata1BCMn" =
// Flags. 0x4000_0050 == HasOverrideTable | Unique | Class
// CHECK-SAME: <i32 0x4000_0050>,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[B_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1BCMa"
// Superclass type.
// CHECK-SAME: @"symbolic _____ 14class_metadata1AC"
// Negative size in words.
// CHECK-SAME: i32 2,
// Positive size in words.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// Immediate member count.
// CHECK-SAME: i32 0,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// Number of method overrides.
// CHECK-SAME: i32 1,
// CHECK-SAME: %swift.method_override_descriptor {
// Override table entry #1: base class.
// CHECK-SAME: @"$s14class_metadata1ACMn"
// Override table entry #1: base method.
// CHECK-SAME: @"$s14class_metadata1ACMn", i32 0, i32 13
// Override table entry #1: invocation function.
// CHECK-SAME: @"$s14class_metadata1BCACycfC"
// CHECK-SAME: }>, section
class C<T> : B {}
// CHECK: [[C_NAME:@.*]] = private constant [2 x i8] c"C\00"
// CHECK-LABEL: @"$s14class_metadata1CCMn" =
// Flags. 0x4000_00d0 == HasOverrideTable | Generic | Unique | Class
// CHECK-SAME: <i32 0x4000_00d0>,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[C_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1CCMa"
// Superclass type.
// CHECK-SAME: @"symbolic _____ 14class_metadata1BC"
// Negative size in words.
// CHECK-SAME: i32 2,
// Positive size in words.
// CHECK-32-SAME: i32 15,
// CHECK-64-SAME: i32 12,
// Num immediate members.
// CHECK-32-SAME: i32 1,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 15,
// CHECK-64-SAME: i32 12,
// Instantiation cache.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1CCMI"
// Instantiation pattern.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1CCMP"
// Generic parameter count.
// CHECK-SAME: i16 1,
// Generic requirement count.
// CHECK-SAME: i16 0,
// Key generic arguments count.
// CHECK-SAME: i16 1,
// Extra generic arguments count.
// CHECK-SAME: i16 0,
// Generic parameter descriptor #1: flags. -128 == 0x80 == Key
// CHECK-SAME: i8 -128,
// Padding.
// CHECK-SAME: i8 0,
// CHECK-SAME: i8 0,
// CHECK-SAME: i8 0,
// Number of method overrides.
// CHECK-SAME: i32 1,
// CHECK-SAME: %swift.method_override_descriptor {
// Override table entry #1: base class.
// CHECK-SAME: @"$s14class_metadata1ACMn"
// Override table entry #1: base method.
// CHECK-SAME: @"$s14class_metadata1ACMn", i32 0, i32 13
// Override table entry #1: invocation function.
// CHECK-SAME: @"$s14class_metadata1CCACyxGycfC"
// CHECK-SAME: }>, section
// CHECK-LABEL: @"$s14class_metadata1CCMP" =
// Instantiation function.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1CCMi"
// For stupid reasons, when we declare the superclass after the subclass,
// we end up using an indirect reference to the nominal type descriptor.
class D : E {}
// CHECK: [[D_NAME:@.*]] = private constant [2 x i8] c"D\00"
// CHECK-LABEL: @"$s14class_metadata1DCMn" =
// Flags. 0x4200_0050 == HasOverrideTable | Unique | Class
// CHECK-SAME: <i32 0x4000_0050>,
// Parent.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadataMXM"
// Name.
// CHECK-SAME: i32 {{.*}} [[D_NAME]]
// Metadata access function.
// CHECK-SAME: i32 {{.*}} @"$s14class_metadata1DCMa"
// Superclass type.
// CHECK-SAME: @"symbolic _____ 14class_metadata1EC"
// Negative size in words.
// CHECK-SAME: i32 2,
// Positive size in words.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// Immediate member count.
// CHECK-SAME: i32 0,
// Field count.
// CHECK-SAME: i32 0,
// Field offset vector offset.
// CHECK-32-SAME: i32 14,
// CHECK-64-SAME: i32 11,
// Number of method overrides.
// CHECK-SAME: i32 1,
// CHECK-SAME: %swift.method_override_descriptor {
// Override table entry #1: base class.
// CHECK-SAME: @"$s14class_metadata1ECMn"
// Override table entry #1: base method.
// CHECK-SAME: @"$s14class_metadata1ECMn"
// Override table entry #1: invocation function.
// CHECK-SAME: @"$s14class_metadata1DCACycfC"
// CHECK-SAME: }>, section
class E {}
// CHECK-LABEL: @"$s14class_metadata1FCMn" =
// CHECK-SAME: @"symbolic _____yq_G 14class_metadata1CC"
class F<T, U> : C<U> { }
| apache-2.0 | cb0a850ce0ede3c38ee5979d7dfd425f | 31.622222 | 135 | 0.641008 | 2.881256 | false | false | false | false |
markohlebar/Import | Import/Functions/Sandboxing.swift | 1 | 1546 | //
// Sandboxing.swift
// Import
//
// Created by Marko Hlebar on 30/11/2016.
// Copyright © 2016 Marko Hlebar. All rights reserved.
//
import Foundation
import Security
public struct Sandboxing {
//https://forums.developer.apple.com/message/135465#135465
public static func isAppSandboxed() -> Bool {
var err: OSStatus
var me: SecCode?
var dynamicInfo: CFDictionary?
let defaultFlags = SecCSFlags(rawValue: 0)
err = SecCodeCopySelf(defaultFlags, &me)
guard me != nil else {
return false
}
var staticMe: SecStaticCode?
err = SecCodeCopyStaticCode(me!, defaultFlags, &staticMe)
guard staticMe != nil else {
return false
}
err = SecCodeCopySigningInformation(staticMe!, SecCSFlags(rawValue: kSecCSDynamicInformation), &dynamicInfo)
assert(err == errSecSuccess)
if let info = dynamicInfo as? [String: Any],
let entitlementsDict = info["entitlements-dict"] as? [String: Any],
let value = entitlementsDict["com.apple.security.app-sandbox"] as? Bool {
return value
}
return false
}
public static func userHomePath() -> String {
guard let usersHomePath = getpwuid(getuid()).pointee.pw_dir else {
return ""
}
let usersHomePathString : String = FileManager.default.string(withFileSystemRepresentation: usersHomePath, length: Int(strlen(usersHomePath)))
return usersHomePathString
}
}
| mit | 2dd63386b61e66eb2513c7d6101e5214 | 27.090909 | 150 | 0.634304 | 4.45245 | false | false | false | false |
exyte/Macaw-Examples | AnimationPrinciples/AnimationPrinciples/Examples/MaterialViewController.swift | 1 | 1892 | //
// MaterialViewController.swift
// Animations
//
// Created by Alisa Mylnikova on 07/08/2018.
// Copyright © 2018 Exyte. All rights reserved.
//
import Macaw
class MaterialViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
let duration = 1.0
let sideSize = 100.0
let coeff = 1.2
let posDelta = sideSize * (1 - coeff) / 2
let rect = RoundRect(rect: Rect(x: 0, y: 0, w: sideSize, h: sideSize), rx: 5, ry: 5)
let springyShape = Shape(
form: rect,
fill: color,
place: .move(dx: 30, dy: 30)
)
let springyGrow = springyShape.placeVar.animation(to: springyShape.place.scale(sx: coeff, sy: coeff).move(dx: posDelta, dy: posDelta), during: duration, delay: 0.5).easing(.elasticInOut(elasticity: 5))
let springyShrink = springyShape.placeVar.animation(from: springyShape.place.scale(sx: coeff, sy: coeff).move(dx: posDelta, dy: posDelta), to: springyShape.place, during: duration, delay: 0.5).easing(.elasticInOut(elasticity: 5))
let springAnimation = [springyGrow, springyShrink].sequence()
let shape = Shape(
form: rect,
fill: color,
place: .move(dx: 180, dy: 30)
)
let grow = shape.placeVar.animation(to: shape.place.scale(sx: coeff, sy: coeff).move(dx: posDelta, dy: posDelta), during: duration, delay: 0.5).easing(.easeInOut)
let shrink = shape.placeVar.animation(from: shape.place.scale(sx: coeff, sy: coeff).move(dx: posDelta, dy: posDelta), to: shape.place, during: duration, delay: 0.5).easing(.easeInOut)
let regularAnimation = [grow, shrink].sequence()
animation = [springAnimation, regularAnimation].combine().cycle()
svgView.node = Group(contents: [springyShape, shape])
}
}
| mit | 5941bb72fab74e33a1c5311f0b0092b9 | 40.108696 | 237 | 0.62771 | 3.859184 | false | false | false | false |
gowansg/firefox-ios | Client/Frontend/Widgets/ThumbnailCell.swift | 1 | 2448 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.2)
private let LabelFont = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Bold" : "HelveticaNeue-Medium", size: 11)
private let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor.darkGrayColor()
private let CellInsets = UIEdgeInsetsMake(8, 8, 8, 8)
private let PlaceholderImage = UIImage(named: "defaultFavicon")
struct ThumbnailCellUX {
/// Ratio of width:height of the thumbnail image.
static let ImageAspectRatio: Float = 1.5
}
class ThumbnailCell: UICollectionViewCell {
let textLabel = UILabel()
let imageView = UIImageViewAligned()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(textLabel)
contentView.addSubview(imageView)
imageView.layer.borderColor = BorderColor.CGColor
imageView.layer.borderWidth = 1
imageView.layer.cornerRadius = 3
imageView.clipsToBounds = true
imageView.snp_makeConstraints({ make in
make.top.left.right.equalTo(self.contentView).insets(CellInsets)
make.width.equalTo(self.imageView.snp_height).multipliedBy(ThumbnailCellUX.ImageAspectRatio)
return
})
textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
textLabel.font = LabelFont
textLabel.textColor = LabelColor
textLabel.snp_makeConstraints({ make in
make.left.right.bottom.equalTo(self.contentView).insets(CellInsets)
return
})
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var image: UIImage? = nil {
didSet {
if let image = image {
imageView.image = image
imageView.alignment = UIImageViewAlignmentMaskTop
imageView.contentMode = UIViewContentMode.ScaleAspectFill
} else {
imageView.image = PlaceholderImage
imageView.alignment = UIImageViewAlignmentMaskCenter
imageView.contentMode = UIViewContentMode.Center
}
}
}
}
| mpl-2.0 | 22a75a637049d44e78f62c30bddcfa36 | 36.090909 | 130 | 0.677696 | 5.016393 | false | false | false | false |
crash-wu/SGRoutePlan | Example/Pods/SCMultipleTableView/SCMultipleTableView/SCMultipleTableView.swift | 1 | 24229 | //
// SCMultipleTableView.swift
// imapMobile
//
// Created by 吴小星 on 16/5/13.
// Copyright © 2016年 crash. All rights reserved.
//
import UIKit
/**
* @author crash [email protected] , 16-05-13 15:05:12
*
* @brief 两级列表协议
*/
@objc public protocol SCMultipleTableDelegate : NSObjectProtocol{
/**
计算每个section中单元格数量
:param: tableView 目标tableView
:param: section 目标section
:returns: section中单元格数量
*/
func m_tableView(tableView:SCMultipleTableView, numberOfRowsInSection section : Int) ->Int
/**
单元格布局
:param: tableView 目标tableView
:param: indexPath 单元格索引
:returns: 单元格
*/
func m_tableView(tableView:SCMultipleTableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell?
/**
计算tableView section数量
:param: tableView 目标tablieView
:returns: section 数量
*/
optional func numberOfSectionsInSCMutlipleTableView(tableView:SCMultipleTableView) ->Int
/**
计算cell高度
:param: tableView 目标tableView
:param: indexPath cell 索引
:returns: cell高度
*/
optional func m_tableView(tableView :SCMultipleTableView , heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
/**
section headView 高度
:param: tableView 目标tableView
:param: section 待计算的section
:returns: section headView 高度
*/
optional func m_tableView(tableView :SCMultipleTableView , heightForHeaderInSection section :Int) ->CGFloat
/**
section footView 高度
:param: tableView 目标tableView
:param: section 待计算的section
:returns: section headView 高度
*/
optional func m_tableView(tableView :SCMultipleTableView , heightForFootInSection section :Int) ->CGFloat
/**
section headView 样式
:param: tableView 目标tableView
:param: section
:returns: section headView 样式
*/
optional func m_tableView(tableView:SCMultipleTableView,viewForHeaderInSection section :Int) ->UIView?
/**
展开section 中的row 单元格
:param: tableView
:param: section 需要展开的section
*/
optional func m_tableView(tableView:SCMultipleTableView , willOpenSubRowFromSection section :Int) ->Void
/**
收起section 中的row 单元格
:param: tableView
:param: section 需要收起的section
:returns:
*/
optional func m_tableView(tableView:SCMultipleTableView ,willCloseSubRowFromSection section :Int) ->Void
/**
选中单元格
:param: tableView
:param: indexPath 单元格索引
:returns:
*/
optional func m_tableView(tableView:SCMultipleTableView ,didSelectRowAtIndexPath indexPath :NSIndexPath) ->Void
optional func m_scrollViewDidScroll(scrollView: UIScrollView)
optional func m_scrollViewDidZoom(scrollView: UIScrollView) // any zoom scale changes
// called on start of dragging (may require some time and or distance to move)
optional func m_scrollViewWillBeginDragging(scrollView: UIScrollView)
// called on finger up if the user dragged. velocity is in points/millisecond. targetContentOffset may be changed to adjust where the scroll view comes to rest
optional func m_scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
// called on finger up if the user dragged. decelerate is true if it will continue moving afterwards
optional func m_scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool)
optional func m_scrollViewWillBeginDecelerating(scrollView: UIScrollView) // called on finger up as we are moving
optional func m_scrollViewDidEndDecelerating(scrollView: UIScrollView) // called when scroll view grinds to a halt
optional func m_scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) // called when setContentOffset/scrollRectVisible:animated: finishes. not called if not animating
optional func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? // return a view that will be scaled. if delegate returns nil, nothing happens
optional func m_scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) // called before the scroll view begins zooming its content
optional func m_scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) // scale between minimum and maximum. called after any 'bounce' animations
optional func m_scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool // return a yes if you want to scroll to the top. if not defined, assumes YES
optional func m_scrollViewDidScrollToTop(scrollView: UIScrollView) // called when scrolling animation finished. may be called immediately if already at top
}
public class SCMultipleTableView: UIView ,UITableViewDataSource,UITableViewDelegate {
public var tableView :UITableView!
public var currentOpenedIndexPaths :Array<NSIndexPath>? = []//当前展开的所有cell的indexPath的数组
weak public var multipleDelegate : SCMultipleTableDelegate? //多重表格代理
public init(frame: CGRect ,style:UITableViewStyle) {
super.init(frame: frame)
tableView = UITableView(frame: frame, style: style)
tableView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .None
self.addSubview(tableView!)
}
required public init?(coder aDecoder: NSCoder) {
fatalError()
}
//=======================================//
// Mark :public methods //
//=======================================//
/**
根据标识符取出重用cell
:param: identifier 标识符
:returns: 可重用的cell,或者nil(如果没有可重用的)
*/
public func dequeueReusableCellWithIdentifier(identifier :String)->UITableViewCell?{
return self.tableView.dequeueReusableCellWithIdentifier(identifier)
}
/**
根据标识符 与cell索引取出可以重用的cell
:param: identifier 标识符
:param: indexPath cell索引
:returns:可重用的cell,或者nil(如果没有可重用的)
*/
public func dequeueReusableCellWithIdentifier(identifier :String ,forIndexPath indexPath :NSIndexPath) ->UITableViewCell?{
return self.tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
}
/**
根据标识符,取出可以重用的section headView or section footView
:param: identifier 标识符
:returns: 可重用的section headView or section footView
*/
public func dequeueReusableHeaderFooterViewWithIdentifier(identifier:String)->UITableViewHeaderFooterView?{
return self.tableView.dequeueReusableHeaderFooterViewWithIdentifier(identifier)
}
/**
取消表格选中状态
:param: indexPath 单元格索引
:param: animate
*/
public func deselectRowAtIndexPath(indexPath:NSIndexPath, animated animate:Bool)->Void{
self.tableView.deselectRowAtIndexPath(indexPath, animated: animate)
}
/**
刷新数据
*/
public func reload() ->Void{
self.tableView!.reloadData()
}
/**
刷新某一section的单元格
:param: sections 需要重新刷新数据的section
:param: animation 动画
*/
public func reloadSections(sections: NSIndexSet, withRowAnimation animation: UITableViewRowAnimation){
self.tableView.reloadSections(sections, withRowAnimation: animation)
}
//=======================================//
// Mark : private UITapGestureRecognizer //
//=======================================//
/**
为view添加一个tap手势,其行为为action
:param: anction 要添加的手势含有的行为
:param: view 需要添加手势的视图
*/
private func addTapGestureRecognizerAction(anction:Selector,toView view:UIView) ->Void{
let tapGR = UITapGestureRecognizer(target: self, action: anction)
view.addGestureRecognizer(tapGR)
}
/**
为view移除一个tap手势
:param: view 要移除手势的view
*/
private func removeTapGestureRecognizerInView(view:UIView) ->Void{
let gestures = view.gestureRecognizers! as [UIGestureRecognizer]
for gr in gestures {
if gr.view!.isEqual(view){
view.removeGestureRecognizer(gr)
}
}
}
/**
添加在header中的点击手势的方法
:param: gesture 点击手势
*/
@objc private func tableViewHeaderTouchUpInside(gesture : UITapGestureRecognizer) ->Void{
let section = gesture.view?.tag
openOrCloseRowWithSection(section!)
}
//.=======================================//
// Mark :open or close section row //
//=======================================//
/**
展开或者收起section中的row
:param: section tableView 中的section
*/
private func openOrCloseRowWithSection(section :Int) ->Void{
var openedIndexPaths :Array<NSIndexPath>? = []//展开的表格
var deleteIndexPaths :Array<NSIndexPath>? = []//收起的表格
//判断当前是否有row被展开
if self.currentOpenedIndexPaths?.count == 0 {
//当前没有任何子列表被打开
openedIndexPaths = self.indexPathsForOpenRowFromSection(section)
}else{
//当前有row被展开
var found = false
//遍历
for ip in self.currentOpenedIndexPaths!{
//关闭当前已经打开的子列表
if ip.section == section{
found = true
deleteIndexPaths = self.indexPathsForCloseRowFromSection(section)
break
}
}
//展开新的section
if !found {
openedIndexPaths = self.indexPathsForOpenRowFromSection(section)
}
}
self.tableView.beginUpdates()
if openedIndexPaths?.count > 0 {
self.tableView.insertRowsAtIndexPaths(openedIndexPaths!, withRowAnimation: .Automatic)
}
if deleteIndexPaths?.count > 0 {
self.tableView.deleteRowsAtIndexPaths(deleteIndexPaths!, withRowAnimation: .Automatic)
}
self.tableView.endUpdates()
let range = NSRange(location: section, length: 1)
let indexSet = NSIndexSet(indexesInRange: range)
self.tableView.reloadSections(indexSet, withRowAnimation: .Automatic)
}
/**
展开一个section 中的row
:param: section 待展开的row所在的section
:return: 该section内所有indexPath信息
*/
private func indexPathsForOpenRowFromSection(section:Int) ->Array<NSIndexPath>?{
var indexPaths :Array<NSIndexPath>? = []
let rowCount = get_numberOfRowsInSection(section)
//调用代理,判断代理是否实现展开section row 的方法
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:willOpenSubRowFromSection:))) {
//如果实现该方法,
self.multipleDelegate?.m_tableView!(self, willOpenSubRowFromSection: section)
}
//打开了第section个子列表
self.currentOpenedIndexPaths?.append(NSIndexPath(forRow: -1, inSection: section))
//往当前section中添加row
for i in 0 ..< rowCount {
indexPaths?.append(NSIndexPath(forRow: i , inSection: section))
}
return indexPaths
}
/**
收起已经展开的section
:param: section 需要收起的section
:returns: 该section内所有indexPath信息
*/
private func indexPathsForCloseRowFromSection(section:Int) -> Array<NSIndexPath>?{
var indexPathS :Array<NSIndexPath>? = []
let rowCount = self.get_numberOfRowsInSection(section)
//判断代理是否实现收起section中的行
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:willCloseSubRowFromSection:))) {
self.multipleDelegate?.m_tableView!(self, willCloseSubRowFromSection: section)
}
//遍历数组,删除元素
for (index ,value ) in (self.currentOpenedIndexPaths?.enumerate())!{
if value.section == section{
self.currentOpenedIndexPaths?.removeAtIndex(index)
break
}
}
//关闭第section个子列表
for i in 0..<rowCount{
indexPathS?.append(NSIndexPath(forRow: i , inSection: section))
}
return indexPathS
}
//.=======================================//
// Mark : UITableViewDateSource //
//=======================================//
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//查找没有打开row 的section
var found = false
for ip in self.currentOpenedIndexPaths!{
if section == ip.section {
found = true
break
}
}
//判断row 是否已经打开
if found {
//如果打开了,则需要计算该section下有多少row
return get_numberOfRowsInSection(section)
}else{
//如果没有打开,则返回0
return 0
}
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height :CGFloat = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:heightForRowAtIndexPath:))){
height = (self.multipleDelegate?.m_tableView!(self, heightForRowAtIndexPath: indexPath))!
}
return height
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return get_cellForRowAtIndexPath(indexPath)
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return get_numberOfSection()
}
//.=======================================//
// Mark :UITableDelegate //
//=======================================//
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
get_didSelectRowAtIndexPath(indexPath)
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var height :CGFloat = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.numberOfSectionsInSCMutlipleTableView(_:))){
height = get_heightForHeaderInSection(section)
}
return height
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
var height :CGFloat = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.numberOfSectionsInSCMutlipleTableView(_:))){
height = get_heightForFootInSection(section)
}
return height
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headView = get_viewForHeaderInSection(section)
if headView != nil{
let height = self.tableView(tableView, heightForHeaderInSection: section)
headView?.frame = CGRectMake(0, 0, self.tableView!.frame.size.width, height)
headView?.tag = section
}
//给section headView 添加点击事件
addTapGestureRecognizerAction(#selector(SCMultipleTableView.tableViewHeaderTouchUpInside(_:)), toView: headView!)
return headView
}
//.=======================================//
// Mark : private func //
//=======================================//
/**
获取每个section中的row数目
:param: section 表格中的section
:returns: section中的row数目
*/
private func get_numberOfRowsInSection(section:Int) ->Int{
// var row = self.multipleDelegate?.m_tableView(self, numberOfRowsInSection: section) ?? 0
var row : Int = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:numberOfRowsInSection:))) {
row = self.multipleDelegate!.m_tableView(self, numberOfRowsInSection: section)
}
return row
}
/**
获取表格中的section数目
:returns: 获取表格中的section数目
*/
private func get_numberOfSection() ->Int{
var number = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.numberOfSectionsInSCMutlipleTableView(_:))) {
number = (self.multipleDelegate?.numberOfSectionsInSCMutlipleTableView!(self))!
}
return number
}
/**
获取tableView 中的单元格
:param: indexPath 表格索引
:returns: 返回tableView中的单元格
*/
private func get_cellForRowAtIndexPath(indexPath:NSIndexPath) ->UITableViewCell{
var cell :UITableViewCell?
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:cellForRowAtIndexPath:))) {
cell = self.multipleDelegate?.m_tableView(self, cellForRowAtIndexPath: indexPath)
}
return cell!
}
/**
获取点中的单元格
:param: indexPath 单元格索引
*/
private func get_didSelectRowAtIndexPath(indexPath:NSIndexPath) ->Void{
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:didSelectRowAtIndexPath:))) {
self.multipleDelegate?.m_tableView!(self, didSelectRowAtIndexPath: indexPath)
}
}
/**
获取tableView section头部高度
:param: section section索引
:returns: 返回section头部高度
*/
private func get_heightForHeaderInSection(section:Int) ->CGFloat{
var height:CGFloat = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:heightForHeaderInSection:))) {
height = (self.multipleDelegate?.m_tableView!(self, heightForHeaderInSection: section))!
}
return height
}
/**
获取tableView section尾部
:param: section section索引
:returns: 返回section尾部高度
*/
private func get_heightForFootInSection(section:Int) ->CGFloat{
var height:CGFloat = 0
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:heightForFootInSection:))) {
height = (self.multipleDelegate?.m_tableView!(self, heightForFootInSection: section))!
}
return height
}
/**
获取section headView
:param: section tableView section索引
:returns: tableView section headView
*/
private func get_viewForHeaderInSection(section:Int) ->UIView?{
var view :UIView?
if self.multipleDelegate != nil && self.multipleDelegate!.respondsToSelector(#selector(SCMultipleTableDelegate.m_tableView(_:viewForHeaderInSection:))) {
view = self.multipleDelegate?.m_tableView!(self, viewForHeaderInSection: section)
}
return view
}
//MARK: UIScrollViewDelegate
public func scrollViewDidScroll(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewDidScroll?(scrollView)
}
public func scrollViewDidZoom(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewDidZoom?(scrollView)
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewWillBeginDragging?(scrollView)
}
public func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
self.multipleDelegate?.m_scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewDidEndDecelerating?(scrollView)
}
public func scrollViewDidEndScrollingAnimation(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewDidEndScrollingAnimation?(scrollView)
}
public func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
var view :UIView?
view = self.multipleDelegate?.viewForZoomingInScrollView?(scrollView)
return view
}
public func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
self.multipleDelegate?.m_scrollViewWillBeginZooming?(scrollView, withView: view)
}
public func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
self.multipleDelegate?.m_scrollViewDidEndZooming?(scrollView, withView: view, atScale: scale)
}
public func scrollViewDidScrollToTop(scrollView: UIScrollView) {
self.multipleDelegate?.m_scrollViewDidScrollToTop?(scrollView)
}
public func scrollViewShouldScrollToTop(scrollView: UIScrollView) -> Bool {
return self.multipleDelegate?.m_scrollViewShouldScrollToTop?(scrollView) ?? false
}
}
| mit | dab5b20e4506382da76efd6db6ab3188 | 28.323116 | 193 | 0.603963 | 5.917526 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Platform/Sources/PlatformKit/Services/ExchangeProvider.swift | 1 | 1647 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import Foundation
import MoneyKit
import ToolKit
/// A provider for exchange rates as per supported crypto.
public protocol ExchangeProviding: AnyObject {
/// Returns the exchange service
subscript(currency: Currency) -> PairExchangeServiceAPI { get }
/// Refreshes all the exchange rates
func refresh()
}
final class ExchangeProvider: ExchangeProviding {
// MARK: - Subscript
subscript(currency: Currency) -> PairExchangeServiceAPI {
retrieveOrCreate(currency: currency.currencyType)
}
// MARK: - Private Properties
private let services: Atomic<[CurrencyType: PairExchangeServiceAPI]>
private let fiatCurrencyService: FiatCurrencyServiceAPI
// MARK: - Init
init(fiatCurrencyService: FiatCurrencyServiceAPI = resolve()) {
services = Atomic([:])
self.fiatCurrencyService = fiatCurrencyService
}
// MARK: - Methods
func refresh() {
services.value.values.forEach { service in
service.fetchTriggerRelay.accept(())
}
}
// MARK: - Private Methods
private func retrieveOrCreate(currency: CurrencyType) -> PairExchangeServiceAPI {
services.mutateAndReturn { services -> PairExchangeServiceAPI in
if let service = services[currency] {
return service
}
let service = PairExchangeService(
currency: currency,
fiatCurrencyService: fiatCurrencyService
)
services[currency] = service
return service
}
}
}
| lgpl-3.0 | cc07f1a651a48d1a95a17c5b89c6ef98 | 25.983607 | 85 | 0.657959 | 5.695502 | false | false | false | false |
jpsim/PeerKit | PeerKit/PeerKit.swift | 1 | 4267 | //
// PeerKit.swift
// CardsAgainst
//
// Created by JP Simard on 11/5/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import Foundation
import MultipeerConnectivity
// MARK: Type Aliases
public typealias PeerBlock = ((_ myPeerID: MCPeerID, _ peerID: MCPeerID) -> Void)
public typealias EventBlock = ((_ peerID: MCPeerID, _ event: String, _ object: AnyObject?) -> Void)
public typealias ObjectBlock = ((_ peerID: MCPeerID, _ object: AnyObject?) -> Void)
public typealias ResourceBlock = ((_ myPeerID: MCPeerID, _ resourceName: String, _ peer: MCPeerID, _ localURL: URL?) -> Void)
// MARK: Event Blocks
public var onConnecting: PeerBlock?
public var onConnect: PeerBlock?
public var onDisconnect: PeerBlock?
public var onEvent: EventBlock?
public var onEventObject: ObjectBlock?
public var onFinishReceivingResource: ResourceBlock?
public var eventBlocks = [String: ObjectBlock]()
// MARK: PeerKit Globals
#if os(iOS)
import UIKit
public let myName = UIDevice.current.name
#else
public let myName = Host.current().localizedName ?? ""
#endif
public var transceiver = Transceiver(displayName: myName)
public var session: MCSession?
// MARK: Event Handling
func didConnecting(myPeerID: MCPeerID, peer: MCPeerID) {
if let onConnecting = onConnecting {
DispatchQueue.main.async {
onConnecting(myPeerID, peer)
}
}
}
func didConnect(myPeerID: MCPeerID, peer: MCPeerID) {
if session == nil {
session = transceiver.session.mcSession
}
if let onConnect = onConnect {
DispatchQueue.main.async {
onConnect(myPeerID, peer)
}
}
}
func didDisconnect(myPeerID: MCPeerID, peer: MCPeerID) {
if let onDisconnect = onDisconnect {
DispatchQueue.main.async {
onDisconnect(myPeerID, peer)
}
}
}
func didReceiveData(_ data: Data, fromPeer peer: MCPeerID) {
if let dict = NSKeyedUnarchiver.unarchiveObject(with: data) as? [String: AnyObject],
let event = dict["event"] as? String,
let object = dict["object"] {
DispatchQueue.main.async {
if let onEvent = onEvent {
onEvent(peer, event, object)
}
if let eventBlock = eventBlocks[event] {
eventBlock(peer, object)
}
}
}
}
func didFinishReceivingResource(myPeerID: MCPeerID, resourceName: String, fromPeer peer: MCPeerID, atURL localURL: URL?) {
if let onFinishReceivingResource = onFinishReceivingResource {
DispatchQueue.main.async {
onFinishReceivingResource(myPeerID, resourceName, peer, localURL)
}
}
}
// MARK: Advertise/Browse
public func transceive(serviceType: String, discoveryInfo: [String: String]? = nil) {
transceiver.startTransceiving(serviceType: serviceType, discoveryInfo: discoveryInfo)
}
public func advertise(serviceType: String, discoveryInfo: [String: String]? = nil) {
transceiver.startAdvertising(serviceType: serviceType, discoveryInfo: discoveryInfo)
}
public func browse(serviceType: String) {
transceiver.startBrowsing(serviceType: serviceType)
}
public func stopTransceiving() {
transceiver.stopTransceiving()
session = nil
}
// MARK: Events
public func sendEvent(_ event: String, object: AnyObject? = nil, toPeers peers: [MCPeerID]? = session?.connectedPeers) {
guard let peers = peers, !peers.isEmpty else {
return
}
var rootObject: [String: AnyObject] = ["event": event as AnyObject]
if let object: AnyObject = object {
rootObject["object"] = object
}
let data = NSKeyedArchiver.archivedData(withRootObject: rootObject)
do {
try session?.send(data, toPeers: peers, with: .reliable)
} catch _ {
}
}
public func sendResourceAtURL(_ resourceURL: URL,
withName resourceName: String,
toPeers peers: [MCPeerID]? = session?.connectedPeers,
withCompletionHandler completionHandler: ((Error?) -> Void)?) -> [Progress?]? {
if let session = session {
return peers?.map { peerID in
return session.sendResource(at: resourceURL, withName: resourceName, toPeer: peerID, withCompletionHandler: completionHandler)
}
}
return nil
}
| mit | e92ba679388db66248eb76f39502b611 | 28.631944 | 138 | 0.67401 | 4.435551 | false | false | false | false |
hmx101607/mhweibo | weibo/weibo/App/model/WBHomeStatusViewModel.swift | 1 | 1966 | //
// WBHomeStatusViewModel.swift
// weibo
//
// Created by mason on 2017/8/19.
// Copyright © 2017年 mason. All rights reserved.
//
import UIKit
class WBHomeStatusViewModel: NSObject {
var status : WBHomeStatusModel?
var sourceText : String?
var createdAtText : String?
var verifiedImage : UIImage?
var vipImage : UIImage?
var picUrls : [URL] = [URL]()
init (status : WBHomeStatusModel) {
self.status = status
if let source = status.source, source != "" {
let startIndex = (source as NSString).range(of: ">").location + 1
let length = (source as NSString).range(of: "</").location - startIndex
sourceText = (source as NSString).substring(with: NSRange(location: startIndex, length: length))
}
if let created_at = status.created_at {
createdAtText = NSDate.createDateString(createAtStr: created_at)
}
let verifiedType = status.user?.verified_type ?? -1
switch verifiedType {
case 0 :
verifiedImage = UIImage(named: "avatar_vip")
case 2, 3, 5 :
verifiedImage = UIImage(named: "avatar_enterprise_vip")
case 220 :
verifiedImage = UIImage(named: "avatar_grassroot")
default:
verifiedImage = nil
}
let mbrank = status.user?.mbrank ?? 0
if mbrank > 0 && mbrank <= 6 {
vipImage = UIImage(named: "common_icon_membership_level\(mbrank)")
}
let picURLDicts = status.pic_urls!.count != 0 ? status.pic_urls : status.retweeted_status?.pic_urls
if let picURLDicts = picURLDicts {
for picURLDict in picURLDicts {
if let picURLString = picURLDict["thumbnail_pic" ] {
picUrls.append(NSURL(string: picURLString)! as URL)
}
}
}
}
}
| mit | 267191310a2937320a8f0881bbab5020 | 29.671875 | 108 | 0.561386 | 4.471526 | false | false | false | false |
nzaghini/mastering-reuse-viper | Weather/Modules/WeatherLocation/Core/View/WeatherLocationViewController.swift | 2 | 3994 | import UIKit
import ASToast
class WeatherLocationViewController: UIViewController {
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
var presenter: WeatherLocationPresenter?
var viewModel: SelectableLocationListViewModel?
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = UIRectEdge()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(cancelAction))
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.keyboardDismissMode = .onDrag
self.searchBar.delegate = self
self.spinner.hidesWhenStopped = true
self.presenter?.loadContent()
}
// MARK: Actions
func cancelAction() {
self.searchBar.resignFirstResponder()
self.presenter?.cancelSearchForLocation()
}
// MARK: Helpers
fileprivate func showToastWithText(_ text: String) {
view.makeToast(message: text, duration: TimeInterval(3.0), position: .center, backgroundColor: nil, messageColor: nil, font: nil)
}
}
// MARK: - <WeatherLocationView>
extension WeatherLocationViewController: WeatherLocationView {
func displayLoading() {
self.searchBar.isHidden = false
self.tableView.isHidden = true
self.spinner.startAnimating()
}
func displaySearch() {
self.searchBar.isHidden = false
self.tableView.isHidden = false
self.spinner.stopAnimating()
self.searchBar.becomeFirstResponder()
}
func displayNoResults() {
self.searchBar.isHidden = false
self.tableView.isHidden = false
self.spinner.stopAnimating()
self.viewModel = nil
self.tableView.reloadData()
self.showToastWithText("No Results")
}
func displayErrorMessage(_ errorMessage: String) {
self.searchBar.isHidden = false
self.tableView.isHidden = false
self.spinner.stopAnimating()
self.showToastWithText(errorMessage)
}
func displayLocations(_ viewModel: SelectableLocationListViewModel) {
self.searchBar.isHidden = false
self.tableView.isHidden = false
self.spinner.stopAnimating()
self.viewModel = viewModel
self.tableView.reloadData()
}
}
// MARK: - <UISearchBarDelegate>
extension WeatherLocationViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
if let text = searchBar.text {
self.presenter?.searchLocation(text)
}
}
}
// MARK: - <UITableViewDelegate>
extension WeatherLocationViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let location = self.viewModel?.locations[indexPath.row] {
self.presenter?.selectLocation(location.locationId)
}
}
}
// MARK: - <UITableViewDataSource>
extension WeatherLocationViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel?.locations.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "WeatherLocationCell")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "WeatherLocationCell")
}
if let location = self.viewModel?.locations[indexPath.row] {
cell?.textLabel?.text = location.name
cell?.detailTextLabel?.text = location.detail
}
return cell!
}
}
| mit | 59f42db56a99163fef506b9ce3ab9c51 | 28.585185 | 141 | 0.656234 | 5.508966 | false | false | false | false |
RoverPlatform/rover-ios | Sources/Location/GeofencesSyncParticipant.swift | 1 | 2472 | //
// GeofencesSyncParticipant.swift
// RoverLocation
//
// Created by Sean Rucker on 2018-08-29.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import CoreData
import os.log
#if !COCOAPODS
import RoverFoundation
import RoverData
#endif
class GeofencesSyncParticipant: PagingSyncParticipant {
typealias Response = GeofencesSyncResponse
let context: NSManagedObjectContext
let userDefaults: UserDefaults
var cursorKey: String {
return "io.rover.RoverLocation.geofencesCursor"
}
var participants = [SyncParticipant]()
init(context: NSManagedObjectContext, userDefaults: UserDefaults) {
self.context = context
self.userDefaults = userDefaults
}
func nextRequest(cursor: String?) -> SyncRequest {
let orderBy: Attributes = [
"field": "UPDATED_AT",
"direction": "ASC"
]
var values: [String: Any] = [
"first": 500,
"orderBy": orderBy
]
if let cursor = cursor {
values["after"] = cursor
}
return SyncRequest(query: SyncQuery.geofences, values: values)
}
func insertObject(from node: GeofencesSyncResponse.Data.Geofences.Node) {
let geofence = Geofence(context: context)
geofence.id = node.id
geofence.name = node.name
geofence.latitude = node.center.latitude
geofence.longitude = node.center.longitude
geofence.radius = node.radius
geofence.tags = node.tags
}
}
// MARK: GeofencesSyncResponse
struct GeofencesSyncResponse: Decodable {
struct Data: Decodable {
struct Geofences: Decodable {
struct Node: Decodable {
struct Center: Decodable {
var latitude: Double
var longitude: Double
}
var id: String
var name: String
var center: Center
var radius: Double
var tags: [String]
}
var nodes: [Node]?
var pageInfo: PageInfo
}
var geofences: Geofences
}
var data: Data
}
extension GeofencesSyncResponse: PagingResponse {
var nodes: [Data.Geofences.Node]? {
return data.geofences.nodes
}
var pageInfo: PageInfo {
return data.geofences.pageInfo
}
}
| apache-2.0 | 7976763cf5fd2b2fe0c27deb466a92ff | 24.214286 | 77 | 0.579522 | 4.961847 | false | false | false | false |
aestesis/Aether | Sources/Aether/Foundation/Rect.swift | 1 | 19522 | //
// Rect.swift
// Aether
//
// Created by renan jegouzo on 23/02/2016.
// Copyright © 2016 aestesis. 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 SwiftyJSON
#if os(macOS) || os(iOS) || os(tvOS)
import CoreGraphics
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct Rect : CustomStringConvertible,JsonConvertible {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var origin: Point
public var size: Size
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var x: Double {
get { return origin.x }
set(x){ origin.x=x }
}
public var y: Double {
get { return origin.y }
set(y){ origin.y=y }
}
public var w: Double {
get { return size.width }
set(width){ size.width=width; }
}
public var h: Double {
get { return size.height }
set(height){ size.height=height; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var width: Double {
get { return size.width }
set(width){ size.width=width; }
}
public var height: Double {
get { return size.height }
set(height){ size.height=height }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var left: Double {
get { return x }
set(l) { w+=x-l; x=l }
}
public var right: Double {
get { return x+width }
set(r) { width=r-x }
}
public var top: Double {
get { return y }
set(t) { h+=y-t; y=t }
}
public var bottom: Double {
get { return y+height }
set(b) { height=b-y }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var topLeft : Point {
return Point(left,top)
}
public var topRight : Point {
return Point(right,top)
}
public var bottomLeft : Point {
return Point(left,bottom)
}
public var bottomRight : Point {
return Point(right,bottom)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func intersect(_ r:Rect) -> Bool {
return !(self.right < r.left || self.bottom < r.top || self.left > r.right || self.top > r.bottom)
}
public func intersection(_ r:Rect) -> Rect {
var rr = Rect.zero
rr.left = max(self.left,r.left)
rr.right = min(self.right,r.right)
rr.top = max(self.top,r.top)
rr.bottom = min(self.bottom,r.bottom)
if rr.w<=0 || rr.h<=0 {
return Rect.zero
}
return rr
}
public func union(_ r:Rect) -> Rect {
if self == Rect.zero {
return r
} else if r == Rect.zero {
return self
} else {
var rr = Rect.zero
rr.left = min(self.left,r.left)
rr.right = max(self.right,r.right)
rr.top = min(self.top,r.top)
rr.bottom = max(self.bottom,r.bottom)
return rr
}
}
public func union(_ o:Point,_ s:Size=Size(1,1)) -> Rect {
return self.union(Rect(o:o,s:s))
}
public func extend(_ border:Double) -> Rect {
return Rect(o:Point(x-border,y-border),s:size.extend(border))
}
public func extend(w:Double,h:Double) -> Rect {
return Rect(o:Point(x-w,y-h),s:size.extend(w:w,h:h))
}
public func extend(_ border:Size) -> Rect {
return Rect(x:x-border.w,y:y-border.h,w:w+border.w*2,h:h+border.h*2)
}
public var bounds : Rect {
return Rect(o:Point.zero,s:size)
}
public var ceil : Rect {
return Rect(o:origin.floor,s:size.ceil)
}
public var center: Point {
get { return origin+size.scale(0.5).point }
set(c) { origin = c - size.scale(0.5).point }
}
public func clip(point p:Point) -> Point {
return constrains(point:p)
}
public func contains(_ point:Point) -> Bool {
return point.x>=left&&point.x<=right&&point.y>=top&&point.y<=bottom
}
public func constrains(point p: Point) -> Point {
return Point(min(max(left,p.x),right),min(max(top,p.y),bottom))
}
public func crop(_ ratio:Double,align:Align=Align.fullCenter,margin:Double=0) -> Rect {
let dd=ratio
let ds=self.ratio
var r=Rect.zero
if ds>dd {
let h=height-margin*2;
let w=dd*h;
r=Rect(x:x+(width-w)*0.5,y:y+margin,w:w,h:h);
} else {
let w=width-margin*2;
let h=w/dd;
r=Rect(x:x+margin, y:y+(height-h)*0.5,w:w,h:h);
}
switch(align.horizontalPart) {
case .right:
r.x = self.right-r.width
case .left:
r.x = self.x
default:
break
}
switch(align.verticalPart) {
case .top:
r.y = self.y
case .bottom:
r.y = self.bottom - r.height
default:
break
}
return r
}
public var description: String {
return "{x:\(x),y:\(y),w:\(width),h:\(height)}"
}
public var diagonale : Double {
return sqrt(width*width+height*height)
}
public func fit(_ ratio:Double,margin:Double=0) -> Rect {
let dd=ratio
let ds=self.ratio
if ds<dd {
let h=height-margin*2;
let w=dd*h;
return Rect(x:x+(width-w)*0.5,y:y+margin,w:w,h:h);
} else {
let w=width-margin*2;
let h=w/dd;
return Rect(x:x+margin,y:y+(height-h)*0.5,w:w,h:h);
}
}
public func fit(rect r:Rect,align a:Align = .centerMiddle) -> Rect {
let s=max(r.w/self.w,r.h/self.h)
var rd = Rect(0,0,w*s,h*s)
switch a.horizontalPart {
case .right:
rd.x = r.right - rd.width
case.middle:
rd.center.x = r.center.x
default:
break
}
switch a.verticalPart {
case .bottom:
rd.y = r.bottom - rd.height
case .center:
rd.center.y = r.center.y
default:
break
}
return rd
}
public func aligned(in r:Rect,align a:Align) -> Rect {
var rd = self
switch a.horizontalPart {
case .right:
rd.x = r.right - rd.width
case.middle:
rd.center.x = r.center.x
default:
break
}
switch a.verticalPart {
case .bottom:
rd.y = r.bottom - rd.height
case .center:
rd.center.y = r.center.y
default:
break
}
return rd
}
public var floor : Rect {
return Rect(o:origin.ceil,s:size.floor)
}
public var int: RectI {
return RectI(x:Int(x),y:Int(y),w:Int(width),h:Int(height))
}
public var json: JSON {
return JSON(["x":x,"y":y,"w":w,"h":h])
}
public func lerp(_ to:Rect,coef:Double) -> Rect {
return Rect(o:origin.lerp(to.origin,coef:coef),s:size.lerp(to.size,coef:coef))
}
public func percent(_ r:Rect) -> Rect {
return Rect(x:x+width*r.x,y:y+height*r.y,w:width*r.w,h:height*r.h)
}
public func percent(_ px:Double=0,_ py:Double=0,_ pw:Double=1,_ ph:Double=1) -> Rect {
return Rect(x:x+width*px,y:y+height*py,w:width*pw,h:height*ph)
}
public func percent(px:Double=0,py:Double=0,pw:Double=1,ph:Double=1) -> Rect {
return Rect(x:x+width*px,y:y+height*py,w:width*pw,h:height*ph)
}
public func point(_ px:Double,_ py:Double) -> Point {
return Point(x+width*px,y+height*py)
}
public func point(px:Double,py:Double) -> Point {
return Point(x+width*px,y+height*py)
}
public func point(_ percent:Point) -> Point {
return Point(x+width*percent.x,y+height*percent.y)
}
public func point(align:Align) -> Point {
return self.point(align.point)
}
public var ratio : Double {
return size.ratio
}
public var random : Point {
return Point(x+width*ß.rnd,y+height*ß.rnd)
}
public var rotate : Rect {
return Rect(x:y,y:x,w:height,h:width)
}
public var round : Rect {
return Rect(o:origin.round,s:size.round)
}
public func scale(_ scale:Double) -> Rect {
let sz=size.scale(scale)
return Rect(origin:origin.translate(-0.5*(sz.width-width),-0.5*(sz.height-height)),size:sz)
}
public func scale(_ w:Double,_ h:Double) -> Rect {
let sz=size.scale(w,h)
return Rect(origin:origin.translate(-0.5*(sz.width-width),-0.5*(sz.height-height)),size:sz)
}
public func scale(_ w:Double,h:Double) -> Rect {
let sz=size.scale(w,h)
return Rect(origin:origin.translate(-0.5*(sz.width-width),-0.5*(sz.height-height)),size:sz)
}
public var square : Rect {
let m=min(width,height)
return Rect(x:x+(width-m)*0.5,y:y+(height-m)*0.5,w:m,h:m)
}
public var strip : [Point] {
return [self.topLeft,self.bottomLeft,self.topRight,self.bottomRight]
}
public func strip(_ rotation:Rotation) -> [Point] {
switch rotation {
case .none:
return [self.topLeft,self.bottomLeft,self.topRight,self.bottomRight]
case .anticlockwise:
return [self.topRight,self.topLeft,self.bottomRight,self.bottomLeft]
case .clockwise:
return [self.bottomLeft,self.bottomRight,self.topLeft,self.topRight]
case .upSideDown:
return [self.bottomLeft,self.topLeft,self.bottomRight,self.topRight]
}
}
public var surface : Double {
return size.surface
}
public func translate(x:Double,y:Double) -> Rect {
return Rect(o:Point(origin.x+x,origin.y+y),s:size)
}
public func translate(_ point:Point) -> Rect {
return Rect(o:Point(self.x+point.x,self.y+point.y),s:size)
}
public func wrap(_ p:Point) -> Point {
return Point(x:ß.modulo(p.x-left,width)+left,y:ß.modulo(p.y-top,height)+top)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(_ r:CGRect) {
self.origin=Point(r.origin)
self.size=Size(r.size)
}
public init(_ r:RectI) {
self.origin=Point(p:r.origin)
self.size=Size(r.size)
}
public init(origin: Point,size: Size) {
self.origin=origin
self.size=size
}
public init(o: Point,s: Size) {
self.origin=o
self.size=s
}
public init(x:Double,y:Double,w:Double,h:Double)
{
origin=Point(x,y)
size=Size(w,h)
}
public init(_ x:Double,_ y:Double,_ w:Double,_ h:Double)
{
origin=Point(x,y)
size=Size(w,h)
}
public init(left:Double,top:Double,right:Double,bottom:Double) {
origin=Point(left,top)
size=Size(right-left,bottom-top)
}
public init(json: JSON) {
origin=Point(json:json);
size=Size(json:json);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var system : CGRect {
return CGRect(origin: origin.system, size: size.system)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: Rect {
return Rect(o:Point.zero,s:Size.zero)
}
public static var infinity: Rect {
return Rect(o:-Point.infinity,s:Size.infinity)
}
public static var unity: Rect {
return Rect(o:Point.zero,s:Size.unity)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: Rect, rhs: Rect) -> Bool {
return (lhs.origin==rhs.origin)&&(lhs.size==rhs.size)
}
public func !=(lhs: Rect, rhs: Rect) -> Bool {
return (lhs.origin != rhs.origin)||(lhs.size != rhs.size)
}
public func +(lhs: Rect, rhs: Rect) -> Rect {
return Rect(left:min(lhs.left,rhs.left),top:min(lhs.top,rhs.top),right:max(lhs.right,rhs.right),bottom:max(lhs.bottom,rhs.bottom))
}
public func +(lhs: Rect, rhs: Point) -> Rect {
return Rect(left:min(lhs.left,rhs.x),top:min(lhs.top,rhs.y),right:max(lhs.right,rhs.x),bottom:max(lhs.bottom,rhs.y))
}
public func *(lhs: Rect, rhs: Size) -> Rect {
return Rect(x:lhs.x*rhs.w,y:lhs.y*rhs.h,w:lhs.w*rhs.w,h:lhs.h*rhs.h)
}
public func /(lhs: Rect, rhs: Size) -> Rect {
return Rect(x:lhs.x/rhs.w,y:lhs.y/rhs.h,w:lhs.w/rhs.w,h:lhs.h/rhs.h)
}
public func *(l:Rect,r:Double) -> Rect {
return Rect(x:l.x*r,y:l.y*r,w:l.w*r,h:l.h*r)
}
public func /(l:Rect,r:Double) -> Rect {
return Rect(x:l.x/r,y:l.y/r,w:l.w/r,h:l.h/r)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public struct RectI : CustomStringConvertible,JsonConvertible {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var origin: PointI
public var size: SizeI
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var x: Int {
get { return origin.x }
set(x){ origin.x=x }
}
public var y: Int {
get { return origin.y }
set(y){ origin.y=y }
}
public var w: Int {
get { return size.width }
set(width){ size.width=width; }
}
public var h: Int {
get { return size.height }
set(height){ size.height=height; }
}
public var width: Int {
get { return size.width }
set(width){ size.width=width; }
}
public var height: Int {
get { return size.height }
set(height){ size.height=height; }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var left: Int {
get { return x }
set { x=left; }
}
public var right: Int {
get { return x+width }
set { width=right-x }
}
public var top: Int {
get { return y }
set { y=top }
}
public var bottom: Int {
get { return y+height }
set { height=bottom-y }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var topleft : PointI {
return PointI(x:left,y:top)
}
public var topright : PointI {
return PointI(x:right,y:top)
}
public var bottomleft : PointI {
return PointI(x:left,y:bottom)
}
public var bottomright : PointI {
return PointI(x:right,y:bottom)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public var description: String {
return "{x:\(x),y:\(y),w:\(width),h:\(height)}"
}
public var json: JSON {
return JSON([x:x,y:y,w:w,h:h])
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public init(origin: PointI,size: SizeI) {
self.origin=origin;
self.size=size;
}
public init(o: PointI,s: SizeI) {
self.origin=o;
self.size=s;
}
public init(x:Int,y:Int,w:Int,h:Int)
{
origin=PointI(x:x,y:y);
size=SizeI(w,h);
}
public init(left:Int,top:Int,right:Int,bottom:Int) {
origin=PointI(x:left,y:top)
size=SizeI(right-left,bottom-top)
}
public init(json: JSON) {
origin=PointI(json:json);
size=SizeI(json:json);
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public static var zero: RectI {
return RectI(o:PointI.zero,s:SizeI.zero)
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
public func ==(lhs: RectI, rhs: RectI) -> Bool {
return (lhs.origin==rhs.origin)&&(lhs.size==rhs.size);
}
public func +(lhs: RectI, rhs: RectI) -> RectI {
return RectI(left:min(lhs.left,rhs.left),top:min(lhs.top,rhs.top),right:max(lhs.right,rhs.right),bottom:max(lhs.bottom,rhs.bottom))
}
public func +(lhs: RectI, rhs: PointI) -> RectI {
return RectI(left:min(lhs.left,rhs.x),top:min(lhs.top,rhs.y),right:max(lhs.right,rhs.x),bottom:max(lhs.bottom,rhs.y))
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////
| apache-2.0 | dfa0d9d8c04343aa05471690f6ea6378 | 35.755179 | 135 | 0.436645 | 4.054217 | false | false | false | false |
zzgo/v2ex | v2ex/Pods/PKHUD/PKHUD/FrameView.swift | 9 | 1795 | //
// HUDView.swift
// PKHUD
//
// Created by Philip Kluz on 6/16/14.
// Copyright (c) 2016 NSExceptional. All rights reserved.
// Licensed under the MIT license.
//
import UIKit
/// Provides the general look and feel of the PKHUD, into which the eventual content is inserted.
internal class FrameView: UIVisualEffectView {
internal init() {
super.init(effect: UIBlurEffect(style: .light))
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
fileprivate func commonInit() {
backgroundColor = UIColor(white: 0.8, alpha: 0.36)
layer.cornerRadius = 9.0
layer.masksToBounds = true
contentView.addSubview(self.content)
let offset = 20.0
let motionEffectsX = UIInterpolatingMotionEffect(keyPath: "center.x", type: .tiltAlongHorizontalAxis)
motionEffectsX.maximumRelativeValue = offset
motionEffectsX.minimumRelativeValue = -offset
let motionEffectsY = UIInterpolatingMotionEffect(keyPath: "center.y", type: .tiltAlongVerticalAxis)
motionEffectsY.maximumRelativeValue = offset
motionEffectsY.minimumRelativeValue = -offset
let group = UIMotionEffectGroup()
group.motionEffects = [motionEffectsX, motionEffectsY]
addMotionEffect(group)
}
fileprivate var _content = UIView()
internal var content: UIView {
get {
return _content
}
set {
_content.removeFromSuperview()
_content = newValue
_content.alpha = 0.85
_content.clipsToBounds = true
_content.contentMode = .center
frame.size = _content.bounds.size
addSubview(_content)
}
}
}
| mit | 26410e1005d73926bf8de243a14cf91f | 27.492063 | 109 | 0.639554 | 4.891008 | false | false | false | false |
stripe/stripe-ios | Stripe/STPCardScanner.swift | 1 | 19473 | //
// STPCardScanner.swift
// StripeiOS
//
// Created by David Estes on 8/17/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
import AVFoundation
import Foundation
@_spi(STP) import StripeCore
@_spi(STP) import StripePayments
@_spi(STP) import StripePaymentsUI
import UIKit
import Vision
enum STPCardScannerError: Int {
/// Camera not available.
case cameraNotAvailable
}
@available(iOS 13, macCatalyst 14, *)
@objc protocol STPCardScannerDelegate: NSObjectProtocol {
@objc(cardScanner:didFinishWithCardParams:error:) func cardScanner(
_ scanner: STPCardScanner,
didFinishWith cardParams: STPPaymentMethodCardParams?,
error: Error?
)
}
@available(iOS 13, macCatalyst 14, *)
@objc(STPCardScanner_legacy)
class STPCardScanner: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate,
STPCardScanningProtocol
{
// iOS will kill the app if it tries to request the camera without an NSCameraUsageDescription
static let cardScanningAvailableCameraHasUsageDescription = {
return
(Bundle.main.infoDictionary?["NSCameraUsageDescription"] != nil
|| Bundle.main.localizedInfoDictionary?["NSCameraUsageDescription"] != nil)
}()
static var cardScanningAvailable: Bool {
// Always allow in tests:
if NSClassFromString("XCTest") != nil {
return true
}
return cardScanningAvailableCameraHasUsageDescription
}
weak var cameraView: STPCameraView?
var feedbackGenerator: UINotificationFeedbackGenerator?
@objc public var deviceOrientation: UIDeviceOrientation {
get {
return stp_deviceOrientation
}
set(newDeviceOrientation) {
stp_deviceOrientation = newDeviceOrientation
// This is an optimization for portrait mode: The card will be centered in the screen,
// so we can ignore the top and bottom. We'll use the whole frame in landscape.
let kSTPCardScanningScreenCenter = CGRect(
x: 0,
y: CGFloat(0.3),
width: 1,
height: CGFloat(0.4)
)
// iOS camera image data is returned in LandcapeLeft orientation by default. We'll flip it as needed:
switch newDeviceOrientation {
case .portraitUpsideDown:
videoOrientation = .portraitUpsideDown
textOrientation = .left
regionOfInterest = kSTPCardScanningScreenCenter
case .landscapeLeft:
videoOrientation = .landscapeRight
textOrientation = .up
regionOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
case .landscapeRight:
videoOrientation = .landscapeLeft
textOrientation = .down
regionOfInterest = CGRect(x: 0, y: 0, width: 1, height: 1)
case .portrait, .faceUp, .faceDown, .unknown:
// swift-format-ignore: NoCasesWithOnlyFallthrough
fallthrough
default:
videoOrientation = .portrait
textOrientation = .right
regionOfInterest = kSTPCardScanningScreenCenter
}
cameraView?.videoPreviewLayer.connection?.videoOrientation = videoOrientation
}
}
override init() {
}
init(
delegate: STPCardScannerDelegate?
) {
super.init()
self.delegate = delegate
captureSessionQueue = DispatchQueue(label: "com.stripe.CardScanning.CaptureSessionQueue")
deviceOrientation = UIDevice.current.orientation
}
func start() {
if isScanning {
return
}
STPAnalyticsClient.sharedClient.addClass(toProductUsageIfNecessary: STPCardScanner.self)
startTime = Date()
isScanning = true
didTimeout = false
timeoutStarted = false
feedbackGenerator = UINotificationFeedbackGenerator()
feedbackGenerator?.prepare()
captureSessionQueue?.async(execute: {
#if targetEnvironment(simulator)
// Camera not supported on Simulator
self.stopWithError(STPCardScanner.stp_cardScanningError())
return
#else
self.detectedNumbers = NSCountedSet() // capacity: 5
self.detectedExpirations = NSCountedSet() // capacity: 5
self.setupCamera()
DispatchQueue.main.async(execute: {
self.cameraView?.captureSession = self.captureSession
self.cameraView?.videoPreviewLayer.connection?.videoOrientation =
self.videoOrientation
})
#endif
})
}
func stop() {
stopWithError(nil)
}
private weak var delegate: STPCardScannerDelegate?
private var captureDevice: AVCaptureDevice?
private var captureSession: AVCaptureSession?
private var captureSessionQueue: DispatchQueue?
private var videoDataOutput: AVCaptureVideoDataOutput?
private var videoDataOutputQueue: DispatchQueue?
private var textRequest: VNRecognizeTextRequest?
private var isScanning = false
private var didTimeout = false
private var timeoutStarted = false
private var stp_deviceOrientation: UIDeviceOrientation!
private var videoOrientation: AVCaptureVideoOrientation!
private var textOrientation: CGImagePropertyOrientation!
private var regionOfInterest = CGRect.zero
private var detectedNumbers: NSCountedSet?
private var detectedExpirations: NSCountedSet?
private var startTime: Date?
// MARK: Public
class func stp_cardScanningError() -> Error {
let userInfo = [
NSLocalizedDescriptionKey: String.Localized.allow_camera_access,
STPError.errorMessageKey: "The camera couldn't be used.",
]
return NSError(
domain: STPCardScannerErrorDomain,
code: STPCardScannerError.cameraNotAvailable.rawValue,
userInfo: userInfo
)
}
deinit {
if isScanning {
captureDevice?.unlockForConfiguration()
captureSession?.stopRunning()
}
}
func stopWithError(_ error: Error?) {
if isScanning {
finish(with: nil, error: error)
}
}
// MARK: Setup
func setupCamera() {
weak var weakSelf = self
textRequest = VNRecognizeTextRequest(completionHandler: { request, error in
let strongSelf = weakSelf
if !(strongSelf?.isScanning ?? false) {
return
}
if error != nil {
strongSelf?.stopWithError(STPCardScanner.stp_cardScanningError())
return
}
strongSelf?.processVNRequest(request)
})
let captureDevice = AVCaptureDevice.default(
.builtInWideAngleCamera,
for: .video,
position: .back
)
self.captureDevice = captureDevice
captureSession = AVCaptureSession()
captureSession?.sessionPreset = .hd1920x1080
var deviceInput: AVCaptureDeviceInput?
do {
if let captureDevice = captureDevice {
deviceInput = try AVCaptureDeviceInput(device: captureDevice)
}
} catch {
stopWithError(STPCardScanner.stp_cardScanningError())
return
}
if let deviceInput = deviceInput {
if captureSession?.canAddInput(deviceInput) ?? false {
captureSession?.addInput(deviceInput)
} else {
stopWithError(STPCardScanner.stp_cardScanningError())
return
}
}
videoDataOutputQueue = DispatchQueue(label: "com.stripe.CardScanning.VideoDataOutputQueue")
videoDataOutput = AVCaptureVideoDataOutput()
videoDataOutput?.alwaysDiscardsLateVideoFrames = true
videoDataOutput?.setSampleBufferDelegate(self, queue: videoDataOutputQueue)
// This is the recommended pixel buffer format for Vision:
videoDataOutput?.videoSettings = [
kCVPixelBufferPixelFormatTypeKey as String:
kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
]
if let videoDataOutput = videoDataOutput {
if captureSession?.canAddOutput(videoDataOutput) ?? false {
captureSession?.addOutput(videoDataOutput)
} else {
stopWithError(STPCardScanner.stp_cardScanningError())
return
}
}
// This improves recognition quality, but means the VideoDataOutput buffers won't match what we're seeing on screen.
videoDataOutput?.connection(with: .video)?.preferredVideoStabilizationMode = .auto
captureSession?.startRunning()
do {
try self.captureDevice?.lockForConfiguration()
self.captureDevice?.autoFocusRangeRestriction = .near
} catch {
}
}
// MARK: Processing
func captureOutput(
_ output: AVCaptureOutput,
didOutput sampleBuffer: CMSampleBuffer,
from connection: AVCaptureConnection
) {
if !isScanning {
return
}
let pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
if pixelBuffer == nil {
return
}
textRequest?.recognitionLevel = .accurate
textRequest?.usesLanguageCorrection = false
textRequest?.regionOfInterest = regionOfInterest
var handler: VNImageRequestHandler?
if let pixelBuffer = pixelBuffer {
handler = VNImageRequestHandler(
cvPixelBuffer: pixelBuffer,
orientation: textOrientation,
options: [:]
)
}
do {
try handler?.perform([textRequest].compactMap { $0 })
} catch {
}
}
func processVNRequest(_ request: VNRequest) {
var allNumbers: [String] = []
for observation in request.results ?? [] {
guard let observation = observation as? VNRecognizedTextObservation else {
continue
}
let candidates = observation.topCandidates(5)
let topCandidate = candidates.first?.string
if STPCardValidator.sanitizedNumericString(for: topCandidate ?? "").count >= 4 {
allNumbers.append(topCandidate ?? "")
}
for recognizedText in candidates {
let possibleNumber = STPCardValidator.sanitizedNumericString(
for: recognizedText.string
)
// This probably isn't something we're interested in, so don't bother processing it.
if possibleNumber.count < 4 {
continue
}
// First strategy: We check if Vision sent us a number in a group on its own. If that fails, we'll try
// to catch it later when we iterate over all the numbers.
if STPCardValidator.validationState(
forNumber: possibleNumber,
validatingCardBrand: true
)
== .valid
{
addDetectedNumber(possibleNumber)
} else if possibleNumber.count >= 4 && possibleNumber.count <= 6
&& STPStringUtils.stringMayContainExpirationDate(recognizedText.string)
{
// Try to parse anything that looks like an expiration date.
let expirationString = STPStringUtils.expirationDateString(
from: recognizedText.string
)
let sanitizedExpiration = STPCardValidator.sanitizedNumericString(
for: expirationString ?? ""
)
let month = (sanitizedExpiration as NSString).substring(to: 2)
let year = (sanitizedExpiration as NSString).substring(from: 2)
// Ignore expiration dates 10+ years in the future, as they're likely to be incorrect recognitions
let calendar = Calendar(identifier: .gregorian)
let presentYear = calendar.component(.year, from: Date())
let maxYear = (presentYear % 100) + 10
if STPCardValidator.validationState(forExpirationYear: year, inMonth: month)
== .valid
&& Int(year) ?? 0 < maxYear
{
addDetectedExpiration(sanitizedExpiration)
}
}
}
}
// Second strategy: We look for consecutive groups of 4/4/4/4 or 4/6/5
// Vision is sending us groups like ["1234 565", "1234 1"], so we'll normalize these into groups with spaces:
let allGroups = allNumbers.joined(separator: " ").components(separatedBy: " ")
if allGroups.count < 3 {
return
}
for i in 0..<(allGroups.count - 3) {
let string1 = allGroups[i]
let string2 = allGroups[i + 1]
let string3 = allGroups[i + 2]
var string4 = ""
if i + 3 < allGroups.count {
string4 = allGroups[i + 3]
}
// Then we'll go through each group and build a potential match:
let potentialCardString = "\(string1)\(string2)\(string3)\(string4)"
let potentialAmexString = "\(string1)\(string2)\(string3)"
// Then we'll add valid matches. It's okay if we add a number a second time after doing so above, as the success of that first pass means it's more likely to be a good match.
if STPCardValidator.validationState(
forNumber: potentialCardString,
validatingCardBrand: true
)
== .valid
{
addDetectedNumber(potentialCardString)
} else if STPCardValidator.validationState(
forNumber: potentialAmexString,
validatingCardBrand: true
) == .valid {
addDetectedNumber(potentialAmexString)
}
}
}
func addDetectedNumber(_ number: String) {
detectedNumbers?.add(number)
// Set a timeout: If we don't get enough scans in the next 1 second, we'll use the best option we have.
if !timeoutStarted {
timeoutStarted = true
weak var weakSelf = self
DispatchQueue.main.async(execute: {
let strongSelf = weakSelf
strongSelf?.cameraView?.playSnapshotAnimation()
strongSelf?.feedbackGenerator?.notificationOccurred(.success)
})
videoDataOutputQueue?.asyncAfter(
deadline: DispatchTime.now() + Double(
Int64(kSTPCardScanningTimeout * Double(NSEC_PER_SEC))
)
/ Double(NSEC_PER_SEC),
execute: {
let strongSelf = weakSelf
if strongSelf?.isScanning ?? false {
strongSelf?.didTimeout = true
strongSelf?.finishIfReady()
}
}
)
}
if (detectedNumbers?.count(for: number) ?? 0) >= kSTPCardScanningMinimumValidScans {
finishIfReady()
}
}
func addDetectedExpiration(_ expiration: String) {
detectedExpirations?.add(expiration)
if (detectedExpirations?.count(for: expiration) ?? 0) >= kSTPCardScanningMinimumValidScans {
finishIfReady()
}
}
// MARK: Completion
func finishIfReady() {
if !isScanning {
return
}
let detectedNumbers = self.detectedNumbers
let detectedExpirations = self.detectedExpirations
let topNumber = (detectedNumbers?.allObjects as NSArray?)?.sortedArray(comparator: {
obj1,
obj2 in
let c1 = detectedNumbers?.count(for: obj1) ?? 0
let c2 = detectedNumbers?.count(for: obj2) ?? 0
if c1 < c2 {
return .orderedAscending
} else if c1 > c2 {
return .orderedDescending
} else {
return .orderedSame
}
}).last
let topExpiration = (detectedExpirations?.allObjects as NSArray?)?.sortedArray(comparator: {
obj1,
obj2 in
let c1 = detectedExpirations?.count(for: obj1) ?? 0
let c2 = detectedExpirations?.count(for: obj2) ?? 0
if c1 < c2 {
return .orderedAscending
} else if c1 > c2 {
return .orderedDescending
} else {
return .orderedSame
}
}).last
if didTimeout
|| (((detectedNumbers?.count(for: topNumber ?? 0) ?? 0)
>= kSTPCardScanningMinimumValidScans)
&& ((detectedExpirations?.count(for: topExpiration ?? 0) ?? 0)
>= kSTPCardScanningMinimumValidScans))
|| ((detectedNumbers?.count(for: topNumber ?? 0) ?? 0) >= kSTPCardScanningMaxValidScans)
{
let params = STPPaymentMethodCardParams()
params.number = topNumber as? String
if let topExpiration = topExpiration {
params.expMonth = NSNumber(
value: Int((topExpiration as! NSString).substring(to: 2)) ?? 0
)
params.expYear = NSNumber(
value: Int((topExpiration as! NSString).substring(from: 2)) ?? 0
)
}
finish(with: params, error: nil)
}
}
func finish(with params: STPPaymentMethodCardParams?, error: Error?) {
var duration: TimeInterval?
if let startTime = startTime {
duration = Date().timeIntervalSince(startTime)
}
isScanning = false
captureDevice?.unlockForConfiguration()
captureSession?.stopRunning()
DispatchQueue.main.async(execute: {
if params == nil {
STPAnalyticsClient.sharedClient.logCardScanCancelled(withDuration: duration ?? 0.0)
} else {
STPAnalyticsClient.sharedClient.logCardScanSucceeded(withDuration: duration ?? 0.0)
}
self.feedbackGenerator = nil
self.cameraView?.captureSession = nil
self.delegate?.cardScanner(self, didFinishWith: params, error: error)
})
}
// MARK: Orientation
}
// The number of successful scans required for both card number and expiration date before returning a result.
private let kSTPCardScanningMinimumValidScans = 2
// If no expiration date is found, we'll return a result after this many successful scans.
private let kSTPCardScanningMaxValidScans = 3
// Once one successful scan is found, we'll stop scanning after this many seconds.
private let kSTPCardScanningTimeout: TimeInterval = 1.0
let STPCardScannerErrorDomain = "STPCardScannerErrorDomain"
@available(iOS 13, macCatalyst 14, *)
/// :nodoc:
extension STPCardScanner: STPAnalyticsProtocol {
static var stp_analyticsIdentifier = "STPCardScanner"
}
| mit | 2b5ab019730ce723c964169f75e2d63c | 36.590734 | 186 | 0.590643 | 5.766065 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/Pods/MaterialKit/Source/MKLabel.swift | 1 | 3567 | //
// MKLabel.swift
// MaterialKit
//
// Created by Le Van Nghia on 11/29/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
open class MKLabel: UILabel {
@IBInspectable open var maskEnabled: Bool = true {
didSet {
mkLayer.maskEnabled = maskEnabled
}
}
@IBInspectable open var cornerRadius: CGFloat = 0 {
didSet {
self.layer.cornerRadius = self.cornerRadius
mkLayer.superLayerDidResize()
}
}
@IBInspectable open var elevation: CGFloat = 0 {
didSet {
mkLayer.elevation = elevation
}
}
@IBInspectable override open var shadowOffset: CGSize {
didSet {
mkLayer.shadowOffset = shadowOffset
}
}
@IBInspectable open var roundingCorners: UIRectCorner = UIRectCorner.allCorners {
didSet {
mkLayer.roundingCorners = roundingCorners
}
}
@IBInspectable open var rippleEnabled: Bool = true {
didSet {
mkLayer.rippleEnabled = rippleEnabled
}
}
@IBInspectable open var rippleDuration: CFTimeInterval = 0.35 {
didSet {
mkLayer.rippleDuration = rippleDuration
}
}
@IBInspectable open var rippleScaleRatio: CGFloat = 1.0 {
didSet {
mkLayer.rippleScaleRatio = rippleScaleRatio
}
}
@IBInspectable open var rippleLayerColor: UIColor = UIColor(hex: 0xEEEEEE) {
didSet {
mkLayer.setRippleColor(rippleLayerColor)
}
}
@IBInspectable open var backgroundAnimationEnabled: Bool = true {
didSet {
mkLayer.backgroundAnimationEnabled = backgroundAnimationEnabled
}
}
override open var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
fileprivate lazy var mkLayer: MKLayer = MKLayer(withView: self)
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
override public init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
// MARK: Setup
fileprivate func setupLayer() {
mkLayer.elevation = self.elevation
self.layer.cornerRadius = self.cornerRadius
mkLayer.elevationOffset = self.shadowOffset
mkLayer.roundingCorners = self.roundingCorners
mkLayer.maskEnabled = self.maskEnabled
mkLayer.rippleScaleRatio = self.rippleScaleRatio
mkLayer.rippleDuration = self.rippleDuration
mkLayer.rippleEnabled = self.rippleEnabled
mkLayer.backgroundAnimationEnabled = self.backgroundAnimationEnabled
mkLayer.setRippleColor(self.rippleLayerColor)
}
// MARK: Touch
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
mkLayer.touchesBegan(touches, withEvent: event)
}
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
mkLayer.touchesEnded(touches, withEvent: event)
}
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
mkLayer.touchesCancelled(touches, withEvent: event)
}
open override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
mkLayer.touchesMoved(touches, withEvent: event)
}
}
| mit | dca0774c1b4eca732ef425a2125116df | 30.017391 | 88 | 0.640875 | 5.199708 | false | false | false | false |
seanwoodward/IBAnimatable | IBAnimatableApp/TransitionViewController.swift | 1 | 1093 | //
// Created by Jake Lin on 3/1/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
import IBAnimatable
class TransitionViewController: AnimatableViewController {
@IBOutlet var presentButton: AnimatableButton!
override func viewDidLoad() {
super.viewDidLoad()
// Transition animations start with `System` do not support Present transition, so hide it
if let animationType = transitionAnimationType where animationType.hasPrefix("System") {
// Cannot use `hidden` here because of `UIStackView`
presentButton.alpha = 0
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
// Set the transition animation type for `AnimatableViewController`, used for Present/Dismiss transitions
if let toViewController = segue.destinationViewController as? AnimatableViewController {
toViewController.transitionAnimationType = transitionAnimationType
toViewController.interactiveGestureType = interactiveGestureType
}
}
}
| mit | 03888cb2d6c2072e64ee0e37db1e19b6 | 33.125 | 109 | 0.748168 | 5.515152 | false | false | false | false |
kitasuke/SwiftProtobufSample | Client/Client/TalkViewController.swift | 1 | 3525 | //
// TalkViewController.swift
// Client
//
// Created by Yusuke Kita on 2/20/17.
// Copyright © 2017 Yusuke Kita. All rights reserved.
//
import UIKit
class TalkViewController: UIViewController {
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var descriptionLabel: UILabel!
@IBOutlet private var tagLabels: [UILabel]!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var imageView: UIImageView!
@IBOutlet private weak var introductionLabel: UILabel!
var contentType: APIClient.ContentType!
var apiClient: APIClient!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
apiClient = APIClient(contentType: contentType)
updateViews()
}
private func updateViews() {
// fetch talk information from server
apiClient.fetchTalks(success: { [weak self] response in
print(response)
// show talk information
let talk = response.talks[0]
self?.titleLabel.text = talk.title
self?.descriptionLabel.text = talk.desc
if let labels = self?.tagLabels {
for (index, label) in labels.enumerated() {
label.text = talk.tags[index]
}
}
self?.nameLabel.text = talk.speaker.name
self?.introductionLabel.text = talk.speaker.introduction
DispatchQueue.global().async {
guard let data = try? Data(contentsOf: URL(string: talk.speaker.photoURL)!),
let image = UIImage(data: data) else {
return
}
DispatchQueue.main.async {
self?.imageView.image = image
}
}
}) { [weak self] error in
// it's required to run server app to get response
let alertController = UIAlertController(title: "Network error", message: "Make sure that your server app is running. See README for more details", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default) { _ in
let _ = self?.navigationController?.popViewController(animated: true)
}
alertController.addAction(action)
self?.present(alertController, animated: true, completion: nil)
}
}
@IBAction private func likeButtonPressed() {
let body = LikeRequest.with {
$0.id = 1
}
// this API always returns network error
apiClient.like(body: body, success: { response in
print(response)
}) { [weak self] error in
print(error)
let title: String
let message: String
switch error.code {
case .badRequest:
title = "\(error.code)"
message = error.message
default:
title = "Error"
message = "Unexpected error occured"
}
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(action)
self?.present(alertController, animated: true, completion: nil)
}
}
}
| mit | b8657eb8eaa5bf032adb51fe93256b9a | 35.329897 | 182 | 0.567537 | 5.228487 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/Moya/Sources/Moya/MoyaProvider+Internal.swift | 4 | 14111 | import Foundation
import Result
// MARK: - Method
extension Method {
/// A Boolean value determining whether the request supports multipart.
public var supportsMultipart: Bool {
switch self {
case .post, .put, .patch, .connect:
return true
case .get, .delete, .head, .options, .trace:
return false
}
}
}
// MARK: - MoyaProvider
/// Internal extension to keep the inner-workings outside the main Moya.swift file.
public extension MoyaProvider {
/// Performs normal requests.
func requestNormal(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable {
let endpoint = self.endpoint(target)
let stubBehavior = self.stubClosure(target)
let cancellableToken = CancellableWrapper()
// Allow plugins to modify response
let pluginsWithCompletion: Moya.Completion = { result in
let processedResult = self.plugins.reduce(result) { $1.process($0, target: target) }
completion(processedResult)
}
if trackInflights {
objc_sync_enter(self)
var inflightCompletionBlocks = self.inflightRequests[endpoint]
inflightCompletionBlocks?.append(pluginsWithCompletion)
self.inflightRequests[endpoint] = inflightCompletionBlocks
objc_sync_exit(self)
if inflightCompletionBlocks != nil {
return cancellableToken
} else {
objc_sync_enter(self)
self.inflightRequests[endpoint] = [pluginsWithCompletion]
objc_sync_exit(self)
}
}
let performNetworking = { (requestResult: Result<URLRequest, MoyaError>) in
if cancellableToken.isCancelled {
self.cancelCompletion(pluginsWithCompletion, target: target)
return
}
var request: URLRequest!
switch requestResult {
case .success(let urlRequest):
request = urlRequest
case .failure(let error):
pluginsWithCompletion(.failure(error))
return
}
// Allow plugins to modify request
let preparedRequest = self.plugins.reduce(request) { $1.prepare($0, target: target) }
let networkCompletion: Moya.Completion = { result in
if self.trackInflights {
self.inflightRequests[endpoint]?.forEach { $0(result) }
objc_sync_enter(self)
self.inflightRequests.removeValue(forKey: endpoint)
objc_sync_exit(self)
} else {
pluginsWithCompletion(result)
}
}
cancellableToken.innerCancellable = self.performRequest(target, request: preparedRequest, callbackQueue: callbackQueue, progress: progress, completion: networkCompletion, endpoint: endpoint, stubBehavior: stubBehavior)
}
requestClosure(endpoint, performNetworking)
return cancellableToken
}
// swiftlint:disable:next function_parameter_count
private func performRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion, endpoint: Endpoint, stubBehavior: Moya.StubBehavior) -> Cancellable {
switch stubBehavior {
case .never:
switch endpoint.task {
case .requestPlain, .requestData, .requestJSONEncodable, .requestCustomJSONEncodable, .requestParameters, .requestCompositeData, .requestCompositeParameters:
return self.sendRequest(target, request: request, callbackQueue: callbackQueue, progress: progress, completion: completion)
case .uploadFile(let file):
return self.sendUploadFile(target, request: request, callbackQueue: callbackQueue, file: file, progress: progress, completion: completion)
case .uploadMultipart(let multipartBody), .uploadCompositeMultipart(let multipartBody, _):
guard !multipartBody.isEmpty && endpoint.method.supportsMultipart else {
fatalError("\(target) is not a multipart upload target.")
}
return self.sendUploadMultipart(target, request: request, callbackQueue: callbackQueue, multipartBody: multipartBody, progress: progress, completion: completion)
case .downloadDestination(let destination), .downloadParameters(_, _, let destination):
return self.sendDownloadRequest(target, request: request, callbackQueue: callbackQueue, destination: destination, progress: progress, completion: completion)
}
default:
return self.stubRequest(target, request: request, callbackQueue: callbackQueue, completion: completion, endpoint: endpoint, stubBehavior: stubBehavior)
}
}
func cancelCompletion(_ completion: Moya.Completion, target: Target) {
let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorCancelled, userInfo: nil), nil)
plugins.forEach { $0.didReceive(.failure(error), target: target) }
completion(.failure(error))
}
/// Creates a function which, when called, executes the appropriate stubbing behavior for the given parameters.
final func createStubFunction(_ token: CancellableToken, forTarget target: Target, withCompletion completion: @escaping Moya.Completion, endpoint: Endpoint, plugins: [PluginType], request: URLRequest) -> (() -> Void) { // swiftlint:disable:this function_parameter_count
return {
if token.isCancelled {
self.cancelCompletion(completion, target: target)
return
}
let validate = { (response: Moya.Response) -> Result<Moya.Response, MoyaError> in
let validCodes = target.validationType.statusCodes
guard !validCodes.isEmpty else { return .success(response) }
if validCodes.contains(response.statusCode) {
return .success(response)
} else {
let statusError = MoyaError.statusCode(response)
let error = MoyaError.underlying(statusError, response)
return .failure(error)
}
}
switch endpoint.sampleResponseClosure() {
case .networkResponse(let statusCode, let data):
let response = Moya.Response(statusCode: statusCode, data: data, request: request, response: nil)
let result = validate(response)
plugins.forEach { $0.didReceive(result, target: target) }
completion(result)
case .response(let customResponse, let data):
let response = Moya.Response(statusCode: customResponse.statusCode, data: data, request: request, response: customResponse)
let result = validate(response)
plugins.forEach { $0.didReceive(result, target: target) }
completion(result)
case .networkError(let error):
let error = MoyaError.underlying(error, nil)
plugins.forEach { $0.didReceive(.failure(error), target: target) }
completion(.failure(error))
}
}
}
/// Notify all plugins that a stub is about to be performed. You must call this if overriding `stubRequest`.
final func notifyPluginsOfImpendingStub(for request: URLRequest, target: Target) {
let alamoRequest = manager.request(request as URLRequestConvertible)
plugins.forEach { $0.willSend(alamoRequest, target: target) }
}
}
private extension MoyaProvider {
func sendUploadMultipart(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, multipartBody: [MultipartFormData], progress: Moya.ProgressBlock? = nil, completion: @escaping Moya.Completion) -> CancellableWrapper {
let cancellable = CancellableWrapper()
let multipartFormData: (RequestMultipartFormData) -> Void = { form in
form.applyMoyaMultipartFormData(multipartBody)
}
manager.upload(multipartFormData: multipartFormData, with: request) { result in
switch result {
case .success(let alamoRequest, _, _):
if cancellable.isCancelled {
self.cancelCompletion(completion, target: target)
return
}
let validationCodes = target.validationType.statusCodes
let validatedRequest = validationCodes.isEmpty ? alamoRequest : alamoRequest.validate(statusCode: validationCodes)
cancellable.innerCancellable = self.sendAlamofireRequest(validatedRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion)
case .failure(let error):
completion(.failure(MoyaError.underlying(error as NSError, nil)))
}
}
return cancellable
}
func sendUploadFile(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, file: URL, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken {
let uploadRequest = manager.upload(file, with: request)
let validationCodes = target.validationType.statusCodes
let alamoRequest = validationCodes.isEmpty ? uploadRequest : uploadRequest.validate(statusCode: validationCodes)
return self.sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
func sendDownloadRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, destination: @escaping DownloadDestination, progress: ProgressBlock? = nil, completion: @escaping Completion) -> CancellableToken {
let downloadRequest = manager.download(request, to: destination)
let validationCodes = target.validationType.statusCodes
let alamoRequest = validationCodes.isEmpty ? downloadRequest : downloadRequest.validate(statusCode: validationCodes)
return self.sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
func sendRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken {
let initialRequest = manager.request(request as URLRequestConvertible)
let validationCodes = target.validationType.statusCodes
let alamoRequest = validationCodes.isEmpty ? initialRequest : initialRequest.validate(statusCode: validationCodes)
return sendAlamofireRequest(alamoRequest, target: target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
// swiftlint:disable:next cyclomatic_complexity
func sendAlamofireRequest<T>(_ alamoRequest: T, target: Target, callbackQueue: DispatchQueue?, progress progressCompletion: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> CancellableToken where T: Requestable, T: Request {
// Give plugins the chance to alter the outgoing request
let plugins = self.plugins
plugins.forEach { $0.willSend(alamoRequest, target: target) }
var progressAlamoRequest = alamoRequest
let progressClosure: (Progress) -> Void = { progress in
let sendProgress: () -> Void = {
progressCompletion?(ProgressResponse(progress: progress))
}
if let callbackQueue = callbackQueue {
callbackQueue.async(execute: sendProgress)
} else {
sendProgress()
}
}
// Perform the actual request
if progressCompletion != nil {
switch progressAlamoRequest {
case let downloadRequest as DownloadRequest:
if let downloadRequest = downloadRequest.downloadProgress(closure: progressClosure) as? T {
progressAlamoRequest = downloadRequest
}
case let uploadRequest as UploadRequest:
if let uploadRequest = uploadRequest.uploadProgress(closure: progressClosure) as? T {
progressAlamoRequest = uploadRequest
}
case let dataRequest as DataRequest:
if let dataRequest = dataRequest.downloadProgress(closure: progressClosure) as? T {
progressAlamoRequest = dataRequest
}
default: break
}
}
let completionHandler: RequestableCompletion = { response, request, data, error in
let result = convertResponseToResult(response, request: request, data: data, error: error)
// Inform all plugins about the response
plugins.forEach { $0.didReceive(result, target: target) }
if let progressCompletion = progressCompletion {
switch progressAlamoRequest {
case let downloadRequest as DownloadRequest:
progressCompletion(ProgressResponse(progress: downloadRequest.progress, response: result.value))
case let uploadRequest as UploadRequest:
progressCompletion(ProgressResponse(progress: uploadRequest.uploadProgress, response: result.value))
case let dataRequest as DataRequest:
progressCompletion(ProgressResponse(progress: dataRequest.progress, response: result.value))
default:
progressCompletion(ProgressResponse(response: result.value))
}
}
completion(result)
}
progressAlamoRequest = progressAlamoRequest.response(callbackQueue: callbackQueue, completionHandler: completionHandler)
progressAlamoRequest.resume()
return CancellableToken(request: progressAlamoRequest)
}
}
| apache-2.0 | 00df0437f20b12a27e9e52da048a6fdb | 50.688645 | 273 | 0.656722 | 5.804607 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/EditNicknameAndBadge/EditNicknameAndBadgeViewController.swift | 1 | 8105 | //
// EditNicknameAndBadgeViewController.swift
// Yep
//
// Created by NIX on 15/7/2.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import YepNetworking
import Ruler
final class EditNicknameAndBadgeViewController: UITableViewController {
@IBOutlet private weak var nicknameTextField: UITextField!
@IBOutlet private weak var centerLeft1GapConstraint: NSLayoutConstraint!
@IBOutlet private weak var centerRight1GapConstraint: NSLayoutConstraint!
@IBOutlet private weak var left1Left2GapConstraint: NSLayoutConstraint!
@IBOutlet private weak var right1Right2GapConstraint: NSLayoutConstraint!
@IBOutlet private weak var promptPickBadgeLabel: UILabel!
@IBOutlet private weak var badgeEnabledImageView: UIImageView!
@IBOutlet private weak var paletteBadgeView: BadgeView!
@IBOutlet private weak var planeBadgeView: BadgeView!
@IBOutlet private weak var heartBadgeView: BadgeView!
@IBOutlet private weak var starBadgeView: BadgeView!
@IBOutlet private weak var bubbleBadgeView: BadgeView!
@IBOutlet private weak var androidBadgeView: BadgeView!
@IBOutlet private weak var appleBadgeView: BadgeView!
@IBOutlet private weak var petBadgeView: BadgeView!
@IBOutlet private weak var wineBadgeView: BadgeView!
@IBOutlet private weak var musicBadgeView: BadgeView!
@IBOutlet private weak var steveBadgeView: BadgeView!
@IBOutlet private weak var cameraBadgeView: BadgeView!
@IBOutlet private weak var gameBadgeView: BadgeView!
@IBOutlet private weak var ballBadgeView: BadgeView!
@IBOutlet private weak var techBadgeView: BadgeView!
private var badgeViews = [BadgeView]()
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Nickname", comment: "")
nicknameTextField.text = YepUserDefaults.nickname.value
nicknameTextField.delegate = self
let gap: CGFloat = Ruler.iPhoneHorizontal(10, 25, 32).value
centerLeft1GapConstraint.constant = gap
centerRight1GapConstraint.constant = gap
left1Left2GapConstraint.constant = gap
right1Right2GapConstraint.constant = gap
promptPickBadgeLabel.text = NSLocalizedString("Pick a badge", comment: "")
paletteBadgeView.badge = .Palette
planeBadgeView.badge = .Plane
heartBadgeView.badge = .Heart
starBadgeView.badge = .Star
bubbleBadgeView.badge = .Bubble
androidBadgeView.badge = .Android
appleBadgeView.badge = .Apple
petBadgeView.badge = .Pet
wineBadgeView.badge = .Wine
musicBadgeView.badge = .Music
steveBadgeView.badge = .Steve
cameraBadgeView.badge = .Camera
gameBadgeView.badge = .Game
ballBadgeView.badge = .Ball
techBadgeView.badge = .Tech
badgeViews = [
paletteBadgeView,
planeBadgeView,
heartBadgeView,
starBadgeView,
bubbleBadgeView,
androidBadgeView,
appleBadgeView,
petBadgeView,
wineBadgeView,
musicBadgeView,
steveBadgeView,
cameraBadgeView,
gameBadgeView,
ballBadgeView,
techBadgeView,
]
let disableAllBadges: () -> Void = { [weak self] in
self?.badgeViews.forEach { $0.enabled = false }
}
badgeViews.forEach {
$0.tapAction = { badgeView in
disableAllBadges()
badgeView.enabled = true
// select animation
if self.badgeEnabledImageView.hidden {
self.badgeEnabledImageViewAppearInCenter(badgeView.center)
} else {
UIView.animateWithDuration(0.2, delay: 0.0, usingSpringWithDamping: 0.65, initialSpringVelocity: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: { [weak self] in
self?.badgeEnabledImageView.center = badgeView.center
}, completion: nil)
}
// try save online & local
let newBadgeName = badgeView.badge.rawValue
updateMyselfWithInfo(["badge": newBadgeName], failureHandler: { [weak self] (reason, errorMessage) in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
SafeDispatch.async {
badgeView.enabled = false
}
YepAlert.alertSorry(message: NSLocalizedString("Set badge failed!", comment: ""), inViewController: self)
}, completion: { success in
SafeDispatch.async {
YepUserDefaults.badge.value = newBadgeName
}
})
}
}
}
private func badgeEnabledImageViewAppearInCenter(center: CGPoint) {
badgeEnabledImageView.center = center
badgeEnabledImageView.alpha = 0
badgeEnabledImageView.hidden = false
badgeEnabledImageView.transform = CGAffineTransformMakeScale(0.0001, 0.0001)
UIView.animateWithDuration(0.2, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.0, options: UIViewAnimationOptions(rawValue: 0), animations: { [weak self] in
self?.badgeEnabledImageView.alpha = 1
self?.badgeEnabledImageView.transform = CGAffineTransformMakeScale(1.0, 1.0)
}, completion: { [weak self] _ in
self?.badgeEnabledImageView.transform = CGAffineTransformIdentity
})
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let badgeName = YepUserDefaults.badge.value {
badgeViews.forEach { $0.enabled = ($0.badge.rawValue == badgeName) }
}
if let enabledBadgeView = badgeViews.filter({ $0.enabled }).first {
badgeEnabledImageViewAppearInCenter(enabledBadgeView.center)
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
override func viewDidDisappear(animated: Bool) {
super.viewDidAppear(animated)
guard let newNickname = nicknameTextField.text else {
return
}
if newNickname != YepUserDefaults.nickname.value {
updateMyselfWithInfo(["nickname": newNickname], failureHandler: nil, completion: { success in
SafeDispatch.async {
YepUserDefaults.nickname.value = newNickname
}
})
}
}
}
extension EditNicknameAndBadgeViewController: UITextFieldDelegate {
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == nicknameTextField {
textField.resignFirstResponder()
guard let newNickname = textField.text else {
return true
}
if newNickname.isEmpty {
YepAlert.alertSorry(message: NSLocalizedString("You did not enter any nickname!", comment: ""), inViewController: self, withDismissAction: {
SafeDispatch.async {
textField.text = YepUserDefaults.nickname.value
}
})
} else {
if newNickname != YepUserDefaults.nickname.value {
updateMyselfWithInfo(["nickname": newNickname], failureHandler: { [weak self] reason, errorMessage in
defaultFailureHandler(reason: reason, errorMessage: errorMessage)
YepAlert.alertSorry(message: NSLocalizedString("Update nickname failed!", comment: ""), inViewController: self)
}, completion: { success in
SafeDispatch.async {
YepUserDefaults.nickname.value = newNickname
}
})
}
}
}
return true
}
} | mit | ef2d9031ecaeac1c2e2da59ab93325fe | 33.05042 | 196 | 0.624583 | 5.694308 | false | false | false | false |
ifeherva/HSTracker | HSTracker/Core/Extensions/NSAlert.swift | 2 | 1507 | //
// NSAlert.swift
// HSTracker
//
// Created by Benjamin Michotte on 23/10/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Cocoa
extension NSAlert {
@discardableResult
class func show(style: NSAlert.Style, message: String,
accessoryView: NSView? = nil, window: NSWindow? = nil,
forceFront: Bool? = false, completion: (() -> Void)? = nil) -> Bool {
let alert = NSAlert()
alert.alertStyle = style
alert.messageText = message
alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
if completion != nil {
alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
}
alert.accessoryView = accessoryView
if let forceFront = forceFront, forceFront {
NSRunningApplication.current.activate(options: [
NSApplication.ActivationOptions.activateAllWindows,
NSApplication.ActivationOptions.activateIgnoringOtherApps
])
NSApp.activate(ignoringOtherApps: true)
}
if let window = window {
alert.beginSheetModal(for: window) { (returnCode) in
if returnCode == NSApplication.ModalResponse.alertFirstButtonReturn {
completion?()
}
}
return true
} else {
return alert.runModal() == NSApplication.ModalResponse.alertFirstButtonReturn
}
}
}
| mit | ce7b215eae65c589e7247b3382ccedbf | 33.227273 | 89 | 0.59429 | 5.417266 | false | false | false | false |
413738916/ZhiBoTest | ZhiBoSwift/ZhiBoSwift/Classes/Home/Controller/RecommendViewController.swift | 1 | 3596 | //
// RecommendViewController.swift
// ZhiBoSwift
//
// Created by 123 on 2017/10/23.
// Copyright © 2017年 ct. All rights reserved.
//
import UIKit
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
class RecommendViewController: BaseAnchorViewController {
// MARK:- 懒加载属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
}
// MARK:- 设置UI界面内容
extension RecommendViewController {
override func setupUI() {
// 1.先调用super.setupUI()
super.setupUI()
// 2.将CycleView添加到UICollectionView中
collectionView.addSubview(cycleView)
// 3.将gameView添加collectionView中
collectionView.addSubview(gameView)
// 4.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
// MARK:- 请求数据
extension RecommendViewController {
override func loadData() {
// 0.给父类中的ViewModel进行赋值
baseVM = recommendVM
// 1.请求推荐数据
recommendVM.requestData {
// 1.展示推荐数据
self.collectionView.reloadData()
// 2.将数据传递给GameView
var groups = self.recommendVM.anchorGroups
// 2.1.移除前两组数据
groups.removeFirst()
groups.removeFirst()
// 2.2.添加更多组
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
groups.append(moreGroup)
self.gameView.groups = groups
// 3.数据请求完成
self.loadDataFinished()
}
// 2.请求轮播数据
recommendVM.requestCycleData {
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
// 1.取出PrettyCell
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
// 2.设置数据
prettyCell.anchor = recommendVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
} else {
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
| mit | fd0d25dca7ef3babb92655182338ad43 | 30.275229 | 160 | 0.625403 | 5.552117 | false | false | false | false |
iHunterX/SocketIODemo | DemoSocketIO/Utils/Validator/Rules/ValidationRuleContains.swift | 1 | 1731 | /*
ValidationRulePattern.swift
Validator
Created by @adamwaite.
Copyright (c) 2015 Adam Waite. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public struct ValidationRuleContains<T: Equatable, S: Sequence>: ValidationRule where S.Iterator.Element == T {
public typealias InputType = T
public var sequence: S
public var failureError: ValidationErrorType
public init(sequence: S, failureError: ValidationErrorType) {
self.sequence = sequence
self.failureError = failureError
}
public func validateInput(input: T?) -> Bool {
guard let input = input else { return false }
return sequence.contains(input)
}
}
| gpl-3.0 | c55123f4920359bfe8ca43a03e1a97e5 | 32.941176 | 111 | 0.749856 | 4.835196 | false | false | false | false |
hushifei/CCEaseRefresh | CCEaseRefresh/CCEaseRefresh/CCEaseRefresh.swift | 2 | 10043 | //
// CCEaseRefresh.swift
// EaseRefresh
//
// Created by v-ling on 15/9/21.
// Copyright (c) 2015年 LiuZeChen. All rights reserved.
//
import UIKit
class CCEaseRefresh: UIControl {
enum CCEaseRefreshState: Int {
case Normal = 1
case Visible
case Targger
case Loading
}
var textX: CGFloat = 0 ///< 文本的X
var textY: CGFloat = 0 ///< 文本的Y
var ballWidth: CGFloat = 0 ///< 球的宽度
var ballHeight: CGFloat = 0 ///< 球的高度
var circleWidth: CGFloat = 0 ///< 圆的宽度
var cricleHeight: CGFloat = 0 ///< 圆的高度
var defaultBallY: CGFloat = 0 ///< 球默认的Y
var currentOffsetY: CGFloat = 0 ///< 当前的offsetY
var lastUpdateTimeString: NSString!
var ballLayer: CALayer!
var circleLayer: CALayer!
var textLabel: NSString!
var targetView: UIScrollView!
var originalContentInset: UIEdgeInsets!
let kContentOffset: String = "contentOffset"
let kRefreshHeight: CGFloat = 64.0
let kTimeViewHeight: CGFloat = 15
let kSubviewEdage: CGFloat = 7
let kBallImage = UIImage(named: "refresh_sphere")!
let kCircleImage = UIImage(named: "refresh_circle")!
let kTextAttribute: Dictionary = [NSFontAttributeName: UIFont.systemFontOfSize(12.0)]
let CCEaseDefaultTitle: String = "下拉刷新"
let CCEaseTriggertTitle: String = "松开刷新"
let CCEaseLoadingTitle: String = "正在刷新"
var _refreshState = CCEaseRefreshState.Normal
var refreshState: CCEaseRefreshState {
get {
return _refreshState
}set {
_refreshState = newValue
switch newValue {
case .Normal:
self.updateTime()
self.updateContentOffset(originalContentInset)
case .Visible:
self.updateTime()
self.updateBallLayerPosition()
case .Targger:
self.updateTime()
case .Loading:
var ei: UIEdgeInsets = originalContentInset
ei.top = ei.top + kRefreshHeight
self.updateContentOffset(ei)
self.updateTime()
self.updateBallLayerPosition()
self.updateCircleLayerPosition()
self.sendActionsForControlEvents(.ValueChanged)
}
}
}
func updateContentOffset(ei: UIEdgeInsets) {
UIView.animateWithDuration(0.25) { () -> Void in
self.targetView.contentInset = ei
}
}
// 更新(Layer的Frame、刷新的时间)
func updateBallLayerPosition() {
var ballLayerMinY: CGFloat = fabs(currentOffsetY) - originalContentInset.top + defaultBallY
let ballLayerMaxY: CGFloat = textY - kSubviewEdage - ballHeight / 2
if ballLayerMinY >= ballLayerMaxY {
ballLayerMinY = ballLayerMaxY
}
// 去掉隐式动画
// 1.
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
ballLayer.position = CGPointMake(ballLayer.position.x, ballLayerMinY)
CATransaction.commit()
// 2.
// ballLayer.actions = ["position": nil]
self.alpha = (fabs(currentOffsetY) - originalContentInset.top) / kRefreshHeight
self.layer.hidden = false
}
func updateCircleLayerPosition() {
circleLayer.position = CGPointMake(circleLayer.position.x, ballLayer.position.y - kSubviewEdage)
circleLayer.hidden = false
self.ballAnimation()
}
func ballAnimation() {
let enlarge: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
enlarge.duration = 0.5
enlarge.repeatCount = 1
enlarge.removedOnCompletion = false
enlarge.fromValue = 0.5
enlarge.toValue = 1
let decrease: CABasicAnimation = CABasicAnimation(keyPath: "transform.scale")
decrease.duration = 0.5
decrease.repeatCount = 1
decrease.removedOnCompletion = false
decrease.fromValue = 1
decrease.toValue = 0.5
decrease.beginTime = 0.5
let position: CABasicAnimation = CABasicAnimation(keyPath: "position")
position.duration = 1
position.repeatCount = MAXFLOAT
position.fromValue = NSValue(CGPoint: circleLayer.position)
position.toValue = NSValue(CGPoint: CGPointMake(circleLayer.position.x, circleLayer.position.y + kTimeViewHeight))
let group: CAAnimationGroup = CAAnimationGroup()
group.duration = 1
group.repeatCount = MAXFLOAT
group.removedOnCompletion = false
group.autoreverses = true
group.animations = [enlarge, decrease, position]
circleLayer.addAnimation(group, forKey: "CCEaseRefresh")
}
func updateTime() {
switch refreshState {
case .Normal, .Visible:
lastUpdateTimeString = CCEaseDefaultTitle
case .Targger:
lastUpdateTimeString = CCEaseTriggertTitle
case .Loading:
lastUpdateTimeString = CCEaseLoadingTitle
}
self.setNeedsDisplay()
}
func calcTextXY() {
if textX == 0.0 || textY == 0.0 {
let options: NSStringDrawingOptions = .UsesLineFragmentOrigin
let textSize = lastUpdateTimeString.boundingRectWithSize(CGSizeMake(CGFloat(MAXFLOAT), CGFloat(MAXFLOAT)), options: options, attributes: kTextAttribute, context: nil).size
textY = self.frame.size.height - textSize.height - kSubviewEdage
textX = (self.frame.size.width - textSize.width) / 2
}
}
override func drawRect(rect: CGRect) {
self.calcTextXY()
lastUpdateTimeString.drawAtPoint(CGPointMake(textX, textY), withAttributes: kTextAttribute)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
}
override func willMoveToSuperview(newSuperview: UIView?) {
if (newSuperview == nil) {
newSuperview?.removeObserver(self, forKeyPath: kContentOffset)
}
}
func loadObserver() {
targetView.addObserver(self, forKeyPath: kContentOffset, options: NSKeyValueObservingOptions.New, context: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == kContentOffset {
if let result = change {
currentOffsetY = (result[NSKeyValueChangeNewKey]?.CGPointValue)!.y
if _refreshState == .Loading {return}
let newOffsetThreshold = -originalContentInset.top
if !targetView.dragging && _refreshState == .Targger {
refreshState = .Loading
} else if currentOffsetY <= (2 * newOffsetThreshold) && targetView.dragging && _refreshState != .Targger {
refreshState = .Targger
} else if (currentOffsetY < newOffsetThreshold && currentOffsetY > (2 * newOffsetThreshold)) {
refreshState = .Visible
} else if (currentOffsetY >= newOffsetThreshold && _refreshState != .Normal) {
refreshState = .Normal
}
}
}
}
deinit {
print("CCEaseRefresh(Swift) deinit...");
targetView?.removeObserver(self, forKeyPath: kContentOffset)
targetView = nil
}
func loadComponent() {
self.updateTime()
self.calcTextXY()
let selfViewWidth = self.frame.size.width;
ballWidth = kBallImage.size.width - kSubviewEdage / 2
ballHeight = kBallImage.size.height - kSubviewEdage / 2
ballLayer = CALayer()
ballLayer.frame = CGRectMake((selfViewWidth - ballWidth) / 2, -ballHeight, ballWidth, ballHeight)
ballLayer.position = CGPointMake(self.center.x, ballLayer.position.y)
ballLayer.contents = kBallImage.CGImage
self.layer.addSublayer(ballLayer)
circleWidth = kCircleImage.size.width
cricleHeight = kCircleImage.size.height
circleLayer = CALayer()
circleLayer.frame = CGRectMake((selfViewWidth - circleWidth) / 2, 0, circleWidth, cricleHeight)
circleLayer.contents = kCircleImage.CGImage
circleLayer.hidden = true
defaultBallY = ballLayer.frame.origin.y
self.alpha = 0
self.layer.addSublayer(ballLayer)
self.layer.insertSublayer(circleLayer, below: ballLayer)
}
func beginRefreshing() {
if _refreshState != .Loading {
refreshState = .Loading;
}
}
func endRefreshing() {
if _refreshState != .Normal {
refreshState = .Normal
self.alpha = 0.0
self.hidden = true
circleLayer.removeAnimationForKey("CCEaseRefresh")
circleLayer.hidden = true
ballLayer.position = CGPointMake(ballLayer.position.x, defaultBallY)
}
}
}
enum CCEaseError: ErrorType {
case OJCNotExist
}
extension CCEaseRefresh {
// Swift错误处理: http://www.cocoachina.com/swift/20150623/12231.html
convenience init(scrollView: UIScrollView) /*throws*/ {
/*guard scrollView == true else {
throw CCEaseError.OJCNotExist
}*/
self.init()
targetView = scrollView
originalContentInset = scrollView.contentInset
self.frame = CGRectMake(0, originalContentInset.top, targetView.frame.size.width, kRefreshHeight)
self.backgroundColor = UIColor.clearColor()
targetView.backgroundColor = UIColor.clearColor()
targetView.superview?.insertSubview(self, belowSubview: targetView)
self.loadObserver()
self.loadComponent()
}
}
| mit | a927c93f62b2ae87dfd41aebb8e1918b | 33.926056 | 183 | 0.622946 | 5.068472 | false | false | false | false |
1457792186/JWSwift | SwiftWX/LGWeChatKit/LGChatKit/conversion/imagePick/LGImagePickViewModel.swift | 1 | 1589 | //
// PHRootViewModel.swift
// LGChatViewController
//
// Created by jamy on 10/22/15.
// Copyright © 2015 jamy. All rights reserved.
//
import Foundation
import Photos
class PHRootViewModel {
let collections: Observable<[PHRootModel]>
init() {
collections = Observable([])
}
func getCollectionList() {
let albumOptions = PHFetchOptions()
albumOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
let userAlbum = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .albumRegular, options: nil)
userAlbum.enumerateObjects { (collection, index, stop) -> Void in
let coll = collection as! PHAssetCollection
let assert = PHAsset.fetchAssets(in: coll, options: nil)
if assert.count > 0 {
let model = PHRootModel(title: coll.localizedTitle!, count: assert.count, fetchResult: assert)
self.collections.value.append(model)
}
}
let userCollection = PHCollectionList.fetchTopLevelUserCollections(with: nil)
userCollection.enumerateObjects { (list, index, stop) -> Void in
let list = list as! PHAssetCollection
let assert = PHAsset.fetchAssets(in: list, options: nil)
if assert.count > 0 {
let model = PHRootModel(title: list.localizedTitle!, count: assert.count, fetchResult: assert)
self.collections.value.append(model)
}
}
}
}
| apache-2.0 | b9ecb71b811daa5884a92d0707ac59c2 | 32.083333 | 120 | 0.61461 | 4.94704 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | Source/DiscussionAPI.swift | 2 | 13914 | //
// DiscussionAPI.swift
// edX
//
// Created by Tang, Jeff on 6/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public enum DiscussionPostsFilter {
case AllPosts
case Unread
case Unanswered
private var apiRepresentation : String? {
switch self {
case AllPosts: return nil // default
case Unread: return "unread"
case Unanswered: return "unanswered"
}
}
}
public enum DiscussionPostsSort {
case RecentActivity
case MostActivity
case VoteCount
private var apiRepresentation : String? {
switch self {
case RecentActivity: return "last_activity_at"
case MostActivity: return "comment_count"
case VoteCount: return "vote_count"
}
}
}
public class DiscussionAPI {
private static func threadDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<DiscussionThread> {
return DiscussionThread(json : json).toResult(NSError.oex_courseContentLoadError())
}
private static func commentDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<DiscussionComment> {
return DiscussionComment(json : json).toResult(NSError.oex_courseContentLoadError())
}
private static func listDeserializer<A>(response : NSHTTPURLResponse, items : [JSON]?, constructor : (JSON -> A?)) -> Result<[A]> {
if let items = items {
var result: [A] = []
for itemJSON in items {
if let item = constructor(itemJSON) {
result.append(item)
}
}
return Success(result)
}
else {
return Failure(NSError.oex_courseContentLoadError())
}
}
private static func threadListDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<[DiscussionThread]> {
return listDeserializer(response, items: json.array, constructor: { DiscussionThread(json : $0) } )
}
private static func commentListDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<[DiscussionComment]> {
return listDeserializer(response, items: json.array, constructor: { DiscussionComment(json : $0) } )
}
private static func topicListDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<[DiscussionTopic]> {
if let coursewareTopics = json["courseware_topics"].array,
nonCoursewareTopics = json["non_courseware_topics"].array
{
var result: [DiscussionTopic] = []
for topics in [nonCoursewareTopics, coursewareTopics] {
for json in topics {
if let topic = DiscussionTopic(json: json) {
result.append(topic)
}
}
}
return Success(result)
}
else {
return Failure(NSError.oex_courseContentLoadError())
}
}
private static func discussionInfoDeserializer(response : NSHTTPURLResponse, json : JSON) -> Result<DiscussionInfo> {
return DiscussionInfo(json : json).toResult(NSError.oex_courseContentLoadError())
}
//MA-1378 - Automatically follow posts when creating a new post
static func createNewThread(newThread: DiscussionNewThread, follow : Bool = true) -> NetworkRequest<DiscussionThread> {
let json = JSON([
"course_id" : newThread.courseID,
"topic_id" : newThread.topicID,
"type" : newThread.type.rawValue,
"title" : newThread.title,
"raw_body" : newThread.rawBody,
"following" : follow
])
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/threads/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : .JSONResponse(threadDeserializer)
)
}
// when parent id is nil, counts as a new post
static func createNewComment(threadID : String, text : String, parentID : String? = nil) -> NetworkRequest<DiscussionComment> {
var json = JSON([
"thread_id" : threadID,
"raw_body" : text,
])
if let parentID = parentID {
json["parent_id"] = JSON(parentID)
}
return NetworkRequest(
method : HTTPMethod.POST,
path : "/api/discussion/v1/comments/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
deserializer : .JSONResponse(commentDeserializer)
)
}
// User can only vote on post and response not on comment.
// thread is the same as post
static func voteThread(voted: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(threadDeserializer)
)
}
static func voteResponse(voted: Bool, responseID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["voted" : !voted])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(responseID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(commentDeserializer)
)
}
// User can flag (report) on post, response, or comment
static func flagThread(abuseFlagged: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["abuse_flagged" : abuseFlagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(threadDeserializer)
)
}
static func flagComment(abuseFlagged: Bool, commentID: String) -> NetworkRequest<DiscussionComment> {
let json = JSON(["abuse_flagged" : abuseFlagged])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/comments/\(commentID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(commentDeserializer)
)
}
// User can only follow original post, not response or comment.
static func followThread(following: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["following" : !following])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(threadDeserializer)
)
}
// mark thread as read
static func readThread(read: Bool, threadID: String) -> NetworkRequest<DiscussionThread> {
let json = JSON(["read" : read])
return NetworkRequest(
method : HTTPMethod.PATCH,
path : "/api/discussion/v1/threads/\(threadID)/",
requiresAuth : true,
body: RequestBody.JSONBody(json),
headers: ["Content-Type": "application/merge-patch+json"], //should push this to a lower level once all our PATCHs support this content-type
deserializer : .JSONResponse(threadDeserializer)
)
}
// Pass nil in place of topicIDs if we need to fetch all threads
static func getThreads(courseID courseID: String, topicIDs: [String]?, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort, pageNumber : Int) -> NetworkRequest<Paginated<[DiscussionThread]>> {
var query = ["course_id" : JSON(courseID)]
if let identifiers = topicIDs {
//TODO: Replace the comma separated strings when the API improves
query["topic_id"] = JSON(identifiers.joinWithSeparator(","))
}
if let view = filter.apiRepresentation {
query["view"] = JSON(view)
}
if let order = orderBy.apiRepresentation {
query["order_by"] = JSON(order)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
query: query,
requiresAuth : true,
deserializer : .JSONResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
static func getFollowedThreads(courseID courseID : String, filter: DiscussionPostsFilter, orderBy: DiscussionPostsSort, pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionThread]>> {
var query = ["course_id" : JSON(courseID), "following" : JSON(true)]
if let view = filter.apiRepresentation {
query["view"] = JSON(view)
}
if let order = orderBy.apiRepresentation {
query["order_by"] = JSON(order)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
query: query,
requiresAuth : true,
deserializer : .JSONResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
static func searchThreads(courseID courseID: String, searchText: String, pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionThread]>> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/threads/",
query: [
"course_id" : JSON(courseID),
"text_search": JSON(searchText)
],
requiresAuth : true,
deserializer : .JSONResponse(threadListDeserializer)
).paginated(page: pageNumber)
}
//TODO: Yet to decide the semantics for the *endorsed* field. Setting false by default to fetch all questions.
//Questions can not be fetched if the endorsed field isn't populated
static func getResponses(environment:RouterEnvironment?, threadID: String, threadType : DiscussionThreadType, endorsedOnly endorsed : Bool = false,pageNumber : Int = 1) -> NetworkRequest<Paginated<[DiscussionComment]>> {
var query = ["thread_id": JSON(threadID)]
if let environment = environment where environment.config.discussionsEnabledProfilePictureParam {
query["requested_fields"] = JSON("profile_image")
}
//Only set the endorsed flag if the post is a question
if threadType == .Question {
query["endorsed"] = JSON(endorsed)
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/comments/", // responses are treated similarly as comments
query: query,
requiresAuth : true,
deserializer : .JSONResponse(commentListDeserializer)
).paginated(page: pageNumber)
}
static func getCourseTopics(courseID: String) -> NetworkRequest<[DiscussionTopic]> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/course_topics/\(courseID)",
requiresAuth : true,
deserializer : .JSONResponse(topicListDeserializer)
)
}
static func getTopicByID(courseID: String, topicID : String) -> NetworkRequest<[DiscussionTopic]> {
let query = ["topic_id" : JSON(topicID)]
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/course_topics/\(courseID)",
query: query,
requiresAuth : true,
deserializer : .JSONResponse(topicListDeserializer)
)
}
// get response comments
static func getComments(environment:RouterEnvironment?, commentID: String, pageNumber: Int) -> NetworkRequest<Paginated<[DiscussionComment]>> {
var query: [String: JSON] = [:]
if let environment = environment where environment.config.discussionsEnabledProfilePictureParam {
query["requested_fields"] = JSON("profile_image")
}
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/comments/\(commentID)/",
query: query,
requiresAuth : true,
deserializer : .JSONResponse(commentListDeserializer)
).paginated(page: pageNumber)
}
static func getDiscussionInfo(courseID: String) -> NetworkRequest<(DiscussionInfo)> {
return NetworkRequest(
method : HTTPMethod.GET,
path : "/api/discussion/v1/courses/\(courseID)",
query: [:],
requiresAuth : true,
deserializer : .JSONResponse(discussionInfoDeserializer)
)
}
}
| apache-2.0 | 6b011fa5df2c3b63d4a7a9636059ca7f | 40.044248 | 226 | 0.61068 | 5.067007 | false | false | false | false |
JanNash/WeakRefCollections | WeakRefCollections/Sources/Public/Types/WeakRefArray.swift | 1 | 4593 | //
// WeakRefArray.swift
// WeakRefCollections
//
// Created by Jan Nash on 12/17/16.
// Copyright © 2016 JanNash. All rights reserved.
//
// MARK: // Public
// MARK: Class Declaration
final public class WeakRefArray<Element: AnyObject> {
// Array Inits
required public init() {}
required public init<S>(_ elements: S) where S : Sequence, Element == S.Element {
var previous: SeqIndxdWeakWrapper_<Element>? = nil
self._array = elements.map(self._wrapMap(&previous))
}
// ExpressibleByArrayLiteral Implementation
required public init(arrayLiteral elements: Element...) {
var previous: SeqIndxdWeakWrapper_<Element>? = nil
self._array = elements.map(self._wrapMap(&previous))
}
// Private Variables
private var _array: [SeqIndxdWeakWrapper_<Element>] = []
}
// MARK: ExpressibleByArrayLiteral
// (Implementation in Class Declaration)
extension WeakRefArray: ExpressibleByArrayLiteral {}
// MARK: Equatable
extension WeakRefArray: Equatable where Element: Equatable {
public static func == (lhs: WeakRefArray<Element>, rhs: WeakRefArray<Element>) -> Bool {
return lhs._array == rhs._array
}
}
// MARK: CustomStringConvertible
extension WeakRefArray: CustomStringConvertible {
public var description: String {
return self._description
}
}
// MARK: CustomDebugStringConvertible
extension WeakRefArray: CustomDebugStringConvertible {
public var debugDescription: String {
return self._debugDescription
}
}
// MARK: Collection
extension WeakRefArray: Collection {
public typealias Index = Int
public var startIndex: Index {
return self._array.startIndex
}
public var endIndex: Index {
return self._array.endIndex
}
public func index(after i: Index) -> Index {
return self._array.index(after: i)
}
public subscript(index: Index) -> Element {
return self._array[index].value!
}
}
// MARK: RangeReplaceableCollection
extension WeakRefArray: RangeReplaceableCollection {
public func replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C : Collection, R : RangeExpression, Element == C.Element, Int == R.Bound {
self._replaceSubrange(subrange, with: newElements)
}
}
// MARK: // Internal
// MARK: WeakWrapperDelegate
extension WeakRefArray: WeakWrapperDelegate_ {
func disconnected<Element>(weakWrapper: WeakWrapper_<Element>) {
self._array.remove(at: (weakWrapper as! SeqIndxdWeakWrapper_).index)
}
}
// MARK: // Private
// MARK: CustomStringConvertible Implementation
private extension WeakRefArray/*: CustomStringConvertible*/ {
var _description: String {
let arrayOfDescriptions: [String] = self._array.map({ String(describing: $0) })
let joinedArrayDescription: String = arrayOfDescriptions.joined(separator: ", ")
return "WeakRefArray[\(joinedArrayDescription)]"
}
}
// MARK: CustomDebugStringConvertible Implementation
private extension WeakRefArray/*: CustomDebugStringConvertible*/ {
var _debugDescription: String {
let array: [SeqIndxdWeakWrapper_] = self._array
let count: Int = array.count
let debugDescriptions: [String] = array.map({ $0.debugDescription })
let joinedDebugDescriptions: String = debugDescriptions.joined(separator: ", \n ")
return "WeakRefArray(" +
"count: \(count), " +
"array: [" +
"\n \(joinedDebugDescriptions)" +
"])"
}
}
// MARK: RangeReplaceableCollection Implementation
private extension WeakRefArray/*: RangeReplaceableCollection*/ {
func _replaceSubrange<C, R>(_ subrange: R, with newElements: C) where C : Collection, R : RangeExpression, Element == C.Element, Int == R.Bound {
let oldElements: ArraySlice<SeqIndxdWeakWrapper_<Element>> = self._array[subrange]
oldElements.forEach({ $0.delegate = nil })
var previous: SeqIndxdWeakWrapper_<Element>? = nil
self._array.replaceSubrange(subrange, with: newElements.map(self._wrapMap(&previous)))
}
}
// MARK: Wrapping Helper Function
private extension WeakRefArray {
func _wrapMap(_ previous: inout SeqIndxdWeakWrapper_<Element>?) -> ((Element) -> SeqIndxdWeakWrapper_<Element>) {
var _previous: SeqIndxdWeakWrapper_? = previous
return {
let wrapper: SeqIndxdWeakWrapper_ = SeqIndxdWeakWrapper_(value: $0, previous: _previous, delegate: self)
_previous = wrapper
return wrapper
}
}
}
| mit | 1c813ac31f49801fd8dca25102da3cf8 | 30.027027 | 155 | 0.672909 | 4.813417 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/goat-latin.swift | 2 | 777 | /**
* https://leetcode.com/problems/goat-latin/
*
*
*/
// Date: Wed Aug 19 17:18:51 PDT 2020
class Solution {
/// - Complexity:
/// - Time: O(n), n is the number of single words in S.
/// - Space: O(length of S)
///
func toGoatLatin(_ S: String) -> String {
var list = S.split(separator: " ")
var trailing = ""
for index in 0 ..< list.count {
trailing += "a"
var origin = list[index]
if let first = origin.first, "aeiou".contains(first) == false, "AEIOU".contains(first) == false {
origin += String(origin.removeFirst())
}
origin += "ma" + trailing
list[index] = origin
}
return list.joined(separator: " ")
}
} | mit | a45c13b69f57cf53f7022e261f8050ad | 28.923077 | 109 | 0.501931 | 3.735577 | false | false | false | false |
nRewik/swift-corelibs-foundation | Foundation/NSSwiftRuntime.swift | 2 | 15989 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
public typealias ObjCBool = Bool
public typealias NSStringEncoding = UInt
public var NSASCIIStringEncoding: UInt { return 1 }
public var NSNEXTSTEPStringEncoding: UInt { return 2 }
public var NSJapaneseEUCStringEncoding: UInt { return 3 }
public var NSUTF8StringEncoding: UInt { return 4 }
public var NSISOLatin1StringEncoding: UInt { return 5 }
public var NSSymbolStringEncoding: UInt { return 6 }
public var NSNonLossyASCIIStringEncoding: UInt { return 7 }
public var NSShiftJISStringEncoding: UInt { return 8 }
public var NSISOLatin2StringEncoding: UInt { return 9 }
public var NSUnicodeStringEncoding: UInt { return 10 }
public var NSWindowsCP1251StringEncoding: UInt { return 11 }
public var NSWindowsCP1252StringEncoding: UInt { return 12 }
public var NSWindowsCP1253StringEncoding: UInt { return 13 }
public var NSWindowsCP1254StringEncoding: UInt { return 14 }
public var NSWindowsCP1250StringEncoding: UInt { return 15 }
public var NSISO2022JPStringEncoding: UInt { return 21 }
public var NSMacOSRomanStringEncoding: UInt { return 30 }
public var NSUTF16StringEncoding: UInt { return NSUnicodeStringEncoding }
public var NSUTF16BigEndianStringEncoding: UInt { return 0x90000100 }
public var NSUTF16LittleEndianStringEncoding: UInt { return 0x94000100 }
public var NSUTF32StringEncoding: UInt { return 0x8c000100 }
public var NSUTF32BigEndianStringEncoding: UInt { return 0x98000100 }
public var NSUTF32LittleEndianStringEncoding: UInt { return 0x9c000100 }
internal class __NSCFType : NSObject {
private var _cfinfo : Int32
override init() {
// This is not actually called; _CFRuntimeCreateInstance will initialize _cfinfo
_cfinfo = 0
}
override var hash: Int {
get {
return Int(CFHash(self))
}
}
override func isEqual(object: AnyObject?) -> Bool {
if let obj = object {
return CFEqual(self, obj)
} else {
return false
}
}
override var description: String {
get {
return CFCopyDescription(unsafeBitCast(self, CFTypeRef.self))._swiftObject
}
}
deinit {
_CFDeinit(self)
}
}
internal func _CFSwiftGetTypeID(cf: AnyObject) -> CFTypeID {
return (cf as! NSObject)._cfTypeID
}
internal func _CFSwiftGetHash(cf: AnyObject) -> CFHashCode {
return CFHashCode((cf as! NSObject).hash)
}
internal func _CFSwiftIsEqual(cf1: AnyObject, cf2: AnyObject) -> Bool {
return (cf1 as! NSObject).isEqual(cf2)
}
// Ivars in _NSCF* types must be zeroed via an unsafe accessor to avoid deinit of potentially unsafe memory to accces as an object/struct etc since it is stored via a foreign object graph
internal func _CFZeroUnsafeIvars<T>(inout arg: T) {
withUnsafeMutablePointer(&arg) { (ptr: UnsafeMutablePointer<T>) -> Void in
bzero(unsafeBitCast(ptr, UnsafeMutablePointer<Void>.self), sizeof(T))
}
}
internal func __CFSwiftGetBaseClass() -> AnyObject.Type {
return __NSCFType.self
}
internal func __CFInitializeSwift() {
_CFRuntimeBridgeTypeToClass(CFStringGetTypeID(), unsafeBitCast(_NSCFString.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFArrayGetTypeID(), unsafeBitCast(_NSCFArray.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFDictionaryGetTypeID(), unsafeBitCast(_NSCFDictionary.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFSetGetTypeID(), unsafeBitCast(_NSCFSet.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFNumberGetTypeID(), unsafeBitCast(NSNumber.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFDataGetTypeID(), unsafeBitCast(NSData.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFDateGetTypeID(), unsafeBitCast(NSDate.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFURLGetTypeID(), unsafeBitCast(NSURL.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFCalendarGetTypeID(), unsafeBitCast(NSCalendar.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFLocaleGetTypeID(), unsafeBitCast(NSLocale.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFTimeZoneGetTypeID(), unsafeBitCast(NSTimeZone.self, UnsafePointer<Void>.self))
_CFRuntimeBridgeTypeToClass(CFCharacterSetGetTypeID(), unsafeBitCast(NSMutableCharacterSet.self, UnsafePointer<Void>.self))
// _CFRuntimeBridgeTypeToClass(CFErrorGetTypeID(), unsafeBitCast(NSError.self, UnsafePointer<Void>.self))
// _CFRuntimeBridgeTypeToClass(CFAttributedStringGetTypeID(), unsafeBitCast(NSMutableAttributedString.self, UnsafePointer<Void>.self))
// _CFRuntimeBridgeTypeToClass(CFReadStreamGetTypeID(), unsafeBitCast(NSInputStream.self, UnsafePointer<Void>.self))
// _CFRuntimeBridgeTypeToClass(CFWriteStreamGetTypeID(), unsafeBitCast(NSOutputStream.self, UnsafePointer<Void>.self))
// _CFRuntimeBridgeTypeToClass(CFRunLoopTimerGetTypeID(), unsafeBitCast(NSTimer.self, UnsafePointer<Void>.self))
__CFSwiftBridge.NSObject.isEqual = _CFSwiftIsEqual
__CFSwiftBridge.NSObject.hash = _CFSwiftGetHash
__CFSwiftBridge.NSObject._cfTypeID = _CFSwiftGetTypeID
__CFSwiftBridge.NSArray.count = _CFSwiftArrayGetCount
__CFSwiftBridge.NSArray.objectAtIndex = _CFSwiftArrayGetValueAtIndex
__CFSwiftBridge.NSArray.getObjects = _CFSwiftArrayGetValues
__CFSwiftBridge.NSMutableArray.addObject = _CFSwiftArrayAppendValue
__CFSwiftBridge.NSMutableArray.setObject = _CFSwiftArraySetValueAtIndex
__CFSwiftBridge.NSMutableArray.replaceObjectAtIndex = _CFSwiftArrayReplaceValueAtIndex
__CFSwiftBridge.NSMutableArray.insertObject = _CFSwiftArrayInsertValueAtIndex
__CFSwiftBridge.NSMutableArray.exchangeObjectAtIndex = _CFSwiftArrayExchangeValuesAtIndices
__CFSwiftBridge.NSMutableArray.removeObjectAtIndex = _CFSwiftArrayRemoveValueAtIndex
__CFSwiftBridge.NSMutableArray.removeAllObjects = _CFSwiftArrayRemoveAllValues
__CFSwiftBridge.NSMutableArray.replaceObjectsInRange = _CFSwiftArrayReplaceValues
__CFSwiftBridge.NSDictionary.count = _CFSwiftDictionaryGetCount
__CFSwiftBridge.NSDictionary.countForKey = _CFSwiftDictionaryGetCountOfKey
__CFSwiftBridge.NSDictionary.containsKey = _CFSwiftDictionaryContainsKey
__CFSwiftBridge.NSDictionary.objectForKey = _CFSwiftDictionaryGetValue
__CFSwiftBridge.NSDictionary._getValueIfPresent = _CFSwiftDictionaryGetValueIfPresent
__CFSwiftBridge.NSDictionary.containsObject = _CFSwiftDictionaryContainsValue
__CFSwiftBridge.NSDictionary.countForObject = _CFSwiftDictionaryGetCountOfValue
__CFSwiftBridge.NSDictionary.getObjects = _CFSwiftDictionaryGetKeysAndValues
__CFSwiftBridge.NSDictionary.__apply = _CFSwiftDictionaryApplyFunction
__CFSwiftBridge.NSMutableDictionary.__addObject = _CFSwiftDictionaryAddValue
__CFSwiftBridge.NSMutableDictionary.replaceObject = _CFSwiftDictionaryReplaceValue
__CFSwiftBridge.NSMutableDictionary.__setObject = _CFSwiftDictionarySetValue
__CFSwiftBridge.NSMutableDictionary.removeObjectForKey = _CFSwiftDictionaryRemoveValue
__CFSwiftBridge.NSMutableDictionary.removeAllObjects = _CFSwiftDictionaryRemoveAllValues
__CFSwiftBridge.NSString._createSubstringWithRange = _CFSwiftStringCreateWithSubstring
__CFSwiftBridge.NSString.copy = _CFSwiftStringCreateCopy
__CFSwiftBridge.NSString.mutableCopy = _CFSwiftStringCreateMutableCopy
__CFSwiftBridge.NSString.length = _CFSwiftStringGetLength
__CFSwiftBridge.NSString.characterAtIndex = _CFSwiftStringGetCharacterAtIndex
__CFSwiftBridge.NSString.getCharacters = _CFSwiftStringGetCharacters
__CFSwiftBridge.NSString.__getBytes = _CFSwiftStringGetBytes
__CFSwiftBridge.NSString._fastCStringContents = _CFSwiftStringFastCStringContents
__CFSwiftBridge.NSString._fastCharacterContents = _CFSwiftStringFastContents
__CFSwiftBridge.NSString._getCString = _CFSwiftStringGetCString
__CFSwiftBridge.NSString._encodingCantBeStoredInEightBitCFString = _CFSwiftStringIsUnicode
__CFSwiftBridge.NSMutableString.insertString = _CFSwiftStringInsert
__CFSwiftBridge.NSMutableString.deleteCharactersInRange = _CFSwiftStringDelete
__CFSwiftBridge.NSMutableString.replaceCharactersInRange = _CFSwiftStringReplace
__CFSwiftBridge.NSMutableString.setString = _CFSwiftStringReplaceAll
__CFSwiftBridge.NSMutableString.appendString = _CFSwiftStringAppend
__CFSwiftBridge.NSMutableString.appendCharacters = _CFSwiftStringAppendCharacters
__CFSwiftBridge.NSMutableString._cfAppendCString = _CFSwiftStringAppendCString
__CFSwiftBridge.NSXMLParser.currentParser = _NSXMLParserCurrentParser
__CFSwiftBridge.NSXMLParser._xmlExternalEntityWithURL = _NSXMLParserExternalEntityWithURL
__CFSwiftBridge.NSXMLParser.getContext = _NSXMLParserGetContext
__CFSwiftBridge.NSXMLParser.internalSubset = _NSXMLParserInternalSubset
__CFSwiftBridge.NSXMLParser.isStandalone = _NSXMLParserIsStandalone
__CFSwiftBridge.NSXMLParser.hasInternalSubset = _NSXMLParserHasInternalSubset
__CFSwiftBridge.NSXMLParser.hasExternalSubset = _NSXMLParserHasExternalSubset
__CFSwiftBridge.NSXMLParser.getEntity = _NSXMLParserGetEntity
__CFSwiftBridge.NSXMLParser.notationDecl = _NSXMLParserNotationDecl
__CFSwiftBridge.NSXMLParser.attributeDecl = _NSXMLParserAttributeDecl
__CFSwiftBridge.NSXMLParser.elementDecl = _NSXMLParserElementDecl
__CFSwiftBridge.NSXMLParser.unparsedEntityDecl = _NSXMLParserUnparsedEntityDecl
__CFSwiftBridge.NSXMLParser.startDocument = _NSXMLParserStartDocument
__CFSwiftBridge.NSXMLParser.endDocument = _NSXMLParserEndDocument
__CFSwiftBridge.NSXMLParser.startElementNs = _NSXMLParserStartElementNs
__CFSwiftBridge.NSXMLParser.endElementNs = _NSXMLParserEndElementNs
__CFSwiftBridge.NSXMLParser.characters = _NSXMLParserCharacters
__CFSwiftBridge.NSXMLParser.processingInstruction = _NSXMLParserProcessingInstruction
__CFSwiftBridge.NSXMLParser.cdataBlock = _NSXMLParserCdataBlock
__CFSwiftBridge.NSXMLParser.comment = _NSXMLParserComment
__CFSwiftBridge.NSXMLParser.externalSubset = _NSXMLParserExternalSubset
__CFDefaultEightBitStringEncoding = UInt32(kCFStringEncodingUTF8)
}
public protocol _ObjectTypeBridgeable {
typealias _ObjectType : AnyObject
/// Convert `self` to an Object type
@warn_unused_result
func _bridgeToObject() -> _ObjectType
/// Bridge from an object of the bridged class type to a value of
/// the Self type.
///
/// This bridging operation is used for forced downcasting (e.g.,
/// via as), and may defer complete checking until later. For
/// example, when bridging from `NSArray` to `Array<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObject(
source: _ObjectType,
inout result: Self?
)
/// Try to bridge from an object of the bridged class type to a value of
/// the Self type.
///
/// This conditional bridging operation is used for conditional
/// downcasting (e.g., via as?) and therefore must perform a
/// complete conversion to the value type; it cannot defer checking
/// to a later time.
///
/// - parameter result: The location where the result is written.
///
/// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant
/// information is provided for the convenience of the runtime's `dynamic_cast`
/// implementation, so that it need not look into the optional representation
/// to determine success.
static func _conditionallyBridgeFromObject(
source: _ObjectType,
inout result: Self?
) -> Bool
}
protocol _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject
}
internal func _NSObjectRepresentableBridge(value: Any) -> NSObject {
if let obj = value as? _NSObjectRepresentable {
return obj._nsObjectRepresentation()
} else if let str = value as? String {
return str._nsObjectRepresentation()
} else if let obj = value as? NSObject {
return obj
}
fatalError("Unable to convert value of type \(value.dynamicType)")
}
extension Array : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Dictionary : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension String : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Set : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Int : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension UInt : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Float : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Double : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
extension Bool : _NSObjectRepresentable {
func _nsObjectRepresentation() -> NSObject {
return _bridgeToObject()
}
}
public func === (lhs: AnyClass, rhs: AnyClass) -> Bool {
return unsafeBitCast(lhs, UnsafePointer<Void>.self) == unsafeBitCast(rhs, UnsafePointer<Void>.self)
}
/// Swift extensions for common operations in Foundation that use unsafe things...
extension UnsafeMutablePointer {
internal init<T: AnyObject>(retained value: T) {
self.init(Unmanaged<T>.passRetained(value).toOpaque())
}
internal init<T: AnyObject>(unretained value: T) {
self.init(Unmanaged<T>.passUnretained(value).toOpaque())
}
internal func array(count: Int) -> [Memory] {
let buffer = UnsafeBufferPointer<Memory>(start: self, count: count)
return Array<Memory>(buffer)
}
}
extension Unmanaged {
internal static func fromOpaque(value: UnsafeMutablePointer<Void>) -> Unmanaged<Instance> {
return self.fromOpaque(COpaquePointer(value))
}
internal static func fromOptionalOpaque(value: UnsafePointer<Void>) -> Unmanaged<Instance>? {
if value != nil {
return self.fromOpaque(COpaquePointer(value))
} else {
return nil
}
}
}
extension Array {
internal mutating func withUnsafeMutablePointerOrAllocation<R>(count: Int, fastpath: UnsafeMutablePointer<Element> = nil, @noescape body: (UnsafeMutablePointer<Element>) -> R) -> R {
if fastpath != nil {
return body(fastpath)
} else if self.count > count {
let buffer = UnsafeMutablePointer<Element>.alloc(count)
let res = body(buffer)
buffer.destroy(count)
buffer.dealloc(count)
return res
} else {
return withUnsafeMutableBufferPointer() { (inout bufferPtr: UnsafeMutableBufferPointer<Element>) -> R in
return body(bufferPtr.baseAddress)
}
}
}
}
public protocol Bridgeable {
typealias BridgeType
func bridge() -> BridgeType
}
| apache-2.0 | 0f80bd5e38e481d12aefce785d523b7b | 41.751337 | 187 | 0.743574 | 5.266469 | false | false | false | false |
piv199/EZSwiftExtensions | Sources/IntExtensions.swift | 1 | 2378 | //
// IntExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 16/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
extension Int {
/// EZSE: Checks if the integer is even.
public var isEven: Bool { return (self % 2 == 0) }
/// EZSE: Checks if the integer is odd.
public var isOdd: Bool { return (self % 2 != 0) }
/// EZSE: Checks if the integer is positive.
public var isPositive: Bool { return (self > 0) }
/// EZSE: Checks if the integer is negative.
public var isNegative: Bool { return (self < 0) }
/// EZSE: Converts integer value to Double.
public var toDouble: Double { return Double(self) }
/// EZSE: Converts integer value to Float.
public var toFloat: Float { return Float(self) }
/// EZSE: Converts integer value to CGFloat.
public var toCGFloat: CGFloat { return CGFloat(self) }
/// EZSE: Converts integer value to String.
public var toString: String { return String(self) }
/// EZSE: Converts integer value to UInt.
public var toUInt: UInt { return UInt(self) }
/// EZSE: Converts integer value to Int32.
public var toInt32: Int32 { return Int32(self) }
/// EZSE: Converts integer value to a 0..<Int range. Useful in for loops.
public var range: CountableRange<Int> { return 0..<self }
/// EZSE: Returns number of digits in the integer.
public var digits: Int {
if self == 0 {
return 1
} else if Int(fabs(Double(self))) <= LONG_MAX {
return Int(log10(fabs(Double(self)))) + 1
} else {
return -1; //out of bound
}
}
}
extension UInt {
/// EZSE: Convert UInt to Int
public var toInt: Int { return Int(self) }
/// EZSE: Greatest common divisor of two integers using the Euclid's algorithm.
/// Time complexity of this in O(log(n))
public static func gcd(_ firstNum:UInt, _ secondNum:UInt) -> UInt {
let remainder = firstNum % secondNum
if remainder != 0 {
return gcd(secondNum, remainder)
} else {
return secondNum
}
}
/// EZSE: Least common multiple of two numbers. LCM = n * m / gcd(n, m)
public static func lcm(_ firstNum:UInt, _ secondNum:UInt) -> UInt {
return firstNum * secondNum / UInt.gcd(firstNum, secondNum)
}
}
| mit | 369f04c23dac4555a856dc040891f8e5 | 30.706667 | 83 | 0.614802 | 4.107081 | false | false | false | false |
hooman/swift | test/Parse/dollar_identifier.swift | 10 | 4641 | // RUN: %target-typecheck-verify-swift -swift-version 4
// SR-1661: Dollar was accidentally allowed as an identifier in Swift 3.
// SE-0144: Reject this behavior in the future.
func dollarVar() {
var $ : Int = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
$ += 1 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarLet() {
let $ = 42 // expected-error {{'$' is not an identifier; use backticks to escape it}} {{7-8=`$`}}
print($) // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarClass() {
class $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{9-10=`$`}}
}
func dollarEnum() {
enum $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
}
func dollarStruct() {
struct $ {} // expected-error {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
}
func dollarFunc() {
func $($ dollarParam: Int) {}
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{8-9=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{10-11=`$`}}
$($: 24)
// expected-error@-1 {{'$' is not an identifier; use backticks to escape it}} {{3-4=`$`}}
// expected-error@-2 {{'$' is not an identifier; use backticks to escape it}} {{5-6=`$`}}
}
func escapedDollarVar() {
var `$` : Int = 42 // no error
`$` += 1
print(`$`)
}
func escapedDollarLet() {
let `$` = 42 // no error
print(`$`)
}
func escapedDollarClass() {
class `$` {} // no error
}
func escapedDollarEnum() {
enum `$` {} // no error
}
func escapedDollarStruct() {
struct `$` {} // no error
}
func escapedDollarFunc() {
func `$`(`$`: Int) {} // no error
`$`(`$`: 25) // no error
}
func escapedDollarAnd() {
// FIXME: Bad diagnostics.
`$0` = 1 // expected-error {{expected expression}}
`$$` = 2
`$abc` = 3
}
// Test that we disallow user-defined $-prefixed identifiers. However, the error
// should not be emitted on $-prefixed identifiers that are not considered
// declarations.
func $declareWithDollar() { // expected-error{{cannot declare entity named '$declareWithDollar'}}
var $foo: Int { // expected-error{{cannot declare entity named '$foo'}}
get { 0 }
set($value) {} // expected-error{{cannot declare entity named '$value'}}
}
func $bar() { } // expected-error{{cannot declare entity named '$bar'}}
func wibble(
$a: Int, // expected-error{{cannot declare entity named '$a'}}
$b c: Int) { } // expected-error{{cannot declare entity named '$b'}}
let _: (Int) -> Int = {
[$capture = 0] // expected-error{{cannot declare entity named '$capture'}}
$a in // expected-error{{inferred projection type 'Int' is not a property wrapper}}
$capture
}
let ($a: _, _) = (0, 0) // expected-error{{cannot declare entity named '$a'}}
$label: if true { // expected-error{{cannot declare entity named '$label'}}
break $label
}
switch 0 {
@$dollar case _: // expected-error {{unknown attribute '$dollar'}}
break
}
if #available($Dummy 9999, *) {} // expected-warning {{unrecognized platform name '$Dummy'}}
@_swift_native_objc_runtime_base($Dollar)
class $Class {} // expected-error{{cannot declare entity named '$Class'; the '$' prefix is reserved}}
enum $Enum {} // expected-error{{cannot declare entity named '$Enum'; the '$' prefix is reserved}}
struct $Struct { // expected-error{{cannot declare entity named '$Struct'; the '$' prefix is reserved}}
@_projectedValueProperty($dummy)
let property: Never
}
}
protocol $Protocol {} // expected-error {{cannot declare entity named '$Protocol'; the '$' prefix is reserved}}
precedencegroup $Precedence { // expected-error {{cannot declare entity named '$Precedence'; the '$' prefix is reserved}}
higherThan: $Precedence // expected-error {{cycle in 'higherThan' relation}}
}
infix operator **: $Precedence
#$UnknownDirective() // expected-error {{use of unknown directive '#$UnknownDirective'}}
// SR-13232
@propertyWrapper
struct Wrapper {
var wrappedValue: Int
var projectedValue: String { String(wrappedValue) }
}
struct S {
@Wrapper var café = 42
}
let _ = S().$café // Okay
infix operator $ // expected-error{{'$' is considered an identifier and must not appear within an operator name}} // SR-13092
infix operator `$` // expected-error{{'$' is considered an identifier and must not appear within an operator name}} // SR-13092
| apache-2.0 | 5be4566c0e69dfde15e60736fd0a45fe | 37.02459 | 127 | 0.640224 | 3.869058 | false | false | false | false |
lorentey/swift | test/IRGen/partial_apply_generic.swift | 9 | 2515 | // RUN: %target-swift-frontend %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
//
// Type parameters
//
infix operator ~>
func ~> <Target, Args, Result> (
target: Target,
method: (Target) -> (Args) -> Result)
-> (Args) -> Result
{
return method(target)
}
protocol Runcible {
associatedtype Element
}
struct Mince {}
struct Spoon: Runcible {
typealias Element = Mince
}
func split<Seq: Runcible>(_ seq: Seq) -> ((Seq.Element) -> Bool) -> () {
return {(isSeparator: (Seq.Element) -> Bool) in
return ()
}
}
var seq = Spoon()
var x = seq ~> split
//
// Indirect return
//
// CHECK-LABEL: define internal swiftcc { i8*, %swift.refcounted* } @"$s21partial_apply_generic5split{{[_0-9a-zA-Z]*}}FTA"(%T21partial_apply_generic5SpoonV* noalias nocapture, %swift.refcounted* swiftself)
// CHECK: [[REABSTRACT:%.*]] = bitcast %T21partial_apply_generic5SpoonV* %0 to %swift.opaque*
// CHECK: tail call swiftcc { i8*, %swift.refcounted* } @"$s21partial_apply_generic5split{{[_0-9a-zA-Z]*}}F"(%swift.opaque* noalias nocapture [[REABSTRACT]],
struct HugeStruct { var a, b, c, d: Int }
struct S {
func hugeStructReturn(_ h: HugeStruct) -> HugeStruct { return h }
}
let s = S()
var y = s.hugeStructReturn
// CHECK-LABEL: define internal swiftcc { i64, i64, i64, i64 } @"$s21partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFFTA"(i64, i64, i64, i64, %swift.refcounted* swiftself) #0 {
// CHECK: entry:
// CHECK: %5 = tail call swiftcc { i64, i64, i64, i64 } @"$s21partial_apply_generic1SV16hugeStructReturnyAA04HugeE0VAFF"(i64 %0, i64 %1, i64 %2, i64 %3)
// CHECK: ret { i64, i64, i64, i64 } %5
// CHECK: }
//
// Witness method
//
protocol Protein {
static func veganOrNothing() -> Protein?
static func paleoDiet() throws -> Protein
}
enum CarbOverdose : Error {
case Mild
case Severe
}
class Chicken : Protein {
static func veganOrNothing() -> Protein? {
return nil
}
static func paleoDiet() throws -> Protein {
throw CarbOverdose.Severe
}
}
func healthyLunch<T: Protein>(_ t: T) -> () -> Protein? {
return T.veganOrNothing
}
let f = healthyLunch(Chicken())
func dietaryFad<T: Protein>(_ t: T) -> () throws -> Protein {
return T.paleoDiet
}
let g = dietaryFad(Chicken())
do {
try g()
} catch {}
//
// Incorrect assertion regarding inout parameters in NecessaryBindings
//
func coyote<T, U>(_ t: T, _ u: U) {}
func hawk<A, B, C>(_: A, _ b: B, _ c: C) {
let fn: (Optional<(A) -> B>, @escaping (inout B, C) -> ()) -> () = coyote
}
| apache-2.0 | 7ec99a8836983ed44fc6d0f726c77e5f | 23.417476 | 205 | 0.644533 | 2.997616 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Authentication/Helpers/CountryCode/CountryCodeTableViewController.swift | 1 | 7535 | //
// 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 Foundation
import UIKit
protocol CountryCodeTableViewControllerDelegate: AnyObject {
func countryCodeTableViewController(_ viewController: UIViewController, didSelect country: Country)
}
final class CountryCodeTableViewController: UITableViewController, UISearchControllerDelegate {
weak var delegate: CountryCodeTableViewControllerDelegate?
private lazy var sections: [[Country]] = {
guard let countries = Country.allCountries else { return [] }
let selector = #selector(getter: Country.displayName)
let sectionTitlesCount = UILocalizedIndexedCollation.current().sectionTitles.count
var mutableSections: [[Country]] = []
for _ in 0..<sectionTitlesCount {
mutableSections.append([Country]())
}
for country in countries {
let sectionNumber = UILocalizedIndexedCollation.current().section(for: country, collationStringSelector: selector)
mutableSections[sectionNumber].append(country)
}
for idx in 0..<sectionTitlesCount {
let objectsForSection = mutableSections[idx]
if let countries = UILocalizedIndexedCollation.current().sortedArray(from: objectsForSection, collationStringSelector: selector) as? [Country] {
mutableSections[idx] = countries
}
}
#if WIRESTAN
mutableSections[0].insert(Country.countryWirestan, at: 0)
#endif
return mutableSections
}()
lazy var searchController: UISearchController = {
return UISearchController(searchResultsController: resultsTableViewController)
}()
private let resultsTableViewController: CountryCodeResultsTableViewController = CountryCodeResultsTableViewController()
override func viewDidLoad() {
super.viewDidLoad()
CountryCell.register(in: tableView)
searchController.searchResultsUpdater = self
searchController.searchBar.sizeToFit()
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
tableView.sectionIndexBackgroundColor = UIColor.clear
resultsTableViewController.tableView.delegate = self
searchController.delegate = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.delegate = self
searchController.searchBar.backgroundColor = UIColor.white
navigationItem.rightBarButtonItem = navigationController?.closeItem()
definesPresentationContext = true
title = NSLocalizedString("registration.country_select.title", comment: "").localizedUppercase
}
// MARK: - UITableViewDelegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCountry: Country?
if resultsTableViewController.tableView == tableView {
selectedCountry = resultsTableViewController.filteredCountries?[indexPath.row]
searchController.isActive = false
} else {
selectedCountry = sections[indexPath.section][indexPath.row]
}
if let selectedCountry = selectedCountry {
delegate?.countryCodeTableViewController(self, didSelect: selectedCountry)
}
}
// MARK: - TableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(ofType: CountryCell.self, for: indexPath)
cell.configure(for: sections[indexPath.section][indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return UILocalizedIndexedCollation.current().sectionTitles[section]
}
override func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return UILocalizedIndexedCollation.current().sectionIndexTitles
}
}
// MARK: - UISearchBarDelegate
extension CountryCodeTableViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
}
}
// MARK: - UISearchResultsUpdating
/// TODO: test
extension CountryCodeTableViewController: UISearchResultsUpdating {
func filter(searchText: String?) -> [Any]? {
guard var searchResults: [Any] = (sections as NSArray).value(forKeyPath: "@unionOfArrays.self") as? [Any] else { return nil}
// Strip out all the leading and trailing spaces
let strippedString = searchText?.trimmingCharacters(in: CharacterSet.whitespaces)
// Break up the search terms (separated by spaces)
let searchItems: [String]
if strippedString?.isEmpty == false {
searchItems = strippedString?.components(separatedBy: " ") ?? []
} else {
searchItems = []
}
var searchItemPredicates: [NSPredicate] = []
var numberPredicates: [NSPredicate] = []
for searchString in searchItems {
let displayNamePredicate = NSPredicate(format: "displayName CONTAINS[cd] %@", searchString)
searchItemPredicates.append(displayNamePredicate)
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .none
if let targetNumber = numberFormatter.number(from: searchString) {
numberPredicates.append(NSPredicate(format: "e164 == %@", targetNumber))
}
}
let andPredicates: NSCompoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: searchItemPredicates)
let orPredicates = NSCompoundPredicate(orPredicateWithSubpredicates: numberPredicates)
let finalPredicate = NSCompoundPredicate(orPredicateWithSubpredicates: [andPredicates, orPredicates])
searchResults = searchResults.filter {
finalPredicate.evaluate(with: $0)
}
return searchResults
}
func updateSearchResults(for searchController: UISearchController) {
// Update the filtered array based on the search text
let searchText = searchController.searchBar.text
guard let searchResults = filter(searchText: searchText) else { return }
// Hand over the filtered results to our search results table
let tableController = self.searchController.searchResultsController as? CountryCodeResultsTableViewController
tableController?.filteredCountries = searchResults as? [Country]
tableController?.tableView.reloadData()
}
}
| gpl-3.0 | f4bca7cc7d39b8f06b3de2bbd16dce50 | 37.840206 | 157 | 0.70856 | 5.951817 | false | false | false | false |
zmeyc/telegram-bot-swift | Sources/TelegramBotSDK/Router/Router+Helpers.swift | 1 | 2886 | //
// Router+Helpers.swift
//
// This source file is part of the Telegram Bot SDK for Swift (unofficial).
//
// Copyright (c) 2015 - 2020 Andrey Fidrya and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information
// See AUTHORS.txt for the list of the project authors
//
import Foundation
extension Router {
// add() taking string
public func add(_ commandString: String, _ options: Command.Options = [], _ handler: @escaping (Context) throws -> Bool) {
add(Command(commandString, options: options), handler)
}
// Subscripts taking ContentType
public subscript(_ contentType: ContentType) -> (Context) throws->Bool {
get { fatalError("Not implemented") }
set { add(contentType, newValue) }
}
// Subscripts taking Command
public subscript(_ command: Command) -> (Context) throws->Bool {
get { fatalError("Not implemented") }
set { add(command, newValue) }
}
public subscript(_ commands: [Command]) -> (Context) throws->Bool {
get { fatalError("Not implemented") }
set { add(commands, newValue) }
}
public subscript(_ commands: Command...) -> (Context) throws->Bool {
get { fatalError("Not implemented") }
set { add(commands, newValue) }
}
// Subscripts taking String
public subscript(_ commandString: String, _ options: Command.Options) -> (Context) throws -> Bool {
get { fatalError("Not implemented") }
set { add(Command(commandString, options: options), newValue) }
}
public subscript(_ commandString: String) -> (Context) throws -> Bool {
get { fatalError("Not implemented") }
set { add(Command(commandString), newValue) }
}
public subscript(_ commandStrings: [String], _ options: Command.Options) -> (Context) throws -> Bool {
get { fatalError("Not implemented") }
set {
let commands = commandStrings.map { Command($0, options: options) }
add(commands, newValue)
}
}
public subscript(commandStrings: [String]) -> (Context) throws -> Bool {
get { fatalError("Not implemented") }
set {
let commands = commandStrings.map { Command($0) }
add(commands, newValue)
}
}
// Segmentation fault
// public subscript(commandStrings: String..., _ options: Command.Options) -> (Context) throws -> Bool {
// get { fatalError("Not implemented") }
// set {
// let commands = commandStrings.map { Command($0, options: options) }
// add(commands, newValue)
// }
// }
public subscript(commandStrings: String...) -> (Context) throws -> Bool {
get { fatalError("Not implemented") }
set {
let commands = commandStrings.map { Command($0) }
add(commands, newValue)
}
}
}
| apache-2.0 | 49ec8625ac168630a1f66310a2c0a344 | 31.066667 | 123 | 0.620236 | 4.262925 | false | false | false | false |
iAlexander/Obminka | XtraLibraries/Tests/SelectableSectionTests.swift | 2 | 9054 | // SelectableSectionTests.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Eureka
class SelectableSectionTests: XCTestCase {
var formVC = FormViewController()
override func setUp() {
super.setUp()
let form = Form()
//create a form with two sections. The second one is of multiple selection
let continents = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]
let oceans = ["Arctic", "Atlantic", "Indian", "Pacific", "Southern"]
form +++ SelectableSection<ListCheckRow<String>> { _ in }
for option in continents {
form.last! <<< ListCheckRow<String>(option) { lrow in
lrow.title = option
lrow.selectableValue = option
lrow.value = nil
}
}
form +++ SelectableSection<ListCheckRow<String>>("And which of the following oceans have you taken a bath in?", selectionType: .multipleSelection)
for option in oceans {
form.last! <<< ListCheckRow<String>(option) { lrow in
lrow.title = option
lrow.selectableValue = option
}
}
form +++ SelectableSection<ListCheckRow<String>>("", selectionType: .singleSelection(enableDeselection: false))
for option in oceans {
form.last! <<< ListCheckRow<String>("\(option)2") { lrow in
lrow.title = option
lrow.selectableValue = option
}
}
formVC.form = form
// load the view to test the cells
formVC.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000)
formVC.tableView?.frame = formVC.view.frame
}
override func tearDown() {
super.tearDown()
}
func testSections() {
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 0))
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 1))
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 3, section: 1))
let value1 = (formVC.form[0] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue
let value2 = (formVC.form[1] as! SelectableSection<ListCheckRow<String>>).selectedRows().map {$0.baseValue}
XCTAssertEqual(value1 as? String, "Antarctica")
XCTAssertTrue(value2.count == 2)
XCTAssertEqual((value2[0] as? String), "Atlantic")
XCTAssertEqual((value2[1] as? String), "Pacific")
//Now deselect One of the multiple selection section and change the value of the first section
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 6, section: 0))
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 1, section: 1))
let value3 = (formVC.form[0] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue
let selectedRows = (formVC.form[1] as! SelectableSection<ListCheckRow<String>>).selectedRows()
let value4 = selectedRows.map { $0.baseValue }
XCTAssertEqual(value3 as? String, "South America")
XCTAssertTrue(value4.count == 1)
XCTAssertEqual((value4[0] as? String), "Pacific")
}
func testDeselectionDisabled() {
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 0, section: 2))
var value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue
XCTAssertEqual(value1 as? String, "Arctic")
// now try deselecting one of each and see that nothing changes.
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 0, section: 2))
value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue
XCTAssertEqual(value1 as? String, "Arctic")
// But we can change the value in the first section
formVC.tableView(formVC.tableView!, didSelectRowAt: IndexPath(row: 2, section: 2))
value1 = (formVC.form[2] as! SelectableSection<ListCheckRow<String>>).selectedRow()?.baseValue
XCTAssertEqual(value1 as? String, "Indian")
}
func testSectionedSections() {
let selectorViewController = SelectorViewController<PushRow<String>>(nibName: nil, bundle: nil)
selectorViewController.row = PushRow<String> { row in
row.options = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]
}
enum Hemisphere: Int {
case west, east, none
}
selectorViewController.sectionKeyForValue = { option in
switch option {
case "Africa", "Asia", "Australia", "Europe":
return String(Hemisphere.west.rawValue)
case "North America", "South America":
return String(Hemisphere.east.rawValue)
default:
return String(Hemisphere.none.rawValue)
}
}
selectorViewController.sectionHeaderTitleForKey = { key in
switch Hemisphere(rawValue: Int(key)!)! {
case .west: return "West hemisphere"
case .east: return "East hemisphere"
case .none: return ""
}
}
selectorViewController.sectionFooterTitleForKey = { key in
switch Hemisphere(rawValue: Int(key)!)! {
case .west: return "West hemisphere"
case .east: return "East hemisphere"
case .none: return ""
}
}
selectorViewController.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000)
selectorViewController.tableView?.frame = selectorViewController.view.frame
let form = selectorViewController.form
XCTAssertEqual(form.count, 3)
XCTAssertEqual(form[0].count, 4)
XCTAssertEqual(form[1].count, 2)
XCTAssertEqual(form[2].count, 1)
XCTAssertEqual(form[0].header?.title, "West hemisphere")
XCTAssertEqual(form[1].header?.title, "East hemisphere")
XCTAssertEqual(form[2].header?.title, "")
XCTAssertEqual(form[0].footer?.title, "West hemisphere")
XCTAssertEqual(form[1].footer?.title, "East hemisphere")
XCTAssertEqual(form[2].footer?.title, "")
XCTAssertEqual(form[0].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["Africa", "Asia", "Australia", "Europe"])
XCTAssertEqual(form[1].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["North America", "South America"])
XCTAssertEqual(form[2].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), ["Antarctica"])
}
func testLazyOptionsProvider() {
let selectorViewController = SelectorViewController<PushRow<String>>(nibName: nil, bundle: nil)
let row = PushRow<String>()
selectorViewController.row = row
let options = ["Africa", "Antarctica", "Asia", "Australia", "Europe", "North America", "South America"]
let optionsFetched = expectation(description: "Fetched options")
row.optionsProvider = .lazy({ form, completion in
DispatchQueue.main.async {
completion(options)
optionsFetched.fulfill()
}
})
let form = selectorViewController.form
XCTAssertEqual(form.count, 0)
selectorViewController.view.frame = CGRect(x: 0, y: 0, width: 375, height: 3000)
selectorViewController.tableView?.frame = selectorViewController.view.frame
waitForExpectations(timeout: 1, handler: nil)
XCTAssertEqual(row.options ?? [], options)
XCTAssertEqual(form.count, 1)
XCTAssertEqual(form[0].count, options.count)
XCTAssertEqual(form[0].flatMap({ ($0 as! ListCheckRow<String>).selectableValue }), options)
}
}
| mit | 2db37ff6459eb6d2a0b14af837ef4346 | 41.707547 | 154 | 0.645129 | 4.710718 | false | false | false | false |
SoaringDragon/ProjectSettings | ProjectSettingsSwift/ProjectSettingsSwift/ViewController.swift | 1 | 5311 | //
// ViewController.swift
// ProjectSettingsSwift
//
// Created by GK on 16/3/26.
// Copyright © 2016年 GK. All rights reserved.
//
import UIKit
import Crashlytics
import Optimizely
internal var messageKey =
OptimizelyVariableKey.optimizelyKeyWithKey("message", defaultNSString: "Hello World!")
internal var reportTimeBlocksKey =
OptimizelyCodeBlocksKey("reportTimeBlocks", blockNames: ["alert", "button"])
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let gregorianCal = NSCalendar(calendarIdentifier: NSCalendarIdentifierChinese)!
let date1 = gregorianCal.dateWithEra(1, year: 2014, month: 9, day: 28, hour: 5, minute: 9, second: 0, nanosecond: 0)!
let date2 = gregorianCal.dateWithEra(1, year: 2015, month: 10, day: 21, hour: 12, minute: 7, second: 0, nanosecond: 0)!
let date3 = gregorianCal.dateWithEra(1, year: 2015, month: 11, day: 3, hour: 12, minute: 38, second: 0, nanosecond: 0)!
let date4 = gregorianCal.dateWithEra(1, year: 2015, month: 11, day: 4, hour: 14, minute: 41, second: 0, nanosecond: 0)!
let date5 = gregorianCal.dateWithEra(1, year: 2015, month: 11, day: 4, hour: 15, minute: 08, second: 0, nanosecond: 0)!
let timeOffset1 = date1.relativeTime // "1 year ago"
let timeOffset2 = date2.relativeTime // "2 weeks ago"
let timeOffset3 = date3.relativeTime // "Yesterday"
let timeOffset4 = date4.relativeTime // "27 minutes ago"
let timeOffset5 = date5.relativeTime // "Just now"
print(timeOffset1)
print(timeOffset2)
print(timeOffset3)
print(timeOffset4)
print(timeOffset5)
print(SERVER_URL)
let button = UIButton(type: UIButtonType.RoundedRect)
button.frame = CGRectMake(20, 50, 100, 30)
button.setTitle("Crash", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(ViewController.crashButtonTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
Crashlytics.sharedInstance().setObjectValue("Test value", forKey: "Crash")
let messageButton1 = UIButton(type: UIButtonType.System)
messageButton1.setTitle("Show Message", forState: UIControlState.Normal)
messageButton1.addTarget(self, action: #selector(ViewController.showMessage(_:)), forControlEvents: UIControlEvents.TouchUpInside)
messageButton1.frame = CGRectMake(25, 60, 200, 50)
view.addSubview(messageButton1)
let messageButton = UIButton(type: UIButtonType.System)
messageButton.setTitle("Report Time", forState: UIControlState.Normal)
messageButton.addTarget(self, action: #selector(ViewController.reportTime(_:)), forControlEvents: UIControlEvents.TouchUpInside)
messageButton.frame = CGRectMake(25, 400, 300, 50)
view.addSubview(messageButton)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func crashButtonTapped(sender : AnyObject){
Answers.logCustomEventWithName("View controller did load", customAttributes: [
"Poem" : "Poem Event",
"Them" : "Them",
"Length" : "1209",
"Picture" : "Picture"
])
Crashlytics.sharedInstance().crash()
}
@IBAction func showMessage(sender: AnyObject) {
let alert = UIAlertController(title: "Live Variable",
message: Optimizely.stringForKey(messageKey),
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default,
handler: nil))
presentViewController(alert, animated: true) {}
}
@IBAction func reportTime(sender: AnyObject) {
let message = NSString(format: "It is %@", NSDate()) as String;
Optimizely.codeBlocksWithKey(reportTimeBlocksKey,
blockOne: {
let alert = UIAlertController(title: "Live Variable",
message: message,
preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK",
style: UIAlertActionStyle.Default,
handler: { (action) -> Void in }))
self.presentViewController(alert, animated: true) {}
},
blockTwo: {
sender.setTitle(message, forState: UIControlState.Normal)
},
defaultBlock: {
print(message)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | ab9a86df52603a1d4c36242f736d6b28 | 40.795276 | 138 | 0.592879 | 5.123552 | false | false | false | false |
godenzim/NetKit | NetKit/Common/Reachability/Reachability.swift | 1 | 3048 | //
// Reachability.swift
// NetKit
//
// Created by Mike Godenzi on 26.10.14.
// Copyright (c) 2014 Mike Godenzi. All rights reserved.
//
import Foundation
import SystemConfiguration
private func blankOf<T>(type: T.Type) -> T {
let ptr = UnsafeMutablePointer<T>.alloc(sizeof(T))
let val = ptr.memory
ptr.destroy()
return val
}
public let NetworkReachabilityChangedNotification = "NetworkReachabilityChangedNotification"
public enum ReachabilityType {
case Internet, LocalWiFi
}
public class Reachability {
public enum NetworkStatus {
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
}
public var currentStatus : NetworkStatus {
var result = NetworkStatus.NotReachable
var flags : SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(reachability, &flags) == true {
result = statusForFlags(flags)
}
return result
}
public var connectionRequires : Bool {
var result = false
var flags : SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(reachability, &flags) == true {
result = flags.contains(SCNetworkReachabilityFlags.ConnectionRequired)
}
return result
}
private let reachability: SCNetworkReachability
public let reachabilityType : ReachabilityType
private init(hostAddress : UnsafePointer<sockaddr_in>, type : ReachabilityType) {
reachabilityType = type
reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer<sockaddr>(hostAddress))!
}
deinit {
stop()
}
public convenience init(type : ReachabilityType) {
var address = blankOf(sockaddr_in)
address.sin_len = UInt8(sizeof(sockaddr_in))
address.sin_family = sa_family_t(AF_INET)
if type == .LocalWiFi {
address.sin_addr.s_addr = CFSwapInt32HostToBig(0xA9FE0000)
}
self.init(hostAddress: &address, type: type)
}
public func start() -> Bool {
let context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
return NKReachabilityStart(reachability, context)
}
public func stop() {
NKReachabilityStop(reachability)
}
private func statusForFlags(flags : SCNetworkReachabilityFlags) -> NetworkStatus {
var result = NetworkStatus.NotReachable
if reachabilityType == .Internet {
if !flags.contains(SCNetworkReachabilityFlags.Reachable) {
return .NotReachable
}
if !flags.contains(SCNetworkReachabilityFlags.ConnectionRequired) {
result = .ReachableViaWiFi
}
if !flags.contains(SCNetworkReachabilityFlags.InterventionRequired) || flags.contains(SCNetworkReachabilityFlags.ConnectionOnTraffic) {
if !flags.contains(SCNetworkReachabilityFlags.InterventionRequired) {
result = .ReachableViaWiFi
}
}
if flags == SCNetworkReachabilityFlags.IsWWAN {
result = .ReachableViaWWAN
}
} else {
if flags.contains(SCNetworkReachabilityFlags.Reachable) && flags.contains(SCNetworkReachabilityFlags.IsDirect) {
result = .ReachableViaWiFi;
}
}
return result
}
}
| mit | ee974227a3fd5d60d175a73541bcf9e4 | 27.485981 | 138 | 0.759186 | 4.192572 | false | false | false | false |
chicio/RangeUISlider | DemoSPM/ViewController.swift | 1 | 4276 | //
// ViewController.swift
// DemoSPM
//
// Created by Fabrizio Duroni on 24/09/2019.
// 2019 Fabrizio Duroni.
//
// swiftlint:disable function_body_length
import UIKit
import RangeUISlider
class ViewController: UIViewController, RangeUISliderDelegate {
private var rangeSlider: RangeUISlider!
override func viewDidLoad() {
super.viewDidLoad()
rangeSlider = RangeUISlider(frame: CGRect(origin: CGPoint(x: 20, y: 20), size: CGSize(width: 100, height: 50)))
rangeSlider.translatesAutoresizingMaskIntoConstraints = false
rangeSlider.delegate = self
rangeSlider.scaleMinValue = 0 // If you don't set any value the default is 0
rangeSlider.scaleMaxValue = 100 // If you don't set any value the default is 1
rangeSlider.defaultValueLeftKnob = 25 // If the scale is the default one insert a value between 0 and 1
rangeSlider.defaultValueRightKnob = 75 // If the scale is the default one insert a value between 0 and 1
rangeSlider.rangeSelectedGradientColor1 = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1)
rangeSlider.rangeSelectedGradientColor2 = #colorLiteral(red: 0.2392156869, green: 0.6745098233, blue: 0.9686274529, alpha: 1)
rangeSlider.rangeSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.rangeNotSelectedGradientColor1 = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
rangeSlider.rangeNotSelectedGradientColor2 = #colorLiteral(red: 0.09019608051, green: 0, blue: 0.3019607961, alpha: 1)
rangeSlider.rangeNotSelectedGradientStartPoint = CGPoint(x: 0, y: 0.5)
rangeSlider.rangeNotSelectedGradientEndPoint = CGPoint(x: 0, y: 1)
rangeSlider.barHeight = 20
rangeSlider.barCorners = 10
rangeSlider.leftKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.leftKnobWidth = 40
rangeSlider.leftKnobHeight = 40
rangeSlider.leftKnobCorners = 20
rangeSlider.rightKnobColor = #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1)
rangeSlider.rightKnobWidth = 40
rangeSlider.rightKnobHeight = 40
rangeSlider.rightKnobCorners = 20
self.view.addSubview(rangeSlider)
// Setup slide with programmatic autolayout.
NSLayoutConstraint.activate([
NSLayoutConstraint(item: rangeSlider!,
attribute: .leading,
relatedBy: .equal,
toItem: self.view,
attribute: .leading,
multiplier: 1.0,
constant: 20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .trailing,
relatedBy: .equal,
toItem: self.view,
attribute: .trailing,
multiplier: 1.0,
constant: -20),
NSLayoutConstraint(item: rangeSlider!,
attribute: .top,
relatedBy: .equal,
toItem: self.view,
attribute: .top,
multiplier: 1.0,
constant: 100),
NSLayoutConstraint(item: rangeSlider!,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: 50)
])
}
func rangeChangeFinished(event: RangeUISliderChangeFinishedEvent) {
print("\(event.minValueSelected) - \(event.maxValueSelected) - identifier: \(event.slider.identifier)")
}
func rangeIsChanging(event: RangeUISliderChangeEvent) {
print("\(event.minValueSelected) - \(event.maxValueSelected) - identifier: \(event.slider.identifier)")
}
}
| mit | 61034bec00a227f4d78c45eccb0a71ad | 48.72093 | 138 | 0.586529 | 5.078385 | false | false | false | false |
johnmcneilstudio/JMSRangeSlider | JMSRangeSlider/JMSRangeSlider.swift | 1 | 18493 | //
// JMSRangeSlider.swift
// JMSRangeSlider
//
// Created by Matthieu Collé on 23/07/2015.
// Copyright © 2015 JohnMcNeil Studio. All rights reserved.
//
import Cocoa
import QuartzCore
public enum JMSRangeSliderDirection: Int {
case horizontal = 1
case vertical
}
public enum JMSRangeSliderCellsSide: Int {
case top = 1
case bottom
case left
case right
case centerVert
case centerHoriz
}
open class JMSRangeSlider: NSControl {
// Previous mouse location
fileprivate var previousLocation: CGPoint = CGPoint()
// Private vars
fileprivate let trackLayer: RangeSliderTrackLayer = RangeSliderTrackLayer()
fileprivate let lowerCellLayer: RangeSliderCellLayer = RangeSliderCellLayer()
fileprivate let upperCellLayer: RangeSliderCellLayer = RangeSliderCellLayer()
// Slider Direction ( Horizontal / Vertical )
open var direction: JMSRangeSliderDirection = JMSRangeSliderDirection.horizontal {
didSet {
// Default values
// Left side when vertical position
// Top side when horizontal position
if direction == JMSRangeSliderDirection.vertical {
if cellsSide != JMSRangeSliderCellsSide.left || cellsSide != JMSRangeSliderCellsSide.right {
cellsSide = JMSRangeSliderCellsSide.left
}
} else {
if cellsSide != JMSRangeSliderCellsSide.top || cellsSide != JMSRangeSliderCellsSide.bottom {
cellsSide = JMSRangeSliderCellsSide.top
}
}
updateLayerFrames()
}
}
// Returns wether or not the slider is in vertical direction
open var isVertical: Bool {
return self.direction == JMSRangeSliderDirection.vertical
}
// Cells side ( Top / Bottom / Left / Right )
open var cellsSide: JMSRangeSliderCellsSide = JMSRangeSliderCellsSide.top {
didSet {
updateLayerFrames()
}
}
// Slider minimum value
open var minValue: Double = 0.0 {
didSet {
updateLayerFrames()
}
}
// Slider maximum value
open var maxValue: Double = 1.0 {
didSet {
updateLayerFrames()
}
}
// Slider lower value
open var lowerValue: Double = 0.0 {
didSet {
updateLayerFrames()
}
}
// Slider upper value
open var upperValue: Double = 1.0 {
didSet {
updateLayerFrames()
}
}
// Cell width
open var cellWidth: CGFloat = 20.0 {
didSet {
updateLayerFrames()
}
}
// Cell height
open var cellHeight: CGFloat = 20.0 {
didSet {
updateLayerFrames()
}
}
// Frame
open override var frame: CGRect {
didSet {
updateLayerFrames()
}
}
// Track thickness
open var trackThickness: CGFloat = 10.0 {
didSet {
updateLayerFrames()
}
}
// Track tint color
open var trackTintColor: NSColor = NSColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0) {
didSet {
trackLayer.setNeedsDisplay()
}
}
// Track highlight tint color
open var trackHighlightTintColor: NSColor = NSColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0) {
didSet {
trackLayer.setNeedsDisplay()
}
}
// Extends the track to the ends of the frame
open var extendTrackToFrame: Bool = false {
didSet {
trackLayer.setNeedsDisplay()
}
}
// Cell tint color
open var cellTintColor: NSColor = NSColor.white {
didSet {
lowerCellLayer.setNeedsDisplay()
upperCellLayer.setNeedsDisplay()
}
}
// Track corner radius
open var trackCornerRadius: CGFloat = 1.0 {
didSet {
updateLayerFrames()
}
}
// Custom lower cell drawing
open var lowerCellDrawingFunction: ((_ frame: NSRect, _ context: CGContext) -> (Void))? {
didSet {
lowerCellLayer.setNeedsDisplay()
}
}
// Custom upper cell drawing
open var upperCellDrawingFunction: ((_ frame: NSRect, _ context: CGContext) -> (Void))? {
didSet {
upperCellLayer.setNeedsDisplay()
}
}
// INIT
public convenience init() {
self.init(frame: CGRect.zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.wantsLayer = true
trackLayer.rangeSlider = self
trackLayer.contentsScale = (NSScreen.main()?.backingScaleFactor)!
layer?.addSublayer(trackLayer)
lowerCellLayer.rangeSlider = self
lowerCellLayer.cellPosition = CellPosition.lower
lowerCellLayer.contentsScale = (NSScreen.main()?.backingScaleFactor)!
layer?.addSublayer(lowerCellLayer)
upperCellLayer.rangeSlider = self
upperCellLayer.cellPosition = CellPosition.upper
upperCellLayer.contentsScale = (NSScreen.main()?.backingScaleFactor)!
layer?.addSublayer(upperCellLayer)
updateLayerFrames()
}
public required init?(coder: NSCoder) {
super.init(coder: coder)
}
//
// USER INTERACTION
//
open override func touchesBegan(with event: NSEvent) {
if #available(OSX 10.12.2, *) {
if let touch = event.touches(matching: .began, in: self).first {
interactionBegan(location: touch.location(in: self))
}
}
}
open override func mouseDown(with evt: NSEvent) {
let location = evt.locationInWindow
interactionBegan(location: convert(location, from: nil))
}
open func interactionBegan(location: NSPoint) {
previousLocation = location
if lowerCellLayer.frame.contains(previousLocation) {
lowerCellLayer.highlighted = true
} else if upperCellLayer.frame.contains(previousLocation) {
upperCellLayer.highlighted = true
}
}
open override func touchesMoved(with event: NSEvent) {
if #available(OSX 10.12.2, *) {
if let touch = event.touches(matching: .moved, in: self).first {
interactionMoved(location: touch.location(in: self))
}
}
}
open override func mouseDragged(with evt: NSEvent) {
let location = evt.locationInWindow
let pointInView = convert(location, from: nil)
interactionMoved(location: pointInView)
}
open func interactionMoved(location: NSPoint) {
// Get delta
let deltaLocation = isVertical ? Double(location.y - previousLocation.y) : Double(location.x - previousLocation.x)
let deltaValue = (maxValue - minValue) * deltaLocation / (isVertical ? Double(bounds.height - cellHeight) : Double(bounds.width - cellWidth))
previousLocation = location
// Update values
let oldLowerValue = lowerValue
let oldUpperValue = upperValue
var newLowerValue = lowerValue
var newUpperValue = upperValue
if lowerCellLayer.highlighted {
newLowerValue += deltaValue
newLowerValue = boundValue(newLowerValue, toLowerValue: minValue, upperValue: upperValue)
} else if upperCellLayer.highlighted {
newUpperValue += deltaValue
newUpperValue = boundValue(newUpperValue, toLowerValue: lowerValue, upperValue: maxValue)
}
if newLowerValue != lowerValue {
lowerValue = newLowerValue
} else if newUpperValue != upperValue {
upperValue = newUpperValue
}
if oldLowerValue != lowerValue || oldUpperValue != upperValue {
// Notify App
NSApp.sendAction(self.action!, to: self.target, from: self)
}
}
open override func touchesEnded(with event: NSEvent) {
if #available(OSX 10.12.2, *) {
interactionEnded()
}
}
open override func touchesCancelled(with event: NSEvent) {
if #available(OSX 10.12.2, *) {
interactionEnded()
}
}
open override func mouseUp(with evt: NSEvent) {
interactionEnded()
}
open func interactionEnded() {
// Cells not highlighted anymore
lowerCellLayer.highlighted = false
upperCellLayer.highlighted = false
}
//
// OVERRIDE
//
// @function drawRect
// Draw rect
//
open override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
}
//
// PUBLIC
//
// @function updateLayerFrames
// Updates layers frame
//
fileprivate func updateLayerFrames() {
CATransaction.begin()
CATransaction.setDisableActions(true)
let lowerCellCenter = CGFloat(positionForValue(lowerValue))
let upperCellCenter = CGFloat(positionForValue(upperValue))
// Is vertical ?
if isVertical {
let y = extendTrackToFrame ? 2.0 : cellHeight
let height = extendTrackToFrame ? bounds.height - 4.0 : bounds.height - (2.0 * self.cellHeight)
trackLayer.frame = CGRect(x: self.frame.width - trackThickness, y: y, width: trackThickness, height: height)
lowerCellLayer.frame = CGRect(x: trackLayer.frame.origin.x - cellWidth, y: lowerCellCenter, width: cellWidth, height: cellHeight)
upperCellLayer.frame = CGRect(x: trackLayer.frame.origin.x - cellWidth, y: upperCellCenter + cellHeight, width: cellWidth, height: cellHeight)
// If Cells on the right side
if cellsSide == JMSRangeSliderCellsSide.right {
trackLayer.frame.origin.x = 0.0
lowerCellLayer.frame.origin.x = trackLayer.frame.width
upperCellLayer.frame.origin.x = trackLayer.frame.width
// If Cells in the center
} else if cellsSide == JMSRangeSliderCellsSide.centerVert {
trackLayer.frame.origin.x = (self.frame.width / 2.0) - (trackThickness / 2.0)
lowerCellLayer.frame.origin.x = trackThickness / 2.0
upperCellLayer.frame.origin.x = trackThickness / 2.0
}
// Is Horizontal ?
} else {
let x = extendTrackToFrame ? 1.0 : cellWidth
let width = extendTrackToFrame ? bounds.width - 2.0 : bounds.width - (2.0 * cellWidth)
trackLayer.frame = CGRect(x: x, y: 0, width: width, height: trackThickness)
lowerCellLayer.frame = CGRect(x: lowerCellCenter, y: trackThickness, width: cellWidth, height: cellHeight)
upperCellLayer.frame = CGRect(x: upperCellCenter + cellWidth, y: trackThickness, width: cellWidth, height: cellHeight)
// If Cells on the bottom side
if cellsSide == JMSRangeSliderCellsSide.bottom {
trackLayer.frame.origin.y = self.frame.height - trackThickness
lowerCellLayer.frame.origin.y = trackLayer.frame.origin.y - cellHeight
upperCellLayer.frame.origin.y = trackLayer.frame.origin.y - cellHeight
// If Cells in the center
} else if cellsSide == JMSRangeSliderCellsSide.centerHoriz {
trackLayer.frame.origin.y = (self.frame.height / 2.0) - (trackThickness / 2.0)
lowerCellLayer.frame.origin.y = 0.0
upperCellLayer.frame.origin.y = 0.0
}
}
// Force display of elements
trackLayer.setNeedsDisplay()
lowerCellLayer.setNeedsDisplay()
upperCellLayer.setNeedsDisplay()
CATransaction.commit()
}
//
// INTERNAL
//
// @function positionForValue
// Get frame position for slider value
//
internal func positionForValue(_ value: Double) -> Double {
// If vertical slider
if isVertical {
return Double(bounds.height - 2 * cellHeight) * (value - minValue) / (maxValue - minValue)
// If horizontal slider
} else {
return Double(bounds.width - 2 * cellWidth) * (value - minValue) / (maxValue - minValue)
}
}
// @function boundValue
// Bounds value
//
internal func boundValue(_ value: Double, toLowerValue lowerValue: Double, upperValue: Double) -> Double {
return min(max(value, lowerValue), upperValue)
}
}
//
// NSTouchBar Style
//
@available(OSX 10.12.2, *)
extension JMSRangeSlider {
// Creates a touch bar item that matches the style of the stock NSSliderTouchBarItem
public static func touchBarItem(identifier: NSTouchBarItemIdentifier, width: CGFloat = 260.0, target: AnyObject, action: Selector, minValue: Double = 0.0, maxValue: Double = 1.0, lowerValue: Double = 0.0, upperValue: Double = 1.0) -> (NSCustomTouchBarItem, JMSRangeSlider) {
let rangeSlider = JMSRangeSlider()
rangeSlider.translatesAutoresizingMaskIntoConstraints = false
rangeSlider.cellWidth = 32.0
rangeSlider.cellHeight = 30.0
rangeSlider.trackThickness = 4.0
rangeSlider.lowerCellDrawingFunction = drawScrubber
rangeSlider.upperCellDrawingFunction = drawScrubber
rangeSlider.trackTintColor = NSColor(deviceWhite: 115.0 / 255.0, alpha: 1.0)
rangeSlider.trackHighlightTintColor = NSColor(deviceRed: 0.0, green: 130.0 / 255.0, blue: 215.0 / 255.0, alpha: 1.0)
rangeSlider.cellsSide = JMSRangeSliderCellsSide.centerHoriz
rangeSlider.trackCornerRadius = 2.0
rangeSlider.extendTrackToFrame = true
rangeSlider.minValue = minValue
rangeSlider.maxValue = maxValue
rangeSlider.lowerValue = lowerValue
rangeSlider.upperValue = upperValue
rangeSlider.target = target
rangeSlider.action = action
let view = TouchBarBackgroundView()
view.translatesAutoresizingMaskIntoConstraints = false
view.wantsLayer = true
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[view(==\(width))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[view(==30.0)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));
view.addSubview(rangeSlider)
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:[rangeSlider(==\(width - 10.0))]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rangeSlider": rangeSlider]));
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[rangeSlider(==30.0)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rangeSlider": rangeSlider]));
view.addConstraint(NSLayoutConstraint(item: rangeSlider, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1.0, constant: 0.0));
view.addConstraint(NSLayoutConstraint(item: rangeSlider, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1.0, constant: 0.0));
let item = NSCustomTouchBarItem(identifier: identifier)
item.view = view
return (item, rangeSlider)
}
fileprivate static func drawScrubber(frame: NSRect, context: CGContext) {
//// Resize to Target Frame
context.saveGState()
//// scrubberShadow Drawing
context.saveGState()
context.setAlpha(0.24)
let scrubberShadowPath = NSBezierPath()
scrubberShadowPath.move(to: NSPoint(x: 3.39, y: 30))
scrubberShadowPath.curve(to: NSPoint(x: 28.61, y: 30), controlPoint1: NSPoint(x: 3.39, y: 30), controlPoint2: NSPoint(x: 28.61, y: 30))
scrubberShadowPath.curve(to: NSPoint(x: 32, y: 24), controlPoint1: NSPoint(x: 30.64, y: 28.78), controlPoint2: NSPoint(x: 32, y: 26.55))
scrubberShadowPath.line(to: NSPoint(x: 32, y: 6))
scrubberShadowPath.curve(to: NSPoint(x: 28.61, y: 0), controlPoint1: NSPoint(x: 32, y: 3.45), controlPoint2: NSPoint(x: 30.64, y: 1.22))
scrubberShadowPath.line(to: NSPoint(x: 3.39, y: 0))
scrubberShadowPath.curve(to: NSPoint(x: 2.31, y: 0.8), controlPoint1: NSPoint(x: 3.01, y: 0.23), controlPoint2: NSPoint(x: 2.64, y: 0.5))
scrubberShadowPath.curve(to: NSPoint(x: 0, y: 6), controlPoint1: NSPoint(x: 0.89, y: 2.08), controlPoint2: NSPoint(x: 0, y: 3.94))
scrubberShadowPath.line(to: NSPoint(x: 0, y: 24))
scrubberShadowPath.curve(to: NSPoint(x: 3.39, y: 30), controlPoint1: NSPoint(x: 0, y: 26.55), controlPoint2: NSPoint(x: 1.36, y: 28.78))
scrubberShadowPath.line(to: NSPoint(x: 3.39, y: 30))
scrubberShadowPath.close()
context.addPath(scrubberShadowPath.CGPath)
context.setFillColor(NSColor.black.cgColor)
context.fillPath()
context.restoreGState()
//// scrubberShape Drawing
let scrubberShapePath = NSBezierPath(roundedRect: NSRect(x: 1, y: 0, width: 30, height: 30), xRadius: 6, yRadius: 6)
context.addPath(scrubberShapePath.CGPath)
context.setFillColor(NSColor.white.cgColor)
context.fillPath()
context.restoreGState()
}
// Using an NSBezierPath for the background because CALayer cornerRadius draws slightly differently
// and it doesn't exactly match the stock control
fileprivate class TouchBarBackgroundView: NSView {
fileprivate override func draw(_ dirtyRect: NSRect) {
let backgroundColor = NSColor(deviceWhite: 54.0 / 255.0, alpha: 1.0)
let path = NSBezierPath(roundedRect: self.bounds, xRadius: 6, yRadius: 6)
backgroundColor.setFill()
path.fill()
}
}
}
| mit | cd9b44511886d585f1077b4630d62227 | 34.355641 | 278 | 0.612136 | 5.034304 | false | false | false | false |
YifengBai/YuDou | YuDou/YuDou/Classes/Live/Controller/LiveListViewController.swift | 1 | 2066 | //
// LiveListViewController.swift
// YuDou
//
// Created by Bemagine on 2017/2/8.
// Copyright © 2017年 bemagine. All rights reserved.
//
import UIKit
class LiveListViewController: BaseAnchorViewController {
fileprivate lazy var liveListVM : LiveListViewModel = LiveListViewModel()
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension LiveListViewController {
override func setupUI() {
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.headerReferenceSize = CGSize(width: 0, height: 0)
layout.sectionInset = UIEdgeInsetsMake(kItemMargin, kItemMargin, 0, kItemMargin)
collectionView.contentInset = UIEdgeInsetsMake(0, 0, kTabBarH, 0)
super.setupUI()
}
override func loadData() {
baseVM = liveListVM
liveListVM.loadLiveListData(tag_id: nil, finishedCallback: {
self.loadDataFinished()
self.collectionView.reloadData()
})
}
}
extension LiveListViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return liveListVM.listArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let item = liveListVM.listArray[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GameCellId, for: indexPath) as! GameCell
cell.roomModel = item
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
return UICollectionReusableView()
}
}
| mit | 7874eb73891f1825e8aae9350ff8a850 | 26.144737 | 171 | 0.654387 | 5.827684 | false | false | false | false |
belatrix/BelatrixEventsIOS | Hackatrix/Resources/Constants.swift | 1 | 1183 | //
// Constants.swift
// Hackatrix
//
// Created by Erik Fernando Flores Quispe on 16/05/17.
// Copyright © 2017 Belatrix. All rights reserved.
//
import Foundation
struct K {
struct url {
static let belatrix = "http://belatrixsf.com"
}
struct email {
static let contact = "[email protected]"
}
struct segue {
static let settings = "settingsSegue"
static let news = "newsSegue"
static let about = "aboutSegue"
static let detail = "detailSegue"
static let map = "mapSegue"
static let citySetting = "citySettingSegue"
static let selectCity = "selectCitySegue"
}
struct cell {
static let menu = "itemMenuCell"
static let event = "eventCell"
static let setting = "settingCell"
static let news = "newsCell"
static let contributor = "contributorCell"
static let interaction = "interactionCell"
static let location = "locationCell"
}
struct key {
static let showedWelcomeAlertInteraction = "isShowedWelcomeAlertInteraction"
static let interactionForAProject = "isInteractionForAProject"
}
}
| apache-2.0 | cd6728fb6097da17a56a061324bd5c00 | 28.55 | 84 | 0.641286 | 4.236559 | false | false | false | false |
Johnykutty/SwiftLint | Source/SwiftLintFramework/Rules/ObjectLiteralRule.swift | 2 | 4469 | //
// ObjectLiteralRule.swift
// SwiftLint
//
// Created by Marcelo Fabri on 12/25/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ObjectLiteralRule: ASTRule, ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "object_literal",
name: "Object Literal",
description: "Prefer object literals over image and color inits.",
nonTriggeringExamples: [
"let image = #imageLiteral(resourceName: \"image.jpg\")",
"let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)",
"let image = UIImage(named: aVariable)",
"let image = UIImage(named: \"interpolated \\(variable)\")",
"let color = UIColor(red: value, green: value, blue: value, alpha: 1)",
"let image = NSImage(named: aVariable)",
"let image = NSImage(named: \"interpolated \\(variable)\")",
"let color = NSColor(red: value, green: value, blue: value, alpha: 1)"
],
triggeringExamples: ["", ".init"].flatMap { (method: String) -> [String] in
["UI", "NS"].flatMap { (prefix: String) -> [String] in
[
"let image = ↓\(prefix)Image\(method)(named: \"foo\")",
"let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)",
"let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)",
"let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)"
]
}
}
)
public func validate(file: File, kind: SwiftExpressionKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard kind == .call,
let offset = dictionary.offset,
isImageNamedInit(dictionary: dictionary, file: file) ||
isColorInit(dictionary: dictionary, file: file) else {
return []
}
return [
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset))
]
}
private func isImageNamedInit(dictionary: [String: SourceKitRepresentable], file: File) -> Bool {
guard let name = dictionary.name,
inits(forClasses: ["UIImage", "NSImage"]).contains(name),
case let arguments = dictionary.enclosedArguments,
arguments.flatMap({ $0.name }) == ["named"],
let argument = arguments.first,
case let kinds = kinds(forArgument: argument, file: file),
kinds == [.string] else {
return false
}
return true
}
private func isColorInit(dictionary: [String: SourceKitRepresentable], file: File) -> Bool {
guard let name = dictionary.name,
inits(forClasses: ["UIColor", "NSColor"]).contains(name),
case let arguments = dictionary.enclosedArguments,
case let argumentsNames = arguments.flatMap({ $0.name }),
argumentsNames == ["red", "green", "blue", "alpha"] || argumentsNames == ["white", "alpha"],
validateColorKinds(arguments: arguments, file: file) else {
return false
}
return true
}
private func inits(forClasses names: [String]) -> [String] {
return names.flatMap { name in
[
name,
name + ".init"
]
}
}
private func validateColorKinds(arguments: [[String: SourceKitRepresentable]], file: File) -> Bool {
for dictionary in arguments where kinds(forArgument: dictionary, file: file) != [.number] {
return false
}
return true
}
private func kinds(forArgument argument: [String: SourceKitRepresentable], file: File) -> Set<SyntaxKind> {
guard let offset = argument.bodyOffset, let length = argument.bodyLength else {
return []
}
let range = NSRange(location: offset, length: length)
return Set(file.syntaxMap.tokens(inByteRange: range).flatMap({ SyntaxKind(rawValue: $0.type) }))
}
}
| mit | caaa0120f3324a3d2fcc93b4949f3e67 | 38.821429 | 115 | 0.574439 | 4.655532 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Example-OSX/Common/Extensions/UIEdgeInsetsExtensions.swift | 1 | 613 | import Cocoa
extension NSEdgeInsets {
init?(top: String?,
left: String?,
bottom: String?,
right: String?) {
guard let topSectionInset = CGFloat(top),
let leftSectionInset = CGFloat(left),
let bottomSectionInset = CGFloat(bottom),
let rightSectionInset = CGFloat(right) else {
return nil
}
self = NSEdgeInsets(top: topSectionInset,
left: leftSectionInset,
bottom: bottomSectionInset,
right: rightSectionInset)
}
}
| mit | 9ade4170471a5a05670853a2c0e79cd9 | 29.65 | 57 | 0.522023 | 5.728972 | false | false | false | false |
huonw/swift | stdlib/public/SDK/HomeKit/HomeKit.swift | 45 | 740 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import HomeKit
import Foundation
@available(iOS 8.0, watchOS 2.0, tvOS 10.0, *)
public let HMCharacteristicPropertySupportsEventNotification = Notification.Name.HMCharacteristicPropertySupportsEvent.rawValue
| apache-2.0 | 5e7e76a81c4bd8dadeee7c101286af42 | 42.529412 | 127 | 0.610811 | 5.174825 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Views/MXCalendarView/Cells/MXInactiveDayCell.swift | 1 | 1432 | //
// Created by Maxim Pervushin on 13/01/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
class MXInactiveDayCell: UICollectionViewCell, MXReusableView {
@IBOutlet weak var dateLabel: UILabel!
var date: NSDate? {
didSet {
updateUI()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
updateAppearance()
}
private var _defaultBackgroundColor: UIColor?
private var _defaultTextColor: UIColor?
private func updateUI() {
if let date = date {
dateLabel.text = "\(date.day())"
} else {
dateLabel.text = ""
}
updateAppearance()
}
private func updateAppearance() {
backgroundColor = _defaultBackgroundColor
dateLabel?.textColor = _defaultTextColor
}
}
extension MXInactiveDayCell {
// MARK: - UIAppearance
dynamic var defaultTextColor: UIColor? {
// UI_APPEARANCE_SELECTOR
get {
return _defaultTextColor
}
set {
_defaultTextColor = newValue
updateAppearance()
}
}
dynamic var defaultBackgroundColor: UIColor? {
// UI_APPEARANCE_SELECTOR
get {
return _defaultBackgroundColor
}
set {
_defaultBackgroundColor = newValue
updateAppearance()
}
}
} | mit | 8bcdb8d576c931391486d2e43bd26dd6 | 20.712121 | 63 | 0.578212 | 5.32342 | false | false | false | false |
jumbo-in-Jap/goodHome | goodHome/AccessoriesTableViewController.swift | 1 | 2944 | //
// AccessoriesTableViewController.swift
// goodHome
//
// Created by 羽田 健太郎 on 2014/09/21.
// Copyright (c) 2014年 me.jumbeeee.ken. All rights reserved.
//
import UIKit
class AccessoriesTableViewController: UITableViewController,HMAccessoryBrowserDelegate {
var accessoryBrowser:HMAccessoryBrowser = HMAccessoryBrowser()
var accessories = [HMAccessory]()
override func viewDidLoad() {
super.viewDidLoad()
self.accessoryBrowser.delegate = self;
self.accessoryBrowser.startSearchingForNewAccessories()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.accessories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = self.accessories[0].name
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO 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
}
}
*/
// - accessory browser delegate
func accessoryBrowser(browser: HMAccessoryBrowser!, didFindNewAccessory accessory: HMAccessory!)
{
/*
NSLog("%@", accessory.identifier)
NSLog("%@", accessory.reachable)
NSLog("%@", accessory.bridged)
NSLog("%@", accessory.blocked)
NSLog("%@", accessory.identifier)
NSLog("%@", accessory.services)
*/
if !contains(self.accessories, accessory)
{
self.accessories.append(accessory)
NSLog("Add Accessory %@", accessory.name)
}
self.tableView.reloadData()
}
func accessoryBrowser(browser: HMAccessoryBrowser!, didRemoveNewAccessory accessory: HMAccessory!)
{
}
}
| apache-2.0 | 44c0d9d91a51d098d88c59873ecf132e | 32.318182 | 159 | 0.667121 | 5.449814 | false | false | false | false |
50WDLARP/app | SonicIOS_class_demo_orig/SonicIOS/Controllers/DisconnectedViewController.swift | 2 | 4631 | //
// DisconnectedViewController.swift
// Cool Beans
//
// Created by Kyle on 11/14/14.
// Copyright (c) 2014 Kyle Weiner. All rights reserved.
//
import UIKit
class DisconnectedViewController: UIViewController, PTDBeanManagerDelegate, UITableViewDelegate, UITableViewDataSource {
let connectedViewControllerSegueIdentifier = "ViewConnection"
var beanArray : [PTDBean] = [PTDBean]()
var manager: PTDBeanManager!
var connectedBean: PTDBean? {
didSet {
if connectedBean == nil {
beanManagerDidUpdateState(manager)
} else {
performSegueWithIdentifier(connectedViewControllerSegueIdentifier, sender: self)
}
}
}
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var beanTableView: UITableView!
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
manager = PTDBeanManager(delegate: self)
}
// MARK: Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == connectedViewControllerSegueIdentifier {
let vc = segue.destinationViewController as! ConnectedViewController
vc.connectedBean = connectedBean
vc.connectedBean?.delegate = vc
}
}
// MARK: PTDBeanManagerDelegate
func beanManagerDidUpdateState(beanManager: PTDBeanManager!) {
switch beanManager.state {
case .Unsupported:
let alertController = UIAlertController(title: "Error", message: "This device is unsupported", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
case .PoweredOff:
let alertController = UIAlertController(title: "Error", message: "Please turn on Bluetooth", preferredStyle: .Alert)
let defaultAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alertController.addAction(defaultAction)
presentViewController(alertController, animated: true, completion: nil)
case .PoweredOn:
beanManager.startScanningForBeans_error(nil);
default:
break
}
}
func beanManager(beanManager: PTDBeanManager!, didDiscoverBean bean: PTDBean!, error: NSError!) {
print("DISCOVERED BEAN \nName: \(bean.name), UUID: \(bean.identifier) RSSI: \(bean.RSSI)")
if connectedBean == nil {
if bean.state == .Discovered {
//manager.connectToBean(bean, error: nil)
beanArray.append(bean)
beanTableView.reloadData()
}
}
}
func BeanManager(beanManager: PTDBeanManager!, didConnectToBean bean: PTDBean!, error: NSError!) {
print("CONNECTED BEAN \nName: \(bean.name), UUID: \(bean.identifier) RSSI: \(bean.RSSI)")
if connectedBean == nil {
connectedBean = bean
}
}
func beanManager(beanManager: PTDBeanManager!, didDisconnectBean bean: PTDBean!, error: NSError!) {
print("DISCONNECTED BEAN \nName: \(bean.name), UUID: \(bean.identifier) RSSI: \(bean.RSSI)")
// Dismiss any modal view controllers.
presentedViewController?.dismissViewControllerAnimated(true, completion: {
self.dismissViewControllerAnimated(true, completion: nil)
})
self.connectedBean = nil
}
// MARK: table functions
func numberOfRowsInTableView(aTableView: UITableView) -> Int
{
let numberOfRows:Int = beanArray.count
return numberOfRows
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return beanArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier( "aCell", forIndexPath: indexPath)
cell.textLabel!.text = self.beanArray[indexPath.row].name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("selected row: " + String(indexPath.row))
manager.connectToBean(self.beanArray[indexPath.row], error: nil)
activityIndicator.startAnimating()
}
}
| mit | a04b790276c15e37a740b7fe39459cad | 35.753968 | 134 | 0.639387 | 5.403734 | false | false | false | false |
alloyapple/GooseGtk | Sources/TreeViewExample/TreeViewExampleViewController.swift | 1 | 2367 | //
// Created by color on 12/11/17.
//
import Foundation
import GooseGtk
import Goose
class TreeViewExampleViewController: GTKViewController {
private lazy var filterEntry: GTKEntry = GTKEntry()
public func viewDidLoad() {
// filterEntry.text = GTKClipboard.default.text
// let filterLabel = GTKLabel("Search")
// let downloadButonn = GTKButton(label: "Download")
// downloadButonn.click = self.downloadFile
//
// let filterBox = GTKBox(orientation: .HORIZONTAL, spacing: 10)
// filterBox.packStart(subView: filterLabel, expand: false, fill: false, padding: 5)
// filterBox.packStart(subView: filterEntry, expand: true, fill: true, padding: 5)
// filterBox.packStart(subView: downloadButonn, expand: false, fill: false, padding: 5)
//
//
// let box = GTKBox(orientation: .VERTICAL, spacing: 0)
// box.packStart(subView: filterBox, expand: false, fill: false, padding: 5)
//
// let listModel = GTKListStore(colTypes: [.GINT, .GSTRING])
//
// var index: Int32 = 1
//
// let data: [(Int32, String)] = [(1, "tom"), (2, "jim"), (3, "kk"), (4, "tom")]
//
// listModel.reload(count: data.count) { (iter, i) in
// let v = data[i]
// listModel.set(iter: iter, column: 0, value: v.0)
// listModel.set(iter: iter, column: 1, value: v.1)
// }
//
// let treeView = GTKTreeView(model: listModel)
// treeView.insertColumnWithAttributes(position: 0, title: "name", cellRender: cellRendererText(), attributeName: "text")
// treeView.insertColumnWithAttributes(position: 1, title: "age", cellRender: cellRendererText(), attributeName: "text")
// treeView.columnsAutosize()
// treeView.headersClickable = true
//
// box.packStart(subView: treeView, expand: true, fill: true, padding: 5)
//
// self.view.addSubView(box)
}
func downloadFile(_ btn: GTKButton) {
// let queue = DispatchQueue(label: "download")
// queue.async {
// let r = Request.get(url: "https://github.com/CodaFi/swift-evolution/blob/3571229e07a03d8e3a037224267fe6525ff33ed1/proposals/NNNN-lolcode-literals.md")
// let response = r.perform()
// appRunQuque.sync{
// self.filterEntry.text = response.text
// }
//
// }
}
} | apache-2.0 | 6c58b7e7443efa3e740552a140b975d2 | 34.343284 | 164 | 0.619772 | 3.511869 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsServices/Email/Switch/EmailSwitchViewInteractor.swift | 1 | 2055 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import ComposableArchitectureExtensions
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
class EmailSwitchViewInteractor: SwitchViewInteracting {
typealias InteractionState = LoadingState<SwitchInteractionAsset>
var state: Observable<InteractionState> {
stateRelay.asObservable()
}
var switchTriggerRelay = PublishRelay<Bool>()
private let service: EmailNotificationSettingsServiceAPI
private let stateRelay = BehaviorRelay<InteractionState>(value: .loading)
private let disposeBag = DisposeBag()
init(service: EmailNotificationSettingsServiceAPI) {
self.service = service
service
.valueObservable
.map { ValueCalculationState.value($0) }
.map { .init(with: $0) }
.catchAndReturn(.loading)
.startWith(.loading)
.bindAndCatch(to: stateRelay)
.disposed(by: disposeBag)
switchTriggerRelay
.do(onNext: { [weak self] _ in
self?.stateRelay.accept(.loading)
})
.flatMap(weak: self) { (self, result) -> Observable<Void> in
self.service
.emailNotifications(enabled: result)
.andThen(Observable.just(()))
}
.subscribe()
.disposed(by: disposeBag)
}
}
extension LoadingState where Content == SwitchInteractionAsset {
/// Initializer that receives the interaction state and
/// maps it to `self`
fileprivate init(with state: ValueCalculationState<WalletSettings>) {
switch state {
case .calculating,
.invalid:
self = .loading
case .value(let value):
let emailVerified = value.isEmailVerified
let emailNotifications = value.isEmailNotificationsEnabled
self = .loaded(next: .init(isOn: emailNotifications, isEnabled: emailVerified))
}
}
}
| lgpl-3.0 | 3090f7dc073f100624bb17b7cd994886 | 30.121212 | 91 | 0.636806 | 5.293814 | false | false | false | false |
blue42u/swift-t | stc/tests/925-liftwait-1.swift | 4 | 585 |
import assert;
main {
int A[] = f(g(1), g(2));
assertEqual(A[1], 1, "A[1]");
assertEqual(A[2], 4, "A[2]");
int B[] = f(g(3), g(4));
assertEqual(B[3], 9, "B[1]");
assertEqual(B[4], 16, "B[2]");
trace(A[1], A[2], B[3], B[4]);
}
(int r) g (int x) {
r = x;
}
(int A[]) f (int a, int b) {
wait (a) {
wait (a, b) {
foreach i in [a:b] {
A[i] = i*i;
}
}
}
}
@sync
(int A[]) f2 (int a, int b) {
wait (a) {
wait (a, b) {
foreach i in [a:b] {
A[i] = i*i;
}
}
}
}
| apache-2.0 | e7d0450a6ece1a86a58096c97d7023d7 | 14.810811 | 34 | 0.355556 | 2.276265 | false | false | false | false |
gouyz/GYZBaking | baking/Classes/Home/Controller/GYZHomeVC.swift | 1 | 14360 | //
// GYZHomeVC.swift
// baking
// 首页
// Created by gouyz on 2017/3/23.
// Copyright © 2017年 gouyz. All rights reserved.
//
import UIKit
import MBProgressHUD
private let homeMenuCell = "homeMenuCell"
private let homeCell = "homeCell"
class GYZHomeVC: GYZBaseVC,UITableViewDelegate,UITableViewDataSource,HomeMenuCellDelegate,HomeCellDelegate,GYZHomeHeaderViewDelegate,GYZRedPacketListViewDelegate {
var address: String = ""
var homeModel: GYZHomeModel?
var redPacketmodels: [GYZRedPacketInfoModel] = [GYZRedPacketInfoModel]()
/// 轮播图片URL
var adsImgArr: [String] = []
/// 轮播连接
var adsLinkArr: [String] = []
///定位
var locationManager: AMapLocationManager = AMapLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.titleView = locationView
locationView.addOnClickListener(target: self, action: #selector(changeAddress))
view.addSubview(tableView)
tableView.snp.makeConstraints { (make) in
make.edges.equalTo(0)
}
tableView.tableHeaderView = headerView
headerView.delegate = self
configLocationManager()
/// 消息推送通知
NotificationCenter.default.addObserver(self, selector: #selector(refreshView(noti:)), name: NSNotification.Name(rawValue: kMessagePush), object: nil)
requestVersion()
requestHomeData()
requestRedPacketData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
NotificationCenter.default.removeObserver(self)
}
/// 显示红包列表
func showRedPacketView(){
let redPacketView = GYZRedPacketListView()
redPacketView.delegate = self
redPacketView.dataModel = redPacketmodels
redPacketView.show()
}
/// 切换地址
func changeAddress(){
configLocationManager()
}
/// 定位配置
func configLocationManager(){
// 带逆地理信息的一次定位(返回坐标和地址信息)
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// 定位超时时间,最低2s,此处设置为10s
locationManager.locationTimeout = 10
// 逆地理请求超时时间,最低2s,此处设置为10s
locationManager.reGeocodeTimeout = 10
locationManager.requestLocation(withReGeocode: true) { [weak self](location: CLLocation?, reGeocode: AMapLocationReGeocode?, error: Error?) in
if error == nil{
if reGeocode != nil{
// print((regeocode?.aoiName)!)
//
// print((regeocode?.street)! + (regeocode?.number)!)
let street: String = reGeocode?.street ?? ""
let number: String = reGeocode?.number ?? ""
if reGeocode?.aoiName != nil{
self?.address = (reGeocode?.aoiName)!
}else{
self?.address = street + number
}
if self?.address.characters.count == 0 {//未定位成功
self?.address = "南京市"
userDefaults.set("", forKey: "currlongitude")//经度
userDefaults.set("", forKey: "currlatitude")//纬度
}else{
userDefaults.set(location?.coordinate.longitude, forKey: "currlongitude")//经度
userDefaults.set(location?.coordinate.latitude, forKey: "currlatitude")//纬度
}
self?.setLocationText()
}
}else{
MBProgressHUD.showAutoDismissHUD(message: "定位失败,请重新定位")
}
}
}
/// 设置定位信息
func setLocationText(){
// 计算文字尺寸
let size = address.size(attributes: [NSFontAttributeName: locationView.addressLab.font])
var width = kScreenWidth * 0.5
if width > size.width {
width = size.width + kMargin
}
locationView.addressLab.text = address
locationView.addressLab.snp.updateConstraints { (make) in
make.width.equalTo(width)
}
}
/// 自定义头部定位
fileprivate var locationView: GYZHomeTabbarView = GYZHomeTabbarView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kTitleHeight))
/// tableview 头部
fileprivate var headerView : GYZHomeHeaderView = GYZHomeHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 210))
/// 懒加载UITableView
fileprivate lazy var tableView : UITableView = {
let table = UITableView(frame: CGRect.zero, style: .grouped)
table.dataSource = self
table.delegate = self
table.tableFooterView = UIView()
table.separatorStyle = .none
table.register(GYZHomeCell.self, forCellReuseIdentifier: homeCell)
table.register(GYZHomeMenuCell.self, forCellReuseIdentifier: homeMenuCell)
return table
}()
///获取首页数据
func requestHomeData(){
weak var weakSelf = self
createHUD(message: "加载中...")
GYZNetWork.requestNetwork("Index/index", success: { (response) in
weakSelf?.hud?.hide(animated: true)
// GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let info = data["info"].dictionaryObject else { return }
weakSelf?.homeModel = GYZHomeModel.init(dict: info)
weakSelf?.setAdsData()
weakSelf?.tableView.reloadData()
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
weakSelf?.hud?.hide(animated: true)
GYZLog(error)
})
}
///获取红包列表数据
func requestRedPacketData(){
weak var weakSelf = self
GYZNetWork.requestNetwork("Index/indexCoupon", parameters :["user_id":"29866"/*userDefaults.string(forKey: "userId") ?? ""*/], success: { (response) in
GYZLog(response)
if response["status"].intValue == kQuestSuccessTag{//请求成功
let data = response["result"]
guard let info = data["info"].array else { return }
for item in info{
guard let itemInfo = item.dictionaryObject else { return }
let model = GYZRedPacketInfoModel.init(dict: itemInfo)
weakSelf?.redPacketmodels.append(model)
}
if weakSelf?.redPacketmodels.count > 0{
weakSelf?.showRedPacketView()
}
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
GYZLog(error)
})
}
/// 设置轮播数据
func setAdsData(){
for item in (homeModel?.ad)! {
adsImgArr.append(item.ad_img!)
adsLinkArr.append(item.link!)
}
headerView.bannerView?.imagePaths = adsImgArr
}
// MARK: - UITableViewDataSource
func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: homeMenuCell) as! GYZHomeMenuCell
cell.delegate = self
cell.selectionStyle = .none
return cell
}else {
let cell = tableView.dequeueReusableCell(withIdentifier: homeCell) as! GYZHomeCell
cell.delegate = self
cell.dataModel = homeModel
cell.selectionStyle = .none
return cell
}
}
///MARK : UITableViewDelegate
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 160
}
return 140
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0.0001
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return kMargin
}
///MARK : HomeMenuCellDelegate
///处理点击事件
func didSelectMenuIndex(index: Int) {
switch index {
case 0:// 同城配送
//如果登录
if checkIsLogin(){
goSendVC(type: .send)
}
case 1://购物商城
goWait()
case 2:// 配方教学
goWebVC(type: "2")
case 3:// 成/半成品
goWait()
case 4://积分商城
goWait()
case 5:// 求职招聘
goWebVC(type: "1")
case 6:// 烘焙集市
goWait()
case 7://联系我们
navigationController?.pushViewController(GYZContractUsVC(), animated: true)
default:
return
}
}
func goWait(){
MBProgressHUD.showAutoDismissHUD(message: "敬请期待...")
}
/// 1求职招聘 2配方教学
func goWebVC(type:String){
let webVC = GYZWebViewVC()
webVC.url = "http://hp.0519app.com/Home/Article/articleList?type=" + type
navigationController?.pushViewController(webVC, animated: true)
}
// 同城配送
func goSendVC(type: SourceViewType){
let sendVC = GYZSendVC()
sendVC.sourceType = type
navigationController?.pushViewController(sendVC, animated: true)
}
// 商品列表
func goGoodsVC(type: String){
let goodsVC = GYZCategoryDetailsVC()
goodsVC.type = type
navigationController?.pushViewController(goodsVC, animated: true)
}
///MARK : HomeCellDelegate
///处理点击事件
func didSelectIndex(index: Int) {
//如果登录
if checkIsLogin(){
switch index {
case 1:// 热门市场 变为通货市场
// goSendVC(type: .hot)
goGoodsVC(type: "1")
case 2://新店推荐 变为商家立减
// goSendVC(type: .recommend)
goGoodsVC(type: "2")
case 3:// 今日好店
goSendVC(type: .good)
default:
return
}
}
}
///MARK GYZHomeHeaderViewDelegate
func didClickedBannerView(index: Int) {
// let webVC = GYZWebViewVC()
// webVC.url = adsLinkArr[index]
// navigationController?.pushViewController(webVC, animated: true)
}
///MARK: GYZRedPacketListViewDelegate
func didClickedMyRedPacket() {
let redPacketVC = GYZMyRedPacketVC()
navigationController?.pushViewController(redPacketVC, animated: true)
}
/// 搜索商品
func didSearchView() {
let searchVC = GYZSearchShopVC()
let navVC = GYZBaseNavigationVC(rootViewController : searchVC)
self.present(navVC, animated: false, completion: nil)
}
///消息通知跳转消息列表
func refreshView(noti: NSNotification){
navigationController?.pushViewController(GYZMineMessageVC(), animated: true)
}
/// 获取App Store版本信息
func requestVersion(){
weak var weakSelf = self
GYZNetWork.requestVersionNetwork("http://itunes.apple.com/cn/lookup?id=\(APPID)", success: { (response) in
// GYZLog(response)
if response["resultCount"].intValue == 1{//请求成功
let data = response["results"].arrayValue
var version: String = GYZUpdateVersionTool.getCurrVersion()
var content: String = ""
if data.count > 0{
version = data[0]["version"].stringValue//版本号
content = data[0]["releaseNotes"].stringValue//更新内容
}
weakSelf?.checkVersion(newVersion: version, content: content)
}else{
MBProgressHUD.showAutoDismissHUD(message: response["result"]["msg"].stringValue)
}
}, failture: { (error) in
GYZLog(error)
})
}
/// 检测APP更新
func checkVersion(newVersion: String,content: String){
let type: UpdateVersionType = GYZUpdateVersionTool.compareVersion(newVersion: newVersion)
switch type {
case .noUpdate:
break
default:
updateVersion(version: newVersion, content: content)
break
}
}
/**
* //不强制更新
* @param version 版本名称
* @param content 更新内容
*/
func updateVersion(version: String,content: String){
GYZAlertViewTools.alertViewTools.showAlert(title:"发现新版本\(version)", message: content, cancleTitle: "残忍拒绝", viewController: self, buttonTitles: "立即更新", alertActionBlock: { (index) in
if index == 0{//立即更新
GYZUpdateVersionTool.goAppStore()
}
})
}
}
| mit | 0983e5c5c7dcf5ab37fe3fdac96a2520 | 32.009639 | 189 | 0.550478 | 5.092565 | false | false | false | false |
chungng/workoutbuddy | Workout Buddy/AppDelegate.swift | 1 | 6055 | //
// AppDelegate.swift
// Workout Buddy
//
// Created by Chung Ng on 12/12/14.
// Copyright (c) 2014 Chung Ng. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// 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 "Noteworthy-Grace.Workout_Buddy_Template" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("WorkoutData", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("WorkoutData.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| mit | 7f0245eec275b72579177f9d6a65f33f | 54.550459 | 290 | 0.711974 | 5.799808 | false | false | false | false |
abertelrud/swift-package-manager | Sources/Commands/Snippets/Cards/TopCard.swift | 2 | 4727 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreCommands
import Foundation
import PackageModel
import PackageGraph
/// The top menu card for a package's help contents, including snippets.
struct TopCard: Card {
/// The root package that hosts the snippets.
let package: ResolvedPackage
/// The top-level snippet groups residing in the `Snippets` subdirectory.
let snippetGroups: [SnippetGroup]
/// The tool used for eventually building and running a chosen snippet.
let swiftTool: SwiftTool
init(package: ResolvedPackage, snippetGroups: [SnippetGroup], swiftTool: SwiftTool) {
self.package = package
self.snippetGroups = snippetGroups
self.swiftTool = swiftTool
}
var inputPrompt: String? {
return """
Choose a group by name or number.
To exit, enter 'q'.
"""
}
func renderProducts() -> String {
let libraries = package.products
.filter {
guard case .library = $0.type else {
return false
}
return true
}
.sorted { $0.name < $1.name }
.map { "- \($0.name) (library)" }
let executables = package.products
.filter { $0.type == .executable }
.sorted { $0.name < $1.name }
.map { "- \($0.name) (executable)" }
guard !(libraries.isEmpty && executables.isEmpty) else {
return ""
}
var rendered = brightCyan {
"\n## Products"
"\n\n"
}.terminalString()
rendered += (libraries + executables).joined(separator: "\n")
return rendered
}
func renderSnippets() -> String {
guard !snippetGroups.isEmpty else {
return ""
}
let snippetPreviews = snippetGroups.enumerated().map { pair -> String in
let (number, snippetGroup) = pair
let snippetNoun = snippetGroup.snippets.count > 1 ? "snippets" : "snippet"
let heading = "\(number). \(snippetGroup.name) (\(snippetGroup.snippets.count) \(snippetNoun))"
return colorized {
cyan {
heading
"\n"
}
if !snippetGroup.explanation.isEmpty {
"""
\(snippetGroup.explanation.spm_multilineIndent(count: 3))
"""
}
}.terminalString()
}
return colorized {
brightCyan {
"\n## Snippets"
}
"\n\n"
snippetPreviews.joined(separator: "\n\n")
"\n"
}.terminalString()
}
func render() -> String {
let heading = brightYellow {
"# "
package.identity.description
}
return """
\(heading)
\(renderProducts())
\(renderSnippets())
"""
}
func acceptLineInput<S>(_ line: S) -> CardEvent? where S : StringProtocol {
guard !line.isEmpty else {
print("\u{0007}")
return nil
}
if line.prefix(while: { !$0.isWhitespace }).lowercased() == "q" {
return .quit()
}
if let index = Int(line),
snippetGroups.indices.contains(index) {
return .push(SnippetGroupCard(snippetGroup: snippetGroups[index], swiftTool: swiftTool))
} else if let groupByName = snippetGroups.first(where: { $0.name == line }) {
return .push(SnippetGroupCard(snippetGroup: groupByName, swiftTool: swiftTool))
} else {
print(red { "There is not a group by that name or index." })
return nil
}
}
}
fileprivate extension Target.Kind {
var pluralDescription: String {
switch self {
case .executable:
return "executables"
case .library:
return "libraries"
case .systemModule:
return "system modules"
case .test:
return "tests"
case .binary:
return "binaries"
case .plugin:
return "plugins"
case .snippet:
return "snippets"
}
}
}
| apache-2.0 | 1e6b6f40cc5f193322435a8d0fa53ca1 | 29.694805 | 107 | 0.520203 | 4.965336 | false | false | false | false |
steryokhin/AsciiArtPlayer | src/AsciiArtPlayer/AsciiArtPlayer/Classes/Core/Services/3rd Party/ThirdPartyManager.swift | 1 | 769 | //
// ThirdPartyManager.swift
// AsciiArtPlayer
//
// Created by Sergey Teryokhin on 20/12/2016.
// Copyright © 2016 iMacDev. All rights reserved.
//
import Foundation
import Watchdog
import QorumLogs
class ThirdPartyManager : ThirdPartyManagerProtocol {
func configure() {
self.setupWatchdog()
self.setupLogging()
}
var watchdog: Watchdog?
func setupWatchdog() {
self.watchdog = Watchdog(threshold: 0.5, strictMode: false)
}
func setupLogging() {
#if DEBUG
//TODO: 1 and 3 ==> make constants
QorumLogs.minimumLogLevelShown = 1
#else
QorumLogs.minimumLogLevelShown = 3
#endif
QorumLogs.enabled = true
QorumLogs.test()
}
}
| mit | 728ba0fa5dea33222c6951543f580da5 | 20.333333 | 67 | 0.617188 | 4.439306 | false | false | false | false |
apple/swift | stdlib/public/Distributed/DistributedMetadata.swift | 5 | 4258 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020-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 Swift
/// Get the parameter count from a mangled method name.
///
/// - Returns: May return a negative number to signal a decoding error.
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getParameterCount(mangledMethodName name: String) -> Int32 {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getParameterCount(
nameUTF8.baseAddress!, UInt(nameUTF8.endIndex))
}
}
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getParameterCount")
public // SPI Distributed
func __getParameterCount(
_ typeNameStart: UnsafePointer<UInt8>,
_ typeNameLength: UInt
) -> Int32
/// Write the Metadata of all the mangled methods name's
/// parameters into the provided buffer.
///
/// - Returns: the actual number of types written,
/// or negative value to signify an error
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getParameterTypeInfo(
mangledMethodName name: String,
genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
genericArguments: UnsafeRawPointer?,
into typesBuffer: Builtin.RawPointer, length typesLength: Int
) -> Int32 {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getParameterTypeInfo(
nameUTF8.baseAddress!, UInt(nameUTF8.endIndex),
genericEnv, genericArguments, typesBuffer, typesLength)
}
}
/// - Returns: the actual number of types written,
/// or a negative value to signal decoding error.
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getParameterTypeInfo")
public // SPI Distributed
func __getParameterTypeInfo(
_ typeNameStart: UnsafePointer<UInt8>, _ typeNameLength: UInt,
_ genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
_ genericArguments: UnsafeRawPointer?,
_ types: Builtin.RawPointer, _ typesLength: Int
) -> Int32
@available(SwiftStdlib 5.7, *)
public // SPI Distributed
func _getReturnTypeInfo(
mangledMethodName name: String,
genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
genericArguments: UnsafeRawPointer?
) -> Any.Type? {
let nameUTF8 = Array(name.utf8)
return nameUTF8.withUnsafeBufferPointer { nameUTF8 in
return __getReturnTypeInfo(nameUTF8.baseAddress!, UInt(nameUTF8.endIndex),
genericEnv, genericArguments)
}
}
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_func_getReturnTypeInfo")
public // SPI Distributed
func __getReturnTypeInfo(
_ typeNameStart: UnsafePointer<UInt8>,
_ typeNameLength: UInt,
_ genericEnv: UnsafeRawPointer?, // GenericEnvironmentDescriptor *
_ genericArguments: UnsafeRawPointer?
) -> Any.Type?
/// Retrieve a generic environment descriptor associated with
/// the given distributed target
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_getGenericEnvironment")
public // SPI Distributed
func _getGenericEnvironmentOfDistributedTarget(
_ targetNameStart: UnsafePointer<UInt8>,
_ targetNameLength: UInt
) -> UnsafeRawPointer?
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_getWitnessTables")
public // SPI Distributed
func _getWitnessTablesFor(
environment: UnsafeRawPointer,
genericArguments: UnsafeRawPointer
) -> (UnsafeRawPointer, Int)
@available(SwiftStdlib 5.7, *)
@_silgen_name("swift_distributed_makeDistributedTargetAccessorNotFoundError")
internal // SPI Distributed
func _makeDistributedTargetAccessorNotFoundError() -> Error {
/// We don't include the name of the target in case the input was compromised.
return ExecuteDistributedTargetError(
message: "Failed to locate distributed function accessor",
errorCode: .targetAccessorNotFound)
}
| apache-2.0 | 7988d971e5d54303aec8e1fe8ca1a890 | 34.483333 | 80 | 0.716299 | 4.638344 | false | false | false | false |
byu-oit/ios-byuSuite | byuSuite/Classes/Reusable/Clients/UApi/Students/StudentClient.swift | 1 | 887 | //
// StudentClient.swift
// byuSuite
//
// Created by Erik Brady on 2/5/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
private let BASE_URL = "https://api.byu.edu/byuapi/students/v1"
class StudentClient: ByuClient2 {
static func getStudentClasses(byuId: String, callback: @escaping ([UApiStudentScheduledClass]?, ByuError?) -> Void) {
let request = ByuRequest2(url: super.url(base: BASE_URL, pathParams: [byuId, "enrolled_classes"]))
makeRequest(request) { (response) in
if let data = response.getDataJson() as? [String: Any], let classData = data["values"] as? [[String: Any]] {
var enrolledClasses = [UApiStudentScheduledClass]()
for tempDict in classData {
enrolledClasses.append(UApiStudentScheduledClass(dict: tempDict))
}
callback(enrolledClasses, nil)
} else {
callback(nil, response.error)
}
}
}
}
| apache-2.0 | 688944709937aea3a1181e82ef5d33c4 | 30.642857 | 118 | 0.697517 | 3.356061 | false | false | false | false |
vector-im/vector-ios | Riot/Managers/URLPreviews/Core Data/URLPreviewDataMO.swift | 1 | 1627 | //
// Copyright 2021 New Vector Ltd
//
// 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 CoreData
extension URLPreviewDataMO {
convenience init(context: NSManagedObjectContext, preview: URLPreviewData, creationDate: Date) {
self.init(context: context)
update(from: preview, on: creationDate)
}
func update(from preview: URLPreviewData, on date: Date) {
url = preview.url
siteName = preview.siteName
title = preview.title
text = preview.text
image = preview.image
creationDate = date
}
func preview(for event: MXEvent) -> URLPreviewData? {
guard let url = url else { return nil }
let viewData = URLPreviewData(url: url,
eventID: event.eventId,
roomID: event.roomId,
siteName: siteName,
title: title,
text: text)
viewData.image = image as? UIImage
return viewData
}
}
| apache-2.0 | 8d64d93d6f709d26df62671f6e97a00f | 32.895833 | 100 | 0.595575 | 5.068536 | false | false | false | false |
krzysztofzablocki/Sourcery | SourceryRuntime/Sources/AST/TypeName/Array.swift | 1 | 1874 | import Foundation
/// Describes array type
@objcMembers public final class ArrayType: NSObject, SourceryModel {
/// Type name used in declaration
public var name: String
/// Array element type name
public var elementTypeName: TypeName
// sourcery: skipEquality, skipDescription
/// Array element type, if known
public var elementType: Type?
/// :nodoc:
public init(name: String, elementTypeName: TypeName, elementType: Type? = nil) {
self.name = name
self.elementTypeName = elementTypeName
self.elementType = elementType
}
/// Returns array as generic type
public var asGeneric: GenericType {
GenericType(name: "Array", typeParameters: [
.init(typeName: elementTypeName)
])
}
public var asSource: String {
"[\(elementTypeName.asSource)]"
}
// sourcery:inline:ArrayType.AutoCoding
/// :nodoc:
required public init?(coder aDecoder: NSCoder) {
guard let name: String = aDecoder.decode(forKey: "name") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["name"])); fatalError() }; self.name = name
guard let elementTypeName: TypeName = aDecoder.decode(forKey: "elementTypeName") else { NSException.raise(NSExceptionName.parseErrorException, format: "Key '%@' not found.", arguments: getVaList(["elementTypeName"])); fatalError() }; self.elementTypeName = elementTypeName
self.elementType = aDecoder.decode(forKey: "elementType")
}
/// :nodoc:
public func encode(with aCoder: NSCoder) {
aCoder.encode(self.name, forKey: "name")
aCoder.encode(self.elementTypeName, forKey: "elementTypeName")
aCoder.encode(self.elementType, forKey: "elementType")
}
// sourcery:end
}
| mit | ec59cac554d3baa78657923c2cac5a6b | 36.48 | 284 | 0.659552 | 4.970822 | false | false | false | false |
kinyong/KYWeiboDemo-Swfit | AYWeibo/AYWeibo/classes/RequestAccount.swift | 1 | 2852 | //
// RequestAccount.swift
// AYWeibo
//
// Created by Ayong on 16/6/25.
// Copyright © 2016年 Ayong. All rights reserved.
//
import UIKit
class RequestAccount {
/// 读取缓存中的授权模型
private static var loadAccount: UserAccount?
// MARK: - 类方法
/// 获取授权用户信息并缓存信息
/// 调用此方法之前,确保已经授权完成并对access_token令牌数据进行转模型
class func loadAndSaveAccount(account: UserAccount, complete:() -> Void) {
// 断言
// 断定access_token一定不等于nil的,如果运行的时候access_token等于nil,程序就会崩溃并且报错
assert(account.access_token != nil, "使用该方法必须先授权")
// 1.准备请求参数
let parameters = ["access_token": account.access_token!, "uid": account.uid]
// 2.发送请求
NetWorkTools.shareIntance.loadUserInfo(parameters as! [String : AnyObject]) { (response) in
guard let data = response.data else {
QL3("获取不到数据")
return
}
do {
let dict = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as! [String: AnyObject]
// 2.1 取出用户信息
account.screen_name = dict["screen_name"] as? String
account.avatar_large = dict["avatar_large"] as? String
// 2.2 缓存用户信息
NSKeyedArchiver.archiveRootObject(account, toFile: "userAccount.plist".cachesDir())
// 回调
complete()
} catch {
QL3("json转字典失败")
}
}
}
/// 解档读取
class func loadUserAccount() -> UserAccount? {
// 1.判断是否已经加载过了
if UserAccount.account != nil {
QL2("已经加载过")
return RequestAccount.loadAccount
}
QL2("userAccount.plist".cachesDir())
// 2.尝试从文件中加载
guard let account = NSKeyedUnarchiver.unarchiveObjectWithFile("userAccount.plist".cachesDir()) as? UserAccount else {
QL2("没有缓存授权文件")
return nil
}
// 3.校验是否过期
guard let date = account.expires_Date where date.compare(NSDate()) != .OrderedAscending else {
QL2("令牌过期了")
return nil
}
RequestAccount.loadAccount = account
return RequestAccount.loadAccount
}
/// 判断用户是否登录
class func isLogin() -> Bool {
return RequestAccount.loadUserAccount() != nil
}
}
| apache-2.0 | 233b4a90fbe69ad952d3e70711b4db41 | 28.211765 | 128 | 0.535642 | 4.572744 | false | false | false | false |
rsaenzi/MyBankManagementApp | MyBankManagementApp/MyBankManagementApp/AccountInfoVC.swift | 1 | 2430 | //
// AccountInfoVC.swift
// MyBankManagementApp
//
// Created by Rigoberto Sáenz Imbacuán on 1/31/16.
// Copyright © 2016 Rigoberto Saenz Imbacuan. All rights reserved.
//
import UIKit
class AccountInfoVC: UIViewController {
@IBOutlet weak var textfieldName: UITextField!
@IBOutlet weak var textfieldNumber: UITextField!
private var editionMode: ScreensInfoEditionMode = .Creation
override func viewWillAppear(animated: Bool) {
if editionMode == .Creation {
self.navigationItem.title = "Add Account"
} else if editionMode == .Edition {
self.navigationItem.title = "Edit Account"
// Fill screen with client info
textfieldName.text = Bank.instance.getSelectedAccount().name
textfieldNumber.text = Bank.instance.getSelectedAccount().number
}
}
@IBAction func onClickSave(sender: UIBarButtonItem) {
// Input validation
if textfieldName.text == "" {
View.showAlert(self, messageToShow: "Name can not be empty")
return
}
if textfieldNumber.text == "" {
View.showAlert(self, messageToShow: "Number can not be empty")
return
}
if let number = Int(textfieldNumber.text!) {
if number <= 0 {
View.showAlert(self, messageToShow: "Number can not be negative or zero")
return
}
}else {
View.showAlert(self, messageToShow: "Number can not have letters and spaces")
return
}
// Account processing
if editionMode == .Creation {
// Account creation
let newAccount = Account(newName: textfieldName.text!, newNumber: textfieldNumber.text!)
Bank.instance.createAccount(newAccount)
} else if editionMode == .Edition {
// Account edition
Bank.instance.editAccount(Bank.instance.getSelectedAccount(), newName: textfieldName.text!, newNumber: textfieldNumber.text!, newBalance: Bank.instance.getSelectedAccount().balance)
}
// Pop current screen
self.navigationController?.popViewControllerAnimated(true)
}
func enableEditionMode(accountId: Int){
editionMode = .Edition
}
} | mit | 3c0e98bade9a8bd46d7d621b3aef17a9 | 31.373333 | 193 | 0.592501 | 5.357616 | false | false | false | false |
RadioBear/CalmKit | CalmKit/Animators/BRBCalmKitDoubleArcAnimator.swift | 1 | 3321 | //
// BRBCalmKitDoubleArcAnimator.swift
// CalmKit
//
// Copyright (c) 2016 RadioBear
//
// 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 BRBCalmKitDoubleArcAnimator: BRBCalmKitAnimator {
var arcWidthRate: CGFloat = 0.05
var totalDuration: NSTimeInterval = 1.0
func setupAnimation(inLayer layer : CALayer, withSize size : CGSize, withColor color : UIColor) {
let beginTime = CACurrentMediaTime()
let arcWidth = size.width * arcWidthRate
let frame: CGRect = CGRectInset(CGRectMake(0.0, 0.0, size.width, size.height), arcWidth, arcWidth)
let radius: CGFloat = frame.width * 0.5
let center: CGPoint = CGPointMake(frame.midX, frame.midY)
let arc = CALayer()
arc.frame = CGRectMake(0.0, 0.0, size.width, size.height)
arc.backgroundColor = color.CGColor
arc.anchorPoint = CGPointMake(0.5, 0.5)
arc.shouldRasterize = true
arc.rasterizationScale = UIScreen.mainScreen().scale
let path = CGPathCreateMutable()
CGPathAddRelativeArc(path, nil, center.x, center.y, radius, p_degToRad(20.0), p_degToRad(140.0))
let pathAdd = CGPathCreateMutable()
CGPathAddRelativeArc(pathAdd, nil, center.x, center.y, radius, p_degToRad(200.0), p_degToRad(140.0))
CGPathAddPath(path, nil, pathAdd)
let mask = CAShapeLayer()
mask.frame = CGRectMake(0.0, 0.0, size.width, size.height)
mask.path = path
mask.strokeColor = UIColor.blackColor().CGColor
mask.fillColor = UIColor.clearColor().CGColor
mask.lineWidth = arcWidth
mask.anchorPoint = CGPointMake(0.5, 0.5)
mask.lineCap = kCALineCapRound
arc.mask = mask;
let anim = CAKeyframeAnimation(keyPath: "transform.rotation.z")
anim.removedOnCompletion = false
anim.repeatCount = HUGE
anim.duration = totalDuration
anim.beginTime = beginTime
anim.timeOffset = NSDate.timeIntervalSinceReferenceDate()
anim.keyTimes = [0.0, 0.5, 1.0]
anim.values = [0.0, M_PI, M_PI * 2.0]
layer.addSublayer(arc)
arc.addAnimation(anim, forKey:"calmkit-anim")
}
}
| mit | 318101d360c6a92aa47b64002ea51bd6 | 41.576923 | 108 | 0.669979 | 4.369737 | false | false | false | false |
AfricanSwift/TUIKit | TUIKit/Source/UIElements/Foundation/TUIView.swift | 1 | 15312 | //
// File: TUIView.swift
// Created by: African Swift
import Darwin
// MARK: -
// MARK: TUIView -
public struct TUIView
{
public private(set) var origin: TUIVec2
public private(set) var size: TUIWindowSize
/// Flag indicating if the cache is invalid
/// Controls rendering
internal var invalidate: Bool
// Optional TUIBorder for the view
public let border: TUIBorder
private var buffer: [[TUICharacter]]
private let borderColor: Ansi
public let backgroundColor: Ansi
public let attribute: Attribute
public let invertYAxis: Bool
/// View cache (rendered Ansi)
/// Used for direct view draw, unused with TUIScreen
public var cache: [Ansi]
/// Border parts
internal var borderParts: (top: Ansi, bottom: Ansi, left: Ansi, right: Ansi) {
let color = self.borderColor != "" ? self.borderColor : Ansi.Color.resetAll()
guard let box = border.toTUIBox() else {
return ("", "", "", "")
}
let width = Int(self.size.character.width)
let topline = String(repeating: box.horizontal.top, count: width)
let bottomline = String(repeating: box.horizontal.bottom, count: width)
return
(Ansi("\(color)\(box.top.left)\(topline)\(box.top.right)\(Ansi.Color.resetAll())"),
Ansi("\(color)\(box.bottom.left)\(bottomline)\(box.bottom.right)\(Ansi.Color.resetAll())"),
Ansi("\(color)\(box.vertical.left)\(Ansi.Color.resetAll())"),
Ansi("\(color)\(box.vertical.right)\(Ansi.Color.resetAll())"))
}
/// Flat array of active buffer cell indexes
internal var activeIndex: [(x: Int, y: Int, type: TUICharacter.Category)] {
let rows = Int(self.size.character.height)
let columns = Int(self.size.character.width)
let viewArray = (0..<rows)
.map { r in (0..<columns)
.map { c in (x: c, y: r, type: self.buffer[r][c].type) } }
return viewArray
.flatMap { $0 }
.filter { $0.type != .none }
}
public enum Attribute
{
case single, widthx2, heightx2
}
/// Maximum Viewable size based on selected size Attribute
///
/// - Parameters:
/// - bordeer: bool
/// - attribute: Attribute
/// - Returns: TUISize
internal static func maxSize(border: Bool, attribute: Attribute) -> TUISize
{
guard let size = TUIWindow.ttysize() else { exit(EXIT_FAILURE) }
let inset = border ? 2 : 0
let width = attribute == .single ? size.character.width : size.character.width / 2
let height = attribute == .heightx2 ? size.character.height / 2 : size.character.height
let columns = Int(width) - inset
let rows = Int(height) - inset
return TUISize(width: columns * 2, height: rows * 4)
}
public struct Parameter
{
internal let border: TUIBorder
internal let color: Ansi
internal let attribute: Attribute
internal let background: Ansi
internal let invertYAxis: Bool
/// Default initializer
///
/// - parameters:
/// - border: TUIBorder
/// - color: Ansi
/// - background: Ansi
/// - attribute: Attribute
public init(border: TUIBorder = .single, color: Ansi = "",
background: Ansi = "", attribute: Attribute = .single, invertYAxis: Bool = false)
{
self.border = border
self.color = color
self.background = background
self.attribute = attribute
self.invertYAxis = invertYAxis
}
}
/// Default initializer
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - width: Int
/// - height: Int
/// - parameters: Parameter
public init(x: Int, y: Int, width: Int, height: Int, parameters: Parameter = Parameter())
{
self.init(origin: TUIVec2(x: x, y: y), size: TUISize(width: width, height: height),
parameters: parameters)
}
/// Default initializer
///
/// - parameters:
/// - origin: Int
/// - size: Int
/// - parameters: Parameter
public init(origin: TUIVec2, size: TUISize, parameters: Parameter = Parameter())
{
self.origin = origin
self.size = TUIWindowSize(width: size.width, height: size.height)
self.invalidate = true
self.border = parameters.border
self.buffer = init2D(
d1: Int(self.size.character.height),
d2: Int(self.size.character.width),
repeatedValue: TUICharacter(
character: " ",
color: Ansi.Color(red: 0, green: 0, blue: 0, alpha: 0)))
self.borderColor = parameters.color
self.backgroundColor = parameters.background
self.attribute = parameters.attribute
self.invertYAxis = parameters.invertYAxis
var cacheSize = Int(self.size.character.height)
if case .none = border { } else { cacheSize += 2 }
self.cache = [Ansi](repeating: Ansi(""), count: cacheSize)
}
/// Default initializer
///
/// - parameters:
/// - parameters: Parameter
public init(parameters: Parameter = Parameter())
{
var hasBorder = true
if case .none = parameters.border { hasBorder = false }
let size = TUIView.maxSize(border: hasBorder, attribute: parameters.attribute)
self.init(origin: TUIVec2(x: 0, y: 0), size: size, parameters: parameters)
}
}
// MARK: -
// MARK: View Adjustments -
public extension TUIView
{
/// Move View
///
/// - parameters:
/// - x: Int
/// - y: Int
public mutating func move(x: Int, y: Int)
{
self.origin = TUIVec2(x: x, y: y)
}
/// Resize View
///
/// - parameters:
/// - width: Int
/// - height: Int
public mutating func resize(width: Int, height: Int)
{
let viewParam = Parameter(border: self.border, color: self.borderColor,
background: self.backgroundColor,
attribute: self.attribute)
self = TUIView.init(
origin: self.origin,
size: TUISize(width: width, height: height),
parameters: viewParam)
self.invalidate = false
}
/// Clear everything
public mutating func clear()
{
self.buffer = init2D(
d1: Int(self.size.character.height),
d2: Int(self.size.character.width),
repeatedValue: TUICharacter(
character: " ",
color: Ansi.Color(red: 0, green: 0, blue: 0, alpha: 0)))
self.invalidate = true
}
}
// MARK: -
// MARK: Render & Draw -
public extension TUIView
{
/// Draw
///
/// - parameters:
/// - atOrigin: Bool (default = true): controls whether the view is
/// drawn at origin or the cursor offset
/// - parameters: TUIRenderParameter
public mutating func draw(
atOrigin: Bool = false,
parameters: TUIRenderParameter = TUIRenderParameter())
{
if self.invalidate
{
render(parameters: parameters)
}
var y = Int(self.origin.y)
let x = Int(self.origin.x)
for line in self.cache
{
var attr1: Ansi = ""
var attr2: Ansi = ""
var doubleLine = false
if self.attribute == .widthx2
{
attr1 = Ansi.Line.Attributes.Width.double()
}
else if self.attribute == .heightx2
{
attr1 = Ansi.Line.Attributes.Height.topHalf()
attr2 = Ansi.Line.Attributes.Height.bottomHalf()
doubleLine = true
}
_ = atOrigin ? Ansi.Cursor.position(row: y, column: x).stdout() : ()
_ = atOrigin ? (attr1 + line).stdout() : (attr1 + line + "\n").stdout()
if doubleLine
{
y += 1
_ = atOrigin ? Ansi.Cursor.position(row: y, column: x).stdout() : ()
_ = atOrigin ? (attr2 + line).stdout() : (attr2 + line + "\n").stdout()
}
y += 1
}
Ansi.resetAll().stdout()
Ansi.flush()
}
/// Render view cache
///
/// - parameters:
/// - parameters: TUIRenderParameter
internal mutating func render(parameters: TUIRenderParameter)
{
guard self.invalidate else { return }
var hasBorder = true
if case .none = self.border
{
hasBorder = false
}
let left = hasBorder ? self.borderParts.left : ""
let right = hasBorder ? self.borderParts.right : ""
if hasBorder
{
self.cache[0] = self.borderParts.top
self.cache[self.cache.count - 1] = self.borderParts.bottom
}
let offset = hasBorder ? 1 : 0
for y in self.buffer.indices
{
var lineBuffer = Ansi("")
for x in self.buffer[0].indices
{
lineBuffer += self.buffer[y][x].toAnsi(parameters: parameters)
}
self.cache[y + offset] = (left + self.backgroundColor + lineBuffer + right)
}
self.invalidate = false
}
}
// MARK: Draw Pixel
public extension TUIView
{
/// Draw Pixel
///
/// - parameters:
/// - x: Double
/// - y: Double
/// - color: Ansi.Color
/// - action: TUICharacter.SetAction
public mutating func drawPixel(x: Double, y: Double,
color: Ansi.Color, action: TUICharacter.SetAction = .on)
{
// Do nothing if out of bounds
guard x < self.size.pixel.width && y < self.size.pixel.height else { return }
guard x >= 0 && y >= 0 else { return }
let y2 = self.invertYAxis ? self.size.pixel.height - (y + 1) : y
guard y2 > 0 else { return }
let char = (x: Int(round(x)) / 2, y: Int(round(y2)) / 4)
self.buffer[char.y][char.x].setPixel(x: x, y: y2, action: action, color: color)
self.invalidate = true
}
/// Draw Pixel
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - color: Ansi.Color
/// - action: TUICharacter.SetAction
public mutating func drawPixel(x: Int, y: Int,
color: Ansi.Color, action: TUICharacter.SetAction = .on)
{
self.drawPixel(x: Double(x), y: Double(y), color: color)
}
/// Draw Pixel
///
/// - parameters:
/// - at: TUIVec2
/// - color: Ansi.Color
/// - action: TUICharacter.SetAction
public mutating func drawPixel(at: TUIVec2, color: Ansi.Color,
action: TUICharacter.SetAction = .on)
{
self.drawPixel(x: at.x, y: at.y, color: color)
}
}
// MARK: Draw Character
public extension TUIView
{
/// Draw Character
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - character: Character
/// - color: Ansi.Color
public mutating func drawCharacter(
x: Int, y: Int, character: Character, color: Ansi.Color)
{
self.buffer[y][x].setCharacter(character: character, color: color)
self.invalidate = true
}
/// Draw Ansi Character
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - character: Character
/// - ansi: Ansi
public mutating func drawAnsiCharacter(
x: Int, y: Int, character: Character, ansi: Ansi)
{
self.buffer[y][x].setAnsiCharacter(character: character, ansi: ansi)
self.invalidate = true
}
}
// MARK: Draw Text
public extension TUIView
{
/// Draw Text
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - text: String
/// - color: Ansi.Color
/// - linewrap: Bool
public mutating func drawText(
x: Int, y: Int, text: String, color: Ansi.Color, linewrap: Bool = false)
{
let chars = text.characters
var position = (x: x, y: y)
var index = 0
for i in chars.indices
{
if position.x + index > Int(self.size.character.width) - 1 && !linewrap
{
break
}
else if position.x + index > Int(self.size.character.width) - 1 && linewrap
{
if position.y + 1 > Int(self.size.character.height) - 1
{
break
}
index = 0
position.y += 1
position.x = 0
}
self.buffer[position.y][position.x + index]
.setCharacter(character: chars[i], color: color)
index += 1
}
self.invalidate = true
}
/// Draw Text
///
/// - parameters:
/// - at: TUIVec2
/// - text: String
/// - color: Ansi.Color
/// - linewrap: Bool
public mutating func drawText(at: TUIVec2, text: String,
color: Ansi.Color, linewrap: Bool = false)
{
self.drawText(x: Int(at.x), y: Int(at.y), text: text, color: color, linewrap: linewrap)
}
// FIXME: Crashes when text is longer than view size, drawText has safe guards, this doesn't
/// Draw Ansi text
///
/// - parameters:
/// - x: Int
/// - y: Int
/// - text: String
/// - linewrap: Bool
public mutating func drawAnsiText(x: Int, y: Int, text: String, linewrap: Bool = false)
{
guard let tokens = try? Ansi.tokenizer(input: Ansi(text)) else {
return
}
let position = (x: x, y: y)
var xoffset = 0
var carryOverAnsi = Ansi("")
for t in tokens
{
if t.function == "<Uncompressable>" // Leading whitespace
{
let char = t.text.characters
for i in char.indices
{
self.buffer[position.y][position.x + xoffset]
.setAnsiCharacter(character: char[i], ansi: "")
xoffset += 1
}
continue
}
if t.function.contains("m") && t.suffix.characters.count == 0
{
carryOverAnsi += Ansi(Ansi.C1.CSI + t.parameter + t.function)
}
let ans = Ansi(Ansi.C1.CSI + t.parameter + t.function) + carryOverAnsi
setAnsiText(text: t.suffix, y: y, x: x, xoffset: &xoffset, ansi: ans, linewrap: linewrap)
}
self.invalidate = true
}
private mutating func setAnsiText(text: String, y: Int, x: Int,
xoffset: inout Int, ansi: Ansi, linewrap: Bool)
{
var p = (x: x, y: y)
var isFirstChar = true
let chars = text.characters
for index in chars.indices
{
guard p.x + xoffset <= Int(self.size.character.width) - 1 && !linewrap else { break }
self.buffer[p.y][p.x + xoffset]
.setAnsiCharacter(character: chars[index], ansi: isFirstChar ? ansi : "")
xoffset += 1
isFirstChar = false
if p.x + xoffset > Int(self.size.character.width) - 1 && linewrap
{
if p.y + 1 > Int(self.size.character.height) - 1 { break }
p.x = 0
p.y += 1
xoffset = 0
}
}
}
/// Draw Rotated Text
///
/// - parameters:
/// - at: TUIVec2
/// - angle: Int
/// - text: String
/// - reverse: Bool
/// - color: Ansi.Color
public mutating func drawRotatedText(at: TUIVec2, angle: Int, text: String,
reverse: Bool = false, color: Ansi.Color)
{
var pos = (x: Int(at.x), y: Int(at.y))
let value = reverse ? text.characters.reversed()
.map { String($0) }.joined(separator: "") : text
var inclination = (x: 1, y: 0)
switch angle
{
case 0, 360:
inclination = (x: 0, y: -1)
case 45:
inclination = (x: 1, y: -1)
case 90:
self.drawText(at: at, text: value, color: color)
return
case 135:
inclination = (x: 1, y: 1)
case 180:
inclination = (x: 0, y: 1)
case 225:
inclination = (x: -1, y: 1)
case 270:
inclination = (x: -1, y: 0)
case 315:
inclination = (x: -1, y: -1)
default:
inclination = (x: 1, y: 0)
}
for c in value.characters
{
self.drawCharacter(x: pos.x, y: pos.y, character: c, color: color)
pos.x += inclination.x
pos.y += inclination.y
}
}
}
| mit | ba7b99c3386d99ee7dec63ca7f9dd0b1 | 26.992687 | 98 | 0.575954 | 3.732813 | false | false | false | false |
remaerd/Elements | Elements/XML.swift | 1 | 4769 | //
// XML.swift
// Elements
//
// Created by Sean Cheng on 8/26/15.
// Copyright © 2015 Sean Cheng. All rights reserved.
//
import Foundation
public final class XML : NSObject, XMLParserDelegate {
public enum XMLError : Error {
case invalidXMLDocumentFilePath
case invalidXMLDocumentData
case invalidElementClass
case invalidParentElementClass
}
public var xmlData : Data?
fileprivate var _parser : XMLParser?
fileprivate var _parserErrors = [Error]()
fileprivate var _currentAttributes : [String:String]?
fileprivate var _currentElementType : ElementType.Type?
fileprivate var _rootElementType : ElementType.Type?
fileprivate lazy var _rootElements : [ElementType] = {
return [ElementType]()
}()
fileprivate lazy var _currentElements : [ElementType] = {
return [ElementType]()
}()
fileprivate lazy var _models : [String:ElementType.Type] = {
return [String:ElementType.Type]()
}()
public convenience init(filePath:String, models:[ElementType.Type]) throws {
if FileManager.default.fileExists(atPath: filePath) != true { throw XMLError.invalidXMLDocumentFilePath }
guard let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else { throw XMLError.invalidXMLDocumentData }
self.init(data: data,models: models)
}
public convenience init(fileURL:URL, models:[ElementType.Type]) throws {
try self.init(filePath:fileURL.path, models: models)
}
public convenience init(xml:String, models:[ElementType.Type]) {
let data = xml.data(using: String.Encoding.utf8)!
self.init(data: data,models: models)
}
public init(data: Data, models:[ElementType.Type]) {
self.xmlData = data
super.init()
for elementType in models { self._models[elementType.element] = elementType }
self._rootElementType = models.first
}
public func decode(_ completionHandler: ((_ rootElements:[ElementType]?, _ errors:[Error]?) -> Void)?) {
guard let data = self.xmlData else { completionHandler?(nil, [XMLError.invalidXMLDocumentData]); return }
self._parser = XMLParser(data:data)
self._parser?.delegate = self
_ = self._parser!.parse()
if _parserErrors.count == 0 { completionHandler?(self._rootElements, nil) }
else { completionHandler?(nil, _parserErrors) }
self._parser = nil
}
public func encode(_ completionHandler: ((_ errors:[Error]?) -> Void)?) {
}
}
extension XML {
public func parserDidStartDocument(_ parser: XMLParser) {
self._rootElements.removeAll()
self._currentElements.removeAll()
self._parserErrors.removeAll()
}
public func parserDidEndDocument(_ parser: XMLParser) {
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if self._currentElementType != nil { self.createElement(self._currentElementType!) }
self._currentElementType = _models[elementName]
self._currentAttributes = attributeDict
}
public func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
self._currentAttributes = nil
self._currentElementType = nil
if self._currentElements.count > 0 { self._currentElements.removeLast() }
}
public func parser(_ parser: XMLParser, foundCharacters string: String) {
guard let elementType = self._currentElementType else { return }
self.createElement(elementType, property: string as AnyObject?)
}
public func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) {
guard let elementType = self._currentElementType else { return }
self.createElement(elementType, property: CDATABlock as AnyObject?)
}
public func parser(_ parser: XMLParser, validationErrorOccurred validationError: Error) {
self._parserErrors.append(validationError)
}
public func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
self._parserErrors.append(parseError)
}
}
extension XML {
fileprivate func createElement(_ classType:ElementType.Type, property: AnyObject? = nil) {
do {
let element = try classType.decode(self._currentElements.last, attributes: self._currentAttributes, property: property)
self._currentElements.append(element)
if self._currentElements.count > 1 {
let previousElement = self._currentElements[self._currentElements.count - 2]
previousElement.child(element)
}
if self._rootElementType == classType { self._rootElements.append(element) }
} catch {
self._parserErrors.append(error)
}
}
}
| bsd-3-clause | fe77482e5cefaaea2854e327cbc71943 | 29.961039 | 178 | 0.694631 | 4.683694 | false | false | false | false |
lyp1992/douyu-Swift | YPTV/Pods/Alamofire/Source/ServerTrustPolicy.swift | 19 | 14092 | //
// ServerTrustPolicy.swift
//
// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// Responsible for managing the mapping of `ServerTrustPolicy` objects to a given host.
open class ServerTrustPolicyManager {
/// The dictionary of policies mapped to a particular host.
public let policies: [String: ServerTrustPolicy]
/// Initializes the `ServerTrustPolicyManager` instance with the given policies.
///
/// Since different servers and web services can have different leaf certificates, intermediate and even root
/// certficates, it is important to have the flexibility to specify evaluation policies on a per host basis. This
/// allows for scenarios such as using default evaluation for host1, certificate pinning for host2, public key
/// pinning for host3 and disabling evaluation for host4.
///
/// - parameter policies: A dictionary of all policies mapped to a particular host.
///
/// - returns: The new `ServerTrustPolicyManager` instance.
public init(policies: [String: ServerTrustPolicy]) {
self.policies = policies
}
/// Returns the `ServerTrustPolicy` for the given host if applicable.
///
/// By default, this method will return the policy that perfectly matches the given host. Subclasses could override
/// this method and implement more complex mapping implementations such as wildcards.
///
/// - parameter host: The host to use when searching for a matching policy.
///
/// - returns: The server trust policy for the given host if found.
open func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
return policies[host]
}
}
// MARK: -
extension URLSession {
private struct AssociatedKeys {
static var managerKey = "URLSession.ServerTrustPolicyManager"
}
var serverTrustPolicyManager: ServerTrustPolicyManager? {
get {
return objc_getAssociatedObject(self, &AssociatedKeys.managerKey) as? ServerTrustPolicyManager
}
set (manager) {
objc_setAssociatedObject(self, &AssociatedKeys.managerKey, manager, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
// MARK: - ServerTrustPolicy
/// The `ServerTrustPolicy` evaluates the server trust generally provided by an `NSURLAuthenticationChallenge` when
/// connecting to a server over a secure HTTPS connection. The policy configuration then evaluates the server trust
/// with a given set of criteria to determine whether the server trust is valid and the connection should be made.
///
/// Using pinned certificates or public keys for evaluation helps prevent man-in-the-middle (MITM) attacks and other
/// vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged
/// to route all communication over an HTTPS connection with pinning enabled.
///
/// - performDefaultEvaluation: Uses the default server trust evaluation while allowing you to control whether to
/// validate the host provided by the challenge. Applications are encouraged to always
/// validate the host in production environments to guarantee the validity of the server's
/// certificate chain.
///
/// - performRevokedEvaluation: Uses the default and revoked server trust evaluations allowing you to control whether to
/// validate the host provided by the challenge as well as specify the revocation flags for
/// testing for revoked certificates. Apple platforms did not start testing for revoked
/// certificates automatically until iOS 10.1, macOS 10.12 and tvOS 10.1 which is
/// demonstrated in our TLS tests. Applications are encouraged to always validate the host
/// in production environments to guarantee the validity of the server's certificate chain.
///
/// - pinCertificates: Uses the pinned certificates to validate the server trust. The server trust is
/// considered valid if one of the pinned certificates match one of the server certificates.
/// By validating both the certificate chain and host, certificate pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - pinPublicKeys: Uses the pinned public keys to validate the server trust. The server trust is considered
/// valid if one of the pinned public keys match one of the server certificate public keys.
/// By validating both the certificate chain and host, public key pinning provides a very
/// secure form of server trust validation mitigating most, if not all, MITM attacks.
/// Applications are encouraged to always validate the host and require a valid certificate
/// chain in production environments.
///
/// - disableEvaluation: Disables all evaluation which in turn will always consider any server trust as valid.
///
/// - customEvaluation: Uses the associated closure to evaluate the validity of the server trust.
public enum ServerTrustPolicy {
case performDefaultEvaluation(validateHost: Bool)
case performRevokedEvaluation(validateHost: Bool, revocationFlags: CFOptionFlags)
case pinCertificates(certificates: [SecCertificate], validateCertificateChain: Bool, validateHost: Bool)
case pinPublicKeys(publicKeys: [SecKey], validateCertificateChain: Bool, validateHost: Bool)
case disableEvaluation
case customEvaluation((_ serverTrust: SecTrust, _ host: String) -> Bool)
// MARK: - Bundle Location
/// Returns all certificates within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `.cer` files.
///
/// - returns: All certificates within the given bundle.
public static func certificates(in bundle: Bundle = Bundle.main) -> [SecCertificate] {
var certificates: [SecCertificate] = []
let paths = Set([".cer", ".CER", ".crt", ".CRT", ".der", ".DER"].map { fileExtension in
bundle.paths(forResourcesOfType: fileExtension, inDirectory: nil)
}.joined())
for path in paths {
if
let certificateData = try? Data(contentsOf: URL(fileURLWithPath: path)) as CFData,
let certificate = SecCertificateCreateWithData(nil, certificateData)
{
certificates.append(certificate)
}
}
return certificates
}
/// Returns all public keys within the given bundle with a `.cer` file extension.
///
/// - parameter bundle: The bundle to search for all `*.cer` files.
///
/// - returns: All public keys within the given bundle.
public static func publicKeys(in bundle: Bundle = Bundle.main) -> [SecKey] {
var publicKeys: [SecKey] = []
for certificate in certificates(in: bundle) {
if let publicKey = publicKey(for: certificate) {
publicKeys.append(publicKey)
}
}
return publicKeys
}
// MARK: - Evaluation
/// Evaluates whether the server trust is valid for the given host.
///
/// - parameter serverTrust: The server trust to evaluate.
/// - parameter host: The host of the challenge protection space.
///
/// - returns: Whether the server trust is valid.
public func evaluate(_ serverTrust: SecTrust, forHost host: String) -> Bool {
var serverTrustIsValid = false
switch self {
case let .performDefaultEvaluation(validateHost):
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
serverTrustIsValid = trustIsValid(serverTrust)
case let .performRevokedEvaluation(validateHost, revocationFlags):
let defaultPolicy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
let revokedPolicy = SecPolicyCreateRevocation(revocationFlags)
SecTrustSetPolicies(serverTrust, [defaultPolicy, revokedPolicy] as CFTypeRef)
serverTrustIsValid = trustIsValid(serverTrust)
case let .pinCertificates(pinnedCertificates, validateCertificateChain, validateHost):
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
SecTrustSetAnchorCertificates(serverTrust, pinnedCertificates as CFArray)
SecTrustSetAnchorCertificatesOnly(serverTrust, true)
serverTrustIsValid = trustIsValid(serverTrust)
} else {
let serverCertificatesDataArray = certificateData(for: serverTrust)
let pinnedCertificatesDataArray = certificateData(for: pinnedCertificates)
outerLoop: for serverCertificateData in serverCertificatesDataArray {
for pinnedCertificateData in pinnedCertificatesDataArray {
if serverCertificateData == pinnedCertificateData {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case let .pinPublicKeys(pinnedPublicKeys, validateCertificateChain, validateHost):
var certificateChainEvaluationPassed = true
if validateCertificateChain {
let policy = SecPolicyCreateSSL(true, validateHost ? host as CFString : nil)
SecTrustSetPolicies(serverTrust, policy)
certificateChainEvaluationPassed = trustIsValid(serverTrust)
}
if certificateChainEvaluationPassed {
outerLoop: for serverPublicKey in ServerTrustPolicy.publicKeys(for: serverTrust) as [AnyObject] {
for pinnedPublicKey in pinnedPublicKeys as [AnyObject] {
if serverPublicKey.isEqual(pinnedPublicKey) {
serverTrustIsValid = true
break outerLoop
}
}
}
}
case .disableEvaluation:
serverTrustIsValid = true
case let .customEvaluation(closure):
serverTrustIsValid = closure(serverTrust, host)
}
return serverTrustIsValid
}
// MARK: - Private - Trust Validation
private func trustIsValid(_ trust: SecTrust) -> Bool {
var isValid = false
var result = SecTrustResultType.invalid
let status = SecTrustEvaluate(trust, &result)
if status == errSecSuccess {
let unspecified = SecTrustResultType.unspecified
let proceed = SecTrustResultType.proceed
isValid = result == unspecified || result == proceed
}
return isValid
}
// MARK: - Private - Certificate Data
private func certificateData(for trust: SecTrust) -> [Data] {
var certificates: [SecCertificate] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if let certificate = SecTrustGetCertificateAtIndex(trust, index) {
certificates.append(certificate)
}
}
return certificateData(for: certificates)
}
private func certificateData(for certificates: [SecCertificate]) -> [Data] {
return certificates.map { SecCertificateCopyData($0) as Data }
}
// MARK: - Private - Public Key Extraction
private static func publicKeys(for trust: SecTrust) -> [SecKey] {
var publicKeys: [SecKey] = []
for index in 0..<SecTrustGetCertificateCount(trust) {
if
let certificate = SecTrustGetCertificateAtIndex(trust, index),
let publicKey = publicKey(for: certificate)
{
publicKeys.append(publicKey)
}
}
return publicKeys
}
private static func publicKey(for certificate: SecCertificate) -> SecKey? {
var publicKey: SecKey?
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let trust = trust, trustCreationStatus == errSecSuccess {
publicKey = SecTrustCopyPublicKey(trust)
}
return publicKey
}
}
| mit | f5b0b9241fd59dd98bc14ac5eb4e5182 | 44.90228 | 120 | 0.655904 | 5.811134 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Controller/LinearEquations/CLinearEquationsPolynomialIndeterminate.swift | 1 | 1103 | import UIKit
class CLinearEquationsPolynomialIndeterminate:CController
{
let model:MLinearEquationsIndeterminates
private weak var viewList:VLinearEquationsIndeterminateList!
init(polynomial:DPolynomial)
{
model = MLinearEquationsIndeterminates(polynomial:polynomial)
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewList:VLinearEquationsIndeterminateList = VLinearEquationsIndeterminateList(
controller:self)
self.viewList = viewList
view = viewList
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
viewList.animateShow()
}
//MARK: public
func close()
{
viewList.animateHide()
parentController.dismissAnimateOver(completion:nil)
}
func selectIndeterminate(indeterminate:DIndeterminate?)
{
model.polynomial?.indeterminate = indeterminate
DManager.sharedInstance?.save()
close()
}
}
| mit | 65c78a7bbd41f51d1a289aee8d58fdf1 | 21.979167 | 91 | 0.646419 | 5.433498 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteCMS/model.CMSMarkdown200Entity.swift | 1 | 1579 | import OpenbuildExtensionPerfect
public class ModelCMSMarkdown200Entity: ResponseModel200Entity, DocumentationProtocol {
public var descriptions = [
"error": "An error has occurred, will always be false",
"message": "Will always be 'Successfully created/fetched the entity.'",
"entity": "Object describing the Markdown entity."
]
public init(entity: ModelCMSMarkdown) {
super.init(entity: entity)
}
public static func describeRAML() -> [String] {
if let docs = ResponseDocumentation.getRAML(key: "RouteCMS.ModelCMSMarkdown200Entity") {
return docs
} else {
let entity = ModelCMSMarkdown(
cms_markdown_id: 1,
handle: "test",
markdown: "#Markdown",
html: "<h1>Markdown</h1>"
)
let model = ModelCMSMarkdown200Entity(entity: entity)
let aMirror = Mirror(reflecting: model)
let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions)
ResponseDocumentation.setRAML(key: "RouteCMS.ModelCMSMarkdown200Entity", lines: docs)
return docs
}
}
}
extension ModelCMSMarkdown200Entity: CustomReflectable {
open var customMirror: Mirror {
return Mirror(
self,
children: [
"error": self.error,
"message": self.message,
"entity": self.entity
],
displayStyle: Mirror.DisplayStyle.class
)
}
} | gpl-2.0 | 2cff3e2e91d6aa01adf86e3bf24a02ca | 26.719298 | 103 | 0.594047 | 5.060897 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.