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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
CartoDB/mobile-ios-samples | AdvancedMap.Objective-C/AdvancedMap/Colors.swift | 1 | 2106 | //
// Utils.swift
// Feature Demo
//
// Created by Aare Undo on 16/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
class Colors {
public static var appleBlue: UIColor = fromRgba(red: 14, green: 122, blue: 254, alpha: 255)
public static var lightTransparentAppleBlue: UIColor = fromRgba(red: 14, green: 122, blue: 254, alpha: 70)
public static var darkTransparentAppleBlue: UIColor = fromRgba(red: 14, green: 122, blue: 254, alpha: 150)
// http://www.htmlcsscolor.com/hex/F24440
public static var locationRed: UIColor = fromRgba(red: 242, green: 68, blue: 64, alpha: 255)
public static var transparentLocationRed: UIColor = fromRgba(red: 215, green: 82, blue: 75, alpha: 150)
public static var transparent: UIColor = fromRgba(red: 0, green: 0, blue: 0, alpha: 0)
public static var navy: UIColor = fromRgba(red: 22, green: 41, blue: 69, alpha: 255)
public static var navyLight: UIColor = fromRgba(red: 32, green: 51, blue: 79, alpha: 200)
public static var nearWhite: UIColor = fromRgba(red: 245, green: 245, blue: 245, alpha: 255)
public static var transparentNavy: UIColor = fromRgba(red: 22, green: 41, blue: 69, alpha: 150)
public static var transparentGray: UIColor = fromRgba(red: 50, green: 50, blue: 50, alpha: 150)
public static var darkTransparentGray: UIColor = fromRgba(red: 50, green: 50, blue: 50, alpha: 200)
public static var lightTransparentGray: UIColor = fromRgba(red: 50, green: 50, blue: 50, alpha: 120)
public static var green: UIColor = fromRgba(red: 115, green: 200, blue: 107, alpha: 255)
public static var purple: UIColor = fromRgba(red: 105, green: 110, blue: 236, alpha: 255)
public static var predictionBlue: UIColor = fromRgba(red: 23, green: 133, blue: 251, alpha: 255)
static func fromRgba(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) -> UIColor {
return UIColor.init(red: red / 255, green: green / 255, blue: blue / 255, alpha: alpha / 255)
}
}
| bsd-2-clause | 48d15cfcb554211dded619d2ae7a8d6f | 41.959184 | 110 | 0.670784 | 3.485099 | false | false | false | false |
chriscox/material-components-ios | components/Palettes/examples/supplemental/PalettesExampleViewController.swift | 1 | 2856 | /*
Copyright 2016-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import MaterialComponents
typealias ExampleTone = (name: String, tone: UIColor)
func ExampleTonesForPalette(_ palette: MDCPalette) -> [ExampleTone] {
var tones: [ExampleTone] = [
(MDCPaletteTint100Name, palette.tint100),
(MDCPaletteTint300Name, palette.tint300),
(MDCPaletteTint500Name, palette.tint500),
(MDCPaletteTint700Name, palette.tint700)
]
if let accent = palette.accent400 {
tones.append((MDCPaletteAccent400Name, accent))
}
return tones
}
class PalettesExampleViewController: UITableViewController {
var palettes : [(name: String, palette: MDCPalette)] = []
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.separatorStyle = .none
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 50
}
override func numberOfSections(in tableView: UITableView) -> Int {
return palettes.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let palette = palettes[section].palette
return ExampleTonesForPalette(palette).count
}
override func tableView(_ tableView: UITableView,
cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
}
let paletteInfo = palettes[indexPath.section]
let tones = ExampleTonesForPalette(paletteInfo.palette)
cell!.textLabel!.text = tones[indexPath.row].name
cell!.backgroundColor = tones[indexPath.row].tone
cell!.selectionStyle = .none
return cell!
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return palettes[section].name
}
convenience init() {
self.init(style: .grouped)
}
override init(style: UITableViewStyle) {
super.init(style: style)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | dd2c27049a269f02dbe154ce0ca17726 | 30.733333 | 96 | 0.727591 | 4.518987 | false | false | false | false |
pyconjp/pyconjp-ios | PyConJP/ViewController/Base/DetailImageViewController.swift | 1 | 1175 | //
// DetailImageViewController.swift
// PyConJP
//
// Created by Yutaro Muta on 2016/08/05.
// Copyright © 2016 PyCon JP. All rights reserved.
//
import UIKit
class DetailImageViewController: UIViewController {
@IBOutlet weak var customImageView: CustomImageView?
override func viewDidLoad() {
super.viewDidLoad()
let doubleTapGesture = UITapGestureRecognizer(target: customImageView, action: #selector(CustomImageView.handleGesture(_:)))
doubleTapGesture.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTapGesture)
let pinchGesture = UIPinchGestureRecognizer(target: customImageView, action: #selector(CustomImageView.handleGesture(_:)))
view.addGestureRecognizer(pinchGesture)
let longPressGesture = UILongPressGestureRecognizer(target: customImageView, action: #selector(CustomImageView.handleGesture(_:)))
view.addGestureRecognizer(longPressGesture)
let panGesture = UIPanGestureRecognizer(target: customImageView, action: #selector(CustomImageView.handleGesture(_:)))
view.addGestureRecognizer(panGesture)
}
}
| mit | 07a5a82f88563d18b27522468667bc36 | 35.6875 | 138 | 0.719761 | 5.726829 | false | false | false | false |
Elm-Tree-Island/Shower | Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoa/NSObject+KeyValueObserving.swift | 5 | 14671 | import Foundation
import ReactiveSwift
import enum Result.NoError
extension Reactive where Base: NSObject {
/// Create a producer which sends the current value and all the subsequent
/// changes of the property specified by the key path.
///
/// The producer completes when the object deinitializes.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func producer(forKeyPath keyPath: String) -> SignalProducer<Any?, NoError> {
return SignalProducer { observer, lifetime in
let disposable = KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.initial, .new],
action: observer.send
)
lifetime.observeEnded(disposable.dispose)
if let lifetimeDisposable = self.lifetime.observeEnded(observer.sendCompleted) {
lifetime.observeEnded(lifetimeDisposable.dispose)
}
}
}
/// Create a signal all changes of the property specified by the key path.
///
/// The signal completes when the object deinitializes.
///
/// - note:
/// Does not send the initial value. See `producer(forKeyPath:)`.
///
/// - parameters:
/// - keyPath: The key path of the property to be observed.
///
/// - returns: A producer emitting values of the property specified by the
/// key path.
public func signal(forKeyPath keyPath: String) -> Signal<Any?, NoError> {
return Signal { observer, signalLifetime in
signalLifetime += KeyValueObserver.observe(
self.base,
keyPath: keyPath,
options: [.new],
action: observer.send
)
signalLifetime += lifetime.observeEnded(observer.sendCompleted)
}
}
}
extension Property where Value: OptionalProtocol {
/// Create a property that observes the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to observe.
public convenience init(object: NSObject, keyPath: String) {
// `Property(_:)` caches the latest value of the `DynamicProperty`, so it is
// saved to be used even after `object` deinitializes.
self.init(UnsafeKVOProperty(object: object, optionalAttributeKeyPath: keyPath))
}
}
extension Property {
/// Create a property that observes the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to observe.
public convenience init(object: NSObject, keyPath: String) {
// `Property(_:)` caches the latest value of the `DynamicProperty`, so it is
// saved to be used even after `object` deinitializes.
self.init(UnsafeKVOProperty(object: object, nonOptionalAttributeKeyPath: keyPath))
}
}
// `Property(unsafeProducer:)` is private to ReactiveSwift. So the fact that
// `Property(_:)` uses only the producer is explioted here to achieve the same effect.
private final class UnsafeKVOProperty<Value>: PropertyProtocol {
var value: Value { fatalError() }
var signal: Signal<Value, NoError> { fatalError() }
let producer: SignalProducer<Value, NoError>
init(producer: SignalProducer<Value, NoError>) {
self.producer = producer
}
convenience init(object: NSObject, nonOptionalAttributeKeyPath keyPath: String) {
self.init(producer: object.reactive.producer(forKeyPath: keyPath).map { $0 as! Value })
}
}
private extension UnsafeKVOProperty where Value: OptionalProtocol {
convenience init(object: NSObject, optionalAttributeKeyPath keyPath: String) {
self.init(producer: object.reactive.producer(forKeyPath: keyPath).map {
return Value(reconstructing: $0.optional as? Value.Wrapped)
})
}
}
extension BindingTarget {
/// Create a binding target that sets the given key path of the given object. The
/// generic type `Value` can be any Swift type that is Objective-C bridgeable.
///
/// - parameters:
/// - object: An object to be observed.
/// - keyPath: The key path to set.
public init(object: NSObject, keyPath: String) {
self.init(lifetime: object.reactive.lifetime) { [weak object] value in
object?.setValue(value, forKey: keyPath)
}
}
}
internal final class KeyValueObserver: NSObject {
typealias Action = (_ object: AnyObject?) -> Void
private static let context = UnsafeMutableRawPointer.allocate(bytes: 1, alignedTo: 0)
unowned(unsafe) let unsafeObject: NSObject
let key: String
let action: Action
fileprivate init(observing object: NSObject, key: String, options: NSKeyValueObservingOptions, action: @escaping Action) {
self.unsafeObject = object
self.key = key
self.action = action
super.init()
object.addObserver(
self,
forKeyPath: key,
options: options,
context: KeyValueObserver.context
)
}
func detach() {
unsafeObject.removeObserver(self, forKeyPath: key, context: KeyValueObserver.context)
}
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
if context == KeyValueObserver.context {
action(object as! NSObject)
}
}
}
extension KeyValueObserver {
/// Establish an observation to the property specified by the key path
/// of `object`.
///
/// - warning: The observation would not be automatically removed when
/// `object` deinitializes. You must manually dispose of the
/// returned disposable before `object` completes its
/// deinitialization.
///
/// - parameters:
/// - object: The object to be observed.
/// - keyPath: The key path of the property to be observed.
/// - options: The desired configuration of the observation.
/// - action: The action to be invoked upon arrival of changes.
///
/// - returns: A disposable that would tear down the observation upon
/// disposal.
static func observe(
_ object: NSObject,
keyPath: String,
options: NSKeyValueObservingOptions,
action: @escaping (_ value: AnyObject?) -> Void
) -> AnyDisposable {
// Compute the key path head and tail.
let components = keyPath.components(separatedBy: ".")
precondition(!components.isEmpty, "Received an empty key path.")
let isNested = components.count > 1
let keyPathHead = components[0]
let keyPathTail = components[1 ..< components.endIndex].joined(separator: ".")
// The serial disposable for the head key.
//
// The inner disposable would be disposed of, and replaced with a new one
// when the value of the head key changes.
let headSerialDisposable = SerialDisposable()
// If the property of the head key isn't actually an object (or is a Class
// object), there is no point in observing the deallocation.
//
// If this property is not a weak reference to an object, we don't need to
// watch for it spontaneously being set to nil.
//
// Attempting to observe non-weak properties using dynamic getters will
// result in broken behavior, so don't even try.
let (shouldObserveDeinit, isWeak) = keyPathHead.withCString { cString -> (Bool, Bool) in
if let propertyPointer = class_getProperty(type(of: object), cString) {
let attributes = PropertyAttributes(property: propertyPointer)
return (attributes.isObject && attributes.objectClass != NSClassFromString("Protocol") && !attributes.isBlock, attributes.isWeak)
}
return (false, false)
}
// Establish the observation.
//
// The initial value is also handled by the closure below, if `Initial` has
// been specified in the observation options.
let observer: KeyValueObserver
if isNested {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options.union(.initial)) { object in
guard let value = object?.value(forKey: keyPathHead) as! NSObject? else {
action(nil)
return
}
let headDisposable = CompositeDisposable()
headSerialDisposable.inner = headDisposable
if shouldObserveDeinit {
let disposable = value.reactive.lifetime.observeEnded {
if isWeak {
action(nil)
}
// Detach the key path tail observers eagarly.
headSerialDisposable.inner = nil
}
headDisposable += disposable
}
// Recursively add observers along the key path tail.
let disposable = KeyValueObserver.observe(
value,
keyPath: keyPathTail,
options: options.subtracting(.initial),
action: action
)
headDisposable += disposable
// Send the latest value of the key path tail.
action(value.value(forKeyPath: keyPathTail) as AnyObject?)
}
} else {
observer = KeyValueObserver(observing: object, key: keyPathHead, options: options) { object in
guard let value = object?.value(forKey: keyPathHead) as AnyObject? else {
action(nil)
return
}
// For a direct key path, the deinitialization needs to be
// observed only if the key path is a weak property.
if shouldObserveDeinit && isWeak {
let disposable = lifetime(of: value).observeEnded {
action(nil)
}
headSerialDisposable.inner = disposable
}
// Send the latest value of the key.
action(value)
}
}
return AnyDisposable {
observer.detach()
headSerialDisposable.dispose()
}
}
}
/// A descriptor of the attributes and type information of a property in
/// Objective-C.
internal struct PropertyAttributes {
struct Code {
static let start = Int8(UInt8(ascii: "T"))
static let quote = Int8(UInt8(ascii: "\""))
static let nul = Int8(UInt8(ascii: "\0"))
static let comma = Int8(UInt8(ascii: ","))
struct ContainingType {
static let object = Int8(UInt8(ascii: "@"))
static let block = Int8(UInt8(ascii: "?"))
}
struct Attribute {
static let readonly = Int8(UInt8(ascii: "R"))
static let copy = Int8(UInt8(ascii: "C"))
static let retain = Int8(UInt8(ascii: "&"))
static let nonatomic = Int8(UInt8(ascii: "N"))
static let getter = Int8(UInt8(ascii: "G"))
static let setter = Int8(UInt8(ascii: "S"))
static let dynamic = Int8(UInt8(ascii: "D"))
static let ivar = Int8(UInt8(ascii: "V"))
static let weak = Int8(UInt8(ascii: "W"))
static let collectable = Int8(UInt8(ascii: "P"))
static let oldTypeEncoding = Int8(UInt8(ascii: "t"))
}
}
/// The class of the property.
let objectClass: AnyClass?
/// Indicate whether the property is a weak reference.
let isWeak: Bool
/// Indicate whether the property is an object.
let isObject: Bool
/// Indicate whether the property is a block.
let isBlock: Bool
init(property: objc_property_t) {
guard let attrString = property_getAttributes(property) else {
preconditionFailure("Could not get attribute string from property.")
}
precondition(attrString[0] == Code.start, "Expected attribute string to start with 'T'.")
let typeString = attrString + 1
let _next = NSGetSizeAndAlignment(typeString, nil, nil)
guard _next != typeString else {
let string = String(validatingUTF8: attrString)
preconditionFailure("Could not read past type in attribute string: \(String(describing: string)).")
}
var next = UnsafeMutablePointer<Int8>(mutating: _next)
let typeLength = typeString.distance(to: next)
precondition(typeLength > 0, "Invalid type in attribute string.")
var objectClass: AnyClass? = nil
// if this is an object type, and immediately followed by a quoted string...
if typeString[0] == Code.ContainingType.object && typeString[1] == Code.quote {
// we should be able to extract a class name
let className = typeString + 2;
// fast forward the `next` pointer.
guard let endQuote = strchr(className, Int32(Code.quote)) else {
preconditionFailure("Could not read class name in attribute string.")
}
next = endQuote
if className != UnsafePointer(next) {
let length = className.distance(to: next)
let name = UnsafeMutablePointer<Int8>.allocate(capacity: length + 1)
name.initialize(from: UnsafeMutablePointer<Int8>(mutating: className), count: length)
(name + length).initialize(to: Code.nul)
// attempt to look up the class in the runtime
objectClass = objc_getClass(name) as! AnyClass?
name.deinitialize(count: length + 1)
name.deallocate(capacity: length + 1)
}
}
if next.pointee != Code.nul {
// skip past any junk before the first flag
next = strchr(next, Int32(Code.comma))
}
let emptyString = UnsafeMutablePointer<Int8>.allocate(capacity: 1)
emptyString.initialize(to: Code.nul)
defer {
emptyString.deinitialize()
emptyString.deallocate(capacity: 1)
}
var isWeak = false
while next.pointee == Code.comma {
let flag = next[1]
next += 2
switch flag {
case Code.nul:
break;
case Code.Attribute.readonly:
break;
case Code.Attribute.copy:
break;
case Code.Attribute.retain:
break;
case Code.Attribute.nonatomic:
break;
case Code.Attribute.getter:
fallthrough
case Code.Attribute.setter:
next = strchr(next, Int32(Code.comma)) ?? emptyString
case Code.Attribute.dynamic:
break
case Code.Attribute.ivar:
// assume that the rest of the string (if present) is the ivar name
if next.pointee != Code.nul {
next = emptyString
}
case Code.Attribute.weak:
isWeak = true
case Code.Attribute.collectable:
break
case Code.Attribute.oldTypeEncoding:
let string = String(validatingUTF8: attrString)
assertionFailure("Old-style type encoding is unsupported in attribute string \"\(String(describing: string))\"")
// skip over this type encoding
while next.pointee != Code.comma && next.pointee != Code.nul {
next += 1
}
default:
let pointer = UnsafeMutablePointer<Int8>.allocate(capacity: 2)
pointer.initialize(to: flag)
(pointer + 1).initialize(to: Code.nul)
let flag = String(validatingUTF8: pointer)
let string = String(validatingUTF8: attrString)
preconditionFailure("ERROR: Unrecognized attribute string flag '\(String(describing: flag))' in attribute string \"\(String(describing: string))\".")
}
}
if next.pointee != Code.nul {
let unparsedData = String(validatingUTF8: next)
let string = String(validatingUTF8: attrString)
assertionFailure("Warning: Unparsed data \"\(String(describing: unparsedData))\" in attribute string \"\(String(describing: string))\".")
}
self.objectClass = objectClass
self.isWeak = isWeak
self.isObject = typeString[0] == Code.ContainingType.object
self.isBlock = isObject && typeString[1] == Code.ContainingType.block
}
}
| gpl-3.0 | a0d79d40944f7819f437d90e0f03a6ca | 30.962963 | 153 | 0.698589 | 3.860789 | false | false | false | false |
lanffy/Flying-Swift | test-swift/ViewController.swift | 1 | 1635 | //
// ViewController.swift
// test-swift
//
// Created by Su Wei on 14-6-4.
// Copyright (c) 2014年 OBJCC.COM. All rights reserved.
//
import UIKit
import QuartzCore
class ViewController: UIViewController {
@IBOutlet var swiftImg : UIImageView
@IBOutlet var hiButton : UIButton
@IBAction func hiButtonClicked(sender : AnyObject) {
fly()
hiButton.hidden = true
}
func fly() {
let thePath:CGMutablePathRef = CGPathCreateMutable();
CGPathMoveToPoint(thePath,nil,74.0,74.0);
CGPathAddCurveToPoint(thePath,nil,74.0,300.0,
230.0,300.0,
230.0,74.0);
// Create the animation object, specifying the position property as the key path.
let theAnimation:CAKeyframeAnimation = CAKeyframeAnimation(keyPath: "position");
theAnimation.path=thePath;
theAnimation.duration=5.0;
theAnimation.rotationMode = "auto"
theAnimation.repeatCount = 9999999
theAnimation.delegate = self
// Add the animation to the layer.
swiftImg.layer.addAnimation(theAnimation, forKey:"position");
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool){
hiButton.hidden = false
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
hiButton.setTitle("Click to fly", forState:nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 3ba719a5a83951920e23acad4e8c3094 | 28.160714 | 89 | 0.646663 | 4.626062 | false | false | false | false |
rnystrom/GitHawk | Pods/Apollo/Sources/Apollo/GraphQLSelectionSet.swift | 1 | 3473 | public typealias ResultMap = [String: Any?]
public protocol GraphQLSelectionSet {
static var selections: [GraphQLSelection] { get }
var resultMap: ResultMap { get }
init(unsafeResultMap: ResultMap)
}
public extension GraphQLSelectionSet {
init(jsonObject: JSONObject, variables: GraphQLMap? = nil) throws {
let executor = GraphQLExecutor { object, info in
.result(.success(object[info.responseKeyForField]))
}
executor.shouldComputeCachePath = false
self = try executor.execute(selections: Self.selections, on: jsonObject, variables: variables, accumulator: GraphQLSelectionSetMapper<Self>()).await()
}
var jsonObject: JSONObject {
return resultMap.jsonObject
}
}
extension GraphQLSelectionSet {
public init(_ selectionSet: GraphQLSelectionSet) throws {
try self.init(jsonObject: selectionSet.jsonObject)
}
}
public protocol GraphQLSelection {
}
public struct GraphQLField: GraphQLSelection {
let name: String
let alias: String?
let arguments: [String: GraphQLInputValue]?
var responseKey: String {
return alias ?? name
}
let type: GraphQLOutputType
public init(_ name: String, alias: String? = nil, arguments: [String: GraphQLInputValue]? = nil, type: GraphQLOutputType) {
self.name = name
self.alias = alias
self.arguments = arguments
self.type = type
}
func cacheKey(with variables: [String: JSONEncodable]?) throws -> String {
if let argumentValues = try arguments?.evaluate(with: variables), !argumentValues.isEmpty {
let argumentsKey = orderIndependentKey(for: argumentValues)
return "\(name)(\(argumentsKey))"
} else {
return name
}
}
}
public indirect enum GraphQLOutputType {
case scalar(JSONDecodable.Type)
case object([GraphQLSelection])
case nonNull(GraphQLOutputType)
case list(GraphQLOutputType)
var namedType: GraphQLOutputType {
switch self {
case .nonNull(let innerType), .list(let innerType):
return innerType.namedType
case .scalar, .object:
return self
}
}
}
private func orderIndependentKey(for object: JSONObject) -> String {
return object.sorted { $0.key < $1.key }.map {
if let object = $0.value as? JSONObject {
return "[\($0.key):\(orderIndependentKey(for: object))]"
} else {
return "\($0.key):\($0.value)"
}
}.joined(separator: ",")
}
public struct GraphQLBooleanCondition: GraphQLSelection {
let variableName: String
let inverted: Bool
let selections: [GraphQLSelection]
public init(variableName: String, inverted: Bool, selections: [GraphQLSelection]) {
self.variableName = variableName
self.inverted = inverted;
self.selections = selections;
}
}
public struct GraphQLTypeCondition: GraphQLSelection {
let possibleTypes: [String]
let selections: [GraphQLSelection]
public init(possibleTypes: [String], selections: [GraphQLSelection]) {
self.possibleTypes = possibleTypes
self.selections = selections;
}
}
public struct GraphQLFragmentSpread: GraphQLSelection {
let fragment: GraphQLFragment.Type
public init(_ fragment: GraphQLFragment.Type) {
self.fragment = fragment
}
}
public struct GraphQLTypeCase: GraphQLSelection {
let variants: [String: [GraphQLSelection]]
let `default`: [GraphQLSelection]
public init(variants: [String: [GraphQLSelection]], default: [GraphQLSelection]) {
self.variants = variants
self.default = `default`;
}
}
| mit | 27589a62abb33753b36829a5fbdfd598 | 26.132813 | 154 | 0.707458 | 4.45828 | false | false | false | false |
CCRogerWang/ReactiveWeatherExample | WhatsTheWeatherIn/NSDate+Extensions.swift | 1 | 1405 | //
// NSDate+Extensions.swift
// WhatsTheWeatherIn
//
// Created by Marin Benčević on 16/05/16.
// Copyright © 2016 marinbenc. All rights reserved.
//
import Foundation
extension Date {
///Returns the time of a date formatted as "HH:mm" (e.g. 18:30)
func formattedTime(_ formatter: DateFormatter)-> String {
formatter.setLocalizedDateFormatFromTemplate("HH:mm")
return formatter.string(from: self)
}
///Returns a string in "d M" format, e.g. 19/9 for June 19.
func formattedDay(_ formatter: DateFormatter)-> String {
//the reason formatter is injected is because creating an
//NSDateFormatter instance is pretty expensive
formatter.setLocalizedDateFormatFromTemplate("d M")
return formatter.string(from: self)
}
///Returns the week day of the NSDate, e.g. Sunday.
func dayOfWeek(_ formatter: DateFormatter)-> String {
//the reason formatter is injected is because creating an
//NSDateFormatter instance is pretty expensive
formatter.setLocalizedDateFormatFromTemplate("EEEE")
return formatter.string(from: self)
}
}
//MARK: - Comparable
extension NSDate: Comparable {}
func ==(lhs: NSDate, rhs: NSDate) -> Bool {
return (lhs == rhs)
}
public func <(lhs: NSDate, rhs: NSDate) -> Bool {
return (lhs as NSDate).earlierDate(rhs as Date) == (lhs as Date)
}
| mit | 8df2b0418337a86885892960928c9281 | 28.829787 | 68 | 0.668331 | 4.23565 | false | false | false | false |
GlebRadchenko/AdvertServer | Sources/App/Controllers/BeaconController.swift | 1 | 3825 | //
// BeaconController.swift
// AdvertServer
//
// Created by Gleb Radchenko on 13.11.16.
//
//
import Foundation
import Vapor
import Auth
import Cookies
import HTTP
class BeaconController: DropConfigurable {
weak var drop: Droplet?
required init(with drop: Droplet) {
self.drop = drop
}
func setup() {
guard drop != nil else {
return
}
addBeaconProvider()
addRoutes()
}
private func addBeaconProvider() {
guard let drop = drop else {
return
}
drop.preparations.append(Beacon.self)
}
private func addRoutes() {
guard let drop = drop else {
debugPrint("Drop is nil")
return
}
let beaconsGroup = drop.grouped("beacons")
let authMiddleware = UserAuthorizedMiddleware()
let tokenGroup = beaconsGroup.grouped(authMiddleware)
tokenGroup.get(handler: beaconInfo)
tokenGroup.post(handler: create)
tokenGroup.delete(handler: delete)
}
func beaconInfo(_ req: Request) throws -> ResponseRepresentable {
//receive user with creds
if let user = try req.auth.user() as? User {
do {
let beaconNodes = try user.beacons()
.all()
.map () { (beacon) in
return try beacon.makeNode()
}
let json = try JSON(node: beaconNodes)
return json
} catch {
throw Abort.custom(status: .badRequest, message: error.localizedDescription)
}
}
throw Abort.custom(status: .badRequest, message: "Invalid credentials")
}
func create(_ req: Request) throws -> ResponseRepresentable {
guard let udid = req.data["udid"]?.string,
let major = req.data["major"]?.string,
let minor = req.data["minor"]?.string else {
throw Abort.custom(status: .badRequest, message: "Wrong parameters")
}
do {
var user = try req.auth.user()
if try Beacon.query()
.filter("udid", udid)
.filter("major", major)
.filter("minor", minor)
.all().count != 0 {
throw Abort.custom(status: .conflict, message: "Such beacon already exist")
} else {
var newBeacon = Beacon(udid: udid, major: major, minor: minor)
newBeacon.parentId = user.id
try newBeacon.save()
return try JSON(node: [["error": false,
"message": "Created"],
try newBeacon.makeNode()] )
}
} catch {
throw Abort.custom(status: .badRequest, message: error.localizedDescription)
}
}
func delete(_ req: Request) throws -> ResponseRepresentable {
guard let id = req.data["id"] as? String else {
throw Abort.custom(status: .badRequest, message: "Wrong parameters")
}
do {
if let user = try req.auth.user() as? User {
if let beaconToDelete = try user.beacons().filter("_id", id).first() {
try beaconToDelete.delete()
return try JSON(node: ["error": false,
"message": "Deleting successed"])
} else {
throw Abort.custom(status: .notFound, message: "Cannot find such beacon")
}
} else {
throw Abort.custom(status: .notFound, message: "Cannot find such user")
}
} catch {
throw Abort.custom(status: .notFound, message: error.localizedDescription)
}
}
}
| mit | a69f05a449d2819597c98a012ccca56b | 34.091743 | 93 | 0.521046 | 4.841772 | false | false | false | false |
cdmx/MiniMancera | miniMancera/Model/Option/ReformaCrossing/Node/MOptionReformaCrossingStop.swift | 1 | 1115 | import Foundation
class MOptionReformaCrossingStop:MGameUpdate<MOptionReformaCrossing>
{
weak var view:VOptionReformaCrossingStop?
private var shouldStop:Bool
private var unblockTimeout:TimeInterval?
private let kBlockDuration:TimeInterval = 0.2
override init()
{
shouldStop = false
super.init()
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionReformaCrossing>)
{
if shouldStop
{
if unblockTimeout == nil
{
view?.animateStop()
}
unblockTimeout = elapsedTime + kBlockDuration
shouldStop = false
}
else
{
if let unblockTimeout:TimeInterval = self.unblockTimeout
{
if elapsedTime > unblockTimeout
{
self.unblockTimeout = nil
view?.restoreStand()
}
}
}
}
//MARK: public
func playerStop()
{
shouldStop = true
}
}
| mit | 6b33a6b79590bb77109ab566ceb590a4 | 21.755102 | 68 | 0.526457 | 5.777202 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Pools/PoolsDataSource.swift | 1 | 2912 | //
// PoolsDataSource.swift
// ScoreReporter
//
// Created by Bradley Smith on 9/24/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import Foundation
import CoreData
import ScoreReporterCore
struct PoolSection {
let pool: Pool
let title: String
let standings: [Standing]
init(pool: Pool) {
self.pool = pool
title = pool.name ?? "Pool"
standings = (pool.standings.allObjects as? [Standing] ?? []).sorted(by: { (lhs, rhs) -> Bool in
let leftSortOrder = lhs.sortOrder?.intValue ?? 0
let rightSortOrder = rhs.sortOrder?.intValue ?? 0
if leftSortOrder == rightSortOrder {
return lhs.seed?.intValue ?? 0 < rhs.seed?.intValue ?? 0
}
else {
return leftSortOrder < rightSortOrder
}
})
}
}
class PoolsDataSource: NSObject, DataSource {
typealias ModelType = Standing
fileprivate let fetchedResultsController: NSFetchedResultsController<Pool>
fileprivate var sections = [PoolSection]()
fileprivate(set) dynamic var empty = false
init(group: Group) {
fetchedResultsController = Pool.fetchedPoolsFor(group: group)
super.init()
fetchedResultsController.delegate = self
empty = fetchedResultsController.fetchedObjects?.isEmpty ?? true
configureSections()
}
deinit {
fetchedResultsController.delegate = nil
}
}
// MARK: - Public
extension PoolsDataSource {
func title(for section: Int) -> String? {
guard section < sections.count else {
return nil
}
return sections[section].title
}
func pool(for section: Int) -> Pool? {
guard section < sections.count else {
return nil
}
return sections[section].pool
}
}
// MARK: - Private
private extension PoolsDataSource {
func configureSections() {
let pools = fetchedResultsController.fetchedObjects ?? []
sections = pools.map { PoolSection(pool: $0) }
}
}
// MARK: - DataSource
extension PoolsDataSource {
func numberOfSections() -> Int {
return sections.count
}
func numberOfItems(in section: Int) -> Int {
guard section < sections.count else {
return 0
}
return sections[section].standings.count
}
func item(at indexPath: IndexPath) -> Standing? {
guard indexPath.section < sections.count && indexPath.item < sections[indexPath.section].standings.count else {
return nil
}
return sections[indexPath.section].standings[indexPath.item]
}
}
// MARK: - NSFetchedResultsControllerDelegate
extension PoolsDataSource: NSFetchedResultsControllerDelegate {
func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
configureSections()
}
}
| mit | d8a4ba90b0a827813b9157683180f036 | 23.258333 | 119 | 0.633116 | 4.71799 | false | false | false | false |
DianQK/Flix | Flix/Provider/TableViewEvent.swift | 1 | 1453 | //
// TableViewEvent.swift
// Flix
//
// Created by DianQK on 2018/4/18.
// Copyright © 2018 DianQK. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
public class TableViewEvent<Provider: TableViewMultiNodeProvider> {
public typealias Value = Provider.Value
public typealias EventValue = (tableView: UITableView, indexPath: IndexPath, value: Value)
public var selectedEvent: ControlEvent<()> { return ControlEvent(events: self._itemSelected.map { _ in }) }
public var modelSelected: ControlEvent<Value> { return ControlEvent(events: self.itemSelected.map { $0.value }) }
public var itemSelected: ControlEvent<EventValue> { return ControlEvent(events: self._itemSelected) }
private(set) lazy var _itemSelected = PublishSubject<EventValue>()
public var modelDeselected: ControlEvent<Value> { return ControlEvent(events: self.itemDeselected.map { $0.value }) }
public var itemDeselected: ControlEvent<EventValue> { return ControlEvent(events: self._itemDeselected) }
private(set) lazy var _itemDeselected = PublishSubject<EventValue>()
public typealias MoveEventValue = (tableView: UITableView, sourceIndex: Int, destinationIndex: Int, value: Value)
private(set) lazy var _moveItem = PublishSubject<MoveEventValue>()
private(set) lazy var _itemDeleted = PublishSubject<EventValue>()
private(set) lazy var _itemInserted = PublishSubject<EventValue>()
init() { }
}
| mit | bca33f671c10722218cfcf495b24568e | 35.3 | 121 | 0.741047 | 4.453988 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | TruckMuncher/TruckDetailView.swift | 1 | 6603 | //
// TruckDetailView.swift
// TruckMuncher
//
// Created by Andrew Moore on 1/11/15.
// Copyright (c) 2015 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
import Alamofire
class TruckDetailView: UIView, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var menuTableView: UITableView!
@IBOutlet var truckTagsLabel: UILabel!
@IBOutlet var truckNameLabel: UILabel!
@IBOutlet var truckLogoImage: UIImageView!
@IBOutlet var distanceLabel: UILabel!
@IBOutlet weak var imageWidthConstraint: NSLayoutConstraint!
@IBOutlet var shareButton: UIButton!
let menuManager = MenuManager()
var menu: RMenu?
var textColor = UIColor.blackColor()
var truckId: String!
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
menuTableView.registerNib(UINib(nibName: "MenuItemTableViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: "MenuItemTableViewCellIdentifier")
menuTableView.estimatedRowHeight = 99.0
menuTableView.rowHeight = UITableViewAutomaticDimension
}
func updateViewForNoTruck() {
menu = RMenu()
truckNameLabel.text = "No Trucks Currently Active"
truckLogoImage.image = nil
imageWidthConstraint.constant = 0
let primary = carouselBackground
backgroundColor = primary
textColor = primary.suggestedTextColor()
truckNameLabel.textColor = textColor
truckTagsLabel.textColor = textColor
distanceLabel.textColor = textColor
shareButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
}
func updateViewWithTruck(truck:RTruck!, showingMenu: Bool, showDistance: Bool = true) {
menu = RMenu.objectsWhere("truckId = %@", truck.id).firstObject() as? RMenu
if menu == nil {
menuManager.getMenu(truckId: truck.id, success: { (response) -> () in
self.menu = response as RMenu
self.menuTableView.reloadData()
}) { (error) -> () in
println("error \(error)")
}
} else {
self.menuTableView.reloadData()
}
imageWidthConstraint.constant = 80
truckLogoImage.layer.cornerRadius = truckLogoImage.frame.size.height / 2
truckLogoImage.layer.masksToBounds = true
truckLogoImage.layer.borderWidth = 0
self.getImageForTruck(truck)
self.truckNameLabel.text = truck.name
var keywords = [String]()
for keyword in truck.keywords {
keywords.append((keyword as! RString).value)
}
self.truckTagsLabel.text = join(", ", keywords)
let primary = showingMenu ? UIColor(rgba: truck.primaryColor) : carouselBackground
self.backgroundColor = primary
self.textColor = primary.suggestedTextColor()
self.truckNameLabel.textColor = self.textColor
self.truckTagsLabel.textColor = self.textColor
if truck.latitude == 0 && truck.longitude == 0 {
self.distanceLabel.text = showDistance ? "N/A" : ""
} else {
self.distanceLabel.text = showDistance ? String(format: "%.02f mi", truck.distanceFromMe) : ""
}
self.distanceLabel.textColor = self.textColor
self.truckId = truck.id
shareButton.titleLabel?.font = UIFont(name: "FontAwesome", size: 30)
shareButton.setTitle("\u{f045}", forState: .Normal)
shareButton.setTitleColor(textColor, forState: .Normal)
}
func updateViewWithColor(color: UIColor) {
backgroundColor = color
textColor = color.suggestedTextColor()
truckNameLabel.textColor = textColor
truckTagsLabel.textColor = textColor
distanceLabel.textColor = textColor
shareButton.setTitleColor(textColor, forState: .Normal)
menuTableView.reloadData()
}
func getImageForTruck(truck:RTruck) {
var imgURL: NSURL? = NSURL(string: truck.imageUrl)
self.truckLogoImage.sd_setImageWithURL(imgURL, placeholderImage: nil, completed: { (image, error, type, url) -> Void in
if error == nil {
self.menuTableView.reloadData()
} else {
self.truckLogoImage.image = nil
self.imageWidthConstraint.constant = 0
}
})
}
// MARK - UITableViewDelegate and UITableViewDataSource Methods
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return menu != nil ? Int(menu!.categories.count) : 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("MenuItemTableViewCellIdentifier") as! MenuItemTableViewCell
cell.givenTextColor = textColor
var category = menu!.categories.objectAtIndex(UInt(indexPath.section)) as! RCategory
cell.menuItem = category.menuItems.objectAtIndex(UInt(indexPath.row)) as? RMenuItem
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Int((menu?.categories.objectAtIndex(UInt(section)) as! RCategory).menuItems.count)
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return (menu?.categories.objectAtIndex(UInt(section)) as! RCategory).name
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return MENU_CATEGORY_HEIGHT
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var container = UIView(frame: CGRectMake(0, 0, menuTableView.frame.size.width, MENU_CATEGORY_HEIGHT))
var label = UILabel(frame: CGRectMake(0, 0, menuTableView.frame.size.width, MENU_CATEGORY_HEIGHT))
label.textAlignment = .Center
label.font = UIFont.italicSystemFontOfSize(18.0)
label.backgroundColor = UIColor.clearColor()
label.textColor = textColor
label.text = self.tableView(tableView, titleForHeaderInSection: section)
container.addSubview(label)
return container
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} | gpl-2.0 | 6cc7b0b99fc88ff331a3defe621a893c | 38.309524 | 164 | 0.660306 | 5.032774 | false | false | false | false |
BLSSwiftHackaton2015/TicTacToe | TicTacToe/ViewController.swift | 1 | 5286 | //
// ViewController.swift
// TicTacToe
//
// Created by Robert Kotecki on 13/06/15.
// Copyright (c) 2015 Hackaton. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var board: [Int?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil]
var currentRound = 0;
var moveInfo: MoveInfo?
var gameOver = false;
@IBOutlet var debug: UILabel!
@IBOutlet var gameOverView: UIVisualEffectView!
@IBOutlet var gameOverWinner: UIImageView!
@IBOutlet var btnResetGame: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("handleWatchKitNotification:"), name: "WatchExtensionCom", object: nil)
btnResetGame.layer.cornerRadius = 15
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func hightlightButton(tag: Int, type: Int)
{
var pin : UIImage = UIImage(named: (type == 0 ? "os" : "xs"))!
let btn : UIButton? = self.view.viewWithTag(tag+1) as? UIButton
btn?.setBackgroundImage(pin, forState: UIControlState.Normal)
}
func highlightLine(a: Int, b: Int, c: Int, type: Int)
{
hightlightButton(a, type: type)
hightlightButton(b, type: type)
hightlightButton(c, type: type)
}
func checkLine(a: Int, b: Int, c: Int) -> Int?
{
if( board[a] == nil || board[b] == nil || board[c] == nil)
{
return nil;
}
let sum = board[a]! + board[b]! + board[c]!
switch sum
{
case 0: debug.text = "o win";
case 3: debug.text = "x win";
default: return nil
}
if let moveInfo = moveInfo {
debug.text = "Game Over\n" + debug.text!
highlightLine(a, b: b, c: c, type: sum == 0 ? 0 : 1)
var winnerImage : UIImage = UIImage(named: (sum == 0 ? "os" : "xs"))!
self.gameOverWinner.image = winnerImage;
self.gameOverView.hidden = false;
self.gameOver = true
let move = ["Tag": sum == 0 ? 1000 : 2000]
moveInfo.replyBlock(move)
}
return sum;
}
func checkBoard()
{
// 1,2,3
// 4,5,6
// 7,8,9
// 1,4,7
// 2,5,8
// 3,6,9
// 1,5,9
// 3,5,7
checkLine(0, b: 1, c: 2)
checkLine(3, b: 4, c: 5)
checkLine(6, b: 7, c: 8)
checkLine(0, b: 3, c: 6)
checkLine(1, b: 4, c: 7)
checkLine(2, b: 5, c: 8)
checkLine(0, b: 4, c: 8)
checkLine(2, b: 4, c: 6)
}
func handleWatchKitNotification(notification: NSNotification)
{
if let userInfo = notification.object as? MoveInfo {
debug.text = String(userInfo.position!)
let btnTag : Int = userInfo.position! + 1 //
let btn : UIButton? = self.view.viewWithTag(btnTag) as? UIButton
btn?.setBackgroundImage(UIImage(named: "o"), forState: UIControlState.Normal)
board[userInfo.position!] = 0;
currentRound = 1;
debug.text = "You turn"
self.moveInfo = userInfo
checkBoard()
}
}
@IBAction func touchBoard(sender: AnyObject) {
if(gameOver)
{
return
}
if(currentRound == 0)
{
debug.text = "Opponent turn"
return
}
println("tag \(sender.tag)");
let btn : UIButton? = self.view.viewWithTag(sender.tag) as? UIButton
let boardTag = sender.tag - 1
if(board[boardTag] == nil)
{
board[boardTag] = 1;
btn?.setBackgroundImage(UIImage(named: "x"), forState: UIControlState.Normal)
}
currentRound = 0
debug.text = "Opponent turn"
if let moveInfo = moveInfo {
let move = ["Tag": boardTag]
moveInfo.replyBlock(move)
}
checkBoard()
}
@IBAction func actionResetGame(sender: AnyObject) {
// reset game
gameOverView.hidden = true;
for(var i = 0; i < 9; i++)
{
board[i] = nil;
let btn : UIButton? = self.view.viewWithTag(i+1) as? UIButton
btn?.setBackgroundImage(UIImage(named: "empty"), forState: UIControlState.Normal)
}
if let moveInfo = moveInfo {
let move = ["Tag": 9999]
moveInfo.replyBlock(move)
}
debug.text = "Opponent turn"
currentRound = 0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | 38639b21651cd2ca930e1c55fd7271f3 | 24.911765 | 153 | 0.496216 | 4.297561 | false | false | false | false |
mpclarkson/vapor | Sources/Vapor/Response/Response.swift | 1 | 3745 | import libc
extension Response {
/**
Convenience Initializer Error
Will return 500
- parameter error: a description of the server error
*/
public init(error: String) {
self.init(status: .internalServerError, headers: [:], body: error.data)
}
/**
Convenience Initializer - Html
- parameter status: http status of response
- parameter html: the html string to be rendered as a response
*/
public init(status: Status, html body: String) {
let html = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
let headers: Headers = [
"Content-Type": "text/html"
]
self.init(status: status, headers: headers, body: html.data)
}
/**
Convenience Initializer - Data
- parameter status: http status
- parameter data: response bytes
*/
public init(status: Status, data: Data) {
self.init(status: status, headers: [:], body: data)
}
/**
Convenience Initializer - Text
- parameter status: http status
- parameter text: basic text response
*/
public init(status: Status, text: String) {
let headers: Headers = [
"Content-Type": "text/plain"
]
self.init(status: status, headers: headers, body: text.data)
}
/**
Convenience Initializer
- parameter status: the http status
- parameter json: any value that will be attempted to be serialized as json. Use 'Json' for more complex objects
*/
public init(status: Status, json: Json) {
let headers: Headers = [
"Content-Type": "application/json"
]
self.init(status: status, headers: headers, body: json.data)
}
/**
Creates an empty response with the
supplied status code.
*/
public init(status: Status) {
self.init(status: status, text: "")
}
public init(redirect location: String) {
let headers: Headers = [
"Location": Headers.Values(location)
]
self.init(status: .movedPermanently, headers: headers, body: [])
}
public init(async closure: Stream throws -> Void) {
self.init(status: .ok, headers: [:], body: closure)
}
public static var date: String {
let DAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
let MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
let RFC1123_TIME_LEN = 29
var t: time_t = 0
var tm: libc.tm = libc.tm()
let buf = UnsafeMutablePointer<Int8>.init(allocatingCapacity: RFC1123_TIME_LEN + 1)
time(&t)
gmtime_r(&t, &tm)
strftime(buf, RFC1123_TIME_LEN+1, "---, %d --- %Y %H:%M:%S GMT", &tm)
memcpy(buf, DAY_NAMES[Int(tm.tm_wday)], 3)
memcpy(buf+8, MONTH_NAMES[Int(tm.tm_mon)], 3)
return String(pointer: buf, length: RFC1123_TIME_LEN + 1) ?? ""
}
public var cookies: [String: String] {
get {
var cookies: [String: String] = [:]
for value in headers["Set-Cookie"] {
for cookie in value.split(";") {
var parts = cookie.split("=")
if parts.count >= 2 {
cookies[parts[0]] = parts[1]
}
}
}
return cookies
}
set(newCookies) {
var cookies: [String] = []
for (key, value) in newCookies {
cookies.append("\(key)=\(value)")
}
headers["Set-Cookie"] = Headers.Value(cookies.joined(separator: ";"))
}
}
}
| mit | 83e936f14390801bd8e143b5ee2a87dd | 27.371212 | 121 | 0.533778 | 4.119912 | false | false | false | false |
auth0-tutorials/mvvm_viper | VIPER Contacts Final/VIPER Contacts Final/ContactList/WireFrame/ContactListWireFrame.swift | 1 | 1624 | import UIKit
class ContactListWireFrame: ContactListWireFrameProtocol {
class func createContactListModule() -> UIViewController {
let navController = mainStoryboard.instantiateViewController(withIdentifier: "ContactsNavigationController")
if let view = navController.childViewControllers.first as? ContactListView {
let presenter: ContactListPresenterProtocol & ContactListInteractorOutputProtocol = ContactListPresenter()
let interactor: ContactListInteractorInputProtocol = ContactListInteractor()
let localDataManager: ContactListLocalDataManagerInputProtocol = ContactListLocalDataManager()
let wireFrame: ContactListWireFrameProtocol = ContactListWireFrame()
view.presenter = presenter
presenter.view = view
presenter.wireFrame = wireFrame
presenter.interactor = interactor
interactor.presenter = presenter
interactor.localDatamanager = localDataManager
return navController
}
return UIViewController()
}
static var mainStoryboard: UIStoryboard {
return UIStoryboard(name: "Main", bundle: Bundle.main)
}
func presentAddContactScreen(from view: ContactListViewProtocol) {
guard let delegate = view.presenter as? AddModuleDelegate else {
return
}
let addContactsView = AddContactWireFrame.createAddContactModule(with: delegate)
if let sourceView = view as? UIViewController {
sourceView.present(addContactsView, animated: true, completion: nil)
}
}
}
| mit | 629d67564f23625d32adadc3d9ee050e | 38.609756 | 118 | 0.705665 | 6.27027 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Post/HomepageEditorNavigationBarManager.swift | 1 | 2319 | import Foundation
protocol HomepageEditorNavigationBarManagerDelegate: PostEditorNavigationBarManagerDelegate {
var continueButtonText: String { get }
func navigationBarManager(_ manager: HomepageEditorNavigationBarManager, continueWasPressed sender: UIButton)
}
class HomepageEditorNavigationBarManager: PostEditorNavigationBarManager {
weak var homepageEditorNavigationBarManagerDelegate: HomepageEditorNavigationBarManagerDelegate?
override weak var delegate: PostEditorNavigationBarManagerDelegate? {
get {
return homepageEditorNavigationBarManagerDelegate
}
set {
if let newDelegate = newValue {
if let newHomepageDelegate = newDelegate as? HomepageEditorNavigationBarManagerDelegate {
homepageEditorNavigationBarManagerDelegate = newHomepageDelegate
} else {
// This should not happen, but fail fast in case
fatalError("homepageEditorNavigationBarManagerDelegate must be of type HomepageEditorNavigationBarManagerDelegate?")
}
} else {
homepageEditorNavigationBarManagerDelegate = nil
}
}
}
/// Continue Button
private(set) lazy var continueButton: UIButton = {
let button = UIButton(type: .system)
button.addTarget(self, action: #selector(continueButtonTapped(sender:)), for: .touchUpInside)
button.setTitle(homepageEditorNavigationBarManagerDelegate?.continueButtonText ?? "", for: .normal)
button.sizeToFit()
button.isEnabled = true
button.setContentHuggingPriority(.required, for: .horizontal)
return button
}()
/// Continue Button
private(set) lazy var continueBarButtonItem: UIBarButtonItem = {
let button = UIBarButtonItem(customView: self.continueButton)
return button
}()
@objc private func continueButtonTapped(sender: UIButton) {
homepageEditorNavigationBarManagerDelegate?.navigationBarManager(self, continueWasPressed: sender)
}
override var leftBarButtonItems: [UIBarButtonItem] {
return []
}
override var rightBarButtonItems: [UIBarButtonItem] {
return [moreBarButtonItem, continueBarButtonItem, separatorButtonItem]
}
}
| gpl-2.0 | 37ffd44cc299b3b5e9f6afc9383061b0 | 38.982759 | 136 | 0.702458 | 6.118734 | false | false | false | false |
CosynPa/TZStackView | TZStackView/TZStackView.swift | 1 | 42916 | //
// TZStackView.swift
// TZStackView
//
// Created by Tom van Zummeren on 10/06/15.
// Copyright © 2015 Tom van Zummeren. All rights reserved.
//
import UIKit
private func constraintIsAutoGenerated(constraint: NSLayoutConstraint) -> Bool {
let autoGenerated = constraint.identifier?.hasPrefix("IB auto generated") == true
|| String(constraint.dynamicType).rangeOfString("Prototyping") != nil
return autoGenerated
}
private func constraintContains(view: UIView) -> (NSLayoutConstraint) -> Bool {
return { ($0.firstItem as? UIView) == view || ($0.secondItem as? UIView) == view }
}
@inline(__always) private func compose<T>(first: (T) -> Bool, _ second: (T) -> Bool) -> (T) -> Bool {
return { first($0) && second($0) }
}
@inline(__always) private func negate<T>(predicate: (T) -> Bool) -> (T) -> Bool {
return { !predicate($0) }
}
@IBDesignable
public class TZStackView: UIView {
public var distribution: TZStackViewDistribution = .Fill {
didSet {
setNeedsUpdateConstraints()
}
}
public var axis: UILayoutConstraintAxis = .Horizontal {
didSet {
setNeedsUpdateConstraints()
}
}
public var alignment: TZStackViewAlignment = .Fill {
didSet {
setNeedsUpdateConstraints()
}
}
@objc @IBInspectable private var axisValue: Int {
get {
return axis.rawValue
}
set {
axis = UILayoutConstraintAxis(rawValue: newValue) ?? .Horizontal
}
}
@objc @IBInspectable private var alignmentValue: Int {
get {
return alignment.rawValue
}
set {
alignment = TZStackViewAlignment(rawValue: newValue) ?? .Fill
}
}
@objc @IBInspectable private var distributionValue: Int {
get {
return distribution.rawValue
}
set {
distribution = TZStackViewDistribution(rawValue: newValue) ?? .Fill
}
}
@objc @IBInspectable public var spacing: CGFloat = 0 {
didSet {
setNeedsUpdateConstraints()
}
}
@objc @IBInspectable public var layoutMarginsRelativeArrangement: Bool = false {
didSet {
setNeedsUpdateConstraints()
}
}
override public var layoutMargins: UIEdgeInsets {
get {
if #available(iOS 8, *) {
return super.layoutMargins
} else {
return _layoutMargins
}
}
set {
if #available(iOS 8, *) {
super.layoutMargins = newValue
} else {
_layoutMargins = newValue
setNeedsUpdateConstraints()
}
}
}
private var _layoutMargins = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
public private(set) var arrangedSubviews: [UIView] = [] {
didSet {
setNeedsUpdateConstraints()
registerHiddenListeners(oldValue)
}
}
private var kvoContext = UInt8()
private var stackViewConstraints = [NSLayoutConstraint]()
private var subviewConstraints = [NSLayoutConstraint]()
private var layoutMarginsView: _TZSpacerView?
private var alignmentSpanner: _TZSpacerView?
private var orderingSpanner: _TZSpacerView?
private var distributionSpacers: [_TZSpacerView] = []
private var registeredKvoSubviews = [UIView]()
private var animatingToHiddenViews = [UIView]()
public convenience init() {
self.init(arrangedSubviews: [])
}
public init(arrangedSubviews: [UIView]) {
super.init(frame: CGRectZero)
commonInit(arrangedSubviews)
}
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit([])
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
commonInit([])
}
private func commonInit(arrangedSubviews: [UIView]) {
for arrangedSubview in arrangedSubviews {
arrangedSubview.translatesAutoresizingMaskIntoConstraints = false
addSubview(arrangedSubview)
}
// Closure to invoke didSet()
{ self.arrangedSubviews = arrangedSubviews }()
}
deinit {
// This removes `hidden` value KVO observers using didSet()
{ self.arrangedSubviews = [] }()
}
override public func awakeFromNib() {
super.awakeFromNib()
// a hack, remove Interface Builder generated constraints that are not created by you
removeConstraints(constraints.filter(constraintIsAutoGenerated))
for aView in subviews {
addArrangedSubview(aView)
}
}
override public func prepareForInterfaceBuilder() {
if #available(iOS 8.0, *) {
super.prepareForInterfaceBuilder()
for aView in subviews {
addArrangedSubview(aView)
}
}
}
private func registerHiddenListeners(previousArrangedSubviews: [UIView]) {
for subview in previousArrangedSubviews {
self.removeHiddenListener(subview)
}
for subview in arrangedSubviews {
self.addHiddenListener(subview)
}
}
private func addHiddenListener(view: UIView) {
view.addObserver(self, forKeyPath: "hidden", options: [.New], context: &kvoContext)
registeredKvoSubviews.append(view)
}
private func removeHiddenListener(view: UIView) {
if let index = registeredKvoSubviews.indexOf(view) {
view.removeObserver(self, forKeyPath: "hidden", context: &kvoContext)
registeredKvoSubviews.removeAtIndex(index)
}
}
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if let view = object as? UIView where keyPath == "hidden" {
let hiddenCallbackKey = "TZSV-hidden-callback"
let hidden = view.hidden
let previouseKeys = Set(view.layer.animationKeys() ?? [])
if let callbackAnimation = view.layer.animationForKey(hiddenCallbackKey) {
(callbackAnimation.delegate as! TZFuncAnimationDelegate).cancel(callbackAnimation)
view.layer.removeAnimationForKey(hiddenCallbackKey)
}
// Canceling the previouse callback will reset the hidden property, so we set it back without triggering KVO
view.layer.hidden = hidden
if hidden {
animatingToHiddenViews.append(view)
}
// Perform the animation
setNeedsUpdateConstraints()
setNeedsLayout()
layoutIfNeeded()
let afterKeys = Set(view.layer.animationKeys() ?? [])
let addedKeys = afterKeys.subtract(previouseKeys)
view.layer.hidden = false // This will set view.hidden without triggering KVO
let animationFinishFunc = { [weak self, weak view] () in
view?.layer.hidden = hidden
if let selv = self, strongView = view {
if let index = selv.animatingToHiddenViews.indexOf(strongView) {
selv.animatingToHiddenViews.removeAtIndex(index)
}
}
}
// Try to find the animation object associated with the hidding process.
if let hidingAnimation = addedKeys.first.flatMap({ key in view.layer.animationForKey(key)}) {
let callbackAnimation = CAAnimationGroup()
callbackAnimation.animations = []
callbackAnimation.delegate = TZFuncAnimationDelegate { _ in
animationFinishFunc()
}
animation(callbackAnimation, copyTimingFrom: hidingAnimation, superLayer: view.layer)
view.layer.addAnimation(callbackAnimation, forKey: hiddenCallbackKey)
} else {
animationFinishFunc()
}
}
}
private func animation(animation: CAAnimation, copyTimingFrom other: CAAnimation, superLayer: CALayer) {
// 1. When a CAAnimation is added to a layer, its beginTime will be adjusted to current time if its beginTime is 0.
// 2. The beginTime of the animation objects added by the system, is the block animation's delay time. So if it's non zero, it should be converted to the layer's time space
animation.beginTime = other.beginTime == 0 ? 0 : superLayer.convertTime(CACurrentMediaTime(), fromLayer: nil) + other.beginTime
animation.duration = other.duration
animation.speed = other.speed
animation.timeOffset = other.timeOffset
animation.repeatCount = other.repeatCount
animation.repeatDuration = other.repeatDuration
animation.autoreverses = other.autoreverses
animation.fillMode = other.fillMode
}
public func addArrangedSubview(view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
view.removeConstraints(view.constraints.filter(constraintIsAutoGenerated))
addSubview(view)
arrangedSubviews.append(view)
}
public func removeArrangedSubview(view: UIView) {
if let index = arrangedSubviews.indexOf(view) {
arrangedSubviews.removeAtIndex(index)
}
}
public func insertArrangedSubview(view: UIView, atIndex stackIndex: Int) {
view.translatesAutoresizingMaskIntoConstraints = false
view.removeConstraints(view.constraints.filter(constraintIsAutoGenerated))
addSubview(view)
arrangedSubviews.insert(view, atIndex: stackIndex)
}
override public func willRemoveSubview(subview: UIView) {
removeArrangedSubview(subview)
}
public override func addConstraint(constraint: NSLayoutConstraint) {
if !constraintIsAutoGenerated(constraint) {
super.addConstraint(constraint)
}
}
public override func addConstraints(constraints: [NSLayoutConstraint]) {
super.addConstraints(constraints.filter(negate(constraintIsAutoGenerated)))
}
override public func updateConstraints() {
removeConstraints(constraints.filter(constraintIsAutoGenerated))
if let superview = superview where superview.constraints.count > 0 {
superview.removeConstraints(superview.constraints.filter(compose(constraintIsAutoGenerated, constraintContains(self))))
}
removeConstraints(stackViewConstraints)
stackViewConstraints.removeAll()
for arrangedSubview in arrangedSubviews {
arrangedSubview.removeConstraints(subviewConstraints)
}
subviewConstraints.removeAll()
if let spacerView = layoutMarginsView {
spacerView.removeFromSuperview()
layoutMarginsView = nil
}
if let spacerView = alignmentSpanner {
spacerView.removeFromSuperview()
alignmentSpanner = nil
}
if let spacerView = orderingSpanner {
spacerView.removeFromSuperview()
orderingSpanner = nil
}
for spacerView in distributionSpacers {
spacerView.removeFromSuperview()
}
distributionSpacers.removeAll()
for arrangedSubview in arrangedSubviews {
if alignment != .Fill {
let guideConstraint: NSLayoutConstraint
switch axis {
case .Horizontal:
guideConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25)
case .Vertical:
guideConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 25)
}
guideConstraint.identifier = "TZSV-ambiguity-suppression"
subviewConstraints.append(guideConstraint)
arrangedSubview.addConstraint(guideConstraint)
}
if isHidden(arrangedSubview) {
let hiddenConstraint: NSLayoutConstraint
switch axis {
case .Horizontal:
hiddenConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, constant: 0)
case .Vertical:
hiddenConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, constant: 0)
}
hiddenConstraint.identifier = "TZSV-hiding"
subviewConstraints.append(hiddenConstraint)
arrangedSubview.addConstraint(hiddenConstraint)
}
}
if arrangedSubviews.count > 0 {
if layoutMarginsRelativeArrangement {
layoutMarginsView = addSpacerView("TZViewLayoutMarginsGuide")
}
if alignment != .Fill || areAllViewsHidden() {
alignmentSpanner = addSpacerView("TZSV-alignment-spanner")
}
if areAllViewsHidden() {
orderingSpanner = addSpacerView("TZSV-ordering-spanner")
}
stackViewConstraints += createMatchEdgesContraints(arrangedSubviews)
stackViewConstraints += createFirstAndLastViewMatchEdgesContraints()
stackViewConstraints += createCanvasFitConstraints()
let visibleArrangedSubviews = arrangedSubviews.filter({!self.isHidden($0)})
switch distribution {
case .FillEqually, .Fill, .FillProportionally:
if distribution == .FillEqually {
stackViewConstraints += createFillEquallyConstraints(arrangedSubviews, identifier: "TZSV-fill-equally")
}
if distribution == .FillProportionally {
let (someStackViewConstraints, someSubviewConstraints) = createFillProportionallyConstraints(arrangedSubviews)
stackViewConstraints += someStackViewConstraints
for (owningView, constraints) in someSubviewConstraints {
owningView.addConstraints(constraints)
subviewConstraints += constraints
}
}
stackViewConstraints += createFillConstraints(arrangedSubviews, constant: spacing, identifier: "TZSV-spacing")
case .EqualSpacing:
var views = [UIView]()
for (index, arrangedSubview) in arrangedSubviews.filter({ !isHidden($0) }).enumerate() {
if index > 0 {
let spacerView = addSpacerView("TZSV-distributing")
distributionSpacers.append(spacerView)
views.append(spacerView)
}
views.append(arrangedSubview)
}
stackViewConstraints += createFillConstraints(views, constant: 0, identifier: "TZSV-distributing-edge")
stackViewConstraints += createFillEquallyConstraints(distributionSpacers, identifier: "TZSV-fill-equally")
stackViewConstraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing, identifier: "TZSV-spacing")
case .EqualCentering:
for (index, _) in visibleArrangedSubviews.enumerate() {
if index > 0 {
distributionSpacers.append(addSpacerView("TZSV-distributing"))
}
}
stackViewConstraints += createEqualCenteringConstraints(arrangedSubviews)
}
if let spanner = alignmentSpanner {
stackViewConstraints += createSurroundingSpacerViewConstraints(spanner, views: visibleArrangedSubviews)
}
if let layoutMarginsView = layoutMarginsView {
let bottomConstraint: NSLayoutConstraint
let leftConstraint: NSLayoutConstraint
let rightConstraint: NSLayoutConstraint
let topConstraint: NSLayoutConstraint
if #available(iOS 8.0, *) {
bottomConstraint = constraint(item: self, attribute: .BottomMargin, toItem: layoutMarginsView, attribute: .Bottom)
leftConstraint = constraint(item: self, attribute: .LeftMargin, toItem: layoutMarginsView, attribute: .Left)
rightConstraint = constraint(item: self, attribute: .RightMargin, toItem: layoutMarginsView, attribute: .Right)
topConstraint = constraint(item: self, attribute: .TopMargin, toItem: layoutMarginsView, attribute: .Top)
} else {
bottomConstraint = constraint(item: self, attribute: .Bottom, toItem: layoutMarginsView, attribute: .Bottom, constant: _layoutMargins.bottom)
leftConstraint = constraint(item: self, attribute: .Left, toItem: layoutMarginsView, attribute: .Left, constant: -_layoutMargins.left)
rightConstraint = constraint(item: self, attribute: .Right, toItem: layoutMarginsView, attribute: .Right, constant: _layoutMargins.right)
topConstraint = constraint(item: self, attribute: .Top, toItem: layoutMarginsView, attribute: .Top, constant: -_layoutMargins.top)
}
bottomConstraint.identifier = "TZView-bottomMargin-guide-constraint"
leftConstraint.identifier = "TZView-leftMargin-guide-constraint"
rightConstraint.identifier = "TZView-rightMargin-guide-constraint"
topConstraint.identifier = "TZView-topMargin-guide-constraint"
stackViewConstraints += [bottomConstraint, leftConstraint, rightConstraint, topConstraint]
}
if axis == .Horizontal {
switch distribution {
case .Fill, .EqualSpacing, .EqualCentering:
let totalVisible = visibleArrangedSubviews.count
let multilineLabels = arrangedSubviews.filter { view in
isMultilineLabel(view)
}
if totalVisible > 0 {
let totalSpacing = spacing * CGFloat(totalVisible - 1)
let ratio = CGFloat(1) / CGFloat(totalVisible)
let decrease = totalSpacing / CGFloat(totalVisible)
let edgeItem = layoutMarginsView ?? self
for label in multilineLabels {
stackViewConstraints.append(constraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: edgeItem, attribute: .Width, multiplier: ratio, constant: -decrease, priority: 760, identifier: "TZSV-text-width-disambiguation"))
}
} else {
for label in multilineLabels {
let aConstraint = constraint(item: label, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 760, identifier: "TZSV-text-width-disambiguation")
subviewConstraints.append(aConstraint)
label.addConstraint(aConstraint)
}
}
case .FillEqually, .FillProportionally:
break
}
}
addConstraints(stackViewConstraints)
}
super.updateConstraints()
}
private func addSpacerView(identifier: String = "") -> _TZSpacerView {
let spacerView = _TZSpacerView()
spacerView.translatesAutoresizingMaskIntoConstraints = false
spacerView.identifier = identifier
insertSubview(spacerView, atIndex: 0)
return spacerView
}
private func createCanvasFitConstraints() -> [NSLayoutConstraint] {
func widthFitConstraint() -> NSLayoutConstraint {
return constraint(item: self, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 49, identifier: "TZSV-canvas-fit")
}
func heightFitConstraint() -> NSLayoutConstraint {
return constraint(item: self, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 49, identifier: "TZSV-canvas-fit")
}
var result = [NSLayoutConstraint]()
let baselineAlignment = (alignment == .FirstBaseline || alignment == .LastBaseline) && axis == .Horizontal
if baselineAlignment && !areAllViewsHidden() {
result.append(heightFitConstraint())
}
switch distribution {
case .FillEqually, .Fill, .FillProportionally:
break
case .EqualSpacing, .EqualCentering:
switch axis {
case .Horizontal:
result.append(widthFitConstraint())
case .Vertical:
result.append(heightFitConstraint())
}
}
return result
}
private func createSurroundingSpacerViewConstraints(spacerView: UIView, views: [UIView]) -> [NSLayoutConstraint] {
if alignment == .Fill {
return []
}
var topPriority: UILayoutPriority = 1000
var topRelation: NSLayoutRelation = .LessThanOrEqual
var bottomPriority: UILayoutPriority = 1000
var bottomRelation: NSLayoutRelation = .GreaterThanOrEqual
if alignment == .Top || alignment == .Leading {
topPriority = 999.5
topRelation = .Equal
}
if alignment == .Bottom || alignment == .Trailing {
bottomPriority = 999.5
bottomRelation = .Equal
}
var constraints = [NSLayoutConstraint]()
for view in views {
switch axis {
case .Horizontal:
constraints.append(constraint(item: spacerView, attribute: .Top, relatedBy: topRelation, toItem: view, priority: topPriority, identifier: "TZSV-spanning-boundary"))
constraints.append(constraint(item: spacerView, attribute: .Bottom, relatedBy: bottomRelation, toItem: view, priority: bottomPriority, identifier: "TZSV-spanning-boundary"))
case .Vertical:
constraints.append(constraint(item: spacerView, attribute: .Leading, relatedBy: topRelation, toItem: view, priority: topPriority, identifier: "TZSV-spanning-boundary"))
constraints.append(constraint(item: spacerView, attribute: .Trailing, relatedBy: bottomRelation, toItem: view, priority: bottomPriority, identifier: "TZSV-spanning-boundary"))
}
}
switch axis {
case .Horizontal:
constraints.append(constraint(item: spacerView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51, identifier: "TZSV-spanning-fit"))
case .Vertical:
constraints.append(constraint(item: spacerView, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, constant: 0, priority: 51, identifier: "TZSV-spanning-fit"))
}
return constraints
}
private func createFillProportionallyConstraints(views: [UIView]) -> (stackViewConstraints: [NSLayoutConstraint], subviewConstraints: [(owningView: UIView, [NSLayoutConstraint])]) {
func intrinsicContentLengthOf(view: UIView) -> CGFloat {
let size = view.intrinsicContentSize()
switch axis {
case .Horizontal:
if let label = view as? UILabel where label.numberOfLines != 1 { // multiline label
return 0
} else {
return size.width != UIViewNoIntrinsicMetric ? size.width : 0
}
case .Vertical:
return size.height != UIViewNoIntrinsicMetric ? size.height : 0
}
}
let nonHiddenViews = views.filter { view in
return !isHidden(view)
}
if nonHiddenViews.count == 0 {
return ([], [])
}
let numberOfHiddenViews = views.count - nonHiddenViews.count
let totalViewLength = nonHiddenViews
.map { view in
intrinsicContentLengthOf(view)
}
.reduce(CGFloat(0), combine: +)
let showingTotalIsSmall: Bool
if numberOfHiddenViews == 0 {
switch nonHiddenViews.count {
case 0: // not possible
showingTotalIsSmall = false
case 1:
let view = nonHiddenViews[0]
showingTotalIsSmall = intrinsicContentLengthOf(view) <= 1
default:
showingTotalIsSmall = totalViewLength == 0
}
} else {
showingTotalIsSmall = totalViewLength <= spacing * CGFloat(numberOfHiddenViews)
}
if showingTotalIsSmall {
return (stackViewConstraints: createFillEquallyConstraints(nonHiddenViews, identifier: "TZSV-fill-equally"), subviewConstraints: [])
}
var stackViewConstraints = [NSLayoutConstraint]()
var subviewConstraints = [(owningView: UIView, [NSLayoutConstraint])]()
let totalSpacing = CGFloat(nonHiddenViews.count - 1) * spacing
let totalSize = totalViewLength + totalSpacing
var priority: UILayoutPriority = 1000
let countDownPriority = nonHiddenViews.count > 1
for arrangedSubview in views {
if countDownPriority {
priority -= 1
}
if isHidden(arrangedSubview) {
continue
}
let length = intrinsicContentLengthOf(arrangedSubview)
if length == 0 {
let theConstraint: NSLayoutConstraint
switch axis {
case .Horizontal:
theConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: nil, attribute: .NotAnAttribute, priority: 1000, constant: 0)
case .Vertical:
theConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: nil, attribute: .NotAnAttribute, priority: 1000, constant: 0)
}
theConstraint.identifier = "TZSV-fill-proportionally"
subviewConstraints.append((owningView: arrangedSubview, [theConstraint]))
} else {
// totalSize can't be zero, since nonHiddenViews.count != 0
let multiplier = length / totalSize
let theConstraint: NSLayoutConstraint
switch axis {
case .Horizontal:
theConstraint = constraint(item: arrangedSubview, attribute: .Width, toItem: self, multiplier: multiplier, priority: priority)
case .Vertical:
theConstraint = constraint(item: arrangedSubview, attribute: .Height, toItem: self, multiplier: multiplier, priority: priority)
}
theConstraint.identifier = "TZSV-fill-proportionally"
stackViewConstraints.append(theConstraint)
}
}
return (stackViewConstraints, subviewConstraints)
}
// Matchs all Width or Height attributes of all given views
private func createFillEquallyConstraints(views: [UIView], identifier: String, priority: UILayoutPriority = 1000) -> [NSLayoutConstraint] {
let constraints: [NSLayoutConstraint]
switch axis {
case .Horizontal:
constraints = equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Width, priority: priority)
case .Vertical:
constraints = equalAttributes(views: views.filter({ !self.isHidden($0) }), attribute: .Height, priority: priority)
}
constraints.forEach { $0.identifier = identifier }
return constraints
}
// Chains together the given views using Leading/Trailing or Top/Bottom
private func createFillConstraints(views: [UIView], priority: UILayoutPriority = 1000, relatedBy relation: NSLayoutRelation = .Equal, constant: CGFloat, identifier: String) -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
var previousView: UIView?
for view in views {
if let previousView = previousView {
var c: CGFloat = 0
if !isHidden(previousView) && !isHidden(view) {
c = constant
} else if isHidden(previousView) && !isHidden(view) && views.first != previousView {
c = (constant / 2)
} else if isHidden(view) && !isHidden(previousView) && views.last != view {
c = (constant / 2)
}
switch axis {
case .Horizontal:
constraints.append(constraint(item: view, attribute: .Leading, relatedBy: relation, toItem: previousView, attribute: .Trailing, constant: c, priority: priority))
case .Vertical:
constraints.append(constraint(item: view, attribute: .Top, relatedBy: relation, toItem: previousView, attribute: .Bottom, constant: c, priority: priority))
}
}
previousView = view
}
constraints.forEach { $0.identifier = identifier }
return constraints
}
private func createEqualCenteringConstraints(views: [UIView]) -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
let visibleViewsWithIndex = views.enumerate().filter { (_, view) in !isHidden(view) }
for enumerationIndex in visibleViewsWithIndex.indices.dropFirst() {
let spacerView = distributionSpacers[enumerationIndex - 1]
let previouseView = visibleViewsWithIndex[enumerationIndex - 1].1
let view = visibleViewsWithIndex[enumerationIndex].1
switch axis {
case .Horizontal:
constraints.append(constraint(item: previouseView, attribute: .CenterX, toItem: spacerView, attribute: .Leading, identifier: "TZSV-distributing-edge"))
constraints.append(constraint(item: view, attribute: .CenterX, toItem: spacerView, attribute: .Trailing, identifier: "TZSV-distributing-edge"))
case .Vertical:
constraints.append(constraint(item: previouseView, attribute: .CenterY, toItem: spacerView, attribute: .Top, identifier: "TZSV-distributing-edge"))
constraints.append(constraint(item: view, attribute: .CenterY, toItem: spacerView, attribute: .Bottom, identifier: "TZSV-distributing-edge"))
}
}
if let firstSpacerView = distributionSpacers.first {
for enumerationIndex in visibleViewsWithIndex.indices.dropFirst(2) {
let spacerView = distributionSpacers[enumerationIndex - 1]
let viewIndex = visibleViewsWithIndex[enumerationIndex - 1].0
let attribute: NSLayoutAttribute
switch axis {
case .Horizontal:
attribute = .Width
case .Vertical:
attribute = .Height
}
let aConstraint = constraint(item: firstSpacerView, attribute: attribute, toItem: spacerView, attribute: attribute, priority: 150 - UILayoutPriority(viewIndex), identifier: "TZSV-fill-equally")
constraints.append(aConstraint)
}
}
constraints += createFillConstraints(arrangedSubviews, relatedBy: .GreaterThanOrEqual, constant: spacing, identifier: "TZSV-spacing")
return constraints
}
// Matches all Bottom/Top or Leading Trailing constraints of te given views and matches those attributes of the first/last view to the container
private func createMatchEdgesContraints(views: [UIView]) -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
switch axis {
case .Horizontal:
switch alignment {
case .Fill:
constraints += equalAttributes(views: views, attribute: .Bottom)
constraints += equalAttributes(views: views, attribute: .Top)
case .Center:
constraints += equalAttributes(views: views, attribute: .CenterY)
case .Leading:
constraints += equalAttributes(views: views, attribute: .Top)
case .Trailing:
constraints += equalAttributes(views: views, attribute: .Bottom)
case .FirstBaseline:
if #available(iOS 8.0, *) {
constraints += equalAttributes(views: views, attribute: .FirstBaseline)
}
case .LastBaseline:
constraints += equalAttributes(views: views, attribute: .Baseline)
}
case .Vertical:
switch alignment {
case .Fill:
constraints += equalAttributes(views: views, attribute: .Trailing)
constraints += equalAttributes(views: views, attribute: .Leading)
case .Center:
constraints += equalAttributes(views: views, attribute: .CenterX)
case .Leading:
constraints += equalAttributes(views: views, attribute: .Leading)
case .Trailing:
constraints += equalAttributes(views: views, attribute: .Trailing)
case .FirstBaseline, .LastBaseline:
constraints += []
}
}
constraints.forEach { $0.identifier = "TZSV-alignment" }
return constraints
}
private func createFirstAndLastViewMatchEdgesContraints() -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
let visibleViews = arrangedSubviews.filter({!self.isHidden($0)})
let firstView = visibleViews.first
let lastView = visibleViews.last
let edgeItem = layoutMarginsView ?? self
if areAllViewsHidden() {
switch axis {
case .Horizontal:
constraints.append(constraint(item: edgeItem, attribute: .Leading, toItem: orderingSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Trailing, toItem: orderingSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Top, toItem: alignmentSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Bottom, toItem: alignmentSpanner!))
switch alignment {
case .Center:
constraints.append(constraint(item: edgeItem, attribute: .CenterY, toItem: alignmentSpanner!))
default:
break
}
case .Vertical:
constraints.append(constraint(item: edgeItem, attribute: .Top, toItem: orderingSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Bottom, toItem: orderingSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Leading, toItem: alignmentSpanner!))
constraints.append(constraint(item: edgeItem, attribute: .Trailing, toItem: alignmentSpanner!))
switch alignment {
case .Center:
constraints.append(constraint(item: edgeItem, attribute: .CenterX, toItem: alignmentSpanner!))
default:
break
}
}
} else {
switch axis {
case .Horizontal:
if let firstView = firstView {
constraints.append(constraint(item: edgeItem, attribute: .Leading, toItem: firstView))
}
if let lastView = lastView {
constraints.append(constraint(item: edgeItem, attribute: .Trailing, toItem: lastView))
}
case .Vertical:
if let firstView = firstView {
constraints.append(constraint(item: edgeItem, attribute: .Top, toItem: firstView))
}
if let lastView = lastView {
constraints.append(constraint(item: edgeItem, attribute: .Bottom, toItem: lastView))
}
}
let firstArrangedView = arrangedSubviews.first!
let topView: UIView
var topRelation = NSLayoutRelation.Equal
let bottomView: UIView
var bottomRelation = NSLayoutRelation.Equal
var centerView: UIView?
// alignmentSpanner must be non nil when alignment is not .Fill
switch alignment {
case .Fill:
topView = firstArrangedView
bottomView = firstArrangedView
case .Center:
topView = alignmentSpanner!
bottomView = alignmentSpanner!
centerView = firstArrangedView
case .Leading:
topView = firstArrangedView
bottomView = alignmentSpanner!
case .Trailing:
topView = alignmentSpanner!
bottomView = firstArrangedView
case .FirstBaseline:
switch axis {
case .Horizontal:
topView = firstArrangedView
bottomView = alignmentSpanner!
topRelation = .LessThanOrEqual
case .Vertical:
topView = alignmentSpanner!
bottomView = alignmentSpanner!
}
case .LastBaseline:
switch axis {
case .Horizontal:
topView = alignmentSpanner!
bottomView = firstArrangedView
bottomRelation = .GreaterThanOrEqual
case .Vertical:
topView = alignmentSpanner!
bottomView = alignmentSpanner!
}
}
switch axis {
case .Horizontal:
constraints.append(constraint(item: edgeItem, attribute: .Top, relatedBy: topRelation, toItem: topView))
constraints.append(constraint(item: edgeItem, attribute: .Bottom, relatedBy: bottomRelation, toItem: bottomView))
if let centerView = centerView {
constraints.append(constraint(item: edgeItem, attribute: .CenterY, toItem: centerView))
}
case .Vertical:
constraints.append(constraint(item: edgeItem, attribute: .Leading, relatedBy: topRelation, toItem: topView))
constraints.append(constraint(item: edgeItem, attribute: .Trailing, relatedBy: bottomRelation, toItem: bottomView))
if let centerView = centerView {
constraints.append(constraint(item: edgeItem, attribute: .CenterX, toItem: centerView))
}
}
}
constraints.forEach { $0.identifier = "TZSV-canvas-connection" }
return constraints
}
private func equalAttributes(views views: [UIView], attribute: NSLayoutAttribute, priority: UILayoutPriority = 1000) -> [NSLayoutConstraint] {
var constraints = [NSLayoutConstraint]()
if views.count > 0 {
var firstView: UIView?
for view in views {
if let firstView = firstView {
constraints.append(constraint(item: firstView, attribute: attribute, toItem: view, priority: priority))
} else {
firstView = view
}
}
}
return constraints
}
// Convenience method to help make NSLayoutConstraint in a less verbose way
private func constraint(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation = .Equal, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute? = nil, multiplier: CGFloat = 1, constant c: CGFloat = 0, priority: UILayoutPriority = 1000, identifier: String? = nil) -> NSLayoutConstraint {
let attribute2 = attr2 != nil ? attr2! : attr1
let constraint = NSLayoutConstraint(item: view1, attribute: attr1, relatedBy: relation, toItem: view2, attribute: attribute2, multiplier: multiplier, constant: c)
constraint.priority = priority
constraint.identifier = identifier
return constraint
}
private func isHidden(view: UIView) -> Bool {
if view.hidden {
return true
}
return animatingToHiddenViews.indexOf(view) != nil
}
private func areAllViewsHidden() -> Bool {
return arrangedSubviews
.map { isHidden($0) }
.reduce(true) { $0 && $1 }
}
private func isMultilineLabel(view: UIView) -> Bool {
if let label = view as? UILabel where label.numberOfLines != 1 {
return true
} else {
return false
}
}
// Disables setting the background color to mimic an actual UIStackView which is a non-drawing view.
override public class func layerClass() -> AnyClass {
return CATransformLayer.self
}
// Suppress the warning of "changing property backgroundColor in transform-only layer, will have no effect"
override public var backgroundColor: UIColor? {
get {
return nil
}
set {
}
}
// Suppress the warning of "changing property opaque in transform-only layer, will have no effect"
override public var opaque: Bool {
get {
return true
}
set {
}
}
}
| mit | e54b61daa9867aa23b2a704b32f3762d | 41.659046 | 338 | 0.590493 | 5.564704 | false | false | false | false |
dilizarov/realm-cocoa | RealmSwift-swift2.0/Tests/SwiftTestObjects.swift | 16 | 5548 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import RealmSwift
class SwiftStringObject: Object {
dynamic var stringCol = ""
}
class SwiftBoolObject: Object {
dynamic var boolCol = false
}
class SwiftIntObject: Object {
dynamic var intCol = 0
}
class SwiftLongObject: Object {
dynamic var longCol: Int64 = 0
}
class SwiftObject: Object {
dynamic var boolCol = false
dynamic var intCol = 123
dynamic var floatCol = 1.23 as Float
dynamic var doubleCol = 12.3
dynamic var stringCol = "a"
dynamic var binaryCol = "a".dataUsingEncoding(NSUTF8StringEncoding)!
dynamic var dateCol = NSDate(timeIntervalSince1970: 1)
dynamic var objectCol: SwiftBoolObject? = SwiftBoolObject()
let arrayCol = List<SwiftBoolObject>()
class func defaultValues() -> [String: AnyObject] {
return ["boolCol": false as AnyObject,
"intCol": 123 as AnyObject,
"floatCol": 1.23 as AnyObject,
"doubleCol": 12.3 as AnyObject,
"stringCol": "a" as AnyObject,
"binaryCol": "a".dataUsingEncoding(NSUTF8StringEncoding)! as NSData,
"dateCol": NSDate(timeIntervalSince1970: 1) as NSDate,
"objectCol": [false],
"arrayCol": [] as NSArray]
}
}
class SwiftOptionalObject: Object {
// FIXME: Support all optional property types
// dynamic var optBoolCol: Bool?
// dynamic var optIntCol: Int?
// dynamic var optFloatCol: Float?
// dynamic var optDoubleCol: Double?
#if REALM_ENABLE_NULL
dynamic var optStringCol: NSString?
dynamic var optBinaryCol: NSData?
#endif
// dynamic var optDateCol: NSDate?
dynamic var optObjectCol: SwiftBoolObject?
// let arrayCol = List<SwiftBoolObject?>()
}
class SwiftImplicitlyUnwrappedOptionalObject: Object {
// FIXME: Support all optional property types
// dynamic var optBoolCol: Bool!
// dynamic var optIntCol: Int!
// dynamic var optFloatCol: Float!
// dynamic var optDoubleCol: Double!
#if REALM_ENABLE_NULL
dynamic var optStringCol: NSString!
dynamic var optBinaryCol: NSData!
#endif
// dynamic var optDateCol: NSDate!
dynamic var optObjectCol: SwiftBoolObject!
// let arrayCol = List<SwiftBoolObject!>()
}
class SwiftDogObject: Object {
dynamic var dogName = ""
}
class SwiftOwnerObject: Object {
dynamic var name = ""
dynamic var dog: SwiftDogObject? = SwiftDogObject()
}
class SwiftAggregateObject: Object {
dynamic var intCol = 0
dynamic var floatCol = 0 as Float
dynamic var doubleCol = 0.0
dynamic var boolCol = false
dynamic var dateCol = NSDate()
dynamic var trueCol = true
let stringListCol = List<SwiftStringObject>()
}
class SwiftAllIntSizesObject: Object {
dynamic var int8 : Int8 = 0
dynamic var int16 : Int16 = 0
dynamic var int32 : Int32 = 0
dynamic var int64 : Int64 = 0
}
class SwiftEmployeeObject: Object {
dynamic var name = ""
dynamic var age = 0
dynamic var hired = false
}
class SwiftCompanyObject: Object {
let employees = List<SwiftEmployeeObject>()
}
class SwiftArrayPropertyObject: Object {
dynamic var name = ""
let array = List<SwiftStringObject>()
let intArray = List<SwiftIntObject>()
}
class SwiftDoubleListOfSwiftObject: Object {
let array = List<SwiftListOfSwiftObject>()
}
class SwiftListOfSwiftObject: Object {
let array = List<SwiftObject>()
}
class SwiftArrayPropertySubclassObject: SwiftArrayPropertyObject {
let boolArray = List<SwiftBoolObject>()
}
class SwiftUTF8Object: Object {
dynamic var 柱колоéнǢкƱаم👍 = "值значен™👍☞⎠‱௹♣︎☐▼❒∑⨌⧭иеمرحبا"
}
class SwiftIgnoredPropertiesObject: Object {
dynamic var name = ""
dynamic var age = 0
dynamic var runtimeProperty: AnyObject?
dynamic var runtimeDefaultProperty = "property"
dynamic var readOnlyProperty: Int { return 0 }
override class func ignoredProperties() -> [String] {
return ["runtimeProperty", "runtimeDefaultProperty"]
}
}
class SwiftLinkToPrimaryStringObject: Object {
dynamic var pk = ""
dynamic var object: SwiftPrimaryStringObject?
let objects = List<SwiftPrimaryStringObject>()
override class func primaryKey() -> String? {
return "pk"
}
}
class SwiftRecursiveObject: Object {
let objects = List<SwiftRecursiveObject>()
}
class SwiftPrimaryStringObject: Object {
dynamic var stringCol = ""
dynamic var intCol = 0
override class func primaryKey() -> String? {
return "stringCol"
}
}
class SwiftIndexedPropertiesObject: Object {
dynamic var stringCol = ""
dynamic var intCol = 0
override class func indexedProperties() -> [String] {
return ["stringCol"] // Add "intCol" when integer indexing is supported
}
}
| apache-2.0 | 5abf92420a9bad12cfbb00c8a94fbe0c | 27.583333 | 81 | 0.67438 | 4.307692 | false | false | false | false |
rajkhatri/RKBarcodeScanner | BarcodeScanner/BarcodeScannerViewController.swift | 1 | 7235 | //
// BarcodeScannerViewController.swift
// BarcodeScanner
//
// Created by Raj Khatri on 2016-01-02.
// Copyright © 2016 Raj Khatri. All rights reserved.
//
import UIKit
import AVFoundation
class BarcodeScannerViewController : UIViewController, AVCaptureMetadataOutputObjectsDelegate {
// AV Properties
private var session:AVCaptureSession!
private var camera:AVCaptureDevice!
private var deviceInput:AVCaptureDeviceInput!
private var output:AVCaptureMetadataOutput!
private var previewLayer:AVCaptureVideoPreviewLayer!
// Custom UI
// Add any other custom overlay view on top. Use this view to modify dynamic content.
var customOverlayView:UIView?
// Highlight Barcode Region
private var highlightView:UIView?
var shouldShowBarcodeRegion:Bool = false
var highlightColor:UIColor = UIColor.blackColor() // Should change
var highlightWidth:CGFloat = 3.0
// Flags (Can be set by user)
var shouldAskForPermissions:Bool = true
var shouldPauseAfterScannedItem:Bool = true
// Barcode Types (only some added) Set this to change.
var barcodeTypes:[NSString] = [AVMetadataObjectTypeUPCECode, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode39Mod43Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeAztecCode, AVMetadataObjectTypeQRCode]
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .blackColor()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if shouldAskForPermissions {
CameraPermissions.sharedInstance.cameraViewController = self
CameraPermissions.sharedInstance.checkCameraPermissions({ () -> () in
self.initCustomUI()
self.initCamera()
})
}
else {
initCustomUI()
initCamera()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if session != nil && session.running {
session.stopRunning()
session = nil
}
}
// MARK: Camera Initialization
private func initCamera() {
session = AVCaptureSession()
camera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
try deviceInput = AVCaptureDeviceInput(device: camera)
}
catch {
print("Error trying to use camera: \(error)")
}
guard deviceInput != nil else {
print("Cannot attach input to session")
return
}
session.addInput(deviceInput)
output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
session.addOutput(output)
output.metadataObjectTypes = output.availableMetadataObjectTypes
previewLayer = AVCaptureVideoPreviewLayer(session: session)
previewLayer.frame = UIScreen.mainScreen().bounds
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.addSublayer(previewLayer)
addCustomUItoView()
// To determine when exactly the camera is ready to "start". Used if you want to show indication when camera has begun.
session.addObserver(self, forKeyPath: "running", options: NSKeyValueObservingOptions.New, context: nil)
session.startRunning()
}
// MARK: Custom UI
private func initCustomUI() {
if shouldShowBarcodeRegion {
highlightView = UIView()
highlightView?.autoresizingMask = [.FlexibleTopMargin, .FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin];
highlightView?.layer.borderColor = highlightColor.CGColor
highlightView?.layer.borderWidth = highlightWidth
}
}
private func addCustomUItoView() {
if shouldShowBarcodeRegion && highlightView != nil {
self.view.addSubview(highlightView!)
self.view.bringSubviewToFront(highlightView!)
}
guard customOverlayView != nil else { return }
self.view.addSubview(customOverlayView!)
self.view.bringSubviewToFront(customOverlayView!)
}
// MARK: Camera Functions
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
var highlightRect = CGRectZero
for data in metadataObjects {
guard let metaData = data as? AVMetadataObject else { continue }
var detectionString:String?
for type in barcodeTypes {
if type == metaData.type {
guard let barcodeObject = previewLayer.transformedMetadataObjectForMetadataObject(metaData) as? AVMetadataMachineReadableCodeObject else { continue }
highlightRect = barcodeObject.bounds
detectionString = (metaData as! AVMetadataMachineReadableCodeObject).stringValue
break
}
}
guard detectionString != nil else { continue }
if shouldPauseAfterScannedItem {
session.stopRunning()
}
barcodeScannerScannedValue(detectionString!)
guard highlightView != nil else { continue }
highlightView?.frame = highlightRect
}
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard object as? AVCaptureSession != nil else { return }
if session.running {
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("barcodeScannerIsReady"), userInfo: nil, repeats: false)
}
}
// MARK: Overridable Functions
func barcodeScannerIsReady() {
}
func barcodeScannerScannedValue(value:String) {
let vc = UIAlertController(title: value, message: nil, preferredStyle: .Alert)
let okButton = UIAlertAction(title: "Ok", style: .Default) { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
self.startCamera()
}
vc.addAction(okButton)
self.presentViewController(vc, animated: true, completion: nil)
}
// MARK: Helper Functions
func startCamera() {
if highlightView != nil {
highlightView?.frame = CGRectZero
}
guard session != nil else {
print("Initialize Camera before calling this function")
return
}
session.startRunning()
}
func stopCamera() {
guard session != nil else { return }
session.stopRunning()
}
} | mit | ca0e3037feb8b4e15d29527678deecff | 34.465686 | 350 | 0.636716 | 5.905306 | false | false | false | false |
wentingwei/develop | ZombieConga/ZombieConga/GameScene.swift | 1 | 13267 | //
// GameScene.swift
// ZombieConga
//
// Created by wentingwei on 14/11/27.
// Copyright (c) 2014年 wentingwei. All rights reserved.
//
import SpriteKit
import AVFoundation
var backgroundMusicPlayer:AVAudioPlayer!
func playBackgroundMusic(fileName:String) {
let url = NSBundle.mainBundle().URLForResource(fileName, withExtension: nil)
if url == nil {
return
}
var error:NSError? = nil
backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)
if backgroundMusicPlayer == nil {
return
}
backgroundMusicPlayer.numberOfLoops = -1
backgroundMusicPlayer.prepareToPlay()
backgroundMusicPlayer.play()
}
func stopBackgroungMusic() {
backgroundMusicPlayer.stop()
}
class GameScene: SKScene {
let zombie:SKSpriteNode = SKSpriteNode(imageNamed: "zombie1")
var lastUpdateTime:NSTimeInterval = 0
var dt:NSTimeInterval = 0
let zombieMovePointsPerSec:CGFloat = 500.0
var velocity = CGPointZero
let playableRect:CGRect
var lastTouchLocation:CGPoint?
let zombieRotateRadiansPerSec:CGFloat = 4.0 * CGFloat(M_PI)
let zombieAnimation:SKAction
let backgroundMovePointsPerSec:CGFloat = 200.0
let backgroundLayer = SKNode()
var lives = 1
var catCount = 0
var gameOver = false
override init(size: CGSize) {
let maxAspectRatio:CGFloat = 16.0/9.0
let playableHeight = size.width/maxAspectRatio
let playableMargin = (size.height - playableHeight)/2.0
playableRect = CGRect(x: 0, y: playableMargin, width: size.width, height: playableHeight)
var textures:[SKTexture] = []
for i in 1...4 {
textures.append(SKTexture(imageNamed: "zombie\(i)"))
}
textures.append(textures[2])
textures.append(textures[1])
zombieAnimation = SKAction.repeatActionForever(
SKAction.animateWithTextures(textures, timePerFrame: 0.1))
super.init(size:size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented") // 6
}
override func didMoveToView(view: SKView) {
initBackground()
spawnZombie()
startSpawnEnemy()
startSpawnCat()
//debugDrawPlayableArea()
}
func initBackground() {
backgroundLayer.zPosition = -1
addChild(backgroundLayer)
for i in 0...1 {
let background = backgroundNode()
background.position = CGPoint(x:CGFloat(i)*background.size.width,y:0)
backgroundLayer.addChild(background)
}
playBackgroundMusic("backgroundMusic.mp3")
}
func backgroundNode() -> SKSpriteNode {
let background = SKSpriteNode()
background.name = "background"
background.anchorPoint = CGPointZero
let background1 = SKSpriteNode(imageNamed: "background1")
background1.anchorPoint = CGPointZero
background1.position = CGPointZero
background.addChild(background1)
let background2 = SKSpriteNode(imageNamed: "background2")
background2.anchorPoint = CGPointZero
background2.position = CGPoint(x: background1.size.width, y: 0)
background.addChild(background2)
background.size = CGSize(width: background1.size.width + background2.size.width, height: background1.size.height)
return background
}
func moveBackground() {
backgroundLayer.position = CGPoint(x: backgroundLayer.position.x - CGFloat(self.dt) * self.backgroundMovePointsPerSec, y: 0)
backgroundLayer.enumerateChildNodesWithName("background") {
node,_ in
let background = node as SKSpriteNode
let backgroundScreenPos = self.backgroundLayer.convertPoint(background.position, toNode: self)
if backgroundScreenPos.x <= -background.size.width {
background.position.x = background.position.x + background.size.width*2
}
}
}
func spawnZombie() {
zombie.position = CGPoint(x: 400, y: 400)
backgroundLayer.addChild(zombie)
}
func startZombieAnimation() {
if zombie.actionForKey("animation") == nil {
zombie.runAction(SKAction.repeatActionForever(zombieAnimation), withKey: "animation")
}
}
func stopZombieAnimation() {
zombie.removeActionForKey("animation")
}
func startSpawnEnemy() {
let sequence = SKAction.sequence([SKAction.runBlock(spawnEnemy),SKAction.waitForDuration(2.0)])
runAction(SKAction.repeatActionForever(sequence))
}
func startSpawnCat() {
let sequence = SKAction.sequence([SKAction.runBlock(spawnCat),SKAction.waitForDuration(1.0)])
runAction(SKAction.repeatActionForever(sequence))
}
func spawnCat() {
let cat = SKSpriteNode(imageNamed: "cat")
cat.name = "cat"
let minX = CGRectGetMinX(playableRect)
let maxX = CGRectGetMaxX(playableRect)
let minY = CGRectGetMinY(playableRect)
let maxY = CGRectGetMaxY(playableRect)
let position = CGPoint(x: randomCGFloat(minX, max: maxX), y: randomCGFloat(minY, max: maxY))
cat.position = backgroundLayer.convertPoint(position, fromNode: self)
cat.setScale(0)
backgroundLayer.addChild(cat)
cat.zRotation = -CGFloat(M_PI) / 16
let leftWiggle = SKAction.rotateByAngle(CGFloat(M_PI)/8, duration: 0.5)
let rightWiggle = leftWiggle.reversedAction()
let fullWiggle = SKAction.sequence([leftWiggle,rightWiggle])
let scaleUp = SKAction.scaleBy(1.2, duration: 0.25)
let scaleDown = scaleUp.reversedAction()
let fullScale = SKAction.sequence([scaleUp,scaleDown,scaleUp,scaleDown])
let group = SKAction.group([fullScale,fullWiggle])
let groupWait = SKAction.repeatAction(group, count: 10)
let appear = SKAction.scaleTo(1.0, duration: 0.5)
let disappear = SKAction.scaleTo(0.0, duration: 0.5)
let remove = SKAction.removeFromParent()
cat.runAction(SKAction.sequence([appear,groupWait,disappear,remove]))
}
func spawnEnemy(){
let enemy = SKSpriteNode(imageNamed: "enemy")
enemy.name = "enemy"
let width = playableRect.height + enemy.size.height
let random = CGFloat(arc4random())%width
let randomY = random + CGRectGetMinY(playableRect) + enemy.size.height/2
let position = CGPoint(x: size.width+enemy.size.width/2, y: randomY)
enemy.position = backgroundLayer.convertPoint(position, fromNode: self)
backgroundLayer.addChild(enemy)
let actionMove = SKAction.moveByX( -size.width - enemy.size.width, y:0,duration: 2.0)
let actionRemove = SKAction.removeFromParent()
let sequence = SKAction.sequence([actionMove,actionRemove])
enemy.runAction(sequence)
}
func moveSprite(sprite:SKSpriteNode,velocity:CGPoint) {
let amountToMove = CGPoint(x: velocity.x*CGFloat(dt), y: velocity.y*CGFloat(dt))
sprite.position = CGPoint(x: sprite.position.x+amountToMove.x, y:sprite.position.y+amountToMove.y)
}
func randomCGFloat(min:CGFloat,max:CGFloat) ->CGFloat {
let length = max - min;
let random = CGFloat(arc4random()) % length
return random + min
}
func shortestAngleBetween(angle1: CGFloat,angle2: CGFloat) -> CGFloat {
let π = CGFloat(M_PI)
let twoπ = π * 2.0
var angle = (angle2 - angle1) % twoπ
if (angle >= π) {
angle = angle - twoπ
}
if (angle <= -π) {
angle = angle + twoπ
}
return angle
}
func rotateSptite(sprite:SKSpriteNode,direction:CGPoint) {
let shortest = shortestAngleBetween(sprite.zRotation, angle2:atan2(direction.y, direction.x))
let amountToRotate = min(zombieRotateRadiansPerSec * CGFloat(dt), abs(shortest))
if shortest>0 {
sprite.zRotation = sprite.zRotation + amountToRotate
}else{
sprite.zRotation = sprite.zRotation - amountToRotate
}
}
func moveZombieToward(location:CGPoint) {
let offset = CGPoint(x: location.x-zombie.position.x, y: location.y - zombie.position.y)
let length = sqrt(offset.x*offset.x+offset.y*offset.y)
let direction = CGPoint(x: offset.x/CGFloat(length), y: offset.y/CGFloat(length))
velocity = CGPoint(x: zombieMovePointsPerSec*direction.x, y: zombieMovePointsPerSec*direction.y)
startZombieAnimation()
}
override func update(currentTime: NSTimeInterval) {
if lastUpdateTime>0 {
dt = currentTime - lastUpdateTime
}else{
dt = 0
}
lastUpdateTime = currentTime
moveSprite(zombie, velocity: velocity)
rotateSptite(zombie, direction: velocity)
boundsCheckZombie()
checkCollisions()
moveBackground()
if lives < 0 && !gameOver{
gameOver = true
self.gameOver(false)
}
if catCount > 10 && !gameOver {
gameOver = true
self.gameOver(true)
}
}
func zombieHitCat(cat:SKSpriteNode) {
catCount++
let remove = SKAction.removeFromParent()
cat.runAction(remove)
runAction(SKAction.playSoundFileNamed("hitCat.wav", waitForCompletion: false))
}
func zombieHitEnemy(enemy:SKSpriteNode) {
lives--
runAction(SKAction.playSoundFileNamed("hitCatLady.wav", waitForCompletion: false))
}
func checkCollisions() {
var hitCats:[SKSpriteNode] = []
backgroundLayer.enumerateChildNodesWithName("cat") { node, _ in
let cat = node as SKSpriteNode
if CGRectIntersectsRect(cat.frame, self.zombie.frame) {
hitCats.append(cat)
}
}
for cat in hitCats {
zombieHitCat(cat)
}
var hitEnemy:[SKSpriteNode] = []
backgroundLayer.enumerateChildNodesWithName("enemy") { node, _ in
let enemy = node as SKSpriteNode
if CGRectIntersectsRect(enemy.frame, self.zombie.frame) {
hitEnemy.append(enemy)
}
}
for enemy in hitEnemy {
zombieHitEnemy(enemy)
}
}
func boundsCheckZombie() {
let bottomLeft = backgroundLayer.convertPoint(CGPoint(x: 0, y: CGRectGetMinY(playableRect)),fromNode:self)
let topRight = backgroundLayer.convertPoint(CGPoint(x: size.width, y: CGRectGetMaxY(playableRect)),fromNode:self)
if zombie.position.x <= bottomLeft.x {
zombie.position.x = bottomLeft.x
velocity.x = -velocity.x
}
if zombie.position.y <= bottomLeft.y {
zombie.position.y = bottomLeft.y
velocity.y = -velocity.y
}
if zombie.position.x >= topRight.x {
zombie.position.x = topRight.x
velocity.x = -velocity.x
}
if zombie.position.y >= topRight.y {
zombie.position.y = topRight.y
velocity.y = -velocity.y
}
}
func sceneTouched(touchLocation:CGPoint) {
lastTouchLocation = touchLocation
moveZombieToward(touchLocation)
}
func gameOver(won:Bool) {
let gameOverScene = GameOverScene(size: size, won: won)
gameOverScene.scaleMode = scaleMode
let reveal = SKTransition.flipHorizontalWithDuration(0.5)
view?.presentScene(gameOverScene, transition: reveal)
if won {
runAction(SKAction.playSoundFileNamed("win.wav", waitForCompletion: false))
}else{
runAction(SKAction.playSoundFileNamed("lose.wav", waitForCompletion: false))
}
stopBackgroungMusic()
}
#if os(iOS)
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(backgroundLayer)
sceneTouched(touchLocation)
}
override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {
let touch = touches.anyObject() as UITouch
let touchLocation = touch.locationInNode(backgroundLayer)
sceneTouched(touchLocation)
}
#else
override func mouseDown(theEvent: NSEvent) {
let touchLocation = theEvent.locationInNode(backgroundLayer)
sceneTouched(touchLocation)
}
override func mouseDragged(theEvent: NSEvent) {
let touchLocation = theEvent.locationInNode(backgroundLayer)
sceneTouched(touchLocation)
}
#endif
func debugDrawPlayableArea() {
let shap = SKShapeNode()
let path = CGPathCreateMutable()
CGPathAddRect(path, nil, playableRect)
shap.path = path
shap.strokeColor = SKColor.redColor()
shap.lineWidth = 4.0
addChild(shap)
}
}
| lgpl-3.0 | 1f8213395f146a582732df01648b917a | 33.704188 | 132 | 0.627593 | 4.606324 | false | false | false | false |
leizh007/HiPDA | HiPDA/HiPDA/General/Delegates/HomeTabBarControllerDelegate.swift | 1 | 2596 | //
// HomeTabBarControllerDelegate.swift
// HiPDA
//
// Created by leizh007 on 16/7/28.
// Copyright © 2016年 HiPDA. All rights reserved.
//
import UIKit
/// 主页TabBarController的Delegate
class HomeTabBarControllerDelegate: NSObject, UITabBarControllerDelegate {
var lastSelectedIndex = 0
func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
if tabBarController.selectedIndex != lastSelectedIndex {
lastSelectedIndex = tabBarController.selectedIndex
} else if lastSelectedIndex == C.Number.homeViewControllerIndex {
NotificationCenter.default.post(name: .HomeViewControllerTabRepeatedSelected, object: nil)
} else if lastSelectedIndex == C.Number.messageViewControllerIndex {
NotificationCenter.default.post(name: .MessageViewControllerTabRepeatedSelected, object: nil)
} else if lastSelectedIndex == C.Number.searchViewControllerIndex {
NotificationCenter.default.post(name: .SearchViewControllerTabRepeatedSelected, object: nil)
}
/// 处理动画相关
let tabBar = tabBarController.tabBar
guard let tabbarItem = tabBar.selectedItem else { return }
var selectedImageView: UIImageView?
for tabBarButton in tabBar.subviews {
let (imageView, label) = tabBarButton.subviews.reduce((nil, nil)) { (result, view) in
return (result.0 ?? view as? UIImageView, result.1 ?? view as? UILabel)
}
if imageView != nil && label != nil && tabbarItem.title == label?.text {
selectedImageView = imageView
break
}
}
guard let imageView = selectedImageView else { return }
/// 给imageView添加动画,动画参数待优化!
UIView.animate(withDuration: 0.15,
animations: {
imageView.transform = CGAffineTransform(scaleX: 0.85, y: 0.85)
}, completion: { (_) in
UIView.animate(withDuration: 0.1,
animations: {
imageView.transform = CGAffineTransform(scaleX: 1.05, y: 1.05)
}, completion: { (_) in
UIView.animate(withDuration: 0.03,
animations: {
imageView.transform = CGAffineTransform.identity
})
})
})
}
}
| mit | a62cd60c6d164219251cc83d622ec3ac | 41.45 | 111 | 0.585395 | 5.597802 | false | false | false | false |
vary-llc/SugarRecord | library/CoreData/Base/iCloudCDStack.swift | 7 | 16518 | //
// iCloudCDStack.swift
// SugarRecord
//
// Created by Pedro Piñera Buendía on 12/10/14.
// Copyright (c) 2014 SugarRecord. All rights reserved.
//
import Foundation
import CoreData
/**
* Struct with the needed information to initialize the iCloud stack
*/
public struct iCloudData
{
/// Is the full AppID (including the Team Prefix). It's needed to change tihs to match the Team Prefix found in the iOS Provisioning profile
internal let iCloudAppID: String
/// Is the name of the directory where the database will be stored in. It should always end with .nosync
internal var iCloudDataDirectoryName: String = "Data.nosync"
/// Is the name of the directory where the database change logs will be stored in
internal var iCloudLogsDirectory: String = "Logs"
/**
Note:
iCloudData = iCloud + DataDirectory
iCloudLogs = iCloud + LogsDirectory
*/
/**
Initializer for the struct
:param: iCloudAppID iCloud app identifier
:param: iCloudDataDirectoryName Directory of the database
:param: iCloudLogsDirectory Directory of the database logs
:returns: Initialized struct
*/
public init (iCloudAppID: String, iCloudDataDirectoryName: String?, iCloudLogsDirectory: String?)
{
self.iCloudAppID = iCloudAppID
if (iCloudDataDirectoryName != nil) {self.iCloudDataDirectoryName = iCloudDataDirectoryName!}
if (iCloudLogsDirectory != nil) {self.iCloudLogsDirectory = iCloudLogsDirectory!}
}
}
/**
* iCloud stack for SugarRecord
*/
public class iCloudCDStack: DefaultCDStack
{
//MARK: - Class properties
public var loadCompletedClosure: ()->() = {}
//MARK: - Properties
/// iCloud Data struct with the information
private var icloudData: iCloudData?
/// Notification center used for iCloud Notifications
lazy var notificationCenter: NSNotificationCenter = NSNotificationCenter.defaultCenter()
/**
Initialize the CoreData stack
:param: databaseURL NSURL with the database path
:param: model NSManagedObjectModel with the database model
:param: automigrating Bool Indicating if the migration has to be automatically executed
:param: icloudData iCloudData information
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: iCloudCDStack object
*/
public init(databaseURL: NSURL, model: NSManagedObjectModel?, automigrating: Bool, icloudData: iCloudData, completion: ()->())
{
super.init(databaseURL: databaseURL, model: model, automigrating: automigrating)
self.loadCompletedClosure = completion
self.icloudData = icloudData
self.automigrating = automigrating
self.databasePath = databaseURL
self.managedObjectModel = model
self.migrationFailedClosure = {}
self.name = "iCloudCoreDataStack"
self.stackDescription = "Stack to connect your local storage with iCloud"
}
/**
Initialize the CoreData default stack passing the database name and a flag indicating if the automigration has to be automatically executed
:param: databaseName String with the database name
:param: icloudData iCloud Data struct
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: DefaultCDStack object
*/
convenience public init(databaseName: String, icloudData: iCloudData, completion: ()->())
{
self.init(databaseURL: iCloudCDStack.databasePathURLFromName(databaseName), icloudData: icloudData, completion: completion)
}
/**
Initialize the CoreData default stack passing the database path in String format and a flag indicating if the automigration has to be automatically executed
:param: databasePath String with the database path
:param: icloudData iCloud Data struct
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: DefaultCDStack object
*/
convenience public init(databasePath: String, icloudData: iCloudData, completion: ()->())
{
self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, icloudData: icloudData, completion: completion)
}
/**
Initialize the CoreData default stack passing the database path URL and a flag indicating if the automigration has to be automatically executed
:param: databaseURL NSURL with the database path
:param: icloudData iCloud Data struct
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: DefaultCDStack object
*/
convenience public init(databaseURL: NSURL, icloudData: iCloudData, completion: ()->())
{
self.init(databaseURL: databaseURL, model: nil, automigrating: true,icloudData: icloudData, completion: completion)
}
/**
Initialize the CoreData default stack passing the database name, the database model object and a flag indicating if the automigration has to be automatically executed
:param: databaseName String with the database name
:param: model NSManagedObjectModel with the database model
:param: icloudData iCloud Data struct
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: DefaultCDStack object
*/
convenience public init(databaseName: String, model: NSManagedObjectModel, icloudData: iCloudData, completion: ()->())
{
self.init(databaseURL: DefaultCDStack.databasePathURLFromName(databaseName), model: model, automigrating: true, icloudData: icloudData, completion: completion)
}
/**
Initialize the CoreData default stack passing the database path in String format, the database model object and a flag indicating if the automigration has to be automatically executed
:param: databasePath String with the database path
:param: model NSManagedObjectModel with the database model
:param: icloudData iCloud Data struct
:param: completion Closure to be executed when iCloud stack finishes initializing
:returns: DefaultCDStack object
*/
convenience public init(databasePath: String, model: NSManagedObjectModel, icloudData: iCloudData, completion: ()->())
{
self.init(databaseURL: NSURL(fileURLWithPath: databasePath)!, model: model, automigrating: true, icloudData: icloudData, completion: completion)
}
/**
Initialize the stacks components and the connections between them
*/
public override func initialize()
{
SugarRecordLogger.logLevelInfo.log("Initializing the stack: \(self.stackDescription)")
createManagedObjecModelIfNeeded()
persistentStoreCoordinator = createPersistentStoreCoordinator()
addDatabase(foriCloud: true, completionClosure: self.dataBaseAddedClosure())
}
/**
Returns the closure to be execute once the database has been created
*/
override public func dataBaseAddedClosure() -> CompletionClosure {
return { [weak self] (error) -> () in
if self == nil {
SugarRecordLogger.logLevelFatal.log("The stack was released while trying to initialize it")
return
}
else if error != nil {
SugarRecordLogger.logLevelFatal.log("Something went wrong adding the database")
return
}
self!.rootSavingContext = self!.createRootSavingContext(self!.persistentStoreCoordinator)
self!.mainContext = self!.createMainContext(self!.rootSavingContext)
self!.addObservers()
self!.stackInitialized = true
self!.loadCompletedClosure()
}
}
//MARK: - Contexts
/**
Creates a temporary root saving context to be used in background operations
Note: This overriding is due to the fact that in this case the merge policy is different
:param: persistentStoreCoordinator NSPersistentStoreCoordinator to be set as the persistent store coordinator of the created context
:returns: Private NSManageObjectContext
*/
override internal func createRootSavingContext(persistentStoreCoordinator: NSPersistentStoreCoordinator?) -> NSManagedObjectContext
{
SugarRecordLogger.logLevelVerbose.log("Creating Root Saving context")
var context: NSManagedObjectContext?
if persistentStoreCoordinator == nil {
SugarRecord.handle(NSError(domain: "The persistent store coordinator is not initialized", code: SugarRecordErrorCodes.CoreDataError.rawValue, userInfo: nil))
}
context = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
context!.persistentStoreCoordinator = persistentStoreCoordinator!
context!.addObserverToGetPermanentIDsBeforeSaving()
context!.name = "Root saving context"
context!.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
SugarRecordLogger.logLevelVerbose.log("Created MAIN context")
return context!
}
//MARK: - Database
/**
Add iCloud Database
*/
internal func addDatabase(foriCloud icloud: Bool, completionClosure: CompletionClosure)
{
/**
* In case of not for iCloud
*/
if !icloud {
self.addDatabase(completionClosure)
return
}
/**
* Database creation is an asynchronous process
*/
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] () -> Void in
// Ensuring that the stack hasn't been released
if self == nil {
SugarRecordLogger.logLevelFatal.log("The stack was initialized while trying to add the database")
return
}
// Checking that the PSC exists before adding the store
if self!.persistentStoreCoordinator == nil {
SugarRecord.handle(NSError())
}
// Logging some data
let fileManager: NSFileManager = NSFileManager()
SugarRecordLogger.logLevelVerbose.log("Initializing iCloud with:")
SugarRecordLogger.logLevelVerbose.log("iCloud App ID: \(self!.icloudData?.iCloudAppID)")
SugarRecordLogger.logLevelVerbose.log("iCloud Data Directory: \(self!.icloudData?.iCloudDataDirectoryName)")
SugarRecordLogger.logLevelVerbose.log("iCloud Logs Directory: \(self!.icloudData?.iCloudLogsDirectory)")
//Getting the root path for iCloud
let iCloudRootPath: NSURL? = fileManager.URLForUbiquityContainerIdentifier(self!.icloudData?.iCloudAppID)
/**
* If iCloud if accesible keep creating the PSC
*/
if iCloudRootPath != nil {
let iCloudLogsPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudLogsDirectory))!
let iCloudDataPath: NSURL = NSURL(fileURLWithPath: iCloudRootPath!.path!.stringByAppendingPathComponent(self!.icloudData!.iCloudDataDirectoryName))!
// Creating data path in case of doesn't existing
var error: NSError?
if !fileManager.fileExistsAtPath(iCloudDataPath.path!) {
fileManager.createDirectoryAtPath(iCloudDataPath.path!, withIntermediateDirectories: true, attributes: nil, error: &error)
}
if error != nil {
completionClosure(error: error!)
return
}
/// Getting the database path
/// iCloudPath + iCloudDataPath + DatabaseName
let path: String? = iCloudRootPath?.path?.stringByAppendingPathComponent((self?.icloudData?.iCloudDataDirectoryName)!).stringByAppendingPathComponent((self?.databasePath?.lastPathComponent)!)
self!.databasePath = NSURL(fileURLWithPath: path!)
// Adding store
self!.persistentStoreCoordinator!.lock()
error = nil
var store: NSPersistentStore? = self!.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: self!.databasePath, options: iCloudCDStack.icloudStoreOptions(contentNameKey: self!.icloudData!.iCloudAppID, contentURLKey: iCloudLogsPath), error: &error)
self!.persistentStoreCoordinator!.unlock()
self!.persistentStore = store!
// Calling completion closure
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionClosure(error: nil)
})
}
/**
* Otherwise use the local store
*/
else {
self!.addDatabase(foriCloud: false, completionClosure: completionClosure)
}
})
}
//MARK: - Database Helpers
/**
Returns the iCloud options to be used when the NSPersistentStore is initialized
:returns: [NSObject: AnyObject] with the options
*/
internal class func icloudStoreOptions(#contentNameKey: String, contentURLKey: NSURL) -> [NSObject: AnyObject]
{
var options: [NSObject: AnyObject] = [NSObject: AnyObject] ()
options[NSMigratePersistentStoresAutomaticallyOption] = NSNumber(bool: true)
options[NSInferMappingModelAutomaticallyOption] = NSNumber(bool: true)
options[NSPersistentStoreUbiquitousContentNameKey] = contentNameKey
options[NSPersistentStoreUbiquitousContentURLKey] = contentURLKey
return options
}
//MARK: - Observers
/**
Add required observers to detect changes in psc's or contexts
*/
internal override func addObservers()
{
super.addObservers()
SugarRecordLogger.logLevelVerbose.log("Adding observers to detect changes on iCloud")
// Store will change
notificationCenter.addObserver(self, selector: Selector("storesWillChange:"), name: NSPersistentStoreCoordinatorStoresWillChangeNotification, object: nil)
// Store did change
notificationCenter.addObserver(self, selector: Selector("storeDidChange:"), name: NSPersistentStoreCoordinatorStoresDidChangeNotification, object: nil)
// Did import Ubiquituous Content
notificationCenter.addObserver(self, selector: Selector("persistentStoreDidImportUbiquitousContentChanges:"), name: NSPersistentStoreDidImportUbiquitousContentChangesNotification, object: nil)
}
/**
Detects changes in the Ubiquituous Container (iCloud) and bring them to the stack contexts
:param: notification Notification with these changes
*/
dynamic internal func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification)
{
SugarRecordLogger.logLevelVerbose.log("Changes detected from iCloud. Merging them into the current CoreData stack")
self.rootSavingContext!.performBlock { [weak self] () -> Void in
if self == nil {
SugarRecordLogger.logLevelWarn.log("The stack was released while trying to bring changes from the iCloud Container")
return
}
self!.rootSavingContext!.mergeChangesFromContextDidSaveNotification(notification)
self!.mainContext!.performBlock({ () -> Void in
self!.mainContext!.mergeChangesFromContextDidSaveNotification(notification)
})
}
}
/**
Posted before the list of open persistent stores changes.
:param: notification Notification with these changes
*/
dynamic internal func storesWillChange(notification: NSNotification)
{
SugarRecordLogger.logLevelVerbose.log("Stores will change, saving pending changes before changing store")
self.saveChanges()
}
/**
Called when the store did change from the persistent store coordinator
:param: notification Notification with the information
*/
dynamic internal func storeDidChange(notification: NSNotification)
{
SugarRecordLogger.logLevelVerbose.log("The persistent store of the psc did change")
// Nothing to do here
}
} | mit | ae669061e157005f038f1ae71cf90e18 | 41.901299 | 308 | 0.679402 | 5.656164 | false | false | false | false |
slavapestov/swift | test/SILGen/complete_object_init.swift | 4 | 1932 | // RUN: %target-swift-frontend %s -emit-silgen | FileCheck %s
struct X { }
class A {
// CHECK-LABEL: sil hidden @_TFC20complete_object_init1Ac{{.*}} : $@convention(method) (@owned A) -> @owned A
// CHECK: bb0([[SELF_PARAM:%[0-9]+]] : $A):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $A
// CHECK: [[PB:%.*]] = project_box [[SELF_BOX]]
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized [delegatingself] [[PB]] : $*A
// CHECK: store [[SELF_PARAM]] to [[SELF]] : $*A
// CHECK: [[SELFP:%[0-9]+]] = load [[SELF]] : $*A
// CHECK: [[INIT:%[0-9]+]] = class_method [[SELFP]] : $A, #A.init!initializer.1 : A.Type -> (x: X) -> A , $@convention(method) (X, @owned A) -> @owned A
// CHECK: [[X_INIT:%[0-9]+]] = function_ref @_TFV20complete_object_init1XC{{.*}} : $@convention(thin) (@thin X.Type) -> X
// CHECK: [[X_META:%[0-9]+]] = metatype $@thin X.Type
// CHECK: [[X:%[0-9]+]] = apply [[X_INIT]]([[X_META]]) : $@convention(thin) (@thin X.Type) -> X
// CHECK: [[INIT_RESULT:%[0-9]+]] = apply [[INIT]]([[X]], [[SELFP]]) : $@convention(method) (X, @owned A) -> @owned A
// CHECK: store [[INIT_RESULT]] to [[SELF]] : $*A
// CHECK: [[RESULT:%[0-9]+]] = load [[SELF]] : $*A
// CHECK: strong_retain [[RESULT]] : $A
// CHECK: strong_release [[SELF_BOX]] : $@box A
// CHECK: return [[RESULT]] : $A
// CHECK-LABEL: sil hidden @_TFC20complete_object_init1AC{{.*}} : $@convention(thin) (@thick A.Type) -> @owned A
convenience init() {
// CHECK: bb0([[SELF_META:%[0-9]+]] : $@thick A.Type):
// CHECK: [[SELF:%[0-9]+]] = alloc_ref_dynamic [[SELF_META]] : $@thick A.Type, $A
// CHECK: [[OTHER_INIT:%[0-9]+]] = function_ref @_TFC20complete_object_init1Ac{{.*}} : $@convention(method) (@owned A) -> @owned A
// CHECK: [[RESULT:%[0-9]+]] = apply [[OTHER_INIT]]([[SELF]]) : $@convention(method) (@owned A) -> @owned A
// CHECK: return [[RESULT]] : $A
self.init(x: X())
}
init(x: X) { }
}
| apache-2.0 | ddd2ff3c363f93605cfcab30bca9f5a2 | 52.666667 | 154 | 0.536749 | 2.875 | false | false | false | false |
ZamzamInc/XcodeUnitTesting-Swift | SampleUnitTesting/WebHelper.swift | 1 | 2205 | //
// WebHelper.swift
// SampleUnitTesting
//
// Created by Basem Emara on 1/21/16.
// Copyright © 2016 Zamzam. All rights reserved.
//
import Foundation
public struct WebHelper {
/**
Add, update, or remove a query string parameter from the URL
- parameter url: the URL
- parameter key: the key of the query string parameter
- parameter value: the value to replace the query string parameter, nil will remove item
- returns: the URL with the mutated query string
*/
public func addOrUpdateQueryStringParameter(url: String, key: String, value: String?) -> String {
if let components = NSURLComponents(string: url),
var queryItems: [NSURLQueryItem] = (components.queryItems ?? []) {
for (index, item) in queryItems.enumerate() {
// Match query string key and update
if item.name.lowercaseString == key.lowercaseString {
if let v = value {
queryItems[index] = NSURLQueryItem(name: key, value: v)
} else {
queryItems.removeAtIndex(index)
}
components.queryItems = queryItems.count > 0
? queryItems : nil
return components.string!
}
}
// Key doesn't exist if reaches here
if let v = value {
// Add key to URL query string
queryItems.append(NSURLQueryItem(name: key, value: v))
components.queryItems = queryItems
return components.string!
}
}
return url
}
/**
Removes a query string parameter from the URL
- parameter url: the URL
- parameter key: the key of the query string parameter
- returns: the URL with the mutated query string
*/
public func removeQueryStringParameter(url: String, key: String) -> String {
return addOrUpdateQueryStringParameter(url, key: key, value: nil)
}
} | mit | 393ec9785986d81d9ff758cbc6850a98 | 34 | 101 | 0.537659 | 5.388753 | false | false | false | false |
appnexus/mobile-sdk-ios | tests/TrackerUITest/UITestApp/AdsViewController/PlacementTest/BannerNativeAdViewController.swift | 1 | 6543 | /* Copyright 2019 APPNEXUS INC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import AppNexusSDK
class BannerNativeAdViewController: UIViewController , ANBannerAdViewDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var viewNative: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var bodyLabel: UILabel!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var callToActionButton: UIButton!
@IBOutlet weak var sponsoredLabel: UILabel!
var adWidth: CGFloat = 300
var adHeight: CGFloat = 50
var banner = ANBannerAdView()
var adKey : String = ""
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Banner Native Ad"
viewNative.isHidden = true
if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerNativeAd.testRTBBannerNative) || ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerNativeAd.testRTBBannerNativeRendering) {
adKey = PlacementTestConstants.BannerNativeAd.testRTBBannerNative
loadBannerNativeAd()
}
}
func loadBannerNativeAd() {
let bannerAdObject : BannerAdObject! = AdObjectModel.decodeBannerObject()
if bannerAdObject != nil {
if let placement = bannerAdObject?.adObject.placement{
var width : CGFloat = 1
var height : CGFloat = 1
if let widthValue = bannerAdObject?.width {
let widthValueInt : Int = Int(widthValue)!
width = CGFloat(widthValueInt)
}
if let heightValue = bannerAdObject?.height{
let heightValueInt : Int = Int(heightValue)!
height = CGFloat(heightValueInt)
}
let screenRect:CGRect = UIScreen.main.bounds
let originX = (screenRect.size.width / 2) - (width / 2)
let originY = (screenRect.size.height / 2) - (height / 2)
// Needed for when we create our ad view.
let rect = CGRect(x: originX, y: originY, width: width, height: height)
let size = CGSize(width: 1, height: 1)
// Make a banner ad view
let banner = ANBannerAdView(frame: rect, placementId: placement , adSize: size)
banner.rootViewController = self
banner.autoRefreshInterval = 60
banner.forceCreativeId = 154679174
banner.delegate = self
if ProcessInfo.processInfo.arguments.contains(PlacementTestConstants.BannerNativeAd.testRTBBannerNativeRendering) {
guard let enableNativeRendering = bannerAdObject.enableNativeRendering else { print("enableNativeRendering not found"); return }
banner.enableNativeRendering = enableNativeRendering
banner.shouldAllowNativeDemand = bannerAdObject!.isNative
}else{
banner.shouldAllowNativeDemand = bannerAdObject!.isNative
}
banner.clickThroughAction = ANClickThroughAction.openDeviceBrowser
// Since this example is for testing, we'll turn on PSAs and verbose logging.
banner.shouldServePublicServiceAnnouncements = true
ANLogManager.setANLogLevel(ANLogLevel.debug)
// Load an ad.
banner.loadAd()
self.banner = banner
}
}
}
func adDidReceiveAd(_ ad: Any) {
activityIndicator.stopAnimating()
if (ad is ANBannerAdView) {
self.view.addSubview(banner)
}
}
func ad(_ loadInstance: Any, didReceiveNativeAd responseInstance: Any) {
viewNative.isHidden = false
activityIndicator.stopAnimating()
viewNative.alpha = 1
var nativeAdResponse = ANNativeAdResponse()
nativeAdResponse = responseInstance as! ANNativeAdResponse
self.titleLabel.text = nativeAdResponse.title
self.bodyLabel.text = nativeAdResponse.body
self.sponsoredLabel.text = nativeAdResponse.sponsoredBy
if let iconImageURL = nativeAdResponse.iconImageURL{
self.iconImageView.downloaded(from : iconImageURL )
}
if let mainImageURL = nativeAdResponse.mainImageURL{
self.mainImageView.downloaded(from : mainImageURL )
}
callToActionButton.setTitle(nativeAdResponse.callToAction, for: .normal)
do {
try nativeAdResponse.registerView(forTracking: self.viewNative, withRootViewController: self, clickableViews: [callToActionButton])
} catch let error as NSError {
print(error)
}
}
func ad(_ ad: Any, requestFailedWithError error: Error) {
print("requestFailedWithError \(String(describing: error))")
}
}
extension UIImageView {
func downloaded(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) { // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloaded(from link: String, contentMode mode: UIView.ContentMode = .scaleAspectFit) { // for swift 4.2 syntax just use ===> mode: UIView.ContentMode
guard let url = URL(string: link) else { return }
downloaded(from: url, contentMode: mode)
}
}
| apache-2.0 | 09451a4d2e0aa362f4c951370e881194 | 39.89375 | 228 | 0.638545 | 5.064241 | false | true | false | false |
belkhadir/Beloved | Beloved/Constants.swift | 1 | 1058 | //
// Constants.swift
// Beloved
//
// Created by Anas Belkhadir on 31/01/2016.
// Copyright © 2016 Anas Belkhadir. All rights reserved.
//
import Foundation
extension FirebaseHelper {
struct Constants {
static let BASE_URL = "https://beloved.firebaseio.com"
static let USER_URL = "https://beloved.firebaseio.com/users"
static let MESSAGE_URL = "https://beloved.firebaseio.com/messages"
}
struct JSONKEY {
static let FIRST_NAME = "first_name"
static let LAST_NAME = "last_name"
static let EMAIL = "email"
static let USERNAME = "username"
static let USERS = "users"
static let MESSAGES = "messages"
static let MESSAGE = "message"
static let UID = "uid"
static let DATE = "date"
static let FRIEND = "ListOfFriend"
static let IMAGE = "image"
static let PASSWORD = "password"
static let SENDERID = "senderId"
static let MESSAGEID = "messageId"
}
}
| mit | a2e55cf3d3eece1931534daa75e28eb5 | 23.022727 | 74 | 0.586566 | 4.049808 | false | false | false | false |
apple/swift | test/Concurrency/async_main.swift | 1 | 4828 | // RUN: %target-swift-frontend -emit-sil -disable-availability-checking -parse-as-library %s | %FileCheck %s --check-prefix=CHECK-SIL
// RUN: %target-build-swift -Xfrontend -disable-availability-checking -Xfrontend -parse-as-library %s -o %t_binary
// RUN: %target-codesign %t_binary
// RUN: %target-run %t_binary | %FileCheck %s --check-prefix=CHECK-EXEC
// REQUIRES: concurrency
// REQUIRES: executable_test
// REQUIRES: OS=macosx || OS=ios
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
@MainActor
var foo: Int = 42
func asyncFunc() async {
print("Hello World!")
}
@main struct MyProgram {
static func main() async throws {
print("\(foo)")
foo += 1
await asyncFunc()
print("\(foo)")
}
}
// CHECK-EXEC: 42
// CHECK-EXEC-NEXT: Hello World!
// CHECK-EXEC-NEXT: 43
// static MyProgram.main()
// CHECK-SIL-LABEL: sil hidden @$s10async_main9MyProgramV0B0yyYaKFZ : $@convention(method) @async (@thin MyProgram.Type) -> @error any Error
// static MyProgram.$main()
// CHECK-SIL-LABEL: sil hidden @$s10async_main9MyProgramV5$mainyyYaKFZ : $@convention(method) @async (@thin MyProgram.Type) -> @error any Error
// async_Main
// CHECK-SIL-LABEL: sil hidden @async_Main : $@convention(thin) @async () -> () {
// call main
// CHECK-SIL: %0 = metatype $@thin MyProgram.Type // user: %2
// CHECK-SIL-NEXT: // function_ref static MyProgram.$main()
// CHECK-SIL-NEXT: %1 = function_ref @$s10async_main9MyProgramV5$mainyyYaKFZ : $@convention(method) @async (@thin MyProgram.Type) -> @error any Error // user: %2
// CHECK-SIL-NEXT: try_apply %1(%0) : $@convention(method) @async (@thin MyProgram.Type) -> @error any Error, normal bb1, error bb2 // id: %2
// unwrap error and exit or explode
// CHECK-SIL: bb1(%3 : $()):
// CHECK-SIL-NEXT: %4 = integer_literal $Builtin.Int32, 0
// CHECK-SIL-NEXT: %5 = struct $Int32 (%4 : $Builtin.Int32)
// CHECK-SIL-NEXT: // function_ref exit
// CHECK-SIL-NEXT: %6 = function_ref @exit : $@convention(c) (Int32) -> Never
// CHECK-SIL-NEXT: %7 = apply %6(%5) : $@convention(c) (Int32) -> Never
// CHECK-SIL-NEXT: unreachable
// CHECK-SIL: bb2(%9 : $any Error):
// CHECK-SIL-NEXT: %10 = builtin "errorInMain"(%9 : $any Error) : $()
// CHECK-SIL-NEXT: unreachable
// main
// CHECK-SIL-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<Optional<UnsafeMutablePointer<Int8>>>) -> Int32 {
// CHECK-SIL: // function_ref async_Main
// CHECK-SIL-NEXT: %2 = function_ref @async_Main : $@convention(thin) @async () -> ()
// CHECK-SIL-NEXT: %3 = integer_literal $Builtin.Int64, 2048
// CHECK-SIL-NEXT: %4 = struct $Int (%3 : $Builtin.Int64)
// CHECK-SIL-NEXT: %5 = metatype $@thick ().Type
// CHECK-SIL-NEXT: %6 = init_existential_metatype %5 : $@thick ().Type, $@thick any Any.Type
// CHECK-SIL-NEXT: // function_ref thunk for @escaping @convention(thin) @async () -> ()
// CHECK-SIL-NEXT: %7 = function_ref @$sIetH_yts5Error_pIegHrzo_TR : $@convention(thin) @async (@convention(thin) @async () -> ()) -> (@out (), @error any Error)
// CHECK-SIL-NEXT: %8 = partial_apply [callee_guaranteed] %7(%2) : $@convention(thin) @async (@convention(thin) @async () -> ()) -> (@out (), @error any Error)
// CHECK-SIL-NEXT: %9 = convert_function %8 : $@async @callee_guaranteed () -> (@out (), @error any Error) to $@async @callee_guaranteed @substituted <τ_0_0> () -> (@out τ_0_0, @error any Error) for <()>
// CHECK-SIL-NEXT: %10 = builtin "createAsyncTask"<()>(%4 : $Int, %6 : $@thick any Any.Type, %9 : $@async @callee_guaranteed @substituted <τ_0_0> () -> (@out τ_0_0, @error any Error) for <()>) : $(Builtin.NativeObject, Builtin.RawPointer)
// CHECK-SIL-NEXT: %11 = tuple_extract %10 : $(Builtin.NativeObject, Builtin.RawPointer), 0
// CHECK-SIL-NEXT: // function_ref swift_job_run
// CHECK-SIL-NEXT: %12 = function_ref @swift_job_run : $@convention(thin) (UnownedJob, UnownedSerialExecutor) -> ()
// CHECK-SIL-NEXT: %13 = builtin "convertTaskToJob"(%11 : $Builtin.NativeObject) : $Builtin.Job
// CHECK-SIL-NEXT: %14 = struct $UnownedJob (%13 : $Builtin.Job)
// CHECK-SIL-NEXT: // function_ref swift_task_getMainExecutor
// CHECK-SIL-NEXT: %15 = function_ref @swift_task_getMainExecutor : $@convention(thin) () -> Builtin.Executor
// CHECK-SIL-NEXT: %16 = apply %15() : $@convention(thin) () -> Builtin.Executor
// CHECK-SIL-NEXT: %17 = struct $UnownedSerialExecutor (%16 : $Builtin.Executor)
// CHECK-SIL-NEXT: %18 = apply %12(%14, %17) : $@convention(thin) (UnownedJob, UnownedSerialExecutor) -> ()
// CHECK-SIL-NEXT: // function_ref swift_task_asyncMainDrainQueue
// CHECK-SIL-NEXT: %19 = function_ref @swift_task_asyncMainDrainQueue : $@convention(thin) () -> Never
// CHECK-SIL-NEXT: %20 = apply %19() : $@convention(thin) () -> Never
// CHECK-SIL-NEXT: unreachable
| apache-2.0 | b9af14d7634a96a07e4437b9effa46a3 | 52.6 | 239 | 0.658582 | 3.070656 | false | false | false | false |
jairoeli/Habit | Zero/Sources/Models/Habit.swift | 1 | 957 | //
// Habit.swift
// Zero
//
// Created by Jairo Eli de Leon on 5/8/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import Foundation
struct Habit: ModelType, Identifiable {
var id: String = UUID().uuidString
var title: String
var memo: String?
var value: Int = 0
init(title: String, memo: String? = nil) {
self.title = title
self.memo = memo
}
init?(dictionary: [String: Any]) {
guard let id = dictionary["id"] as? String,
let title = dictionary["title"] as? String
else { return nil }
self.id = id
self.title = title
self.memo = dictionary["memo"] as? String
self.value = dictionary["value"] as? Int ?? 0
}
func asDictionary() -> [String: Any] {
var dictionary: [String: Any] = [
"id": self.id,
"title": self.title,
"value": self.value
]
if let memo = self.memo {
dictionary["memo"] = memo
}
return dictionary
}
}
| mit | 864d83486cf61ccbfbd990cc557a16fc | 18.895833 | 60 | 0.59267 | 3.523985 | false | false | false | false |
shuoli84/RxSwift | RxSwift/RxSwift/Observables/Implementations/TakeUntil.swift | 16 | 3500 | //
// TakeUntil.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/7/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class TakeUntilSinkOther<ElementType, Other, O: ObserverType where O.Element == ElementType> : ObserverType {
typealias Parent = TakeUntilSink<ElementType, Other, O>
typealias Element = Other
let parent: Parent
let singleAssignmentDisposable = SingleAssignmentDisposable()
var disposable: Disposable {
get {
return abstractMethod()
}
set(value) {
singleAssignmentDisposable.disposable = value
}
}
init(parent: Parent) {
self.parent = parent
#if TRACE_RESOURCES
OSAtomicIncrement32(&resourceCount)
#endif
}
func on(event: Event<Element>) {
switch event {
case .Next:
parent.lock.performLocked {
trySendCompleted(parent.observer)
parent.dispose()
}
case .Error(let e):
parent.lock.performLocked {
trySendError(parent.observer, e)
parent.dispose()
}
case .Completed:
parent.lock.performLocked { () -> Void in
parent.open = true
singleAssignmentDisposable.dispose()
}
}
}
#if TRACE_RESOURCES
deinit {
OSAtomicDecrement32(&resourceCount)
}
#endif
}
class TakeUntilSink<ElementType, Other, O: ObserverType where O.Element == ElementType> : Sink<O>, ObserverType {
typealias Element = ElementType
typealias Parent = TakeUntil<Element, Other>
let parent: Parent
let lock = NSRecursiveLock()
var open = false
init(parent: Parent, observer: O, cancel: Disposable) {
self.parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(event: Event<Element>) {
switch event {
case .Next:
if open {
trySend(observer, event)
}
else {
lock.performLocked {
trySend(observer, event)
}
}
break
case .Error:
lock.performLocked {
trySend(observer, event)
self.dispose()
}
break
case .Completed:
lock.performLocked {
trySend(observer, event)
self.dispose()
}
break
}
}
func run() -> Disposable {
let otherObserver = TakeUntilSinkOther(parent: self)
let otherSubscription = parent.other.subscribeSafe(otherObserver)
otherObserver.disposable = otherSubscription
let sourceSubscription = parent.source.subscribeSafe(self)
return CompositeDisposable(sourceSubscription, otherSubscription)
}
}
class TakeUntil<Element, Other>: Producer<Element> {
let source: Observable<Element>
let other: Observable<Other>
init(source: Observable<Element>, other: Observable<Other>) {
self.source = source
self.other = other
}
override func run<O : ObserverType where O.Element == Element>(observer: O, cancel: Disposable, setSink: (Disposable) -> Void) -> Disposable {
let sink = TakeUntilSink(parent: self, observer: observer, cancel: cancel)
setSink(sink)
return sink.run()
}
} | mit | 79ace662f2dc8c2f9a1d14b5166d561f | 26.139535 | 146 | 0.572571 | 5.043228 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/ViewControllers/OWSPinSetupViewController.swift | 1 | 15912 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
@objc(OWSPinSetupViewController)
public class PinSetupViewController: OWSViewController {
private let pinTextField = UITextField()
private lazy var pinStrokeNormal = pinTextField.addBottomStroke()
private lazy var pinStrokeError = pinTextField.addBottomStroke(color: .ows_destructiveRed, strokeWidth: 2)
private let validationWarningLabel = UILabel()
enum Mode {
case creating
case recreating
case changing
case confirming(pinToMatch: String)
var isChanging: Bool {
guard case .changing = self else { return false }
return true
}
}
private let mode: Mode
private let initialMode: Mode
enum ValidationState {
case valid
case tooShort
case tooLong
case mismatch
var isInvalid: Bool {
return self != .valid
}
}
private var validationState: ValidationState = .valid {
didSet {
updateValidationWarnings()
}
}
private let completionHandler: () -> Void
init(mode: Mode, initialMode: Mode? = nil, completionHandler: @escaping () -> Void) {
self.mode = mode
self.initialMode = initialMode ?? mode
self.completionHandler = completionHandler
super.init(nibName: nil, bundle: nil)
if case .confirming = self.initialMode {
owsFailDebug("pin setup flow should never start in the confirming state")
}
}
@objc
convenience init(completionHandler: @escaping () -> Void) {
self.init(mode: .creating, completionHandler: completionHandler)
}
@objc
class func changing(completionHandler: @escaping () -> Void) -> PinSetupViewController {
return .init(mode: .changing, completionHandler: completionHandler)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Don't hide the nav bar when changing
guard !initialMode.isChanging else { return }
navigationController?.setNavigationBarHidden(true, animated: false)
}
public override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// TODO: Maybe do this in will appear, to avoid the keyboard sliding in when the view is pushed?
pinTextField.becomeFirstResponder()
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// Don't hide the nav bar when changing
guard !initialMode.isChanging else { return }
navigationController?.setNavigationBarHidden(false, animated: false)
}
override public var preferredStatusBarStyle: UIStatusBarStyle {
return Theme.isDarkThemeEnabled ? .lightContent : .default
}
override public func loadView() {
view = UIView()
if navigationController == nil {
owsFailDebug("This view should always be presented in a nav controller")
}
view.backgroundColor = Theme.backgroundColor
view.layoutMargins = .zero
let topRow: UIView?
let titleLabel: UILabel?
// We have a nav bar and use the nav bar back button + title
if initialMode.isChanging {
topRow = nil
titleLabel = nil
title = NSLocalizedString("PIN_CREATION_CHANGING_TITLE", comment: "Title of the 'pin creation' recreation view.")
// We have no nav bar and build our own back button + title label
} else {
// Back button
let topButton = UIButton()
let topButtonImage = CurrentAppContext().isRTL ? #imageLiteral(resourceName: "NavBarBackRTL") : #imageLiteral(resourceName: "NavBarBack")
topButton.setTemplateImage(topButtonImage, tintColor: Theme.secondaryColor)
topButton.autoSetDimensions(to: CGSize(width: 40, height: 40))
topButton.addTarget(self, action: #selector(navigateBack), for: .touchUpInside)
let topButtonRow = UIView()
topButtonRow.addSubview(topButton)
topButton.autoPinEdge(toSuperviewEdge: .leading)
topButton.autoPinHeightToSuperview()
// Title
let label = UILabel()
label.textColor = Theme.primaryColor
label.font = UIFont.ows_dynamicTypeTitle1Clamped.ows_semiBold()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
titleLabel = label
let arrangedSubviews: [UIView]
// If we're in creating mode AND we're the rootViewController, don't allow going back
if case .creating = mode, navigationController?.viewControllers.first == self {
arrangedSubviews = [UIView.spacer(withHeight: 40), label, UIView.spacer(withHeight: 10)]
} else {
arrangedSubviews = [topButtonRow, label, UIView.spacer(withHeight: 10)]
}
let row = UIStackView(arrangedSubviews: arrangedSubviews)
row.axis = .vertical
row.distribution = .fill
topRow = row
}
switch initialMode {
case .recreating:
titleLabel?.text = NSLocalizedString("PIN_CREATION_RECREATION_TITLE", comment: "Title of the 'pin creation' recreation view.")
default:
titleLabel?.text = NSLocalizedString("PIN_CREATION_TITLE", comment: "Title of the 'pin creation' view.")
}
// Explanation
let explanationLabel = UILabel()
explanationLabel.textColor = Theme.secondaryColor
explanationLabel.font = .ows_dynamicTypeSubheadlineClamped
let placeholderText: String
switch mode {
case .creating, .changing:
let explanationText = NSLocalizedString("PIN_CREATION_EXPLANATION",
comment: "The explanation in the 'pin creation' view.")
let explanationBoldText = NSLocalizedString("PIN_CREATION_BOLD_EXPLANATION",
comment: "The bold portion of the explanation in the 'pin creation' view.")
let attributedExplanation = NSAttributedString(string: explanationText) + " " + NSAttributedString(string: explanationBoldText, attributes: [.font: UIFont.ows_dynamicTypeSubheadlineClamped.ows_semiBold()])
explanationLabel.attributedText = attributedExplanation
placeholderText = NSLocalizedString("PIN_CREATION_PIN_CREATION_PLACEHOLDER", comment: "The placeholder when creating a pin in the 'pin creation' view.")
case .recreating:
let explanationText = NSLocalizedString("PIN_CREATION_RECREATION_EXPLANATION",
comment: "The re-creation explanation in the 'pin creation' view.")
let explanationBoldText = NSLocalizedString("PIN_CREATION_RECREATION_BOLD_EXPLANATION",
comment: "The bold portion of the re-creation explanation in the 'pin creation' view.")
let attributedExplanation = NSAttributedString(string: explanationText) + " " + NSAttributedString(string: explanationBoldText, attributes: [.font: UIFont.ows_dynamicTypeSubheadlineClamped.ows_semiBold()])
explanationLabel.attributedText = attributedExplanation
placeholderText = NSLocalizedString("PIN_CREATION_PIN_CREATION_PLACEHOLDER", comment: "The placeholder when creating a pin in the 'pin creation' view.")
case .confirming:
explanationLabel.text = NSLocalizedString("PIN_CREATION_CONFIRMATION_EXPLANATION",
comment: "The explanation of confirmation in the 'pin creation' view.")
placeholderText = NSLocalizedString("PIN_CREATION_PIN_CONFIRMATION_PLACEHOLDER", comment: "The placeholder when confirming a pin in the 'pin creation' view.")
}
explanationLabel.numberOfLines = 0
explanationLabel.textAlignment = .center
explanationLabel.lineBreakMode = .byWordWrapping
explanationLabel.accessibilityIdentifier = "pinCreation.explanationLabel"
// Pin text field
pinTextField.delegate = self
pinTextField.keyboardType = .numberPad
pinTextField.textColor = Theme.primaryColor
pinTextField.font = .ows_dynamicTypeBodyClamped
pinTextField.isSecureTextEntry = true
pinTextField.defaultTextAttributes.updateValue(5, forKey: .kern)
pinTextField.keyboardAppearance = Theme.keyboardAppearance
pinTextField.setContentHuggingHorizontalLow()
pinTextField.setCompressionResistanceHorizontalLow()
pinTextField.autoSetDimension(.height, toSize: 40)
pinTextField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [.foregroundColor: Theme.placeholderColor])
pinTextField.accessibilityIdentifier = "pinCreation.pinTextField"
validationWarningLabel.textColor = .ows_destructiveRed
validationWarningLabel.font = UIFont.ows_dynamicTypeCaption1Clamped
validationWarningLabel.accessibilityIdentifier = "pinCreation.validationWarningLabel"
let pinStack = UIStackView(arrangedSubviews: [
pinTextField,
UIView.spacer(withHeight: 10),
validationWarningLabel
])
pinStack.axis = .vertical
pinStack.alignment = .fill
let pinStackRow = UIView()
pinStackRow.addSubview(pinStack)
pinStack.autoHCenterInSuperview()
pinStack.autoPinHeightToSuperview()
pinStack.autoSetDimension(.width, toSize: 227)
pinStackRow.setContentHuggingVerticalHigh()
let font = UIFont.ows_dynamicTypeBodyClamped.ows_mediumWeight()
let buttonHeight = OWSFlatButton.heightForFont(font)
let nextButton = OWSFlatButton.button(
title: NSLocalizedString("BUTTON_NEXT",
comment: "Label for the 'next' button."),
font: font,
titleColor: .white,
backgroundColor: .ows_materialBlue,
target: self,
selector: #selector(nextPressed)
)
nextButton.autoSetDimension(.height, toSize: buttonHeight)
nextButton.accessibilityIdentifier = "pinCreation.nextButton"
let topSpacer = UIView.vStretchingSpacer()
let bottomSpacer = UIView.vStretchingSpacer()
var arrangedSubviews = [
explanationLabel,
topSpacer,
pinStackRow,
bottomSpacer,
UIView.spacer(withHeight: 10),
nextButton
]
if let topRow = topRow {
arrangedSubviews.insert(topRow, at: 0)
}
let stackView = UIStackView(arrangedSubviews: arrangedSubviews)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.layoutMargins = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
stackView.isLayoutMarginsRelativeArrangement = true
view.addSubview(stackView)
stackView.autoPinWidthToSuperview()
stackView.autoPin(toTopLayoutGuideOf: self, withInset: 0)
autoPinView(toBottomOfViewControllerOrKeyboard: stackView, avoidNotch: true)
// Ensure whitespace is balanced, so inputs are vertically centered.
topSpacer.autoMatch(.height, to: .height, of: bottomSpacer)
updateValidationWarnings()
}
// MARK: - Events
@objc func navigateBack() {
Logger.info("")
if case .recreating = mode {
dismiss(animated: true, completion: nil)
} else {
navigationController?.popViewController(animated: true)
}
}
@objc func nextPressed() {
Logger.info("")
tryToContinue()
}
private func tryToContinue() {
Logger.info("")
guard let pin = pinTextField.text?.ows_stripped(), pin.count >= kMin2FAPinLength else {
validationState = .tooShort
return
}
guard FeatureFlags.registrationLockV2 || pin.count <= kMax2FAv1PinLength else {
validationState = .tooLong
return
}
if case .confirming(let pinToMatch) = mode, pinToMatch != pin {
validationState = .mismatch
return
}
switch mode {
case .creating, .changing, .recreating:
let confirmingVC = PinSetupViewController(
mode: .confirming(pinToMatch: pin),
initialMode: initialMode,
completionHandler: completionHandler
)
navigationController?.pushViewController(confirmingVC, animated: true)
case .confirming:
enable2FAAndContinue(withPin: pin)
}
}
private func updateValidationWarnings() {
AssertIsOnMainThread()
pinStrokeNormal.isHidden = validationState.isInvalid
pinStrokeError.isHidden = !validationState.isInvalid
validationWarningLabel.isHidden = !validationState.isInvalid
switch validationState {
case .tooShort:
validationWarningLabel.text = NSLocalizedString("PIN_CREATION_TOO_SHORT_ERROR",
comment: "Label indicating that the attempted PIN is too short")
case .tooLong:
validationWarningLabel.text = NSLocalizedString("PIN_CREATION_TOO_LONG_ERROR",
comment: "Label indicating that the attempted PIN is too long")
case .mismatch:
validationWarningLabel.text = NSLocalizedString("PIN_CREATION_MISMATCH_ERROR",
comment: "Label indicating that the attempted PIN does not match the first PIN")
default:
break
}
}
private func enable2FAAndContinue(withPin pin: String) {
Logger.debug("")
pinTextField.resignFirstResponder()
ModalActivityIndicatorViewController.present(fromViewController: self, canCancel: false) { modalVC in
OWS2FAManager.shared().requestEnable2FA(withPin: pin, success: { [weak self] in
AssertIsOnMainThread()
modalVC.dismiss {
self?.completionHandler()
}
}, failure: { error in
AssertIsOnMainThread()
Logger.error("Failed to enable 2FA with error: \(error)")
// The client may have fallen out of sync with the service.
// Try to get back to a known good state by disabling 2FA
// whenever enabling it fails.
OWS2FAManager.shared().disable2FA(success: nil, failure: nil)
modalVC.dismiss {
OWSAlerts.showErrorAlert(message: NSLocalizedString("ENABLE_2FA_VIEW_COULD_NOT_ENABLE_2FA", comment: "Error indicating that attempt to enable 'two-factor auth' failed."))
}
})
}
}
}
// MARK: -
extension PinSetupViewController: UITextFieldDelegate {
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
ViewControllerUtils.ows2FAPINTextField(textField, shouldChangeCharactersIn: range, replacementString: string)
// Reset the validation state to clear errors, since the user is trying again
validationState = .valid
// Inform our caller that we took care of performing the change.
return false
}
}
| gpl-3.0 | dbfe942416de902a08e650cfbe93fb9d | 37.809756 | 217 | 0.636878 | 5.35938 | false | false | false | false |
shhuangtwn/ProjectLynla | Pods/SwiftCharts/SwiftCharts/Layers/ChartDividersLayer.swift | 1 | 3300 | //
// ChartDividersLayer.swift
// SwiftCharts
//
// Created by ischuetz on 21/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
public struct ChartDividersLayerSettings {
let linesColor: UIColor
let linesWidth: CGFloat
let start: CGFloat // points from start to axis, axis is 0
let end: CGFloat // points from axis to end, axis is 0
let onlyVisibleValues: Bool
public init(linesColor: UIColor = UIColor.grayColor(), linesWidth: CGFloat = 0.3, start: CGFloat = 5, end: CGFloat = 5, onlyVisibleValues: Bool = false) {
self.linesColor = linesColor
self.linesWidth = linesWidth
self.start = start
self.end = end
self.onlyVisibleValues = onlyVisibleValues
}
}
public enum ChartDividersLayerAxis {
case X, Y, XAndY
}
public class ChartDividersLayer: ChartCoordsSpaceLayer {
private let settings: ChartDividersLayerSettings
private let xScreenLocs: [CGFloat]
private let yScreenLocs: [CGFloat]
let axis: ChartDividersLayerAxis
public init(xAxis: ChartAxisLayer, yAxis: ChartAxisLayer, innerFrame: CGRect, axis: ChartDividersLayerAxis = .XAndY, settings: ChartDividersLayerSettings) {
self.axis = axis
self.settings = settings
func screenLocs(axisLayer: ChartAxisLayer) -> [CGFloat] {
let values = settings.onlyVisibleValues ? axisLayer.axisValues.filter{!$0.hidden} : axisLayer.axisValues
return values.map{axisLayer.screenLocForScalar($0.scalar)}
}
self.xScreenLocs = screenLocs(xAxis)
self.yScreenLocs = screenLocs(yAxis)
super.init(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame)
}
private func drawLine(context context: CGContextRef, color: UIColor, width: CGFloat, p1: CGPoint, p2: CGPoint) {
ChartDrawLine(context: context, p1: p1, p2: p2, width: width, color: color)
}
override public func chartViewDrawing(context context: CGContextRef, chart: Chart) {
let xScreenLocs = self.xScreenLocs
let yScreenLocs = self.yScreenLocs
if self.axis == .X || self.axis == .XAndY {
for xScreenLoc in xScreenLocs {
let x1 = xScreenLoc
let y1 = self.xAxis.lineP1.y + (self.xAxis.low ? -self.settings.end : self.settings.end)
let x2 = xScreenLoc
let y2 = self.xAxis.lineP1.y + (self.xAxis.low ? self.settings.start : -self.settings.start)
self.drawLine(context: context, color: self.settings.linesColor, width: self.settings.linesWidth, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
if self.axis == .Y || self.axis == .XAndY {
for yScreenLoc in yScreenLocs {
let x1 = self.yAxis.lineP1.x + (self.yAxis.low ? -self.settings.start : self.settings.start)
let y1 = yScreenLoc
let x2 = self.yAxis.lineP1.x + (self.yAxis.low ? self.settings.end : self.settings.end)
let y2 = yScreenLoc
self.drawLine(context: context, color: self.settings.linesColor, width: self.settings.linesWidth, p1: CGPointMake(x1, y1), p2: CGPointMake(x2, y2))
}
}
}
}
| mit | e0d620d69f783ebe46d1ea806e42700e | 38.759036 | 163 | 0.638182 | 3.961585 | false | false | false | false |
andrewgrant/TodoApp | TodoApp/EditListViewController.swift | 1 | 1611 | //
// EditListViewController.swift
// EditReminders
//
// Created by Andrew Grant on 5/26/15.
// Copyright (c) Andrew Grant. All rights reserved.
//
import UIKit
class EditListViewController : UITableViewController
{
// MARK: - Properties
@IBOutlet var saveBarButton : UIBarButtonItem!
@IBOutlet var titleTextField : UITextField!
var editList : TodoList!
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if editList != nil {
self.titleTextField.text = editList.title
self.navigationItem.title = editList.title
}
else {
self.navigationItem.rightBarButtonItem = saveBarButton
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if editList != nil && titleTextField.text?.characters.count > 0 {
editList.title = titleTextField.text
var error : NSError?
TodoStore.sharedInstance.saveObject(editList, error: &error)
if error != nil {
print(error!.description)
}
}
}
// MARK: - Actions
@IBAction func onSave(sender : UIBarButtonItem)
{
if titleTextField.text?.characters.count > 0 {
// create a new list, it will be saved when we disappear
editList = TodoList(title: titleTextField.text!)
self.navigationController?.popViewControllerAnimated(true)
}
}
}
| mit | e6046b6f9649116c33e66e9ba9370256 | 24.983871 | 73 | 0.577902 | 5.247557 | false | false | false | false |
caronae/caronae-ios | Caronae/Ride/RideViewController.swift | 1 | 23686 | import Foundation
import SVProgressHUD
import InputMask
class RideViewController: UIViewController {
// Ride info
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var referenceLabel: UILabel!
@IBOutlet weak var driverPhoto: UIImageView!
@IBOutlet weak var phoneButton: UIButton!
@IBOutlet weak var driverNameLabel: UILabel!
@IBOutlet weak var driverCourseLabel: UILabel!
@IBOutlet weak var mutualFriendsLabel: UILabel!
@IBOutlet weak var driverMessageLabel: UILabel!
@IBOutlet weak var routeLabel: UILabel!
@IBOutlet weak var carDetailsView: UIView!
@IBOutlet weak var carPlateLabel: UILabel!
@IBOutlet weak var carModelLabel: UILabel!
@IBOutlet weak var carColorLabel: UILabel!
@IBOutlet weak var noRidersLabel: UILabel!
// Assets
@IBOutlet weak var headerView: UIView!
@IBOutlet weak var phoneView: UIView!
@IBOutlet weak var ridersView: UIView!
@IBOutlet weak var mutualFriendsView: UIView!
@IBOutlet weak var mutualFriendsCollectionHeight: NSLayoutConstraint!
@IBOutlet weak var finishRideView: UIView!
@IBOutlet weak var shareRideView: UIView!
@IBOutlet weak var ridersCollectionView: UICollectionView!
@IBOutlet weak var mutualFriendsCollectionView: UICollectionView!
@IBOutlet weak var clockIcon: UIImageView!
@IBOutlet weak var carIconPlate: UIImageView!
@IBOutlet weak var carIconModel: UIImageView!
@IBOutlet weak var requestsTable: UITableView!
@IBOutlet weak var requestsTableHeight: NSLayoutConstraint!
// Buttons
@IBOutlet weak var requestRideButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var finishRideButton: UIButton!
@IBOutlet weak var shareRideButton: UIButton!
var ride: Ride!
var shouldOpenChatWindow = false
var shouldLoadFromRealm = true
var rideIsFull = false
var requesters = [User]()
var mutualFriends = [User]()
var selectedUser: User?
var color: UIColor! {
didSet {
headerView.backgroundColor = color
clockIcon.tintColor = color
dateLabel.textColor = color
driverPhoto.layer.borderColor = color?.cgColor
carIconPlate.tintColor = color
carIconModel.tintColor = color
finishRideButton.layer.borderColor = color?.cgColor
finishRideButton.tintColor = color
shareRideButton.layer.borderColor = color?.cgColor
shareRideButton.tintColor = color
requestRideButton.backgroundColor = color
finishRideButton.setTitleColor(color, for: .normal)
shareRideButton.setTitleColor(color, for: .normal)
}
}
struct CaronaeRequestButtonState {
static let new = "PEGAR CARONA"
static let alreadyRequested = "SOLICITAÇÃO ENVIADA"
static let fullRide = "CARONA CHEIA"
}
class func instance(for ride: Ride) -> RideViewController {
let rideVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "RideViewController") as! RideViewController
rideVC.ride = ride
return rideVC
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
// Load ride from realm database if available
if shouldLoadFromRealm {
self.loadRealmRide()
}
shouldLoadFromRealm = true
self.clearNotifications()
NotificationCenter.default.addObserver(self, selector: #selector(updateChatButtonBadge), name: .CaronaeDidUpdateNotifications, object: nil)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm | E | dd/MM"
let dateString = dateFormatter.string(from: ride.date).capitalized(after: "|")
titleLabel.text = ride.title.uppercased()
dateLabel.text = ride.going ? String(format: "Chegando às %@", dateString) : String(format: "Saindo às %@", dateString)
driverNameLabel.text = ride.driver.name
driverCourseLabel.text = ride.driver.occupation
referenceLabel.text = ride.place.isEmpty ? "---" : ride.place
routeLabel.text = ride.route.isEmpty ? "---" : ride.route.replacingOccurrences(of: ", ", with: "\n").replacingOccurrences(of: ",", with: "\n")
driverMessageLabel.text = ride.notes.isEmpty ? "---" : ride.notes
if let profilePictureURL = ride.driver.profilePictureURL, !profilePictureURL.isEmpty {
driverPhoto.crn_setImage(with: URL(string: profilePictureURL))
}
color = PlaceService.instance.color(forZone: ride.region)
let requestCellNib = UINib(nibName: String(describing: JoinRequestCell.self), bundle: nil)
requestsTable.register(requestCellNib, forCellReuseIdentifier: "Request Cell")
requestsTable.dataSource = self
requestsTable.delegate = self
requestsTable.rowHeight = 95.0
requestsTableHeight.constant = 0
if !ride.date.isInTheFuture() {
DispatchQueue.main.async {
self.shareRideView.removeFromSuperview()
}
}
if userIsDriver() {
configureRideForDriver()
} else if userIsRider() {
configureRideForRider()
} else {
configureRideForOutsider()
}
// Add gesture recognizer to phoneButton for longpress
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressPhoneButton))
phoneButton.addGestureRecognizer(longPressGesture)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if shouldOpenChatWindow {
openChatWindow()
shouldOpenChatWindow = false
}
}
// If the user is the driver of the ride, load pending join requests and hide 'join' button
func configureRideForDriver() {
self.loadJoinRequests()
self.updateChatButtonBadge()
DispatchQueue.main.async {
self.requestRideButton.removeFromSuperview()
self.mutualFriendsView.removeFromSuperview()
self.phoneView.removeFromSuperview()
if !self.ride.isActive || self.ride.date.isInTheFuture() {
self.finishRideView.removeFromSuperview()
}
}
// Car details
let user = UserService.instance.user!
carPlateLabel.text = user.carPlate?.uppercased()
carModelLabel.text = user.carModel
carColorLabel.text = user.carColor
}
// If the user is already a rider, hide 'join' button
func configureRideForRider() {
self.updateChatButtonBadge()
DispatchQueue.main.async {
self.requestRideButton.removeFromSuperview()
self.finishRideView.removeFromSuperview()
}
cancelButton.setTitle("DESISTIR", for: .normal)
let phoneMask = try! Mask(format: Caronae9PhoneNumberPattern)
let phoneNumber = ride.driver.phoneNumber!
let result = phoneMask.apply(toText: CaretString(string: phoneNumber, caretPosition: phoneNumber.endIndex))
let formattedPhoneNumber = result.formattedText.string
phoneButton.setTitle(formattedPhoneNumber, for: .normal)
// Car details
carPlateLabel.text = ride.driver.carPlate?.uppercased()
carModelLabel.text = ride.driver.carModel
carColorLabel.text = ride.driver.carColor
self.updateMutualFriends()
}
// If the user is not related to the ride, hide 'cancel' button, car details view, riders view
func configureRideForOutsider() {
DispatchQueue.main.async {
self.cancelButton.removeFromSuperview()
self.phoneView.removeFromSuperview()
self.carDetailsView.removeFromSuperview()
self.finishRideView.removeFromSuperview()
self.ridersView.removeFromSuperview()
}
// Update the state of the join request button if the user has already requested to join
if RideService.instance.hasRequestedToJoinRide(withID: ride.id) {
requestRideButton.isEnabled = false
requestRideButton.setTitle(CaronaeRequestButtonState.alreadyRequested, for: .normal)
} else if rideIsFull {
requestRideButton.isEnabled = false
requestRideButton.setTitle(CaronaeRequestButtonState.fullRide, for: .normal)
rideIsFull = false
} else {
requestRideButton.isEnabled = true
requestRideButton.setTitle(CaronaeRequestButtonState.new, for: .normal)
}
self.updateMutualFriends()
}
func updateMutualFriends() {
UserService.instance.mutualFriendsForUser(withFacebookID: ride.driver.facebookID, success: { mutualFriends, totalCount in
if !mutualFriends.isEmpty {
self.mutualFriends = mutualFriends
self.mutualFriendsCollectionHeight.constant = 40.0
self.mutualFriendsView.layoutIfNeeded()
self.mutualFriendsCollectionView.reloadData()
}
self.mutualFriendsLabel.text = totalCount > 0 ? String(format: "Amigos em comum: %ld no total e %ld no Caronaê", totalCount, mutualFriends.count) : "Amigos em comum: 0"
}, error: { error in
NSLog("Error loading mutual friends for user: %@", error.localizedDescription)
})
}
// MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ViewProfile" {
let profileVC = segue.destination as! ProfileViewController
profileVC.user = selectedUser
}
}
@objc func openChatWindow() {
let chatVC = ChatViewController(ride: ride, color: color)
navigationController?.show(chatVC, sender: self)
}
// MARK: IBActions
@objc func didLongPressPhoneButton() {
let alert = PhoneNumberAlert().actionSheet(view: self, buttonText: phoneButton.titleLabel!.text!, user: ride.driver)
self.present(alert!, animated: true, completion: nil)
}
@IBAction func didTapPhoneButton(_ sender: Any) {
guard let phoneNumber = ride.driver.phoneNumber else {
return
}
let phoneNumberURLString = String(format: "telprompt://%@", phoneNumber)
UIApplication.shared.openURL(URL(string: phoneNumberURLString)!)
}
@IBAction func didTapRequestRide(_ sender: UIButton) {
let alert = CaronaeAlertController(title: "Deseja mesmo solicitar a carona?",
message: "Ao confirmar, o motorista receberá uma notificação e poderá aceitar ou recusar a carona.",
preferredStyle: .alert)
alert?.addAction(SDCAlertAction(title: "Cancelar", style: .cancel, handler: nil))
alert?.addAction(SDCAlertAction(title: "Solicitar", style: .recommended, handler: { _ in
self.requestJoinRide()
}))
alert?.present(completion: nil)
}
@IBAction func viewUserProfile(_ sender: Any) {
selectedUser = User(value: ride.driver)
if !self.userIsDriver() && !self.userIsRider() {
// Hide driver's phone number
selectedUser?.phoneNumber = nil
}
performSegue(withIdentifier: "ViewProfile", sender: self)
}
@IBAction func didTapCancelRide(_ sender: Any) {
let alert = CaronaeAlertController(title: "Deseja mesmo desistir da carona?",
message: """
Você é livre para cancelar caronas caso não possa participar,
mas é importante fazer isso com responsabilidade.
Caso haja outros usuários na carona, eles serão notificados.
""",
preferredStyle: .alert)
alert?.addAction(SDCAlertAction(title: "Voltar", style: .cancel, handler: nil))
alert?.addAction(SDCAlertAction(title: "Desistir", style: .destructive, handler: { _ in
self.cancelRide()
}))
alert?.present(completion: nil)
}
@IBAction func didTapFinishRide(_ sender: Any) {
let alert = CaronaeAlertController(title: "E aí? Correu tudo bem?",
message: "Caso você tenha tido algum problema com a carona, use o Falaê para entrar em contato conosco.",
preferredStyle: .alert)
alert?.addAction(SDCAlertAction(title: "Cancelar", style: .cancel, handler: nil))
alert?.addAction(SDCAlertAction(title: "Concluir", style: .recommended, handler: { _ in
self.finishRide()
}))
alert?.present(completion: nil)
}
@IBAction func didTapShareRide(_ sender: Any) {
var rideToShare = "Vai uma Caronaê?\n\n"
rideToShare += String(format: "👤 %@\n", ride.driver.shortName)
rideToShare += String(format: "📍 %@\n", ride.title)
rideToShare += String(format: "🕐📅 %@\n", dateLabel.text!)
rideToShare += "Para solicitar uma vaga é só clicar nesse link aqui embaixo! 🚗🌿🙂 \n\n"
rideToShare += String(format: "%@/carona/%ld", CaronaeURLString.base, ride.id)
let activityVC = UIActivityViewController(activityItems: [rideToShare], applicationActivities: nil)
activityVC.excludedActivityTypes = [.addToReadingList]
present(activityVC, animated: true, completion: nil)
}
// MARK: Ride operations
func cancelRide() {
if self.userIsDriver() && ride.isRoutine {
let alert = UIAlertController(title: "Esta carona pertence a uma rotina.", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Desistir somente desta", style: .destructive, handler: { _ in
self.leaveRide()
}))
alert.addAction(UIAlertAction(title: "Desistir da rotina", style: .destructive, handler: { _ in
self.deleteRoutine()
}))
alert.addAction(UIAlertAction(title: "Cancelar", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
} else {
leaveRide()
}
}
func leaveRide() {
NSLog("Requesting to leave/cancel ride %ld", ride.id)
cancelButton.isEnabled = false
SVProgressHUD.show()
RideService.instance.leaveRide(withID: ride.id, success: {
SVProgressHUD.dismiss()
NSLog("User left the ride.")
lastAllRidesUpdate = Date.distantPast
self.navigationController?.popViewController(animated: true)
}, error: { error in
NSLog("Error leaving/cancelling ride: %@", error.localizedDescription)
SVProgressHUD.dismiss()
self.cancelButton.isEnabled = true
CaronaeAlertController.presentOkAlert(withTitle: "Algo deu errado.",
message: String(format: "Não foi possível cancelar sua carona. (%@)", error.localizedDescription))
})
}
func finishRide() {
NSLog("Requesting to finish ride %ld", ride.id)
finishRideButton.isEnabled = false
SVProgressHUD.show()
RideService.instance.finishRide(withID: ride.id, success: {
SVProgressHUD.dismiss()
NSLog("User finished the ride.")
self.navigationController?.popViewController(animated: true)
}, error: { error in
NSLog("Error finishing ride: %@", error.localizedDescription)
SVProgressHUD.dismiss()
self.finishRideButton.isEnabled = true
CaronaeAlertController.presentOkAlert(withTitle: "Algo deu errado.",
message: String(format: "Não foi possível concluir sua carona. (%@)", error.localizedDescription))
})
}
// MARK: Join request methods
func requestJoinRide() {
NSLog("Requesting to join ride %ld", ride.id)
requestRideButton.isEnabled = false
SVProgressHUD.show()
RideService.instance.requestJoinOnRide(ride, success: {
SVProgressHUD.dismiss()
NSLog("Done requesting ride.")
self.requestRideButton.setTitle(CaronaeRequestButtonState.alreadyRequested, for: .normal)
}, error: { error in
NSLog("Error requesting to join ride: %@", error.localizedDescription)
SVProgressHUD.dismiss()
self.requestRideButton.isEnabled = true
CaronaeAlertController.presentOkAlert(withTitle: "Algo deu errado.",
message: String(format: "Não foi possível solicitar a carona. (%@)", error.localizedDescription))
})
}
func loadJoinRequests() {
RideService.instance.getRequestersForRide(withID: ride.id, success: { users in
self.requesters = users
if !self.requesters.isEmpty {
self.requestsTable.reloadData()
self.adjustHeightOfTableview()
}
}, error: { error in
NSLog("Error loading join requests for ride %lu: %@", self.ride.id, error.localizedDescription)
CaronaeAlertController.presentOkAlert(withTitle: "Algo deu errado.",
message: String(format: "Não foi possível carregar as solicitações da sua carona. (%@)", error.localizedDescription))
})
}
}
// MARK: JoinRequestDelegate Methods (handle requests responses)
extension RideViewController: JoinRequestDelegate {
func handleAcceptedJoinRequest(of user: User, cell: JoinRequestCell) {
cell.setButtonsEnabled(false)
if ride.availableSlots == 1 && requesters.count > 1 {
let alert = CaronaeAlertController(title: String(format: "Deseja mesmo aceitar %@?", user.firstName),
message: "Ao aceitar, sua carona estará cheia e você irá recusar os outros caronistas.",
preferredStyle: .alert)
alert?.addAction(SDCAlertAction(title: "Cancelar", style: .cancel, handler: { _ in
cell.setButtonsEnabled(true)
}))
alert?.addAction(SDCAlertAction(title: "Aceitar", style: .recommended, handler: { _ in
self.answerJoinRequest(of: user, hasAccepted: true, cell: cell)
}))
alert?.present(completion: nil)
} else {
self.answerJoinRequest(of: user, hasAccepted: true, cell: cell)
}
}
func answerJoinRequest(of requestingUser: User, hasAccepted: Bool, cell: JoinRequestCell) {
cell.setButtonsEnabled(false)
RideService.instance.answerRequestOnRide(withID: ride.id, fromUser: requestingUser, accepted: hasAccepted, success: {
NSLog("Request for user %@ was %@", requestingUser.name, hasAccepted ? "accepted" : "not accepted")
self.removeJoinRequest(requestingUser: requestingUser)
if hasAccepted {
self.ridersCollectionView.reloadData()
self.removeAllJoinRequestIfNeeded()
}
}, error: { error in
NSLog("Error accepting join request: %@", error.localizedDescription)
cell.setButtonsEnabled(true)
})
}
func removeAllJoinRequestIfNeeded() {
if ride.availableSlots == 0 {
for requester in requesters {
self.removeJoinRequest(requestingUser: requester)
}
}
}
func removeJoinRequest(requestingUser: User) {
requestsTable.beginUpdates()
let index = requesters.index(of: requestingUser)!
requestsTable.deleteRows(at: [IndexPath(row: index, section: 0)], with: .automatic)
requesters.remove(at: index)
requestsTable.endUpdates()
self.adjustHeightOfTableview()
self.clearNotificationOfJoinRequest(from: requestingUser.id)
}
func tappedUserDetails(of user: User) {
self.selectedUser = user
performSegue(withIdentifier: "ViewProfile", sender: self)
}
}
// MARK: Table methods (Join requests)
extension RideViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return requesters.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Request Cell", for: indexPath) as! JoinRequestCell
cell.delegate = self
cell.configureCell(withUser: requesters[indexPath.row], andColor: color)
return cell
}
func adjustHeightOfTableview() {
self.view.layoutIfNeeded()
let height = CGFloat(self.requesters.count) * self.requestsTable.rowHeight
self.requestsTableHeight.constant = height
UIView.animate(withDuration: 0.25) {
self.view.layoutIfNeeded()
}
}
}
// MARK: Collection methods (Riders, Mutual friends)
extension RideViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if collectionView == ridersCollectionView {
// Show message if there is no riders
if ride.riders.isEmpty {
noRidersLabel.isHidden = false
} else {
noRidersLabel.isHidden = true
}
return ride.riders.count
} else {
return mutualFriends.count
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
var cell: RiderCell!
var user: User!
if collectionView == ridersCollectionView {
user = ride.riders[indexPath.row]
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Rider Cell", for: indexPath) as? RiderCell
} else {
user = self.mutualFriends[indexPath.row]
cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Friend Cell", for: indexPath) as? RiderCell
}
cell.configure(with: user)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: true)
if collectionView == ridersCollectionView {
let cell = collectionView.cellForItem(at: indexPath) as! RiderCell
self.selectedUser = cell.user
performSegue(withIdentifier: "ViewProfile", sender: self)
}
}
}
| gpl-3.0 | 27b88e257608e8bf1f97737c5af61436 | 40.824779 | 180 | 0.622911 | 4.891534 | false | false | false | false |
soapyigu/LeetCode_Swift | Search/SearchInRotatedSortedArray.swift | 1 | 1061 | /**
* Question Link: https://leetcode.com/problems/search-in-rotated-sorted-array/
* Primary idea: Binary Search, check left or right is sorted, then search in the part
*
* Time Complexity: O(logn), Space Complexity: O(1)
*/
class SearchInRotatedSortedArray {
func search(nums: [Int], _ target: Int) -> Int {
var left = 0
var right = nums.count - 1
var mid = 0
while left <= right {
mid = (right - left) / 2 + left
if nums[mid] == target {
return mid
}
if nums[mid] >= nums[left] {
if nums[mid] > target && target >= nums[left] {
right = mid - 1
} else {
left = mid + 1
}
} else {
if nums[mid] < target && target <= nums[right] {
left = mid + 1
} else {
right = mid - 1
}
}
}
return -1
}
} | mit | 942fcfb521ea5faa05eb3d8c846cd13b | 26.947368 | 88 | 0.415646 | 4.495763 | false | false | false | false |
milankamilya/SpringAnimation | Animation/LineAnimationViewController.swift | 1 | 4558 | //
// LineAnimationViewController.swift
// Animation
//
// Created by Milan Kamilya on 14/09/15.
// Copyright (c) 2015 innofied. All rights reserved.
//
import UIKit
class LineAnimationViewController: UIViewController {
//MARK:- CONTANTS
let shapeRect = CAShapeLayer()
let waitingRect = CAShapeLayer()
//MARK:- STORYBOARD COMPONENT
//MARK:- PUBLIC PROPERTIES
var toggle: Bool? = false
//MARK:- PRIVATE PROPERTIES
//MARK: - LIFE CYCLE METHODS
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.drawLine()
self.loadSpinningAnimation()
}
//MARK:- CUSTOM VIEW
func drawLine() {
let line = UIBezierPath()
line.moveToPoint(CGPointMake(0,100))
line.addLineToPoint(CGPointMake(250, 100))
line.addArcWithCenter(CGPointMake(250, 75), radius: CGFloat(25.0), startAngle: CGFloat(1.0*M_PI_2), endAngle: CGFloat(-3.0*M_PI_2), clockwise: false)
shapeRect.path = line.CGPath
shapeRect.strokeColor = UIColor.grayColor().CGColor
shapeRect.fillColor = UIColor.clearColor().CGColor
shapeRect.strokeStart = 0.0
shapeRect.strokeEnd = 0.6
self.view.layer.addSublayer(shapeRect)
}
@IBAction func toggleButtonClicked(sender: UIButton) {
if toggle! {
CATransaction.begin()
let start = CABasicAnimation(keyPath: "strokeStart")
start.toValue = 0.0
let end = CABasicAnimation(keyPath: "strokeEnd")
end.toValue = 0.61
// 4
let group = CAAnimationGroup()
group.animations = [start, end]
group.duration = 2.5
group.repeatCount = 1
group.delegate = self
self.shapeRect.addAnimation(group, forKey: "k")
CATransaction.setCompletionBlock({ () -> Void in
self.shapeRect.strokeStart = 0.0
self.shapeRect.strokeEnd = 0.61
self.toggle = false
println("Ehlloe")
})
CATransaction.commit()
} else {
CATransaction.begin()
let start = CABasicAnimation(keyPath: "strokeStart")
start.toValue = 0.61
let end = CABasicAnimation(keyPath: "strokeEnd")
end.toValue = 1
// 4
let group = CAAnimationGroup()
group.animations = [start, end]
group.duration = 2.5
group.repeatCount = 1
self.shapeRect.addAnimation(group, forKey: "k")
CATransaction.setCompletionBlock({ () -> Void in
self.shapeRect.strokeStart = 0.61
self.shapeRect.strokeEnd = 1.0
self.toggle = true
})
CATransaction.commit()
}
}
func loadSpinningAnimation() {
// Draw Path
let line = UIBezierPath()
line.moveToPoint(CGPointMake(150,200))
line.addLineToPoint(CGPointMake(200, 200))
line.addLineToPoint(CGPointMake(150, 100))
line.addLineToPoint(CGPointMake(200, 100))
line.closePath()
// ShapeLayer
waitingRect.path = line.CGPath
waitingRect.strokeColor = UIColor.grayColor().CGColor
waitingRect.fillColor = UIColor.clearColor().CGColor
waitingRect.strokeStart = 0.0
waitingRect.strokeEnd = 0.1
self.view.layer.addSublayer(waitingRect)
// Start animation
let start = CABasicAnimation(keyPath: "strokeStart")
start.toValue = 0.9
let end = CABasicAnimation(keyPath: "strokeEnd")
end.toValue = 1.0
let group = CAAnimationGroup()
group.animations = [start, end]
group.duration = 1.5
group.repeatCount = HUGE
group.autoreverses = false
waitingRect.addAnimation(group, forKey: "Spinning")
}
//MARK:- UTILITY METHODS
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
print("animationDidStop")
}
}
| mit | 285d4a4d1cae71382afc2af34de29848 | 26.96319 | 157 | 0.550461 | 5.075724 | false | false | false | false |
tensorflow/swift-apis | Tests/AnnotationTests/TFEagerTests.swift | 1 | 2329 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import TensorFlow
import XCTest
@testable import Tensor
final class AnnotationTFEagerTests: XCTestCase {
public struct SummaryNet: Layer {
public var dense1 = Dense<Float>(inputSize: 1, outputSize: 1)
public var dense2 = Dense<Float>(inputSize: 4, outputSize: 4)
public var dense3 = Dense<Float>(inputSize: 4, outputSize: 4)
public var flatten = Flatten<Float>()
@differentiable
public func callAsFunction(_ input: Tensor<Float>) -> Tensor<Float> {
let layer1 = dense1(input)
let layer2 = layer1.reshaped(to: [1, 4])
let layer3 = dense2(layer2)
let layer4 = dense3(layer3)
return flatten(layer4)
}
}
lazy var model: SummaryNet = { SummaryNet() }()
lazy var input: Tensor<Float> = { Tensor<Float>(ones: [1, 4, 1, 1]) }()
override func setUp() {
super.setUp()
LazyTensorBarrier()
}
func testLayerSummaryTensor() {
let annotations = model.summary(input: input)
XCTAssertEqual(annotations, Device.defaultTFEager.annotationsAvailable)
}
func testTensorAnnotations() {
let output = model(input)
let annotations = output.annotations
XCTAssertEqual(annotations, Device.defaultTFEager.annotationsAvailable)
}
func testTensorAnnotationsSummary() {
let output = model(input)
let annotations = output.summary
XCTAssertEqual(annotations, Device.defaultTFEager.annotationsAvailable)
}
}
extension AnnotationTFEagerTests {
static var allTests = [
("testLayerSummaryTensor", testLayerSummaryTensor),
("testTensorAnnotations", testTensorAnnotations),
("testTensorAnnotationsSummary", testTensorAnnotationsSummary),
]
}
XCTMain([
testCase(AnnotationTFEagerTests.allTests)
])
| apache-2.0 | 103385cb7e14193fe5c52e52bbcc669c | 30.90411 | 75 | 0.723486 | 4.173835 | false | true | false | false |
suwa-yuki/SamplePresentation | SamplePresentation/TableViewController.swift | 1 | 3607 | //
// TableViewController.swift
// SamplePresentation
//
// Created by suwa.yuki on 2014/10/06.
// Copyright (c) 2014年 underscore, Inc. All rights reserved.
//
import UIKit
class TableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
@IBAction func closeButtonDidTouch(sender: AnyObject) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
/*
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
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
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 31cf02c074a4310841a62fa6458caa65 | 33.333333 | 159 | 0.682108 | 5.580495 | false | false | false | false |
podverse/podverse-ios | Podverse/DeletingPodcasts.swift | 1 | 1434 | //
// DeletingPodcasts.swift
// Podverse
//
// Created by Mitchell Downey on 11/19/17.
// Copyright © 2017 Podverse LLC. All rights reserved.
//
import Foundation
final class DeletingPodcasts {
static let shared = DeletingPodcasts()
var podcastKeys = [String]()
func addPodcast(podcastId:String?, feedUrl:String?) {
if let podcastId = podcastId {
if self.podcastKeys.filter({$0 == podcastId}).count < 1 {
self.podcastKeys.append(podcastId)
}
} else if let feedUrl = feedUrl {
if self.podcastKeys.filter({$0 == feedUrl}).count < 1 {
self.podcastKeys.append(feedUrl)
}
}
}
func removePodcast(podcastId:String?, feedUrl:String?) {
if let podcastId = podcastId, let index = self.podcastKeys.index(of: podcastId) {
self.podcastKeys.remove(at: index)
} else if let feedUrl = feedUrl, let index = self.podcastKeys.index(of: feedUrl) {
self.podcastKeys.remove(at: index)
}
}
func hasMatchingId(podcastId:String) -> Bool {
if let _ = self.podcastKeys.index(of: podcastId) {
return true
}
return false
}
func hasMatchingUrl(feedUrl:String) -> Bool {
if let _ = self.podcastKeys.index(of: feedUrl) {
return true
}
return false
}
}
| agpl-3.0 | b7ef44681426f898cef6f7be082d7a9d | 27.098039 | 90 | 0.573622 | 4.129683 | false | false | false | false |
jessesquires/JSQCoreDataKit | Tests/ModelTests.swift | 1 | 8523 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015-present Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import ExampleModel
@testable import JSQCoreDataKit
import XCTest
// swiftlint:disable force_try
final class ModelTests: XCTestCase {
override func setUp() {
let model = CoreDataModel(name: modelName, bundle: modelBundle)
_ = try? model.removeExistingStore()
super.setUp()
}
func test_ThatSQLiteModel_InitializesSuccessfully() {
// GIVEN: a model name and bundle
// WHEN: we create a model
let model = CoreDataModel(name: modelName, bundle: modelBundle)
// THEN: the model has the correct name, bundle, and type
XCTAssertEqual(model.name, modelName)
XCTAssertEqual(model.bundle, modelBundle)
XCTAssertEqual(model.storeType, StoreType.sqlite(CoreDataModel.defaultDirectoryURL()))
// THEN: the model returns the correct database filename
XCTAssertEqual(model.databaseFileName, model.name + "." + ModelFileExtension.sqlite.rawValue)
// THEN: the store file is in the correct directory
#if os(iOS) || os(macOS) || os(watchOS)
let dir = "Documents"
#elseif os(tvOS)
let dir = "Caches"
#endif
let storeURLComponents = model.storeURL!.pathComponents
XCTAssertEqual(String(storeURLComponents.last!), model.databaseFileName)
XCTAssertEqual(String(storeURLComponents[storeURLComponents.count - 2]), dir)
XCTAssertTrue(model.storeURL!.isFileURL)
// THEN: the model is in its specified bundle
let modelURLComponents = model.modelURL.pathComponents
XCTAssertEqual(String(modelURLComponents.last!), model.name + ".momd")
#if os(iOS) || os(tvOS) || os(watchOS)
let count = modelURLComponents.count - 2
#elseif os(macOS)
let count = modelURLComponents.count - 3
#endif
XCTAssertEqual(String(modelURLComponents[count]), NSString(string: model.bundle.bundlePath).lastPathComponent)
// THEN: the managed object model does not assert
XCTAssertNotNil(model.managedObjectModel)
// THEN: the store doesn't need migration
XCTAssertFalse(model.needsMigration)
}
func test_ThatBinaryModel_InitializesSuccessfully() {
// GIVEN: a model name and bundle
// WHEN: we create a model
let model = CoreDataModel(name: modelName, bundle: modelBundle, storeType: .binary(URL(fileURLWithPath: NSTemporaryDirectory())))
// THEN: the model has the correct name, bundle, and type
XCTAssertEqual(model.name, modelName)
XCTAssertEqual(model.bundle, modelBundle)
XCTAssertEqual(model.storeType, StoreType.binary(URL(fileURLWithPath: NSTemporaryDirectory())))
// THEN: the model returns the correct database filename
XCTAssertEqual(model.databaseFileName, model.name)
// THEN: the store file is in the tmp directory
let storeURLComponents = model.storeURL!.pathComponents
XCTAssertEqual(String(storeURLComponents.last!), model.databaseFileName)
#if os(iOS) || os(tvOS) || os(watchOS)
let temp = "tmp"
#elseif os(macOS)
let temp = "T"
#endif
XCTAssertEqual(String(storeURLComponents[storeURLComponents.count - 2]), temp)
XCTAssertTrue(model.storeURL!.isFileURL)
// THEN: the model is in its specified bundle
let modelURLComponents = model.modelURL.pathComponents
XCTAssertEqual(String(modelURLComponents.last!), model.name + ".momd")
#if os(iOS) || os(tvOS) || os(watchOS)
let count = modelURLComponents.count - 2
#elseif os(macOS)
let count = modelURLComponents.count - 3
#endif
XCTAssertEqual(String(modelURLComponents[count]), NSString(string: model.bundle.bundlePath).lastPathComponent)
// THEN: the managed object model does not assert
XCTAssertNotNil(model.managedObjectModel)
// THEN: the store doesn't need migration
XCTAssertFalse(model.needsMigration)
}
func test_ThatInMemoryModel_InitializesSuccessfully() {
// GIVEN: a model name and bundle
// WHEN: we create a model
let model = CoreDataModel(name: modelName, bundle: modelBundle, storeType: .inMemory)
// THEN: the model has the correct name, bundle, and type
XCTAssertEqual(model.name, modelName)
XCTAssertEqual(model.bundle, modelBundle)
XCTAssertEqual(model.storeType, StoreType.inMemory)
// THEN: the model returns the correct database filename
XCTAssertEqual(model.databaseFileName, model.name)
// THEN: the store URL is nil
XCTAssertNil(model.storeURL)
// THEN: the model is in its specified bundle
let modelURLComponents = model.modelURL.pathComponents
XCTAssertEqual(String(modelURLComponents.last!), model.name + ".momd")
#if os(iOS) || os(tvOS) || os(watchOS)
let count = modelURLComponents.count - 2
#elseif os(macOS)
let count = modelURLComponents.count - 3
#endif
XCTAssertEqual(String(modelURLComponents[count]), NSString(string: model.bundle.bundlePath).lastPathComponent)
// THEN: the managed object model does not assert
XCTAssertNotNil(model.managedObjectModel)
// THEN: the store doesn't need migration
XCTAssertFalse(model.needsMigration)
}
func test_ThatSQLiteModel_RemoveExistingStore_Succeeds() {
// GIVEN: a core data model and stack
let model = CoreDataModel(name: modelName, bundle: modelBundle)
let factory = CoreDataStackProvider(model: model)
let result = factory.createStack()
let stack = try! result.get()
stack.mainContext.saveSync()
let fileManager = FileManager.default
XCTAssertTrue(fileManager.fileExists(atPath: model.storeURL!.path), "Model store should exist on disk")
XCTAssertTrue(fileManager.fileExists(atPath: model.storeURL!.path + "-wal"), "Model write ahead log should exist on disk")
XCTAssertTrue(fileManager.fileExists(atPath: model.storeURL!.path + "-shm"), "Model shared memory file should exist on disk")
// WHEN: we remove the existing model store
do {
try model.removeExistingStore()
} catch {
XCTFail("Removing existing model store should not error.")
}
// THEN: the model store is successfully removed
XCTAssertFalse(fileManager.fileExists(atPath: model.storeURL!.path), "Model store should NOT exist on disk")
XCTAssertFalse(fileManager.fileExists(atPath: model.storeURL!.path + "-wal"), "Model write ahead log should NOT exist on disk")
XCTAssertFalse(fileManager.fileExists(atPath: model.storeURL!.path + "-shm"), "Model shared memory file should NOT exist on disk")
}
func test_ThatSQLiteModel_RemoveExistingStore_Fails() {
// GIVEN: a core data model
let model = CoreDataModel(name: modelName, bundle: modelBundle)
// WHEN: we do not create a core data stack
// THEN: the model store does not exist on disk
XCTAssertFalse(FileManager.default.fileExists(atPath: model.storeURL!.path), "Model store should not exist on disk")
// WHEN: we attempt to remove the existing model store
var success = true
do {
try model.removeExistingStore()
} catch {
success = false
}
// THEN: then removal is ignored
XCTAssertTrue(success, "Removing store should be ignored")
}
func test_ThatInMemoryModel_RemoveExistingStore_Fails() {
// GIVEN: a core data model in-memory
let model = CoreDataModel(name: modelName, bundle: modelBundle, storeType: .inMemory)
// THEN: the store URL is nil
XCTAssertNil(model.storeURL)
// WHEN: we attempt to remove the existing model store
var success = true
do {
try model.removeExistingStore()
} catch {
success = false
}
// THEN: then removal is ignored
XCTAssertTrue(success, "Removing store should be ignored")
}
}
// swiftlint:enable force_try
| mit | 7a6d74a7915c3d8c5b9d6becd55bde45 | 36.377193 | 138 | 0.668153 | 4.795723 | false | false | false | false |
IvanVorobei/Sparrow | sparrow/ui/views/views/SPGradientView.swift | 1 | 3940 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
public class SPGradientView: UIView {
var startColor: UIColor = UIColor.white { didSet { self.updateGradient() }}
var endColor: UIColor = UIColor.black { didSet { self.updateGradient() }}
var startColorPoint: CGPoint = CGPoint.zero { didSet { self.updateGradient() }}
var endColorPoint: CGPoint = CGPoint.zero { didSet { self.updateGradient() }}
var gradientLayer: CAGradientLayer!
public init() {
super.init(frame: CGRect.zero)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.commonInit()
}
public func setStartColorPosition(_ position: Position) {
self.startColorPoint = getPointForPosition(position)
}
public func setEndColorPosition(_ position: Position) {
self.endColorPoint = getPointForPosition(position)
}
private func commonInit() {
self.gradientLayer = CAGradientLayer()
self.layer.insertSublayer(self.gradientLayer!, at: 0)
}
private func updateGradient() {
self.gradientLayer!.colors = [startColor.cgColor, endColor.cgColor]
self.gradientLayer!.locations = [0.0, 1.0]
self.gradientLayer!.startPoint = self.startColorPoint
self.gradientLayer!.endPoint = self.endColorPoint
}
override public func layoutSublayers(of layer: CALayer) {
super.layoutSublayers(of: layer)
self.gradientLayer.frame = self.bounds
}
public enum Position {
case TopLeft
case TopCenter
case TopRight
case BottomLeft
case BottomCenter
case BottomRight
}
private func getPointForPosition(_ position: Position) -> CGPoint {
switch position {
case .TopLeft:
return CGPoint.init(x: 0, y: 0)
case .TopCenter:
return CGPoint.init(x: 0.5, y: 0)
case .TopRight:
return CGPoint.init(x: 1, y: 0)
case .BottomLeft:
return CGPoint.init(x: 0, y: 1)
case .BottomCenter:
return CGPoint.init(x: 0.5, y: 1)
case .BottomRight:
return CGPoint.init(x: 1, y: 1)
}
}
}
class SPGradientWithPictureView: SPGradientView {
var pictureView: UIView? {
willSet {
if self.pictureView != nil {
if self.subviews.contains(self.pictureView!) {
self.pictureView?.removeFromSuperview()
}
}
}
didSet {
if self.pictureView != nil {
self.addSubview(pictureView!)
}
}
}
override func layoutSubviews() {
self.pictureView?.frame = self.bounds
}
}
| mit | a0cf03b298adb5204d51fa2c152e44af | 32.666667 | 83 | 0.642041 | 4.623239 | false | false | false | false |
huangxinping/XPKit-swift | Source/Extensions/UIKit/UILabel+XPKit.swift | 1 | 4265 | //
// UILabel+XPKit.swift
// XPKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015 - 2016 Fabrizio Brancati. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import UIKit
/// This extesion adds some useful functions to UILabel
public extension UILabel {
// MARK: - Init functions -
/**
Create an UILabel with the given parameters, with clearColor for the shadow
- parameter frame: Label's frame
- parameter text: Label's text
- parameter font: Label's font name, FontName enum is declared in UIFont+XPKit
- parameter size: Label's font size
- parameter color: Label's text color
- parameter alignment: Label's text alignment
- parameter lines: Label's text lines
- returns: Returns the created UILabel
*/
@available(*, obsoleted=1.2.0, message="Use UILabel(_, text:, font:, size:, color:, alignment:, lines:, shadowColor:)")
public convenience init(frame: CGRect, text: String, font: FontName, size: CGFloat, color: UIColor, alignment: NSTextAlignment, lines: Int) {
self.init(frame: frame, text: text, font: font, size: size, color: color, alignment: alignment, lines: lines, shadowColor: UIColor.clearColor())
}
/**
Create an UILabel with the given parameters
- parameter frame: Label's frame
- parameter text: Label's text
- parameter font: Label's font name, FontName enum is declared in UIFont+XPKit
- parameter size: Label's font size
- parameter color: Label's text color
- parameter alignment: Label's text alignment
- parameter lines: Label's text lines
- parameter shadowColor: Label's text shadow color
- returns: Returns the created UILabel
*/
public convenience init(frame: CGRect, text: String, font: FontName, size: CGFloat, color: UIColor, alignment: NSTextAlignment, lines: Int, shadowColor: UIColor = UIColor.clearColor()) {
self.init(frame: frame)
self.font = UIFont(fontName: font, size: size)
self.text = text
self.backgroundColor = UIColor.clearColor()
self.textColor = color
self.textAlignment = alignment
self.numberOfLines = lines
self.shadowColor = shadowColor
}
// MARK: - Instance functions -
/**
Calculates height based on text, width and font
- returns: Returns calculated height
*/
public func calculatedHeight() -> CGFloat {
let text: String = self.text!
return text.heightForWidth(self.frame.size.width, font: self.font)
}
/**
Sets a custom font from a character at an index to character at another index
- parameter font: New font to be setted
- parameter fromIndex: The start index
- parameter toIndex: The end index
*/
public func setFont(font: UIFont, fromIndex: Int, toIndex: Int) {
let string = NSMutableAttributedString(string: self.text!)
string.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(fromIndex, toIndex - fromIndex))
self.attributedText = string;
}
}
| mit | c533d1fec2668d48ddc9815330d61961 | 40.813725 | 190 | 0.675733 | 4.605832 | false | false | false | false |
benlangmuir/swift | benchmark/single-source/Walsh.swift | 10 | 2492 | //===--- Walsh.swift ------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
#if os(Linux)
import Glibc
#elseif os(Windows)
import MSVCRT
#else
import Darwin
#endif
public let benchmarks =
BenchmarkInfo(
name: "Walsh",
runFunction: run_Walsh,
tags: [.validation, .algorithm])
func isPowerOfTwo(_ x: Int) -> Bool { return (x & (x - 1)) == 0 }
// Fast Walsh Hadamard Transform
func walshTransform(_ data: inout [Double]) {
assert(isPowerOfTwo(data.count), "Not a power of two")
var temp = [Double](repeating: 0, count: data.count)
let ret = walshImpl(&data, &temp, 0, data.count)
for i in 0..<data.count {
data[i] = ret[i]
}
}
func scale(_ data: inout [Double], _ scalar : Double) {
for i in 0..<data.count {
data[i] = data[i] * scalar
}
}
func inverseWalshTransform(_ data: inout [Double]) {
walshTransform(&data)
scale(&data, Double(1)/Double(data.count))
}
func walshImpl(_ data: inout [Double], _ temp: inout [Double], _ start: Int, _ size: Int) -> [Double] {
if (size == 1) { return data }
let stride = size/2
for i in 0..<stride {
temp[start + i] = data[start + i + stride] + data[start + i]
temp[start + i + stride] = data[start + i] - data[start + i + stride]
}
_ = walshImpl(&temp, &data, start, stride)
return walshImpl(&temp, &data, start + stride, stride)
}
func checkCorrectness() {
let input: [Double] = [1,0,1,0,0,1,1,0]
let output: [Double] = [4,2,0,-2,0,2,0,2]
var data: [Double] = input
walshTransform(&data)
let mid = data
inverseWalshTransform(&data)
for i in 0..<input.count {
// Check encode.
check(abs(data[i] - input[i]) < 0.0001)
// Check decode.
check(abs(mid[i] - output[i]) < 0.0001)
}
}
@inline(never)
public func run_Walsh(_ n: Int) {
checkCorrectness()
// Generate data.
var data2 : [Double] = []
for i in 0..<1024 {
data2.append(Double(sin(Float(i))))
}
// Transform back and forth.
for _ in 1...10*n {
walshTransform(&data2)
inverseWalshTransform(&data2)
}
}
| apache-2.0 | ee541e71f32506b122386f5985a838eb | 25.510638 | 103 | 0.599117 | 3.287599 | false | false | false | false |
malaonline/iOS | mala-ios/View/Profile/SaveNameView.swift | 1 | 4762 | //
// SaveNameView.swift
// mala-ios
//
// Created by 王新宇 on 3/12/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
class SaveNameView: UIView, UITextFieldDelegate {
// MARK: - Property
var controller: UIViewController?
// MARK: - Components
/// 输入区域背景
private lazy var inputBackground: UIView = {
let inputBackground = UIView()
inputBackground.backgroundColor = UIColor.white
return inputBackground
}()
/// 输入控件
private lazy var inputField: UITextField = {
let inputField = UITextField()
inputField.textAlignment = .center
inputField.placeholder = "请输入学生姓名"
inputField.font = UIFont.systemFont(ofSize: 14)
inputField.textColor = UIColor(named: .ArticleText)
inputField.tintColor = UIColor(named: .ThemeBlue)
inputField.addTarget(self, action: #selector(SaveNameView.inputFieldDidChange), for: .editingChanged)
return inputField
}()
/// 描述label
private lazy var descLabel: UILabel = {
let descLabel = UILabel()
descLabel.textColor = UIColor(named: .HeaderTitle)
descLabel.font = UIFont.systemFont(ofSize: 12)
descLabel.text = "请填写真实姓名,不得超过4个汉字"
return descLabel
}()
/// [验证] 按钮
private lazy var finishButton: UIButton = {
let finishButton = UIButton()
finishButton.layer.cornerRadius = 5
finishButton.layer.masksToBounds = true
finishButton.setTitle("完成", for: UIControlState())
finishButton.setTitleColor(UIColor.white, for: UIControlState())
finishButton.setBackgroundImage(UIImage.withColor(UIColor(named: .LoginBlue)), for: .disabled)
finishButton.setBackgroundImage(UIImage.withColor(UIColor(named: .ThemeBlueTranslucent95)), for: UIControlState())
finishButton.addTarget(self, action: #selector(SaveNameView.finishButtonDidTap), for: .touchUpInside)
finishButton.isEnabled = false
return finishButton
}()
// MARK: - Constructed
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private
private func setupUserInterface() {
// Style
backgroundColor = UIColor(named: .CardBackground)
// SubViews
addSubview(inputBackground)
addSubview(inputField)
addSubview(descLabel)
addSubview(finishButton)
// Autolayout
inputBackground.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(self).offset(12)
maker.left.equalTo(self)
maker.right.equalTo(self)
maker.height.equalTo(MalaLayout_ProfileModifyViewHeight)
}
inputField.snp.makeConstraints { (maker) -> Void in
maker.left.equalTo(inputBackground)
maker.right.equalTo(inputBackground)
maker.centerY.equalTo(inputBackground)
}
descLabel.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(inputBackground.snp.bottom).offset(12)
maker.left.equalTo(self).offset(12)
maker.height.equalTo(12)
}
finishButton.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(descLabel.snp.bottom).offset(12)
maker.left.equalTo(self).offset(12)
maker.right.equalTo(self).offset(-12)
maker.height.equalTo(37)
}
}
private func validateName(_ name: String) -> Bool {
let nameRegex = "^[\\u4e00-\\u9fa5]{2,4}$"
let nameTest = NSPredicate(format: "SELF MATCHES %@", nameRegex)
return nameTest.evaluate(with: name)
}
// MARK: - Event Response
@objc private func inputFieldDidChange() {
guard let name = inputField.text else { return }
finishButton.isEnabled = validateName(name)
}
@objc private func finishButtonDidTap() {
guard let name = inputField.text else { return }
MAProvider.saveStudentName(name: name, failureHandler: { (error) in
self.showToastAtBottom(L10n.networkNotReachable)
}) { result in
println("Save Student Name - \(result as Optional)")
MalaUserDefaults.studentName.value = name
MalaUserDefaults.fetchUserInfo()
self.closeButtonDidClick()
}
}
@objc private func closeButtonDidClick() {
controller?.dismiss(animated: true, completion: nil)
}
}
| mit | 0597802967b1849f8f8affe6e56fd3dc | 33.375 | 122 | 0.626096 | 4.741379 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Authentication/Event Handlers/Pre-Login/AuthenticationEmailVerificationRequiredErrorHandler.swift | 1 | 1716 | //
// Wire
// Copyright (C) 2022 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 WireSyncEngine
/**
* Handles the event that informs the app when the email login verification code is available.
*/
class AuthenticationEmailVerificationRequiredErrorHandler: AuthenticationEventHandler {
weak var statusProvider: AuthenticationStatusProvider?
func handleEvent(currentStep: AuthenticationFlowStep, context: NSError) -> [AuthenticationCoordinatorAction]? {
let error = context
// Only handle e-mail login errors
guard case let .authenticateEmailCredentials(credentials) = currentStep else {
return nil
}
// Only handle accountIsPendingVerification error
guard error.userSessionErrorCode == .accountIsPendingVerification else {
return nil
}
guard let email = credentials.email else { return nil }
guard let password = credentials.password else { return nil }
return [.hideLoadingView, .requestEmailVerificationCode(email: email, password: password)]
}
}
| gpl-3.0 | 96bfa3673f8cb4ef7a808fcab44bc47a | 35.510638 | 115 | 0.727273 | 4.916905 | false | false | false | false |
Look-ARound/LookARound2 | Pods/Polyline/Polyline/Polyline.swift | 1 | 13707 | // Polyline.swift
//
// Copyright (c) 2015 Raphaël Mor
//
// 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 CoreLocation
import MapKit
// MARK: - Public Classes -
/// This class can be used for :
///
/// - Encoding an [CLLocation] or a [CLLocationCoordinate2D] to a polyline String
/// - Decoding a polyline String to an [CLLocation] or a [CLLocationCoordinate2D]
/// - Encoding / Decoding associated levels
///
/// it is aims to produce the same results as google's iOS sdk not as the online
/// tool which is fuzzy when it comes to rounding values
///
/// it is based on google's algorithm that can be found here :
///
/// :see: https://developers.google.com/maps/documentation/utilities/polylinealgorithm
public struct Polyline {
/// The array of coordinates (nil if polyline cannot be decoded)
public let coordinates: [CLLocationCoordinate2D]?
/// The encoded polyline
public let encodedPolyline: String
/// The array of levels (nil if cannot be decoded, or is not provided)
public let levels: [UInt32]?
/// The encoded levels (nil if cannot be encoded, or is not provided)
public let encodedLevels: String?
/// The array of location (computed from coordinates)
public var locations: [CLLocation]? {
return self.coordinates.map(toLocations)
}
#if !os(watchOS)
/// Convert polyline to MKPolyline to use with MapKit (nil if polyline cannot be decoded)
@available(tvOS 9.2, *)
public var mkPolyline: MKPolyline? {
guard let coordinates = self.coordinates else { return nil }
let mkPolyline = MKPolyline(coordinates: coordinates, count: coordinates.count)
return mkPolyline
}
#endif
// MARK: - Public Methods -
/// This designated initializer encodes a `[CLLocationCoordinate2D]`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter levels: The optional `Array` of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(coordinates: [CLLocationCoordinate2D], levels: [UInt32]? = nil, precision: Double = 1e5) {
self.coordinates = coordinates
self.levels = levels
encodedPolyline = encodeCoordinates(coordinates, precision: precision)
encodedLevels = levels.map(encodeLevels)
}
/// This designated initializer decodes a polyline `String`
///
/// - parameter encodedPolyline: The polyline that you want to decode
/// - parameter encodedLevels: The levels that you want to decode (default: `nil`)
/// - parameter precision: The precision used for decoding (default: `1e5`)
public init(encodedPolyline: String, encodedLevels: String? = nil, precision: Double = 1e5) {
self.encodedPolyline = encodedPolyline
self.encodedLevels = encodedLevels
coordinates = decodePolyline(encodedPolyline, precision: precision)
levels = self.encodedLevels.flatMap(decodeLevels)
}
/// This init encodes a `[CLLocation]`
///
/// - parameter locations: The `Array` of `CLLocation` that you want to encode
/// - parameter levels: The optional array of levels that you want to encode (default: `nil`)
/// - parameter precision: The precision used for encoding (default: `1e5`)
public init(locations: [CLLocation], levels: [UInt32]? = nil, precision: Double = 1e5) {
let coordinates = toCoordinates(locations)
self.init(coordinates: coordinates, levels: levels, precision:precision)
}
}
// MARK: - Public Functions -
/// This function encodes an `[CLLocationCoordinate2D]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocationCoordinate2D` that you want to encode
/// - parameter precision: The precision used to encode coordinates (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeCoordinates(_ coordinates: [CLLocationCoordinate2D], precision: Double = 1e5) -> String {
var previousCoordinate = IntegerCoordinates(0, 0)
var encodedPolyline = ""
for coordinate in coordinates {
let intLatitude = Int(round(coordinate.latitude * precision))
let intLongitude = Int(round(coordinate.longitude * precision))
let coordinatesDifference = (intLatitude - previousCoordinate.latitude, intLongitude - previousCoordinate.longitude)
encodedPolyline += encodeCoordinate(coordinatesDifference)
previousCoordinate = (intLatitude,intLongitude)
}
return encodedPolyline
}
/// This function encodes an `[CLLocation]` to a `String`
///
/// - parameter coordinates: The `Array` of `CLLocation` that you want to encode
/// - parameter precision: The precision used to encode locations (default: `1e5`)
///
/// - returns: A `String` representing the encoded Polyline
public func encodeLocations(_ locations: [CLLocation], precision: Double = 1e5) -> String {
return encodeCoordinates(toCoordinates(locations), precision: precision)
}
/// This function encodes an `[UInt32]` to a `String`
///
/// - parameter levels: The `Array` of `UInt32` levels that you want to encode
///
/// - returns: A `String` representing the encoded Levels
public func encodeLevels(_ levels: [UInt32]) -> String {
return levels.reduce("") {
$0 + encodeLevel($1)
}
}
/// This function decodes a `String` to a `[CLLocationCoordinate2D]?`
///
/// - parameter encodedPolyline: `String` representing the encoded Polyline
/// - parameter precision: The precision used to decode coordinates (default: `1e5`)
///
/// - returns: A `[CLLocationCoordinate2D]` representing the decoded polyline if valid, `nil` otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocationCoordinate2D]? {
let data = encodedPolyline.data(using: String.Encoding.utf8)!
let byteArray = (data as NSData).bytes.assumingMemoryBound(to: Int8.self)
let length = Int(data.count)
var position = Int(0)
var decodedCoordinates = [CLLocationCoordinate2D]()
var lat = 0.0
var lon = 0.0
while position < length {
do {
let resultingLat = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lat += resultingLat
let resultingLon = try decodeSingleCoordinate(byteArray: byteArray, length: length, position: &position, precision: precision)
lon += resultingLon
} catch {
return nil
}
decodedCoordinates.append(CLLocationCoordinate2D(latitude: lat, longitude: lon))
}
return decodedCoordinates
}
/// This function decodes a String to a [CLLocation]?
///
/// - parameter encodedPolyline: String representing the encoded Polyline
/// - parameter precision: The precision used to decode locations (default: 1e5)
///
/// - returns: A [CLLocation] representing the decoded polyline if valid, nil otherwise
public func decodePolyline(_ encodedPolyline: String, precision: Double = 1e5) -> [CLLocation]? {
return decodePolyline(encodedPolyline, precision: precision).map(toLocations)
}
/// This function decodes a `String` to an `[UInt32]`
///
/// - parameter encodedLevels: The `String` representing the levels to decode
///
/// - returns: A `[UInt32]` representing the decoded Levels if the `String` is valid, `nil` otherwise
public func decodeLevels(_ encodedLevels: String) -> [UInt32]? {
var remainingLevels = encodedLevels.unicodeScalars
var decodedLevels = [UInt32]()
while remainingLevels.count > 0 {
do {
let chunk = try extractNextChunk(&remainingLevels)
let level = decodeLevel(chunk)
decodedLevels.append(level)
} catch {
return nil
}
}
return decodedLevels
}
// MARK: - Private -
// MARK: Encode Coordinate
private func encodeCoordinate(_ locationCoordinate: IntegerCoordinates) -> String {
let latitudeString = encodeSingleComponent(locationCoordinate.latitude)
let longitudeString = encodeSingleComponent(locationCoordinate.longitude)
return latitudeString + longitudeString
}
private func encodeSingleComponent(_ value: Int) -> String {
var intValue = value
if intValue < 0 {
intValue = intValue << 1
intValue = ~intValue
} else {
intValue = intValue << 1
}
return encodeFiveBitComponents(intValue)
}
// MARK: Encode Levels
private func encodeLevel(_ level: UInt32) -> String {
return encodeFiveBitComponents(Int(level))
}
private func encodeFiveBitComponents(_ value: Int) -> String {
var remainingComponents = value
var fiveBitComponent = 0
var returnString = String()
repeat {
fiveBitComponent = remainingComponents & 0x1F
if remainingComponents >= 0x20 {
fiveBitComponent |= 0x20
}
fiveBitComponent += 63
let char = UnicodeScalar(fiveBitComponent)!
returnString.append(String(char))
remainingComponents = remainingComponents >> 5
} while (remainingComponents != 0)
return returnString
}
// MARK: Decode Coordinate
// We use a byte array (UnsafePointer<Int8>) here for performance reasons. Check with swift 2 if we can
// go back to using [Int8]
private func decodeSingleCoordinate(byteArray: UnsafePointer<Int8>, length: Int, position: inout Int, precision: Double = 1e5) throws -> Double {
guard position < length else { throw PolylineError.singleCoordinateDecodingError }
let bitMask = Int8(0x1F)
var coordinate: Int32 = 0
var currentChar: Int8
var componentCounter: Int32 = 0
var component: Int32 = 0
repeat {
currentChar = byteArray[position] - 63
component = Int32(currentChar & bitMask)
coordinate |= (component << (5*componentCounter))
position += 1
componentCounter += 1
} while ((currentChar & 0x20) == 0x20) && (position < length) && (componentCounter < 6)
if (componentCounter == 6) && ((currentChar & 0x20) == 0x20) {
throw PolylineError.singleCoordinateDecodingError
}
if (coordinate & 0x01) == 0x01 {
coordinate = ~(coordinate >> 1)
} else {
coordinate = coordinate >> 1
}
return Double(coordinate) / precision
}
// MARK: Decode Levels
private func extractNextChunk(_ encodedString: inout String.UnicodeScalarView) throws -> String {
var currentIndex = encodedString.startIndex
while currentIndex != encodedString.endIndex {
let currentCharacterValue = Int32(encodedString[currentIndex].value)
if isSeparator(currentCharacterValue) {
let extractedScalars = encodedString[encodedString.startIndex...currentIndex]
encodedString = String.UnicodeScalarView(encodedString[encodedString.index(after: currentIndex)..<encodedString.endIndex])
return String(extractedScalars)
}
currentIndex = encodedString.index(after: currentIndex)
}
throw PolylineError.chunkExtractingError
}
private func decodeLevel(_ encodedLevel: String) -> UInt32 {
let scalarArray = [] + encodedLevel.unicodeScalars
return UInt32(agregateScalarArray(scalarArray))
}
private func agregateScalarArray(_ scalars: [UnicodeScalar]) -> Int32 {
let lastValue = Int32(scalars.last!.value)
let fiveBitComponents: [Int32] = scalars.map { scalar in
let value = Int32(scalar.value)
if value != lastValue {
return (value - 63) ^ 0x20
} else {
return value - 63
}
}
return Array(fiveBitComponents.reversed()).reduce(0) { ($0 << 5 ) | $1 }
}
// MARK: Utilities
enum PolylineError: Error {
case singleCoordinateDecodingError
case chunkExtractingError
}
private func toCoordinates(_ locations: [CLLocation]) -> [CLLocationCoordinate2D] {
return locations.map {location in location.coordinate}
}
private func toLocations(_ coordinates: [CLLocationCoordinate2D]) -> [CLLocation] {
return coordinates.map { coordinate in
CLLocation(latitude:coordinate.latitude, longitude:coordinate.longitude)
}
}
private func isSeparator(_ value: Int32) -> Bool {
return (value - 63) & 0x20 != 0x20
}
private typealias IntegerCoordinates = (latitude: Int, longitude: Int)
| apache-2.0 | 90592115447c799a2c561ca53cbfec7a | 34.416021 | 145 | 0.680651 | 4.607059 | false | false | false | false |
SuperAwesomeLTD/sa-kws-app-demo-ios | KWSDemo/FeatureViewController.swift | 1 | 24732 | //
// FeaturesViewController.swift
// KWSDemo
//
// Created by Gabriel Coman on 21/06/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import SAUtils
import KWSiOSSDKObjC
class FeatureViewController: KWSBaseController {
// constants to setup KWS
fileprivate let CLIENT_ID = "sa-mobile-app-sdk-client-0"
fileprivate let APP_ID = 313
fileprivate let CLIENT_SECRET = "_apikey_5cofe4ppp9xav2t9"
fileprivate let KWS_API = "https://kwsapi.demo.superawesome.tv/"
// outlets
@IBOutlet weak var tableView: UITableView!
private var hasChecked: Bool = false
// the data source
private var dataSource: RxDataSource?
override func viewDidLoad() {
super.viewDidLoad()
// setup the session
KWSChildren.sdk().setup(withClientId: CLIENT_ID, andClientSecret: CLIENT_SECRET, andAPIUrl: KWS_API)
Observable
.from([
FeatureAuthViewModel (),
FeatureNotifViewModel (),
FeaturePermViewModel (),
FeatureEventViewModel (),
FeatureInviteViewModel (),
FeatureAppDataViewModel ()
])
.toArray()
.subscribe(onNext: { (features: [ViewModel]) in
self.dataSource = RxDataSource
.bindTable(self.tableView)
.estimateRowHeight(100)
//
// customise Login & Logout row
.customiseRow(cellIdentifier: "FeatureAuthRowId", cellType: FeatureAuthViewModel.self) { (model, cell) in
let cell = cell as? FeatureAuthRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
let local = KWSChildren.sdk().getLoggedUser()
cell?.authActionButton.setTitle(
isLogged ?
"page_features_row_auth_button_login_logged".localized + "\(local!.metadata!.userId)" :
"page_features_row_auth_button_login_not_logged".localized, for: .normal)
cell?.authActionButton.onAction {
let lIsLogged = KWSChildren.sdk().getLoggedUser() != nil
self.performSegue(withIdentifier: lIsLogged ? "FeaturesToUserSegue" : "FeaturesToLoginSegue", sender: self)
}
cell?.authDocsButton.onAction {
self.openDocumentation()
}
}
//
// customise the Remote Notifications row
.customiseRow(cellIdentifier: "FeatureNotifRowId", cellType: FeatureNotifViewModel.self) { (model, cell) in
let cell = cell as? FeatureNotifRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
let isRegistered = isLogged && KWSChildren.sdk().getLoggedUser().isRegisteredForNotifications()
cell?.notifEnableOrDisableButton.isEnabled = isLogged && self.hasChecked
cell?.notifEnableOrDisableButton.setTitle(
isRegistered ?
"page_features_row_notif_button_disable".localized :
"page_features_row_notif_button_enable".localized, for: .normal)
cell?.notifEnableOrDisableButton.onAction {
let lIsRegistered = KWSChildren.sdk().getLoggedUser() != nil && KWSChildren.sdk().getLoggedUser().isRegisteredForNotifications()
if lIsRegistered {
RxKWS.unregisterForNotifications()
.subscribe(onNext: { (isUnregistered: Bool) in
if isUnregistered {
self.featurePopup("page_features_row_notif_popup_unreg_success_title".localized,
"page_features_row_notif_popup_unreg_success_message".localized)
} else {
self.featurePopup("page_features_row_notif_popup_unreg_error_network_title".localized,
"page_features_row_notif_popup_unreg_error_network_message".localized)
}
// update data source
self.dataSource?.update()
})
.addDisposableTo(self.disposeBag)
} else {
RxKWS.registerForNotifications()
.subscribe(onNext: { (status: KWSChildrenRegisterForRemoteNotificationsStatus) in
switch status {
case .registerForRemoteNotifications_Success:
self.featurePopup("page_features_row_notif_popup_reg_success_title".localized,
"page_features_row_notif_popup_reg_success_message".localized)
break
case .registerForRemoteNotifications_ParentDisabledNotifications:
self.featurePopup("page_features_row_notif_popup_reg_error_disable_parent_title".localized,
"page_features_row_notif_popup_reg_error_disable_parent_message".localized)
break
case .registerForRemoteNotifications_UserDisabledNotifications:
self.featurePopup("page_features_row_notif_popup_reg_error_disable_user_title".localized,
"page_features_row_notif_popup_reg_error_disable_user_message".localized)
break
case .registerForRemoteNotifications_NoParentEmail:
self.featurePopup("page_features_row_notif_popup_reg_error_no_email_title".localized,
"page_features_row_notif_popup_reg_error_no_email_message".localized)
break
case .registerForRemoteNotifications_FirebaseNotSetup:
self.featurePopup("page_features_row_notif_popup_reg_error_firebase_not_setup_title".localized,
"page_features_row_notif_popup_reg_error_firebase_not_setup_message".localized)
break
case .registerForRemoteNotifications_FirebaseCouldNotGetToken:
self.featurePopup("page_features_row_notif_popup_reg_error_firebase_nil_token_title".localized,
"page_features_row_notif_popup_reg_error_firebase_nil_token_message".localized)
break
case .registerForRemoteNotifications_NetworkError:
self.featurePopup("page_features_row_notif_popup_reg_error_network_title".localized,
"page_features_row_notif_popup_reg_error_network_message".localized)
break
}
// update data source
self.dataSource?.update()
})
.addDisposableTo(self.disposeBag)
}
}
cell?.notifDocButton.onAction {
self.openDocumentation()
}
}
//
// customise the Permissions row
.customiseRow(cellIdentifier: "FeaturePermRowId", cellType: FeaturePermViewModel.self) { (model, cell) in
let cell = cell as? FeaturePermRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
cell?.permAddPermissionsButton.isEnabled = isLogged
cell?.permAddPermissionsButton.onAction {
let myActionSheet = UIAlertController(title: "page_features_row_perm_popup_perm_title".localized,
message: "page_features_row_perm_popup_perm_message".localized,
preferredStyle: .actionSheet)
let permissions = [
["name":"page_features_row_perm_popup_perm_option_email".localized,
"type":KWSChildrenPermissionType.permissionType_AccessEmail.rawValue],
["name":"page_features_row_perm_popup_perm_option_address".localized,
"type":KWSChildrenPermissionType.permissionType_AccessAddress.rawValue],
["name":"page_features_row_perm_popup_perm_option_first_name".localized,
"type":KWSChildrenPermissionType.permissionType_AccessFirstName.rawValue],
["name":"page_features_row_perm_popup_perm_option_last_name".localized,
"type":KWSChildrenPermissionType.permissionType_AccessLastName.rawValue],
["name":"page_features_row_perm_popup_perm_option_newsletter".localized,
"type":KWSChildrenPermissionType.permissionType_SendNewsletter.rawValue],
]
for i in 0 ..< permissions.count {
if let title = permissions[i]["name"] as? String,
let type = permissions[i]["type"] as? NSInteger {
myActionSheet.addAction(UIAlertAction(title: title, style: .default, handler: { (action) in
let requestedPermission = [type]
RxKWS.addPermissions(permissions: requestedPermission as [NSNumber]!)
.subscribe(onNext: { (status: KWSChildrenRequestPermissionStatus) in
switch status {
case .requestPermission_Success:
self.featurePopup("page_features_row_perm_popup_success_title".localized,
"page_features_row_perm_popup_success_message".localized)
break
case .requestPermission_NetworkError:
self.featurePopup("page_features_row_perm_popup_error_network_title".localized,
"page_features_row_perm_popup_error_network_message".localized)
break
case .requestPermission_NoParentEmail:
self.featurePopup("page_features_row_perm_popup_error_no_email_title".localized,
"page_features_row_perm_popup_error_no_email_message".localized)
break
}
})
.addDisposableTo(self.disposeBag)
}))
}
}
// present action sheet
self.present(myActionSheet, animated: true, completion: nil)
}
cell?.permSeeDocsButton.onAction {
self.openDocumentation()
}
}
//
// customise the Events row
.customiseRow(cellIdentifier: "FeatureEventRowId", cellType: FeatureEventViewModel.self) { (model, cell) in
let cell = cell as? FeatureEventRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
cell?.evtAdd20PointsButton.isEnabled = isLogged
cell?.evtSub10PointsButton.isEnabled = isLogged
cell?.evtGetScoreButton.isEnabled = isLogged
cell?.evtSeeLeaderboardButton.isEnabled = isLogged
cell?.evtAdd20PointsButton.onAction {
RxKWS.triggerEvent(event: "GabrielAdd20ForAwesomeApp")
.subscribe(onNext: { (isTriggered) in
if isTriggered {
self.featurePopup("page_features_row_events_popup_success_20pcts_title".localized,
"page_features_row_events_popup_success_20pcts_message".localized)
} else {
self.featurePopup("page_features_row_events_popup_error_network_title".localized,
"page_features_row_events_popup_error_network_message".localized)
}
})
.addDisposableTo(self.disposeBag)
}
cell?.evtSub10PointsButton.onAction {
RxKWS.triggerEvent(event: "GabrielSub10ForAwesomeApp")
.subscribe(onNext: { (isTriggered) in
if isTriggered {
self.featurePopup("page_features_row_events_popup_success_10pcts_title".localized,
"page_features_row_events_popup_success_10pcts_message".localized)
} else {
self.featurePopup("page_features_row_events_popup_error_network_title".localized,
"page_features_row_events_popup_error_network_message".localized)
}
})
.addDisposableTo(self.disposeBag)
}
cell?.evtGetScoreButton.onAction {
RxKWS.getScore()
.subscribe(onNext: { (score: KWSScore?) in
if let score = score {
let message = NSString(format: "page_features_row_events_popup_success_score_message".localized as NSString, score.rank, score.score) as String
self.featurePopup("page_features_row_events_popup_success_score_title".localized,
message)
} else {
self.featurePopup("page_features_row_events_popup_error_network_title".localized,
"page_features_row_events_popup_error_network_message".localized)
}
})
.addDisposableTo(self.disposeBag)
}
cell?.evtSeeLeaderboardButton.onAction {
self.performSegue(withIdentifier: "FeaturesToLeaderboardSegue", sender: self)
}
cell?.evtSeeDocsButton.onAction {
self.openDocumentation()
}
}
//
// customise the Invite row
.customiseRow(cellIdentifier: "FeatureInviteRowId", cellType: FeatureInviteViewModel.self) { (model, cell) in
let cell = cell as? FeatureInviteRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
cell?.invInviteFriendButton.isEnabled = isLogged
cell?.invInviteFriendButton.onAction {
SAAlert.getInstance().show(withTitle: "page_features_row_invite_popup_email_title".localized,
andMessage: "page_features_row_invite_popup_email_message".localized,
andOKTitle: "page_features_row_invite_popup_email_button_ok".localized,
andNOKTitle: "page_features_row_invite_popup_email_button_cancel".localized,
andTextField: true,
andKeyboardTyle: UIKeyboardType.emailAddress)
{ (button: Int32, email: String?) in
if let email = email, button == 0 {
RxKWS.inviteFriend(email: email)
.subscribe(onNext: { (invited: Bool) in
if invited {
self.featurePopup("page_features_row_invite_popup_success_title".localized,
"page_features_row_invite_popup_success_message".localized)
} else {
self.featurePopup("page_features_row_invite_popup_error_network_title".localized,
"page_features_row_invite_popup_error_network_message".localized) }
})
.addDisposableTo(self.disposeBag)
}
}
}
cell?.invSeeDocsButton.onAction {
self.openDocumentation()
}
}
//
// customise the App Data row
.customiseRow(cellIdentifier: "FeatureAppDataRowId", cellType: FeatureAppDataViewModel.self) { (model, cell) in
let cell = cell as? FeatureAppDataRow
let isLogged = KWSChildren.sdk().getLoggedUser() != nil
cell?.appdSeeAppDataButton.isEnabled = isLogged
cell?.appdSeeAppDataButton.onAction {
self.performSegue(withIdentifier: "FeaturesToAddDataSegue", sender: self)
}
cell?.appdSeeDocsButton.onAction {
self.openDocumentation()
}
}
// update the data for the first time
self.dataSource?.update(features)
})
.addDisposableTo(disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.hasChecked = false
dataSource?.update()
self.navigationController?.navigationBar.topItem?.title = "page_features_title".localized
KWSChildren.sdk().isRegistered(forRemoteNotifications: { (isReg) in
self.hasChecked = true
self.dataSource?.update()
})
}
func openDocumentation () {
let docUrl: String = "http://doc.superawesome.tv/sa-kws-ios-sdk/latest/"
let url = URL(string: docUrl)
if #available(iOS 10.0, *) {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url!)
}
}
func featurePopup(_ title: String, _ message: String) {
SAAlert.getInstance().show(withTitle: title,
andMessage: message,
andOKTitle: "page_features_row_popup_button_ok_generic".localized,
andNOKTitle: nil,
andTextField: false,
andKeyboardTyle: .alphabet,
andPressed: nil)
}
}
| gpl-3.0 | 1c568c48b092271f141012f6f1e94859 | 57.053991 | 183 | 0.400267 | 7.029847 | false | false | false | false |
kelvin13/maxpng | sources/png/error.swift | 2 | 52635 | /// protocol PNG.Error
/// : Swift.Error
/// Functionality common to all library error types.
/// # [Propogating errors](error-propogation)
/// # [See also](error-handling)
/// ## (error-handling)
public
protocol _PNGError:Error
{
/// static var PNG.Error.namespace : Swift.String { get }
/// required
/// A human-readable namespace for this error type.
static
var namespace:String
{
get
}
/// var PNG.Error.message : Swift.String { get }
/// required
/// A human-readable summary of this error.
/// ## ()
var message:String
{
get
}
/// var PNG.Error.details : Swift.String? { get }
/// required
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
var details:String?
{
get
}
}
extension PNG.Error
{
/// var PNG.Error.fatal : Swift.Never
/// Halts execution by converting this error into a fatal error.
/// ## (error-propogation)
public
var fatal:Never
{
fatalError("\(self)")
}
}
extension PNG
{
public
typealias Error = _PNGError
}
extension PNG
{
/// enum PNG.LexingError
/// : Error
/// A lexing error.
/// # [See also](error-handling)
/// ## (error-handling)
public
enum LexingError
{
/// case PNG.LexingError.truncatedSignature
/// The lexer encountered end-of-stream while reading signature
/// bytes from a bytestream.
case truncatedSignature
/// case PNG.LexingError.invalidSignature(_:)
/// The signature bytes read by the lexer did not match the expected
/// sequence.
///
/// The expected byte sequence is `[137, 80, 78, 71, 13, 10, 26, 10]`.
/// - _ : [Swift.UInt8]
/// The invalid signature bytes.
case invalidSignature([UInt8])
/// case PNG.LexingError.truncatedChunkHeader
/// The lexer encountered end-of-stream while reading a chunk header
/// from a bytestream.
case truncatedChunkHeader
/// case PNG.LexingError.truncatedChunkBody(expected:)
/// The lexer encountered end-of-stream while reading a chunk body
/// from a bytestream.
/// - expected : Swift.Int
/// The number of bytes the lexer expected to read.
case truncatedChunkBody(expected:Int)
/// case PNG.LexingError.invalidChunkTypeCode(_:)
/// The lexer read a chunk with an invalid type identifier code.
/// - _ : Swift.UInt32
/// The invalid type identifier code.
case invalidChunkTypeCode(UInt32)
/// case PNG.LexingError.invalidChunkChecksum(declared:computed:)
/// The chunk checksum computed by the lexer did not match the
/// checksum declared in the chunk footer.
/// - declared : Swift.UInt32
/// The checksum declared in the chunk footer.
/// - computed : Swift.UInt32
/// The checksum computed by the lexer.
case invalidChunkChecksum(declared:UInt32, computed:UInt32)
}
/// enum PNG.FormattingError
/// : Error
/// A formatting error.
/// # [See also](error-handling)
/// ## (error-handling)
public
enum FormattingError
{
/// case PNG.FormattingError.invalidDestination
/// The formatter failed to write to a destination bytestream.
case invalidDestination
}
/// enum PNG.ParsingError
/// : Error
/// A parsing error.
/// # [Header errors](IHDR-parsing-errors)
/// # [Palette errors](PLTE-parsing-errors)
/// # [Transparency errors](tRNS-parsing-errors)
/// # [Background errors](bKGD-parsing-errors)
/// # [Histogram errors](hIST-parsing-errors)
/// # [Gamma errors](gAMA-parsing-errors)
/// # [Chromaticity errors](cHRM-parsing-errors)
/// # [Color rendering errors](sRGB-parsing-errors)
/// # [Significant bits errors](sBIT-parsing-errors)
/// # [Color profile errors](iCCP-parsing-errors)
/// # [Physical dimensions errors](pHYs-parsing-errors)
/// # [Suggested palette errors](sPLT-parsing-errors)
/// # [Time modified errors](tIME-parsing-errors)
/// # [Text comment errors](text-chunk-parsing-errors)
/// # [See also](error-handling)
/// ## (error-handling)
public
enum ParsingError
{
/// case PNG.ParsingError.invalidHeaderChunkLength(_:)
/// An [`(Chunk).IHDR`] chunk had the wrong length.
///
/// Header chunks should be exactly `13` bytes long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderPixelFormatCode(_:)
/// An [`(Chunk).IHDR`] chunk had an invalid pixel format code.
/// - _ : (Swift.UInt8, Swift.UInt8)
/// The invalid pixel format code.
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderPixelFormat(_:standard:)
/// An [`(Chunk).IHDR`] chunk specified a pixel format that is disallowed
/// according to the PNG standard used by the image.
///
/// This error gets thrown when an iphone-optimized image
/// ([`(Standard).ios`]) has a pixel format that is not
/// [`(Format.Pixel).rgb8`] or [`(Format.Pixel).rgba8`].
/// - _ : Format.Pixel
/// The invalid pixel format.
/// - standard : Standard
/// The PNG standard. This error is only relevant for iphone-optimized
/// images, so library-generated instances of this error case always have
/// this field set to [`(Standard).ios`].
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderCompressionMethodCode(_:)
/// An [`(Chunk).IHDR`] chunk had an invalid compression method code.
///
/// The compression method code should always be `0`.
/// - _ : Swift.UInt8
/// The invalid compression method code.
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderFilterCode(_:)
/// An [`(Chunk).IHDR`] chunk had an invalid filter code.
///
/// The filter code should always be `0`.
/// - _ : Swift.UInt8
/// The invalid filter code.
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderInterlacingCode(_:)
/// An [`(Chunk).IHDR`] chunk had an invalid interlacing code.
///
/// The interlacing code should be either `0` or `1`.
/// - _ : Swift.UInt8
/// The invalid interlacing code.
/// ## (IHDR-parsing-errors)
/// case PNG.ParsingError.invalidHeaderSize(_:)
/// An [`(Chunk).IHDR`] chunk specified an invalid image size.
///
/// Both size dimensions must be strictly positive.
/// - _ : (x:Swift.Int, y:Swift.Int)
/// The invalid size.
/// ## (IHDR-parsing-errors)
case invalidHeaderChunkLength(Int)
case invalidHeaderPixelFormatCode((UInt8, UInt8))
case invalidHeaderPixelFormat(PNG.Format.Pixel, standard:PNG.Standard)
case invalidHeaderCompressionMethodCode(UInt8)
case invalidHeaderFilterCode(UInt8)
case invalidHeaderInterlacingCode(UInt8)
case invalidHeaderSize((x:Int, y:Int))
/// case PNG.ParsingError.unexpectedPalette(pixel:)
/// The parser encountered a [`(Chunk).PLTE`] chunk in an image
/// with a pixel format that forbids it.
/// - pixel : Format.Pixel
/// The image pixel format.
/// ## (PLTE-parsing-errors)
/// case PNG.ParsingError.invalidPaletteChunkLength(_:)
/// A [`(Chunk).PLTE`] chunk had a length that is not divisible by `3`.
/// - _ : Swift.Int
/// The chunk length.
/// ## (PLTE-parsing-errors)
/// case PNG.ParsingError.invalidPaletteCount(_:max:)
/// A [`(Chunk).PLTE`] chunk contained more entries than allowed.
/// - _ : Swift.Int
/// The number of palette entries.
/// - max : Swift.Int
/// The maximum allowed number of palette entries, according to the
/// image bit depth.
/// ## (PLTE-parsing-errors)
case unexpectedPalette(pixel:PNG.Format.Pixel)
case invalidPaletteChunkLength(Int)
case invalidPaletteCount(Int, max:Int)
/// case PNG.ParsingError.unexpectedTransparency(pixel:)
/// The parser encountered a [`(Chunk).tRNS`] chunk in an image
/// with a pixel format that forbids it.
/// - pixel : Format.Pixel
/// The image pixel format.
/// ## (tRNS-parsing-errors)
/// case PNG.ParsingError.invalidTransparencyChunkLength(_:expected:)
/// A [`(Chunk).tRNS`] chunk had the wrong length.
/// - _ : Swift.Int
/// The chunk length.
/// - expected : Swift.Int
/// The expected chunk length.
/// ## (tRNS-parsing-errors)
/// case PNG.ParsingError.invalidTransparencySample(_:max:)
/// A [`(Chunk).tRNS`] chunk contained an invalid chroma key sample.
/// - _ : Swift.UInt16
/// The value of the invalid chroma key sample.
/// - max : Swift.UInt16
/// The maximum allowed value for a chroma key sample, according to the
/// image color depth.
/// ## (tRNS-parsing-errors)
/// case PNG.ParsingError.invalidTransparencyCount(_:max:)
/// A [`(Chunk).tRNS`] chunk contained too many alpha samples.
/// - _ : Swift.Int
/// The number of alpha samples present.
/// - max : Swift.Int
/// The maximum allowed number of alpha samples, which is equal to
/// the number of entries in the image palette.
/// ## (tRNS-parsing-errors)
case unexpectedTransparency(pixel:PNG.Format.Pixel)
case invalidTransparencyChunkLength(Int, expected:Int)
case invalidTransparencySample(UInt16, max:UInt16)
case invalidTransparencyCount(Int, max:Int)
/// case PNG.ParsingError.invalidBackgroundChunkLength(_:expected:)
/// A [`(Chunk).bKGD`] chunk had the wrong length.
/// - _ : Swift.Int
/// The chunk length.
/// - expected : Swift.Int
/// The expected chunk length.
/// ## (bKGD-parsing-errors)
/// case PNG.ParsingError.invalidBackgroundSample(_:max:)
/// A [`(Chunk).bKGD`] chunk contained an invalid background sample.
/// - _ : Swift.UInt16
/// The value of the invalid background sample.
/// - max : Swift.UInt16
/// The maximum allowed value for a background sample, according to the
/// image color depth.
/// ## (bKGD-parsing-errors)
/// case PNG.ParsingError.invalidBackgroundIndex(_:max:)
/// A [`(Chunk).bKGD`] chunk specified an out-of-range palette index.
/// - _ : Swift.Int
/// The invalid index.
/// - max : Swift.Int
/// The maximum allowed index value, which is equal to one less than
/// the number of entries in the image palette.
/// ## (bKGD-parsing-errors)
case invalidBackgroundChunkLength(Int, expected:Int)
case invalidBackgroundSample(UInt16, max:UInt16)
case invalidBackgroundIndex(Int, max:Int)
/// case PNG.ParsingError.invalidHistogramChunkLength(_:expected:)
/// A [`(Chunk).hIST`] chunk had the wrong length.
/// - _ : Swift.Int
/// The chunk length.
/// - expected : Swift.Int
/// The expected chunk length.
/// ## (hIST-parsing-errors)
case invalidHistogramChunkLength(Int, expected:Int)
/// case PNG.ParsingError.invalidGammaChunkLength(_:)
/// A [`(Chunk).gAMA`] chunk had the wrong length.
///
/// Gamma chunks should be exactly `4` bytes long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (gAMA-parsing-errors)
case invalidGammaChunkLength(Int)
/// case PNG.ParsingError.invalidChromaticityChunkLength(_:)
/// A [`(Chunk).cHRM`] chunk had the wrong length.
///
/// Chromaticity chunks should be exactly `32` bytes long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (cHRM-parsing-errors)
case invalidChromaticityChunkLength(Int)
/// case PNG.ParsingError.invalidColorRenderingChunkLength(_:)
/// An [`(Chunk).sRGB`] chunk had the wrong length.
///
/// Color rendering chunks should be exactly `1` byte long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (sRGB-parsing-errors)
/// case PNG.ParsingError.invalidColorRenderingCode(_:)
/// An [`(Chunk).sRGB`] chunk had an invalid color rendering code.
///
/// The color rendering code should be one of `0`, `1`, `2`, or `3`.
/// - _ : Swift.UInt8
/// The invalid color rendering code.
/// ## (sRGB-parsing-errors)
case invalidColorRenderingChunkLength(Int)
case invalidColorRenderingCode(UInt8)
/// case PNG.ParsingError.invalidSignificantBitsChunkLength(_:expected:)
/// An [`(Chunk).sBIT`] chunk had the wrong length.
/// - _ : Swift.Int
/// The chunk length.
/// - expected : Swift.Int
/// The expected chunk length.
/// ## (sBIT-parsing-errors)
/// case PNG.ParsingError.invalidSignificantBitsPrecision(_:max:)
/// An [`(Chunk).sBIT`] chunk specified an invalid precision value.
/// - _ : Swift.Int
/// The invalid precision value.
/// - max : Swift.Int
/// The maximum allowed precision value, which is equal to the image
/// color depth.
/// ## (sBIT-parsing-errors)
case invalidSignificantBitsChunkLength(Int, expected:Int)
case invalidSignificantBitsPrecision(Int, max:Int)
/// case PNG.ParsingError.invalidColorProfileChunkLength(_:min:)
/// An [`(Chunk).iCCP`] chunk had an invalid length.
/// - _ : Swift.Int
/// The chunk length.
/// - min : Swift.Int
/// The minimum expected chunk length.
/// ## (iCCP-parsing-errors)
/// case PNG.ParsingError.invalidColorProfileName(_:)
/// An [`(Chunk).iCCP`] chunk had an invalid profile name.
/// - _ : Swift.String?
/// The invalid profile name, or `nil` if the parser could not find
/// the null-terminator of the profile name string.
/// ## (iCCP-parsing-errors)
/// case PNG.ParsingError.invalidColorProfileCompressionMethodCode(_:)
/// An [`(Chunk).iCCP`] chunk had an invalid compression method code.
///
/// The compression method code should always be `0`.
/// - _ : Swift.UInt8
/// The invalid compression method code.
/// ## (iCCP-parsing-errors)
/// case PNG.ParsingError.incompleteColorProfileCompressedDatastream
/// The compressed data stream in an [`(Chunk).iCCP`] chunk was not
/// properly terminated.
/// ## (iCCP-parsing-errors)
case invalidColorProfileChunkLength(Int, min:Int)
case invalidColorProfileName(String?)
case invalidColorProfileCompressionMethodCode(UInt8)
case incompleteColorProfileCompressedDatastream
/// case PNG.ParsingError.invalidPhysicalDimensionsChunkLength(_:)
/// A [`(Chunk).pHYs`] chunk had the wrong length.
///
/// Physical dimensions chunks should be exactly `9` bytes long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (pHYs-parsing-errors)
/// case PNG.ParsingError.invalidPhysicalDimensionsDensityUnitCode(_:)
/// A [`(Chunk).pHYs`] chunk had an invalid density unit code.
///
/// The density code should be either `0` or `1`.
/// - _ : Swift.UInt8
/// The invalid density unit code.
/// ## (pHYs-parsing-errors)
case invalidPhysicalDimensionsChunkLength(Int)
case invalidPhysicalDimensionsDensityUnitCode(UInt8)
/// case PNG.ParsingError.invalidSuggestedPaletteChunkLength(_:min:)
/// An [`(Chunk).sPLT`] chunk had an invalid length.
/// - _ : Swift.Int
/// The chunk length.
/// - min : Swift.Int
/// The minimum expected chunk length.
/// ## (sPLT-parsing-errors)
/// case PNG.ParsingError.invalidSuggestedPaletteName(_:)
/// An [`(Chunk).sPLT`] chunk had an invalid palette name.
/// - _ : Swift.String?
/// The invalid palette name, or `nil` if the parser could not find
/// the null-terminator of the palette name string.
/// ## (sPLT-parsing-errors)
/// case PNG.ParsingError.invalidSuggestedPaletteDataLength(_:stride:)
/// The length of the palette data in an [`(Chunk).sPLT`] chunk was
/// not divisible by its expected stride.
/// - _ : Swift.Int
/// The length of the palette data.
/// - stride : Swift.Int
/// The expected stride of the palette entries.
/// ## (sPLT-parsing-errors)
/// case PNG.ParsingError.invalidSuggestedPaletteDepthCode(_:)
/// An [`(Chunk).sPLT`] chunk had an invalid depth code.
///
/// The depth code should be either `8` or `16`.
/// - _ : Swift.UInt8
/// The invalid depth code.
/// ## (sPLT-parsing-errors)
/// case PNG.ParsingError.invalidSuggestedPaletteFrequency
/// The entries in an [`(Chunk).sPLT`] chunk were not ordered by
/// descending frequency.
/// ## (sPLT-parsing-errors)
case invalidSuggestedPaletteChunkLength(Int, min:Int)
case invalidSuggestedPaletteName(String?)
case invalidSuggestedPaletteDataLength(Int, stride:Int)
case invalidSuggestedPaletteDepthCode(UInt8)
case invalidSuggestedPaletteFrequency
/// case PNG.ParsingError.invalidTimeModifiedChunkLength(_:)
/// A [`(Chunk).tIME`] chunk had the wrong length.
///
/// Time modified chunks should be exactly `7` bytes long.
/// - _ : Swift.Int
/// The chunk length.
/// ## (tIME-parsing-errors)
/// case PNG.ParsingError.invalidTimeModifiedTime(year:month:day:hour:minute:second:)
/// A [`(Chunk).tIME`] chunk specified an invalid timestamp.
/// - year : Swift.Int
/// The specified year.
/// - month : Swift.Int
/// The specified month.
/// - day : Swift.Int
/// The specified day.
/// - hour : Swift.Int
/// The specified hour.
/// - minute : Swift.Int
/// The specified minute.
/// - second : Swift.Int
/// The specified second.
/// ## (tIME-parsing-errors)
case invalidTimeModifiedChunkLength(Int)
case invalidTimeModifiedTime(year:Int, month:Int, day:Int, hour:Int, minute:Int, second:Int)
/// case PNG.ParsingError.invalidTextEnglishKeyword(_:)
/// A [`(Chunk).tEXt`], [`(Chunk).zTXt`], or [`(Chunk).iTXt`] chunk
/// had an invalid english keyword.
/// - _ : Swift.String?
/// The invalid english keyword, or `nil` if the parser could not find
/// the null-terminator of the keyword string.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.invalidTextChunkLength(_:min:)
/// A [`(Chunk).tEXt`], [`(Chunk).zTXt`], or [`(Chunk).iTXt`] chunk
/// had an invalid length.
/// - _ : Swift.Int
/// The chunk length.
/// - min : Swift.Int
/// The minimum expected chunk length.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.invalidTextCompressionCode(_:)
/// An [`(Chunk).iTXt`] chunk had an invalid compression code.
///
/// The compression code should be either `0` or `1`.
/// - _ : Swift.UInt8
/// The invalid compression code.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.invalidTextCompressionMethodCode(_:)
/// A [`(Chunk).zTXt`] or [`(Chunk).iTXt`] chunk had an invalid
/// compression method code.
///
/// The compression method code should always be `0`.
/// - _ : Swift.UInt8
/// The invalid compression method code.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.invalidTextLanguageTag(_:)
/// An [`(Chunk).iTXt`] chunk had an invalid language tag.
/// - _ : Swift.String?
/// The invalid language tag component, or `nil` if the parser could
/// not find the null-terminator of the language tag string.
/// The language tag component is not the entire language tag string.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.invalidTextLocalizedKeyword
/// The parser could not find the null-terminator of the localized
/// keyword string in an [`(Chunk).iTXt`] chunk.
/// ## (text-chunk-parsing-errors)
/// case PNG.ParsingError.incompleteTextCompressedDatastream
/// The compressed data stream in a [`(Chunk).zTXt`] or [`(Chunk).iTXt`]
/// chunk was not properly terminated.
/// ## (text-chunk-parsing-errors)
case invalidTextEnglishKeyword(String?)
case invalidTextChunkLength(Int, min:Int)
case invalidTextCompressionCode(UInt8)
case invalidTextCompressionMethodCode(UInt8)
case invalidTextLanguageTag(String?)
case invalidTextLocalizedKeyword
case incompleteTextCompressedDatastream
}
/// enum PNG.DecodingError
/// : Error
/// A decoding error.
/// # [See also](error-handling)
/// ## (error-handling)
public
enum DecodingError
{
/// case PNG.DecodingError.required(chunk:before:)
/// The decoder encountered a chunk of a type that requires a
/// previously encountered chunk of a particular type.
/// - chunk : Chunk
/// The type of the preceeding chunk required by the encountered chunk.
/// - before : Chunk
/// The type of the encountered chunk.
/// ## ()
/// case PNG.DecodingError.duplicate(chunk:)
/// The decoder encountered multiple instances of a chunk type that
/// can only appear once in a PNG file.
/// - chunk : Chunk
/// The type of the duplicated chunk.
/// ## ()
/// case PNG.DecodingError.unexpected(chunk:after:)
/// The decoder encountered a chunk of a type that is not allowed
/// to appear after a previously encountered chunk of a particular type.
///
/// If both fields are set to [`(Chunk).IDAT`], this indicates
/// a non-contiguous [`(Chunk).IDAT`] sequence.
/// - chunk : Chunk
/// The type of the encountered chunk.
/// - after : Chunk
/// The type of the preceeding chunk that precludes the encountered chunk.
/// ## ()
case required(chunk:PNG.Chunk, before:PNG.Chunk)
case duplicate(chunk:PNG.Chunk)
case unexpected(chunk:PNG.Chunk, after:PNG.Chunk)
/// case PNG.DecodingError.incompleteImageDataCompressedDatastream
/// The decoder finished processing the last [`(Chunk).IDAT`] chunk
/// before the compressed image data stream was properly terminated.
case incompleteImageDataCompressedDatastream
/// case PNG.DecodingError.extraneousImageDataCompressedData
/// The decoder encountered additional [`(Chunk).IDAT`] chunks
/// after the end of the compressed image data stream.
///
/// This error should not be confused with an [`unexpected(chunk:after:)`]
/// error with both fields set to [`(Chunk).IDAT`], which indicates a
/// non-contiguous [`(Chunk).IDAT`] sequence.
case extraneousImageDataCompressedData
/// case PNG.DecodingError.extraneousImageData
/// The compressed image data stream produces more uncompressed image
/// data than expected.
case extraneousImageData
}
}
extension LZ77
{
/// enum LZ77.DecompressionError
/// : PNG.Error
/// A decompression error.
/// # [Stream errors](decompression-stream-errors)
/// # [INFLATE errors](inflate-errors)
/// # [See also](error-handling)
/// ## (error-handling)
public
enum DecompressionError
{
// stream errors
/// case LZ77.DecompressionError.invalidStreamCompressionMethodCode(_:)
/// A compressed data stream had an invalid compression method code.
///
/// The compression method code should always be `8`.
/// - _ : Swift.UInt8
/// The invalid compression method code.
/// ## (decompression-stream-errors)
/// case LZ77.DecompressionError.invalidStreamWindowSize(exponent:)
/// A compressed data stream specified an invalid window size.
///
/// The window size exponent should be in the range `8 ... 15`.
/// - exponent : Swift.Int
/// The invalid window size exponent.
/// ## (decompression-stream-errors)
/// case LZ77.DecompressionError.invalidStreamHeaderCheckBits
/// A compressed data stream had invalid header check bits.
///
/// The header check bits should not be confused with the modular
/// redundancy checksum, which corresponds to the
/// [`invalidStreamChecksum(declared:computed:)`] error case.
/// ## (decompression-stream-errors)
/// case LZ77.DecompressionError.unexpectedStreamDictionary
/// A compressed data stream contains a stream dictionary, which
/// is not allowed in a PNG compressed data stream.
/// ## (decompression-stream-errors)
/// case LZ77.DecompressionError.invalidStreamChecksum(declared:computed:)
/// The modular redundancy checksum computed on
/// the uncompressed data did not match the checksum declared in the
/// compressed data stream footer.
///
/// This error should not be confused with [`invalidStreamHeaderCheckBits`].
/// Nor should it be confused with [`PNG.LexingError.invalidChunkChecksum(declared:computed:)`],
/// which refers to the cyclic redundancy checksum in every PNG chunk.
/// - declared : Swift.UInt32
/// The checksum declared in the compressed data stream footer.
/// - computed : Swift.UInt32
/// The checksum computed on the uncompressed data.
/// ## (decompression-stream-errors)
case invalidStreamCompressionMethodCode(UInt8)
case invalidStreamWindowSize(exponent:Int)
case invalidStreamHeaderCheckBits
case unexpectedStreamDictionary
case invalidStreamChecksum(declared:UInt32, computed:UInt32)
// block errors
/// case LZ77.DecompressionError.invalidBlockTypeCode(_:)
/// A compressed block had an invalid block type code.
///
/// The block type code should be one of `0`, `1`, or `2`.
/// - _ : Swift.UInt8
/// The invalid block type code.
/// ## (inflate-errors)
/// case LZ77.DecompressionError.invalidBlockElementCountParity(_:_:)
/// A compressed block of stored type had inconsistent element count fields.
///
/// A valid element count field is the bitwise negation of the other
/// element count field.
/// - _ : Swift.UInt16
/// The value of the first element count field.
/// - _ : Swift.UInt16
/// The value of the second element count field.
/// ## (inflate-errors)
/// case LZ77.DecompressionError.invalidHuffmanRunLiteralSymbolCount(_:)
/// A compressed block of dynamic type declared an invalid number of
/// run-literal symbols.
///
/// The number of run-literal symbols must be in the range `257 ... 286`.
/// - _ : Swift.Int
/// The number of run-literal symbols declared in the compressed block.
/// ## (inflate-errors)
/// case LZ77.DecompressionError.invalidHuffmanCodelengthHuffmanTable()
/// A compressed block of dynamic type declared an invalid
/// codelength huffman table.
/// ## (inflate-errors)
/// case LZ77.DecompressionError.invalidHuffmanCodelengthSequence
/// A compressed block of dynamic type declared an invalid sequence of
/// symbol codelengths.
/// ## (inflate-errors)
/// case LZ77.DecompressionError.invalidHuffmanTable
/// A compressed block of dynamic type declared an invalid
/// distance or run-literal huffman table.
/// ## (inflate-errors)
case invalidBlockTypeCode(UInt8)
case invalidBlockElementCountParity(UInt16, UInt16)
case invalidHuffmanRunLiteralSymbolCount(Int)
case invalidHuffmanCodelengthHuffmanTable
case invalidHuffmanCodelengthSequence
case invalidHuffmanTable
/// case LZ77.DecompressionError.invalidStringReference
/// A compressed block contains an invalid run-length string reference.
/// ## (inflate-errors)
case invalidStringReference
}
}
extension PNG.LexingError:PNG.Error
{
/// static var PNG.LexingError.namespace : Swift.String { get }
/// ?: Error
/// The string `"lexing error"`.
public static
var namespace:String
{
"lexing error"
}
/// var PNG.LexingError.message : Swift.String { get }
/// ?: Error
/// A human-readable summary of this error.
/// ## ()
public
var message:String
{
switch self
{
case .invalidSignature:
return "invalid png signature bytes"
case .truncatedSignature:
return "failed to read png signature bytes from source bytestream"
case .truncatedChunkHeader:
return "failed to read chunk header from source bytestream"
case .truncatedChunkBody:
return "failed to read chunk body from source bytestream"
case .invalidChunkTypeCode:
return "invalid chunk type code"
case .invalidChunkChecksum:
return "invalid chunk checksum"
}
}
/// var PNG.LexingError.details : Swift.String? { get }
/// ?: Error
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
public
var details:String?
{
switch self
{
case .invalidSignature(let declared):
return "signature \(declared) does not match expected png signature \(PNG.signature)"
case .truncatedSignature, .truncatedChunkHeader, .truncatedChunkBody:
return nil
case .invalidChunkTypeCode(let name):
let string:String = withUnsafeBytes(of: name.bigEndian)
{
.init(decoding: $0, as: Unicode.ASCII.self)
}
return "type specifier '\(string)' is not a valid chunk type"
case .invalidChunkChecksum(declared: let declared, computed: let computed):
return "computed crc-32 checksum (\(computed)) does not match declared checksum (\(declared))"
}
}
}
extension PNG.FormattingError:PNG.Error
{
/// static var PNG.FormattingError.namespace : Swift.String { get }
/// ?: Error
/// The string `"formatting error"`.
public static
var namespace:String
{
"formatting error"
}
/// var PNG.FormattingError.message : Swift.String { get }
/// ?: Error
/// A human-readable summary of this error.
/// ## ()
public
var message:String
{
switch self
{
case .invalidDestination:
return "failed to write to destination bytestream"
}
}
/// var PNG.FormattingError.details : Swift.String? { get }
/// ?: Error
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
public
var details:String?
{
switch self
{
case .invalidDestination:
return nil
}
}
}
extension PNG.ParsingError:PNG.Error
{
/// static var PNG.ParsingError.namespace : Swift.String { get }
/// ?: Error
/// The string `"parsing error"`.
public static
var namespace:String
{
"parsing error"
}
private
var scope:Any.Type
{
switch self
{
case .invalidHeaderChunkLength,
.invalidHeaderPixelFormatCode,
.invalidHeaderPixelFormat,
.invalidHeaderCompressionMethodCode,
.invalidHeaderFilterCode,
.invalidHeaderInterlacingCode,
.invalidHeaderSize:
return PNG.Header.self
case .unexpectedPalette,
.invalidPaletteChunkLength,
.invalidPaletteCount:
return PNG.Palette.self
case .unexpectedTransparency,
.invalidTransparencyChunkLength,
.invalidTransparencySample,
.invalidTransparencyCount:
return PNG.Transparency.self
case .invalidBackgroundChunkLength,
.invalidBackgroundSample,
.invalidBackgroundIndex:
return PNG.Background.self
case .invalidHistogramChunkLength:
return PNG.Histogram.self
case .invalidGammaChunkLength:
return PNG.Gamma.self
case .invalidChromaticityChunkLength:
return PNG.Chromaticity.self
case .invalidColorRenderingChunkLength,
.invalidColorRenderingCode:
return PNG.ColorRendering.self
case .invalidSignificantBitsChunkLength,
.invalidSignificantBitsPrecision:
return PNG.SignificantBits.self
case .invalidColorProfileChunkLength,
.invalidColorProfileName,
.invalidColorProfileCompressionMethodCode,
.incompleteColorProfileCompressedDatastream:
return PNG.ColorProfile.self
case .invalidPhysicalDimensionsChunkLength,
.invalidPhysicalDimensionsDensityUnitCode:
return PNG.PhysicalDimensions.self
case .invalidSuggestedPaletteChunkLength,
.invalidSuggestedPaletteDataLength,
.invalidSuggestedPaletteName,
.invalidSuggestedPaletteFrequency,
.invalidSuggestedPaletteDepthCode:
return PNG.SuggestedPalette.self
case .invalidTimeModifiedChunkLength,
.invalidTimeModifiedTime:
return PNG.TimeModified.self
case .invalidTextChunkLength,
.invalidTextEnglishKeyword,
.invalidTextCompressionCode,
.invalidTextCompressionMethodCode,
.invalidTextLanguageTag,
.invalidTextLocalizedKeyword,
.incompleteTextCompressedDatastream:
return PNG.Text.self
}
}
/// var PNG.ParsingError.message : Swift.String { get }
/// ?: Error
/// A human-readable summary of this error.
/// ## ()
public
var message:String
{
let text:String
switch self
{
case .invalidHeaderChunkLength,
.invalidPaletteChunkLength,
.invalidTransparencyChunkLength,
.invalidBackgroundChunkLength,
.invalidHistogramChunkLength,
.invalidGammaChunkLength,
.invalidChromaticityChunkLength,
.invalidColorRenderingChunkLength,
.invalidColorProfileChunkLength,
.invalidSignificantBitsChunkLength,
.invalidPhysicalDimensionsChunkLength,
.invalidSuggestedPaletteChunkLength,
.invalidSuggestedPaletteDataLength,
.invalidTimeModifiedChunkLength,
.invalidTextChunkLength:
text = "invalid chunk length"
case .invalidHeaderPixelFormatCode,
.invalidHeaderCompressionMethodCode,
.invalidHeaderFilterCode,
.invalidHeaderInterlacingCode,
.invalidColorRenderingCode,
.invalidPhysicalDimensionsDensityUnitCode,
.invalidColorProfileCompressionMethodCode,
.invalidSuggestedPaletteDepthCode,
.invalidTextCompressionMethodCode,
.invalidTextCompressionCode:
text = "invalid flag code"
case .invalidHeaderPixelFormat:
text = "invalid pixel format"
case .invalidHeaderSize:
text = "invalid image size"
case .unexpectedPalette,
.unexpectedTransparency:
text = "unexpected chunk"
case .invalidPaletteCount,
.invalidTransparencyCount:
text = "invalid count"
case .invalidTransparencySample,
.invalidBackgroundSample:
text = "invalid sample"
case .invalidBackgroundIndex:
text = "invalid index"
case .invalidSignificantBitsPrecision:
text = "invalid precision"
case .invalidColorProfileName,
.invalidSuggestedPaletteName:
text = "invalid name"
case .invalidSuggestedPaletteFrequency:
text = "invalid frequency"
case .incompleteColorProfileCompressedDatastream,
.incompleteTextCompressedDatastream:
text = "content field does not contain a full compressed data stream"
case .invalidTimeModifiedTime:
text = "invalid time"
case .invalidTextEnglishKeyword,
.invalidTextLocalizedKeyword:
text = "invalid keyword"
case .invalidTextLanguageTag:
text = "invalid language tag"
}
return "(\(self.scope)) \(text)"
}
/// var PNG.ParsingError.details : Swift.String? { get }
/// ?: Error
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
public
var details:String?
{
func plural(bytes count:Int) -> String
{
count == 1 ? "1 byte" : "\(count) bytes"
}
switch self
{
case .invalidHeaderChunkLength (let bytes):
return "chunk is \(plural(bytes: bytes)), expected 13 bytes"
case .invalidPaletteChunkLength (let bytes):
return "chunk length (\(bytes)) must be divisible by 3"
case .invalidTransparencyChunkLength (let bytes, expected: let expected),
.invalidBackgroundChunkLength (let bytes, expected: let expected),
.invalidHistogramChunkLength (let bytes, expected: let expected),
.invalidSignificantBitsChunkLength (let bytes, expected: let expected):
return "chunk is \(plural(bytes: bytes)), expected \(plural(bytes: expected))"
case .invalidGammaChunkLength (let bytes):
return "chunk is \(plural(bytes: bytes)), expected 4 bytes"
case .invalidChromaticityChunkLength (let bytes):
return "chunk is \(plural(bytes: bytes)), expected 32 bytes"
case .invalidColorRenderingChunkLength (let bytes):
return "chunk is \(plural(bytes: bytes)), expected 1 byte"
case .invalidPhysicalDimensionsChunkLength(let bytes):
return "chunk is \(plural(bytes: bytes)), expected 9 bytes"
case .invalidTimeModifiedChunkLength (let bytes):
return "chunk is \(plural(bytes: bytes)), expected 7 bytes"
case .invalidColorProfileChunkLength (let bytes, min: let min),
.invalidSuggestedPaletteChunkLength (let bytes, min: let min),
.invalidTextChunkLength (let bytes, min: let min):
return "chunk is \(plural(bytes: bytes)), expected at least \(plural(bytes: min))"
case .invalidSuggestedPaletteDataLength(let bytes, stride: let stride):
return "palette data length (\(plural(bytes: bytes))) must be divisible by \(stride)"
case .invalidHeaderPixelFormatCode(let code):
return "\(code) is not a valid pixel format code"
case .invalidHeaderPixelFormat(let pixel, standard: let standard):
return "`\(pixel)` is not a valid pixel format under the png standard `\(standard)`"
case .invalidTextCompressionCode(let code):
return "(\(code)) is not a valid compression code"
case .invalidHeaderFilterCode(let code):
return "(\(code)) is not a valid filter code"
case .invalidHeaderInterlacingCode(let code):
return "(\(code)) is not a valid interlacing code"
case .invalidColorRenderingCode(let code):
return "(\(code)) is not a valid color rendering code"
case .invalidPhysicalDimensionsDensityUnitCode(let code):
return "(\(code)) is not a valid density unit code"
case .invalidSuggestedPaletteDepthCode(let code):
return "(\(code)) is not a valid suggested palette depth code"
case .invalidHeaderCompressionMethodCode(let code),
.invalidColorProfileCompressionMethodCode(let code),
.invalidTextCompressionMethodCode(let code):
return "(\(code)) is not a valid compression method code"
case .invalidHeaderSize(let size):
return "image dimensions \(size) must be greater than 0"
case .unexpectedPalette(pixel: let pixel):
return "palette not allowed for pixel format `\(pixel)`"
case .invalidPaletteCount(let count, max: let max):
return "number of palette entries (\(count)) must be in the range 1 ... \(max)"
case .unexpectedTransparency(pixel: let pixel):
switch pixel
{
case .indexed1, .indexed2, .indexed4, .indexed8:
return "transparency for pixel format `\(pixel)` requires a previously-defined image palette"
default:
return "transparency not allowed for pixel format `\(pixel)`"
}
case .invalidTransparencySample(let sample, max: let max):
return "chroma key sample (\(sample)) must be in the range 0 ... \(max)"
case .invalidTransparencyCount(let count, max: let max):
return "number of alpha samples (\(count)) exceeds number of palette entries (\(max))"
case .invalidBackgroundSample(let sample, max: let max):
return "background sample (\(sample)) must be in the range 0 ... \(max)"
case .invalidBackgroundIndex(let index, max: let max):
return "background index (\(index)) is out of range for palette of length \(max + 1)"
case .invalidSignificantBitsPrecision(let precision, max: let max):
return "precision (\(precision)) must be in the range 1 ... \(max)"
case .incompleteColorProfileCompressedDatastream,
.incompleteTextCompressedDatastream:
return nil
case .invalidSuggestedPaletteFrequency:
return "frequency values must appear in descending order"
case .invalidTimeModifiedTime(
year: let year,
month: let month,
day: let day,
hour: let hour,
minute: let minute,
second: let second):
return "\((year: year, month: month, day: day, hour: hour, minute: minute, second: second)) is not a valid time stamp"
case .invalidColorProfileName(nil):
return "color profile name must be a null-terminated string"
case .invalidSuggestedPaletteName(nil):
return "suggested palette name must be a null-terminated string"
case .invalidTextEnglishKeyword(nil):
return "english keyword must be a null-terminated string"
case .invalidTextLanguageTag(nil):
return "language specifier must be a null-terminated string"
case .invalidTextLocalizedKeyword:
return "localized keyword must be a null-terminated string"
case .invalidColorProfileName(let name?):
return "color profile name '\(name)' is not a valid name"
case .invalidSuggestedPaletteName(let name?):
return "suggested palette name '\(name)' is not a valid name"
case .invalidTextEnglishKeyword(let name?):
return "english keyword '\(name)' is not a valid keyword"
case .invalidTextLanguageTag(let tag?):
return "language tag '\(tag)' is not a valid language tag"
}
}
}
extension PNG.DecodingError:PNG.Error
{
/// static var PNG.DecodingError.namespace : Swift.String { get }
/// ?: Error
/// The string `"decoding error"`.
public static
var namespace:String
{
"decoding error"
}
/// var PNG.DecodingError.message : Swift.String { get }
/// ?: Error
/// A human-readable summary of this error.
/// ## ()
public
var message:String
{
switch self
{
case .incompleteImageDataCompressedDatastream:
return "image data chunks do not contain a full compressed data stream"
case .extraneousImageDataCompressedData:
return "image contains trailing image data chunks that are not part of the compressed data stream"
case .extraneousImageData:
return "compressed image data stream produces more uncompressed image data than expected"
case .duplicate:
return "duplicate chunk"
case .required, .unexpected:
return "invalid chunk ordering"
}
}
/// var PNG.DecodingError.details : Swift.String? { get }
/// ?: Error
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
public
var details:String?
{
switch self
{
case .incompleteImageDataCompressedDatastream,
.extraneousImageDataCompressedData,
.extraneousImageData:
return nil
case .required(chunk: let previous, before: let chunk):
return "chunk of type '\(chunk)' requires a previously encountered chunk of type '\(previous)'"
case .duplicate(chunk: let chunk):
return "chunk of type '\(chunk)' can only appear once"
case .unexpected(chunk: .IDAT, after: .IDAT):
return "chunks of type 'IDAT' must be contiguous"
case .unexpected(chunk: let chunk, after: let previous):
return "chunk of type '\(chunk)' cannot appear after chunk of type '\(previous)'"
}
}
}
extension LZ77.DecompressionError:PNG.Error
{
/// static var LZ77.DecompressionError.namespace : Swift.String { get }
/// ?: PNG.Error
/// The string `"decompression error"`.
public static
var namespace:String
{
"decompression error"
}
/// var LZ77.DecompressionError.message : Swift.String { get }
/// ?: PNG.Error
/// A human-readable summary of this error.
/// ## ()
public
var message:String
{
switch self
{
case .invalidStreamCompressionMethodCode:
return "invalid rfc-1950 stream compression method code"
case .invalidStreamWindowSize:
return "invalid rfc-1950 stream window size"
case .invalidStreamHeaderCheckBits:
return "invalid rfc-1950 stream header check bits"
case .unexpectedStreamDictionary:
return "unexpected rfc-1950 stream dictionary"
case .invalidStreamChecksum:
return "invalid rfc-1950 checksum"
case .invalidBlockTypeCode:
return "invalid rfc-1951 block type code"
case .invalidBlockElementCountParity:
return "invalid rfc-1951 block element count parity"
case .invalidHuffmanRunLiteralSymbolCount:
return "invalid rfc-1951 run-literal huffman symbol count"
case .invalidHuffmanCodelengthHuffmanTable:
return "invalid rfc-1951 codelength huffman table"
case .invalidHuffmanCodelengthSequence:
return "invalid rfc-1951 codelength sequence"
case .invalidHuffmanTable:
return "invalid rfc-1951 run-literal/distance huffman table"
case .invalidStringReference:
return "invalid rfc-1951 string reference"
}
}
/// var LZ77.DecompressionError.details : Swift.String? { get }
/// ?: PNG.Error
/// An optional human-readable string providing additional details
/// about this error.
/// ## ()
public
var details:String?
{
switch self
{
case .invalidStreamCompressionMethodCode(let code):
return "(\(code)) is not a valid compression method code"
case .invalidStreamWindowSize(exponent: let exponent):
return "base-2 log of stream window size (\(exponent)) must be in the range 8 ... 15"
case .invalidStreamHeaderCheckBits,
.unexpectedStreamDictionary,
.invalidHuffmanCodelengthHuffmanTable,
.invalidHuffmanCodelengthSequence,
.invalidHuffmanTable,
.invalidStringReference:
return nil
case .invalidStreamChecksum(declared: let declared, computed: let computed):
return "computed mrc-32 checksum (\(computed)) does not match declared checksum (\(declared))"
case .invalidBlockTypeCode(let code):
return "(\(code)) is not a valid block type code"
case .invalidBlockElementCountParity(let l, let m):
return "inverted block element count (\(String.init(~l, radix: 2))) does not match declared parity bits (\(String.init(m, radix: 2)))"
case .invalidHuffmanRunLiteralSymbolCount(let count):
return "run-literal symbol count (\(count)) must be in the range 257 ... 286"
}
}
}
| gpl-3.0 | 8759fc08ca5ad2e8efcb3554e7b70d66 | 41.75792 | 146 | 0.581894 | 4.763348 | false | false | false | false |
alloyapple/FileManager | Sources/FileManager/GFileManager.swift | 1 | 4311 | import Glibc
import Foundation
let PATH_MAX = 4096
public typealias FileDate = (accessDate: time_t, modifyDate: time_t, createDate: time_t)
public typealias FileSize = (fileWithBytes: __off_t, fileWithK: Double, fileWithM: Double, fileWithG: Double)
final public class GFileManager {
public static let defaultFileManager = GFileManager()
public func GetCwd() -> String? {
let cwd = getcwd(nil, Int(PATH_MAX))
guard cwd != nil else { return nil }
defer {
free(cwd)
}
guard let path = String.fromCString(cwd) else { return nil }
return path
}
public func ListFiles(filePath: String) -> [String] {
let dir = opendir(filePath)
guard dir != nil else { return [] }
var result: [String] = []
defer {
closedir(dir)
}
var file = readdir(dir)
while (file != nil) {
let fileName = withUnsafePointer(&file.memory.d_name, { (ptr) -> String? in
let int8Ptr = unsafeBitCast(ptr, UnsafePointer<Int8>.self)
return String.fromCString(int8Ptr)
})
if let fileName = fileName {
result.append(fileName)
}
file = readdir(dir)
}
return result
}
public func TmpFile() -> UnsafeMutablePointer<FILE> {
let retValue = tmpfile()
return retValue
}
public func TmpNam() -> String? {
let name = tmpnam(nil)
let newName = unsafeBitCast(name, UnsafePointer<Int8>.self)
return String.fromCString(newName)
}
public func HomeDir() -> String {
let home = getenv("HOME")
let homeString = String.fromCString(home)
if let homeString = homeString {
return homeString
} else {
return ""
}
}
public func FileIsExists(fileName: String) -> Bool {
return access(fileName, F_OK) != -1
}
public func CreateFile(filePath: String) -> Bool {
let fileId = creat(filePath, S_IRWXG)
guard fileId != -1 else { return false }
close(fileId)
return true
}
public func RenameFile(oldName: String, newName: String) -> Bool {
let retValue = rename(oldName, newName)
return retValue != -1
}
public func RemoveFile(filePath: String) -> Bool {
let retValue = remove(filePath)
return retValue != -1
}
//access date, modify date, create date
public func GetFileDate(filePath: String) -> FileDate? {
guard FileIsExists(filePath) else { return nil }
var stat_struct = stat()
stat(filePath, &stat_struct)
return (accessDate: stat_struct.st_atim.tv_sec, modifyDate: stat_struct.st_mtim.tv_sec, createDate: stat_struct.st_ctim.tv_sec)
}
public func CanExecute(filePath: String) -> Bool {
return access(filePath, X_OK) != -1
}
public func SetExecute(filePath: String, canexe: Bool) -> Bool {
return chmod(filePath, S_IXGRP) == 0
}
public func CanRead(filePath: String) -> Bool {
return access(filePath, R_OK) != -1
}
public func SetRead(filePath: String, canexe: Bool) -> Bool {
return chmod(filePath, S_IRGRP) == 0
}
public func CanWrite(filePath: String) -> Bool {
return access(filePath, W_OK) != -1
}
public func SetWrite(filePath: String, canexe: Bool) -> Bool {
return chmod(filePath, S_IWUSR) == 0
}
public func IsDirectory(filePath: String) -> Bool {
guard FileIsExists(filePath) else { return false }
var stat_struct = stat()
stat(filePath, &stat_struct)
return (stat_struct.st_mode & 61440 == 16384)
}
public func IsFile(filePath: String) -> Bool {
guard FileIsExists(filePath) else { return false }
var stat_struct = stat()
stat(filePath, &stat_struct)
return (stat_struct.st_mode & 61440 == 32768)
}
public func IsHidden(filePath: String) -> Bool {
guard filePath.characters.count > 0 else { return false }
if filePath.characters.first == "." {
return true
} else {
return false
}
}
public func GetFileSize(filePath: String) -> FileSize? {
guard FileIsExists(filePath) else { return nil }
var stat_struct = stat()
stat(filePath, &stat_struct)
return (fileWithBytes: stat_struct.st_size,
fileWithK: Double(stat_struct.st_size) / 1024,
fileWithM: Double(stat_struct.st_size) / (1024 * 1024),
fileWithG: Double(stat_struct.st_size) / (1024 * 1024 * 1024))
}
}
| bsd-3-clause | d1d3e88178df116042e593da95bba21b | 21.570681 | 131 | 0.638831 | 3.684615 | false | false | false | false |
mlgoogle/wp | wp/AppAPI/SocketAPI/SocketReqeust/SocketRequest.swift | 1 | 1776 | //
// SocketRequest.swift
// viossvc
//
// Created by yaowang on 2016/11/23.
// Copyright © 2016年 ywwlcom.yundian. All rights reserved.
//
import UIKit
//import XCGLogger
class SocketRequest {
static var errorDict:NSDictionary?;
var error: ErrorBlock?
var complete: CompleteBlock?
var timestamp: TimeInterval = Date().timeIntervalSince1970
class func errorString(_ code:Int) ->String {
if errorDict == nil {
if let bundlePath = Bundle.main.path(forResource: "errorcode", ofType: "plist") {
errorDict = NSDictionary(contentsOfFile: bundlePath)
}
}
let key:String = String(format: "%d", code);
if errorDict?.object(forKey: key) != nil {
return errorDict!.object(forKey: key) as! String
}
return "Unknown";
}
deinit {
// XCGLogger.debug(" \(self)")
}
func isReqeustTimeout() -> Bool {
return timestamp + Double(AppConst.Network.TimeoutSec) <= Date().timeIntervalSince1970
}
fileprivate func dispatch_main_async(_ block:@escaping ()->()) {
DispatchQueue.main.async(execute: {
block()
})
}
func onComplete(_ obj:AnyObject!) {
dispatch_main_async {
self.complete?(obj)
}
}
func onError(_ errorCode:Int!) {
let errorStr:String = SocketRequest.errorString(errorCode)
let error = NSError(domain: AppConst.ErrorDomain, code: errorCode
, userInfo: [NSLocalizedDescriptionKey:errorStr]);
onError(error)
}
func onError(_ error:NSError!) {
dispatch_main_async {
self.error?(error)
}
}
}
| apache-2.0 | 2c0067b45ad7f56e75a0040ee53c80ce | 23.287671 | 95 | 0.57022 | 4.690476 | false | false | false | false |
GetZero/-Swift-LeetCode | LeetCode/InvertBinaryTree.swift | 1 | 1439 | //
// InvertBinaryTree.swift
// LeetCode
//
// Created by 韦曲凌 on 2016/11/9.
// Copyright © 2016年 Wake GetZero. All rights reserved.
//
import Foundation
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class InvertBinaryTree: NSObject {
// Invert a binary tree.
//
// 4
// / \
// 2 7
// / \ / \
// 1 3 6 9
//
// to
//
// 4
// / \
// 7 2
// / \ / \
// 9 6 3 1
//
// Trivia:
// This problem was inspired by this original tweet by Max Howell:
// Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
func invertTree(_ root: TreeNode?) -> TreeNode? {
guard let root = root else {
return nil
}
invert(root)
return root
}
private func invert(_ root: TreeNode?) {
guard let root = root else {
return
}
let original = root.left
root.left = root.right
root.right = original
invert(root.left)
invert(root.right)
}
}
| apache-2.0 | c775fba499dd086615296b138ee2596f | 19.4 | 137 | 0.492297 | 3.57 | false | false | false | false |
qRoC/Loobee | Sources/Loobee/Library/AssertionConcern/AssertionNotification.swift | 1 | 1480 | // This file is part of the Loobee package.
//
// (c) Andrey Savitsky <[email protected]>
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
/// Notification about the unsuccessful assertion result.
public struct AssertionNotification: Equatable, CustomStringConvertible, CustomDebugStringConvertible {
/// Message from assertion.
public let message: String
/// File where assertion was called.
public let file: StaticString
/// Line where assertion was called.
public let line: UInt
///
@inlinable
internal init(message: String, file: StaticString, line: UInt) {
self.message = message
self.file = file
self.line = line
}
/// Returns `message`.
public var description: String {
return self.message
}
/// Returns string in format "[#file:#line] message".
public var debugDescription: String {
return "[\(self.file):\(self.line)] \(self.message)"
}
/// `AssertionNotification` factory method.
public static func create(message: String, file: StaticString, line: UInt) -> AssertionNotification {
return .init(message: message, file: file, line: line)
}
///
public static func == (lhs: AssertionNotification, rhs: AssertionNotification) -> Bool {
return lhs.line == rhs.line && lhs.file.utf8Start == rhs.file.utf8Start && lhs.message == rhs.message
}
}
| mit | 5c486ff0a7805571b3da8dc618879b22 | 31.173913 | 109 | 0.668919 | 4.49848 | false | false | false | false |
GE-N/Leaflet | Pod/Classes/UIButton+StateBGColor.swift | 1 | 2481 | // UIButton+StateBGColor.swift
// ButtonExtension
//
// Created by Jerapong Nampetch on 7/19/2558 BE.
// Copyright (c) 2558 Jerapong Nampetch. All rights reserved.
//
import UIKit
private var highlightBGColorKey = 0
private var selectedBGColorKey = 0
private var disableBGColorKey = 0
extension UIButton {
@IBInspectable var highlightBGColor: UIColor? {
get {
return objc_getAssociatedObject(self, &highlightBGColorKey) as? UIColor
}
set {
guard let normalColor = backgroundColor,
let highlightColor = newValue else { return }
objc_setAssociatedObject(self, &highlightBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
setBackgroundImage(bgColorImage(color: normalColor), for: .normal)
setBackgroundImage(bgColorImage(color: highlightColor), for: .highlighted)
}
}
@IBInspectable var selectedBGColor: UIColor? {
get {
return objc_getAssociatedObject(self, &selectedBGColorKey) as? UIColor
}
set {
guard let normalColor = backgroundColor,
let selectedColor = newValue else { return }
objc_setAssociatedObject(self, &selectedBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
setBackgroundImage(bgColorImage(color: normalColor), for: .normal)
setBackgroundImage(bgColorImage(color: selectedColor), for: .selected)
}
}
@IBInspectable var disabledBGColor: UIColor? {
get {
return objc_getAssociatedObject(self, &disableBGColorKey) as? UIColor
}
set {
guard let normalColor = backgroundColor,
let disabledColor = newValue else { return }
objc_setAssociatedObject(self, &disableBGColorKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
setBackgroundImage(bgColorImage(color: normalColor), for: .normal)
setBackgroundImage(bgColorImage(color: disabledColor), for: .disabled)
}
}
// Create 1px image from quartz, inspired from
// http://stackoverflow.com/questions/9151379/is-it-possible-to-use-quartz-2d-to-make-a-uiimage-on-another-thread
func bgColorImage(color: UIColor) -> UIImage {
let size = CGSize(width: 1, height: 1)
let opaque = false
let scale: CGFloat = 0
UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
color.setFill()
UIRectFill(CGRect(origin: CGPoint.zero, size: size))
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
}
| mit | 9e063c060717c0f23a6166bacffea07a | 35.485294 | 116 | 0.723499 | 4.494565 | false | false | false | false |
mcudich/HeckelDiff | Examples/HeckelDiffExample/ViewController.swift | 1 | 1466 | //
// ViewController.swift
// HeckelDiffExample
//
// Created by Matias Cudich on 11/23/16.
// Copyright © 2016 Matias Cudich. All rights reserved.
//
import UIKit
import HeckelDiff
class ViewController: UIViewController, UITableViewDataSource {
lazy var tableView: UITableView = {
let tableView = UITableView(frame: CGRect.zero, style: .plain)
tableView.dataSource = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
return tableView
}()
var items = ["1", "2", "3", "4", "5"]
override func loadView() {
view = tableView
}
override func viewDidLoad() {
super.viewDidLoad()
refresh()
}
func refresh() {
let previousItems = items
let last = items.removeLast()
items.insert(last, at: 0)
tableView.applyDiff(previousItems, items, inSection: 0, withAnimation: .right)
let time = DispatchTime.now() + DispatchTimeInterval.seconds(1)
DispatchQueue.main.asyncAfter(deadline: time) {
self.refresh()
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = items[indexPath.row]
return cell
}
}
| mit | fd9d8545bdc1ed13661e49c99bbf4a5c | 23.830508 | 98 | 0.692833 | 4.283626 | false | false | false | false |
RoverPlatform/rover-ios-beta | Sources/Services/SessionController.swift | 2 | 6122 | //
// SessionController.swift
// Rover
//
// Created by Sean Rucker on 2018-05-21.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import UIKit
/// Responsible for emitting events including a view duration for open and closable registered sessions, such as
/// Experience Viewed or Screen Viewed. Includes some basic hysteresis for ensuring that rapidly re-opened sessions are
/// aggregated into a single session.
class SessionController {
/// The shared singleton sesion controller.
static let shared = SessionController()
private let keepAliveTime: Int = 10
private var observers: [NSObjectProtocol] = []
private init() {
#if swift(>=4.2)
let didBecomeActiveNotification = UIApplication.didBecomeActiveNotification
let willResignActiveNotification = UIApplication.willResignActiveNotification
#else
let didBecomeActiveNotification = NSNotification.Name.UIApplicationDidBecomeActive
let willResignActiveNotification = NSNotification.Name.UIApplicationWillResignActive
#endif
observers = [
NotificationCenter.default.addObserver(
forName: didBecomeActiveNotification,
object: nil,
queue: OperationQueue.main,
using: { _ in
self.entries.forEach {
$0.value.session.start()
}
}
),
NotificationCenter.default.addObserver(
forName: willResignActiveNotification,
object: nil,
queue: OperationQueue.main,
using: { _ in
self.entries.forEach {
$0.value.session.end()
}
}
)
]
}
deinit {
observers.forEach(NotificationCenter.default.removeObserver)
}
// MARK: Registration
private struct Entry {
let session: Session
var isUnregistered = false
init(session: Session) {
self.session = session
}
}
private var entries = [String: Entry]()
func registerSession(identifier: String, completionHandler: @escaping (Double) -> Void) {
if var entry = entries[identifier] {
entry.session.start()
if entry.isUnregistered {
entry.isUnregistered = false
entries[identifier] = entry
}
return
}
let session = Session(keepAliveTime: keepAliveTime) { result in
completionHandler(result.duration)
if let entry = self.entries[identifier], entry.isUnregistered {
self.entries[identifier] = nil
}
}
session.start()
entries[identifier] = Entry(session: session)
}
func unregisterSession(identifier: String) {
if var entry = entries[identifier] {
entry.isUnregistered = true
entries[identifier] = entry
entry.session.end()
}
}
}
private class Session {
let keepAliveTime: Int
struct Result {
var startedAt: Date
var endedAt: Date
var duration: Double {
return endedAt.timeIntervalSince1970 - startedAt.timeIntervalSince1970
}
init(startedAt: Date, endedAt: Date) {
self.startedAt = startedAt
self.endedAt = endedAt
}
init(startedAt: Date) {
let now = Date()
self.init(startedAt: startedAt, endedAt: now)
}
}
private let completionHandler: (Result) -> Void
enum State {
case ready
case started(startedAt: Date)
case ending(startedAt: Date, timer: Timer)
case complete(result: Result)
}
private(set) var state: State = .ready {
didSet {
if case .complete(let result) = state {
completionHandler(result)
}
}
}
init(keepAliveTime: Int, completionHandler: @escaping (Result) -> Void) {
self.keepAliveTime = keepAliveTime
self.completionHandler = completionHandler
}
func start() {
switch state {
case .ready, .complete:
let now = Date()
state = .started(startedAt: now)
case .started:
break
case let .ending(startedAt, timer):
timer.invalidate()
state = .started(startedAt: startedAt)
}
}
func end() {
switch state {
case .ready, .ending, .complete:
break
case .started(let startedAt):
// Capture endedAt now, as opposed to when the timer fires
let endedAt = Date()
// Start a background task before running the timer to allow it to run its course if the app is backgrounded while ending the session.
var backgroundTaskID: UIBackgroundTaskIdentifier!
backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Keep Alive Timer") { [weak self] in
self?.finish(endedAt: endedAt)
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
let timeInterval = TimeInterval(keepAliveTime)
let timer = Timer.scheduledTimer(withTimeInterval: timeInterval, repeats: false, block: { [weak self] _ in
self?.finish(endedAt: endedAt)
UIApplication.shared.endBackgroundTask(backgroundTaskID)
})
state = .ending(startedAt: startedAt, timer: timer)
}
}
func finish(endedAt: Date) {
switch state {
case let .ending(startedAt, timer):
timer.invalidate()
let result = Result(startedAt: startedAt, endedAt: endedAt)
state = .complete(result: result)
default:
break
}
}
}
| mit | 07feae2478b2514d710c05068077eac9 | 30.229592 | 146 | 0.56298 | 5.350524 | false | false | false | false |
RoverPlatform/rover-ios-beta | Sources/UI/ScreenViewLayoutAttributes.swift | 2 | 1413 | //
// ScreenViewLayoutAttributes.swift
// Rover
//
// Created by Sean Rucker on 2018-04-18.
// Copyright © 2018 Rover Labs Inc. All rights reserved.
//
import UIKit
class ScreenLayoutAttributes: UICollectionViewLayoutAttributes {
/**
* Where in absolute space (both position and dimensions) for the entire screen view controller
* this item should be placed.
*/
var referenceFrame = CGRect.zero
var verticalAlignment = UIControl.ContentVerticalAlignment.top
/**
* An optional clip area, in the coordinate space of the block view itself (ie., top left of the view
* is origin).
*/
var clipRect: CGRect? = CGRect.zero
override func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone)
guard let attributes = copy as? ScreenLayoutAttributes else {
return copy
}
attributes.referenceFrame = referenceFrame
attributes.verticalAlignment = verticalAlignment
attributes.clipRect = clipRect
return attributes
}
override func isEqual(_ object: Any?) -> Bool {
guard let rhs = object as? ScreenLayoutAttributes else {
return false
}
return super.isEqual(object) && referenceFrame == rhs.referenceFrame && verticalAlignment == rhs.verticalAlignment && clipRect == rhs.clipRect
}
}
| mit | c1f6f00375d14a6e89d52b26a3dec7c3 | 30.377778 | 150 | 0.646601 | 5.079137 | false | false | false | false |
snyderdesign/wit-fight-alpha | Sources/App/Models/Post.swift | 1 | 2214 | import Vapor
import Fluent
import Foundation
final class Post: Model {
var id: Node?
var content: String
init(content: String) {
self.id = UUID().uuidString.makeNode()
self.content = content
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
content = try node.extract("content")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"content": content
])
}
}
extension Post {
/**
This will automatically fetch from database, using example here to load
automatically for example. Remove on real models.
*/
public convenience init?(from string: String) throws {
self.init(content: string)
}
}
extension Post: Preparation {
static func prepare(_ database: Database) throws {
//
}
static func revert(_ database: Database) throws {
//
}
}
final class Fight {
var id: Node?
var user1: Int
var user2: Int
var title: String
var one: Argument?
var two: Argument?
var three: Argument?
var four: Argument?
var five: Argument?
var six: Argument?
var seven: Argument?
var eight: Argument?
var nine: Argument?
var ten: Argument?
init(user1: Int, user2: Int, title: String) {
self.user1 = user1
self.user2 = user2
self.title = title
}
// init(node: Node, in context: Context) throws {
// id = try node.extract("id")
// namer = try node.extract("name")
// }
static func prepare(_ database: Database) throws {
try database.create("fights") { users in
users.id()
users.string("name")
}
}
static func returnList() -> [Fight] {
let fight1 = Fight(user1: 289, user2: 562, title: "BitchWHAAAT")
let fight2 = Fight(user1: 432, user2: 676, title: "Chaz Drinks Coke")
let fight3 = Fight(user1: 999, user2: 902, title: "Turn down for")
let fight4 = Fight(user1: 969, user2: 696, title: "Ethical implications of the treaty of 1862")
return [fight1, fight2, fight3, fight4]
}
}
final class Argument {
var theArgument: String
var link: String
init(phrase: String, link: String) {
self.theArgument = phrase
self.link = link
}
}
| mit | 7223bb9cec5d4051bebdb35330a432ef | 21.363636 | 97 | 0.632791 | 3.314371 | false | false | false | false |
dreamsxin/swift | test/attr/attr_override.swift | 3 | 15683 | // RUN: %target-parse-verify-swift
@override // expected-error {{'override' can only be specified on class members}} {{1-11=}} expected-error {{'override' is a declaration modifier, not an attribute}} {{1-2=}}
func virtualAttributeCanNotBeUsedInSource() {}
class MixedKeywordsAndAttributes { // expected-note {{in declaration of 'MixedKeywordsAndAttributes'}}
// expected-error@+1 {{expected declaration}} expected-error@+1 {{consecutive declarations on a line must be separated by ';'}} {{11-11=;}}
override @inline(never) func f1() {}
}
class DuplicateOverrideBase {
func f1() {}
class func cf1() {}
class func cf2() {}
class func cf3() {}
class func cf4() {}
}
class DuplicateOverrideDerived : DuplicateOverrideBase {
override override func f1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override override class func cf1() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf2() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
class override override func cf3() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
override class override func cf4() {} // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
}
class A {
func f0() { }
func f1() { } // expected-note{{overridden declaration is here}}
var v1: Int { return 5 }
var v2: Int { return 5 } // expected-note{{overridden declaration is here}}
var v4: String { return "hello" }// expected-note{{attempt to override property here}}
var v5: A { return self }
var v6: A { return self }
var v7: A { // expected-note{{attempt to override property here}}
get { return self }
set { }
}
var v8: Int = 0 // expected-note {{attempt to override property here}}
var v9: Int { return 5 } // expected-note{{attempt to override property here}}
subscript (i: Int) -> String { // expected-note{{potential overridden subscript 'subscript' here}}
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-note{{overridden declaration is here}} expected-note{{potential overridden subscript 'subscript' here}}
get {
return "hello"
}
set {
}
}
subscript (i: Int8) -> A { // expected-note{{potential overridden subscript 'subscript' here}}
get { return self }
}
subscript (i: Int16) -> A { // expected-note{{attempt to override subscript here}} expected-note{{potential overridden subscript 'subscript' here}}
get { return self }
set { }
}
func overriddenInExtension() {} // expected-note {{overridden declaration is here}}
}
class B : A {
override func f0() { }
func f1() { } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
override func f2() { } // expected-error{{method does not override any method from its superclass}}
override var v1: Int { return 5 }
var v2: Int { return 5 } // expected-error{{overriding declaration requires an 'override' keyword}}
override var v3: Int { return 5 } // expected-error{{property does not override any property from its superclass}}
override var v4: Int { return 5 } // expected-error{{property 'v4' with type 'Int' cannot override a property with type 'String'}}
// Covariance
override var v5: B { return self }
override var v6: B {
get { return self }
set { }
}
override var v7: B { // expected-error{{cannot override mutable property 'v7' of type 'A' with covariant type 'B'}}
get { return self }
set { }
}
// Stored properties
override var v8: Int { return 5 } // expected-error {{cannot override mutable property with read-only property 'v8'}}
override var v9: Int // expected-error{{cannot override with a stored property 'v9'}}
override subscript (i: Int) -> String {
get {
return "hello"
}
set {
}
}
subscript (d: Double) -> String { // expected-error{{overriding declaration requires an 'override' keyword}} {{3-3=override }}
get {
return "hello"
}
set {
}
}
override subscript (f: Float) -> String { // expected-error{{subscript does not override any subscript from its superclass}}
get {
return "hello"
}
set {
}
}
// Covariant
override subscript (i: Int8) -> B {
get { return self }
}
override subscript (i: Int16) -> B { // expected-error{{cannot override mutable subscript of type '(Int16) -> B' with covariant type '(Int16) -> A'}}
get { return self }
set { }
}
override init() { }
override deinit { } // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
override typealias Inner = Int // expected-error{{'override' modifier cannot be applied to this declaration}} {{3-12=}}
}
extension B {
override func overriddenInExtension() {} // expected-error{{declarations in extensions cannot override yet}}
}
struct S {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
extension S {
override func ef() {} // expected-error{{method does not override any method from its superclass}}
}
enum E {
override func f() { } // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
protocol P {
override func f() // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
override func f() { } // expected-error{{'override' can only be specified on class members}} {{1-10=}}
// Invalid 'override' on declarations inside closures.
var rdar16654075a = {
override func foo() {} // expected-error{{'override' can only be specified on class members}} {{3-12=}}
}
var rdar16654075b = {
class A {
override func foo() {} // expected-error{{method does not override any method from its superclass}}
}
}
var rdar16654075c = { () -> () in
override func foo() {} // expected-error {{'override' can only be specified on class members}} {{3-12=}}
()
}
var rdar16654075d = { () -> () in
class A {
override func foo() {} // expected-error {{method does not override any method from its superclass}}
}
A().foo()
}
var rdar16654075e = { () -> () in
class A {
func foo() {}
}
class B : A {
override func foo() {}
}
A().foo()
}
class C {
init(string: String) { } // expected-note{{overridden declaration is here}}
required init(double: Double) { } // expected-note 3{{overridden required initializer is here}}
convenience init() { self.init(string: "hello") } // expected-note{{attempt to override convenience initializer here}}
}
class D1 : C {
override init(string: String) { super.init(string: string) }
required init(double: Double) { }
convenience init() { self.init(string: "hello") }
}
class D2 : C {
init(string: String) { super.init(string: string) } // expected-error{{overriding declaration requires an 'override' keyword}}{{3-3=override }}
// FIXME: Would like to remove the space after 'override' as well.
required override init(double: Double) { } // expected-warning{{'override' is implied when overriding a required initializer}} {{12-21=}}
override convenience init() { self.init(string: "hello") } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class D3 : C {
override init(string: String) { super.init(string: string) }
override init(double: Double) { } // expected-error{{use the 'required' modifier to override a required initializer}}{{3-11=required}}
}
class D4 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required override init(string: String) { super.init(string: string) }
required init(double: Double) { }
}
class D5 : C {
// "required override" only when we're overriding a non-required
// designated initializer with a required initializer.
required convenience override init(string: String) { self.init(double: 5.0) }
required init(double: Double) { }
}
class D6 : C {
init(double: Double) { } // expected-error{{'required' modifier must be present on all overrides of a required initializer}} {{3-3=required }}
}
// rdar://problem/18232867
class C_empty_tuple {
init() { }
}
class D_empty_tuple : C_empty_tuple {
override init(foo:()) { } // expected-error{{initializer does not override a designated initializer from its superclass}}
}
class C_with_let {
let x = 42 // expected-note {{attempt to override property here}}
}
class D_with_let : C_with_let {
override var x : Int { get { return 4 } set {} } // expected-error {{cannot override immutable 'let' property 'x' with the getter of a 'var'}}
}
// <rdar://problem/21311590> QoI: Inconsistent diagnostics when no constructor is available
class C21311590 {
override init() {} // expected-error {{initializer does not override a designated initializer from its superclass}}
}
class B21311590 : C21311590 {}
_ = C21311590()
_ = B21311590()
class MismatchOptionalBase {
func param(_: Int?) {}
func paramIUO(_: Int!) {}
func result() -> Int { return 0 }
func fixSeveralTypes(a: Int?, b: Int!) -> Int { return 0 }
func functionParam(x: ((Int) -> Int)?) {}
func tupleParam(x: (Int, Int)?) {}
func nameAndTypeMismatch(label: Int?) {}
func ambiguousOverride(a: Int, b: Int?) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
func ambiguousOverride(a: Int?, b: Int) {} // expected-note 2 {{overridden declaration is here}} expected-note {{potential overridden instance method 'ambiguousOverride(a:b:)' here}}
var prop: Int = 0 // expected-note {{attempt to override property here}}
var optProp: Int? // expected-note {{attempt to override property here}}
var getProp: Int { return 0 } // expected-note {{attempt to override property here}}
var getOptProp: Int? { return nil }
init(param: Int?) {}
init() {} // expected-note {{non-failable initializer 'init()' overridden here}}
subscript(a: Int?) -> Void { // expected-note {{attempt to override subscript here}}
get { return () }
set {}
}
subscript(b: Void) -> Int { // expected-note {{attempt to override subscript here}}
get { return 0 }
set {}
}
subscript(get a: Int?) -> Void {
return ()
}
subscript(get b: Void) -> Int {
return 0
}
subscript(ambiguous a: Int, b: Int?) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
subscript(ambiguous a: Int?, b: Int) -> Void { // expected-note {{overridden declaration is here}} expected-note {{potential overridden subscript 'subscript(ambiguous:_:)' here}}
return ()
}
}
class MismatchOptional : MismatchOptionalBase {
override func param(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{29-29=?}}
override func paramIUO(_: Int) {} // expected-error {{cannot override instance method parameter of type 'Int!' with non-optional type 'Int'}} {{32-32=?}}
override func result() -> Int? { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int?'}} {{32-33=}}
override func fixSeveralTypes(a: Int, b: Int) -> Int! { return nil }
// expected-error@-1 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{39-39=?}}
// expected-error@-2 {{cannot override instance method parameter of type 'Int!' with non-optional type 'Int'}} {{47-47=?}}
// expected-error@-3 {{cannot override instance method result type 'Int' with optional type 'Int!'}} {{55-56=}}
override func functionParam(x: (Int) -> Int) {} // expected-error {{cannot override instance method parameter of type '((Int) -> Int)?' with non-optional type '(Int) -> Int'}} {{34-34=(}} {{46-46=)?}}
override func tupleParam(x: (Int, Int)) {} // expected-error {{cannot override instance method parameter of type '(Int, Int)?' with non-optional type '(Int, Int)'}} {{41-41=?}}
override func nameAndTypeMismatch(_: Int) {}
// expected-error@-1 {{argument names for method 'nameAndTypeMismatch' do not match those of overridden method 'nameAndTypeMismatch(label:)'}} {{37-37=label }}
// expected-error@-2 {{cannot override instance method parameter of type 'Int?' with non-optional type 'Int'}} {{43-43=?}}
override func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}} {{none}}
override func ambiguousOverride(a: Int, b: Int) {} // expected-error {{method does not override any method from its superclass}} {{none}}
override var prop: Int? { // expected-error {{property 'prop' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
get { return nil }
set {}
}
override var optProp: Int { // expected-error {{cannot override mutable property 'optProp' of type 'Int?' with covariant type 'Int'}} {{none}}
get { return 0 }
set {}
}
override var getProp: Int? { return nil } // expected-error {{property 'getProp' with type 'Int?' cannot override a property with type 'Int'}} {{none}}
override var getOptProp: Int { return 0 } // okay
override init(param: Int) {} // expected-error {{cannot override initializer parameter of type 'Int?' with non-optional type 'Int'}}
override init?() {} // expected-error {{failable initializer 'init()' cannot override a non-failable initializer}} {{none}}
override subscript(a: Int) -> Void { // expected-error {{cannot override mutable subscript of type '(Int) -> Void' with covariant type '(Int?) -> Void'}}
get { return () }
set {}
}
override subscript(b: Void) -> Int? { // expected-error {{cannot override mutable subscript of type '(Void) -> Int?' with covariant type '(Void) -> Int'}}
get { return nil }
set {}
}
override subscript(get a: Int) -> Void { // expected-error {{cannot override subscript index of type 'Int?' with non-optional type 'Int'}} {{32-32=?}}
return ()
}
override subscript(get b: Void) -> Int? { // expected-error {{cannot override subscript element type 'Int' with optional type 'Int?'}} {{41-42=}}
return nil
}
override subscript(ambiguous a: Int?, b: Int?) -> Void { // expected-error {{declaration 'subscript(ambiguous:_:)' cannot override more than one superclass declaration}}
return ()
}
override subscript(ambiguous a: Int, b: Int) -> Void { // expected-error {{subscript does not override any subscript from its superclass}}
return ()
}
}
class MismatchOptional2 : MismatchOptionalBase {
override func result() -> Int! { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Int!'}} {{32-33=}}
// None of these are overrides because we didn't say 'override'. Since they're
// not exact matches, they shouldn't result in errors.
func param(_: Int) {}
func ambiguousOverride(a: Int, b: Int) {}
// This is covariant, so we still assume it's meant to override.
func ambiguousOverride(a: Int?, b: Int?) {} // expected-error {{declaration 'ambiguousOverride(a:b:)' cannot override more than one superclass declaration}}
}
class MismatchOptional3 : MismatchOptionalBase {
override func result() -> Optional<Int> { return nil } // expected-error {{cannot override instance method result type 'Int' with optional type 'Optional<Int>'}} {{none}}
}
| apache-2.0 | beb30dea5a5792851a69be656b4a2ff8 | 39.947781 | 202 | 0.673914 | 3.992617 | false | false | false | false |
adamkaplan/swifter | SwifterTests/TreeTests.swift | 1 | 1758 | //
// TreeTests.swift
// Swifter
//
// Created by Daniel Hanggi on 7/23/14.
// Copyright (c) 2014 Yahoo!. All rights reserved.
//
import XCTest
private let t0 = Leaf<Int>()
private let t1 = Node(t0, 1, t0)
private let t2 = Node(t1, 2, t1)
private let t3 = Node(t1, 3, t2)
private let t4 = Node(t3, 4, t0)
class TreeTests: XCTestCase {
func testFold() -> () {
let fold = t4.fold(1) {
(left: Int, node: Int, right: Int) -> Int in
return -node + left * right
}
XCTAssertEqual(fold, -7)
}
func testNode() -> () {
XCTAssertNil(t0.node())
XCTAssertEqual(t3.node()!, 3)
}
func testIsEmpty() -> () {
XCTAssertTrue(t0.isEmpty())
XCTAssertFalse(t2.isEmpty())
}
func testMap() -> () {
XCTAssertNil(t0.map { $0 * 10 }.node())
XCTAssertEqual(t1.map { $0 * 10 }.node()!, 10)
XCTAssertEqual(t3.map { $0 * 10 }.node()!, 30)
let sum: Tree<Int> -> Int = { $0.fold(0) { $0 + $1 + $2 } }
XCTAssertEqual(sum(t2.map { $0 * 10}), 10 * sum(t2))
}
func testContains() -> () {
XCTAssertFalse(t0.contains(1, ==))
XCTAssertFalse(t1.contains(2, ==))
XCTAssertTrue(t1.contains(1, ==))
}
func testSize() -> () {
XCTAssertEqual(t0.count(), 0)
XCTAssertEqual(t1.count(), 1)
XCTAssertEqual(t2.count(), 3)
XCTAssertEqual(t3.count(), 5)
XCTAssertEqual(t4.count(), 6)
}
func testEqual() -> () {
XCTAssertFalse(t0.equal(t1, ==))
XCTAssertTrue(t0.equal(t0, ==))
XCTAssertTrue(t2.equal(t2, ==))
XCTAssertFalse(t3.equal(t4, ==))
XCTAssertTrue(t3.equal(t4.leftSubtree()!, ==))
}
}
| apache-2.0 | 3ea5b9667fd2b22eb7c65b2ddc01c99a | 25.238806 | 67 | 0.52446 | 3.279851 | false | true | false | false |
qkrqjadn/SoonChat | source/RegisterController.swift | 2 | 9302 | //
// RegisterController.swift
// soonchat
//
// Created by 박범우 on 2016. 12. 18..
// Copyright © 2016년 bumwoo. All rights reserved.
//
import UIKit
import Firebase
import NVActivityIndicatorView
class RegisterController : UIViewController
{
let inputsContainerView : UIView = {
let view = UIView()
view.backgroundColor = UIColor.white
view.translatesAutoresizingMaskIntoConstraints = false
view.layer.cornerRadius = 5
view.layer.masksToBounds = true
return view
}()
lazy var loginRegisterButton: UIButton = {
let button = UIButton(type: .system)
button.backgroundColor = UIColor(r: 53, g: 146, b: 232)
button.setTitle("가입하기", for: .normal)
button.setTitleColor(.white, for: .normal)
button.translatesAutoresizingMaskIntoConstraints = false
button.layer.cornerRadius = 5
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.addTarget(self, action: #selector(clickregister), for: .touchUpInside)
return button
}()
let cancelButton : UIButton = {
let button = UIButton(type: .system)
button.setTitle("취소", for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
button.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
return button
}()
let nameTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "Name"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let emailTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "e-mail"
tf.translatesAutoresizingMaskIntoConstraints = false
return tf
}()
let passwdTextField : UITextField = {
let tf = UITextField()
tf.placeholder = "PassWord"
tf.translatesAutoresizingMaskIntoConstraints = false
tf.isSecureTextEntry = true
return tf
}()
let separatorView : [UIView] = {
var conview = [UIView]()
let view1 = UIView()
let view2 = UIView()
conview.append(view1)
conview.append(view2)
conview.forEach({
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = UIColor(r: 200, g: 200, b: 200)
})
return conview
}()
let activityindicator : NVActivityIndicatorView = {
let ai = NVActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 60, height: 60), type: .ballPulse, color: UIColor(r: 250, g: 156, b: 0), padding: NVActivityIndicatorView.DEFAULT_PADDING)
ai.translatesAutoresizingMaskIntoConstraints = false
return ai
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(r: 53, g: 101, b: 232)
view.addSubview(loginRegisterButton)
view.addSubview(inputsContainerView)
view.addSubview(cancelButton)
view.addSubview(nameTextField)
view.addSubview(emailTextField)
view.addSubview(passwdTextField)
view.addSubview(separatorView[0])
view.addSubview(separatorView[1])
view.addSubview(activityindicator)
setupInputsContainerView()
setupLoginRegisterButton()
setupCancelButton()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
func clickregister()
{
self.activityindicator.startAnimating()
DispatchQueue.global().async {
guard let email = self.emailTextField.text ,let passwd = self.passwdTextField.text , let name = self.nameTextField.text else {return}
FIRAuth.auth()?.createUser(withEmail: email, password: passwd, completion: { (user: FIRUser?, error) in
if error != nil {
self.activityindicator.stopAnimating()
let alertview = UIAlertController(title: "에러", message: error?.localizedDescription, preferredStyle: .alert)
alertview.addAction(UIAlertAction(title: "취소", style: .cancel, handler: { (_) in }))
self.present(alertview, animated: true , completion: nil)
return
}
guard let uid = user?.uid else { return }
let ref = FirebaseAPI.sharedInstance.dataBaseRef
let usersReference = ref.child("users").child(uid)
let values = ["name": name,"email":email]
usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
if err != nil {
self.activityindicator.stopAnimating()
let alertview = UIAlertController(title: "에러", message: err?.localizedDescription, preferredStyle: .alert)
alertview.addAction(UIAlertAction(title: "취소", style: .cancel, handler: { (_) in }))
self.present(alertview, animated: true , completion: nil)
return
}
self.activityindicator.stopAnimating()
self.dismiss(animated: true, completion: nil)
})
})
}
}
func cancelButtonClick()
{
dismiss(animated: true, completion: nil)
}
func setupInputsContainerView()
{
inputsContainerView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
inputsContainerView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
inputsContainerView.widthAnchor.constraint(equalTo: view.widthAnchor, constant: -24).isActive = true
inputsContainerView.heightAnchor.constraint(equalToConstant: 150).isActive = true
nameTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant : 12).isActive = true
nameTextField.topAnchor.constraint(equalTo: inputsContainerView.topAnchor).isActive = true
nameTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
nameTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3).isActive = true
emailTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant : 12).isActive = true
emailTextField.topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
emailTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
emailTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3).isActive = true
passwdTextField.leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor, constant : 12).isActive = true
passwdTextField.topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
passwdTextField.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
passwdTextField.heightAnchor.constraint(equalTo: inputsContainerView.heightAnchor, multiplier: 1/3).isActive = true
separatorView[0].leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
separatorView[0].topAnchor.constraint(equalTo: nameTextField.bottomAnchor).isActive = true
separatorView[0].widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
separatorView[0].heightAnchor.constraint(equalToConstant: 1).isActive = true
separatorView[1].leftAnchor.constraint(equalTo: inputsContainerView.leftAnchor).isActive = true
separatorView[1].topAnchor.constraint(equalTo: emailTextField.bottomAnchor).isActive = true
separatorView[1].widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
separatorView[1].heightAnchor.constraint(equalToConstant: 1).isActive = true
activityindicator.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
activityindicator.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
}
func setupLoginRegisterButton()
{
loginRegisterButton.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
loginRegisterButton.topAnchor.constraint(equalTo: inputsContainerView.bottomAnchor, constant: 12).isActive = true
loginRegisterButton.widthAnchor.constraint(equalTo: inputsContainerView.widthAnchor).isActive = true
loginRegisterButton.heightAnchor.constraint(equalToConstant: 50).isActive = true
}
func setupCancelButton()
{
_ = cancelButton.anchor(view.topAnchor, left: view.leftAnchor, bottom: nil, right: nil, topConstant: 20, leftConstant: 10, bottomConstant: 0, rightConstant: 0, widthConstant: 50, heightConstant: 30)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension UIColor
{
convenience init(r: CGFloat , g : CGFloat, b: CGFloat)
{
self.init(red: r/255,green: g/255, blue: b/255, alpha: 1)
}
}
| mit | 6f57e7454b143b5742318af96cd7a755 | 42.497653 | 206 | 0.665839 | 5.082282 | false | false | false | false |
dbahat/conventions-ios | Conventions/Conventions/secondhand/SecondHandViewController.swift | 1 | 8548 | //
// secondHandViewController.swift
// Conventions
//
// Created by David Bahat on 30/09/2017.
// Copyright © 2017 Amai. All rights reserved.
//
import Foundation
import Firebase
class SecondHandViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate, SecondHandFormProtocol, UIScrollViewDelegate {
@IBOutlet private weak var refreshIndicatorView: UIActivityIndicatorView!
@IBOutlet private weak var noItemsFoundLabel: UILabel!
@IBOutlet private weak var tableView: UITableView!
// Keeping the tableController as a child so we'll be able to add other subviews to the current
// screen's view controller (e.g. snackbarView)
private let tableViewController = UITableViewController()
var forms: Array<SecondHand.Form> {
get {
return Convention.instance.secondHand.forms
}
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: String(describing: SecondHandFormHeaderView.self), bundle: nil), forHeaderFooterViewReuseIdentifier: String(describing: SecondHandFormHeaderView.self))
tableView.register(UINib(nibName: String(describing: SecondHandItemViewCell.self), bundle: nil), forCellReuseIdentifier: String(describing: SecondHandItemViewCell.self))
addRefreshController()
noItemsFoundLabel.textColor = Colors.textColor
noItemsFoundLabel.isHidden = forms.count > 0
tableView.isHidden = forms.count == 0
tableView.estimatedSectionHeaderHeight = 70
tableView.estimatedRowHeight = 70
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.rowHeight = UITableView.automaticDimension
refreshIndicatorView.color = Colors.colorAccent
refresh(force: false)
}
func numberOfSections(in tableView: UITableView) -> Int {
return forms.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return forms[section].items.count
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: String(describing: SecondHandFormHeaderView.self)) as! SecondHandFormHeaderView
headerView.form = forms[section]
headerView.delegate = self
return headerView
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SecondHandItemViewCell.self)) as! SecondHandItemViewCell
let form = forms[indexPath.section]
let item = form.items[indexPath.row]
cell.bind(item: item, isFormClosed: form.status.isClosed())
return cell
}
func removeWasClicked(formId: Int) {
if let formIndex = forms.firstIndex(where: {$0.id == formId}) {
Convention.instance.secondHand.remove(formId: formId)
tableView.deleteSections(IndexSet(integer: formIndex), with: .automatic)
noItemsFoundLabel.isHidden = forms.count > 0
tableView.isHidden = forms.count == 0
}
}
@objc func userPulledToRefresh() {
refresh(force: true)
}
private func refresh(force: Bool) {
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Convention.instance.secondHand.refresh(force: force, {success in
self.tableViewController.refreshControl?.endRefreshing()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
Analytics.logEvent("SecondHand", parameters: [
"name": "PullToRefresh" as NSObject,
"success": success as NSObject
])
if (!success) {
TTGSnackbar(message: "לא ניתן לעדכן. בדוק חיבור לאינטרנט", duration: TTGSnackbarDuration.middle, superView: self.view).show()
return
}
self.tableView.reloadData()
self.noItemsFoundLabel.isHidden = self.forms.count > 0
self.tableView.isHidden = self.forms.count == 0
})
}
@IBAction func addFormWasClicked(_ sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "הוספת טופס", message: "הכנס את מספר הטופס", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "בטל", style: .cancel) { (result : UIAlertAction) -> Void in }
let okAction = UIAlertAction(title: "הוסף", style: .default) { (result : UIAlertAction) -> Void in
guard let formId = Int(alertController.textFields![0].text!) else {
TTGSnackbar(message: "מספר טופס לא תקין", duration: TTGSnackbarDuration.middle, superView: self.view).show()
return
}
if formId < 0 {
TTGSnackbar(message: "מספר טופס לא תקין", duration: TTGSnackbarDuration.middle, superView: self.view).show()
return
}
if self.forms.contains(where: {$0.id == formId}) {
TTGSnackbar(message: "הטופס כבר קיים ברשימה", duration: TTGSnackbarDuration.middle, superView: self.view).show()
return
}
self.refreshIndicatorView.startAnimating()
UIApplication.shared.isNetworkActivityIndicatorVisible = true
Convention.instance.secondHand.refresh(formId: formId, {success in
self.refreshIndicatorView.stopAnimating()
UIApplication.shared.isNetworkActivityIndicatorVisible = false
Analytics.logEvent("SecondHand", parameters: [
"name": "AddForm" as NSObject,
"formId": formId as NSObject,
"success": success as NSObject
])
if !success {
TTGSnackbar(message: "לא ניתן להוסיף את הטופס", duration: TTGSnackbarDuration.middle, superView: self.view).show()
return
}
self.tableView.insertSections(IndexSet(integer: self.forms.count - 1), with: .automatic)
self.noItemsFoundLabel.isHidden = self.forms.count > 0
self.tableView.isHidden = self.forms.count == 0
})
}
alertController.addTextField(configurationHandler: {textField in })
alertController.addAction(cancelAction)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
// Needed so the events can be invisible when scrolled behind the sticky header.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
for cell in tableView.visibleCells {
guard let navController = navigationController else {
continue
}
let hiddenFrameHeight = scrollView.contentOffset.y + navController.navigationBar.frame.size.height - cell.frame.origin.y
if (hiddenFrameHeight >= 0 || hiddenFrameHeight <= cell.frame.size.height) {
if let customCell = cell as? SecondHandItemViewCell {
customCell.maskCell(fromTop: hiddenFrameHeight)
}
}
}
}
// TODO - Remove duplication with EventsViewController
private func addRefreshController() {
// Adding a tableViewController for hosting a UIRefreshControl.
// Without a table controller the refresh control causes weird UI issues (e.g. wrong handling of
// sticky section headers).
tableViewController.tableView = tableView;
tableViewController.refreshControl = UIRefreshControl()
tableViewController.refreshControl?.tintColor = Colors.colorAccent
tableViewController.refreshControl?.addTarget(self, action: #selector(SecondHandViewController.userPulledToRefresh), for: UIControl.Event.valueChanged)
tableViewController.refreshControl?.backgroundColor = UIColor.clear
addChild(tableViewController)
tableViewController.didMove(toParent: self)
}
}
| apache-2.0 | 048b97778cb565a91d595a695b1db507 | 43.099476 | 193 | 0.641577 | 5.083283 | false | false | false | false |
Anviking/Decodable | Tests/DecodableOperatorsTests.swift | 2 | 8983 | //
// DecodableOperatorsTests.swift
// Decodable
//
// Created by FJBelchi on 13/07/15.
// Copyright © 2015 anviking. All rights reserved.
//
import XCTest
import protocol Decodable.Decodable
import enum Decodable.DecodingError
@testable import Decodable
class DecodableOperatorsTests: XCTestCase {
// MARK: =>
func testDecodeAnyDecodableSuccess() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
let string = try! dictionary => KeyPath(key) as String
// then
XCTAssertEqual(string, value)
}
func testDecodeAnyDecodableDictionarySuccess() {
// given
let key = "key"
let value: NSDictionary = [key : "value"]
let dictionary: NSDictionary = [key: value]
// when
let result: NSDictionary = try! dictionary => KeyPath(key) as! NSDictionary
// then
XCTAssertEqual(result, value)
}
func testDecodeDictOfArraysSucess() {
// given
let key = "key"
let value: NSDictionary = ["list": [1, 2, 3]]
let dictionary: NSDictionary = [key: value]
// when
let result: [String: [Int]] = try! dictionary => KeyPath(key)
// then
XCTAssertEqual(result as NSDictionary, value)
}
// MARK: - Nested keys
func testDecodeNestedDictionarySuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key"
// then
XCTAssertEqual(result as? NSDictionary, value)
}
func testDecodeNestedDictionaryOptionalSuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key" as! [String : Any]
// then
XCTAssertEqual(result as NSDictionary, value)
}
// TODO: this does not compile with Swift 3
// func testDecodeNestedIntSuccess() {
// // given
// let value = 4
// let dictionary: NSDictionary = ["key1": ["key2": ["key3": value]]]
// // when
// let result: Int = try! dictionary => "key1" => "key2" => "key3"
// // then
// XCTAssertEqual(result, value)
// }
func testDecodeNestedDictionaryCastingSuccess() {
// given
let value: NSDictionary = ["aKey" : "value"]
let dictionary: NSDictionary = ["key": ["key": value]]
// when
let result = try! dictionary => "key" => "key" as! [String: String]
// then
XCTAssertEqual(result, value as! [String : String])
}
func testDecodeAnyDecodableOptionalSuccess() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
let string = try! dictionary => KeyPath(key) as String?
// then
XCTAssertEqual(string!, value)
}
func testDecodeAnyDecodableOptionalNilSuccess() {
// given
let key = "key"
let dictionary: NSDictionary = [key: NSNull()]
// when
let string = try! dictionary => KeyPath(key) as String?
// then
XCTAssertNil(string)
}
func testDecodeAnyDecodableOptionalTypeMismatchFailure() {
// given
let key = "key"
let dictionary: NSDictionary = [key: 2]
// when
do {
let a = try dictionary => KeyPath(key) as String?
print(a as Any)
XCTFail()
} catch let DecodingError.typeMismatch(_, actual, _) {
let typeString = String(describing: actual)
XCTAssertTrue(typeString.contains("Number"), "\(typeString) should contain NSNumber")
} catch let error {
XCTFail("should not throw \(error)")
}
}
// MARK: - Nested =>? operators
// Should throw on typemismatch with correct metadata
func testDecodeNestedTypeMismatchFailure() {
let json: NSDictionary = ["user": ["followers": "not_an_integer"]]
do {
let _ : Int? = try json =>? "user" => "followers"
XCTFail("should throw")
} catch let DecodingError.typeMismatch(_, _, metadata) {
XCTAssertEqual(metadata.formattedPath, "user.followers")
} catch {
XCTFail("should not throw \(error)")
}
}
// Should currently (though really it shoult not) treat all keys as either optional or non-optional
func testDecodeNestedTypeReturnNilForSubobjectMissingKey() {
let json: NSDictionary = ["user": ["something_else": "test"]]
try! XCTAssertEqual(json =>? "user" =>? "followers", Optional<Int>.none)
}
// Sanity check
func testDecodeNestedTypeSuccess() {
let json: NSDictionary = ["user": ["followers": 3]]
try! XCTAssertEqual(json =>? "user" => "followers", 3)
}
// MARK: => Errors
/* //
func testDecodeNestedDictionaryCastingFailure() {
// given
let value: NSDictionary = ["apple" : 2]
let dictionary: NSDictionary = ["firstKey": ["secondKey": value]]
// when
do {
_ = try dictionary => "firstKey" => "secondKey" as [String: String]
XCTFail()
} catch DecodingError.typeMismatchError(_, Dictionary<String, String>.self, let info) {
// then
XCTAssertEqual(info.formattedPath, "firstKey.secondKey")
XCTAssertEqual(info.object as? NSDictionary, value)
} catch let error {
XCTFail("should not throw \(error)")
}
}
*/
func testDecodeAnyDecodableThrowMissingKeyException() {
// given
let key = "key"
let value = "value"
let dictionary: NSDictionary = [key: value]
// when
do {
_ = try dictionary => "nokey" as String
} catch let DecodingError.missingKey(key, metadata) {
// then
XCTAssertEqual(key, "nokey")
XCTAssertEqual(metadata.path, [])
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSDictionary, dictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableThrowNoJsonObjectException() {
// given
let key = "key"
let noDictionary: NSString = "hello"
// when
do {
_ = try noDictionary => KeyPath(key) as String
} catch let DecodingError.typeMismatch(expected, actual, metadata) where expected == NSDictionary.self {
// then
XCTAssertTrue(true)
XCTAssertTrue(String(describing: actual).contains("String"))
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSString, (noDictionary))
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowMissingKeyException() {
// given
let key = "key"
let value: NSDictionary = [key : "value"]
let dictionary: NSDictionary = [key: value]
// when
do {
_ = try dictionary => "nokey"
} catch let DecodingError.missingKey(key, metadata) {
// then
XCTAssertEqual(key, "nokey")
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.path, [])
XCTAssertEqual(metadata.object as? NSDictionary, dictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowJSONNotObjectException() {
// given
let key = "key"
let noDictionary: NSString = "noDictionary"
// when
do {
_ = try noDictionary => KeyPath(key)
} catch let DecodingError.typeMismatch(expected, actual, metadata) where expected == NSDictionary.self {
// then
XCTAssertTrue(true)
XCTAssertEqual(String(describing: actual), "__NSCFString")
XCTAssertEqual(metadata.formattedPath, "")
XCTAssertEqual(metadata.object as? NSString, noDictionary)
} catch let error {
XCTFail("should not throw \(error)")
}
}
func testDecodeAnyDecodableDictionaryThrowTypeMismatchException() {
// given
let key = "key"
let dictionary: NSDictionary = [key: "value"]
// when
do {
_ = try dictionary => KeyPath(key)
} catch DecodingError.typeMismatch {
// then
XCTAssertTrue(true)
} catch let error {
XCTFail("should not throw \(error)")
}
}
}
| mit | 47e36ae937dc17584225e7489c60da43 | 32.266667 | 112 | 0.567802 | 4.785296 | false | true | false | false |
adrfer/swift | test/SILGen/pointer_conversion.swift | 2 | 7845 | // RUN: %target-swift-frontend -emit-silgen -sdk %S/Inputs -I %S/Inputs -enable-source-import %s | FileCheck %s
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Foundation
func takesMutablePointer(x: UnsafeMutablePointer<Int>) {}
func takesConstPointer(x: UnsafePointer<Int>) {}
func takesMutableVoidPointer(x: UnsafeMutablePointer<Void>) {}
func takesConstVoidPointer(x: UnsafePointer<Void>) {}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion16pointerToPointerFTGSpSi_GSPSi__T_
// CHECK: bb0([[MP:%.*]] : $UnsafeMutablePointer<Int>, [[CP:%.*]] : $UnsafePointer<Int>):
func pointerToPointer(mp: UnsafeMutablePointer<Int>,
_ cp: UnsafePointer<Int>) {
// There should be no conversion here
takesMutablePointer(mp)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[MP]])
takesMutableVoidPointer(mp)
// CHECK: [[TAKES_MUTABLE_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion23takesMutableVoidPointer
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafeMutablePointer<()>>
// CHECK: apply [[TAKES_MUTABLE_VOID_POINTER]]
takesConstPointer(mp)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_TF18pointer_conversion17takesConstPointerFGSPSi_T_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<Int>>
// CHECK: apply [[TAKES_CONST_POINTER]]
takesConstVoidPointer(mp)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion21takesConstVoidPointerFGSPT__T_
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs32_convertPointerToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>, UnsafePointer<()>>
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion14arrayToPointerFT_T_
func arrayToPointer() {
var ints = [1,2,3]
takesMutablePointer(&ints)
// CHECK: [[TAKES_MUTABLE_POINTER:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[CONVERT_MUTABLE:%.*]] = function_ref @_TFs37_convertMutableArrayToPointerArgument
// CHECK: apply [[CONVERT_MUTABLE]]<Int, UnsafeMutablePointer<Int>>([[TUPLE_BUF:%[0-9]*]],
// CHECK: [[TUPLE:%.*]] = load [[TUPLE_BUF]]
// CHECK: [[OWNER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 0
// CHECK: [[POINTER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 1
// CHECK: apply [[TAKES_MUTABLE_POINTER]]([[POINTER]])
// CHECK: release_value [[OWNER]]
takesConstPointer(ints)
// CHECK: [[TAKES_CONST_POINTER:%.*]] = function_ref @_TF18pointer_conversion17takesConstPointerFGSPSi_T_
// CHECK: [[CONVERT_CONST:%.*]] = function_ref @_TFs35_convertConstArrayToPointerArgument
// CHECK: apply [[CONVERT_CONST]]<Int, UnsafePointer<Int>>([[TUPLE_BUF:%[0-9]*]],
// CHECK: [[TUPLE:%.*]] = load [[TUPLE_BUF]]
// CHECK: [[OWNER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 0
// CHECK: [[POINTER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 1
// CHECK: apply [[TAKES_CONST_POINTER]]([[POINTER]])
// CHECK: release_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion15stringToPointerFSST_
func stringToPointer(s: String) {
takesConstVoidPointer(s)
// CHECK: [[TAKES_CONST_VOID_POINTER:%.*]] = function_ref @_TF18pointer_conversion21takesConstVoidPointerFGSPT__T_
// CHECK: [[CONVERT_STRING:%.*]] = function_ref @_TFs40_convertConstStringToUTF8PointerArgument
// CHECK: apply [[CONVERT_STRING]]<UnsafePointer<()>>([[TUPLE_BUF:%[0-9]*]],
// CHECK: [[TUPLE:%.*]] = load [[TUPLE_BUF]]
// CHECK: [[OWNER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 0
// CHECK: [[POINTER:%.*]] = tuple_extract [[TUPLE]] : ${{.*}}, 1
// CHECK: apply [[TAKES_CONST_VOID_POINTER]]([[POINTER]])
// CHECK: release_value [[OWNER]]
}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion14inoutToPointerFT_T_
func inoutToPointer() {
var int = 0
// CHECK: [[INT:%.*]] = alloc_box $Int
// CHECK: [[PB:%.*]] = project_box [[INT]]
takesMutablePointer(&int)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[POINTER:%.*]] = address_to_pointer [[PB]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_MUTABLE]]
var logicalInt: Int {
get { return 0 }
set { }
}
takesMutablePointer(&logicalInt)
// CHECK: [[TAKES_MUTABLE:%.*]] = function_ref @_TF18pointer_conversion19takesMutablePointer
// CHECK: [[GETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_gL_10logicalIntSi
// CHECK: apply [[GETTER]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<Int>>
// CHECK: apply [[TAKES_MUTABLE]]
// CHECK: [[SETTER:%.*]] = function_ref @_TFF18pointer_conversion14inoutToPointerFT_T_sL_10logicalIntSi
// CHECK: apply [[SETTER]]
}
class C {}
func takesPlusOnePointer(x: UnsafeMutablePointer<C>) {}
func takesPlusZeroPointer(x: AutoreleasingUnsafeMutablePointer<C>) {}
func takesPlusZeroOptionalPointer(x: AutoreleasingUnsafeMutablePointer<C?>) {}
// CHECK-LABEL: sil hidden @_TF18pointer_conversion19classInoutToPointerFT_T_
func classInoutToPointer() {
var c = C()
// CHECK: [[VAR:%.*]] = alloc_box $C
// CHECK: [[PB:%.*]] = project_box [[VAR]]
takesPlusOnePointer(&c)
// CHECK: [[TAKES_PLUS_ONE:%.*]] = function_ref @_TF18pointer_conversion19takesPlusOnePointer
// CHECK: [[POINTER:%.*]] = address_to_pointer [[PB]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<UnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ONE]]
takesPlusZeroPointer(&c)
// CHECK: [[TAKES_PLUS_ZERO:%.*]] = function_ref @_TF18pointer_conversion20takesPlusZeroPointerFGVs33AutoreleasingUnsafeMutablePointerCS_1C_T_
// CHECK: [[WRITEBACK:%.*]] = alloc_stack $@sil_unmanaged C
// CHECK: [[OWNED:%.*]] = load [[PB]]
// CHECK: [[UNOWNED:%.*]] = ref_to_unmanaged [[OWNED]]
// CHECK: store [[UNOWNED]] to [[WRITEBACK]]
// CHECK: [[POINTER:%.*]] = address_to_pointer [[WRITEBACK]]
// CHECK: [[CONVERT:%.*]] = function_ref @_TFs30_convertInOutToPointerArgument
// CHECK: apply [[CONVERT]]<AutoreleasingUnsafeMutablePointer<C>>({{%.*}}, [[POINTER]])
// CHECK: apply [[TAKES_PLUS_ZERO]]
// CHECK: [[UNOWNED_OUT:%.*]] = load [[WRITEBACK]]
// CHECK: [[OWNED_OUT:%.*]] = unmanaged_to_ref [[UNOWNED_OUT]]
// CHECK: retain_value [[OWNED_OUT]]
// CHECK: assign [[OWNED_OUT]] to [[PB]]
var cq: C? = C()
takesPlusZeroOptionalPointer(&cq)
}
// Check that pointer types don't bridge anymore.
@objc class ObjCMethodBridging : NSObject {
// CHECK-LABEL: sil hidden [thunk] @_TToFC18pointer_conversion18ObjCMethodBridging11pointerArgs{{.*}} : $@convention(objc_method) (UnsafeMutablePointer<Int>, UnsafePointer<Int>, AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>, ObjCMethodBridging)
@objc func pointerArgs(x: UnsafeMutablePointer<Int>,
y: UnsafePointer<Int>,
z: AutoreleasingUnsafeMutablePointer<ObjCMethodBridging>) {}
}
// rdar://problem/21505805
// CHECK-LABEL: sil hidden @_TF18pointer_conversion22functionInoutToPointerFT_T_
func functionInoutToPointer() {
// CHECK: [[BOX:%.*]] = alloc_box $@callee_owned () -> ()
var f: () -> () = {}
// CHECK: [[REABSTRACT_BUF:%.*]] = alloc_stack $@callee_owned (@out (), @in ()) -> ()
// CHECK: address_to_pointer [[REABSTRACT_BUF]]
takesMutableVoidPointer(&f)
}
| apache-2.0 | 2fc7599fd7e2caeb8704fd925acd1162 | 48.03125 | 254 | 0.671765 | 3.988307 | false | false | false | false |
frootloops/swift | test/Reflection/typeref_decoding.swift | 1 | 26756 | // REQUIRES: no_asan
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -o %t/libTypesToReflect.%target-dylib-extension
// RUN: %target-swift-reflection-dump -binary-filename %t/libTypesToReflect.%target-dylib-extension | %FileCheck %s
// CHECK: FIELDS:
// CHECK: =======
// CHECK: TypesToReflect.Box
// CHECK: ------------------
// CHECK: item: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: anEnum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (variadic
// CHECK: (struct TypesToReflect.S))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (inout
// CHECK: (class TypesToReflect.C))
// CHECK: (inout
// CHECK: (struct Swift.Int))
// CHECK: (result
// CHECK: (tuple))
// CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (shared
// CHECK: (class TypesToReflect.C))
// CHECK: (result
// CHECK: (tuple))
// CHECK: TypesToReflect.S.NestedS
// CHECK: ------------------------
// CHECK: aField: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: TypesToReflect.S
// CHECK: ----------------
// CHECK: aClass: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (struct TypesToReflect.S))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (enum TypesToReflect.E))
// CHECK: (struct Swift.Int))
// CHECK: aMetatype: TypesToReflect.C.Type
// CHECK: (metatype
// CHECK: (class TypesToReflect.C))
// CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (struct Swift.Int))
// CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> ()
// CHECK: (function convention=thin
// CHECK: (tuple))
// CHECK: aFunctionWithCRepresentation: @convention(c) () -> ()
// CHECK: (function convention=c
// CHECK: (tuple))
// CHECK: TypesToReflect.E
// CHECK: ----------------
// CHECK: Class: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: Struct: TypesToReflect.S
// CHECK: (struct TypesToReflect.S)
// CHECK: Enum: TypesToReflect.E
// CHECK: (enum TypesToReflect.E)
// CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> ()
// CHECK: (function
// CHECK: (parameters
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int)
// CHECK: (result
// CHECK: (tuple))
// CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (struct Swift.Int))
// CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int)
// CHECK: (tuple
// CHECK: (class TypesToReflect.C)
// CHECK: (struct TypesToReflect.S)
// CHECK: (enum TypesToReflect.E)
// CHECK: (struct Swift.Int))
// CHECK: NestedStruct: TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S.NestedS
// CHECK: (struct TypesToReflect.S))
// CHECK: Metatype
// CHECK: EmptyCase
// CHECK: TypesToReflect.References
// CHECK: -------------------------
// CHECK: strongRef: TypesToReflect.C
// CHECK: (class TypesToReflect.C)
// CHECK: weakRef: weak Swift.Optional<TypesToReflect.C>
// CHECK: (weak_storage
// CHECK: (bound_generic_enum Swift.Optional
// CHECK: (class TypesToReflect.C)))
// CHECK: unownedRef: unowned TypesToReflect.C
// CHECK: (unowned_storage
// CHECK: (class TypesToReflect.C))
// CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C
// CHECK: (unmanaged_storage
// CHECK: (class TypesToReflect.C))
// CHECK: TypesToReflect.C1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: dependentMember: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.C2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.C3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: anEnum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.C4
// CHECK: -----------------
// CHECK: TypesToReflect.S1
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: TypesToReflect.S2
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: TypesToReflect.S3
// CHECK: -----------------
// CHECK: aClass: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>>
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (function
// CHECK: (parameters
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (struct Swift.Int))))
// CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (bound_generic_class TypesToReflect.Box
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (struct Swift.Int))
// CHECK: primaryArchetype: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: dependentMember1: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: dependentMember2: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.S4
// CHECK: -----------------
// CHECK: TypesToReflect.E1
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C1<A>
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S1<A>
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E1<A>
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Int: Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: Function: (A) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S1
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: Metatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E2
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C2<A>
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S2<A>
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E2<A>
// CHECK: (bound_generic_enum TypesToReflect.E2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S2
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberInner: A.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (generic_type_parameter depth=0 index=0) member=Inner)
// CHECK: ExistentialMetatype: A.Type
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: TypesToReflect.E3
// CHECK: -----------------
// CHECK: Class: TypesToReflect.C3<A>
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Struct: TypesToReflect.S3<A>
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Enum: TypesToReflect.E3<A>
// CHECK: (bound_generic_enum TypesToReflect.E3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A>
// CHECK: (function
// CHECK: (parameters
// CHECK: (metatype
// CHECK: (metatype
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: (result
// CHECK: (bound_generic_enum TypesToReflect.E1
// CHECK: (generic_type_parameter depth=0 index=0)))
// CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int)
// CHECK: (tuple
// CHECK: (bound_generic_class TypesToReflect.C3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (bound_generic_struct TypesToReflect.S3
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: (struct Swift.Int))
// CHECK: Primary: A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: DependentMemberOuter: A.Outer
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer)
// CHECK: DependentMemberInner: A.Outer.Inner
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P1)
// CHECK: (dependent_member
// CHECK: (protocol TypesToReflect.P2)
// CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner)
// CHECK: TypesToReflect.E4
// CHECK: -----------------
// CHECK: TypesToReflect.P1
// CHECK: -----------------
// CHECK: TypesToReflect.P2
// CHECK: -----------------
// CHECK: TypesToReflect.P3
// CHECK: -----------------
// CHECK: TypesToReflect.P4
// CHECK: -----------------
// CHECK: TypesToReflect.ClassBoundP
// CHECK: --------------------------
// CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}})
// CHECK: -------------------------------------------------------------------------
// CHECK: TypesToReflect.HasFileprivateProtocol
// CHECK: -------------------------------------
// CHECK: x: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}})
// CHECK: (protocol TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}))
// CHECK: ASSOCIATED TYPES:
// CHECK: =================
// CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.C4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.S4 : TypesToReflect.P2
// CHECK: typealias Outer = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P1
// CHECK: typealias Inner = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P2
// CHECK: typealias Outer = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.E4 : TypesToReflect.P3
// CHECK: typealias First = A
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: typealias Second = B
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: - TypesToReflect.S : TypesToReflect.P4
// CHECK: typealias Result = Swift.Int
// CHECK: (struct Swift.Int)
// CHECK: BUILTIN TYPES:
// CHECK: ==============
// CHECK: CAPTURE DESCRIPTORS:
// CHECK: ====================
// CHECK: - Capture types:
// CHECK: (sil_box
// CHECK: (generic_type_parameter depth=0 index=0))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (closure_binding index=1)
// CHECK: - Capture types:
// CHECK: (struct Swift.Int)
// CHECK: - Metadata sources:
// CHECK: - Capture types:
// CHECK: (bound_generic_class TypesToReflect.C1
// CHECK: (generic_type_parameter depth=0 index=1))
// CHECK: - Metadata sources:
// CHECK: (generic_type_parameter depth=0 index=0)
// CHECK: (closure_binding index=0)
// CHECK: (generic_type_parameter depth=0 index=1)
// CHECK: (generic_argument index=0
// CHECK: (reference_capture index=0))
| apache-2.0 | 949a2a00d148a2d2146a4f1f8b992769 | 35.010767 | 285 | 0.662393 | 3.377856 | false | false | false | false |
Floater-ping/DYDemo | DYDemo/DYDemo/Classes/Tools/Common.swift | 1 | 441 | //
// Common.swift
// DYDemo
//
// Created by ZYP-MAC on 2017/8/2.
// Copyright © 2017年 ZYP-MAC. All rights reserved.
//
import UIKit
/// 电池栏高度
let pStatusBarH : CGFloat = 20
/// 导航条高度
let pNavigationBarH : CGFloat = 44
/// tabBar高度
let pTabBarH : CGFloat = 44
/// 屏幕宽度
let pScreenWidth : CGFloat = UIScreen.main.bounds.width
/// 屏幕高度
let pScreenHeight : CGFloat = UIScreen.main.bounds.height
| mit | 81accda57212aecc83444a171d72fc5e | 19.947368 | 57 | 0.693467 | 3.061538 | false | false | false | false |
garricn/CopyPaste | CopyPaste/DebugFlow.swift | 1 | 3336 | //
// DebugFlow.swift
// CopyPaste
//
// Created by Garric Nahapetian on 4/1/18.
// Copyright © 2018 SwiftCoders. All rights reserved.
//
import UIKit
public final class DebugFlow {
lazy var itemsContext: DataContext<[Item]> = AppContext.shared.itemsContext
lazy var defaultsContext: DataContext<Defaults> = AppContext.shared.defaultsContext
private var didGetItems: (([Item]) -> Void)?
public func start(presenter: UIViewController) {
let alert = UIAlertController(title: "DEBUG", message: nil, preferredStyle: .actionSheet)
let dataTitle = "Load"
let dataHandler: (UIAlertAction) -> Void = { _ in self.load() }
let dataAction = UIAlertAction(title: dataTitle, style: .destructive, handler: dataHandler)
dataAction.accessibilityLabel = "resetData"
alert.addAction(dataAction)
let defaultsTitle = "Reset"
let defaultsHandler: (UIAlertAction) -> Void = { _ in self.presentReset(presenter: presenter) }
let defaultsAction = UIAlertAction(title: defaultsTitle, style: .destructive, handler: defaultsHandler)
defaultsAction.accessibilityLabel = "resetDefaults"
alert.addAction(defaultsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
cancelAction.accessibilityLabel = "cancel"
alert.addAction(cancelAction)
presenter.present(alert, animated: true, completion: nil)
}
public func onGet(perform action: @escaping ([Item]) -> Void) {
didGetItems = action
}
private func load() {
let url = Bundle.main.url(forResource: "sampleItems", withExtension: "json")!
let data = try! Data(contentsOf: url)
let items = try! JSONDecoder().decode([Item].self, from: data)
didGetItems?(items)
}
private func presentReset(presenter: UIViewController) {
let alert = UIAlertController(title: "RESET", message: nil, preferredStyle: .actionSheet)
let dataTitle = "Data"
let dataHandler: (UIAlertAction) -> Void = { _ in self.itemsContext.reset() }
let dataAction = UIAlertAction(title: dataTitle, style: .destructive, handler: dataHandler)
dataAction.accessibilityLabel = "resetData"
alert.addAction(dataAction)
let defaultsTitle = "Defaults"
let defaultsHandler: (UIAlertAction) -> Void = { _ in self.defaultsContext.reset() }
let defaultsAction = UIAlertAction(title: defaultsTitle, style: .destructive, handler: defaultsHandler)
defaultsAction.accessibilityLabel = "resetDefaults"
alert.addAction(defaultsAction)
let bothTitle = "Both"
let bothHandler: (UIAlertAction) -> Void = { _ in self.itemsContext.reset(); self.defaultsContext.reset() }
let bothAction = UIAlertAction(title: bothTitle, style: .destructive, handler: bothHandler)
bothAction.accessibilityLabel = "resetDataAndDefaults"
alert.addAction(bothAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
cancelAction.accessibilityLabel = "cancel"
alert.addAction(cancelAction)
presenter.present(alert, animated: true, completion: nil)
}
}
| mit | 36da1208498a636b561ec965baf79091 | 41.75641 | 116 | 0.662969 | 4.619114 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Extensions/CLPlacemark+Formatting.swift | 2 | 708 | import UIKit
import CoreLocation
extension CLPlacemark {
/// Returns a single string with the address information of a placemark formatted
@objc func formattedAddress() -> String? {
var address = ""
if let number = subThoroughfare {
address.append(number + " ")
}
if let street = thoroughfare {
address.append(street)
}
address.append("\n")
if let city = locality {
address.append(city)
}
if let zipCode = postalCode {
address.append(", " + zipCode)
}
if let country = country {
address.append(", " + country)
}
return address
}
}
| gpl-2.0 | e45d79187ada0e6348da50112055bd56 | 26.230769 | 85 | 0.542373 | 4.985915 | false | false | false | false |
imjerrybao/SKTUtils | Examples/Playground/MyPlayground.playground/Contents.swift | 2 | 370 | // To run this playground, first build the project (Command-B).
// To see the output, open the Assistant Editor (Option-Command-Enter).
import SKTUtils
let pt1 = CGPoint(x: 10, y: 20)
let pt2 = CGPoint(x: -5, y: 0)
let pt3 = pt1 + pt2
let pt4 = pt3 * CGFloat(100)
println("Point has length \(pt4.length())")
let pt5 = pt4.normalized()
let dist = pt1.distanceTo(pt2)
| mit | b8812c385e81917b60893a65c144dc30 | 25.428571 | 71 | 0.686486 | 2.868217 | false | false | false | false |
cvillaseca/CVLoggerSwift | CVLoggerSwift/Classes/CVButton.swift | 1 | 3040 | //
// CVButton.swift
// Pods
//
// Created by Cristian Villaseca on 5/5/16.
//
//
import UIKit
class CVButton: UIButton {
let buttonMargin:CGFloat = 5.0
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() -> Void {
self.frame = CGRectMake(50, 70, 40, 40);
self.backgroundColor = UIColor(white: 0.6, alpha: 0.7)
self.showsTouchWhenHighlighted = true
setTransparentWithAnimation();
}
override func drawRect(rect: CGRect) {
self.layer.cornerRadius = self.frame.size.width / 2;
self.layer.masksToBounds = true;
}
//MARK: touch events
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.backgroundColor = UIColor(white: 0.6, alpha: 0.7)
super.touchesBegan(touches, withEvent: event)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let touch = event?.allTouches()?.first
let window = UIApplication.sharedApplication().keyWindow
let touchLocation = touch?.locationInView(window)
self.center = touchLocation!
self.touchesCancelled(touches, withEvent: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
var frame = self.frame;
let screenLimit = UIScreen.mainScreen().bounds;
var change = false;
if (self.frame.origin.x < buttonMargin) {
change = true;
frame.origin.x = buttonMargin;
}
if (self.frame.origin.y < buttonMargin) {
change = true;
frame.origin.y = buttonMargin;
}
if (self.frame.origin.x + self.frame.size.width > screenLimit.size.width - buttonMargin ) {
change = true;
frame.origin.x = screenLimit.size.width - buttonMargin - frame.size.width ;
}
if (self.frame.origin.y + self.frame.size.height > screenLimit.size.height - buttonMargin ) {
change = true;
frame.origin.y = screenLimit.size.height - buttonMargin - frame.size.height ;
}
if (change) {
UIView.animateWithDuration(0.6, animations: {
self.frame = frame;
})
}
setTransparentWithAnimation();
super.touchesEnded(touches, withEvent: event)
}
//mark: private methods
private func setTransparentWithAnimation() {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(4 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
UIView.animateWithDuration(0.3, animations: {
self.backgroundColor = UIColor(white: 0.8, alpha: 0.4)
})
}
}
}
| mit | 5c4155a5bc398fbc6877f17873bec233 | 28.514563 | 101 | 0.577303 | 4.477172 | false | false | false | false |
stephentyrone/swift | test/decl/enum/enumtest.swift | 7 | 20196 | // RUN: %target-typecheck-verify-swift
//===----------------------------------------------------------------------===//
// Tests for various simple enum constructs
//===----------------------------------------------------------------------===//
public enum unionSearchFlags {
case none
case backwards
case anchored
init() { self = .none }
}
func test1() -> unionSearchFlags {
let _ : unionSearchFlags
var b = unionSearchFlags.none
b = unionSearchFlags.anchored
_ = b
return unionSearchFlags.backwards
}
func test1a() -> unionSearchFlags {
var _ : unionSearchFlags
var b : unionSearchFlags = .none
b = .anchored
_ = b
// ForwardIndex use of MaybeInt.
_ = MaybeInt.none
return .backwards
}
func test1b(_ b : Bool) {
_ = 123
_ = .description == 1 // expected-error {{cannot infer contextual base in reference to member 'description'}}
}
enum MaybeInt {
case none
case some(Int) // expected-note {{'some' declared here}}
init(_ i: Int) { self = MaybeInt.some(i) }
}
func test2(_ a: Int, _ b: Int, _ c: MaybeInt) {
_ = MaybeInt.some(4)
_ = MaybeInt.some
_ = MaybeInt.some(b)
test2(1, 2, .none)
}
enum ZeroOneTwoThree {
case Zero
case One(Int)
case Two(Int, Int)
case Three(Int,Int,Int)
case Unknown(MaybeInt, MaybeInt, MaybeInt)
init (_ i: Int) { self = .One(i) }
init (_ i: Int, _ j: Int, _ k: Int) { self = .Three(i, j, k) }
init (_ i: MaybeInt, _ j: MaybeInt, _ k: MaybeInt) { self = .Unknown(i, j, k) }
}
func test3(_ a: ZeroOneTwoThree) {
_ = ZeroOneTwoThree.Three(1,2,3)
_ = ZeroOneTwoThree.Unknown(
MaybeInt.none, MaybeInt.some(4), MaybeInt.some(32))
_ = ZeroOneTwoThree(MaybeInt.none, MaybeInt(4), MaybeInt(32))
var _ : Int =
ZeroOneTwoThree.Zero // expected-error {{cannot convert value of type 'ZeroOneTwoThree' to specified type 'Int'}}
// expected-warning @+1 {{unused}}
test3 ZeroOneTwoThree.Zero // expected-error {{expression resolves to an unused function}} expected-error{{consecutive statements}} {{8-8=;}}
test3 (ZeroOneTwoThree.Zero)
test3(ZeroOneTwoThree.Zero)
test3 // expected-error {{expression resolves to an unused function}}
// expected-warning @+1 {{unused}}
(ZeroOneTwoThree.Zero)
var _ : ZeroOneTwoThree = .One(4)
var _ : (Int,Int) -> ZeroOneTwoThree = .Two // expected-error{{type '(Int, Int) -> ZeroOneTwoThree' has no member 'Two'}}
var _ : Int = .Two // expected-error{{type 'Int' has no member 'Two'}}
var _ : MaybeInt = 0 > 3 ? .none : .soma(3) // expected-error {{type 'MaybeInt' has no member 'soma'; did you mean 'some'?}}
}
func test3a(_ a: ZeroOneTwoThree) {
var e : ZeroOneTwoThree = (.Three(1, 2, 3))
var f = ZeroOneTwoThree.Unknown(.none, .some(4), .some(32))
var g = .none // expected-error {{reference to member 'none' cannot be resolved without a contextual type}}
// Overload resolution can resolve this to the right constructor.
var h = ZeroOneTwoThree(1)
var i = 0 > 3 ? .none : .some(3) // expected-error {{cannot infer contextual base in reference to member 'none'}}
// expected-error@-1 {{cannot infer contextual base in reference to member 'some'}}
test3a; // expected-error {{unused function}}
.Zero // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}}
test3a // expected-error {{unused function}}
(.Zero) // expected-error {{reference to member 'Zero' cannot be resolved without a contextual type}}
test3a(.Zero)
}
struct CGPoint { var x : Int, y : Int }
typealias OtherPoint = (x : Int, y : Int)
func test4() {
var a : CGPoint
// Note: we reject the following because it conflicts with the current
// "init" hack.
var b = CGPoint.CGPoint(1, 2) // expected-error {{type 'CGPoint' has no member 'CGPoint'}}
var c = CGPoint(x: 2, y : 1) // Using injected name.
var e = CGPoint.x // expected-error {{member 'x' cannot be used on type 'CGPoint'}}
var f = OtherPoint.x // expected-error {{type 'OtherPoint' (aka '(x: Int, y: Int)') has no member 'x'}}
}
struct CGSize { var width : Int, height : Int }
extension CGSize {
func area() -> Int {
return width*self.height
}
func area_wrapper() -> Int {
return area()
}
}
struct CGRect {
var origin : CGPoint,
size : CGSize
func area() -> Int {
return self.size.area()
}
}
func area(_ r: CGRect) -> Int {
return r.size.area()
}
extension CGRect {
func search(_ x: Int) -> CGSize {}
func bad_search(_: Int) -> CGSize {}
}
func test5(_ myorigin: CGPoint) {
let x1 = CGRect(origin: myorigin, size: CGSize(width: 42, height: 123))
let x2 = x1
_ = 4+5
// Dot syntax.
_ = x2.origin.x
_ = x1.size.area()
_ = (r : x1.size).r.area() // expected-error {{cannot create a single-element tuple with an element label}}
_ = x1.size.area()
_ = (r : x1.size).r.area() // expected-error {{cannot create a single-element tuple with an element label}}
_ = x1.area
_ = x1.search(42)
_ = x1.search(42).width
// TODO: something like this (name binding on the LHS):
// var (CGSize(width, height)) = CGSize(1,2)
// TODO: something like this, how do we get it in scope in the {} block?
//if (var some(x) = somemaybeint) { ... }
}
struct StructTest1 {
var a : Int, c, b : Int
typealias ElementType = Int
}
enum UnionTest1 {
case x
case y(Int)
func foo() {}
init() { self = .x }
}
extension UnionTest1 {
func food() {}
func bar() {}
// Type method.
static func baz() {}
}
struct EmptyStruct {
func foo() {}
}
func f() {
let a : UnionTest1
a.bar()
UnionTest1.baz() // dot syntax access to a static method.
// Test that we can get the "address of a member".
var _ : () -> () = UnionTest1.baz
var _ : (UnionTest1) -> () -> () = UnionTest1.bar
}
func union_error(_ a: ZeroOneTwoThree) {
var _ : ZeroOneTwoThree = .Zero(1) // expected-error {{enum case 'Zero' has no associated values}}
var _ : ZeroOneTwoThree = .Zero() // expected-error {{enum case 'Zero' has no associated values}} {{34-36=}}
var _ : ZeroOneTwoThree = .One // expected-error {{member 'One' expects argument of type 'Int'}}
var _ : ZeroOneTwoThree = .foo // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}}
var _ : ZeroOneTwoThree = .foo() // expected-error {{type 'ZeroOneTwoThree' has no member 'foo'}}
}
func local_struct() {
struct s { func y() {} }
}
//===----------------------------------------------------------------------===//
// A silly units example showing "user defined literals".
//===----------------------------------------------------------------------===//
struct distance { var v : Int }
func - (lhs: distance, rhs: distance) -> distance {}
extension Int {
func km() -> enumtest.distance {}
func cm() -> enumtest.distance {}
}
func units(_ x: Int) -> distance {
return x.km() - 4.cm() - 42.km()
}
var %% : distance -> distance // expected-error {{expected pattern}}
func badTupleElement() {
typealias X = (x : Int, y : Int)
var y = X.y // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'y'}}
var z = X.z // expected-error{{type 'X' (aka '(x: Int, y: Int)') has no member 'z'}}
}
enum Direction {
case North(distance: Int)
case NorthEast(distanceNorth: Int, distanceEast: Int)
}
func testDirection() {
var dir: Direction = .North(distance: 5)
dir = .NorthEast(distanceNorth: 5, distanceEast: 7)
var i: Int
switch dir {
case .North(let x):
i = x
break
case .NorthEast(let x): // expected-warning {{enum case 'NorthEast' has 2 associated values; matching them as a tuple is deprecated}}
// expected-note@-14 {{'NorthEast(distanceNorth:distanceEast:)' declared here}}
i = x.distanceEast
break
}
_ = i
}
enum NestedSingleElementTuple {
case Case(x: (y: Int)) // expected-error{{cannot create a single-element tuple with an element label}} {{17-20=}}
}
enum SimpleEnum {
case X, Y
}
func testSimpleEnum() {
let _ : SimpleEnum = .X
let _ : SimpleEnum = (.X)
let _ : SimpleEnum=.X // expected-error {{'=' must have consistent whitespace on both sides}}
}
enum SR510: String {
case Thing = "thing"
case Bob = {"test"} // expected-error {{raw value for enum case must be a literal}}
}
// <rdar://problem/21269142> Diagnostic should say why enum has no .rawValue member
enum E21269142 { // expected-note {{did you mean to specify a raw type on the enum declaration?}}
case Foo
}
print(E21269142.Foo.rawValue) // expected-error {{value of type 'E21269142' has no member 'rawValue'}}
// Check that typo correction does something sensible with synthesized members.
enum SyntheticMember { // expected-note {{property 'hashValue' is implicitly declared}}
case Foo
}
func useSynthesizedMember() {
print(SyntheticMember.Foo.hasValue) // expected-error {{value of type 'SyntheticMember' has no member 'hasValue'; did you mean 'hashValue'?}}
}
// Non-materializable argument type
enum Lens<T> {
case foo(inout T) // expected-error {{'inout' may only be used on parameters}}
case bar(inout T, Int) // expected-error {{'inout' may only be used on parameters}}
case baz((inout T) -> ()) // ok
case quux((inout T, inout T) -> ()) // ok
}
// In the long term, these should be legal, but we don't support them right
// now and we shouldn't pretend to.
// rdar://46684504
enum HasVariadic {
case variadic(x: Int...) // expected-error {{variadic enum cases are not supported}}
}
// SR-2176
enum Foo {
case bar
case none
}
let _: Foo? = .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{15-15=Optional}}
// expected-note@-2 {{use 'Foo.none' instead}} {{15-15=Foo}}
let _: Foo?? = .none // expected-warning {{assuming you mean 'Optional<Optional<Foo>>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{16-16=Optional}}
// expected-note@-2 {{use 'Foo.none' instead}} {{16-16=Foo}}
let _: Foo = .none // ok
let _: Foo = .bar // ok
let _: Foo? = .bar // ok
let _: Foo?? = .bar // ok
let _: Foo = Foo.bar // ok
let _: Foo = Foo.none // ok
let _: Foo? = Foo.none // ok
let _: Foo?? = Foo.none // ok
func baz(_: Foo?) {}
baz(.none) // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{5-5=Optional}}
// expected-note@-2 {{use 'Foo.none' instead}} {{5-5=Foo}}
let test: Foo? = .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{18-18=Optional}}
// expected-note@-2 {{use 'Foo.none' instead}} {{18-18=Foo}}
let answer = test == .none // expected-warning {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{22-22=Optional}}
// expected-note@-2 {{use 'Foo.none' instead}} {{22-22=Foo}}
enum Bar {
case baz
}
let _: Bar? = .none // ok
let _: Bar?? = .none // ok
let _: Bar? = .baz // ok
let _: Bar?? = .baz // ok
let _: Bar = .baz // ok
enum AnotherFoo {
case none(Any)
}
let _: AnotherFoo? = .none // ok
let _: AnotherFoo? = .none(0) // ok
struct FooStruct {
static let none = FooStruct()
static let one = FooStruct()
}
let _: FooStruct? = .none // expected-warning {{assuming you mean 'Optional<FooStruct>.none'; did you mean 'FooStruct.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{21-21=Optional}}
// expected-note@-2 {{use 'FooStruct.none' instead}} {{21-21=FooStruct}}
let _: FooStruct?? = .none // expected-warning {{assuming you mean 'Optional<Optional<FooStruct>>.none'; did you mean 'FooStruct.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{22-22=Optional}}
// expected-note@-2 {{use 'FooStruct.none' instead}} {{22-22=FooStruct}}
let _: FooStruct = .none // ok
let _: FooStruct = .one // ok
let _: FooStruct? = .one // ok
let _: FooStruct?? = .one // ok
struct NestedBazEnum {
enum Baz {
case one
case none
}
}
let _: NestedBazEnum.Baz? = .none // expected-warning {{assuming you mean 'Optional<NestedBazEnum.Baz>.none'; did you mean 'NestedBazEnum.Baz.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{29-29=Optional}}
// expected-note@-2 {{use 'NestedBazEnum.Baz.none' instead}} {{29-29=NestedBazEnum.Baz}}
let _: NestedBazEnum.Baz?? = .none // expected-warning {{assuming you mean 'Optional<Optional<NestedBazEnum.Baz>>.none'; did you mean 'NestedBazEnum.Baz.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{30-30=Optional}}
// expected-note@-2 {{use 'NestedBazEnum.Baz.none' instead}} {{30-30=NestedBazEnum.Baz}}
let _: NestedBazEnum.Baz = .none // ok
let _: NestedBazEnum.Baz = .one // ok
let _: NestedBazEnum.Baz? = .one // ok
let _: NestedBazEnum.Baz?? = .one // ok
struct NestedBazEnumGeneric {
enum Baz<T> {
case one
case none
}
}
let _: NestedBazEnumGeneric.Baz<Int>? = .none // expected-warning {{assuming you mean 'Optional<NestedBazEnumGeneric.Baz<Int>>.none'; did you mean 'NestedBazEnumGeneric.Baz<Int>.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{41-41=Optional}}
// expected-note@-2 {{use 'NestedBazEnumGeneric.Baz<Int>.none' instead}} {{41-41=NestedBazEnumGeneric.Baz<Int>}}
let _: NestedBazEnumGeneric.Baz<Int>?? = .none // expected-warning {{assuming you mean 'Optional<Optional<NestedBazEnumGeneric.Baz<Int>>>.none'; did you mean 'NestedBazEnumGeneric.Baz<Int>.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}} {{42-42=Optional}}
// expected-note@-2 {{use 'NestedBazEnumGeneric.Baz<Int>.none' instead}} {{42-42=NestedBazEnumGeneric.Baz<Int>}}
let _: NestedBazEnumGeneric.Baz<Int> = .none // ok
let _: NestedBazEnumGeneric.Baz<Int> = .one // ok
let _: NestedBazEnumGeneric.Baz<Int>? = .one // ok
let _: NestedBazEnumGeneric.Baz<Int>?? = .one // ok
class C {}
protocol P {}
enum E : C & P {}
// expected-error@-1 {{inheritance from class-constrained protocol composition type 'C & P'}}
// SR-11522
enum EnumWithStaticNone1 {
case a
static let none = 1
}
enum EnumWithStaticNone2 {
case a
static let none = EnumWithStaticNone2.a
}
enum EnumWithStaticNone3 {
case a
static let none = EnumWithStaticNone3.a
var none: EnumWithStaticNone3 { return .a }
}
enum EnumWithStaticNone4 {
case a
var none: EnumWithStaticNone4 { return .a }
static let none = EnumWithStaticNone4.a
}
enum EnumWithStaticFuncNone1 {
case a
static func none() -> Int { return 1 }
}
enum EnumWithStaticFuncNone2 {
case a
static func none() -> EnumWithStaticFuncNone2 { return .a }
}
/// Make sure we don't diagnose 'static let none = 1', but do diagnose 'static let none = TheEnum.anotherCase' ///
let _: EnumWithStaticNone1? = .none // Okay
let _: EnumWithStaticNone2? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone2>.none'; did you mean 'EnumWithStaticNone2.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}}
// expected-note@-2 {{use 'EnumWithStaticNone2.none' instead}}{{31-31=EnumWithStaticNone2}}
/// Make sure we diagnose if we have both static and instance 'none' member regardless of source order ///
let _: EnumWithStaticNone3? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone3>.none'; did you mean 'EnumWithStaticNone3.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}}
// expected-note@-2 {{use 'EnumWithStaticNone3.none' instead}}{{31-31=EnumWithStaticNone3}}
let _: EnumWithStaticNone4? = .none // expected-warning {{assuming you mean 'Optional<EnumWithStaticNone4>.none'; did you mean 'EnumWithStaticNone4.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{31-31=Optional}}
// expected-note@-2 {{use 'EnumWithStaticNone4.none' instead}}{{31-31=EnumWithStaticNone4}}
/// Make sure we don't diagnose 'static func none -> T' ///
let _: EnumWithStaticFuncNone1? = .none // Okay
let _: EnumWithStaticFuncNone2? = .none // Okay
/// Make sure we diagnose generic ones as well including conditional ones ///
enum GenericEnumWithStaticNone<T> {
case a
static var none: GenericEnumWithStaticNone<Int> { .a }
}
let _: GenericEnumWithStaticNone<Int>? = .none // expected-warning {{assuming you mean 'Optional<GenericEnumWithStaticNone<Int>>.none'; did you mean 'GenericEnumWithStaticNone<Int>.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{42-42=Optional}}
// expected-note@-2 {{use 'GenericEnumWithStaticNone<Int>.none' instead}}{{42-42=GenericEnumWithStaticNone<Int>}}
let _: GenericEnumWithStaticNone<String>? = .none // Okay
let _: GenericEnumWithStaticNone? = .none // FIXME(SR-11535): This should be diagnosed
enum GenericEnumWithoutNone<T> {
case a
}
extension GenericEnumWithoutNone where T == Int {
static var none: GenericEnumWithoutNone<Int> { .a }
}
let _: GenericEnumWithoutNone<Int>? = .none // expected-warning {{assuming you mean 'Optional<GenericEnumWithoutNone<Int>>.none'; did you mean 'GenericEnumWithoutNone<Int>.none' instead?}}
// expected-note@-1 {{explicitly specify 'Optional' to silence this warning}}{{39-39=Optional}}
// expected-note@-2 {{use 'GenericEnumWithoutNone<Int>.none' instead}}{{39-39=GenericEnumWithoutNone<Int>}}
let _: GenericEnumWithoutNone<String>? = .none // Okay
// A couple of edge cases that shouldn't trigger the warning //
enum EnumWithStructNone {
case bar
struct none {}
}
enum EnumWithTypealiasNone {
case bar
typealias none = EnumWithTypealiasNone
}
enum EnumWithBothStructAndComputedNone {
case bar
struct none {}
var none: EnumWithBothStructAndComputedNone { . bar }
}
enum EnumWithBothTypealiasAndComputedNone {
case bar
typealias none = EnumWithBothTypealiasAndComputedNone
var none: EnumWithBothTypealiasAndComputedNone { . bar }
}
let _: EnumWithStructNone? = .none // Okay
let _: EnumWithTypealiasNone? = .none // Okay
let _: EnumWithBothStructAndComputedNone? = .none // Okay
let _: EnumWithBothTypealiasAndComputedNone? = .none // Okay
// SR-12063
let foo1: Foo? = Foo.none
let foo2: Foo?? = Foo.none
switch foo1 {
case .none: break
// expected-warning@-1 {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-2 {{use 'nil' to silence this warning}}{{8-13=nil}}
// expected-note@-3 {{use 'none?' instead}}{{9-13=none?}}
case .bar: break
default: break
}
switch foo2 {
case .none: break
// expected-warning@-1 {{assuming you mean 'Optional<Optional<Foo>>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-2 {{use 'nil' to silence this warning}}{{8-13=nil}}
// expected-note@-3 {{use 'none??' instead}}{{9-13=none??}}
case .bar: break
default: break
}
if case .none = foo1 {}
// expected-warning@-1 {{assuming you mean 'Optional<Foo>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-2 {{use 'nil' to silence this warning}}{{9-14=nil}}
// expected-note@-3 {{use 'none?' instead}}{{10-14=none?}}
if case .none = foo2 {}
// expected-warning@-1 {{assuming you mean 'Optional<Optional<Foo>>.none'; did you mean 'Foo.none' instead?}}
// expected-note@-2 {{use 'nil' to silence this warning}}{{9-14=nil}}
// expected-note@-3 {{use 'none??' instead}}{{10-14=none??}}
switch foo1 {
case nil: break // Okay
case .bar: break
default: break
}
switch foo1 {
case .none?: break // Okay
case .bar: break
default: break
}
switch foo2 {
case nil: break // Okay
case .bar: break
default: break
}
switch foo2 {
case .none??: break // Okay
case .bar: break
default: break
}
if case nil = foo1 {} // Okay
if case .none? = foo1 {} // Okay
if case nil = foo2 {} // Okay
if case .none?? = foo2 {} // Okay
| apache-2.0 | 46a18b0a9b52880dc10a5e15e5da6ee6 | 31.679612 | 205 | 0.66023 | 3.629111 | false | true | false | false |
staticdreams/IJReachability | IJReachability/IJReachability/IJReachability.swift | 1 | 2706 | //
// IJReachability.swift
// IJReachability
//
// Created by Isuru Nanayakkara on 1/14/15.
// Copyright (c) 2015 Appex. All rights reserved.
//
import Foundation
import SystemConfiguration
public enum IJReachabilityType {
case WWAN,
WiFi,
NotConnected
}
public class IJReachability {
/**
:see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
*/
public class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
public class func isConnectedToNetworkOfType() -> IJReachabilityType {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
return .NotConnected
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) != 0
//let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0
if(isReachable && isWWAN){
return .WWAN
}
if(isReachable && !isWWAN){
return .WiFi
}
return .NotConnected
//let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
//return (isReachable && !needsConnection) ? true : false
}
}
| mit | c426b1d450ffcc0df367af3f2d2fbf2c | 34.605263 | 143 | 0.628973 | 4.609881 | false | false | false | false |
Vanlol/MyYDW | SwiftCocoa/Resource/TabbarC/View/CustomTabBar.swift | 1 | 3711 | //
// CustomTabBar.swift
// SwiftCocoa
//
// Created by admin on 2017/7/3.
// Copyright © 2017年 admin. All rights reserved.
//
import UIKit
class CustomTabBar: UITabBar {
fileprivate lazy var centerBtn:UIButton = {
let btn = UIButton()
btn.setBackgroundImage(UIImage(named: "tabBar_publish_icon"), for: .normal)
btn.setBackgroundImage(UIImage(named: "tabBar_publish_click_icon"), for: .highlighted)
btn.bounds.size = (btn.currentBackgroundImage?.size)!
btn.addTarget(self, action: #selector(centerBtnClick), for: .touchUpInside)
return btn
}()
/**
* 中间按钮点击事件
*/
func centerBtnClick() {
Print.dlog("centerBtnClick")
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(centerBtn)
testTwo()
setupTabbarItem()
}
/**
* "toobar"图片上带有阴影
* "toobar"图片的高度无要求
*/
fileprivate func testOne(){
backgroundImage = UIImage()
shadowImage = UIImage()
let imgVi = UIImageView(image: UIImage(named: "toobar"))
imgVi.frame = CGRect(x: 0, y: -5, width: C.SCREEN_WIDTH, height: 54)
insertSubview(imgVi, at: 0)
}
/**
* "newtabbar"图片上没有阴影
* "newtabbar"图片的高度必须为"49"
*/
fileprivate func testTwo(){
backgroundImage = UIImage(named: "tabbar-light")
shadowImage = UIImage()
layer.shadowColor = 0xaaaaaa.HexColor.cgColor
layer.shadowOffset = CGSize.zero
layer.shadowRadius = 2
layer.shadowOpacity = 1
}
/**
* 设置背景颜色
*/
fileprivate func testThree() {
barTintColor = 0x0.HexColor
shadowImage = UIImage()
}
/**
* 设置tabbarItem的字体大小与颜色
*/
fileprivate func setupTabbarItem() {
var normalAttrs = [String:Any]()
normalAttrs[NSForegroundColorAttributeName] = 0x8190a7.HexColor
normalAttrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 12)
var selectAttrs = [String:Any]()
selectAttrs[NSForegroundColorAttributeName] = 0xffa623.HexColor
selectAttrs[NSFontAttributeName] = UIFont.systemFont(ofSize: 12)
let item = UITabBarItem.appearance()
item.setTitleTextAttributes(normalAttrs, for: .normal)
item.setTitleTextAttributes(selectAttrs, for: .selected)
}
override func layoutSubviews() {
super.layoutSubviews()
layoutItems()
layoutCenterButton()
}
/**
* 重新布局新添加按钮
*/
fileprivate func layoutCenterButton(){
let width = bounds.size.width
let height = bounds.size.height
centerBtn.center = CGPoint(x: width * 0.5, y: height * 0.5)
let y:CGFloat = 0
let w = width / 5
let h = height
var index = 0
for btn in subviews {
if (!btn.isKind(of: UIControl.classForCoder()) || btn == centerBtn) {} else {
let count = index > 1 ? (index + 1):index
let x = w * CGFloat(count)
btn.frame = CGRect(x: x, y: y, width: w, height: h)
index += 1
}
}
}
/**
* 重新布局Item的距离和位置
*/
fileprivate func layoutItems(){
for item in items! {
item.imageInsets = UIEdgeInsets(top: -3, left: 0, bottom: 3, right: 0)
item.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -4)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | d0dc5cffd676545262d14f99580a96cb | 27.047244 | 94 | 0.585626 | 4.230404 | false | false | false | false |
vishw3/IOSChart-IOS-7.0-Support | VisChart/Classes/Animation/ChartAnimationEasing.swift | 1 | 13869 | //
// ChartAnimationUtils.swift
// Charts
//
// Created by Daniel Cohen Gindi on 23/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
@objc
public enum ChartEasingOption: Int
{
case Linear
case EaseInQuad
case EaseOutQuad
case EaseInOutQuad
case EaseInCubic
case EaseOutCubic
case EaseInOutCubic
case EaseInQuart
case EaseOutQuart
case EaseInOutQuart
case EaseInQuint
case EaseOutQuint
case EaseInOutQuint
case EaseInSine
case EaseOutSine
case EaseInOutSine
case EaseInExpo
case EaseOutExpo
case EaseInOutExpo
case EaseInCirc
case EaseOutCirc
case EaseInOutCirc
case EaseInElastic
case EaseOutElastic
case EaseInOutElastic
case EaseInBack
case EaseOutBack
case EaseInOutBack
case EaseInBounce
case EaseOutBounce
case EaseInOutBounce
}
public typealias ChartEasingFunctionBlock = ((elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat);
internal func easingFunctionFromOption(easing: ChartEasingOption) -> ChartEasingFunctionBlock
{
switch easing
{
case .Linear:
return EasingFunctions.Linear;
case .EaseInQuad:
return EasingFunctions.EaseInQuad;
case .EaseOutQuad:
return EasingFunctions.EaseOutQuad;
case .EaseInOutQuad:
return EasingFunctions.EaseInOutQuad;
case .EaseInCubic:
return EasingFunctions.EaseInCubic;
case .EaseOutCubic:
return EasingFunctions.EaseOutCubic;
case .EaseInOutCubic:
return EasingFunctions.EaseInOutCubic;
case .EaseInQuart:
return EasingFunctions.EaseInQuart;
case .EaseOutQuart:
return EasingFunctions.EaseOutQuart;
case .EaseInOutQuart:
return EasingFunctions.EaseInOutQuart;
case .EaseInQuint:
return EasingFunctions.EaseInQuint;
case .EaseOutQuint:
return EasingFunctions.EaseOutQuint;
case .EaseInOutQuint:
return EasingFunctions.EaseInOutQuint;
case .EaseInSine:
return EasingFunctions.EaseInSine;
case .EaseOutSine:
return EasingFunctions.EaseOutSine;
case .EaseInOutSine:
return EasingFunctions.EaseInOutSine;
case .EaseInExpo:
return EasingFunctions.EaseInExpo;
case .EaseOutExpo:
return EasingFunctions.EaseOutExpo;
case .EaseInOutExpo:
return EasingFunctions.EaseInOutExpo;
case .EaseInCirc:
return EasingFunctions.EaseInCirc;
case .EaseOutCirc:
return EasingFunctions.EaseOutCirc;
case .EaseInOutCirc:
return EasingFunctions.EaseInOutCirc;
case .EaseInElastic:
return EasingFunctions.EaseInElastic;
case .EaseOutElastic:
return EasingFunctions.EaseOutElastic;
case .EaseInOutElastic:
return EasingFunctions.EaseInOutElastic;
case .EaseInBack:
return EasingFunctions.EaseInBack;
case .EaseOutBack:
return EasingFunctions.EaseOutBack;
case .EaseInOutBack:
return EasingFunctions.EaseInOutBack;
case .EaseInBounce:
return EasingFunctions.EaseInBounce;
case .EaseOutBounce:
return EasingFunctions.EaseOutBounce;
case .EaseInOutBounce:
return EasingFunctions.EaseInOutBounce;
}
}
internal struct EasingFunctions
{
internal static let Linear = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in return CGFloat(elapsed / duration); };
internal static let EaseInQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position;
};
internal static let EaseOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return -position * (position - 2.0);
};
internal static let EaseInOutQuad = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position;
}
return -0.5 * ((--position) * (position - 2.0) - 1.0);
};
internal static let EaseInCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position;
};
internal static let EaseOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return (position * position * position + 1.0);
};
internal static let EaseInOutCubic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position;
}
position -= 2.0;
return 0.5 * (position * position * position + 2.0);
};
internal static let EaseInQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position * position;
};
internal static let EaseOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return -(position * position * position * position - 1.0);
};
internal static let EaseInOutQuart = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position * position;
}
position -= 2.0;
return -0.5 * (position * position * position * position - 2.0);
};
internal static let EaseInQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return position * position * position * position * position;
};
internal static let EaseOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return (position * position * position * position * position + 1.0);
};
internal static let EaseInOutQuint = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / (duration / 2.0));
if (position < 1.0)
{
return 0.5 * position * position * position * position * position;
}
else
{
position -= 2.0;
return 0.5 * (position * position * position * position * position + 2.0);
}
};
internal static let EaseInSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( -cos(position * M_PI_2) + 1.0 );
};
internal static let EaseOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( sin(position * M_PI_2) );
};
internal static let EaseInOutSine = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
return CGFloat( -0.5 * (cos(M_PI * position) - 1.0) );
};
internal static let EaseInExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return (elapsed == 0) ? 0.0 : CGFloat(pow(2.0, 10.0 * (elapsed / duration - 1.0)));
};
internal static let EaseOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return (elapsed == duration) ? 1.0 : (-CGFloat(pow(2.0, -10.0 * elapsed / duration)) + 1.0);
};
internal static let EaseInOutExpo = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0)
{
return 0.0;
}
if (elapsed == duration)
{
return 1.0;
}
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
return CGFloat( 0.5 * pow(2.0, 10.0 * (position - 1.0)) );
}
return CGFloat( 0.5 * (-pow(2.0, -10.0 * --position) + 2.0) );
};
internal static let EaseInCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
return -(CGFloat(sqrt(1.0 - position * position)) - 1.0);
};
internal static let EaseOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position = CGFloat(elapsed / duration);
position--;
return CGFloat( sqrt(1 - position * position) );
};
internal static let EaseInOutCirc = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
return CGFloat( -0.5 * (sqrt(1.0 - position * position) - 1.0) );
}
position -= 2.0;
return CGFloat( 0.5 * (sqrt(1.0 - position * position) + 1.0) );
};
internal static let EaseInElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / duration;
if (position == 1.0)
{
return 1.0;
}
var p = duration * 0.3;
var s = p / (2.0 * M_PI) * asin(1.0);
position -= 1.0;
return CGFloat( -(pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) );
};
internal static let EaseOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / duration;
if (position == 1.0)
{
return 1.0;
}
var p = duration * 0.3;
var s = p / (2.0 * M_PI) * asin(1.0);
return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) + 1.0 );
};
internal static let EaseInOutElastic = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed == 0.0)
{
return 0.0;
}
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position == 2.0)
{
return 1.0;
}
var p = duration * (0.3 * 1.5);
var s = p / (2.0 * M_PI) * asin(1.0);
if (position < 1.0)
{
position -= 1.0;
return CGFloat( -0.5 * (pow(2.0, 10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p)) );
}
position -= 1.0;
return CGFloat( pow(2.0, -10.0 * position) * sin((position * duration - s) * (2.0 * M_PI) / p) * 0.5 + 1.0 );
};
internal static let EaseInBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
let s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / duration;
return CGFloat( position * position * ((s + 1.0) * position - s) );
};
internal static let EaseOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
let s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / duration;
position--;
return CGFloat( (position * position * ((s + 1.0) * position + s) + 1.0) );
};
internal static let EaseInOutBack = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var s: NSTimeInterval = 1.70158;
var position: NSTimeInterval = elapsed / (duration / 2.0);
if (position < 1.0)
{
s *= 1.525;
return CGFloat( 0.5 * (position * position * ((s + 1.0) * position - s)) );
}
s *= 1.525;
position -= 2.0;
return CGFloat( 0.5 * (position * position * ((s + 1.0) * position + s) + 2.0) );
};
internal static let EaseInBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
return 1.0 - EaseOutBounce(duration - elapsed, duration);
};
internal static let EaseOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
var position: NSTimeInterval = elapsed / duration;
if (position < (1.0 / 2.75))
{
return CGFloat( 7.5625 * position * position );
}
else if (position < (2.0 / 2.75))
{
position -= (1.5 / 2.75);
return CGFloat( 7.5625 * position * position + 0.75 );
}
else if (position < (2.5 / 2.75))
{
position -= (2.25 / 2.75);
return CGFloat( 7.5625 * position * position + 0.9375 );
}
else
{
position -= (2.625 / 2.75);
return CGFloat( 7.5625 * position * position + 0.984375 );
}
};
internal static let EaseInOutBounce = { (elapsed: NSTimeInterval, duration: NSTimeInterval) -> CGFloat in
if (elapsed < (duration / 2.0))
{
return EaseInBounce(elapsed * 2.0, duration) * 0.5;
}
return EaseOutBounce(elapsed * 2.0 - duration, duration) * 0.5 + 0.5;
};
}; | mit | 80c3fe8f383dfd486dc68e91aa4e6caa | 34.203046 | 139 | 0.599034 | 4.408455 | false | false | false | false |
inloop/INLConfig | INLConfig/INLConfig/INLConfig.swift | 1 | 1469 | //
// INLConfig.swift
// ConfigDemo
//
// Created by Tomas Hakel on 26/02/2016.
// Copyright © 2016 Inloop. All rights reserved.
//
import Foundation
extension INLConfig {
public func updateConfig(completion: (()->())?) {
guard let meta = config["INLMeta"],
let versionURLStr = meta["version"] as? String,
let versionURL = NSURL(string: versionURLStr)
else {
downloadConfig(completion)
return
}
let localVersion = NSUserDefaults.standardUserDefaults().stringForKey("inlconfig.\(configName).version")
INLConfigDownloader().get(versionURL) { version in
if let version = version where version != localVersion {
self.downloadConfig(completion)
NSUserDefaults.standardUserDefaults().setObject(version, forKey: "inlconfig.\(self.configName).version")
}
}
}
func downloadConfig(completion: (()->())?) {
guard let meta = config["INLMeta"],
let configURLStr = meta["config"] as? String,
let configURL = NSURL(string: configURLStr)
else {
return
}
INLConfigDownloader().get(configURL) { configuration in
if let configuration = configuration {
NSFileManager.defaultManager().createFileAtPath(self.pathForConfig(self.configName), contents: configuration.dataUsingEncoding(NSUTF8StringEncoding), attributes: nil)
self.loadConfigurationWithPlist(self.configName)
if let completion = completion {
dispatch_async(dispatch_get_main_queue()) {
completion()
}
}
}
}
}
}
| cc0-1.0 | f0f270b98bfaf9693cb485f9e09f3f3c | 27.784314 | 170 | 0.705722 | 3.853018 | false | true | false | false |
sayheyrickjames/codepath-week2-carousel | week2-homework-carousel/CreateAccountViewController.swift | 1 | 5766 | //
// CreateAccountViewController.swift
// week2-homework-carousel
//
// Created by Rick James! Chatas on 5/14/15.
// Copyright (c) 2015 SayHey. All rights reserved.
//
import UIKit
class CreateAccountViewController: UIViewController, UIAlertViewDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var createAccountView: UIView!
@IBOutlet weak var createAccount2View: UIView!
@IBOutlet weak var firstNameField: UITextField!
@IBOutlet weak var lastNameField: UITextField!
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var termsCheckbox: UIButton!
@IBOutlet weak var termsWebLink: UIButton!
@IBOutlet weak var createButton: UIButton!
var initialCenter : CGPoint!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
initialCenter = self.createAccount2View.center
scrollView.contentSize = CGSize(width: 320, height: 504)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func backButton(sender: AnyObject) {
navigationController!.popViewControllerAnimated(true)
}
@IBAction func termsSelect(sender: AnyObject) {
termsCheckbox.selected = !termsCheckbox.selected
}
@IBAction func onTap(sender: AnyObject) {
view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
// Set view properties in here that you want to match with the animation of the keyboard
// If you need it, you can use the kbSize property above to get the keyboard width and height.
self.createAccountView.frame.origin.y = -140
self.createAccount2View.center.y = 218
}, completion: nil)
}
func keyboardWillHide(notification: NSNotification!) {
var userInfo = notification.userInfo!
// Get the keyboard height and width from the notification
// Size varies depending on OS, language, orientation
var kbSize = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().size
var durationValue = userInfo[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
var animationDuration = durationValue.doubleValue
var curveValue = userInfo[UIKeyboardAnimationCurveUserInfoKey] as! NSNumber
var animationCurve = curveValue.integerValue
UIView.animateWithDuration(animationDuration, delay: 0.0, options: UIViewAnimationOptions(UInt(animationCurve << 16)), animations: {
// Set view properties in here that you want to match with the animation of the keyboard
// If you need it, you can use the kbSize property above to get the keyboard width and height.
self.createAccountView.frame.origin.y = 0
self.createAccount2View.center = self.initialCenter
}, completion: nil)
}
@IBAction func accountCreated(sender: AnyObject) {
if firstNameField.text == "" || lastNameField.text == "" || emailField.text == "" || passwordField.text == "" {
var callAlertView = UIAlertView(title: "Hmm...", message: "Looks like something was left blank. Please fill out all fields.", delegate: self, cancelButtonTitle: "Go back")
callAlertView.show()
} else if termsCheckbox.selected.boolValue == false {
var callAlertView = UIAlertView(title: "One more thing...", message: "Please accept the terms.", delegate: self, cancelButtonTitle: "Go back")
callAlertView.show()
} else {
var alertView = UIAlertView(title: "Thank you. Creating your Dropbox...", message: nil, delegate: nil, cancelButtonTitle: nil)
alertView.show()
delay(2, { () -> () in
alertView.dismissWithClickedButtonIndex(0, animated: true)
self.performSegueWithIdentifier("accountCreated", sender: self)
})
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | eff546c1e164c43df34800cab05bc638 | 39.321678 | 183 | 0.659209 | 5.592629 | false | false | false | false |
dasdom/GlobalADN | GlobalADN/DataFetch/PostsParser.swift | 1 | 2404 | //
// PostsParser.swift
// GlobalADN
//
// Created by dasdom on 19.06.14.
// Copyright (c) 2014 Dominik Hauser. All rights reserved.
//
import UIKit
class PostsParser {
var postBuilder: CanBuildPost
var userBuilder: CanBuildUser
var mentionBuilder: CanBuildMention
init(postBuilder: CanBuildPost, userBuilder: CanBuildUser, mentionBuilder: CanBuildMention) {
self.postBuilder = postBuilder
self.userBuilder = userBuilder
self.mentionBuilder = mentionBuilder
}
convenience init() {
self.init(postBuilder: PostBuilder(), userBuilder: UserBuilder(), mentionBuilder: MentionBuilder())
}
func postsArrayFromData(data: NSData) -> (array: Array<Post>?, meta: Meta?, error: NSError?) {
var jsonError: NSError? = nil
var dictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &jsonError) as? NSDictionary
// println("dictionary \(dictionary)")
if jsonError != nil {
return (nil, nil, jsonError)
}
let metaDict = dictionary!["meta"] as Dictionary<String, AnyObject>
println("metaDict: \(metaDict)")
let meta = MetaBuilder().metaFromDictionary(metaDict)
if let errorMessage = metaDict["error_message"] as? NSString {
var code = metaDict["code"] as NSNumber
var error = NSError.errorWithDomain(ADNFetchError, code: code.integerValue, userInfo: [NSLocalizedDescriptionKey : errorMessage])
return (nil, nil, error)
}
let array = self.postsArrayFromDataDictionary(dictionary!)
return (array, meta, nil)
}
func postsArrayFromDataDictionary(dictionary: NSDictionary) -> Array<Post> {
var postsArray = [Post]()
if let rawPostsArray = dictionary["data"] as? NSArray {
// println("\(rawPostsArray)")
for arrayEntry: AnyObject in rawPostsArray {
if let postDictionary = arrayEntry as? NSDictionary {
if let post = postBuilder.postFromDictionary(postDictionary) {
postsArray.append(post)
} else {
println("user or post is nil")
}
} else {
println("post dict is nil")
}
}
}
return postsArray
}
} | mit | 6cc11d18d4e2263cbb3bb5d5c51fe7a0 | 33.357143 | 141 | 0.603161 | 4.779324 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPressShared/WordPressShared/Core/Utility/String+Helpers.swift | 2 | 5726 | import Foundation
extension String {
public func stringByDecodingXMLCharacters() -> String {
return NSString.decodeXMLCharacters(in: self)
}
public func stringByEncodingXMLCharacters() -> String {
return NSString.encodeXMLCharacters(in: self)
}
public func trim() -> String {
return trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
/// Returns `self` if not empty, or `nil` otherwise
///
public func nonEmptyString() -> String? {
return isEmpty ? nil : self
}
/// Returns a string without the character at the specified index.
/// This is a non-mutating version of `String.remove(at:)`.
public func removing(at index: Index) -> String {
var copy = self
copy.remove(at: index)
return copy
}
}
// MARK: - Prefix removal
public extension String {
/// Removes the given prefix from the string, if exists.
///
/// Calling this method might invalidate any existing indices for use with this string.
///
/// - Parameters:
/// - prefix: A possible prefix to remove from this string.
///
public mutating func removePrefix(_ prefix: String) {
if let prefixRange = range(of: prefix), prefixRange.lowerBound == startIndex {
removeSubrange(prefixRange)
}
}
/// Returns a string with the given prefix removed, if it exists.
///
/// - Parameters:
/// - prefix: A possible prefix to remove from this string.
///
public func removingPrefix(_ prefix: String) -> String {
var copy = self
copy.removePrefix(prefix)
return copy
}
/// Removes the prefix from the string that matches the given pattern, if any.
///
/// Calling this method might invalidate any existing indices for use with this string.
///
/// - Parameters:
/// - pattern: The regular expression pattern to search for. Avoid using `^`.
/// - options: The options applied to the regular expression during matching.
///
/// - Throws: an error if it the pattern is not a valid regular expression.
///
public mutating func removePrefix(pattern: String, options: NSRegularExpression.Options = []) throws {
let regexp = try NSRegularExpression(pattern: "^\(pattern)", options: options)
let fullRange = NSRange(location: 0, length: (self as NSString).length)
if let match = regexp.firstMatch(in: self, options: [], range: fullRange) {
let matchRange = match.range
self = (self as NSString).replacingCharacters(in: matchRange, with: "")
}
}
/// Returns a string without the prefix that matches the given pattern, if it exists.
///
/// - Parameters:
/// - pattern: The regular expression pattern to search for. Avoid using `^`.
/// - options: The options applied to the regular expression during matching.
///
/// - Throws: an error if it the pattern is not a valid regular expression.
///
public func removingPrefix(pattern: String, options: NSRegularExpression.Options = []) throws -> String {
var copy = self
try copy.removePrefix(pattern: pattern, options: options)
return copy
}
}
// MARK: - Suffix removal
public extension String {
/// Removes the given suffix from the string, if exists.
///
/// Calling this method might invalidate any existing indices for use with this string.
///
/// - Parameters:
/// - suffix: A possible suffix to remove from this string.
///
public mutating func removeSuffix(_ suffix: String) {
if let suffixRange = range(of: suffix, options: [.backwards]), suffixRange.upperBound == endIndex {
removeSubrange(suffixRange)
}
}
/// Returns a string with the given suffix removed, if it exists.
///
/// - Parameters:
/// - suffix: A possible suffix to remove from this string.
///
public func removingSuffix(_ suffix: String) -> String {
var copy = self
copy.removeSuffix(suffix)
return copy
}
/// Removes the suffix from the string that matches the given pattern, if any.
///
/// Calling this method might invalidate any existing indices for use with this string.
///
/// - Parameters:
/// - pattern: The regular expression pattern to search for. Avoid using `$`.
/// - options: The options applied to the regular expression during matching.
///
/// - Throws: an error if it the pattern is not a valid regular expression.
///
public mutating func removeSuffix(pattern: String, options: NSRegularExpression.Options = []) throws {
let regexp = try NSRegularExpression(pattern: "\(pattern)$", options: options)
let fullRange = NSRange(location: 0, length: (self as NSString).length)
if let match = regexp.firstMatch(in: self, options: [], range: fullRange) {
let matchRange = match.range
self = (self as NSString).replacingCharacters(in: matchRange, with: "")
}
}
/// Returns a string without the suffix that matches the given pattern, if it exists.
///
/// - Parameters:
/// - pattern: The regular expression pattern to search for. Avoid using `$`.
/// - options: The options applied to the regular expression during matching.
///
/// - Throws: an error if it the pattern is not a valid regular expression.
///
public func removingSuffix(pattern: String, options: NSRegularExpression.Options = []) throws -> String {
var copy = self
try copy.removeSuffix(pattern: pattern, options: options)
return copy
}
}
| gpl-2.0 | 8c1445743513e0db78eb130fcde6ceae | 37.42953 | 109 | 0.635522 | 4.783626 | false | false | false | false |
linkedin/ConsistencyManager-iOS | ConsistencyManager/Protocols/ConsistencyManagerModel.swift | 2 | 11704 | // © 2016 LinkedIn Corp. 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.
/**
This protocol should be implemented by all the models you want to track using the consistency manager. Effectively, it asks you to treat a model as a tree, which enables the library to traverse the tree and map the tree.
IMPORTANT: These methods should be thread safe. Since they are all read operations, and do not mutate the model in any way, this shouldn't be a problem. We recommend using this library with completely immutable models for this reason. However, if there is a problem, you should place a lock on your model when running these methods.
Example Implementation:
```
class Person: ConsistencyManagerModel {
let id: String
let name: String
let currentLocation: Location?
let homeTown: Location
var modelIdentifier: String? {
return id
}
func map(transform: ConsistencyManagerModel -> ConsistencyManagerModel?) -> Person? {
let newCurrentLocation: Location? = {
if let currentLocation = self.currentLocation {
return transform(currentLocation) as? Location
} else {
return nil
}
}()
let newHomeTown = transform(homeTown) as? Location
if newHomeTown == nil {
return nil
}
return Person(id: id, name: name, currentLocation: newCurrentLocation, homeTown: newHomeTown!)
}
func forEach(function: ConsistencyManagerModel -> Void) {
if let currentLocation = currentLocation {
function(currentLocation)
}
function(homeTown)
}
func isEqualToModel(other: ConsistencyManagerModel) -> Bool {
guard let other = other as? Person {
return false
}
if id != other.id { return false }
if name != other.name { return false }
if !homeTown.isEqualToModel(other.homeTown) { return false }
if let currentLocation = currentLocation, let otherLocation = other.currentLocation where !currentLocation.isEqualToModel(otherLocation) {
return false
} else if currentLocation != nil || other.currentLocation != nil {
return false
}
return true
}
}
class Location: ConsistencyManagerModel {
let name: String
var modelIdentifier: String? {
// No id, so let's return nil
return nil
}
func map(transform: ConsistencyManagerModel -> ConsistencyManagerModel?) -> Location? {
// We have no submodels, so nothing to map here
return self
}
func forEach(function: ConsistencyManagerModel -> Void) {
// Do nothing. Nothing to iterate over.
}
func isEqualToModel(other: ConsistencyManagerModel) -> Bool {
guard let other = other as? Person {
return false
}
if name != other.name { return false }
return true
}
}
```
For other examples, see the documentation on Github.
*/
public protocol ConsistencyManagerModel {
// MARK: Required Methods
/**
This method should return a globally unique identifier for the model.
If it has no id, then you can return nil. If it has no id, it will be considered part of its parent model and you will not be able to update this model in isolation.
Whenever you change a field on this model, you must post the parent model to the consistency manager for the updates to take place.
If you're ids are not globally unique, then it's recommended to prefix this id with the class name.
Ids must be globally unique or you will get unexpected behavior.
*/
var modelIdentifier: String? { get }
/**
This method should run a map function on each child model and return a new version of self.
It should iterate over all the model's children models and run a transform function on each model.
Then, it should return a new version of self with the new child models.
Note: child models are any model which conforms to the protocol. So you can ignore anything else (strings, ints, etc).
If transform returns nil, it should remove this child model.
If this child is in an array, it's recommended that you just remove this element from the array.
If the model is a required model, it is up to you how you implement this.
However, we recommend that you consider this a cascading delete and return nil from this function (signifying that we should delete the current model).
It should NOT be recursive. As in, it should only map on the immediate children.
It should not call map on its children's children.
- NOTE: Ideally, we'd like this function to return `Self?`, not `ConsistencyManagerModel?`.
However, Swift currently has a few bugs regarding returning Self in protocols which make this protocol hard to implement (e.g. returning self in protocol extensions doesn't work).
When these bugs are fixed in Swift, we may consider moving back to using Self.
You should always return the same type of model from this function even though the protocol doesn't specifically require it.
- parameter transform: The mapping function
- Returns: A new version of self with the map function applied
*/
func map(_ transform: (ConsistencyManagerModel) -> ConsistencyManagerModel?) -> ConsistencyManagerModel?
/**
This function should simply iterate over all the child models and run the function passed in.
Just like map, it only needs to run on anything which is a child and a ConsistencyManagerModel.
This is very similar to map, and you can actually implement it using map (possibly in a protocol extension).
For instance:
extension ConsistencyManagerModel {
func forEach(function: ConsistencyManagerModel -> Void) {
_ = map() { model in
function(model)
return model
}
}
}
Here, we are just running map and discarding the result.
This is correct and can save you some lines of code, but it's less performant since you are creating a new model and then discarding it.
This performance difference is minor, so it's up to you which you prefer.
It should NOT be recursive. It should only iterate over the immediate children. Not its children chilrden.
- parameter visit: The iterating function to be called on each child element.
*/
func forEach(_ visit: (ConsistencyManagerModel) -> Void)
/**
This function should compare one model to another model.
If you are Equatable, you do NOT need to implement this, and it will automatically be implemented using ==.
This is implemented in the protocol extension later in this file.
Nearly always, you want this to act like == and return false if there are any differences.
However, in some cases, there may be fields that you don't care about that change a lot.
For instance, you may have some Globally Unique ID returned by the server which isn't used for rendering.
If you want, you can choose to return true from this function even if these 'transient fields' are different.
This means that if only this field changes, it will NOT cause a consistency manager update.
Instead, the change will be dropped.
However, if there are any other field changes, it will still cause an update and update the whole model.
This is rare, but an open option if you need it.
- parameter other: The other model to compare to.
- Returns: True if the models are equal and we should not generate a consistency manager change.
*/
func isEqualToModel(_ other: ConsistencyManagerModel) -> Bool
// MARK: Projections
/**
Optional
Most setups don't need to implement this method. You only need to implement this if you are using projections.
For more information on projections, see https://plivesey.github.io/ConsistencyManager/pages/055_projections.html.
This should take another model and merge it into the current model.
If you have two models with the same id but different data, this should merge one model into the other.
This should return the same type as Self. It should take all updates from the other model and merge it into the current model.
For performance reasons, you could check if the other model is the same projection.
If it is, you could avoid merging and just return the other model (since it's the correct class).
- NOTE: Ideally, we'd like this function to return `Self?`, not `ConsistencyManagerModel?`.
However, Swift currently has a few bugs regarding returning Self in protocols which make this protocol hard to implement (e.g. returning self in protocol extensions doesn't work).
When these bugs are fixed in Swift, we may consider moving back to using Self.
You should always return the same type of model from this function even though the protocol doesn't specifically require it.
- parameter model: The other model to merge into the current model.
- Returns: A new version of the current model with the changes from the other model.
*/
func mergeModel(_ model: ConsistencyManagerModel) -> ConsistencyManagerModel
/**
You can override to distinguish different projections. Usually, you would have a different class for each projection.
But you can use this to have one class represent multiple different projections (with optional fields for missing members).
This is unusual and it's recommended instead to just use different classes for each projection.
If you do this, you do not need to override this method and can use the default value.
*/
var projectionIdentifier: String { get }
}
public extension ConsistencyManagerModel where Self: Equatable {
/**
This is a default implementation for isEqualToModel for models which are equatable.
This can be overridden in subclasses if you don't want this default behavior.
*/
func isEqualToModel(_ other: ConsistencyManagerModel) -> Bool {
if let other = other as? Self {
return self == other
} else {
return false
}
}
}
/**
This extension contains the default implementations which make `mergeModel(:)` and `projectionIdentifier` optional.
*/
public extension ConsistencyManagerModel {
func mergeModel(_ model: ConsistencyManagerModel) -> ConsistencyManagerModel {
// Usually, we don't need to merge and instead just return the other model.
// This is because when we're not using projections, classes of the same id will always be of the same type.
// So, we should just replace the current model with the updated model.
assert(type(of: self) == type(of: model), "Two models of different classes have the same ID. This is not allowed without override mergeModel(:). See the documentation for more information on projections. Current Model: \(type(of: self)) - Update Model: \(type(of: model))")
return model
}
var projectionIdentifier: String {
// Returns the class name as a string
// This means each class type identifies a different projection
return String(describing: type(of: self))
}
}
| apache-2.0 | 3872e17c63655767ce424ea4e451b10c | 46.963115 | 332 | 0.703324 | 4.919294 | false | false | false | false |
GuiminChu/JianshuExamples | CoreTextDemo/CoreTextDemo/CoreText/图文混排/CoreTextUtils.swift | 4 | 2561 | //
// CoreTextUtils.swift
// CoreTextDemo
//
// Created by Chu Guimin on 17/3/8.
// Copyright © 2017年 cgm. All rights reserved.
//
import UIKit
struct CoreTextUtils {
static func touchLink(inView view: UIView, atPoint point: CGPoint, data: CoreTextData) -> CoreTextLinkData? {
guard let linkArray = data.linkArray else {
return nil
}
let textFrame = data.ctFrame
let lines = CTFrameGetLines(textFrame) as Array
// 获取每一行的 origin 坐标
let origins = UnsafeMutablePointer<CGPoint>.allocate(capacity: lines.count)
CTFrameGetLineOrigins(textFrame, CFRangeMake(0, 0), origins)
// 翻转坐标系
let transform = CGAffineTransform(translationX: 0, y: view.bounds.size.height)
transform.scaledBy(x: 1, y: -1)
for i in 0..<lines.count {
let linePoint = origins[i]
let line: CTLine = lines[i] as! CTLine
// 获取每一行的 CGRect 信息
let flippedRect = getLineBounds(bounds: line, point: linePoint)
let rect = flippedRect.applying(transform)
print(rect)
if rect.contains(point) {
print("hh")
// 将点击的坐标转换成相对于当前行的坐标
let relativePoint = CGPoint(x: point.x - rect.minX, y: point.y - rect.minY)
// 获得当前点击坐标对应的字符串偏移
let index = CTLineGetStringIndexForPosition(line, relativePoint)
// 判断这个偏移是否在我们的链接列表中
return link(index: index, linkArray: linkArray)
}
}
return nil
}
private static func getLineBounds(bounds: CTLine, point: CGPoint) -> CGRect {
var ascent = CGFloat()
var descent = CGFloat()
var leading = CGFloat()
let width = CGFloat(CTLineGetTypographicBounds(bounds, &ascent, &descent, &leading))
let height = ascent + descent
return CGRect(x: point.x, y: point.y - descent, width: width, height: height)
}
static func link(index: CFIndex, linkArray: [CoreTextLinkData]) -> CoreTextLinkData? {
for coreTextLinkData in linkArray {
if NSLocationInRange(index, coreTextLinkData.range) {
return coreTextLinkData
}
}
return nil
}
}
| mit | c693794c6bdac82c93380a96b675b6f1 | 31.186667 | 113 | 0.562552 | 4.47037 | false | false | false | false |
ykyouhei/QiitaKit | Example/APITableViewController.swift | 1 | 3156 | //
// APITableViewController.swift
// QiitaKit
//
// Created by kyo__hei on 2016/07/16.
// Copyright © 2016年 kyo__hei. All rights reserved.
//
import UIKit
import QiitaKit
internal final class APITableViewController: UITableViewController {
fileprivate var successObject: Any?
override func viewDidLoad() {
super.viewDidLoad()
title = currentUser.name
navigationController?.delegate = self
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
switch (indexPath as NSIndexPath).row {
case 0:
send(QiitaAPI.User.GetAuthenticatedUserRequest())
case 1:
send(QiitaAPI.User.GetUsersRequest(
page: 1,
perPage: 10)
)
case 2:
send(QiitaAPI.User.GetFolloweesRequest(
userID: currentUser.id,
page: 1,
perPage: 10)
)
case 3:
send(QiitaAPI.User.GetFollowersRequest(
userID: currentUser.id,
page: 1,
perPage: 10)
)
case 4:
send(QiitaAPI.Item.GetItemsRequest(
type: .authenticatedUser,
page: 1,
perPage: 10)
)
case 5:
send(QiitaAPI.Tag.GetFollowingTagsRequest(
userID: currentUser.id,
page: 1,
perPage: 10)
)
default:
break
}
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
switch segue.destination {
case let vc as RequestViewController:
vc.object = successObject
default:
break
}
}
func send<T: QiitaRequest>(_ request: T) {
let indicator = UIActivityIndicatorView(frame: view.bounds)
indicator.startAnimating()
indicator.activityIndicatorViewStyle = .gray
view.addSubview(indicator)
APIClient().send(request) { result in
indicator.removeFromSuperview()
switch result {
case .success(let object):
print(object)
self.successObject = object
self.performSegue(withIdentifier: "showRequest", sender: nil)
case .failure(let error):
self.showErrorAlert(error)
}
}
}
}
extension APITableViewController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
willShow viewController: UIViewController,
animated: Bool) {
if viewController is LoginViewController {
let _ = try? AuthManager.sharedManager.logout()
}
}
}
| mit | 654a15fdd68b975002029e7cd9001ab8 | 26.902655 | 106 | 0.527117 | 5.650538 | false | false | false | false |
ulfie22/CSwiftV | CSwiftVTests/CSwiftVTests.swift | 2 | 8853 | //
// CSwiftVTests.swift
// CSwiftVTests
//
// Created by Daniel Haight on 30/08/2014.
// Copyright (c) 2014 ManyThings. All rights reserved.
//
import Foundation
import XCTest
import CSwiftV
public let newLineSeparation = "Year,Make,Model,Description,Price\r\n1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00\r\n"
public let newLineSeparationNoEnd = "Year,Make,Model,Description,Price\r\n1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00"
public let withoutHeader = "1997,Ford,E350,descrition,3000.00\r\n1999,Chevy,Venture,another description,4900.00"
public let withRandomQuotes = "Year,Make,Model,Description,Price\r\n1997,Ford,\"E350\",descrition,3000.00\r\n1999,Chevy,Venture,\"another description\",4900.00"
public let withCommasInQuotes = "Year,Make,Model,Description,Price\r\n1997,Ford,\"E350\",descrition,3000.00\r\n1999,Chevy,Venture,\"another, amazing, description\",4900.00"
public let withQuotesInQuotes = "Year,Make,Model,Description,Price\r\n1997,Ford,\"E350\",descrition,3000.00\r\n1999,Chevy,Venture,\"another, \"\"amazing\"\", description\",4900.00"
public let withNewLinesInQuotes = "Year,Make,Model,Description,Price\r\n1997,Ford,\"E350\",descrition,3000.00\r\n1999,Chevy,Venture,\"another, \"\"amazing\"\",\r\ndescription\r\n\",4900.00\r\n"
public let withTabSeparator = "Year\tMake\tModel\tDescription\tPrice\r\n1997\tFord\t\"E350\"\tdescrition\t3000.00\r\n1999\tChevy\tVenture\t\"another\t \"\"amazing\"\"\t description\"\t4900.00\r\n"
class CSwiftVTests: XCTestCase {
var testString: String!
// modelling from http://tools.ietf.org/html/rfc4180#section-2
//1. Each record is located on a separate line, delimited by a line
//break (CRLF). For example:
//aaa,bbb,ccc CRLF
//zzz,yyy,xxx CRLF
func testThatItParsesLinesSeperatedByNewLines() {
testString = newLineSeparation
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
//2. The last record in the file may or may not have an ending line
//break. For example:
//aaa,bbb,ccc CRLF
//zzz,yyy,xxx
func testThatItParsesLinesSeperatedByNewLinesWithoutNewLineAtEnd() {
testString = newLineSeparationNoEnd
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
//3. There maybe an optional header line appearing as the first line
//of the file with the same format as normal record lines. This
//header will contain names corresponding to the fields in the file
//and should contain the same number of fields as the records in
//the rest of the file (the presence or absence of the header line
//should be indicated via the optional "header" parameter of this
//MIME type). For example:
//field_name,field_name,field_name CRLF
//aaa,bbb,ccc CRLF
//zzz,yyy,xxx CRLF
func testThatItParsesHeadersCorrectly() {
testString = newLineSeparationNoEnd
let arrayUnderTest : [String] = CSwiftV(String: testString, headers:nil).headers
let expectedArray = ["Year","Make","Model","Description","Price"]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
// still 3. in RFC. This is the first decision we make in
// api design with regards to headers. Currently if nothing
// is passed in to the `headers` parameter (as is the case)
// with the convenience initialiser. We assume that the csv
// contains headers. If the headers are passed in, then we
// assume that the csv file does not contain them and expect
// it to be parsed accordingly.
func testThatItParsesRowsWithoutHeaders() {
testString = withoutHeader
let arrayUnderTest = CSwiftV(String: testString, headers:["Year","Make","Model","Description","Price"]).rows
//XCTAssertNil(arrayUnderTest)
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
// 4. Within the header and each record, there may be one or more
// fields, separated by commas. Each line should contain the same
// number of fields throughout the file. Spaces are considered part
// of a field and should not be ignored. The last field in the
// record must not be followed by a comma. For example:
//
// aaa,bbb,ccc
//
// This is covered by previous test cases since there are spaces in
// fields and no commas at the end of the lines
//
// 5. Each field may or may not be enclosed in double quotes (however
// some programs, such as Microsoft Excel, do not use double quotes
// at all). If fields are not enclosed with double quotes, then
// double quotes may not appear inside the fields. For example:
//
// "aaa","bbb","ccc" CRLF
// zzz,yyy,xxx
func testThatItParsesFieldswithQuotes() {
testString = withRandomQuotes
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
// 6. Fields containing line breaks (CRLF), double quotes, and commas
// should be enclosed in double-quotes. For example:
//
// "aaa","b CRLF
// bb","ccc" CRLF
// zzz,yyy,xxx
func testThatItParsesFieldswithCommasInQuotes() {
testString = withCommasInQuotes
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another, amazing, description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
func testThatItParsesFieldswithNewLinesInQuotes() {
testString = withNewLinesInQuotes
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another, \"amazing\",\r\ndescription\r\n","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
// 7. If double-quotes are used to enclose fields, then a double-quote
// appearing inside a field must be escaped by preceding it with
// another double quote. For example:
//
// "aaa","b""bb","ccc"
func testThatItParsesFieldswithQuotesInQuotes() {
testString = withQuotesInQuotes
let arrayUnderTest = CSwiftV(String: testString).rows
let expectedArray = [
["1997","Ford","E350","descrition","3000.00"],
["1999","Chevy","Venture","another, \"amazing\", description","4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
func testThatCanReturnKeyedRows() {
testString = withQuotesInQuotes
let arrayUnderTest = CSwiftV(String: testString).keyedRows!
let expectedArray = [
["Year":"1997","Make":"Ford","Model":"E350","Description":"descrition","Price":"3000.00"],
["Year":"1999","Make":"Chevy","Model":"Venture","Description":"another, \"amazing\", description","Price":"4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
func testThatItCanParseArbitrarySeparators() {
testString = withTabSeparator
let arrayUnderTest = CSwiftV(String: testString, separator:"\t").keyedRows!
let expectedArray = [
["Year":"1997","Make":"Ford","Model":"E350","Description":"descrition","Price":"3000.00"],
["Year":"1999","Make":"Chevy","Model":"Venture","Description":"another\t \"amazing\"\t description","Price":"4900.00"]
]
XCTAssertEqual(arrayUnderTest, expectedArray)
}
}
| bsd-3-clause | 6d406c8083a0db3331ad1046d8bf4e40 | 34.842105 | 196 | 0.628826 | 4.077844 | false | true | false | false |
Gilbertat/SYKanZhiHu | SYKanZhihu/SYKanZhihu/Class/Manager/Refresh/UIScrollview+Refresh.swift | 1 | 3120 | //
// UIScrollview+Refresh.swift
// SYKanZhihu
//
// Created by shiyue on 16/3/5.
// Copyright © 2016年 shiyue. All rights reserved.
//
import UIKit
extension UIScrollView {
func addHeaderWithCallback( _ callback:(() -> Void)!){
let header:RefreshHeaderView = RefreshHeaderView.header()
self.addSubview(header)
header.beginRefreshingCallBack = callback
header.addState(RefreshState.normal)
}
func removeHeader()
{
for view : AnyObject in self.subviews{
if view is RefreshHeaderView{
view.removeFromSuperview()
}
}
}
func headerBeginRefreshing()
{
for object : AnyObject in self.subviews{
if object is RefreshHeaderView{
object.beginRefreshing()
}
}
}
func headerEndRefreshing()
{
for object : AnyObject in self.subviews{
if object is RefreshHeaderView{
object.endRefreshing()
}
}
}
func setHeaderHidden(_ hidden:Bool)
{
for object : AnyObject in self.subviews{
if object is RefreshHeaderView{
let view:UIView = object as! UIView
view.isHidden = hidden
}
}
}
func isHeaderHidden()
{
for object : AnyObject in self.subviews{
if object is RefreshHeaderView{
let view:UIView = object as! UIView
view.isHidden = isHidden
}
}
}
func addFooterWithCallback( _ callback:(() -> Void)!){
let footer:RefreshFooterView = RefreshFooterView.footer()
self.addSubview(footer)
footer.beginRefreshingCallBack = callback
footer.addState(RefreshState.normal)
}
func removeFooter()
{
for view : AnyObject in self.subviews{
if view is RefreshFooterView{
view.removeFromSuperview()
}
}
}
func footerBeginRefreshing()
{
for object : AnyObject in self.subviews{
if object is RefreshFooterView{
object.beginRefreshing()
}
}
}
func footerEndRefreshing()
{
for object : AnyObject in self.subviews{
if object is RefreshFooterView{
object.endRefreshing()
}
}
}
func setFooterHidden(_ hidden:Bool)
{
for object : AnyObject in self.subviews{
if object is RefreshFooterView{
let view:UIView = object as! UIView
view.isHidden = hidden
}
}
}
func isFooterHidden()
{
for object : AnyObject in self.subviews{
if object is RefreshFooterView{
let view:UIView = object as! UIView
view.isHidden = isHidden
}
}
}
}
| mit | 2c98c1246fe5025ce7bbbae4484e0997 | 21.264286 | 65 | 0.509464 | 5.392734 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsScreen/SettingsViewController.swift | 1 | 8478 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Localization
import PlatformUIKit
import RxCocoa
import RxDataSources
import RxSwift
import ToolKit
public final class SettingsViewController: BaseScreenViewController {
// MARK: - Accessibility
private typealias AccessibilityIDs = Accessibility.Identifier.Settings.SettingsCell
private typealias RxDataSource = RxTableViewSectionedAnimatedDataSource<SettingsSectionViewModel>
// MARK: - Private IBOutlets
@IBOutlet private var tableView: UITableView!
// MARK: - Private Properties
private let presenter: SettingsScreenPresenter
private let disposeBag = DisposeBag()
// MARK: - Setup
public init(presenter: SettingsScreenPresenter) {
self.presenter = presenter
super.init(nibName: SettingsViewController.objectName, bundle: .module)
}
@available(*, unavailable)
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Lifecycle
override public func viewDidLoad() {
super.viewDidLoad()
title = LocalizationConstants.settings
setupTableView()
presenter.refresh()
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setupNavigationBar()
presenter.refresh()
}
// MARK: - Private Functions
private func setupNavigationBar() {
titleViewStyle = .text(value: LocalizationConstants.settings)
set(
barStyle: presenter.barStyle,
leadingButtonStyle: presenter.leadingButton,
trailingButtonStyle: presenter.trailingButton
)
trailingButtonStyle = .close
}
private func setupTableView() {
tableView.backgroundColor = .background
tableView.tableFooterView = AboutView()
tableView.tableFooterView?.frame = .init(
origin: .zero,
size: .init(
width: tableView.bounds.width,
height: AboutView.estimatedHeight(for: tableView.bounds.width)
)
)
tableView.estimatedRowHeight = 80
tableView.estimatedSectionHeaderHeight = 70
tableView.sectionHeaderHeight = UITableView.automaticDimension
tableView.rowHeight = UITableView.automaticDimension
tableView.registerNibCell(SwitchTableViewCell.self, in: .module)
tableView.registerNibCell(ReferralTableViewCell.self, in: .module)
tableView.registerNibCell(ClipboardTableViewCell.self, in: .module)
tableView.registerNibCell(BadgeTableViewCell.self, in: .platformUIKit)
tableView.registerNibCell(CommonTableViewCell.self, in: .module)
tableView.registerNibCell(AddPaymentMethodTableViewCell.self, in: .module)
tableView.register(LinkedBankTableViewCell.self)
tableView.registerNibCell(LinkedCardTableViewCell.self, in: .platformUIKit)
tableView.register(SettingsSkeletonTableViewCell.self)
tableView.registerHeaderView(TableHeaderView.objectName, bundle: .module)
let dataSource = RxDataSource(configureCell: { [weak self] _, _, indexPath, item in
guard let self = self else { return UITableViewCell() }
let cell: UITableViewCell
switch item.cellType {
case .badge(_, let presenter):
cell = self.badgeCell(for: indexPath, presenter: presenter)
case .clipboard(let type):
cell = self.clipboardCell(for: indexPath, viewModel: type.viewModel)
case .common(let type):
cell = self.commonCell(for: indexPath, viewModel: type.viewModel)
case .cards(let type):
switch type {
case .skeleton:
cell = self.skeletonCell(for: indexPath)
case .add(let presenter):
cell = self.addPaymentMethodCell(for: indexPath, presenter: presenter)
case .linked(let presenter):
cell = self.linkedCardCell(for: indexPath, presenter: presenter)
}
case .banks(let type):
switch type {
case .skeleton:
cell = self.skeletonCell(for: indexPath)
case .add(let presenter):
cell = self.addPaymentMethodCell(for: indexPath, presenter: presenter)
case .linked(let viewModel):
cell = self.linkedBankCell(for: indexPath, viewModel: viewModel)
}
case .switch(_, let presenter):
cell = self.switchCell(for: indexPath, presenter: presenter)
case .refferal(_, let viewModel):
cell = self.referralCell(for: indexPath, viewModel: viewModel)
}
cell.selectionStyle = .none
return cell
})
presenter.sectionObservable
.bindAndCatch(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView.rx
.modelSelected(SettingsCellViewModel.self)
.bindAndCatch(weak: self) { (self, model) in
model.recordSelection()
self.presenter.actionRelay.accept(model.action)
}
.disposed(by: disposeBag)
}
override public func navigationBarLeadingButtonPressed() {
presenter.navigationBarLeadingButtonTapped()
}
}
// MARK: - UITableViewDelegate, UITableViewDataSource
extension SettingsViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: TableHeaderView.objectName) as? TableHeaderView else {
return nil
}
let section = presenter.sectionArrangement[section]
let viewModel = TableHeaderViewModel.settings(title: section.sectionTitle)
header.viewModel = viewModel
return header
}
private func skeletonCell(for indexPath: IndexPath) -> SettingsSkeletonTableViewCell {
let cell = tableView.dequeue(SettingsSkeletonTableViewCell.self, for: indexPath)
return cell
}
private func switchCell(for indexPath: IndexPath, presenter: SwitchCellPresenting) -> SwitchTableViewCell {
let cell = tableView.dequeue(SwitchTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func clipboardCell(for indexPath: IndexPath, viewModel: ClipboardCellViewModel) -> ClipboardTableViewCell {
let cell = tableView.dequeue(ClipboardTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
private func commonCell(for indexPath: IndexPath, viewModel: CommonCellViewModel) -> CommonTableViewCell {
let cell = tableView.dequeue(CommonTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
private func addPaymentMethodCell(for indexPath: IndexPath, presenter: AddPaymentMethodCellPresenter) -> AddPaymentMethodTableViewCell {
let cell = tableView.dequeue(AddPaymentMethodTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func linkedCardCell(
for indexPath: IndexPath,
presenter: LinkedCardCellPresenter
) -> LinkedCardTableViewCell {
let cell = tableView.dequeue(LinkedCardTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func linkedBankCell(
for indexPath: IndexPath,
viewModel: BeneficiaryLinkedBankViewModel
) -> LinkedBankTableViewCell {
let cell = tableView.dequeue(LinkedBankTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
private func badgeCell(for indexPath: IndexPath, presenter: BadgeCellPresenting) -> BadgeTableViewCell {
let cell = tableView.dequeue(BadgeTableViewCell.self, for: indexPath)
cell.presenter = presenter
return cell
}
private func referralCell(
for indexPath: IndexPath,
viewModel: ReferralTableViewCellViewModel
) -> ReferralTableViewCell {
let cell = tableView.dequeue(ReferralTableViewCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
}
| lgpl-3.0 | 5b1e29f442f5100c2b8386a7ed1b09b5 | 37.531818 | 140 | 0.665212 | 5.454955 | false | false | false | false |
vamsirajendra/firefox-ios | ClientTests/MockProfile.swift | 2 | 4879 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
public class MockSyncManager: SyncManager {
public var isSyncing = false
public func syncClients() -> SyncResult { return deferMaybe(.Completed) }
public func syncClientsThenTabs() -> SyncResult { return deferMaybe(.Completed) }
public func syncHistory() -> SyncResult { return deferMaybe(.Completed) }
public func syncLogins() -> SyncResult { return deferMaybe(.Completed) }
public func syncEverything() -> Success {
return succeed()
}
public func beginTimedSyncs() {}
public func endTimedSyncs() {}
public func applicationDidBecomeActive() {
self.beginTimedSyncs()
}
public func applicationDidEnterBackground() {
self.endTimedSyncs()
}
public func onAddedAccount() -> Success {
return succeed()
}
public func onRemovedAccount(account: FirefoxAccount?) -> Success {
return succeed()
}
}
public class MockTabQueue: TabQueue {
public func addToQueue(tab: ShareItem) -> Success {
return succeed()
}
public func getQueuedTabs() -> Deferred<Maybe<Cursor<ShareItem>>> {
return deferMaybe(ArrayCursor<ShareItem>(data: []))
}
public func clearQueuedTabs() -> Success {
return succeed()
}
}
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
func shutdown() {
if dbCreated {
db.close()
}
}
private var dbCreated = false
lazy var db: BrowserDB = {
self.dbCreated = true
return BrowserDB(filename: "mock.db", files: self.files)
}()
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = {
return SQLiteHistory(db: self.db)!
}()
var favicons: Favicons {
return self.places
}
lazy var queue: TabQueue = {
return MockTabQueue()
}()
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> {
return self.places
}
lazy var syncManager: SyncManager = {
return MockSyncManager()
}()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
let p = self.places
return SQLiteBookmarks(db: self.db)
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
lazy var prefs: Prefs = {
return MockProfilePrefs()
}()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
internal lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
private lazy var syncCommands: SyncCommands = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = {
return MockLogins(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.None
}
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount) {
self.account = account
self.syncManager.onAddedAccount()
}
func removeAccount() {
let old = self.account
self.account = nil
self.syncManager.onRemovedAccount(old)
}
func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return deferMaybe([])
}
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return deferMaybe([])
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return deferMaybe(0)
}
func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
}
}
| mpl-2.0 | 11fa8d85c1c38dcbe21040792f55c9bf | 26.410112 | 126 | 0.652593 | 5.061203 | false | false | false | false |
keyOfVv/Cusp | CuspDemo/Classes/Scan+Connect+Subscribe/ConnectTableViewController.swift | 1 | 2620 | //
// ConnectTableViewController.swift
// Cusp
//
// Created by Ke Yang on 27/02/2017.
// Copyright © 2017 com.keyofvv. All rights reserved.
//
import UIKit
import Cusp
class ConnectTableViewController: UITableViewController {
var count = 0
var ad: Advertisement? {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Connect/Disconnect & Subscription"
tableView.register(UINib(nibName: "ScanTableViewCell", bundle: nil), forCellReuseIdentifier: ScanTableViewCellReuseID)
CuspCentral.default.scanForUUIDString(["FE90"], completion: { (ads) in
self.ad = ads.first
}, abruption: nil)
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int { return 1 }
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.ad == nil ? 0 : 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: ScanTableViewCellReuseID, for: indexPath) as! ScanTableViewCell
cell.advertisement = self.ad
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 }
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
recount()
tableView.deselectRow(at: indexPath, animated: true)
guard let peripheral = self.ad?.peripheral else { return }
switch peripheral.state {
case .disconnected:
CuspCentral.default.connect(peripheral, success: { (_) in
peripheral.subscribe(characteristic: "00008002-60B2-21F8-BCE3-94EEA697F98C",
ofService: "00008000-60B2-21F8-BCE3-94EEA697F98C",
success: { (_) in
dog("subscribed")
}, failure: nil, update: { (resp) in
self.count += 1
})
}, failure: nil, abruption: nil)
case .connected:
peripheral.unsubscribe(characteristic: "00008002-60B2-21F8-BCE3-94EEA697F98C",
ofService: "00008000-60B2-21F8-BCE3-94EEA697F98C",
success: { (_) in
dog("unsubscribed")
CuspCentral.default.disconnect(peripheral, completion: {
dog("diconnected")
})
}, failure: nil)
case .unknown:
dog("unknown state")
case .connecting:
dog("connecting")
}
}
func recount() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10.0) {
print(self.count)
self.count = 0
self.recount()
}
}
}
| mit | 9b069ccb59f07daed7e8c40cfe881886 | 29.811765 | 122 | 0.673921 | 3.704385 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Vender/Cheetah/Bezier.swift | 2 | 2183 | //
// Bezier.swift
// Cheetah
//
// Created by Suguru Namura on 2015/08/20.
// Copyright © 2015年 Suguru Namura.
//
// This implementation is based on WebCore Bezier implmentation
// http://opensource.apple.com/source/WebCore/WebCore-955.66/platform/graphics/UnitBezier.h
//
private let epsilon: CGFloat = 1.0 / 1000
struct UnitBezier {
var ax: CGFloat
var ay: CGFloat
var bx: CGFloat
var by: CGFloat
var cx: CGFloat
var cy: CGFloat
init(p1x: CGFloat, p1y: CGFloat, p2x: CGFloat, p2y: CGFloat) {
cx = 3 * p1x
bx = 3 * (p2x - p1x) - cx
ax = 1 - cx - bx
cy = 3 * p1y
by = 3 * (p2y - p1y) - cy
ay = 1.0 - cy - by
}
func sampleCurveX(_ t: CGFloat) -> CGFloat {
return ((ax * t + bx) * t + cx) * t
}
func sampleCurveY(_ t: CGFloat) -> CGFloat {
return ((ay * t + by) * t + cy) * t
}
func sampleCurveDerivativeX(_ t: CGFloat) -> CGFloat {
return (3.0 * ax * t + 2.0 * bx) * t + cx
}
func solveCurveX(_ x: CGFloat) -> CGFloat {
var t0, t1, t2, x2, d2: CGFloat
// Firstly try a few iterations of Newton's method -- normally very fast
t2 = x
for _ in 0..<8 {
x2 = sampleCurveX(t2) - x
if fabs(x2) < epsilon {
return t2
}
d2 = sampleCurveDerivativeX(t2)
if fabs(x2) < 1e-6 {
break
}
t2 = t2 - x2 / d2
}
// Fall back to the bisection method for reliability
t0 = 0
t1 = 1
t2 = x
if t2 < t0 {
return t0
}
if t2 > t1 {
return t1
}
while t0 < t1 {
x2 = sampleCurveX(t2)
if fabs(x2 - x) < epsilon {
return t2
}
if x > x2 {
t0 = t2
} else {
t1 = t2
}
t2 = (t1 - t0) * 0.5 + t0
}
// Failure
return t2
}
func solve(_ x: CGFloat) -> CGFloat {
return sampleCurveY(solveCurveX(x))
}
}
| mit | 1d4219f8849017066fa4c4cde266087a | 23.494382 | 91 | 0.455505 | 3.488 | false | false | false | false |
atuooo/GuttlerPageControl | Sources/PacmanPageControl.swift | 2 | 8250 | //
// PacmanPageControl.swift
// PacmanPageControl
//
// Copyright (c) 2017 oOatuo ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable
open class PacmanPageControl: UIView {
public enum DotColorStyle {
case same(UIColor)
case different([UIColor])
case random(hue: Hue, luminosity: Luminosity)
}
public enum PacmanColorStyle {
case fixed(UIColor)
case changeWithEatenDot
}
open var dotColorStyle: DotColorStyle = .random(hue: .random, luminosity: .light)
open var pacmanColorStyle: PacmanColorStyle = .changeWithEatenDot
@IBInspectable open var pacmanDiameter: CGFloat = 12
@IBInspectable open var dotDiameter: CGFloat = 5
@IBInspectable open var dotInterval: CGFloat = 0
@IBOutlet open var scrollView: UIScrollView? {
didSet {
guard oldValue !== scrollView else { return }
[#keyPath(UIScrollView.contentOffset)].forEach {
oldValue?.removeObserver(self, forKeyPath: $0)
scrollView?.addObserver(self, forKeyPath: $0, options: [.new, .old, .initial], context: nil)
}
if let newSV = scrollView {
pageCount = lroundf(Float(newSV.contentSize.width / newSV.frame.width))
}
}
}
open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
guard keyPath == #keyPath(UIScrollView.contentOffset), let scrlView = scrollView else { return }
scroll(with: scrlView)
}
open override func didMoveToSuperview() {
super.didMoveToSuperview()
isUserInteractionEnabled = false
setDotColors()
setSubLayers()
}
deinit {
scrollView?.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset))
}
#if TARGET_INTERFACE_BUILDER
open override func draw(_ rect: CGRect) {
setSubLayers()
}
open override func prepareForInterfaceBuilder() {
pageCount = 6
}
#endif
// MARK: - Private
private var pageCount: Int = 0 {
didSet {
guard oldValue != pageCount, superview != nil else { return }
setDotColors()
setSubLayers()
}
}
private var progress: CGFloat = 0
private var pacmanOriginX: CGFloat = 0
private var lastContentOffsetX: CGFloat = 0
private var dotColors: [UIColor] = []
private var dotLayers: [CAShapeLayer] = []
private lazy var pacmanLayer: PacmanLayer = {
return PacmanLayer()
}()
private func scroll(with scrollView: UIScrollView) {
let svOffsetX = scrollView.contentOffset.x
let svWidth = scrollView.frame.width
progress = svOffsetX / svWidth
let checkCount = lroundf(Float(scrollView.contentSize.width / svWidth))
guard checkCount == pageCount, checkCount > 0 else { return pageCount = checkCount }
if lastContentOffsetX < svOffsetX {
pacmanLayer.direction = .right
} else if lastContentOffsetX > svOffsetX {
pacmanLayer.direction = .left
}
let offset = abs(fmodf(Float(svOffsetX), Float(svWidth)))
let factor = max(0, CGFloat(offset)/svWidth)
if factor == 0 {
lastContentOffsetX = svOffsetX
if case .changeWithEatenDot = pacmanColorStyle {
pacmanLayer.color = dotColors[Int(progress)]
}
}
CATransaction.begin()
CATransaction.setDisableActions(true)
pacmanLayer.position.x = pacmanOriginX + pacmanDiameter / 2 + progress * (dotDiameter + dotInterval)
CATransaction.commit()
pacmanLayer.factor = CGFloat(factor)
for (index, layer) in dotLayers.enumerated() {
setDotLayer(layer, at: index)
}
}
private func setDotColors() {
guard pageCount != 0 else { return dotColors.removeAll() }
switch dotColorStyle {
case .same(let color):
dotColors = Array(repeating: color, count: pageCount)
case .different(let colors):
if colors.isEmpty {
let defaultColor = UIColor(red: 0.94, green: 0.72, blue: 0.3, alpha: 1)
dotColors = Array.init(repeating: defaultColor, count: pageCount)
} else {
(0 ..< (pageCount / colors.count)).forEach { _ in
dotColors.append(contentsOf: colors)
}
dotColors.append(contentsOf: colors.prefix(pageCount % colors.count))
}
case .random(let hue, let luminosity):
dotColors = randomColors(count: pageCount, hue: hue, luminosity: luminosity)
}
}
private func setSubLayers() {
dotLayers.forEach { $0.removeFromSuperlayer() }
pacmanLayer.removeFromSuperlayer()
guard pageCount != 0 else { return }
if dotInterval <= 0 {
dotInterval = dotDiameter * 1.2
}
let dotTotalWidth = dotDiameter * CGFloat(pageCount) + dotInterval * CGFloat(pageCount - 1)
let dotOriginY = (frame.height - dotDiameter) / 2
let dotOriginX = (frame.width - dotTotalWidth) / 2
pacmanOriginX = dotOriginX + dotDiameter / 2 - pacmanDiameter / 2
var dotFrame = CGRect(x: dotOriginX, y: dotOriginY, width: dotDiameter, height: dotDiameter)
dotLayers = (0..<pageCount).map { index in
let dot = CAShapeLayer()
dot.frame = dotFrame
dot.fillColor = dotColors[index].cgColor
dotFrame.origin.x += dotDiameter + dotInterval
setDotLayer(dot, at: index)
layer.addSublayer(dot)
return dot
}
let oriX = pacmanOriginX + progress * (dotDiameter + dotInterval)
pacmanLayer.frame = CGRect(x: oriX, y: (frame.height - pacmanDiameter) / 2, width: pacmanDiameter, height: pacmanDiameter)
pacmanLayer.contentsScale = UIScreen.main.scale
if case let .fixed(color) = pacmanColorStyle {
pacmanLayer.color = color
} else {
pacmanLayer.color = dotColors[min(0, Int(progress))]
}
layer.addSublayer(pacmanLayer)
pacmanLayer.setNeedsDisplay()
}
private func setDotLayer(_ dotLayer: CAShapeLayer, at index: Int) {
guard progress >= 0 && progress <= CGFloat(pageCount - 1) else { return }
let originRect = CGRect(x: 0, y: 0, width: dotDiameter, height: dotDiameter)
let offset = abs(progress - CGFloat(index))
let x = min(1, offset)
let insetDis = dotDiameter / 2 * (x * x - 2 * x + 1)
let scaleRect = originRect.insetBy(dx: insetDis, dy: insetDis)
dotLayer.path = UIBezierPath(ovalIn: scaleRect).cgPath
}
}
| mit | 444a13685e0dd4b28265b5777298c708 | 35.666667 | 156 | 0.609697 | 4.763279 | false | false | false | false |
rafaelstz/firefox-ios | Client/Frontend/Browser/URLBarView.swift | 2 | 31018 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import SnapKit
private struct URLBarViewUX {
static let TextFieldBorderColor = UIColor(rgb: 0xBBBBBB)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let TextFieldContentInset = UIOffsetMake(9, 5)
static let LocationLeftPadding = 5
static let LocationHeight = 28
static let LocationContentOffset: CGFloat = 8
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
static let TabsButtonRotationOffset: CGFloat = 1.5
static let TabsButtonHeight: CGFloat = 18.0
static let ToolbarButtonInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
static func backgroundColorWithAlpha(alpha: CGFloat) -> UIColor {
return UIConstants.AppBackgroundColor.colorWithAlphaComponent(alpha)
}
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
/// :returns: whether the long-press was handled by the delegate; i.e. return `false` when the conditions for even starting handling long-press were not satisfied
func urlBarDidLongPressReaderMode(urlBar: URLBarView) -> Bool
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidEnterOverlayMode(urlBar: URLBarView)
func urlBarDidLeaveOverlayMode(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBarLocationAccessibilityActions(urlBar: URLBarView) -> [UIAccessibilityCustomAction]?
func urlBarDidPressScrollToTop(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView {
weak var delegate: URLBarDelegate?
weak var browserToolbarDelegate: BrowserToolbarDelegate?
var helper: BrowserToolbarHelper?
var toolbarIsShowing = false
/// Overlay mode is the state where the lock/reader icons are hidden, the home panels are shown,
/// and the Cancel button is visible (allowing the user to leave overlay mode). Overlay mode
/// is *not* tied to the location text field's editing state; for instance, when selecting
/// a panel, the first responder will be resigned, yet the overlay mode UI is still active.
var inOverlayMode = false
var backButtonLeftConstraint: Constraint?
lazy var locationView: BrowserLocationView = {
let locationView = BrowserLocationView()
locationView.setTranslatesAutoresizingMaskIntoConstraints(false)
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
return locationView
}()
private lazy var locationTextField: ToolbarTextField = {
let locationTextField = ToolbarTextField()
locationTextField.setTranslatesAutoresizingMaskIntoConstraints(false)
locationTextField.autocompleteDelegate = self
locationTextField.keyboardType = UIKeyboardType.WebSearch
locationTextField.autocorrectionType = UITextAutocorrectionType.No
locationTextField.autocapitalizationType = UITextAutocapitalizationType.None
locationTextField.returnKeyType = UIReturnKeyType.Go
locationTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
locationTextField.backgroundColor = UIColor.whiteColor()
locationTextField.font = UIConstants.DefaultMediumFont
locationTextField.isAccessibilityElement = true
// locationTextField.accessibilityActionsSource = self
locationTextField.accessibilityIdentifier = "address"
locationTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationTextField.attributedPlaceholder = self.locationView.placeholder
return locationTextField
}()
private lazy var locationContainer: UIView = {
let locationContainer = UIView()
locationContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
// Enable clipping to apply the rounded edges to subviews.
locationContainer.clipsToBounds = true
locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
return locationContainer
}()
private lazy var tabsButton: UIButton = {
let tabsButton = InsetButton()
tabsButton.setTranslatesAutoresizingMaskIntoConstraints(false)
tabsButton.setTitle("0", forState: UIControlState.Normal)
tabsButton.setTitleColor(URLBarViewUX.backgroundColorWithAlpha(1), forState: UIControlState.Normal)
tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 2
tabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the tabs button in the browser toolbar")
return tabsButton
}()
private lazy var progressBar: UIProgressView = {
let progressBar = UIProgressView()
progressBar.progressTintColor = UIColor(red:1, green:0.32, blue:0, alpha:1)
progressBar.alpha = 0
progressBar.hidden = true
return progressBar
}()
private lazy var cancelButton: UIButton = {
let cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = UIConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
return cancelButton
}()
private lazy var curveShape: CurveView = { return CurveView() }()
private lazy var scrollToTopButton: UIButton = {
let button = UIButton()
button.addTarget(self, action: "SELtappedScrollToTopArea", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
lazy var shareButton: UIButton = { return UIButton() }()
lazy var bookmarkButton: UIButton = { return UIButton() }()
lazy var forwardButton: UIButton = { return UIButton() }()
lazy var backButton: UIButton = { return UIButton() }()
lazy var stopReloadButton: UIButton = { return UIButton() }()
lazy var actionButtons: [UIButton] = {
return [self.shareButton, self.bookmarkButton, self.forwardButton, self.backButton, self.stopReloadButton]
}()
// Used to temporarily store the cloned button so we can respond to layout changes during animation
private weak var clonedTabsButton: InsetButton?
private var rightBarConstraint: Constraint?
private let defaultRightOffset: CGFloat = URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer
var currentURL: NSURL? {
get {
return locationView.url
}
set(newURL) {
locationView.url = newURL
}
}
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = URLBarViewUX.backgroundColorWithAlpha(0)
addSubview(curveShape)
addSubview(scrollToTopButton)
locationContainer.addSubview(locationView)
locationContainer.addSubview(locationTextField)
addSubview(locationContainer)
addSubview(progressBar)
addSubview(tabsButton)
addSubview(cancelButton)
addSubview(shareButton)
addSubview(bookmarkButton)
addSubview(forwardButton)
addSubview(backButton)
addSubview(stopReloadButton)
helper = BrowserToolbarHelper(toolbar: self)
setupConstraints()
// Make sure we hide any views that shouldn't be showing in non-overlay mode.
updateViewsForOverlayModeAndToolbarChanges()
}
private func setupConstraints() {
scrollToTopButton.snp_makeConstraints { make in
make.top.equalTo(self)
make.left.right.equalTo(self.locationContainer)
}
progressBar.snp_makeConstraints { make in
make.top.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_makeConstraints { make in
make.edges.equalTo(self.locationContainer)
}
cancelButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
tabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.width.height.equalTo(UIConstants.ToolbarHeight)
}
curveShape.snp_makeConstraints { make in
make.top.left.bottom.equalTo(self)
self.rightBarConstraint = make.right.equalTo(self).constraint
self.rightBarConstraint?.updateOffset(defaultRightOffset)
}
locationTextField.snp_makeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
remakeLocationContainerConstraints()
}
private func updateToolbarConstraints() {
if toolbarIsShowing {
backButton.snp_remakeConstraints { (make) -> () in
self.backButtonLeftConstraint = make.left.equalTo(self).constraint
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
backButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
forwardButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.backButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
forwardButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
stopReloadButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.forwardButton.snp_right)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
stopReloadButton.contentEdgeInsets = URLBarViewUX.ToolbarButtonInsets
shareButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.bookmarkButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
bookmarkButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.tabsButton.snp_left)
make.centerY.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
}
}
override func updateConstraints() {
updateToolbarConstraints()
remakeLocationContainerConstraints()
super.updateConstraints()
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
updateViewsForOverlayModeAndToolbarChanges()
}
func updateAlphaForSubviews(alpha: CGFloat) {
self.tabsButton.alpha = alpha
self.locationContainer.alpha = alpha
self.backgroundColor = URLBarViewUX.backgroundColorWithAlpha(1 - alpha)
self.actionButtons.map { $0.alpha = alpha }
}
func updateTabCount(count: Int) {
// make a 'clone' of the tabs button
let newTabsButton = InsetButton()
self.clonedTabsButton = newTabsButton
newTabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
newTabsButton.setTitleColor(UIConstants.AppBackgroundColor, forState: UIControlState.Normal)
newTabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
newTabsButton.titleLabel?.layer.cornerRadius = 2
newTabsButton.titleLabel?.font = UIConstants.DefaultSmallFontBold
newTabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
newTabsButton.setTitle(count.description, forState: .Normal)
addSubview(newTabsButton)
newTabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(URLBarViewUX.TabsButtonHeight)
}
newTabsButton.snp_makeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.size.equalTo(UIConstants.ToolbarHeight)
}
newTabsButton.frame = tabsButton.frame
// Instead of changing the anchorPoint of the CALayer, lets alter the rotation matrix math to be
// a rotation around a non-origin point
if let labelFrame = newTabsButton.titleLabel?.frame {
let halfTitleHeight = CGRectGetHeight(labelFrame) / 2
var newFlipTransform = CATransform3DIdentity
newFlipTransform = CATransform3DTranslate(newFlipTransform, 0, halfTitleHeight, 0)
newFlipTransform.m34 = -1.0 / 200.0 // add some perspective
newFlipTransform = CATransform3DRotate(newFlipTransform, CGFloat(-M_PI_2), 1.0, 0.0, 0.0)
newTabsButton.titleLabel?.layer.transform = newFlipTransform
var oldFlipTransform = CATransform3DIdentity
oldFlipTransform = CATransform3DTranslate(oldFlipTransform, 0, halfTitleHeight, 0)
oldFlipTransform.m34 = -1.0 / 200.0 // add some perspective
oldFlipTransform = CATransform3DRotate(oldFlipTransform, CGFloat(M_PI_2), 1.0, 0.0, 0.0)
UIView.animateWithDuration(1.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { _ in
newTabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.titleLabel?.layer.transform = oldFlipTransform
self.tabsButton.titleLabel?.layer.opacity = 0
}, completion: { _ in
// remove the clone and setup the actual tab button
newTabsButton.removeFromSuperview()
self.tabsButton.titleLabel?.layer.opacity = 1
self.tabsButton.titleLabel?.layer.transform = CATransform3DIdentity
self.tabsButton.setTitle(count.description, forState: UIControlState.Normal)
self.tabsButton.accessibilityValue = count.description
self.tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
})
}
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { _ in
self.progressBar.setProgress(0.0, animated: false)
})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress))
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func setAutocompleteSuggestion(suggestion: String?) {
locationTextField.setAutocompleteSuggestion(suggestion)
}
func enterOverlayMode(locationText: String?, pasted: Bool) {
if pasted {
// Clear any existing text, focus the field, then set the actual pasted text.
// This avoids highlighting all of the text.
locationTextField.text = ""
locationTextField.becomeFirstResponder()
locationTextField.text = locationText
} else {
// Copy the current URL to the editable text field, then activate it.
locationTextField.text = locationText
locationTextField.becomeFirstResponder()
}
// Show the overlay mode UI, which includes hiding the locationView and replacing it
// with the editable locationTextField.
animateToOverlayState(true)
delegate?.urlBarDidEnterOverlayMode(self)
}
func leaveOverlayMode() {
locationTextField.resignFirstResponder()
animateToOverlayState(false)
delegate?.urlBarDidLeaveOverlayMode(self)
}
func remakeLocationContainerConstraints() {
if inOverlayMode {
// In overlay mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.left.equalTo(self.stopReloadButton.snp_right)
make.right.equalTo(self.shareButton.snp_left)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self)
}
}
}
func prepareOverlayAnimation() {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.cancelButton.hidden = false
self.progressBar.hidden = false
self.locationTextField.hidden = false
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
}
func transitionToOverlay() {
self.cancelButton.alpha = inOverlayMode ? 1 : 0
self.progressBar.alpha = inOverlayMode ? 0 : 1
self.locationTextField.alpha = inOverlayMode ? 1 : 0
self.shareButton.alpha = inOverlayMode ? 0 : 1
self.bookmarkButton.alpha = inOverlayMode ? 0 : 1
self.forwardButton.alpha = inOverlayMode ? 0 : 1
self.backButton.alpha = inOverlayMode ? 0 : 1
self.stopReloadButton.alpha = inOverlayMode ? 0 : 1
let borderColor = inOverlayMode ? URLBarViewUX.TextFieldActiveBorderColor : URLBarViewUX.TextFieldBorderColor
locationContainer.layer.borderColor = borderColor.CGColor
if inOverlayMode {
self.cancelButton.transform = CGAffineTransformIdentity
let tabsButtonTransform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.tabsButton.transform = tabsButtonTransform
self.clonedTabsButton?.transform = tabsButtonTransform
self.rightBarConstraint?.updateOffset(URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer + tabsButton.frame.width)
if self.toolbarIsShowing {
self.backButtonLeftConstraint?.updateOffset(-3 * UIConstants.ToolbarHeight)
}
// Make the editable text field span the entire URL bar, covering the lock and reader icons.
self.locationTextField.snp_remakeConstraints { make in
make.leading.equalTo(self.locationContainer).offset(URLBarViewUX.LocationContentOffset)
make.top.bottom.trailing.equalTo(self.locationContainer)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.clonedTabsButton?.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.rightBarConstraint?.updateOffset(defaultRightOffset)
if self.toolbarIsShowing {
self.backButtonLeftConstraint?.updateOffset(0)
}
// Shrink the editable text field back to the size of the location view before hiding it.
self.locationTextField.snp_remakeConstraints { make in
make.edges.equalTo(self.locationView.urlTextField)
}
}
}
func updateViewsForOverlayModeAndToolbarChanges() {
self.cancelButton.hidden = !inOverlayMode
self.progressBar.hidden = inOverlayMode
self.locationTextField.hidden = !inOverlayMode
self.shareButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.bookmarkButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.forwardButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.backButton.hidden = !self.toolbarIsShowing || inOverlayMode
self.stopReloadButton.hidden = !self.toolbarIsShowing || inOverlayMode
}
func animateToOverlayState(overlay: Bool) {
prepareOverlayAnimation()
layoutIfNeeded()
inOverlayMode = overlay
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: nil, animations: { _ in
self.transitionToOverlay()
self.setNeedsUpdateConstraints()
self.layoutIfNeeded()
}, completion: { _ in
self.updateViewsForOverlayModeAndToolbarChanges()
})
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func SELdidClickCancel() {
leaveOverlayMode()
}
func SELtappedScrollToTopArea() {
delegate?.urlBarDidPressScrollToTop(self)
}
}
extension URLBarView: BrowserToolbarProtocol {
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateForwardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
func updatePageStatus(#isWebPage: Bool) {
bookmarkButton.enabled = isWebPage
stopReloadButton.enabled = isWebPage
shareButton.enabled = isWebPage
}
override var accessibilityElements: [AnyObject]! {
get {
if inOverlayMode {
return [locationTextField, cancelButton]
} else {
if toolbarIsShowing {
return [backButton, forwardButton, stopReloadButton, locationView, shareButton, bookmarkButton, tabsButton, progressBar]
} else {
return [locationView, tabsButton, progressBar]
}
}
}
set {
super.accessibilityElements = newValue
}
}
}
extension URLBarView: BrowserLocationViewDelegate {
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) -> Bool {
return delegate?.urlBarDidLongPressReaderMode(self) ?? false
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
enterOverlayMode(locationView.url?.absoluteString, pasted: false)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewLocationAccessibilityActions(browserLocationView: BrowserLocationView) -> [UIAccessibilityCustomAction]? {
return delegate?.urlBarLocationAccessibilityActions(self)
}
}
extension URLBarView: AutocompleteTextFieldDelegate {
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didSubmitText: locationTextField.text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didEnterText text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
autocompleteTextField.highlightAll()
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
private lazy var leftCurvePath: UIBezierPath = {
var leftArc = UIBezierPath(arcCenter: CGPoint(x: 5, y: 5), radius: CGFloat(5), startAngle: CGFloat(-M_PI), endAngle: CGFloat(-M_PI_2), clockwise: true)
leftArc.addLineToPoint(CGPoint(x: 0, y: 0))
leftArc.addLineToPoint(CGPoint(x: 0, y: 5))
leftArc.closePath()
return leftArc
}()
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
self.opaque = false
self.contentMode = .Redraw
}
private func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
private func drawFromTop(path: UIBezierPath) {
let height: Double = Double(UIConstants.ToolbarHeight)
let width = getWidthForHeight(height)
var from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(0))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: UIConstants.ToolbarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: 0))
path.addLineToPoint(CGPoint(x: 0, y: 0))
path.closePath()
return path
}
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
CGContextClearRect(context, rect)
CGContextSetFillColorWithColor(context, URLBarViewUX.backgroundColorWithAlpha(1).CGColor)
getPath().fill()
leftCurvePath.fill()
CGContextDrawPath(context, kCGPathFill)
CGContextRestoreGState(context)
}
}
private class ToolbarTextField: AutocompleteTextField {
weak var accessibilityActionsSource: AccessibilityActionsSource?
override var accessibilityCustomActions: [AnyObject]! {
get {
if !editing {
return accessibilityActionsSource?.accessibilityCustomActionsForView(self)
}
return super.accessibilityCustomActions
}
set {
super.accessibilityCustomActions = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mpl-2.0 | dc0a1b4b0f13e1418d516955ee92abe9 | 40.634899 | 198 | 0.683829 | 5.564765 | false | false | false | false |
BalestraPatrick/HomeKitty | Sources/App/Models/Manufacturer.swift | 1 | 1084 | //
// Copyright © 2018 HomeKitty. All rights reserved.
//
import Vapor
import FluentPostgreSQL
final class Manufacturer: PostgreSQLModel {
typealias ID = Int
static var entity = "manufacturer"
var id: Int?
var name: String
var websiteLink: String
var approved = false
init(name: String, websiteLink: String) {
self.name = name
self.websiteLink = websiteLink
self.approved = false
}
enum CodingKeys: String, CodingKey {
case id
case name
case websiteLink = "website_link"
case approved
}
}
// MARK: - Database Migration
extension Manufacturer: PostgreSQLMigration {
static func prepare(on connection: PostgreSQLConnection) -> Future<Void> {
return Database.create(self, on: connection, closure: { builder in
builder.field(for: \Manufacturer.id, type: .int, .primaryKey())
builder.field(for: \Manufacturer.name)
builder.field(for: \Manufacturer.websiteLink)
builder.field(for: \Manufacturer.approved)
})
}
}
| mit | c38f823e4bf3175d0ace96602de7aedc | 24.186047 | 78 | 0.642659 | 4.366935 | false | false | false | false |
cxy921126/SoftSwift | SoftSwift/SoftSwift/BaseViewController.swift | 1 | 1172 | //
// BaseViewController.swift
// SoftSwift
//
// Created by Mac mini on 16/3/5.
// Copyright © 2016年 XMU. All rights reserved.
//
import UIKit
class BaseViewController: UITableViewController, UnloginViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
unloginView.delegate = self
if isLogin{
tableView.separatorStyle = .None
}
}
//MARK: - 根据登录状态初始化view
override func loadView() {
isLogin ? super.loadView():setUnloginView()
}
//MARK: - 未登录View设为属性
lazy var unloginView:UnloginView = {
let thisView = NSBundle.mainBundle().loadNibNamed("UnloginView", owner: self, options: nil).last as! UnloginView
return thisView
}()
func setUnloginView(){
view = unloginView
}
//MARK: - 实现UnloginViewDelegate代理方法
func presentSignUp() {
}
func presentLogin() {
let oauthCtr = OAuthViewController()
let navCtr = UINavigationController(rootViewController: oauthCtr)
presentViewController(navCtr, animated: true, completion: nil)
}
}
| mit | d09a5c7e4f3ff6be0fa054f324f85ffd | 23.456522 | 120 | 0.632 | 4.518072 | false | false | false | false |
prey/prey-ios-client | Prey/Swifter/HttpResponse.swift | 1 | 6358 | //
// HttpResponse.swift
// Swifter
//
// Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
//
import Foundation
public enum SerializationError: Error {
case invalidObject
case notSupported
}
public protocol HttpResponseBodyWriter {
func write(_ file: String.File) throws
func write(_ data: [UInt8]) throws
func write(_ data: ArraySlice<UInt8>) throws
func write(_ data: NSData) throws
func write(_ data: Data) throws
}
public enum HttpResponseBody {
case json(AnyObject)
case html(String)
case text(String)
case data(Data)
case custom(Any, (Any) throws -> String)
func content() -> (Int, ((HttpResponseBodyWriter) throws -> Void)?) {
do {
switch self {
case .json(let object):
#if os(Linux)
let data = [UInt8]("Not ready for Linux.".utf8)
return (data.count, {
try $0.write(data)
})
#else
guard JSONSerialization.isValidJSONObject(object) else {
throw SerializationError.invalidObject
}
let data = try JSONSerialization.data(withJSONObject: object)
return (data.count, {
try $0.write(data)
})
#endif
case .text(let body):
let data = [UInt8](body.utf8)
return (data.count, {
try $0.write(data)
})
case .html(let body):
let serialised = "<html><meta charset=\"UTF-8\"><body>\(body)</body></html>"
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
case .data(let data):
return (data.count, {
try $0.write(data)
})
case .custom(let object, let closure):
let serialised = try closure(object)
let data = [UInt8](serialised.utf8)
return (data.count, {
try $0.write(data)
})
}
} catch {
let data = [UInt8]("Serialisation error: \(error)".utf8)
return (data.count, {
try $0.write(data)
})
}
}
}
// swiftlint:disable cyclomatic_complexity
public enum HttpResponse {
case switchProtocols([String: String], (Socket) -> Void)
case ok(HttpResponseBody), created, accepted
case movedPermanently(String)
case movedTemporarily(String)
case badRequest(HttpResponseBody?), unauthorized, forbidden, notFound
case internalServerError
case raw(Int, String, [String:String]?, ((HttpResponseBodyWriter) throws -> Void)? )
func statusCode() -> Int {
switch self {
case .switchProtocols : return 101
case .ok : return 200
case .created : return 201
case .accepted : return 202
case .movedPermanently : return 301
case .movedTemporarily : return 307
case .badRequest : return 400
case .unauthorized : return 401
case .forbidden : return 403
case .notFound : return 404
case .internalServerError : return 500
case .raw(let code, _, _, _) : return code
}
}
func reasonPhrase() -> String {
switch self {
case .switchProtocols : return "Switching Protocols"
case .ok : return "OK"
case .created : return "Created"
case .accepted : return "Accepted"
case .movedPermanently : return "Moved Permanently"
case .movedTemporarily : return "Moved Temporarily"
case .badRequest : return "Bad Request"
case .unauthorized : return "Unauthorized"
case .forbidden : return "Forbidden"
case .notFound : return "Not Found"
case .internalServerError : return "Internal Server Error"
case .raw(_, let phrase, _, _) : return phrase
}
}
func headers() -> [String: String] {
var headers = ["Server": "Swifter \(HttpServer.VERSION)"]
switch self {
case .switchProtocols(let switchHeaders, _):
for (key, value) in switchHeaders {
headers[key] = value
}
case .ok(let body):
switch body {
case .json: headers["Content-Type"] = "application/json"
case .html: headers["Content-Type"] = "text/html"
default:break
}
case .movedPermanently(let location):
headers["Location"] = location
case .movedTemporarily(let location):
headers["Location"] = location
case .raw(_, _, let rawHeaders, _):
if let rawHeaders = rawHeaders {
for (key, value) in rawHeaders {
headers.updateValue(value, forKey: key)
}
}
default:break
}
return headers
}
func content() -> (length: Int, write: ((HttpResponseBodyWriter) throws -> Void)?) {
switch self {
case .ok(let body) : return body.content()
case .badRequest(let body) : return body?.content() ?? (-1, nil)
case .raw(_, _, _, let writer) : return (-1, writer)
default : return (-1, nil)
}
}
func socketSession() -> ((Socket) -> Void)? {
switch self {
case .switchProtocols(_, let handler) : return handler
default: return nil
}
}
}
/**
Makes it possible to compare handler responses with '==', but
ignores any associated values. This should generally be what
you want. E.g.:
let resp = handler(updatedRequest)
if resp == .NotFound {
print("Client requested not found: \(request.url)")
}
*/
func == (inLeft: HttpResponse, inRight: HttpResponse) -> Bool {
return inLeft.statusCode() == inRight.statusCode()
}
| gpl-3.0 | b2b99065114068b2e4af238a4eda61e3 | 33.737705 | 92 | 0.514236 | 4.81956 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | byuSuite/Classes/Reusable/UI/Buildings/CampusBuildingsMapViewController2.swift | 2 | 3239 | //
// CampusBuildingsMapViewController2.swift
// byuSuite
//
// Created by Erik Brady on 4/11/18.
// Copyright © 2018 Brigham Young University. All rights reserved.
//
private let SELECTOR_DELAY = 1.25
private let BUILDING_DETAIL_SEGUE_ID = "showBuildingDetail"
class CampusBuildingsMapViewController2: ByuMapViewController2, CLLocationManagerDelegate {
//MARK: Public Properties
var building: CampusBuilding2?
var showDetailDisclosureButton = true
//MARK: Private Properties
private var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
//If no title was provided by the previous view, set the title to the building's acronym
if title == nil, let building = building {
title = building.acronym
}
/*
Calls the function that shows the callout of the current building after a delay.
If the callout is shown too early, before the map has finished zooming in to the right level, and the callout has a lot of text, the screen cuts it off because it's not centered for the zoomed-in map.
*/
perform(#selector(selectBuildingAnnotation), with: nil, afterDelay: SELECTOR_DELAY)
configureLocationManager()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let building = building {
mapView.addAnnotation(building)
zoomToFitMapAnnotations(includeUserLocation: false, keepByuInFrame: false)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
locationManager.stopUpdatingLocation()
}
deinit {
mapView.delegate = nil
locationManager.delegate = nil
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == BUILDING_DETAIL_SEGUE_ID, let vc = segue.destination as? CampusBuildingsDetailViewController2 {
vc.building = building
}
}
//MARK: CLLocationManagerDelegate Methods
//This method is called every time this view controller loads, even if the user's authorization status didn't change
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
//User has authorized feature to use location services
locationManager.startUpdatingLocation()
mapView.showsUserLocation = true
} else {
mapView.showsUserLocation = false
}
}
//MARK: MKMapViewDelegate Methods
func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
mapView.deselectAnnotation(view.annotation, animated: true)
performSegue(withIdentifier: BUILDING_DETAIL_SEGUE_ID, sender: nil)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
return mapView.defaultBuildingAnnotationView(annotation: annotation, displayDetailDisclosureButton: showDetailDisclosureButton)
}
//MARK: Custom Methods
private func configureLocationManager() {
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
@objc func selectBuildingAnnotation() {
if let building = building {
mapView.selectAnnotation(building, animated: true)
}
}
}
| apache-2.0 | b7b458215276cdd631f876ce8edee87f | 30.436893 | 202 | 0.764052 | 4.411444 | false | false | false | false |
LukaszLiberda/Swift-Design-Patterns | PatternProj/Structural/FacadePattern.swift | 1 | 5061 | //
// FacadePattern.swift
// PatternProj
//
// Created by lukaszliberda on 06.07.2015.
// Copyright (c) 2015 lukasz. All rights reserved.
//
import Foundation
/*
The facade pattern is used to define a simplified interface to a more complex subsystem.
The facade pattern (or façade pattern) is a software design pattern commonly used with object-oriented programming. The name is by analogy to an architectural facade.
A facade is an object that provides a simplified interface to a larger body of code, such as a class library. A facade can:
make a software library easier to use, understand and test, since the facade has convenient methods for common tasks;
make the library more readable, for the same reason;
reduce dependencies of outside code on the inner workings of a library, since most code uses the facade, thus allowing more flexibility in developing the system;
wrap a poorly designed collection of APIs with a single well-designed API (as per task needs).
The Facade design pattern is often used when a system is very complex or difficult to understand because the system has a large number of interdependent classes or its source code is unavailable. This pattern hides the complexities of the larger system and provides a simpler interface to the client. It typically involves a single wrapper class which contains a set of members required by client. These members access the system on behalf of the facade client and hide the implementation details.
*/
class Eternal {
class func setObject(value: AnyObject!, forKey defaultName: String!) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(value, forKey: defaultName)
defaults.synchronize()
}
class func objectForKey(defaultName: String!) -> AnyObject! {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
return defaults.objectForKey(defaultName)
}
}
/*
usage
*/
class TestFacade {
func test() {
Eternal.setObject("Disconnect me. I'd rather be nothing", forKey: "Bishop")
Eternal.objectForKey("Bishop")
println()
}
func test2() {
println()
var line1: Line = Line(ori: Point(xx: 2, yy: 4), end: Point(xx: 5, yy: 7))
line1.move(-2, dy: -4)
println("after move: \(line1.toString())")
line1.rotate(45)
println("after rotate: \(line1.toString())")
var line2: Line = Line(ori: Point(xx: 2, yy: 1), end: Point(xx: 2.866, yy: 1.5))
line2.rotate(30)
println("30 degrees to 60 degrees \(line2.toString())")
println()
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class PointCarte {
var x, y : Double
init(xx: Double, yy: Double) {
x = xx
y = yy
}
func move(#dx: Int, dy: Int) {
x += Double(dx)
y += Double(dy)
}
func toStrinng() -> String {
return "\(x), \(y)"
}
}
class PointPolar {
var radius, angle: Double
init(r: Double, a: Double) {
radius = r
angle = a
}
func rotate(ang: Int) {
angle += Double(ang % 360)
}
func toString() -> String {
return "[\(radius)@\(angle)]"
}
}
class Point {
var pc: PointCarte
init(xx: Double, yy: Double) {
pc = PointCarte(xx: xx, yy: yy)
}
func toString() -> String {
return pc.toStrinng()
}
func move(#dx: Int, dy: Int) {
pc.move(dx: dx, dy: dy)
}
func rotate(angle: Int, o: Point) {
var x = pc.x - o.pc.x
var y = pc.y - o.pc.y
var pp: PointPolar = PointPolar(r: sqrt(x*x+y*y), a: atan2(x, y)*180 / M_PI)
pp.rotate(angle)
println("Point polar is \(pp.toString())")
var str = pp.toString()
var i = str.rangeOfString("@")!.startIndex
var i1 = advance(str.startIndex, 1)
var i2 = advance(str.rangeOfString("]")!.startIndex, -1)
var rg: Range = Range(start:i1, end:i)
var rg2: Range = Range(start:advance(i, 1), end:i2)
var r: Double = str.substringWithRange(rg).toDouble()!
var a: Double = str.substringWithRange(rg2).toDouble()!
pc = PointCarte(xx: r * cos(a * M_PI / 180) + o.pc.x , yy: r * sin(a * M_PI / 180) + o.pc.y)
}
}
class Line {
var o, e: Point
init(ori: Point, end: Point) {
o = ori
e = end
}
func move(dx: Int, dy: Int) {
o.move(dx: dx, dy: dy)
e.move(dx: dx, dy: dy)
}
func rotate(angle: Int) {
e.rotate(angle, o: o)
}
func toString() -> String {
return "origin is \(o.toString()), end is \(e.toString())"
}
}
extension String {
func toDouble() -> Double? {
return NSNumberFormatter().numberFromString(self)?.doubleValue
}
}
| gpl-2.0 | 1be35ea2aa8f3e684bbdb21313ee5da4 | 23.095238 | 497 | 0.58498 | 3.946958 | false | false | false | false |
qvacua/vimr | NvimView/Sources/NvimView/NvimView+Objects.swift | 1 | 1445 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import RxPack
import RxNeovim
public extension NvimView {
struct Buffer: Equatable {
public static func == (lhs: Buffer, rhs: Buffer) -> Bool {
guard lhs.handle == rhs.handle else { return false }
// Transient buffer active -> open a file -> the resulting buffer has the same handle,
// but different URL
return lhs.url == rhs.url
}
public let apiBuffer: RxNeovimApi.Buffer
public let url: URL?
public let type: String
public let isDirty: Bool
public let isCurrent: Bool
public let isListed: Bool
public var isTransient: Bool {
if self.isDirty { return false }
if self.url != nil { return false }
return true
}
public var name: String? {
if self.type == "quickfix" { return "Quickfix" }
return self.url?.lastPathComponent
}
public var handle: Int { self.apiBuffer.handle }
}
struct Window {
public let apiWindow: RxNeovimApi.Window
public let buffer: Buffer
public let isCurrentInTab: Bool
public var handle: Int { self.apiWindow.handle }
}
struct Tabpage {
public let apiTabpage: RxNeovimApi.Tabpage
public let windows: [Window]
public let isCurrent: Bool
public var currentWindow: Window? { self.windows.first { $0.isCurrentInTab } }
public var handle: Int { self.apiTabpage.handle }
}
}
| mit | 378a29e17922e296fe60692569906b4d | 22.688525 | 92 | 0.658131 | 4.070423 | false | false | false | false |
ncalexan/mentat | sdks/swift/Mentat/Mentat/Query/RelResult.swift | 3 | 2942 | /* Copyright 2018 Mozilla
*
* 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 MentatStore
/**
Wraps a `Rel` result from a Mentat query.
A `Rel` result is a list of rows of `TypedValues`.
Individual rows can be fetched or the set can be iterated.
To fetch individual rows from a `RelResult` use `row(Int32)`.
```
query.run { rows in
let row1 = rows.row(0)
let row2 = rows.row(1)
}
```
To iterate over the result set use standard iteration flows.
```
query.run { rows in
rows.forEach { row in
...
}
}
```
Note that iteration is consuming and can only be done once.
*/
open class RelResult: OptionalRustObject {
/**
Fetch the row at the requested index.
- Parameter index: the index of the row to be fetched
- Throws: `PointerError.pointerConsumed` if the result set has already been iterated.
- Returns: The row at the requested index as a `TupleResult`, if present, or nil if there is no row at that index.
*/
open func row(index: Int32) throws -> TupleResult? {
guard let row = row_at_index(try self.validPointer(), index) else {
return nil
}
return TupleResult(raw: row)
}
override open func cleanup(pointer: OpaquePointer) {
typed_value_result_set_destroy(pointer)
}
}
/**
Iterator for `RelResult`.
To iterate over the result set use standard iteration flows.
```
query.run { result in
rows.forEach { row in
...
}
}
```
Note that iteration is consuming and can only be done once.
*/
open class RelResultIterator: OptionalRustObject, IteratorProtocol {
public typealias Element = TupleResult
init(iter: OpaquePointer?) {
super.init(raw: iter)
}
open func next() -> Element? {
guard let iter = self.raw,
let rowPtr = typed_value_result_set_iter_next(iter) else {
return nil
}
return TupleResult(raw: rowPtr)
}
override open func cleanup(pointer: OpaquePointer) {
typed_value_result_set_iter_destroy(pointer)
}
}
extension RelResult: Sequence {
open func makeIterator() -> RelResultIterator {
do {
let rowIter = typed_value_result_set_into_iter(try self.validPointer())
self.raw = nil
return RelResultIterator(iter: rowIter)
} catch {
return RelResultIterator(iter: nil)
}
}
}
| apache-2.0 | c4fc46b2eeec6ef9c9ed0c62c626ff96 | 26.754717 | 119 | 0.657376 | 4.091794 | false | false | false | false |
chethankumar/DigitalBank | DigitalBankiOS/DigitalBank/LoginViewController.swift | 1 | 3744 | /*
*
COPYRIGHT LICENSE: This information contains sample code provided in source code form. You may copy, modify, and distribute
these sample programs in any form without payment to IBM® for the purposes of developing, using, marketing or distributing
application programs conforming to the application programming interface for the operating platform for which the sample code is written.
Notwithstanding anything to the contrary, IBM PROVIDES THE SAMPLE SOURCE CODE ON AN "AS IS" BASIS AND IBM DISCLAIMS ALL WARRANTIES,
EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, ANY IMPLIED WARRANTIES OR CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND ANY WARRANTY OR CONDITION OF NON-INFRINGEMENT. IBM SHALL NOT BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR OPERATION OF THE SAMPLE SOURCE CODE.
IBM HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS OR MODIFICATIONS TO THE SAMPLE SOURCE CODE.
*/
import UIKit
import WatchConnectivity
class LoginViewController: UIViewController,WCSessionDelegate {
var challengeHandler : ChallengeHandler?
@IBOutlet weak var errorMsg: UILabel!
@IBOutlet weak var username: UITextField!
@IBOutlet weak var password: UITextField!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
commonInit()
}
func commonInit() {
// Initialize the `WCSession` and the `CLLocationManager`.
WCSession.defaultSession().delegate = self
WCSession.defaultSession().activateSession()
}
override func viewDidLoad() {
super.viewDidLoad()
commonInit()
let dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1.0 * Double(NSEC_PER_SEC)))
self.title = "Custom Authentication"
if (WCSession.defaultSession().paired){
self.username.text = NSUserDefaults.standardUserDefaults().stringForKey("username1")
self.password.text = NSUserDefaults.standardUserDefaults().stringForKey("password1")
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
self.challengeHandler?.submitLoginForm("/my_custom_auth_request_url",
requestParameters: ["username" : self.username.text!, "password" : self.password.text!],
requestHeaders: nil, requestTimeoutInMilliSeconds: 0, requestMethod: "POST")
})
}
else
{
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func login(sender: AnyObject) {
let url = "/my_custom_auth_request_url"
NSUserDefaults.standardUserDefaults().setObject(self.username.text, forKey: "username")
NSUserDefaults.standardUserDefaults().setObject(self.password.text, forKey: "password")
self.challengeHandler?.submitLoginForm(url,
requestParameters: ["username" : self.username.text!, "password" : self.password.text!],
requestHeaders: nil, requestTimeoutInMilliSeconds: 0, requestMethod: "POST")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(true)
if self.isMovingFromParentViewController(){
//Back button pressed
self.challengeHandler?.submitFailure(nil)
}
}
}
| mit | 27b59a0a483313892416aae278a2cbc6 | 37.587629 | 137 | 0.685012 | 5.099455 | false | false | false | false |
DaiYue/HAMLeetcodeSwiftSolutions | solutions/68_Text_Justification.playground/Contents.swift | 1 | 3500 | // #68 Text Justification https://leetcode.com/problems/text-justification/?tab=Description
// 这道题写起来真是太长了,太麻烦了…… >w< 再重复一遍,太麻烦了!还好不涉及什么复杂算法,就是一个 buffer,满了之后往结果里吐就行了。
// 时间复杂度:O(n) 空间复杂度:O(n)
class Solution {
func fullJustify(_ words: [String], _ maxWidth: Int) -> [String] {
var result = [String]()
var buffer = [String]()
var bufferLength = 0
var wordIndex = 0
while wordIndex < words.count {
let word = words[wordIndex]
let wordLength = word.characters.count
if bufferLength + wordLength + 1 < maxWidth {
bufferLength += wordLength + 1
buffer.append(word)
wordIndex += 1
} else if bufferLength + wordLength <= maxWidth {
buffer.append(word)
if wordIndex == words.count - 1 {
break // last line
} else {
result.append(lineFromBuffer(buffer, maxWidth:maxWidth))
}
buffer = []
bufferLength = 0
wordIndex += 1
} else {
result.append(lineFromBuffer(buffer, maxWidth:maxWidth))
buffer = []
bufferLength = 0
}
}
if buffer.count > 0 {
result.append(lastLineFromBuffer(buffer, maxWidth:maxWidth))
}
return result
}
func lineFromBuffer(_ buffer:[String], maxWidth:Int) -> String {
guard buffer.count > 0 else {
return ""
}
guard buffer.count > 1 else {
var result = buffer[0]
if result.characters.count < maxWidth {
for _ in (result.characters.count + 1)...maxWidth {
result.append(" ")
}
}
return result
}
var wordsTotalLength = 0
for word in buffer {
wordsTotalLength += word.characters.count
}
let totalWhiteSpace = maxWidth - wordsTotalLength
let whitespacesForEachWord = totalWhiteSpace / (buffer.count - 1)
var redundantWhitespaces = totalWhiteSpace % (buffer.count - 1)
var result = ""
for (index, word) in buffer.enumerated() {
result.append(word)
if index == buffer.count - 1 {
break // last
}
for _ in 1...whitespacesForEachWord {
result.append(" ")
}
if redundantWhitespaces > 0 {
result.append(" ")
redundantWhitespaces -= 1
}
}
return result
}
func lastLineFromBuffer(_ buffer:[String], maxWidth:Int) -> String {
var result = ""
for (index, word) in buffer.enumerated() {
result.append(word)
if index < buffer.count - 1 {
result.append(" ")
}
}
let trailingWhiteSpaces = maxWidth - result.characters.count
if trailingWhiteSpaces > 0 {
for _ in 1...trailingWhiteSpaces {
result.append(" ")
}
}
return result
}
}
Solution().fullJustify(["",""], 0) | mit | effe6eb14d3146179c0e4f9bccfe4aae | 30.688679 | 91 | 0.483026 | 4.916545 | false | false | false | false |
marty-suzuki/HoverConversion | HoverConversion/HCViewContentable.swift | 1 | 1720 | //
// HCViewContentable.swift
// HoverConversion
//
// Created by Taiki Suzuki on 2016/07/18.
// Copyright © 2016年 marty-suzuki. All rights reserved.
//
import UIKit
import MisterFusion
public protocol HCViewControllable: HCNavigationViewDelegate {
var navigationView: HCNavigationView! { get set }
var navigatoinContainerView: UIView! { get set }
var tableView: UITableView! { get set }
func addViews()
}
extension HCViewControllable where Self: UIViewController {
public func addViews() {
navigationView.delegate = self
view.addLayoutSubview(navigatoinContainerView, andConstraints:
navigatoinContainerView.top,
navigatoinContainerView.right,
navigatoinContainerView.left,
navigatoinContainerView.height |==| HCNavigationView.height
)
navigatoinContainerView.addLayoutSubview(navigationView, andConstraints:
navigationView.top,
navigationView.right,
navigationView.left,
navigationView.bottom
)
view.addLayoutSubview(tableView, andConstraints:
tableView.top |==| navigatoinContainerView.bottom,
tableView.right,
tableView.left,
tableView.bottom
)
view.bringSubview(toFront: navigatoinContainerView)
}
public func navigationView(_ navigationView: HCNavigationView, didTapLeftButton button: UIButton) {}
public func navigationView(_ navigationView: HCNavigationView, didTapRightButton button: UIButton) {}
}
public protocol HCViewContentable: HCViewControllable {
weak var scrollDelegate: HCContentViewControllerScrollDelegate? { get set }
}
| mit | 67329b6dd27f30be1300cb1e71f2b5dc | 32.666667 | 105 | 0.694234 | 5.20303 | false | false | false | false |
panyam/swiftli | Sources/Core/Payload.swift | 2 | 4851 | //
// WSPayload.swift
// SwiftHTTP
//
// Created by Sriram Panyam on 12/31/15.
// Copyright © 2015 Sriram Panyam. All rights reserved.
//
import SwiftIO
public typealias PayloadWriteCallback = (error: ErrorType?) -> Void
public protocol Payload
{
/**
* Returns the length of the message to be sent out (before fragmentation)
* If the message size is unknown at this time then this information MUST
* be returned during the frame creation.
* If during frame creation the length is unknown then it is assumed
* that a single frame is to be sent for this message.
* The opcodes and masking keys are already provided during the call to
* connection.sendMessage
*/
var totalLength : LengthType? { get }
/**
* If the message length above is not given then this method can be called to
* begin the "next" frame of the message which *must* have a length.
* If this method returns 0 then there are no more frames available.
*/
func nextFrame() -> LengthType?
/**
* Called to write the next length set of bytes to the underlying channel.
*
* A length of 0 indicates to the payload source that it can write as many bytes as it has.
*/
func write(writer: Writer, length: LengthType, completion: PayloadWriteCallback)
}
/**
* A http writer of strings
*/
public class StringPayload : Payload
{
var value : String
public init(_ stringValue : String)
{
value = stringValue
}
public var totalLength : LengthType? {
get {
return LengthType(value.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
}
}
public func nextFrame() -> LengthType? {
return nil
}
/**
* Called to write the next length set of bytes to the underlying channel.
*
* A length of 0 indicates to the payload source that it can write as many bytes as it has.
*/
public func write(writer: Writer, length: LengthType, completion: PayloadWriteCallback)
{
writer.writeString(value) { (length, error) -> () in
completion(error: error)
}
}
}
public class BufferPayload : Payload
{
var buffer : ReadBufferType
var offset : OffsetType = 0
var length : LengthType
public init(buffer : ReadBufferType, length: LengthType)
{
self.buffer = buffer
self.length = length
}
public var totalLength : LengthType? {
return length
}
/**
* If the message length above is not given then frames can be specified
* by the message source explicitly to indicate framing per message.
*/
public func nextFrame() -> LengthType? {
return nil
}
/**
* Called to write the next length set of bytes to the underlying channel.
*
* A length of 0 indicates to the payload source that it can write as many bytes as it has.
*/
public func write(writer: Writer, length: LengthType, completion: PayloadWriteCallback)
{
writer.write(buffer.advancedBy(offset), length: LengthType(length)) { (length, error) -> () in
self.offset += length
completion(error: error)
}
}
}
public class FilePayload : Payload
{
var filePath : String
var offset : OffsetType = 0
var fileSize : LengthType?
var dataBuffer = ReadBufferType.alloc(DEFAULT_BUFFER_LENGTH)
var reader : StreamReader
var fileAttrs : [String : AnyObject]?
public init(_ path: String)
{
filePath = path
fileSize = SizeOfFile(filePath)
reader = FileReader(filePath)
}
public var totalLength : LengthType?
{
return fileSize
}
public func nextFrame() -> LengthType? {
return nil
}
/**
* Called to write the next length set of bytes to the underlying channel.
*
* A length of 0 indicates to the payload source that it can write as many bytes as it has.
*/
public func write(writer: Writer, length: LengthType, completion: PayloadWriteCallback)
{
var totalWritten = 0
assert(false, "Come back to this")
func readSender()
{
reader.read(dataBuffer, length: DEFAULT_BUFFER_LENGTH) { (length, error) in
if error != nil || length == 0 {
completion(error: error)
} else {
writer.write(self.dataBuffer, length: length) { (length, error) in
if error != nil {
completion(error: error)
} else {
totalWritten += length
readSender()
}
}
}
}
}
readSender()
}
}
| apache-2.0 | aab25a3bf91b69dea0a8dcb8585fca5f | 27.869048 | 102 | 0.598144 | 4.645594 | false | false | false | false |
linbin00303/Dotadog | DotaDog/DotaDog/Classes/LeftView/View/DDogShowZJHeader.swift | 1 | 2479 | //
// DDogShowZJHeader.swift
// DotaDog
//
// Created by 林彬 on 16/5/25.
// Copyright © 2016年 linbin. All rights reserved.
//
import UIKit
/** 当前状态(0:离线 1:在线 2:忙碌 3:离开 4:打盹 5:正在浏览商品 6:正在玩游戏) */
class DDogShowZJHeader: UIView {
var playerModel : DDogPlayerModel? {
didSet{
// nil值校验
guard let _ = playerModel else {
return
}
playerIcon.sd_setImageWithURL(NSURL(string: playerModel!.avatarfull), placeholderImage: UIImage(named: "iconPlace"), completed: nil)
name.text = playerModel?.personaname
// 要减去76561197960265728
steamID.text = "\(Int64(playerModel!.steamid)! - 76561197960265728)"
switch playerModel!.personastate.integerValue {
case 0:
state.text = "离线"
state.backgroundColor = UIColor.grayColor()
case 1:
state.text = "在线"
state.backgroundColor = UIColor.greenColor()
case 2:
state.text = "忙碌"
state.backgroundColor = UIColor.redColor()
case 3:
state.text = "离开"
state.backgroundColor = UIColor.orangeColor()
case 4:
state.text = "打盹"
state.backgroundColor = UIColor.purpleColor()
case 5:
state.text = "浏览商品"
state.backgroundColor = UIColor.greenColor()
case 6:
state.text = "游戏中"
state.backgroundColor = UIColor.greenColor()
default:
state.text = "未知"
}
let times = DDogTimeTransform.timeTransUTCtoDate(playerModel!.lastlogoff.integerValue) as String
lasttime.text = times
}
}
@IBOutlet weak var playerIcon: UIImageView!
@IBOutlet weak var name: UILabel!
@IBOutlet weak var steamID: UILabel!
@IBOutlet weak var state: UILabel!
@IBOutlet weak var lasttime: UILabel!
class func showZJHeadFromNib() -> DDogShowZJHeader {
let header = NSBundle.mainBundle().loadNibNamed("DDogShowZJHeader", owner: self, options: nil).last as! DDogShowZJHeader
return header
}
}
| mit | af7293155f9e53d452d011f342b729ab | 29.973684 | 144 | 0.536534 | 4.48381 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/YPImagePicker/Source/Helpers/YPPhotoSaver.swift | 3 | 2052 | //
// YPPhotoSaver.swift
// YPImgePicker
//
// Created by Sacha Durand Saint Omer on 10/11/16.
// Copyright © 2016 Yummypets. All rights reserved.
//
import UIKit
import Photos
public class YPPhotoSaver {
class func trySaveImage(_ image: UIImage, inAlbumNamed: String) {
if PHPhotoLibrary.authorizationStatus() == .authorized {
if let album = album(named: inAlbumNamed) {
saveImage(image, toAlbum: album)
} else {
createAlbum(withName: inAlbumNamed) {
if let album = album(named: inAlbumNamed) {
saveImage(image, toAlbum: album)
}
}
}
}
}
fileprivate class func saveImage(_ image: UIImage, toAlbum album: PHAssetCollection) {
PHPhotoLibrary.shared().performChanges({
let changeRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
let albumChangeRequest = PHAssetCollectionChangeRequest(for: album)
let enumeration: NSArray = [changeRequest.placeholderForCreatedAsset!]
albumChangeRequest?.addAssets(enumeration)
})
}
fileprivate class func createAlbum(withName name: String, completion:@escaping () -> Void) {
PHPhotoLibrary.shared().performChanges({
PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: name)
}, completionHandler: { success, _ in
if success {
completion()
}
})
}
fileprivate class func album(named: String) -> PHAssetCollection? {
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "title = %@", named)
let collection = PHAssetCollection.fetchAssetCollections(with: .album,
subtype: .any,
options: fetchOptions)
return collection.firstObject
}
}
| mit | b92e0e50cefa81954cdbd8f3090217e1 | 36.981481 | 96 | 0.584593 | 5.543243 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.