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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
JamieScanlon/AugmentKit | AugmentKit/Renderer/Passes/DrawCall.swift | 1 | 17939 | //
// DrawCall.swift
// AugmentKit
//
// MIT License
//
// Copyright (c) 2018 JamieScanlon
//
// 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 AugmentKitShader
// MARK: - DrawCall
/// Represents a draw call which is a single mesh geometry that is rendered with a Vertex / Fragment Shader. A single draw call can have many submeshes. Each submesh calls `drawIndexPrimitives`
struct DrawCall {
var uuid: UUID
var renderPipelineState: MTLRenderPipelineState {
guard qualityRenderPipelineStates.count > 0 else {
fatalError("Attempting to fetch the `renderPipelineState` property before the render pipelines states have not been initialized")
}
return qualityRenderPipelineStates[0]
}
var qualityRenderPipelineStates = [MTLRenderPipelineState]()
var depthStencilState: MTLDepthStencilState?
var cullMode: MTLCullMode = .back
var depthBias: RenderPass.DepthBias?
var drawData: DrawData?
var usesSkeleton: Bool {
if let myDrawData = drawData {
return myDrawData.skeleton != nil
} else {
return false
}
}
var vertexFunction: MTLFunction? {
guard qualityVertexFunctions.count > 0 else {
return nil
}
return qualityVertexFunctions[0]
}
var qualityVertexFunctions = [MTLFunction]()
var fragmentFunction: MTLFunction? {
guard qualityFragmentFunctions.count > 0 else {
return nil
}
return qualityFragmentFunctions[0]
}
var qualityFragmentFunctions = [MTLFunction]()
/// Create a new `DralCall`
/// - Parameters:
/// - renderPipelineState: A render pipeline state used for the command encoder
/// - depthStencilState: The depth stencil state used for the command encoder
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
init(renderPipelineState: MTLRenderPipelineState, depthStencilState: MTLDepthStencilState? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) {
self.uuid = uuid
self.qualityRenderPipelineStates.append(renderPipelineState)
self.depthStencilState = depthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Create a new `DralCall`
/// - Parameters:
/// - qualityRenderPipelineStates: An array of render pipeline states for each quality level. The index of the render pipeline state will be it's quality level. the number of `qualityRenderPipelineStates` determines the number of distinct Levels of Detail. The descriptor at 0 should be the **highest** quality state with the quality level reducing as the index gets higher.
/// - depthStencilState: The depth stencil state used for the command encoder
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
init(qualityRenderPipelineStates: [MTLRenderPipelineState], depthStencilState: MTLDepthStencilState? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID()) {
self.uuid = uuid
self.qualityRenderPipelineStates = qualityRenderPipelineStates
self.qualityRenderPipelineStates.append(renderPipelineState)
self.depthStencilState = depthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Create a new `DralCall`
/// - Parameters:
/// - device: The metal device used to create the render pipeline state
/// - renderPipelineDescriptor: The render pass descriptor used to create the render pipeline state
/// - depthStencilDescriptor: The depth stencil descriptor used to make the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
init(withDevice device: MTLDevice, renderPipelineDescriptor: MTLRenderPipelineDescriptor, depthStencilDescriptor: MTLDepthStencilDescriptor? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil) {
let myPipelineState: MTLRenderPipelineState = {
do {
return try device.makeRenderPipelineState(descriptor: renderPipelineDescriptor)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
let myDepthStencilState: MTLDepthStencilState? = {
if let depthStencilDescriptor = depthStencilDescriptor {
return device.makeDepthStencilState(descriptor: depthStencilDescriptor)
} else {
return nil
}
}()
self.init(renderPipelineState: myPipelineState, depthStencilState: myDepthStencilState, cullMode: cullMode, depthBias: depthBias, drawData: drawData)
}
/// Create a new `DralCall`
/// - Parameters:
/// - device: The metal device used to create the render pipeline state
/// - qualityRenderPipelineDescriptors: An array of render pipeline descriptors used to create render pipeline states for each quality level. The index of the render pipeline descriptor will be it's quality level. the number of `qualityRenderPipelineDescriptors` determines the number of distinct Levels of Detail. The descriptor at 0 should be the **highest** quality descriptor with the quality level reducing as the index gets higher.
/// - depthStencilDescriptor: The depth stencil descriptor used to make the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
init(withDevice device: MTLDevice, qualityRenderPipelineDescriptors: [MTLRenderPipelineDescriptor], depthStencilDescriptor: MTLDepthStencilDescriptor? = nil, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil) {
let myPipelineStates: [MTLRenderPipelineState] = qualityRenderPipelineDescriptors.map {
do {
return try device.makeRenderPipelineState(descriptor: $0)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}
let myDepthStencilState: MTLDepthStencilState? = {
if let depthStencilDescriptor = depthStencilDescriptor {
return device.makeDepthStencilState(descriptor: depthStencilDescriptor)
} else {
return nil
}
}()
self.init(qualityRenderPipelineStates: myPipelineStates, depthStencilState: myDepthStencilState, cullMode: cullMode, depthBias: depthBias, drawData: drawData)
}
/// All shader function and pipeline states are created during initialization so it is reccommended that these objects be created on an asynchonous thread
/// - Parameters:
/// - metalLibrary: The metal library for the compiled render functions
/// - renderPass: The `RenderPass` associated with this draw call
/// - vertexFunctionName: The name of the vertex function that will be created.
/// - fragmentFunctionName: The name of the fragment function that will be created.
/// - vertexDescriptor: The vertex decriptor that will be used for the render pipeline state
/// - depthComareFunction: The depth compare function that will be used for the depth stencil state
/// - depthWriteEnabled: The `depthWriteEnabled` flag that will be used for the depth stencil state
/// - cullMode: The `cullMode` property that will be used for the render encoder
/// - depthBias: The optional `depthBias` property that will be used for the render encoder
/// - drawData: The draw call data
/// - uuid: An unique identifier for this draw call
/// - numQualityLevels: When using Level Of Detail optimizations in the renderer, this parameter indecates the number of distinct levels and also determines how many pipeline states are set up. This value must be greater than 0
init(metalLibrary: MTLLibrary, renderPass: RenderPass, vertexFunctionName: String, fragmentFunctionName: String, vertexDescriptor: MTLVertexDescriptor? = nil, depthComareFunction: MTLCompareFunction = .less, depthWriteEnabled: Bool = true, cullMode: MTLCullMode = .back, depthBias: RenderPass.DepthBias? = nil, drawData: DrawData? = nil, uuid: UUID = UUID(), numQualityLevels: Int = 1) {
guard numQualityLevels > 0 else {
fatalError("Invalid number of quality levels provided. Must be at least 1")
}
var myPipelineStates = [MTLRenderPipelineState]()
var myVertexFunctions = [MTLFunction]()
var myFragmentFunctions = [MTLFunction]()
for level in 0..<numQualityLevels {
let funcConstants = RenderUtilities.getFuncConstants(forDrawData: drawData, qualityLevel: QualityLevel(rawValue: UInt32(level)))
let fragFunc: MTLFunction = {
do {
return try metalLibrary.makeFunction(name: fragmentFunctionName, constantValues: funcConstants)
} catch let error {
print("Failed to create fragment function for pipeline state descriptor, error \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
let vertFunc: MTLFunction = {
do {
// Specify which shader to use based on if the model has skinned skeleton suppot
return try metalLibrary.makeFunction(name: vertexFunctionName, constantValues: funcConstants)
} catch let error {
print("Failed to create vertex function for pipeline state descriptor, error \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
guard let renderPipelineStateDescriptor = renderPass.renderPipelineDescriptor(withVertexDescriptor: vertexDescriptor, vertexFunction: vertFunc, fragmentFunction: fragFunc) else {
print("failed to create render pipeline state descriptorfor the device.")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: nil))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
let renderPipelineState: MTLRenderPipelineState = {
do {
return try renderPass.device.makeRenderPipelineState(descriptor: renderPipelineStateDescriptor)
} catch let error {
print("failed to create render pipeline state for the device. ERROR: \(error)")
let newError = AKError.seriousError(.renderPipelineError(.failedToInitialize(PipelineErrorInfo(moduleIdentifier: nil, underlyingError: error))))
NotificationCenter.default.post(name: .abortedDueToErrors, object: nil, userInfo: ["errors": [newError]])
fatalError()
}
}()
myVertexFunctions.append(vertFunc)
myFragmentFunctions.append(fragFunc)
myPipelineStates.append(renderPipelineState)
}
let depthStencilDescriptor = renderPass.depthStencilDescriptor(withDepthComareFunction: depthComareFunction, isDepthWriteEnabled: depthWriteEnabled)
let myDepthStencilState: MTLDepthStencilState? = renderPass.device.makeDepthStencilState(descriptor: depthStencilDescriptor)
self.uuid = uuid
self.qualityVertexFunctions = myVertexFunctions
self.qualityFragmentFunctions = myFragmentFunctions
self.qualityRenderPipelineStates = myPipelineStates
self.depthStencilState = myDepthStencilState
self.cullMode = cullMode
self.depthBias = depthBias
self.drawData = drawData
}
/// Prepares the Render Command Encoder with the draw call state.
/// You must call `prepareCommandEncoder(withCommandBuffer:)` before calling this method
/// - Parameters:
/// - renderPass: The `RenderPass` associated with this draw call
/// - qualityLevel: Indicates at which texture quality the pass will be rendered. a `qualityLevel` of 0 indicates **highest** quality. The higher the number the lower the quality. The level must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization
func prepareDrawCall(withRenderPass renderPass: RenderPass, qualityLevel: Int = 0) {
guard let renderCommandEncoder = renderPass.renderCommandEncoder else {
return
}
renderCommandEncoder.setRenderPipelineState(renderPipelineState(for: qualityLevel))
renderCommandEncoder.setDepthStencilState(depthStencilState)
renderCommandEncoder.setCullMode(cullMode)
if let depthBias = depthBias {
renderCommandEncoder.setDepthBias(depthBias.bias, slopeScale: depthBias.slopeScale, clamp: depthBias.clamp)
}
}
/// Returns the `MTLRenderPipelineState` for the given quality level
/// - Parameter qualityLevel: Indicates at which texture quality the pass will be rendered. a `qualityLevel` of 0 indicates **highest** quality. The higher the number the lower the quality. The level must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization
func renderPipelineState(for qualityLevel: Int = 0 ) -> MTLRenderPipelineState {
guard qualityLevel < qualityRenderPipelineStates.count else {
fatalError("The qualityLevel must be less than the number of `qualityRenderPasses` or `numQualityLevels` passed in durring initialization")
}
return qualityRenderPipelineStates[qualityLevel]
}
func markTexturesAsVolitile() {
drawData?.markTexturesAsVolitile()
}
func markTexturesAsNonVolitile() {
drawData?.markTexturesAsNonVolitile()
}
}
extension DrawCall: CustomDebugStringConvertible, CustomStringConvertible {
/// :nodoc:
var description: String {
return debugDescription
}
/// :nodoc:
var debugDescription: String {
let myDescription = "<DrawCall: > uuid: \(uuid), renderPipelineState:\(String(describing: renderPipelineState.debugDescription)), depthStencilState:\(depthStencilState?.debugDescription ?? "None"), cullMode: \(cullMode), usesSkeleton: \(usesSkeleton), vertexFunction: \(vertexFunction?.debugDescription ?? "None"), fragmentFunction: \(fragmentFunction?.debugDescription ?? "None")"
return myDescription
}
}
| mit | c56b7ba94b17c7c2d4ad3c0c55b0a154 | 58.009868 | 443 | 0.689949 | 5.612954 | false | false | false | false |
alessioborraccino/reviews | reviewsTests/ViewModel/AddReviewViewModelTests.swift | 1 | 1565 | //
// AddReviewViewModelTests.swift
// reviews
//
// Created by Alessio Borraccino on 16/05/16.
// Copyright © 2016 Alessio Borraccino. All rights reserved.
//
import XCTest
@testable import reviews
class AddReviewViewModelTests: XCTestCase {
private let reviewAPI = ReviewAPIMock()
private lazy var addReviewViewModel : AddReviewViewModelType = AddReviewViewModel(reviewAPI: self.reviewAPI)
func didTryToSaveNotValidReview() {
setInvalidValues()
let expectation = expectationWithDescription("invalid values")
addReviewViewModel.didTryToSaveNotValidReview.observeNext {
expectation.fulfill()
}
addReviewViewModel.addReview()
waitForExpectationsWithTimeout(0.001, handler: nil)
}
func testSaveReview() {
setValidValues()
let expectation = expectationWithDescription("valid values")
addReviewViewModel.didSaveReview.observeNext { review in
if let _ = review {
expectation.fulfill()
} else {
XCTFail("No Review saved")
}
}
addReviewViewModel.addReview()
waitForExpectationsWithTimeout(0.001, handler: nil)
}
private func setValidValues() {
addReviewViewModel.author = "Author"
addReviewViewModel.message = "Message"
addReviewViewModel.title = "Title"
}
private func setInvalidValues() {
addReviewViewModel.author = "Author"
addReviewViewModel.message = ""
addReviewViewModel.title = ""
}
}
| mit | 3d3284998c80f6fc2e7123462c16c529 | 28.509434 | 112 | 0.660486 | 5.161716 | false | true | false | false |
sammeadley/responder-chain | ResponderChain/ViewController.swift | 1 | 3795 | //
// ViewController.swift
// ResponderChain
//
// Created by Sam Meadley on 03/01/2016.
// Copyright © 2016 Sam Meadley. All rights reserved.
//
import UIKit
// Gross global variable to suppress print output until touch event received. There is almost certainly a better way. Maybe 100 better ways.
var touchReceived = false
class ViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
// Nil-targeted actions are passed up the responder chain until they are handled.
// The didSelectButton:sender implementation below shows a useful example, detecting the
// collection view cell in which a button touch event occurred.
@IBAction func didSelectButton(sender: UIButton) {
let point = sender.convertPoint(CGPointZero, toView:self.collectionView)
let indexPath = self.collectionView.indexPathForItemAtPoint(point)
print("Event handled! I'm \(self.dynamicType) and I will handle the \(sender.dynamicType) touch event for item \(indexPath!.row) \n\n... Now where was I? Oh yeah...", terminator:"\n\n")
}
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
extension ViewController: UICollectionViewDataSource {
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 3
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
return collectionView.dequeueReusableCellWithReuseIdentifier(CollectionViewCell.defaultReuseIdentifier(), forIndexPath: indexPath)
}
}
class View: UIView {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class CollectionView: UICollectionView {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class CollectionViewCell: UICollectionViewCell {
class func defaultReuseIdentifier() -> String {
return "CollectionViewCell"
}
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
}
class Button: UIButton {
override func nextResponder() -> UIResponder? {
let nextResponder = super.nextResponder()
printNextResponder(nextResponder)
return nextResponder
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
touchReceived = true
printEvent(event)
super.touchesBegan(touches, withEvent: event)
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
printEvent(event)
super.touchesEnded(touches, withEvent: event)
}
func printEvent(event: UIEvent?) {
if let phase = event?.allTouches()?.first?.phase {
print("\nHi, Button here. \"\(phase)\" received and understood. I'll let the Responder Chain know...")
}
}
}
extension UIResponder {
func printNextResponder(nextResponder: UIResponder?) {
guard let responder = nextResponder else {
return
}
if (touchReceived) {
print("-> \(self.dynamicType): Hey \(responder.dynamicType), something coming your way!")
}
}
}
| mit | 871979df23590d2d97dbef867fa9fb27 | 28.184615 | 193 | 0.661834 | 5.56305 | false | false | false | false |
functionaldude/XLPagerTabStrip | Example/Example/ReloadExampleViewController.swift | 1 | 3204 | // ReloadExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import XLPagerTabStrip
class ReloadExampleViewController: UIViewController {
@IBOutlet lazy var titleLabel: UILabel! = {
let label = UILabel()
return label
}()
lazy var bigLabel: UILabel = {
let bigLabel = UILabel()
bigLabel.backgroundColor = .clear
bigLabel.textColor = .white
bigLabel.font = UIFont.boldSystemFont(ofSize: 20)
bigLabel.adjustsFontSizeToFitWidth = true
return bigLabel
}()
override func viewDidLoad() {
super.viewDidLoad()
if navigationController != nil {
navigationItem.titleView = bigLabel
bigLabel.sizeToFit()
}
if let pagerViewController = childViewControllers.first as? PagerTabStripViewController {
updateTitle(of: pagerViewController)
}
}
@IBAction func reloadTapped(_ sender: UIBarButtonItem) {
for childViewController in childViewControllers {
guard let child = childViewController as? PagerTabStripViewController else {
continue
}
child.reloadPagerTabStripView()
updateTitle(of: child)
break
}
}
@IBAction func closeTapped(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
func updateTitle(of pagerTabStripViewController: PagerTabStripViewController) {
func stringFromBool(_ bool: Bool) -> String {
return bool ? "YES" : "NO"
}
titleLabel.text = "Progressive = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isProgressiveIndicator)) ElasticLimit = \(stringFromBool(pagerTabStripViewController.pagerBehaviour.isElasticIndicatorLimit))"
(navigationItem.titleView as? UILabel)?.text = titleLabel.text
navigationItem.titleView?.sizeToFit()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
| mit | feaf8c681c53ab689a9eec59236a8373 | 36.255814 | 228 | 0.696941 | 5.261084 | false | false | false | false |
ruddfawcett/VerticalTextView | Source/VerticalTextView.swift | 1 | 2870 | // VerticalTextView.swift
// Copyright (c) 2015 Brendan Conron
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class VerticalTextView: UITextView {
enum VerticalAlignment: Int {
case Top = 0, Middle, Bottom
}
var verticalAlignment: VerticalAlignment = .Middle
//override contentSize property and observe using didSet
override var contentSize: CGSize {
didSet {
let height = self.bounds.size.height
let contentHeight: CGFloat = contentSize.height
var topCorrect: CGFloat = 0.0
switch (self.verticalAlignment) {
case .Top:
self.contentOffset = CGPointZero //set content offset to top
case .Middle:
topCorrect = (height - contentHeight * self.zoomScale) / 2.0
topCorrect = topCorrect < 0 ? 0 : topCorrect
self.contentOffset = CGPoint(x: 0, y: -topCorrect)
case .Bottom:
topCorrect = self.bounds.size.height - contentHeight
topCorrect = topCorrect < 0 ? 0 : topCorrect
self.contentOffset = CGPoint(x: 0, y: -topCorrect)
}
if contentHeight >= height { // if the contentSize is greater than the height
topCorrect = contentHeight - height // set the contentOffset to be the
topCorrect = topCorrect < 0 ? 0 : topCorrect // contentHeight - height of textView
self.contentOffset = CGPoint(x: 0, y: topCorrect)
}
}
}
// MARK: - UIView
override func layoutSubviews() {
super.layoutSubviews()
let size = self.contentSize // forces didSet to be called
self.contentSize = size
}
} | mit | 5110d130d19c36064870aaf8e715d39a | 39.43662 | 98 | 0.639024 | 5.161871 | false | false | false | false |
openhab/openhab.ios | openHAB/UIAlertView+Block.swift | 1 | 1884 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import ObjectiveC
import UIKit
private var kNSCBAlertWrapper = 0
class NSCBAlertWrapper: NSObject {
var completionBlock: ((_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void)?
// MARK: - UIAlertViewDelegate
// Called when a button is clicked. The view will be automatically dismissed after this call returns
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if completionBlock != nil {
completionBlock?(alertView, buttonIndex)
}
}
// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
func alertViewCancel(_ alertView: UIAlertView) {
// Just simulate a cancel button click
if completionBlock != nil {
completionBlock?(alertView, alertView.cancelButtonIndex)
}
}
}
extension UIAlertView {
@objc
func show(withCompletion completion: @escaping (_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void) {
let alertWrapper = NSCBAlertWrapper()
alertWrapper.completionBlock = completion
delegate = alertWrapper as AnyObject
// Set the wrapper as an associated object
objc_setAssociatedObject(self, &kNSCBAlertWrapper, alertWrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// Show the alert as normal
show()
}
// MARK: - Class Public
}
| epl-1.0 | b9f00c1ba33e21ffba6925667a2ed799 | 33.888889 | 133 | 0.697452 | 4.781726 | false | false | false | false |
soxjke/Redux-ReactiveSwift | Example/Simple-Weather-App/Simple-Weather-App/Store/AppStore.swift | 1 | 5542 | //
// AppStore.swift
// Simple-Weather-App
//
// Created by Petro Korienev on 10/30/17.
// Copyright © 2017 Sigma Software. All rights reserved.
//
import Foundation
import Redux_ReactiveSwift
extension AppState: Defaultable {
static var defaultValue: AppState = AppState(location: AppLocation(locationState: .notYetRequested,
locationRequestState: .none),
weather: AppWeather(geopositionRequestState: .none,
weatherRequestState: .none))
}
final class AppStore: Store<AppState, AppEvent> {
static let shared: AppStore = AppStore()
init() {
super.init(state: AppState.defaultValue, reducers: [appstore_reducer])
}
required init(state: AppState, reducers: [AppStore.Reducer]) {
super.init(state: state, reducers: reducers)
}
}
internal func appstore_reducer(state: AppState, event: AppEvent) -> AppState {
return AppState(location: locationReducer(state.location, event),
weather: weatherReducer(state.weather, event))
}
// MARK: Location reducers
fileprivate func locationReducer(_ state: AppLocation, _ event: AppEvent) -> AppLocation {
switch event {
case .locationPermissionResult(let success): return location(permissionResult: success, previous: state)
case .locationRequest: return locationRequest(previous: state)
case .locationResult(let latitude, let longitude, let timestamp, let error):
return locationResult(latitude: latitude, longitude: longitude, timestamp: timestamp, error: error, previous: state)
default: return state
}
}
fileprivate func location(permissionResult: Bool, previous: AppLocation) -> AppLocation {
return AppLocation(locationState: permissionResult ? .available : .notAvailable,
locationRequestState: previous.locationRequestState)
}
fileprivate func locationRequest(previous: AppLocation) -> AppLocation {
guard case .available = previous.locationState else { return previous }
if case .success(_, _, let timestamp) = previous.locationRequestState {
if (Date().timeIntervalSince1970 - timestamp < 10) { // Don't do update if location succeeded within last 10 seconds
return previous
}
}
return AppLocation(locationState: previous.locationState, locationRequestState: .updating) // Perform location update
}
fileprivate func locationResult(latitude: Double?, longitude: Double?, timestamp: TimeInterval?, error: Swift.Error?, previous: AppLocation) -> AppLocation {
guard let error = error else {
if let latitude = latitude, let longitude = longitude, let timestamp = timestamp {
return AppLocation(locationState: previous.locationState, locationRequestState: .success(latitude: latitude, longitude: longitude, timestamp: timestamp))
}
return AppLocation(locationState: previous.locationState, locationRequestState: .error(error: AppError.inconsistentLocationEvent))
}
return AppLocation(locationState: previous.locationState, locationRequestState: .error(error: error))
}
// MARK: Weather reducers
fileprivate func weatherReducer(_ state: AppWeather, _ event: AppEvent) -> AppWeather {
switch event {
case .geopositionRequest: return geopositionRequest(previous: state)
case .geopositionResult(let geoposition, let error): return geopositionResult(geoposition: geoposition, error: error, previous: state)
case .weatherRequest: return weatherRequest(previous: state)
case .weatherResult(let current, let forecast, let error): return weatherResult(current: current, forecast: forecast, error: error, previous: state)
default: return state
}
}
fileprivate func geopositionRequest(previous: AppWeather) -> AppWeather {
return AppWeather(geopositionRequestState: .updating, weatherRequestState: previous.weatherRequestState)
}
fileprivate func geopositionResult(geoposition: Geoposition?, error: Swift.Error?, previous: AppWeather) -> AppWeather {
guard let error = error else {
if let geoposition = geoposition {
return AppWeather(geopositionRequestState: .success(geoposition: geoposition), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: .error(error: AppError.inconsistentGeopositionEvent), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: .error(error: error), weatherRequestState: previous.weatherRequestState)
}
fileprivate func weatherRequest(previous: AppWeather) -> AppWeather {
return AppWeather(geopositionRequestState: previous.geopositionRequestState, weatherRequestState: .updating)
}
fileprivate func weatherResult(current: CurrentWeather?, forecast: [Weather]?, error: Swift.Error?, previous: AppWeather) -> AppWeather {
guard let error = error else {
if let current = current, let forecast = forecast {
return AppWeather(geopositionRequestState: previous.geopositionRequestState,
weatherRequestState: .success(currentWeather: current, forecast: forecast))
}
return AppWeather(geopositionRequestState: .error(error: AppError.inconsistentWeatherEvent), weatherRequestState: previous.weatherRequestState)
}
return AppWeather(geopositionRequestState: previous.geopositionRequestState, weatherRequestState: .error(error: error))
}
| mit | d670aff3a1c1da42049f64c6ffdce0b7 | 54.969697 | 165 | 0.724057 | 5.327885 | false | false | false | false |
kenjitayama/MustacheMultitypeRender | Example/Tests/Tests.swift | 1 | 2813 | import UIKit
import XCTest
import MustacheMultitypeRender
class Tests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
let filters: [String: TemplateStringRender.Filter] = [
"flyingTo": { (args: [String]) in
return "\(args[0]) 🛫🛬 \(args[1])"
}
]
let implicitFilter = { (renderSource: String) in
return "[\(renderSource)]"
}
// start/end with non-placeholder
// 1 valid replacemnt, 1 missing replacement
var template = TemplateStringRender(
templateString: "start {{apple}} {{candy}} {{flyingTo(city1,city2)}} end",
filters: filters,
implicitFilter: implicitFilter)
var renderResult = template.render([
"apple": "cherry",
"city1": "Tokyo",
"city2": "New York"
])
XCTAssertEqual(renderResult, "[start ][cherry][ ][candy][ ]Tokyo 🛫🛬 New York[ end]")
// start/end with placeholder,
// 1 valid replacemnt, 1 missing replacement
// 1 missing filter argument (2 needed)
template = TemplateStringRender(
templateString: "{{apple}} {{candy}} {{flyingTo(city1,city2)}}, {{flyingTo(city1,city3)}}",
filters: filters,
implicitFilter: implicitFilter)
renderResult = template.render([
"apple": "cherry",
"city1": "Tokyo",
])
XCTAssertEqual(renderResult, "[cherry][ ][candy][ ]Tokyo 🛫🛬 city2[, ]Tokyo 🛫🛬 city3")
// start with placeholder,
// 1 valid replacemnt, 1 missing replacement
// 2 missing filter argument (2 needed)
template = TemplateStringRender(
templateString: "[start ][cherry][ ][mentos][ ][distance(city1,city2)][, ]city1 🛫🛬 city3",
filters: filters,
implicitFilter: implicitFilter)
renderResult = template.render([
"apple": "cherry",
"candy": "mentos"
])
XCTAssertEqual(renderResult, "[[start ][cherry][ ][mentos][ ][distance(city1,city2)][, ]city1 🛫🛬 city3]")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit | 8069e2406519b6802194bc92cc9bb1b4 | 35.064935 | 113 | 0.556356 | 4.722789 | false | true | false | false |
DeliciousRaspberryPi/MockFive | MockFiveTests/MockFiveTests.swift | 1 | 11771 | import Quick
import Nimble
@testable import MockFive
protocol MyMockableProtocol {
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String)
func myOptionalMethod(arg: Int) -> String?
func mySimpleMethod()
}
protocol MockFiveTests: MyMockableProtocol, Mock {}
struct TestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() { stub(identifier: "mySimpleMethod") }
func myOptionalMethod(arg: Int) -> String? { return stub(identifier: "myOptionalMethod", arguments: arg) }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description, price, accessories) { _ in (7, "Fashion") } }
}
class MockFiveSpecs: QuickSpec {
override func spec() {
var mock: MockFiveTests = TestMock()
beforeEach { mock.resetMock() }
describe("logging method calls") {
context("when it's a simple call") {
beforeEach {
mock.mySimpleMethod()
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("mySimpleMethod()"))
}
}
context("When it's a complex call") {
context("with the correct number of arguments") {
beforeEach {
mock.myComplexMethod(nil, price: 42, accessories: "shoes", "shirts", "timepieces")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: nil, price: 42, accessories: [\"shoes\", \"shirts\", \"timepieces\"]) -> (Int, String)"))
}
}
context("with too few arguments") {
struct TooFewTestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() {}
func myOptionalMethod(arg: Int) -> String? { return .None }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description) { _ in (7, "Fashion") } }
}
beforeEach {
mock = TooFewTestMock()
mock.myComplexMethod("A fun argument", price: 7, accessories: "Necklace")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: A fun argument, price: , accessories: ) -> (Int, String) [Expected 3, got 1]"))
}
}
context("with too many arguments") {
struct TooManyTestMock: MockFiveTests {
let mockFiveLock = lock()
func mySimpleMethod() {}
func myOptionalMethod(arg: Int) -> String? { return .None }
func myComplexMethod(description: String?, price: Int, accessories: Any...) -> (Int, String) { return stub(identifier: "myComplexMethod", arguments: description, price, accessories, "fruit", 9) { _ in (7, "Fashion") } }
}
beforeEach {
mock = TooManyTestMock()
mock.myComplexMethod("A fun argument", price: 7, accessories: "Necklace")
}
it("should have the correct output") {
expect(mock.invocations.count).to(equal(1))
expect(mock.invocations.first).to(equal("myComplexMethod(_: A fun argument, price: 7, accessories: [\"Necklace\"]) -> (Int, String) [Expected 3, got 5: fruit, 9]"))
}
}
}
}
describe("stubbing method implementations") {
let testMock = TestMock()
var fatalErrorString: String? = .None
let fatalErrorDispatch = { (behavior: () -> ()) in dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), behavior) }
beforeEach { FatalErrorUtil.replaceFatalError({ (message, _, _) -> () in fatalErrorString = message }) }
afterEach { FatalErrorUtil.restoreFatalError() }
context("when the type does not conform to nilLiteralConvertible") {
context("when I have registered a closure of the correct type") {
var arguments: [Any?]? = .None
beforeEach {
testMock.registerStub("myComplexMethod") { args -> (Int, String) in
arguments = args
return (21, "string")
}
testMock.myComplexMethod("", price: 1)
}
it("should pass the arguments to the closure") {
if let description = arguments?[0] as? String {
expect(description).to(equal(""))
} else { fail() }
if let price = arguments?[1] as? Int {
expect(price).to(equal(1))
} else { fail() }
}
it("should return the registered closure's value") {
expect(testMock.myComplexMethod("", price: 1).0).to(equal(21))
expect(testMock.myComplexMethod("", price: 1).1).to(equal("string"))
}
describe("resetting the mock") {
beforeEach {
testMock.unregisterStub("myComplexMethod")
}
it("should return the default block's value") {
expect(testMock.myComplexMethod("", price: 1).0).to(equal(7))
expect(testMock.myComplexMethod("", price: 1).1).to(equal("Fashion"))
}
}
}
context("when I have registered a closure of the incorrect type") {
beforeEach {
testMock.registerStub("myComplexMethod") { _ in return 7 }
fatalErrorDispatch({ testMock.myComplexMethod("", price: 1) })
}
it("should throw a fatal error") {
expect(fatalErrorString).toEventually(equal("MockFive: Incompatible block of type 'Array<Optional<protocol<>>> -> Int' registered for function 'myComplexMethod' requiring block type '([Any?]) -> (Int, String)'"))
}
}
}
context("when the type conforms to nil literal convertible") {
context("when I have not registered a closure") {
it("should return a default of nil") {
expect(testMock.myOptionalMethod(7)).to(beNil())
}
}
context("when I have registered a closure of the correct type") {
var arguments: [Any?]? = .None
beforeEach {
testMock.registerStub("myOptionalMethod") { args -> String? in
arguments = args
return "string"
}
testMock.myOptionalMethod(7)
}
it("should pass the arguments to the closure") {
if let arg = arguments?[0] as? Int {
expect(arg).to(equal(7))
} else { fail() }
}
it("should return the closure value") {
expect(testMock.myOptionalMethod(7)).to(equal("string"))
}
describe("resetting the mock") {
beforeEach {
testMock.unregisterStub("myOptionalMethod")
}
it("should return nil") {
expect(testMock.myOptionalMethod(7)).to(beNil())
}
}
}
context("when I have registered a closure of the incorrect type") {
beforeEach {
testMock.registerStub("myOptionalMethod") { _ in 21 }
}
it("should throw a fatal error") {
expect(fatalErrorString).toEventually(equal("MockFive: Incompatible block of type 'Array<Optional<protocol<>>> -> Int' registered for function 'myComplexMethod' requiring block type '([Any?]) -> (Int, String)'"))
}
}
}
}
describe("mock object identity") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock1.myComplexMethod("", price: 9)
}
it("should log the calls on the first mock") {
expect(mock1.invocations.count).to(equal(2))
}
it("should not log the calls on the second mock") {
expect(mock2.invocations.count).to(equal(0))
}
}
describe("resetting the mock log") {
context("when I am resetting the mock log for one instance") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock2.myComplexMethod("", price: 9)
mock1.resetMock()
}
it("should empty the invocations on the mock") {
expect(mock1.invocations.count).to(equal(0))
}
it("should not empty the invocations on other mocks") {
expect(mock2.invocations.count).toNot(equal(0))
}
}
context("when I am resetting the global mock log") {
let mock1 = TestMock()
let mock2 = TestMock()
beforeEach {
mock1.mySimpleMethod()
mock2.myComplexMethod("", price: 9)
resetMockFive()
}
it("should empty the invocations of the mock") {
expect(mock1.invocations.count).to(equal(0))
}
it("should empty the invocations of the mock") {
expect(mock2.invocations.count).to(equal(0))
}
}
}
}
}
| apache-2.0 | dcf79b69120d90e7c9a42f6cd91f1d43 | 44.624031 | 243 | 0.451448 | 5.859134 | false | true | false | false |
jschmid/couchbase-chat | ios-app/couchbase-chat/Controllers/LoginViewController.swift | 1 | 1676 | //
// LoginViewController.swift
// couchbase-chat
//
// Created by Jonas Schmid on 13/07/15.
// Copyright © 2015 schmid. All rights reserved.
//
import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
override func viewDidLoad() {
}
override func viewDidAppear(animated: Bool) {
let prefs = NSUserDefaults.standardUserDefaults()
if let username = prefs.stringForKey("username"),
let password = prefs.stringForKey("password") {
startLogin(username, password: password)
}
}
@IBAction func signinClick(sender: UIButton) {
if let username = usernameTextField.text,
let password = passwordTextField.text {
startLogin(username, password: password)
}
}
private func startLogin(username: String, password: String) {
let syncHelper = SyncHelper(username: username, password: password)
let app = UIApplication.sharedApplication().delegate as! AppDelegate
app.syncHelper = syncHelper
syncHelper.start()
let prefs = NSUserDefaults.standardUserDefaults()
prefs.setObject(username, forKey: "username")
prefs.setObject(password, forKey: "password")
// Async call because this method may be called from viewDidLoad and the performSegue will not work
dispatch_async(dispatch_get_main_queue()) {
let ctrl = self.storyboard?.instantiateViewControllerWithIdentifier("splitViewController")
app.window!.rootViewController = ctrl
}
}
}
| mit | b70c6cbfb031b248908619cb9dfc3107 | 30.018519 | 107 | 0.669851 | 5.122324 | false | false | false | false |
ZhaoBingDong/EasySwifty | EasySwifty/Classes/Easy+UIView.swift | 1 | 6230 | //
// Easy+UIView.swift
// EaseSwifty
//
// Created by 董招兵 on 2017/8/6.
// Copyright © 2017年 大兵布莱恩特. All rights reserved.
//
import Foundation
import UIKit
//public func kScaleWidth(_ value : CGFloat) -> CGFloat {
// return UIScreen.main.autoScaleW(value)
//}
//
public func kScaleWidth(_ value : CGFloat) -> CGFloat {
return 0.0
}
// MARK: - UIView
public extension UIView {
class func viewType() -> Self {
return self.init()
}
// Top
var top : CGFloat {
set (_newTop){
var rect = self.frame;
rect.origin.y = _newTop;
self.frame = rect;
}
get { return self.frame.minY }
}
// Left
var left : CGFloat {
set(_newLeft) {
var rect = self.frame;
rect.origin.x = _newLeft;
self.frame = rect;
}
get { return self.frame.minX }
}
// Bottom
var bottom : CGFloat {
set (_newBottom) {
var frame = self.frame
frame.origin.y = _newBottom - frame.size.height;
self.frame = frame;
}
get { return self.frame.maxY }
}
// Right
var right : CGFloat {
set (_newRight){
var rect = self.frame;
rect.origin.x = _newRight - rect.width;
self.frame = rect;
}
get { return self.frame.maxX }
}
// Width
var width : CGFloat {
set(_newWidth) {
var rect = self.frame;
rect.size.width = _newWidth;
self.frame = rect;
}
get { return self.frame.width }
}
// Height
var height : CGFloat {
set (_newHeight){
var rect = self.frame;
rect.size.height = _newHeight;
self.frame = rect;
}
get { return self.frame.height }
}
// Size
var size : CGSize {
set(_newSize) {
var frame = self.frame;
frame.size = _newSize;
self.frame = frame;
}
get { return self.frame.size }
}
// Origin
var origin : CGPoint {
set (_newOrgin) {
var frame = self.frame;
frame.origin = _newOrgin;
self.frame = frame;
}
get { return self.frame.origin }
}
// CenterX
var center_x : CGFloat {
set (_newCenterX) {
self.center = CGPoint(x: _newCenterX, y: self.center_x)
}
get { return self.center.x }
}
// CenterY
var center_y : CGFloat {
set (_newCenterY) {
self.center = CGPoint(x: self.center_x, y: _newCenterY)
}
get { return self.center.y }
}
/**
移除所有子视图
*/
func removeAllSubviews() {
while self.subviews.count > 0 {
let view = self.subviews.last
view?.removeFromSuperview()
}
}
/**
给一个 view 添加手势事件
*/
func addTarget(_ target : AnyObject?, action : Selector?) {
if (target == nil || action == nil) { return }
self.isUserInteractionEnabled = true;
self.addGestureRecognizer(UITapGestureRecognizer(target: target, action: action!))
}
@discardableResult
class func viewFromNib<T: UIView>() -> T {
let className = T.reuseIdentifier.components(separatedBy: ".").last ?? ""
let nib = Bundle.main.loadNibNamed(className, owner: nil, options: nil)?.last
guard nib != nil else {
fatalError("Could not find Nib with name: \(className)")
}
return nib as! T
}
}
// MARK: - UIButton
@objc public extension UIButton {
/**
给按钮设置不同状态下的颜色
*/
func setBackgroundColor(backgroundColor color: UIColor? ,forState state: UIControl.State) {
guard color != nil else { return }
self.setBackgroundImage(UIImage.imageWithColor(color!), for: state)
}
/// 获取 button 所在tableview cell 的 indexPath
/// button 点击方法应该
// button.addTarget(self, action: #selector(buttonClick(btn:event:)), for: .touchUpInside)
// @objc func buttonClick(btn:UIButton,event:Any) {
//
// if let indexPath = btn.indexPath(at: UITableView(), forEvent: event) {
// print(indexPath)
// }
// }
@discardableResult
func indexPathAtTableView(_ tableView : UITableView, forEvent event : Any) -> IndexPath? {
// 获取 button 所在 cell 的indexPath
let set = (event as! UIEvent).allTouches
for (_ ,anyObj) in (set?.enumerated())! {
let point = anyObj.location(in: tableView)
let indexPath = tableView.indexPathForRow(at: point)
if indexPath != nil {
return indexPath!;
}
}
return nil
}
/// 当点击某个 CollectionCell 上 button 时 获取某个 cell.indexPath
// button.addTarget(self, action: #selector(buttonClick(btn:event:)), for: .touchUpInside)
// @objc func buttonClick(btn:UIButton,event:Any) {
//
// if let indexPath = btn.indexPath(at: UICollectionView(), forEvent: event) {
// print(indexPath)
// }
// }
@discardableResult
func indexPathAtCollectionView(_ collectionView : UICollectionView, forEvent event : NSObject) -> IndexPath? {
// 获取 button 所在 cell 的indexPath
let set = (event as! UIEvent).allTouches
for (_ ,anyObj) in (set?.enumerated())! {
let point = anyObj.location(in: collectionView)
let indexPath = collectionView.indexPathForItem(at: point)
if indexPath != nil {
return indexPath!;
}
}
return nil
}
}
extension UIView : ViewNameReusable {
public class var reuseIdentifier:String {
return String(describing: self)
}
public class var xib : UINib? {
return UINib(nibName: self.reuseIdentifier, bundle: nil)
}
}
public protocol ViewNameReusable : class {
static var reuseIdentifier : String { get }
}
| apache-2.0 | f80916e4c17ffb4b31cc40b4bb6efc1d | 24.468619 | 115 | 0.541482 | 4.235908 | false | false | false | false |
szpnygo/firefox-ios | Client/Frontend/Reader/ReadabilityBrowserHelper.swift | 20 | 2103 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import WebKit
protocol ReadabilityBrowserHelperDelegate {
func readabilityBrowserHelper(readabilityBrowserHelper: ReadabilityBrowserHelper, didFinishWithReadabilityResult result: ReadabilityResult)
}
class ReadabilityBrowserHelper: BrowserHelper {
var delegate: ReadabilityBrowserHelperDelegate?
class func name() -> String {
return "ReadabilityBrowserHelper"
}
init?(browser: Browser) {
if let readabilityPath = NSBundle.mainBundle().pathForResource("Readability", ofType: "js"),
let readabilitySource = NSMutableString(contentsOfFile: readabilityPath, encoding: NSUTF8StringEncoding, error: nil),
let readabilityBrowserHelperPath = NSBundle.mainBundle().pathForResource("ReadabilityBrowserHelper", ofType: "js"),
let readabilityBrowserHelperSource = NSMutableString(contentsOfFile: readabilityBrowserHelperPath, encoding: NSUTF8StringEncoding, error: nil) {
readabilityBrowserHelperSource.replaceOccurrencesOfString("%READABILITYJS%", withString: readabilitySource as String, options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readabilityBrowserHelperSource.length))
var userScript = WKUserScript(source: readabilityBrowserHelperSource as String, injectionTime: WKUserScriptInjectionTime.AtDocumentEnd, forMainFrameOnly: true)
browser.webView!.configuration.userContentController.addUserScript(userScript)
}
}
func scriptMessageHandlerName() -> String? {
return "readabilityMessageHandler"
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if let readabilityResult = ReadabilityResult(object: message.body) {
delegate?.readabilityBrowserHelper(self, didFinishWithReadabilityResult: readabilityResult)
}
}
} | mpl-2.0 | 21fd7e873bba16dd5c48268c68c791b5 | 52.948718 | 238 | 0.768426 | 6.131195 | false | false | false | false |
watr/PTPPT | PTP/PTPDataSet.swift | 1 | 6522 |
import Foundation
public protocol PTPDataSet {
init?(data: Data)
}
public struct GetDeviceInfoDataSet: PTPDataSet, CustomStringConvertible {
public typealias StandardVersion = UInt16
public let standardVersion: StandardVersion
public typealias VendorExtensionID = UInt32
public let vendorExtensionID: VendorExtensionID
public typealias VendorExtensionVersion = UInt16
public let vendorExtensionVersion: VendorExtensionVersion
public typealias VendorExtensionDesc = String
public let vendorExtensionDesc: VendorExtensionDesc
public typealias FunctionalMode = UInt16
public let functionalMode: FunctionalMode
public typealias OperationsSupported = [UInt16]
public let operationsSupported: OperationsSupported
public typealias EventsSupported = [UInt16]
public let eventsSupported: EventsSupported
public typealias DevicePropertiesSupported = [UInt16]
public let devicePropertiesSupported: DevicePropertiesSupported
public typealias CaptureFormats = [UInt16]
public let captureFormats: CaptureFormats
public typealias ImageFormats = [UInt16]
public let imageFormats: ImageFormats
public typealias Manufacturer = String
public let manufacturer: Manufacturer
public typealias Model = String
public let model: Model
public typealias DeviceVersion = String
public let deviceVersion: DeviceVersion
public typealias SerialNumber = String
public let serialNumber: SerialNumber
public init?(data: Data) {
var offset: Int = 0
var capacity: Int = 0
capacity = MemoryLayout<StandardVersion>.size
self.standardVersion = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = MemoryLayout<VendorExtensionID>.size
self.vendorExtensionID = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = MemoryLayout<VendorExtensionVersion>.size
self.vendorExtensionVersion = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.vendorExtensionDesc = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = MemoryLayout<FunctionalMode>.size
self.functionalMode = data.subdata(in: offset..<(offset + capacity)).withUnsafeBytes({$0.pointee})
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.operationsSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.eventsSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.devicePropertiesSupported = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.captureFormats = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt16>.size)
self.imageFormats = data.subdata(in: offset..<(offset + capacity)).ptpArray()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.manufacturer = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.model = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.deviceVersion = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
capacity = data.ptpStringCapacity(from: offset)
self.serialNumber = data.subdata(in: offset..<(offset + capacity)).ptpString()
offset += capacity
}
public var description: String {
let descriptions: [String] = [
"data set \"get deice info\"",
" standard version: \(self.standardVersion)",
" vendor extension id: \(self.vendorExtensionID)",
" vendor extension version: \(self.vendorExtensionVersion)",
" vendor extension desc: \(self.vendorExtensionDesc)",
" functional mode: \(self.functionalMode)",
" operations supported: \(self.operationsSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" events supported: \(self.eventsSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
"device properties supported: \(self.devicePropertiesSupported.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" capture formats: \(self.captureFormats.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" image formats: \(self.imageFormats.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
" manufacturer: \(self.manufacturer)",
" model: \(self.model)",
" device version: \(self.deviceVersion)",
" serial number: \(self.serialNumber)",
]
return descriptions.joined(separator: "\n")
}
}
public struct GetStorageIDsDataSet: PTPDataSet, CustomStringConvertible {
public let storageIDs: [UInt32]
public init?(data: Data) {
var offset: Int = 0
var capacity: Int = 0
capacity = data.ptpArrayCapacity(from: offset, each: MemoryLayout<UInt32>.size)
self.storageIDs = data.ptpArray()
offset += capacity
}
public var description: String {
let descriptions: [String] = [
"data set \"get storage IDs\"",
"storage IDs: \(self.storageIDs.map({String(format: "0x%x", $0)}).joined(separator: ", "))",
]
return descriptions.joined(separator: "\n")
}
}
| mit | c3e643c94bf329a4b7cf2fb6e3541535 | 41.350649 | 135 | 0.638148 | 5.032407 | false | false | false | false |
pyze/iOS-Samples | PyzeWatchOSInApp/PyzeWatchOSInApp WatchKit Extension/NotificationController.swift | 1 | 2916 | import WatchKit
import Foundation
import UserNotifications
import Pyze
class NotificationController: WKUserNotificationInterfaceController {
override init() {
// Initialize variables here.
super.init()
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
// MARK: - WatchOS2
override func didReceiveRemoteNotification(_ remoteNotification: [AnyHashable : Any], withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Void) {
if let aps = remoteNotification["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
if let body = alert["body"] as? NSString {
let alert:WKAlertAction = WKAlertAction(title: "OK", style: .default, handler: {
print("Alert action 'OK' performed")
})
let actions = [alert]
self.presentAlert(withTitle: title as String, message: body as String, preferredStyle: .alert, actions: actions)
Pyze.processReceivedRemoteNotification(remoteNotification)
}
}
}
}
}
// MARK: - WatchOS3
@available(watchOSApplicationExtension 3.0, *)
override func didReceive(_ notification: UNNotification, withCompletion completionHandler: @escaping (WKUserNotificationInterfaceType) -> Swift.Void) {
let userInfo = notification.request.content.userInfo
if let aps = userInfo["aps"] as? NSDictionary {
if let alert = aps["alert"] as? NSDictionary {
if let title = alert["title"] as? NSString {
if let body = alert["body"] as? NSString {
let alert:WKAlertAction = WKAlertAction(title: "OK", style: .default, handler: {
print("Alert action 'OK' performed")
})
let actions = [alert]
self.presentAlert(withTitle: title as String, message: body as String, preferredStyle: .alert, actions: actions)
Pyze.processReceivedRemoteNotification(userInfo)
}
}
}
}
completionHandler(.custom)
}
}
| mit | ecb307e58d625c6a476ceac5cba17b95 | 35 | 178 | 0.53155 | 6.177966 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ApplePlatform/Performance/CIContextPool.swift | 1 | 4143 | //
// CIContextPool.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#if canImport(CoreImage) && canImport(Metal)
private struct CIContextOptions: Hashable {
var colorSpace: ColorSpace<RGBColorModel>?
var outputPremultiplied: Bool
var workingFormat: CIFormat
}
public class CIContextPool {
public static let `default`: CIContextPool = CIContextPool()
public let commandQueue: MTLCommandQueue?
private let lck = NSLock()
private var table: [CIContextOptions: CIContext] = [:]
public init() {
self.commandQueue = MTLCreateSystemDefaultDevice()?.makeCommandQueue()
}
public init(device: MTLDevice) {
self.commandQueue = device.makeCommandQueue()
}
public init(commandQueue: MTLCommandQueue) {
self.commandQueue = commandQueue
}
}
extension CIContextPool {
private func make_context(options: CIContextOptions) -> CIContext? {
let _options: [CIContextOption: Any]
if let colorSpace = options.colorSpace {
guard let cgColorSpace = colorSpace.cgColorSpace else { return nil }
_options = [
.workingColorSpace: cgColorSpace,
.outputColorSpace: cgColorSpace,
.outputPremultiplied: options.outputPremultiplied,
.workingFormat: options.workingFormat,
]
} else {
_options = [
.workingColorSpace: CGColorSpaceCreateDeviceRGB(),
.outputColorSpace: CGColorSpaceCreateDeviceRGB(),
.outputPremultiplied: options.outputPremultiplied,
.workingFormat: options.workingFormat,
]
}
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, *), let commandQueue = commandQueue {
return CIContext(mtlCommandQueue: commandQueue, options: _options)
} else if let device = commandQueue?.device {
return CIContext(mtlDevice: device, options: _options)
} else {
return CIContext(options: _options)
}
}
public func makeContext(colorSpace: ColorSpace<RGBColorModel>? = nil, outputPremultiplied: Bool = true, workingFormat: CIFormat = .BGRA8) -> CIContext? {
lck.lock()
defer { lck.unlock() }
let options = CIContextOptions(
colorSpace: colorSpace,
outputPremultiplied: outputPremultiplied,
workingFormat: workingFormat
)
if table[options] == nil {
table[options] = make_context(options: options)
}
return table[options]
}
public func clearCaches() {
lck.lock()
defer { lck.unlock() }
for context in table.values {
context.clearCaches()
}
}
}
#endif
| mit | bce7a32dc7badc93af7fcca99068becc | 31.116279 | 157 | 0.620082 | 5.146584 | false | false | false | false |
duycao2506/SASCoffeeIOS | Pods/ExSwift/ExSwift/Range.swift | 1 | 1866 | //
// Range.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension Range {
/**
For each element in the range invokes function.
:param: function Function to call
*/
func times (function: () -> ()) {
each { (current: T) -> () in
function()
}
}
/**
For each element in the range invokes function passing the element as argument.
:param: function Function to invoke
*/
func times (function: (T) -> ()) {
each (function)
}
/**
For each element in the range invokes function passing the element as argument.
:param: function Function to invoke
*/
func each (function: (T) -> ()) {
for i in self {
function(i)
}
}
/**
Range of Int with random bounds between from and to (inclusive).
:param: from Lower bound
:param: to Upper bound
:returns: Random range
*/
static func random (from: Int, to: Int) -> Range<Int> {
let lowerBound = Int.random(min: from, max: to)
let upperBound = Int.random(min: lowerBound, max: to)
return lowerBound...upperBound
}
}
/**
* Operator == to compare 2 ranges first, second by start & end indexes. If first.startIndex is equal to
* second.startIndex and first.endIndex is equal to second.endIndex the ranges are considered equal.
*/
public func == <U: ForwardIndexType> (first: Range<U>, second: Range<U>) -> Bool {
return first.startIndex == second.startIndex &&
first.endIndex == second.endIndex
}
/**
* DP2 style open range operator
*/
public func .. <U : Comparable> (first: U, second: U) -> HalfOpenInterval<U> {
return first..<second
}
| gpl-3.0 | ac40dea1d11b68be91d6ad17482e3a98 | 23.233766 | 104 | 0.57985 | 4.193258 | false | false | false | false |
omondigeno/ActionablePushMessages | PushedActionableMessages/DodoDistrib.swift | 1 | 78403 | //
// Dodo
//
// A message bar for iOS.
//
// https://github.com/marketplacer/Dodo
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// DodoAnimation.swift
//
// ----------------------------
import UIKit
/// A closure that is called for animation of the bar when it is being shown or hidden.
public typealias DodoAnimation = (UIView, duration: NSTimeInterval?,
locationTop: Bool, completed: DodoAnimationCompleted)->()
/// A closure that is called by the animator when animation has finished.
public typealias DodoAnimationCompleted = ()->()
// ----------------------------
//
// DodoAnimations.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing and hiding the notification bar.
public enum DodoAnimations: String {
/// Animation that fades the bar in/out.
case Fade = "Fade"
/// Used for showing notification without animation.
case NoAnimation = "No animation"
/// Animation that rotates the bar around X axis in perspective with spring effect.
case Rotate = "Rotate"
/// Animation that swipes the bar to/from the left with fade effect.
case SlideLeft = "Slide left"
/// Animation that swipes the bar to/from the right with fade effect.
case SlideRight = "Slide right"
/// Animation that slides the bar in/out vertically.
case SlideVertically = "Slide vertically"
/**
Get animation function that can be used for showing notification bar.
- returns: Animation function.
*/
public var show: DodoAnimation {
switch self {
case .Fade:
return DodoAnimationsShow.fade
case .NoAnimation:
return DodoAnimations.noAnimation
case .Rotate:
return DodoAnimationsShow.rotate
case .SlideLeft:
return DodoAnimationsShow.slideLeft
case .SlideRight:
return DodoAnimationsShow.slideRight
case .SlideVertically:
return DodoAnimationsShow.slideVertically
}
}
/**
Get animation function that can be used for hiding notification bar.
- returns: Animation function.
*/
public var hide: DodoAnimation {
switch self {
case .Fade:
return DodoAnimationsHide.fade
case .NoAnimation:
return DodoAnimations.noAnimation
case .Rotate:
return DodoAnimationsHide.rotate
case .SlideLeft:
return DodoAnimationsHide.slideLeft
case .SlideRight:
return DodoAnimationsHide.slideRight
case .SlideVertically:
return DodoAnimationsHide.slideVertically
}
}
/**
A empty animator which is used when no animation is supplied.
It simply calls the completion closure.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func noAnimation(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
completed()
}
/// Helper function for fading the view in and out.
static func fade(duration: NSTimeInterval?, showView: Bool, view: UIView,
completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
let startAlpha: CGFloat = showView ? 0 : 1
let endAlpha: CGFloat = showView ? 1 : 0
view.alpha = startAlpha
UIView.animateWithDuration(actualDuration,
animations: {
view.alpha = endAlpha
},
completion: { finished in
completed()
}
)
}
/// Helper function for sliding the view vertically
static func slideVertically(duration: NSTimeInterval?, showView: Bool, view: UIView,
locationTop: Bool, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.5
view.layoutIfNeeded()
var distance: CGFloat = 0
if locationTop {
distance = view.frame.height + view.frame.origin.y
} else {
distance = UIScreen.mainScreen().bounds.height - view.frame.origin.y
}
let transform = CGAffineTransformMakeTranslation(0, locationTop ? -distance : distance)
let start: CGAffineTransform = showView ? transform : CGAffineTransformIdentity
let end: CGAffineTransform = showView ? CGAffineTransformIdentity : transform
view.transform = start
UIView.animateWithDuration(actualDuration,
delay: 0,
usingSpringWithDamping: 1,
initialSpringVelocity: 1,
options: [],
animations: {
view.transform = end
},
completion: { finished in
completed()
}
)
}
static weak var timer: MoaTimer?
/// Animation that rotates the bar around X axis in perspective with spring effect.
static func rotate(duration: NSTimeInterval?, showView: Bool, view: UIView, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 2.0
let start: Double = showView ? Double(M_PI / 2) : 0
let end: Double = showView ? 0 : Double(M_PI / 2)
let damping = showView ? 0.85 : 3
let myCALayer = view.layer
var transform = CATransform3DIdentity
transform.m34 = -1.0/200.0
myCALayer.transform = CATransform3DRotate(transform, CGFloat(end), 1, 0, 0)
myCALayer.zPosition = 300
SpringAnimationCALayer.animate(myCALayer,
keypath: "transform.rotation.x",
duration: actualDuration,
usingSpringWithDamping: damping,
initialSpringVelocity: 1,
fromValue: start,
toValue: end,
onFinished: showView ? completed : nil)
// Hide the bar prematurely for better looks
timer?.cancel()
if !showView {
timer = MoaTimer.runAfter(0.3) { timer in
completed()
}
}
}
/// Animation that swipes the bar to the right with fade-out effect.
static func slide(duration: NSTimeInterval?, right: Bool, showView: Bool,
view: UIView, completed: DodoAnimationCompleted) {
let actualDuration = duration ?? 0.4
let distance = UIScreen.mainScreen().bounds.width
let transform = CGAffineTransformMakeTranslation(right ? distance : -distance, 0)
let start: CGAffineTransform = showView ? transform : CGAffineTransformIdentity
let end: CGAffineTransform = showView ? CGAffineTransformIdentity : transform
let alphaStart: CGFloat = showView ? 0.2 : 1
let alphaEnd: CGFloat = showView ? 1 : 0.2
view.transform = start
view.alpha = alphaStart
UIView.animateWithDuration(actualDuration,
delay: 0,
options: UIViewAnimationOptions.CurveEaseOut,
animations: {
view.transform = end
view.alpha = alphaEnd
},
completion: { finished in
completed()
}
)
}
}
// ----------------------------
//
// DodoAnimationsHide.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for hiding the notification bar.
struct DodoAnimationsHide {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.rotate(duration, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar from to the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: false, showView: false, view: view, completed: completed)
}
/**
Animation that swipes the bar to the right with fade-out effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: true, showView: false, view: view, completed: completed)
}
/**
Animation that fades the bar out.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.fade(duration, showView: false, view: view, completed: completed)
}
/**
Animation that slides the bar vertically out of view.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slideVertically(duration, showView: false, view: view,
locationTop: locationTop, completed: completed)
}
}
// ----------------------------
//
// DodoAnimationsShow.swift
//
// ----------------------------
import UIKit
/// Collection of animation effects use for showing the notification bar.
struct DodoAnimationsShow {
/**
Animation that rotates the bar around X axis in perspective with spring effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func rotate(view: UIView, duration: NSTimeInterval?,
locationTop: Bool, completed: DodoAnimationCompleted) {
DodoAnimations.rotate(duration, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the left with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideLeft(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: false, showView: true, view: view, completed: completed)
}
/**
Animation that swipes the bar from the right with fade-in effect.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideRight(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slide(duration, right: true, showView: true, view: view, completed: completed)
}
/**
Animation that fades the bar in.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func fade(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.fade(duration, showView: true, view: view, completed: completed)
}
/**
Animation that slides the bar in/out vertically.
- parameter view: View supplied for animation.
- parameter completed: A closure to be called after animation completes.
*/
static func slideVertically(view: UIView, duration: NSTimeInterval?, locationTop: Bool,
completed: DodoAnimationCompleted) {
DodoAnimations.slideVertically(duration, showView: true, view: view,
locationTop: locationTop,completed: completed)
}
}
// ----------------------------
//
// DodoButtonOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar button is tapped
public typealias DodoButtonOnTap = ()->()
// ----------------------------
//
// DodoButtonView.swift
//
// ----------------------------
import UIKit
class DodoButtonView: UIImageView {
private let style: DodoButtonStyle
weak var delegate: DodoButtonViewDelegate?
var onTap: OnTap?
init(style: DodoButtonStyle) {
self.style = style
super.init(frame: CGRect())
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Create button views for given button styles.
static func createMany(styles: [DodoButtonStyle]) -> [DodoButtonView] {
if !haveButtons(styles) { return [] }
return styles.map { style in
let view = DodoButtonView(style: style)
view.setup()
return view
}
}
static func haveButtons(styles: [DodoButtonStyle]) -> Bool {
let hasImages = styles.filter({ $0.image != nil }).count > 0
let hasIcons = styles.filter({ $0.icon != nil }).count > 0
return hasImages || hasIcons
}
func doLayout(onLeftSide onLeftSide: Bool) {
precondition(delegate != nil, "Button view delegate can not be nil")
translatesAutoresizingMaskIntoConstraints = false
// Set button's size
TegAutolayoutConstraints.width(self, value: style.size.width)
TegAutolayoutConstraints.height(self, value: style.size.height)
if let superview = superview {
let alignAttribute = onLeftSide ? NSLayoutAttribute.Left : NSLayoutAttribute.Right
let marginHorizontal = onLeftSide ? style.horizontalMarginToBar : -style.horizontalMarginToBar
// Align the button to the left/right of the view
TegAutolayoutConstraints.alignSameAttributes(self, toItem: superview,
constraintContainer: superview,
attribute: alignAttribute, margin: marginHorizontal)
// Center the button verticaly
TegAutolayoutConstraints.centerY(self, viewTwo: superview, constraintContainer: superview)
}
}
func setup() {
if let image = DodoButtonView.image(style) { applyStyle(image) }
setupTap()
}
/// Increase the hitsize of the image view if it's less than 44px for easier tapping.
override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
let oprimizedBounds = DodoTouchTarget.optimize(bounds)
return oprimizedBounds.contains(point)
}
/// Returns the image supplied by user or create one from the icon
class func image(style: DodoButtonStyle) -> UIImage? {
if style.image != nil {
return style.image
}
if let icon = style.icon {
let bundle = NSBundle(forClass: self)
let imageName = icon.rawValue
return UIImage(named: imageName, inBundle: bundle, compatibleWithTraitCollection: nil)
}
return nil
}
private func applyStyle(imageIn: UIImage) {
var imageToShow = imageIn
if let tintColorToShow = style.tintColor {
// Replace image colors with the specified tint color
imageToShow = imageToShow.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
tintColor = tintColorToShow
}
layer.minificationFilter = kCAFilterTrilinear // make the image crisp
image = imageToShow
contentMode = UIViewContentMode.ScaleAspectFit
// Make button accessible
if let accessibilityLabelToShow = style.accessibilityLabel {
isAccessibilityElement = true
accessibilityLabel = accessibilityLabelToShow
accessibilityTraits = UIAccessibilityTraitButton
}
}
private func setupTap() {
onTap = OnTap(view: self, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTap()
}
}
private func didTap() {
self.delegate?.buttonDelegateDidTap(self.style)
style.onTap?()
}
}
// ----------------------------
//
// DodoButtonViewDelegate.swift
//
// ----------------------------
protocol DodoButtonViewDelegate: class {
func buttonDelegateDidTap(buttonStyle: DodoButtonStyle)
}
// ----------------------------
//
// Dodo.swift
//
// ----------------------------
import UIKit
/**
Main class that coordinates the process of showing and hiding of the message bar.
Instance of this class is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
final class Dodo: DodoInterface, DodoButtonViewDelegate {
private weak var superview: UIView!
private var hideTimer: MoaTimer?
// Gesture handler that hides the bar when it is tapped
var onTap: OnTap?
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport?
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport?
/// Defines styles for the bar.
var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
init(superview: UIView) {
self.superview = superview
DodoKeyboardListener.startListening()
}
/// Changes the style preset for the bar widget.
var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
/**
Shows the message bar with *.Success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(message: String) {
preset = .Success
show(message)
}
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(message: String) {
preset = .Info
show(message)
}
/**
Shows the message bar with *.Warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(message: String) {
preset = .Warning
show(message)
}
/**
Shows the message bar with *.Warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(message: String) {
preset = .Error
show(message)
}
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(message: String) {
removeExistingBars()
setupHideTimer()
let bar = DodoToolbar(witStyle: style)
setupHideOnTap(bar)
bar.layoutGuide = style.bar.locationTop ? topLayoutGuide : bottomLayoutGuide
bar.buttonViewDelegate = self
bar.show(inSuperview: superview, withMessage: message)
}
/// Hide the message bar if it's currently open.
func hide() {
hideTimer?.cancel()
toolbar?.hide(onAnimationCompleted: {})
}
func listenForKeyboard() {
}
private var toolbar: DodoToolbar? {
get {
return superview.subviews.filter { $0 is DodoToolbar }.map { $0 as! DodoToolbar }.first
}
}
private func removeExistingBars() {
for view in superview.subviews {
if let existingToolbar = view as? DodoToolbar {
existingToolbar.removeFromSuperview()
}
}
}
// MARK: - Hiding after delay
private func setupHideTimer() {
hideTimer?.cancel()
if style.bar.hideAfterDelaySeconds > 0 {
hideTimer = MoaTimer.runAfter(style.bar.hideAfterDelaySeconds) { [weak self] timer in
dispatch_async(dispatch_get_main_queue()) {
self?.hide()
}
}
}
}
// MARK: - Reacting to tap
private func setupHideOnTap(toolbar: UIView) {
onTap = OnTap(view: toolbar, gesture: UITapGestureRecognizer()) { [weak self] in
self?.didTapTheBar()
}
}
/// The bar has been tapped
private func didTapTheBar() {
style.bar.onTap?()
if style.bar.hideOnTap {
hide()
}
}
// MARK: - DodoButtonViewDelegate
func buttonDelegateDidTap(buttonStyle: DodoButtonStyle) {
if buttonStyle.hideOnTap {
hide()
}
}
}
// ----------------------------
//
// DodoBarOnTap.swift
//
// ----------------------------
/// A closure that is called when a bar is tapped
public typealias DodoBarOnTap = ()->()
// ----------------------------
//
// DodoInterface.swift
//
// ----------------------------
import UIKit
/**
Coordinates the process of showing and hiding of the message bar.
The instance is created automatically in the `dodo` property of any UIView instance.
It is not expected to be instantiated manually anywhere except unit tests.
For example:
let view = UIView()
view.dodo.info("Horses are blue?")
*/
public protocol DodoInterface: class {
/// Specify optional layout guide for positioning the bar view.
var topLayoutGuide: UILayoutSupport? { get set }
/// Specify optional layout guide for positioning the bar view.
var bottomLayoutGuide: UILayoutSupport? { get set }
/// Defines styles for the bar.
var style: DodoStyle { get set }
/// Changes the style preset for the bar widget.
var preset: DodoPresets { get set }
/**
Shows the message bar with *.Success* preset. It can be used to indicate successful completion of an operation.
- parameter message: The text message to be shown.
*/
func success(message: String)
/**
Shows the message bar with *.Info* preset. It can be used for showing information messages that have neutral emotional value.
- parameter message: The text message to be shown.
*/
func info(message: String)
/**
Shows the message bar with *.Warning* preset. It can be used for for showing warning messages.
- parameter message: The text message to be shown.
*/
func warning(message: String)
/**
Shows the message bar with *.Warning* preset. It can be used for showing critical error messages
- parameter message: The text message to be shown.
*/
func error(message: String)
/**
Shows the message bar. Set `preset` property to change the appearance of the message bar, or use the shortcut methods: `success`, `info`, `warning` and `error`.
- parameter message: The text message to be shown.
*/
func show(message: String)
/// Hide the message bar if it's currently open.
func hide()
}
// ----------------------------
//
// DodoKeyboardListener.swift
//
// ----------------------------
/**
Start listening for keyboard events. Used for moving the message bar from under the keyboard when the bar is shown at the bottom of the screen.
*/
struct DodoKeyboardListener {
static let underKeyboardLayoutConstraint = UnderKeyboardLayoutConstraint()
static func startListening() {
// Just access the static property to make it initialize itself lazily if it hasn't been already.
underKeyboardLayoutConstraint.isAccessibilityElement = false
}
}
// ----------------------------
//
// DodoToolbar.swift
//
// ----------------------------
import UIKit
class DodoToolbar: UIView {
var layoutGuide: UILayoutSupport?
var style: DodoStyle
weak var buttonViewDelegate: DodoButtonViewDelegate?
private var didCallHide = false
convenience init(witStyle style: DodoStyle) {
self.init(frame: CGRect())
self.style = style
}
override init(frame: CGRect) {
style = DodoStyle()
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func show(inSuperview parentView: UIView, withMessage message: String) {
if superview != nil { return } // already being shown
parentView.addSubview(self)
applyStyle()
layoutBarInSuperview()
let buttons = createButtons()
createLabel(message, withButtons: buttons)
style.bar.animationShow(self, duration: style.bar.animationShowDuration,
locationTop: style.bar.locationTop, completed: {})
}
func hide(onAnimationCompleted onAnimationCompleted: ()->()) {
// Respond only to the first hide() call
if didCallHide { return }
didCallHide = true
style.bar.animationHide(self, duration: style.bar.animationHideDuration,
locationTop: style.bar.locationTop, completed: { [weak self] in
self?.removeFromSuperview()
onAnimationCompleted()
})
}
// MARK: - Label
private func createLabel(message: String, withButtons buttons: [UIView]) {
let label = UILabel()
label.font = style.label.font
label.text = message
label.textColor = style.label.color
label.textAlignment = NSTextAlignment.Center
label.numberOfLines = style.label.numberOfLines
if style.bar.debugMode {
label.backgroundColor = UIColor.redColor()
}
if let shadowColor = style.label.shadowColor {
label.shadowColor = shadowColor
label.shadowOffset = style.label.shadowOffset
}
addSubview(label)
layoutLabel(label, withButtons: buttons)
}
private func layoutLabel(label: UILabel, withButtons buttons: [UIView]) {
label.translatesAutoresizingMaskIntoConstraints = false
// Stretch the label vertically
TegAutolayoutConstraints.fillParent(label, parentView: self,
margin: style.label.horizontalMargin, vertically: true)
if buttons.count == 0 {
if let superview = superview {
// If there are no buttons - stretch the label to the entire width of the view
TegAutolayoutConstraints.fillParent(label, parentView: superview,
margin: style.label.horizontalMargin, vertically: false)
}
} else {
layoutLabelWithButtons(label, withButtons: buttons)
}
}
private func layoutLabelWithButtons(label: UILabel, withButtons buttons: [UIView]) {
if buttons.count != 2 { return }
let views = [buttons[0], label, buttons[1]]
if let superview = superview {
TegAutolayoutConstraints.viewsNextToEachOther(views,
constraintContainer: superview, margin: style.label.horizontalMargin, vertically: false)
}
}
// MARK: - Buttons
private func createButtons() -> [DodoButtonView] {
precondition(buttonViewDelegate != nil, "Button view delegate can not be nil")
let buttonStyles = [style.leftButton, style.rightButton]
let buttonViews = DodoButtonView.createMany(buttonStyles)
for (index, button) in buttonViews.enumerate() {
addSubview(button)
button.delegate = buttonViewDelegate
button.doLayout(onLeftSide: index == 0)
if style.bar.debugMode {
button.backgroundColor = UIColor.yellowColor()
}
}
return buttonViews
}
// MARK: - Style the bar
private func applyStyle() {
backgroundColor = style.bar.backgroundColor
layer.cornerRadius = style.bar.cornerRadius
layer.masksToBounds = true
if let borderColor = style.bar.borderColor where style.bar.borderWidth > 0 {
layer.borderColor = borderColor.CGColor
layer.borderWidth = style.bar.borderWidth
}
}
private func layoutBarInSuperview() {
translatesAutoresizingMaskIntoConstraints = false
if let superview = superview {
// Stretch the toobar horizontally to the width if its superview
TegAutolayoutConstraints.fillParent(self, parentView: superview,
margin: style.bar.marginToSuperview.width, vertically: false)
let vMargin = style.bar.marginToSuperview.height
let verticalMargin = style.bar.locationTop ? -vMargin : vMargin
var verticalConstraints = [NSLayoutConstraint]()
if let layoutGuide = layoutGuide {
// Align the top/bottom edge of the toolbar with the top/bottom layout guide
// (a tab bar, for example)
verticalConstraints = TegAutolayoutConstraints.alignVerticallyToLayoutGuide(self,
onTop: style.bar.locationTop,
layoutGuide: layoutGuide,
constraintContainer: superview,
margin: verticalMargin)
} else {
// Align the top/bottom of the toolbar with the top/bottom of its superview
verticalConstraints = TegAutolayoutConstraints.alignSameAttributes(superview, toItem: self,
constraintContainer: superview,
attribute: style.bar.locationTop ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
margin: verticalMargin)
}
setupKeyboardEvader(verticalConstraints)
}
}
// Moves the message bar from under the keyboard
private func setupKeyboardEvader(verticalConstraints: [NSLayoutConstraint]) {
if let bottomConstraint = verticalConstraints.first,
superview = superview
where !style.bar.locationTop {
DodoKeyboardListener.underKeyboardLayoutConstraint.setup(bottomConstraint,
view: superview, bottomLayoutGuide: layoutGuide)
}
}
}
// ----------------------------
//
// DodoTouchTarget.swift
//
// ----------------------------
import UIKit
/**
Helper function to make sure bounds are big enought to be used as touch target.
The function is used in pointInside(point: CGPoint, withEvent event: UIEvent?) of UIImageView.
*/
struct DodoTouchTarget {
static func optimize(bounds: CGRect) -> CGRect {
let recommendedHitSize: CGFloat = 44
var hitWidthIncrease:CGFloat = recommendedHitSize - bounds.width
var hitHeightIncrease:CGFloat = recommendedHitSize - bounds.height
if hitWidthIncrease < 0 { hitWidthIncrease = 0 }
if hitHeightIncrease < 0 { hitHeightIncrease = 0 }
let extendedBounds: CGRect = CGRectInset(bounds,
-hitWidthIncrease / 2,
-hitHeightIncrease / 2)
return extendedBounds
}
}
// ----------------------------
//
// DodoIcons.swift
//
// ----------------------------
/**
Collection of icons included with Dodo library.
*/
public enum DodoIcons: String {
/// Icon for closing the bar.
case Close = "Close"
/// Icon for reloading.
case Reload = "Reload"
}
// ----------------------------
//
// DodoMock.swift
//
// ----------------------------
import UIKit
/**
This class is for testing the code that uses Dodo. It helps verifying the messages that were shown in the message bar without actually showing them.
Here is how to use it in your unit test.
1. Create an instance of DodoMock.
2. Set it to the `view.dodo` property of the view.
3. Run the code that you are testing.
4. Finally, verify which messages were shown in the message bar.
Example:
// Supply mock to the view
let dodoMock = DodoMock()
view.dodo = dodoMock
// Run the code from the app
runSomeAppCode()
// Verify the message is visible
XCTAssert(dodoMock.results.visible)
// Check total number of messages shown
XCTAssertEqual(1, dodoMock.results.total)
// Verify the text of the success message
XCTAssertEqual("To be prepared is half the victory.", dodoMock.results.success[0])
*/
public class DodoMock: DodoInterface {
/// This property is used in unit tests to verify which messages were displayed in the message bar.
public var results = DodoMockResults()
public var topLayoutGuide: UILayoutSupport?
public var bottomLayoutGuide: UILayoutSupport?
public var style = DodoStyle(parentStyle: DodoPresets.defaultPreset.style)
public init() { }
public var preset: DodoPresets = DodoPresets.defaultPreset {
didSet {
if preset != oldValue {
style.parent = preset.style
}
}
}
public func success(message: String) {
preset = .Success
show(message)
}
public func info(message: String) {
preset = .Info
show(message)
}
public func warning(message: String) {
preset = .Warning
show(message)
}
public func error(message: String) {
preset = .Error
show(message)
}
public func show(message: String) {
let mockMessage = DodoMockMessage(preset: preset, message: message)
results.messages.append(mockMessage)
results.visible = true
}
public func hide() {
results.visible = false
}
}
// ----------------------------
//
// DodoMockMessage.swift
//
// ----------------------------
/**
Contains information about the message that was displayed in message bar. Used in unit tests.
*/
struct DodoMockMessage {
let preset: DodoPresets
let message: String
}
// ----------------------------
//
// DodoMockResults.swift
//
// ----------------------------
/**
Used in unit tests to verify the messages that were shown in the message bar.
*/
public struct DodoMockResults {
/// An array of success messages displayed in the message bar.
public var success: [String] {
return messages.filter({ $0.preset == DodoPresets.Success }).map({ $0.message })
}
/// An array of information messages displayed in the message bar.
public var info: [String] {
return messages.filter({ $0.preset == DodoPresets.Info }).map({ $0.message })
}
/// An array of warning messages displayed in the message bar.
public var warning: [String] {
return messages.filter({ $0.preset == DodoPresets.Warning }).map({ $0.message })
}
/// An array of error messages displayed in the message bar.
public var errors: [String] {
return messages.filter({ $0.preset == DodoPresets.Error }).map({ $0.message })
}
/// Total number of messages shown.
public var total: Int {
return messages.count
}
/// Indicates whether the message is visible
public var visible = false
var messages = [DodoMockMessage]()
}
// ----------------------------
//
// DodoBarDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar view.
Default styles are used when individual element styles are not set.
*/
public struct DodoBarDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
animationHide = _animationHide
animationHideDuration = _animationHideDuration
animationShow = _animationShow
animationShowDuration = _animationShowDuration
backgroundColor = _backgroundColor
borderColor = _borderColor
borderWidth = _borderWidth
cornerRadius = _cornerRadius
debugMode = _debugMode
hideAfterDelaySeconds = _hideAfterDelaySeconds
hideOnTap = _hideOnTap
locationTop = _locationTop
marginToSuperview = _marginToSuperview
onTap = _onTap
}
// ---------------------------
private static let _animationHide: DodoAnimation = DodoAnimationsHide.rotate
/// Specify a function for animating the bar when it is hidden.
public static var animationHide: DodoAnimation = _animationHide
// ---------------------------
private static let _animationHideDuration: NSTimeInterval? = nil
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public static var animationHideDuration: NSTimeInterval? = _animationHideDuration
// ---------------------------
private static let _animationShow: DodoAnimation = DodoAnimationsShow.rotate
/// Specify a function for animating the bar when it is shown.
public static var animationShow: DodoAnimation = _animationShow
// ---------------------------
private static let _animationShowDuration: NSTimeInterval? = nil
/// Duration of show animation. When nil it uses default duration for selected animation function.
public static var animationShowDuration: NSTimeInterval? = _animationShowDuration
// ---------------------------
private static let _backgroundColor: UIColor? = nil
/// Background color of the bar.
public static var backgroundColor = _backgroundColor
// ---------------------------
private static let _borderColor: UIColor? = nil
/// Color of the bar's border.
public static var borderColor = _borderColor
// ---------------------------
private static let _borderWidth: CGFloat = 1 / UIScreen.mainScreen().scale
/// Border width of the bar.
public static var borderWidth = _borderWidth
// ---------------------------
private static let _cornerRadius: CGFloat = 20
/// Corner radius of the bar view.
public static var cornerRadius = _cornerRadius
// ---------------------------
private static let _debugMode = false
/// When true it highlights the view background for spotting layout issues.
public static var debugMode = _debugMode
// ---------------------------
private static let _hideAfterDelaySeconds: NSTimeInterval = 0
/**
Hides the bar automatically after the specified number of seconds.
The bar is kept on screen indefinitely if the value is zero.
*/
public static var hideAfterDelaySeconds = _hideAfterDelaySeconds
// ---------------------------
private static let _hideOnTap = false
/// When true the bar is hidden when user taps on it.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _locationTop = true
/// Position of the bar. When true the bar is shown on top of the screen.
public static var locationTop = _locationTop
// ---------------------------
private static let _marginToSuperview = CGSize(width: 5, height: 5)
/// Margin between the bar edge and its superview.
public static var marginToSuperview = _marginToSuperview
// ---------------------------
private static let _onTap: DodoBarOnTap? = nil
/// Supply a function that will be called when user taps the bar.
public static var onTap = _onTap
// ---------------------------
}
// ----------------------------
//
// DodoBarStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the bar view in general.
public class DodoBarStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoBarStyle?
init(parentStyle: DodoBarStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_animationHide = nil
_animationHideDuration = nil
_animationShow = nil
_animationShowDuration = nil
_backgroundColor = nil
_borderColor = nil
_borderWidth = nil
_cornerRadius = nil
_debugMode = nil
_hideAfterDelaySeconds = nil
_hideOnTap = nil
_locationTop = nil
_marginToSuperview = nil
_onTap = nil
}
// -----------------------------
private var _animationHide: DodoAnimation?
/// Specify a function for animating the bar when it is hidden.
public var animationHide: DodoAnimation {
get {
return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide
}
set {
_animationHide = newValue
}
}
// ---------------------------
private var _animationHideDuration: NSTimeInterval?
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public var animationHideDuration: NSTimeInterval? {
get {
return (_animationHideDuration ?? parent?.animationHideDuration) ??
DodoBarDefaultStyles.animationHideDuration
}
set {
_animationHideDuration = newValue
}
}
// ---------------------------
private var _animationShow: DodoAnimation?
/// Specify a function for animating the bar when it is shown.
public var animationShow: DodoAnimation {
get {
return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow
}
set {
_animationShow = newValue
}
}
// ---------------------------
private var _animationShowDuration: NSTimeInterval?
/// Duration of show animation. When nil it uses default duration for selected animation function.
public var animationShowDuration: NSTimeInterval? {
get {
return (_animationShowDuration ?? parent?.animationShowDuration) ??
DodoBarDefaultStyles.animationShowDuration
}
set {
_animationShowDuration = newValue
}
}
// ---------------------------
private var _backgroundColor: UIColor?
/// Background color of the bar.
public var backgroundColor: UIColor? {
get {
return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor
}
set {
_backgroundColor = newValue
}
}
// -----------------------------
private var _borderColor: UIColor?
/// Color of the bar's border.
public var borderColor: UIColor? {
get {
return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor
}
set {
_borderColor = newValue
}
}
// -----------------------------
private var _borderWidth: CGFloat?
/// Border width of the bar.
public var borderWidth: CGFloat {
get {
return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth
}
set {
_borderWidth = newValue
}
}
// -----------------------------
private var _cornerRadius: CGFloat?
/// Corner radius of the bar view.
public var cornerRadius: CGFloat {
get {
return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius
}
set {
_cornerRadius = newValue
}
}
// -----------------------------
private var _debugMode: Bool?
/// When true it highlights the view background for spotting layout issues.
public var debugMode: Bool {
get {
return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode
}
set {
_debugMode = newValue
}
}
// ---------------------------
private var _hideAfterDelaySeconds: NSTimeInterval?
/**
Hides the bar automatically after the specified number of seconds.
If nil the bar is kept on screen.
*/
public var hideAfterDelaySeconds: NSTimeInterval {
get {
return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ??
DodoBarDefaultStyles.hideAfterDelaySeconds
}
set {
_hideAfterDelaySeconds = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true the bar is hidden when user taps on it.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ??
DodoBarDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _locationTop: Bool?
/// Position of the bar. When true the bar is shown on top of the screen.
public var locationTop: Bool {
get {
return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop
}
set {
_locationTop = newValue
}
}
// -----------------------------
private var _marginToSuperview: CGSize?
/// Margin between the bar edge and its superview.
public var marginToSuperview: CGSize {
get {
return _marginToSuperview ?? parent?.marginToSuperview ??
DodoBarDefaultStyles.marginToSuperview
}
set {
_marginToSuperview = newValue
}
}
// ---------------------------
private var _onTap: DodoBarOnTap?
/// Supply a function that will be called when user taps the bar.
public var onTap: DodoBarOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoBarDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoButtonDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the bar button.
Default styles are used when individual element styles are not set.
*/
public struct DodoButtonDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
accessibilityLabel = _accessibilityLabel
hideOnTap = _hideOnTap
horizontalMarginToBar = _horizontalMarginToBar
icon = _icon
image = _image
onTap = _onTap
size = _size
tintColor = _tintColor
}
// ---------------------------
private static let _accessibilityLabel: String? = nil
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public static var accessibilityLabel = _accessibilityLabel
// ---------------------------
private static let _hideOnTap = false
/// When true it hides the bar when the button is tapped.
public static var hideOnTap = _hideOnTap
// ---------------------------
private static let _horizontalMarginToBar: CGFloat = 10
/// Margin between the bar edge and the button
public static var horizontalMarginToBar = _horizontalMarginToBar
// ---------------------------
private static let _icon: DodoIcons? = nil
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public static var icon = _icon
// ---------------------------
private static let _image: UIImage? = nil
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public static var image = _image
// ---------------------------
private static let _onTap: DodoButtonOnTap? = nil
/// Supply a function that will be called when user taps the button.
public static var onTap = _onTap
// ---------------------------
private static let _size = CGSize(width: 25, height: 25)
/// Size of the button.
public static var size = _size
// ---------------------------
private static let _tintColor: UIColor? = nil
/// Replaces the color of the image or icon. The original colors are used when nil.
public static var tintColor = _tintColor
// ---------------------------
}
// ----------------------------
//
// DodoButtonStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles for the bar button.
public class DodoButtonStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoButtonStyle?
init(parentStyle: DodoButtonStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_accessibilityLabel = nil
_hideOnTap = nil
_horizontalMarginToBar = nil
_icon = nil
_image = nil
_onTap = nil
_size = nil
_tintColor = nil
}
// -----------------------------
private var _accessibilityLabel: String?
/**
This text is spoken by the device when it is in accessibility mode. It is recommended to always set the accessibility label for your button. The text can be a short localized description of the button function, for example: "Close the message", "Reload" etc.
*/
public var accessibilityLabel: String? {
get {
return _accessibilityLabel ?? parent?.accessibilityLabel ?? DodoButtonDefaultStyles.accessibilityLabel
}
set {
_accessibilityLabel = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true it hides the bar when the button is tapped.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ?? DodoButtonDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _horizontalMarginToBar: CGFloat?
/// Horizontal margin between the bar edge and the button.
public var horizontalMarginToBar: CGFloat {
get {
return _horizontalMarginToBar ?? parent?.horizontalMarginToBar ??
DodoButtonDefaultStyles.horizontalMarginToBar
}
set {
_horizontalMarginToBar = newValue
}
}
// -----------------------------
private var _icon: DodoIcons?
/// When set it shows one of the default Dodo icons. Use `image` property to supply a custom image. The color of the image can be changed with `tintColor` property.
public var icon: DodoIcons? {
get {
return _icon ?? parent?.icon ?? DodoButtonDefaultStyles.icon
}
set {
_icon = newValue
}
}
// -----------------------------
private var _image: UIImage?
/// Custom image for the button. One can also use the `icon` property to show one of the default Dodo icons. The color of the image can be changed with `tintColor` property.
public var image: UIImage? {
get {
return _image ?? parent?.image ?? DodoButtonDefaultStyles.image
}
set {
_image = newValue
}
}
// ---------------------------
private var _onTap: DodoButtonOnTap?
/// Supply a function that will be called when user taps the button.
public var onTap: DodoButtonOnTap? {
get {
return _onTap ?? parent?.onTap ?? DodoButtonDefaultStyles.onTap
}
set {
_onTap = newValue
}
}
// -----------------------------
private var _size: CGSize?
/// Size of the button.
public var size: CGSize {
get {
return _size ?? parent?.size ?? DodoButtonDefaultStyles.size
}
set {
_size = newValue
}
}
// -----------------------------
private var _tintColor: UIColor?
/// Replaces the color of the image or icon. The original colors are used when nil.
public var tintColor: UIColor? {
get {
return _tintColor ?? parent?.tintColor ?? DodoButtonDefaultStyles.tintColor
}
set {
_tintColor = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoLabelDefaultStyles.swift
//
// ----------------------------
import UIKit
/**
Default styles for the text label.
Default styles are used when individual element styles are not set.
*/
public struct DodoLabelDefaultStyles {
/// Revert the property values to their defaults
public static func resetToDefaults() {
color = _color
font = _font
horizontalMargin = _horizontalMargin
numberOfLines = _numberOfLines
shadowColor = _shadowColor
shadowOffset = _shadowOffset
}
// ---------------------------
private static let _color = UIColor.whiteColor()
/// Color of the label text.
public static var color = _color
// ---------------------------
private static let _font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
/// Font of the label text.
public static var font = _font
// ---------------------------
private static let _horizontalMargin: CGFloat = 10
/// Margin between the bar/button edge and the label.
public static var horizontalMargin = _horizontalMargin
// ---------------------------
private static let _numberOfLines: Int = 3
/// The maximum number of lines in the label.
public static var numberOfLines = _numberOfLines
// ---------------------------
private static let _shadowColor: UIColor? = nil
/// Color of text shadow.
public static var shadowColor = _shadowColor
// ---------------------------
private static let _shadowOffset = CGSize(width: 0, height: 1)
/// Text shadow offset.
public static var shadowOffset = _shadowOffset
// ---------------------------
}
// ----------------------------
//
// DodoLabelStyle.swift
//
// ----------------------------
import UIKit
/// Defines styles related to the text label.
public class DodoLabelStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoLabelStyle?
init(parentStyle: DodoLabelStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_color = nil
_font = nil
_horizontalMargin = nil
_numberOfLines = nil
_shadowColor = nil
_shadowOffset = nil
}
// -----------------------------
private var _color: UIColor?
/// Color of the label text.
public var color: UIColor {
get {
return _color ?? parent?.color ?? DodoLabelDefaultStyles.color
}
set {
_color = newValue
}
}
// -----------------------------
private var _font: UIFont?
/// Color of the label text.
public var font: UIFont {
get {
return _font ?? parent?.font ?? DodoLabelDefaultStyles.font
}
set {
_font = newValue
}
}
// -----------------------------
private var _horizontalMargin: CGFloat?
/// Margin between the bar/button edge and the label.
public var horizontalMargin: CGFloat {
get {
return _horizontalMargin ?? parent?.horizontalMargin ??
DodoLabelDefaultStyles.horizontalMargin
}
set {
_horizontalMargin = newValue
}
}
// -----------------------------
private var _numberOfLines: Int?
/// The maximum number of lines in the label.
public var numberOfLines: Int {
get {
return _numberOfLines ?? parent?.numberOfLines ??
DodoLabelDefaultStyles.numberOfLines
}
set {
_numberOfLines = newValue
}
}
// -----------------------------
private var _shadowColor: UIColor?
/// Color of text shadow.
public var shadowColor: UIColor? {
get {
return _shadowColor ?? parent?.shadowColor ?? DodoLabelDefaultStyles.shadowColor
}
set {
_shadowColor = newValue
}
}
// -----------------------------
private var _shadowOffset: CGSize?
/// Text shadow offset.
public var shadowOffset: CGSize {
get {
return _shadowOffset ?? parent?.shadowOffset ?? DodoLabelDefaultStyles.shadowOffset
}
set {
_shadowOffset = newValue
}
}
// -----------------------------
}
// ----------------------------
//
// DodoPresets.swift
//
// ----------------------------
/**
Defines the style presets for the bar.
*/
public enum DodoPresets {
/// A styling preset used for indicating successful completion of an operation. Usually styled with green color.
case Success
/// A styling preset for showing information messages, neutral in color.
case Info
/// A styling preset for showing warning messages. Can be styled with yellow/orange colors.
case Warning
/// A styling preset for showing critical error messages. Usually styled with red color.
case Error
/// The preset is used by default for the bar if it's not set by the user.
static let defaultPreset = DodoPresets.Success
/// The preset cache.
private static var styles = [DodoPresets: DodoStyle]()
/// Returns the style for the preset
public var style: DodoStyle {
var style = DodoPresets.styles[self]
if style == nil {
style = DodoPresets.makeStyle(forPreset: self)
DodoPresets.styles[self] = style
}
precondition(style != nil, "Failed to create style")
return style ?? DodoStyle()
}
/// Reset alls preset styles to their initial states.
public static func resetAll() {
styles = [:]
}
/// Reset the preset style to its initial state.
public func reset() {
DodoPresets.styles.removeValueForKey(self)
}
private static func makeStyle(forPreset preset: DodoPresets) -> DodoStyle{
let style = DodoStyle()
switch preset {
case .Success:
style.bar.backgroundColor = DodoColor.fromHexString("#00CC03C9")
case .Info:
style.bar.backgroundColor = DodoColor.fromHexString("#0057FF96")
case .Warning:
style.bar.backgroundColor = DodoColor.fromHexString("#CEC411DD")
case .Error:
style.bar.backgroundColor = DodoColor.fromHexString("#FF0B0BCC")
}
return style
}
}
// ----------------------------
//
// DodoStyle.swift
//
// ----------------------------
import UIKit
/// Combines various styles for the toolbar element.
public class DodoStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoStyle? {
didSet {
changeParent()
}
}
init(parentStyle: DodoStyle? = nil) {
self.parent = parentStyle
}
private func changeParent() {
bar.parent = parent?.bar
label.parent = parent?.label
leftButton.parent = parent?.leftButton
rightButton.parent = parent?.rightButton
}
/**
Reverts all the default styles to their initial values. Usually used in setUp() function in the unit tests.
*/
public static func resetDefaultStyles() {
DodoBarDefaultStyles.resetToDefaults()
DodoLabelDefaultStyles.resetToDefaults()
DodoButtonDefaultStyles.resetToDefaults()
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
bar.clear()
label.clear()
leftButton.clear()
rightButton.clear()
}
/**
Styles for the bar view.
*/
public lazy var bar: DodoBarStyle = self.initBarStyle()
private func initBarStyle() -> DodoBarStyle {
return DodoBarStyle(parentStyle: parent?.bar)
}
/**
Styles for the text label.
*/
public lazy var label: DodoLabelStyle = self.initLabelStyle()
private func initLabelStyle() -> DodoLabelStyle {
return DodoLabelStyle(parentStyle: parent?.label)
}
/**
Styles for the left button.
*/
public lazy var leftButton: DodoButtonStyle = self.initLeftButtonStyle()
private func initLeftButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.leftButton)
}
/**
Styles for the right button.
*/
public lazy var rightButton: DodoButtonStyle = self.initRightButtonStyle()
private func initRightButtonStyle() -> DodoButtonStyle {
return DodoButtonStyle(parentStyle: parent?.rightButton)
}
}
// ----------------------------
//
// UIView+SwiftAlertBar.swift
//
// ----------------------------
import UIKit
private var sabAssociationKey: UInt8 = 0
/**
UIView extension for showing a notification widget.
let view = UIView()
view.dodo.show("Hello World!")
*/
public extension UIView {
/**
Message bar extension.
Call `dodo.show`, `dodo.success`, dodo.error` functions to show a notification widget in the view.
let view = UIView()
view.dodo.show("Hello World!")
*/
public var dodo: DodoInterface {
get {
if let value = objc_getAssociatedObject(self, &sabAssociationKey) as? DodoInterface {
return value
} else {
let dodo = Dodo(superview: self)
objc_setAssociatedObject(self, &sabAssociationKey, dodo,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return dodo
}
}
set {
objc_setAssociatedObject(self, &sabAssociationKey, newValue,
objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
// ----------------------------
//
// DodoColor.swift
//
// ----------------------------
import UIKit
/**
Creates a UIColor object from a string.
Examples:
DodoColor.fromHexString('#340f9a')
// With alpha channel
DodoColor.fromHexString('#f1a2b3a6')
*/
public class DodoColor {
/**
Creates a UIColor object from a string.
- parameter rgba: a RGB/RGBA string representation of color. It can include optional alpha value. Example: "#cca213" or "#cca21312" (with alpha value).
- returns: UIColor object.
*/
public class func fromHexString(rgba: String) -> UIColor {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if !rgba.hasPrefix("#") {
print("Warning: DodoColor.fromHexString, # character missing")
return UIColor()
}
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if !scanner.scanHexLongLong(&hexValue) {
print("Warning: DodoColor.fromHexString, error scanning hex value")
return UIColor()
}
if hex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("Warning: DodoColor.fromHexString, invalid rgb string, length should be 7 or 9")
return UIColor()
}
return UIColor(red: red, green: green, blue: blue, alpha: alpha)
}
}
// ----------------------------
//
// MoaTimer.swift
//
// ----------------------------
import UIKit
/**
Creates a timer that executes code after delay.
Usage
var timer: MoaTimer.runAfter?
...
func myFunc() {
timer = MoaTimer.runAfter(0.010) { timer in
... code to run
}
}
Canceling the timer
Timer is Canceling automatically when it is deallocated. You can also cancel it manually:
let timer = MoaTimer.runAfter(0.010) { timer in ... }
timer.cancel()
*/
final class MoaTimer: NSObject {
private let repeats: Bool
private var timer: NSTimer?
private var callback: ((MoaTimer)->())?
private init(interval: NSTimeInterval, repeats: Bool = false, callback: (MoaTimer)->()) {
self.repeats = repeats
super.init()
self.callback = callback
timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self,
selector: "timerFired:", userInfo: nil, repeats: repeats)
}
/// Timer is cancelled automatically when it is deallocated.
deinit {
cancel()
}
/**
Cancels the timer and prevents it from firing in the future.
Note that timer is cancelled automatically whe it is deallocated.
*/
func cancel() {
timer?.invalidate()
timer = nil
}
/**
Runs the closure after specified time interval.
- parameter interval: Time interval in milliseconds.
:repeats: repeats When true, the code is run repeatedly.
- returns: callback A closure to be run by the timer.
*/
class func runAfter(interval: NSTimeInterval, repeats: Bool = false,
callback: (MoaTimer)->()) -> MoaTimer {
return MoaTimer(interval: interval, repeats: repeats, callback: callback)
}
func timerFired(timer: NSTimer) {
self.callback?(self)
if !repeats { cancel() }
}
}
// ----------------------------
//
// OnTap.swift
//
// ----------------------------
import UIKit
/**
Calling tap with closure.
*/
class OnTap: NSObject {
var closure: ()->()
init(view: UIView, gesture: UIGestureRecognizer, closure:()->()) {
self.closure = closure
super.init()
view.addGestureRecognizer(gesture)
view.userInteractionEnabled = true
gesture.addTarget(self, action: "didTap:")
}
func didTap(gesture: UIGestureRecognizer) {
closure()
}
}
// ----------------------------
//
// SpringAnimationCALayer.swift
//
// ----------------------------
import UIKit
/**
Animating CALayer with spring effect in iOS with Swift
https://github.com/evgenyneu/SpringAnimationCALayer
*/
class SpringAnimationCALayer {
// Animates layer with spring effect.
class func animate(layer: CALayer,
keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double,
onFinished: (()->())?) {
CATransaction.begin()
CATransaction.setCompletionBlock(onFinished)
let animation = create(keypath, duration: duration,
usingSpringWithDamping: usingSpringWithDamping,
initialSpringVelocity: initialSpringVelocity,
fromValue: fromValue, toValue: toValue)
layer.addAnimation(animation, forKey: keypath + " spring animation")
CATransaction.commit()
}
// Creates CAKeyframeAnimation object
class func create(keypath: String,
duration: CFTimeInterval,
usingSpringWithDamping: Double,
initialSpringVelocity: Double,
fromValue: Double,
toValue: Double) -> CAKeyframeAnimation {
let dampingMultiplier = Double(10)
let velocityMultiplier = Double(10)
let values = animationValues(fromValue, toValue: toValue,
usingSpringWithDamping: dampingMultiplier * usingSpringWithDamping,
initialSpringVelocity: velocityMultiplier * initialSpringVelocity)
let animation = CAKeyframeAnimation(keyPath: keypath)
animation.values = values
animation.duration = duration
return animation
}
class func animationValues(fromValue: Double, toValue: Double,
usingSpringWithDamping: Double, initialSpringVelocity: Double) -> [Double]{
let numOfPoints = 1000
var values = [Double](count: numOfPoints, repeatedValue: 0.0)
let distanceBetweenValues = toValue - fromValue
for point in (0..<numOfPoints) {
let x = Double(point) / Double(numOfPoints)
let valueNormalized = animationValuesNormalized(x,
usingSpringWithDamping: usingSpringWithDamping, initialSpringVelocity: initialSpringVelocity)
let value = toValue - distanceBetweenValues * valueNormalized
values[point] = value
}
return values
}
private class func animationValuesNormalized(x: Double, usingSpringWithDamping: Double,
initialSpringVelocity: Double) -> Double {
return pow(M_E, -usingSpringWithDamping * x) * cos(initialSpringVelocity * x)
}
}
// ----------------------------
//
// TegAutolayoutConstraints.swift
//
// ----------------------------
//
// TegAlign.swift
//
// Collection of shortcuts to create autolayout constraints.
//
import UIKit
class TegAutolayoutConstraints {
class func centerX(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: false)
}
class func centerY(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
return center(viewOne, viewTwo: viewTwo, constraintContainer: constraintContainer, vertically: true)
}
private class func center(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, vertically: Bool = false) -> [NSLayoutConstraint] {
let attribute = vertically ? NSLayoutAttribute.CenterY : NSLayoutAttribute.CenterX
let constraint = NSLayoutConstraint(
item: viewOne,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: viewTwo,
attribute: attribute,
multiplier: 1,
constant: 0)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func alignSameAttributes(item: AnyObject, toItem: AnyObject,
constraintContainer: UIView, attribute: NSLayoutAttribute, margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: item,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: toItem,
attribute: attribute,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func alignVerticallyToLayoutGuide(item: AnyObject, onTop: Bool,
layoutGuide: UILayoutSupport, constraintContainer: UIView,
margin: CGFloat = 0) -> [NSLayoutConstraint] {
let constraint = NSLayoutConstraint(
item: layoutGuide,
attribute: onTop ? NSLayoutAttribute.Bottom : NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: item,
attribute: onTop ? NSLayoutAttribute.Top : NSLayoutAttribute.Bottom,
multiplier: 1,
constant: margin)
constraintContainer.addConstraint(constraint)
return [constraint]
}
class func aspectRatio(view: UIView, ratio: CGFloat) {
let constraint = NSLayoutConstraint(
item: view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Height,
multiplier: ratio,
constant: 0)
view.addConstraint(constraint)
}
class func fillParent(view: UIView, parentView: UIView, margin: CGFloat = 0, vertically: Bool = false) {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "|\(marginFormat)[view]\(marginFormat)|"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: ["view": view])
parentView.addConstraints(constraints)
}
class func viewsNextToEachOther(views: [UIView],
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
if views.count < 2 { return [] }
var constraints = [NSLayoutConstraint]()
for (index, view) in views.enumerate() {
if index >= views.count - 1 { break }
let viewTwo = views[index + 1]
constraints += twoViewsNextToEachOther(view, viewTwo: viewTwo,
constraintContainer: constraintContainer, margin: margin, vertically: vertically)
}
return constraints
}
class func twoViewsNextToEachOther(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView, margin: CGFloat = 0,
vertically: Bool = false) -> [NSLayoutConstraint] {
var marginFormat = ""
if margin != 0 {
marginFormat = "-\(margin)-"
}
var format = "[viewOne]\(marginFormat)[viewTwo]"
if vertically {
format = "V:" + format
}
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(format,
options: [], metrics: nil,
views: [ "viewOne": viewOne, "viewTwo": viewTwo ])
constraintContainer.addConstraints(constraints)
return constraints
}
class func equalWidth(viewOne: UIView, viewTwo: UIView,
constraintContainer: UIView) -> [NSLayoutConstraint] {
let constraints = NSLayoutConstraint.constraintsWithVisualFormat("[viewOne(==viewTwo)]",
options: [], metrics: nil,
views: ["viewOne": viewOne, "viewTwo": viewTwo])
constraintContainer.addConstraints(constraints)
return constraints
}
class func height(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: false)
}
class func width(view: UIView, value: CGFloat) -> [NSLayoutConstraint] {
return widthOrHeight(view, value: value, isWidth: true)
}
private class func widthOrHeight(view: UIView, value: CGFloat,
isWidth: Bool) -> [NSLayoutConstraint] {
let attribute = isWidth ? NSLayoutAttribute.Width : NSLayoutAttribute.Height
let constraint = NSLayoutConstraint(
item: view,
attribute: attribute,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: value)
view.addConstraint(constraint)
return [constraint]
}
}
// ----------------------------
//
// UnderKeyboardDistrib.swift
//
// ----------------------------
//
// An iOS libary for moving content from under the keyboard.
//
// https://github.com/marketplacer/UnderKeyboard
//
// This file was automatically generated by combining multiple Swift source files.
//
// ----------------------------
//
// UnderKeyboardLayoutConstraint.swift
//
// ----------------------------
import UIKit
/**
Adjusts the length (constant value) of the bottom layout constraint when keyboard shows and hides.
*/
@objc public class UnderKeyboardLayoutConstraint: NSObject {
private weak var bottomLayoutConstraint: NSLayoutConstraint?
private weak var bottomLayoutGuide: UILayoutSupport?
private var keyboardObserver = UnderKeyboardObserver()
private var initialConstraintConstant: CGFloat = 0
private var minMargin: CGFloat = 10
private var viewToAnimate: UIView?
public override init() {
super.init()
keyboardObserver.willAnimateKeyboard = keyboardWillAnimate
keyboardObserver.animateKeyboard = animateKeyboard
keyboardObserver.start()
}
deinit {
stop()
}
/// Stop listening for keyboard notifications.
public func stop() {
keyboardObserver.stop()
}
/**
Supply a bottom Auto Layout constraint. Its constant value will be adjusted by the height of the keyboard when it appears and hides.
- parameter bottomLayoutConstraint: Supply a bottom layout constraint. Its constant value will be adjusted when keyboard is shown and hidden.
- parameter view: Supply a view that will be used to animate the constraint. It is usually the superview containing the view with the constraint.
- parameter minMargin: Specify the minimum margin between the keyboard and the bottom of the view the constraint is attached to. Default: 10.
- parameter bottomLayoutGuide: Supply an optional bottom layout guide (like a tab bar) that will be taken into account during height calculations.
*/
public func setup(bottomLayoutConstraint: NSLayoutConstraint,
view: UIView, minMargin: CGFloat = 10,
bottomLayoutGuide: UILayoutSupport? = nil) {
initialConstraintConstant = bottomLayoutConstraint.constant
self.bottomLayoutConstraint = bottomLayoutConstraint
self.minMargin = minMargin
self.bottomLayoutGuide = bottomLayoutGuide
self.viewToAnimate = view
// Keyboard is already open when setup is called
if let currentKeyboardHeight = keyboardObserver.currentKeyboardHeight
where currentKeyboardHeight > 0 {
keyboardWillAnimate(currentKeyboardHeight)
}
}
func keyboardWillAnimate(height: CGFloat) {
guard let bottomLayoutConstraint = bottomLayoutConstraint else { return }
let layoutGuideHeight = bottomLayoutGuide?.length ?? 0
let correctedHeight = height - layoutGuideHeight
if height > 0 {
let newConstantValue = correctedHeight + minMargin
if newConstantValue > initialConstraintConstant {
// Keyboard height is bigger than the initial constraint length.
// Increase constraint length.
bottomLayoutConstraint.constant = newConstantValue
} else {
// Keyboard height is NOT bigger than the initial constraint length.
// Show the initial constraint length.
bottomLayoutConstraint.constant = initialConstraintConstant
}
} else {
bottomLayoutConstraint.constant = initialConstraintConstant
}
}
func animateKeyboard(height: CGFloat) {
viewToAnimate?.layoutIfNeeded()
}
}
// ----------------------------
//
// UnderKeyboardObserver.swift
//
// ----------------------------
import UIKit
/**
Detects appearance of software keyboard and calls the supplied closures that can be used for changing the layout and moving view from under the keyboard.
*/
public final class UnderKeyboardObserver: NSObject {
public typealias AnimationCallback = (height: CGFloat) -> ()
let notificationCenter: NSNotificationCenter
/// Function that will be called before the keyboard is shown and before animation is started.
public var willAnimateKeyboard: AnimationCallback?
/// Function that will be called inside the animation block. This can be used to call `layoutIfNeeded` on the view.
public var animateKeyboard: AnimationCallback?
/// Current height of the keyboard. Has value `nil` if unknown.
public var currentKeyboardHeight: CGFloat?
public override init() {
notificationCenter = NSNotificationCenter.defaultCenter()
super.init()
}
deinit {
stop()
}
/// Start listening for keyboard notifications.
public func start() {
stop()
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillShowNotification, object: nil);
notificationCenter.addObserver(self, selector: Selector("keyboardNotification:"), name:UIKeyboardWillHideNotification, object: nil);
}
/// Stop listening for keyboard notifications.
public func stop() {
notificationCenter.removeObserver(self)
}
// MARK: - Notification
func keyboardNotification(notification: NSNotification) {
let isShowing = notification.name == UIKeyboardWillShowNotification
if let userInfo = notification.userInfo,
let height = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue().height,
let duration: NSTimeInterval = (userInfo[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let animationCurveRawNSN = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber {
let correctedHeight = isShowing ? height : 0
willAnimateKeyboard?(height: correctedHeight)
UIView.animateWithDuration(duration,
delay: NSTimeInterval(0),
options: UIViewAnimationOptions(rawValue: animationCurveRawNSN.unsignedLongValue),
animations: { [weak self] in
self?.animateKeyboard?(height: correctedHeight)
},
completion: nil
)
currentKeyboardHeight = correctedHeight
}
}
}
| apache-2.0 | cc7d624480f1d962142db8ac55fd842c | 24.655432 | 260 | 0.642731 | 5.148608 | false | false | false | false |
justindarc/firefox-ios | Account/FxAState.swift | 2 | 13469 | /* 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 FxA
import Shared
import SwiftyJSON
// The version of the state schema we persist.
let StateSchemaVersion = 2
// We want an enum because the set of states is closed. However, each state has state-specific
// behaviour, and the state's behaviour accumulates, so each state is a class. Switch on the
// label to get exhaustive cases.
public enum FxAStateLabel: String {
case engagedBeforeVerified = "engagedBeforeVerified"
case engagedAfterVerified = "engagedAfterVerified"
case cohabitingBeforeKeyPair = "cohabitingBeforeKeyPair"
case cohabitingAfterKeyPair = "cohabitingAfterKeyPair"
case married = "married"
case separated = "separated"
case doghouse = "doghouse"
// See http://stackoverflow.com/a/24137319
static let allValues: [FxAStateLabel] = [
engagedBeforeVerified,
engagedAfterVerified,
cohabitingBeforeKeyPair,
cohabitingAfterKeyPair,
married,
separated,
doghouse,
]
}
public enum FxAActionNeeded {
case none
case needsVerification
case needsPassword
case needsUpgrade
}
func state(fromJSON json: JSON) -> FxAState? {
if json.error != nil {
return nil
}
if let version = json["version"].int {
if version == 1 {
return stateV1(fromJSON: json)
} else if version == 2 {
return stateV2(fromJSON: json)
}
}
return nil
}
func stateV1(fromJSON json: JSON) -> FxAState? {
var json = json
json["version"] = 2
if let kB = json["kB"].string?.hexDecodedData {
let kSync = FxAClient10.deriveKSync(kB)
let kXCS = FxAClient10.computeClientState(kB)
json["kSync"] = JSON(kSync.hexEncodedString as NSString)
json["kXCS"] = JSON(kXCS as NSString)
json["kA"] = JSON.null
json["kB"] = JSON.null
}
return stateV2(fromJSON: json)
}
// Identical to V1 except `(kA, kB)` have been replaced with `(kSync, kXCS)` throughout.
func stateV2(fromJSON json: JSON) -> FxAState? {
if let labelString = json["label"].string {
if let label = FxAStateLabel(rawValue: labelString) {
switch label {
case .engagedBeforeVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData,
let knownUnverifiedAt = json["knownUnverifiedAt"].int64,
let lastNotifiedUserAt = json["lastNotifiedUserAt"].int64 {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: UInt64(knownUnverifiedAt), lastNotifiedUserAt: UInt64(lastNotifiedUserAt),
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .engagedAfterVerified:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let keyFetchToken = json["keyFetchToken"].string?.hexDecodedData,
let unwrapkB = json["unwrapkB"].string?.hexDecodedData {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
case .cohabitingBeforeKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string {
return CohabitingBeforeKeyPairState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS)
}
case .cohabitingAfterKeyPair:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string,
let keyPairJSON = json["keyPair"].dictionaryObject,
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64 {
return CohabitingAfterKeyPairState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt))
}
case .married:
if let
sessionToken = json["sessionToken"].string?.hexDecodedData,
let kSync = json["kSync"].string?.hexDecodedData,
let kXCS = json["kXCS"].string,
let keyPairJSON = json["keyPair"].dictionaryObject,
let keyPair = RSAKeyPair(jsonRepresentation: keyPairJSON),
let keyPairExpiresAt = json["keyPairExpiresAt"].int64,
let certificate = json["certificate"].string,
let certificateExpiresAt = json["certificateExpiresAt"].int64 {
return MarriedState(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: UInt64(keyPairExpiresAt),
certificate: certificate, certificateExpiresAt: UInt64(certificateExpiresAt))
}
case .separated:
return SeparatedState()
case .doghouse:
return DoghouseState()
}
}
}
return nil
}
// Not an externally facing state!
open class FxAState: JSONLiteralConvertible {
open var label: FxAStateLabel { return FxAStateLabel.separated } // This is bogus, but we have to do something!
open var actionNeeded: FxAActionNeeded {
// Kind of nice to have this in one place.
switch label {
case .engagedBeforeVerified: return .needsVerification
case .engagedAfterVerified: return .none
case .cohabitingBeforeKeyPair: return .none
case .cohabitingAfterKeyPair: return .none
case .married: return .none
case .separated: return .needsPassword
case .doghouse: return .needsUpgrade
}
}
open func asJSON() -> JSON {
return JSON([
"version": StateSchemaVersion,
"label": self.label.rawValue,
])
}
}
open class SeparatedState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.separated }
override public init() {
super.init()
}
}
// Not an externally facing state!
open class TokenState: FxAState {
let sessionToken: Data
init(sessionToken: Data) {
self.sessionToken = sessionToken
super.init()
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["sessionToken"] = JSON(sessionToken.hexEncodedString as NSString)
return JSON(d)
}
}
// Not an externally facing state!
open class ReadyForKeys: TokenState {
let keyFetchToken: Data
let unwrapkB: Data
init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.keyFetchToken = keyFetchToken
self.unwrapkB = unwrapkB
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d: [String: JSON] = super.asJSON().dictionary!
d["keyFetchToken"] = JSON(keyFetchToken.hexEncodedString as NSString)
d["unwrapkB"] = JSON(unwrapkB.hexEncodedString as NSString)
return JSON(d)
}
}
open class EngagedBeforeVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedBeforeVerified }
// Timestamp, in milliseconds after the epoch, when we first knew the account was unverified.
// Use this to avoid nagging the user to verify her account immediately after connecting.
let knownUnverifiedAt: Timestamp
let lastNotifiedUserAt: Timestamp
public init(knownUnverifiedAt: Timestamp, lastNotifiedUserAt: Timestamp, sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
self.knownUnverifiedAt = knownUnverifiedAt
self.lastNotifiedUserAt = lastNotifiedUserAt
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["knownUnverifiedAt"] = JSON(NSNumber(value: knownUnverifiedAt))
d["lastNotifiedUserAt"] = JSON(NSNumber(value: lastNotifiedUserAt))
return JSON(d)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedBeforeVerifiedState {
return EngagedBeforeVerifiedState(
knownUnverifiedAt: knownUnverifiedAt, lastNotifiedUserAt: lastNotifiedUserAt,
sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
open class EngagedAfterVerifiedState: ReadyForKeys {
override open var label: FxAStateLabel { return FxAStateLabel.engagedAfterVerified }
override public init(sessionToken: Data, keyFetchToken: Data, unwrapkB: Data) {
super.init(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
func withUnwrapKey(_ unwrapkB: Data) -> EngagedAfterVerifiedState {
return EngagedAfterVerifiedState(sessionToken: sessionToken, keyFetchToken: keyFetchToken, unwrapkB: unwrapkB)
}
}
// Not an externally facing state!
open class TokenAndKeys: TokenState {
public let kSync: Data
public let kXCS: String
init(sessionToken: Data, kSync: Data, kXCS: String) {
self.kSync = kSync
self.kXCS = kXCS
super.init(sessionToken: sessionToken)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["kSync"] = JSON(kSync.hexEncodedString as NSString)
d["kXCS"] = JSON(kXCS as NSString)
return JSON(d)
}
}
open class CohabitingBeforeKeyPairState: TokenAndKeys {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingBeforeKeyPair }
}
// Not an externally facing state!
open class TokenKeysAndKeyPair: TokenAndKeys {
let keyPair: KeyPair
// Timestamp, in milliseconds after the epoch, when keyPair expires. After this time, generate a new keyPair.
let keyPairExpiresAt: Timestamp
init(sessionToken: Data, kSync: Data, kXCS: String, keyPair: KeyPair, keyPairExpiresAt: Timestamp) {
self.keyPair = keyPair
self.keyPairExpiresAt = keyPairExpiresAt
super.init(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["keyPair"] = JSON(keyPair.jsonRepresentation() as Any)
d["keyPairExpiresAt"] = JSON(NSNumber(value: keyPairExpiresAt))
return JSON(d)
}
func isKeyPairExpired(_ now: Timestamp) -> Bool {
return keyPairExpiresAt < now
}
}
open class CohabitingAfterKeyPairState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.cohabitingAfterKeyPair }
}
open class MarriedState: TokenKeysAndKeyPair {
override open var label: FxAStateLabel { return FxAStateLabel.married }
let certificate: String
let certificateExpiresAt: Timestamp
init(sessionToken: Data, kSync: Data, kXCS: String, keyPair: KeyPair, keyPairExpiresAt: Timestamp, certificate: String, certificateExpiresAt: Timestamp) {
self.certificate = certificate
self.certificateExpiresAt = certificateExpiresAt
super.init(sessionToken: sessionToken, kSync: kSync, kXCS: kXCS, keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
}
open override func asJSON() -> JSON {
var d = super.asJSON().dictionary!
d["certificate"] = JSON(certificate as NSString)
d["certificateExpiresAt"] = JSON(NSNumber(value: certificateExpiresAt))
return JSON(d)
}
func isCertificateExpired(_ now: Timestamp) -> Bool {
return certificateExpiresAt < now
}
func withoutKeyPair() -> CohabitingBeforeKeyPairState {
let newState = CohabitingBeforeKeyPairState(sessionToken: sessionToken,
kSync: kSync, kXCS: kXCS)
return newState
}
func withoutCertificate() -> CohabitingAfterKeyPairState {
let newState = CohabitingAfterKeyPairState(sessionToken: sessionToken,
kSync: kSync, kXCS: kXCS,
keyPair: keyPair, keyPairExpiresAt: keyPairExpiresAt)
return newState
}
open func generateAssertionForAudience(_ audience: String, now: Timestamp) -> String {
let assertion = JSONWebTokenUtils.createAssertionWithPrivateKeyToSign(with: keyPair.privateKey,
certificate: certificate,
audience: audience,
issuer: "127.0.0.1",
issuedAt: now,
duration: OneHourInMilliseconds)
return assertion!
}
}
open class DoghouseState: FxAState {
override open var label: FxAStateLabel { return FxAStateLabel.doghouse }
override public init() {
super.init()
}
}
| mpl-2.0 | c6c12b64d688f99f1d4c8364e0a078b9 | 36.940845 | 158 | 0.649937 | 5.31951 | false | false | false | false |
tomasharkema/R.swift | Sources/RswiftCore/ResourceTypes/Storyboard.swift | 1 | 9853 | //
// Storyboard.swift
// R.swift
//
// Created by Mathijs Kadijk on 09-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
private let ElementNameToTypeMapping = [
"viewController": Type._UIViewController,
"tableViewCell": Type(module: "UIKit", name: "UITableViewCell"),
"tabBarController": Type(module: "UIKit", name: "UITabBarController"),
"glkViewController": Type(module: "GLKit", name: "GLKViewController"),
"pageViewController": Type(module: "UIKit", name: "UIPageViewController"),
"tableViewController": Type(module: "UIKit", name: "UITableViewController"),
"splitViewController": Type(module: "UIKit", name: "UISplitViewController"),
"navigationController": Type(module: "UIKit", name: "UINavigationController"),
"avPlayerViewController": Type(module: "AVKit", name: "AVPlayerViewController"),
"collectionViewController": Type(module: "UIKit", name: "UICollectionViewController"),
]
struct Storyboard: WhiteListedExtensionsResourceType, ReusableContainer {
static let supportedExtensions: Set<String> = ["storyboard"]
let name: String
private let initialViewControllerIdentifier: String?
let viewControllers: [ViewController]
let viewControllerPlaceholders: [ViewControllerPlaceholder]
let usedAccessibilityIdentifiers: [String]
let usedImageIdentifiers: [String]
let usedColorResources: [String]
let reusables: [Reusable]
var initialViewController: ViewController? {
return viewControllers
.filter { $0.id == self.initialViewControllerIdentifier }
.first
}
init(url: URL) throws {
try Storyboard.throwIfUnsupportedExtension(url.pathExtension)
guard let filename = url.filename else {
throw ResourceParsingError.parsingFailed("Couldn't extract filename from URL: \(url)")
}
name = filename
guard let parser = XMLParser(contentsOf: url) else {
throw ResourceParsingError.parsingFailed("Couldn't load file at: '\(url)'")
}
let parserDelegate = StoryboardParserDelegate()
parser.delegate = parserDelegate
guard parser.parse() else {
throw ResourceParsingError.parsingFailed("Invalid XML in file at: '\(url)'")
}
initialViewControllerIdentifier = parserDelegate.initialViewControllerIdentifier
viewControllers = parserDelegate.viewControllers
viewControllerPlaceholders = parserDelegate.viewControllerPlaceholders
usedAccessibilityIdentifiers = parserDelegate.usedAccessibilityIdentifiers
usedImageIdentifiers = parserDelegate.usedImageIdentifiers
usedColorResources = parserDelegate.usedColorReferences
reusables = parserDelegate.reusables
}
struct ViewController {
let id: String
let storyboardIdentifier: String?
let type: Type
private(set) var segues: [Segue]
fileprivate mutating func add(_ segue: Segue) {
segues.append(segue)
}
}
struct ViewControllerPlaceholder {
enum ResolvedResult {
case customBundle
case resolved(ViewController?)
}
let id: String
let storyboardName: String?
let referencedIdentifier: String?
let bundleIdentifier: String?
func resolveWithStoryboards(_ storyboards: [Storyboard]) -> ResolvedResult {
if nil != bundleIdentifier {
// Can't resolve storyboard in other bundles
return .customBundle
}
guard let storyboardName = storyboardName else {
// Storyboard reference without a storyboard defined?!
return .resolved(nil)
}
let storyboard = storyboards
.filter { $0.name == storyboardName }
guard let referencedIdentifier = referencedIdentifier else {
return .resolved(storyboard.first?.initialViewController)
}
return .resolved(storyboard
.flatMap {
$0.viewControllers.filter { $0.storyboardIdentifier == referencedIdentifier }
}
.first)
}
}
struct Segue {
let identifier: String
let type: Type
let destination: String
let kind: String
}
}
private class StoryboardParserDelegate: NSObject, XMLParserDelegate {
var initialViewControllerIdentifier: String?
var viewControllers: [Storyboard.ViewController] = []
var viewControllerPlaceholders: [Storyboard.ViewControllerPlaceholder] = []
var usedImageIdentifiers: [String] = []
var usedColorReferences: [String] = []
var usedAccessibilityIdentifiers: [String] = []
var reusables: [Reusable] = []
// State
var currentViewController: Storyboard.ViewController?
@objc func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
switch elementName {
case "document":
if let initialViewController = attributeDict["initialViewController"] {
initialViewControllerIdentifier = initialViewController
}
case "segue":
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
if let customType = customType , attributeDict["kind"] != "custom" , attributeDict["kind"] != "unwind" {
warn("Set the segue of class \(customType) with identifier '\(attributeDict["identifier"] ?? "-no identifier-")' to type custom, using segue subclasses with other types can cause crashes on iOS 8 and lower.")
}
if let segueIdentifier = attributeDict["identifier"],
let destination = attributeDict["destination"],
let kind = attributeDict["kind"]
{
let type = customType ?? Type._UIStoryboardSegue
let segue = Storyboard.Segue(identifier: segueIdentifier, type: type, destination: destination, kind: kind)
currentViewController?.add(segue)
}
case "image":
if let imageIdentifier = attributeDict["name"] {
usedImageIdentifiers.append(imageIdentifier)
}
case "color":
if let colorName = attributeDict["name"] {
usedColorReferences.append(colorName)
}
case "accessibility":
if let accessibilityIdentifier = attributeDict["identifier"] {
usedAccessibilityIdentifiers.append(accessibilityIdentifier)
}
case "userDefinedRuntimeAttribute":
if let accessibilityIdentifier = attributeDict["value"], "accessibilityIdentifier" == attributeDict["keyPath"] && "string" == attributeDict["type"] {
usedAccessibilityIdentifiers.append(accessibilityIdentifier)
}
case "viewControllerPlaceholder":
if let id = attributeDict["id"] , attributeDict["sceneMemberID"] == "viewController" {
let placeholder = Storyboard.ViewControllerPlaceholder(
id: id,
storyboardName: attributeDict["storyboardName"],
referencedIdentifier: attributeDict["referencedIdentifier"],
bundleIdentifier: attributeDict["bundleIdentifier"]
)
viewControllerPlaceholders.append(placeholder)
}
default:
if let viewController = viewControllerFromAttributes(attributeDict, elementName: elementName) {
currentViewController = viewController
}
if let reusable = reusableFromAttributes(attributeDict, elementName: elementName) {
reusables.append(reusable)
}
}
}
@objc func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
// We keep the current view controller open to collect segues until the closing scene:
// <scene>
// <viewController>
// ...
// <segue />
// </viewController>
// <segue />
// </scene>
if elementName == "scene" {
if let currentViewController = currentViewController {
viewControllers.append(currentViewController)
self.currentViewController = nil
}
}
}
func viewControllerFromAttributes(_ attributeDict: [String : String], elementName: String) -> Storyboard.ViewController? {
guard let id = attributeDict["id"] , attributeDict["sceneMemberID"] == "viewController" else {
return nil
}
let storyboardIdentifier = attributeDict["storyboardIdentifier"]
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
let type = customType ?? ElementNameToTypeMapping[elementName] ?? Type._UIViewController
return Storyboard.ViewController(id: id, storyboardIdentifier: storyboardIdentifier, type: type, segues: [])
}
func reusableFromAttributes(_ attributeDict: [String : String], elementName: String) -> Reusable? {
guard let reuseIdentifier = attributeDict["reuseIdentifier"] , reuseIdentifier != "" else {
return nil
}
let customModuleProvider = attributeDict["customModuleProvider"]
let customModule = (customModuleProvider == "target") ? nil : attributeDict["customModule"]
let customClass = attributeDict["customClass"]
let customType = customClass
.map { SwiftIdentifier(name: $0, lowercaseStartingCharacters: false) }
.map { Type(module: Module(name: customModule), name: $0, optional: false) }
let type = customType ?? ElementNameToTypeMapping[elementName] ?? Type._UIView
return Reusable(identifier: reuseIdentifier, type: type)
}
}
| mit | a4bd7ac6e12b71cb8f18f9c8d56e3ecf | 36.32197 | 216 | 0.707094 | 5.294465 | false | false | false | false |
davidcairns/IntroToXcodeGA | DCDrawingStore.swift | 1 | 1187 | //
// DCDrawingStore.swift
// Drawr
//
// Created by David Cairns on 5/17/15.
// Copyright (c) 2015 David Cairns. All rights reserved.
//
import UIKit
public class DCDrawingStore {
static let sharedInstance = DCDrawingStore()
var images: [UIImage]
private let kCachedImagesKey = "kCachedImagesKey"
init() {
images = []
if let storedImageDataArray = (NSUserDefaults.standardUserDefaults().arrayForKey(kCachedImagesKey) as? [NSData]) {
for storedImageData in storedImageDataArray {
if let decodedImage = UIImage(data: storedImageData) {
images.append(decodedImage)
}
}
}
}
func saveAllImagesToUserDefaults() {
var imageDataArray: [NSData] = []
for image in images {
let imageData = UIImagePNGRepresentation(image)!
imageDataArray.append(imageData)
}
NSUserDefaults.standardUserDefaults().setObject(imageDataArray, forKey: kCachedImagesKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
func saveImage(image: UIImage) {
// Save to our app's settings.
images.append(image)
saveAllImagesToUserDefaults()
// Also save this image to the photos album.
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
}
| mit | 6ec35e197f413a73e7ef7ee5b4cd9f6a | 24.804348 | 116 | 0.72957 | 3.674923 | false | false | false | false |
grahamgilbert/munki-dnd | MSC DND/AppDelegate.swift | 1 | 1732 | //
// AppDelegate.swift
// MSC DND
//
// Created by Graham Gilbert on 05/07/2015.
// Copyright (c) 2015 Graham Gilbert. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
let popover = NSPopover()
var eventMonitor: EventMonitor?
func applicationDidFinishLaunching(notification: NSNotification) {
if let button = statusItem.button {
button.image = NSImage(named: "hibernate")
button.action = Selector("togglePopover:")
}
popover.contentViewController = DNDViewController(nibName: "DNDViewController", bundle: nil)
eventMonitor = EventMonitor(mask: .LeftMouseDownMask | .RightMouseDownMask) { [unowned self] event in
if self.popover.shown {
self.closePopover(event)
}
}
eventMonitor?.start()
showPopover(nil)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func showPopover(sender: AnyObject?) {
if let button = statusItem.button {
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
eventMonitor?.start()
}
}
func closePopover(sender: AnyObject?) {
popover.performClose(sender)
eventMonitor?.stop()
}
func togglePopover(sender: AnyObject?) {
if popover.shown {
closePopover(sender)
} else {
showPopover(sender)
}
}
}
| apache-2.0 | c3ae280a37d14c3c863b9184017a91a1 | 26.0625 | 109 | 0.625289 | 5.00578 | false | false | false | false |
CaueAlvesSilva/DropDownAlert | DropDownAlert/DropDownAlert/ExampleViewController/ExampleViewController.swift | 1 | 3893 | //
// ExampleViewController.swift
// DropDownAlert
//
// Created by Cauê Silva on 06/06/17.
// Copyright © 2017 Caue Alves. All rights reserved.
//
import Foundation
import UIKit
// MARK: Enum for button pressed
enum ButtonPressed: Int {
case success
case custom
case fail
}
class ExampleViewController: UIViewController {
// MARK: Outlets
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet var showDropDownAlertButtons: [UIButton]!
// MARK: VC life cycle
override func viewDidLoad() {
super.viewDidLoad()
setupButtons()
setupTextField()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
showDropDownAlert(message: "Hello message", success: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
DropDownAlertPresenter.dismiss()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
// MARK: Components setup
private func setupButtons() {
let buttonAttributes: [(title: String, color: UIColor)] = [("Success", UIColor.successDropDownAlertColor()),
("Custom", UIColor(red: 239/255, green: 91/255, blue: 48/255, alpha: 1.0)),
("Fail", UIColor.failDropDownAlertColor())]
for (index, button) in showDropDownAlertButtons.enumerated() {
button.layer.cornerRadius = 4
button.setTitle(buttonAttributes[index].title, for: .normal)
button.setTitle(buttonAttributes[index].title, for: .highlighted)
button.setTitleColor(.white, for: .normal)
button.setTitleColor(.white, for: .highlighted)
button.backgroundColor = buttonAttributes[index].color
button.tag = index
}
}
private func setupTextField() {
messageTextField.placeholder = "Enter a custom message for alert"
messageTextField.clearButtonMode = .whileEditing
}
// MARK: Action
@IBAction func showDropDownAlertButtonPressed(_ sender: UIButton) {
guard let buttonPressed = ButtonPressed(rawValue: sender.tag), let inputedMessage = messageTextField.text else {
return
}
let message = inputedMessage.isEmpty ? "Input a message\nnext time" : inputedMessage
switch buttonPressed {
case .success:
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: true))
case .custom:
DropDownAlertPresenter.show(with: ExampleCustomAlertLayout(message: message))
case .fail:
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: false))
}
}
}
// MARK: Custom alert layout example
struct ExampleCustomAlertLayout: DropDownAlertLayout {
private var message = ""
init(message: String) {
self.message = message
}
var layoutDTO: DropDownAlertViewDTO {
return DropDownAlertViewDTO(image: UIImage(named: "customDropDownAlertIcon") ?? UIImage(),
message: message,
messageColor: .white,
backgroundColor: UIColor(red: 239/255, green: 91/255, blue: 48/255, alpha: 1.0),
visibleTime: 5)
}
}
// MARK: Show DropDownAlet using an extension
extension UIViewController {
func showDropDownAlert(message: String, success: Bool) {
DropDownAlertPresenter.show(with: DefaultDropDownAlertLayout(message: message, success: success))
}
}
| mit | 7f2c53630abf3458676026620e38a9d4 | 31.425 | 142 | 0.61064 | 5.167331 | false | false | false | false |
mfitzpatrick79/BidHub-iOS | AuctionApp/CategoryVC/CategoryViewController.swift | 1 | 3608 | //
// CategoryViewController.swift
// AuctionApp
//
// Created by Michael Fitzpatrick on 5/28/17.
// Copyright © 2017 fitz.guru. All rights reserved.
//
import Foundation
import UIKit
protocol CategoryViewControllerDelegate {
func categoryViewControllerDidFilter(_ viewController: CategoryViewController, onCategory: String)
func categoryViewControllerDidCancel(_ viewController: CategoryViewController)
}
class CategoryViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet var darkView: UIView!
@IBOutlet var categoryPicker: UIPickerView!
@IBOutlet var toolbar: UIToolbar!
@IBOutlet var cancelButton: UIBarButtonItem!
@IBOutlet var doneButton: UIBarButtonItem!
var delegate: CategoryViewControllerDelegate?
var categoryNames = ["Art - All", "Art - Paintings", "Art - Photography", "Art - Prints, Drawings, & Other", "Experiences - All", "Experiences - Fashion", "Experiences - Sports", "Experiences - Travel"]
var categoryValues = ["art", "painting", "photo", "pdo", "other", "fashion", "sport", "travel"]
/// UIPickerViewDataSource Methods
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return categoryNames.count;
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return categoryNames[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
return
}
override func viewDidLoad() {
super.viewDidLoad()
categoryPicker.delegate = self
categoryPicker.dataSource = self
animateIn()
}
@IBAction func didTapBackground(_ sender: AnyObject) {
animateOut()
}
@IBAction func didPressCancel(_ sender: AnyObject) {
animateOut()
}
@IBAction func didPressDone(_ sender: AnyObject) {
let category = categoryValues[categoryPicker.selectedRow(inComponent: 0)] as String
if self.delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidFilter(self, onCategory: category)
})
}
}
func didSelectCategory(_ category: String) {
if self.delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidFilter(self, onCategory: category)
})
}
}
func animateIn(){
UIView.animate(
withDuration: 0.5,
delay: 0.0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.0,
options: UIViewAnimationOptions.curveLinear,
animations: {
self.darkView.alpha = 1.0
},
completion: { (fininshed: Bool) -> () in })
}
func animateOut(){
if delegate != nil {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.darkView.alpha = 0
}, completion: { (finished: Bool) -> Void in
self.delegate!.categoryViewControllerDidCancel(self)
})
}
}
}
| apache-2.0 | bba6929a615e80c6a90fb9cb8f440b61 | 32.398148 | 206 | 0.618242 | 5.044755 | false | false | false | false |
jdkelley/Udacity-OnTheMap-ExampleApps | TheMovieManager-v2/TheMovieManager/BorderedButton.swift | 2 | 2649 | //
// BorderedButton.swift
// MyFavoriteMovies
//
// Created by Jarrod Parkes on 1/23/15.
// Copyright (c) 2015 Udacity. All rights reserved.
//
import UIKit
// MARK: - BorderedButton: Button
class BorderedButton: UIButton {
// MARK: Properties
// constants for styling and configuration
let darkerBlue = UIColor(red: 0.0, green: 0.298, blue: 0.686, alpha:1.0)
let lighterBlue = UIColor(red: 0.0, green:0.502, blue:0.839, alpha: 1.0)
let titleLabelFontSize: CGFloat = 17.0
let borderedButtonHeight: CGFloat = 44.0
let borderedButtonCornerRadius: CGFloat = 4.0
let phoneBorderedButtonExtraPadding: CGFloat = 14.0
var backingColor: UIColor? = nil
var highlightedBackingColor: UIColor? = nil
// MARK: Initialization
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
themeBorderedButton()
}
override init(frame: CGRect) {
super.init(frame: frame)
themeBorderedButton()
}
private func themeBorderedButton() {
layer.masksToBounds = true
layer.cornerRadius = borderedButtonCornerRadius
highlightedBackingColor = darkerBlue
backingColor = lighterBlue
backgroundColor = lighterBlue
setTitleColor(UIColor.whiteColor(), forState: .Normal)
titleLabel?.font = UIFont.systemFontOfSize(titleLabelFontSize)
}
// MARK: Setters
private func setBackingColor(newBackingColor: UIColor) {
if let _ = backingColor {
backingColor = newBackingColor
backgroundColor = newBackingColor
}
}
private func setHighlightedBackingColor(newHighlightedBackingColor: UIColor) {
highlightedBackingColor = newHighlightedBackingColor
backingColor = highlightedBackingColor
}
// MARK: Tracking
override func beginTrackingWithTouch(touch: UITouch, withEvent: UIEvent?) -> Bool {
backgroundColor = highlightedBackingColor
return true
}
override func endTrackingWithTouch(touch: UITouch?, withEvent event: UIEvent?) {
backgroundColor = backingColor
}
override func cancelTrackingWithEvent(event: UIEvent?) {
backgroundColor = backingColor
}
// MARK: Layout
override func sizeThatFits(size: CGSize) -> CGSize {
let extraButtonPadding : CGFloat = phoneBorderedButtonExtraPadding
var sizeThatFits = CGSizeZero
sizeThatFits.width = super.sizeThatFits(size).width + extraButtonPadding
sizeThatFits.height = borderedButtonHeight
return sizeThatFits
}
} | mit | db1587fd117e9a835f58cf8203d8bf05 | 29.113636 | 87 | 0.670064 | 5.298 | false | false | false | false |
toohotz/Alamofire | Tests/TLSEvaluationTests.swift | 69 | 16725 | // TLSEvaluationTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Alamofire
import Foundation
import XCTest
private struct TestCertificates {
static let RootCA = TestCertificates.certificateWithFileName("root-ca-disig")
static let IntermediateCA = TestCertificates.certificateWithFileName("intermediate-ca-disig")
static let Leaf = TestCertificates.certificateWithFileName("testssl-expire.disig.sk")
static func certificateWithFileName(fileName: String) -> SecCertificate {
class Bundle {}
let filePath = NSBundle(forClass: Bundle.self).pathForResource(fileName, ofType: "cer")!
let data = NSData(contentsOfFile: filePath)!
let certificate = SecCertificateCreateWithData(nil, data).takeRetainedValue()
return certificate
}
}
// MARK: -
private struct TestPublicKeys {
static let RootCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.RootCA)
static let IntermediateCA = TestPublicKeys.publicKeyForCertificate(TestCertificates.IntermediateCA)
static let Leaf = TestPublicKeys.publicKeyForCertificate(TestCertificates.Leaf)
static func publicKeyForCertificate(certificate: SecCertificate) -> SecKey {
let policy = SecPolicyCreateBasicX509().takeRetainedValue()
var unmanagedTrust: Unmanaged<SecTrust>?
let trustCreationStatus = SecTrustCreateWithCertificates(certificate, policy, &unmanagedTrust)
let trust = unmanagedTrust!.takeRetainedValue()
let publicKey = SecTrustCopyPublicKey(trust).takeRetainedValue()
return publicKey
}
}
// MARK: -
class TLSEvaluationExpiredLeafCertificateTestCase: BaseTestCase {
let URL = "https://testssl-expire.disig.sk/"
let host = "testssl-expire.disig.sk"
var configuration: NSURLSessionConfiguration!
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
}
// MARK: Default Behavior Tests
func testThatExpiredCertificateRequestFailsWithNoServerTrustPolicy() {
// Given
let expectation = expectationWithDescription("\(URL)")
let manager = Manager(configuration: configuration)
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorServerCertificateUntrusted, "error should be NSURLErrorServerCertificateUntrusted")
}
// MARK: Server Trust Policy - Perform Default Tests
func testThatExpiredCertificateRequestFailsWithDefaultServerTrustPolicy() {
// Given
let policies = [host: ServerTrustPolicy.PerformDefaultEvaluation(validateHost: true)]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
// MARK: Server Trust Policy - Certificate Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafCertificateWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestFailsWhenPinningAllCertificatesWithCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf, TestCertificates.IntermediateCA, TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafCertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCACertificateWithoutCertificateChainValidation() {
// Given
let certificates = [TestCertificates.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinCertificates(certificates: certificates, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Public Key Pinning Tests
func testThatExpiredCertificateRequestFailsWhenPinningLeafPublicKeyWithCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: true, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningLeafPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.Leaf]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningIntermediateCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.IntermediateCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestSucceedsWhenPinningRootCAPublicKeyWithoutCertificateChainValidation() {
// Given
let publicKeys = [TestPublicKeys.RootCA]
let policies: [String: ServerTrustPolicy] = [
host: .PinPublicKeys(publicKeys: publicKeys, validateCertificateChain: false, validateHost: true)
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Disabling Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenDisablingEvaluation() {
// Given
let policies = [host: ServerTrustPolicy.DisableEvaluation]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
// MARK: Server Trust Policy - Custom Evaluation Tests
func testThatExpiredCertificateRequestSucceedsWhenCustomEvaluationReturnsTrue() {
// Given
let policies = [
host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return true
}
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNil(error, "error should be nil")
}
func testThatExpiredCertificateRequestFailsWhenCustomEvaluationReturnsFalse() {
// Given
let policies = [
host: ServerTrustPolicy.CustomEvaluation { _, _ in
// Implement a custom evaluation routine here...
return false
}
]
let manager = Manager(
configuration: configuration,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: policies)
)
let expectation = expectationWithDescription("\(URL)")
var error: NSError?
// When
manager.request(.GET, URL)
.response { _, _, _, responseError in
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? -1, NSURLErrorCancelled, "error should be NSURLErrorCancelled")
}
}
| mit | 5b06811c0e0cbde11b4bf87133791f8f | 34.505308 | 135 | 0.651737 | 6.184541 | false | true | false | false |
SergeyVorontsov/SimpleNewsApp | SimpleNewsApp/DataProvider/NewsCache.swift | 1 | 6168 | //
// NewsCache.swift
// Simple News
//
// Created by Sergey Vorontsov
// Copyright (c) 2015 Sergey. All rights reserved.
//
import Foundation
private let NewsListKey = "NewsListKey"
private let NewsTextKey = "NewsTextKey"
private let LikesKey = "LikesKey"
private let PendingLikesKey = "PendingLikesKey"
/**
* Storage news using NSUserDefaults
*/
class NewsCache : NewsInternalStorage {
//MARK: News
/**
Save the news list
*/
func saveNewsList(newsList:[News]) {
let defaults = NSUserDefaults.standardUserDefaults()
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(newsList)
defaults.setObject(objectsData, forKey: NewsListKey)
defaults.synchronize()
}
/**
Restoring the news list
*/
func restoreNewsList() -> [News]?{
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData = defaults.dataForKey(NewsListKey) {
let news = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [News]
return news
}
//failed to recover news
return nil
}
/**
Save text news
*/
func saveNewsText(newsId:String, text:String){
let defaults = NSUserDefaults.standardUserDefaults()
//getting saved dict
var textNewsDict:[String:String] = [:]
if let objectsData:NSData = defaults.dataForKey(NewsTextKey) {
textNewsDict = (NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:String]) ?? [String:String]()
}
textNewsDict[newsId] = text
//save
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(textNewsDict)
defaults.setObject(objectsData, forKey: NewsTextKey)
defaults.synchronize()
}
/**
Restore text news
*/
func restoreNewsText(newsId:String) -> String? {
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(NewsTextKey) {
let textNewsDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as! [String:String]
return textNewsDict[newsId]
}
//не удалось восстановить текст новости
return nil
}
//MARK: Likes
/**
Set like/unlike for news
*/
func saveMyLike(newsId:String, like:Bool) {
var likes = self.restoreLikesDict()
if like {
likes[newsId] = true
} else {
likes.removeValueForKey(newsId)
}
self.saveLikesDict(likes)
}
/**
Returns True if the news we liked
*/
func isLikedNews(newsId:String) -> Bool {
let likes = self.restoreLikesDict()
//if there is an element, then liked
if let likedFlag = likes[newsId]{
return true
}
return false
}
//MARK: PendingLikes
/**
Save pending like
:returns: true if pending like stored
*/
func savePendingLike(newsId:String, like:Bool) -> Bool {
var pendingLikesDict = self.restorePendingLikes()
var storedLikeValue = pendingLikesDict[newsId]
if storedLikeValue == nil {
//add this like as pending
pendingLikesDict[newsId] = like
} else {
//remove pending like
if storedLikeValue != like {
pendingLikesDict.removeValueForKey(newsId)
}else{
println("Warning! Unbalanced PendingLike add/remove")
}
}
return self.savePendingLikesDict(pendingLikesDict)
}
/**
Delete penfing like
:returns: true if like deleted
*/
func deletePendingLike(newsId:String) -> Bool {
var likesDict = self.restorePendingLikes()
if likesDict[newsId] != nil {
likesDict.removeValueForKey(newsId)
return self.savePendingLikesDict(likesDict)
}
return false
}
/**
Restore pending likes dictionary
key - news id, value - is liked (Bool)
:returns: pending likes dictionary
*/
func restorePendingLikes() -> [String:Bool]{
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(PendingLikesKey),
let likesDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:Bool] {
return likesDict
}else{
return [String:Bool]()
}
}
}
//MARK: Private
private extension NewsCache {
/**
Save likes
:param: likes [String:Bool] (news id : liked)
*/
private func saveLikesDict(likes:[String:Bool]) -> Void {
let defaults = NSUserDefaults.standardUserDefaults()
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(likes)
defaults.setObject(objectsData, forKey: LikesKey)
defaults.synchronize()
}
/**
Restore likes
:returns: [String:Bool] (news id : liked)
*/
private func restoreLikesDict() -> [String:Bool] {
let defaults = NSUserDefaults.standardUserDefaults()
if let objectsData:NSData = defaults.dataForKey(LikesKey) {
let likesDict = NSKeyedUnarchiver.unarchiveObjectWithData(objectsData) as? [String:Bool]
return likesDict!
}
return [String:Bool]()
}
/**
Save pending likes dictionary
:param: pendingLikes pending likes dictionary. key - news id, value - is liked (Bool)
:returns: true if saved
*/
private func savePendingLikesDict(pendingLikes:[String:Bool]) -> Bool {
let defaults = NSUserDefaults.standardUserDefaults()
//save
let objectsData = NSKeyedArchiver.archivedDataWithRootObject(pendingLikes)
defaults.setObject(objectsData, forKey: PendingLikesKey)
return defaults.synchronize()
}
}
| mit | 8b56790863a1bf8ecd097c609a47eb80 | 25.106383 | 124 | 0.601467 | 5.151134 | false | false | false | false |
iOSWizards/AwesomeMedia | Example/Pods/AwesomeCore/AwesomeCore/Classes/Model/QuestMediaContent.swift | 1 | 934 | //
// QuestMediaContent.swift
// AwesomeCore
//
// Created by Leonardo Vinicius Kaminski Ferreira on 15/05/19.
//
import Foundation
public struct QuestMediaContent: Codable {
public let contentAsset: QuestAsset?
public let coverAsset: QuestAsset?
public let position: Int?
public let title: String?
public let type: String?
}
// MARK: - Equatable
extension QuestMediaContent: Equatable {
public static func ==(lhs: QuestMediaContent, rhs: QuestMediaContent) -> Bool {
if lhs.contentAsset != rhs.contentAsset {
return false
}
if lhs.coverAsset != rhs.coverAsset {
return false
}
if lhs.position != rhs.position {
return false
}
if lhs.title != rhs.title {
return false
}
if lhs.type != rhs.type {
return false
}
return true
}
}
| mit | e3eafcc8790c31e32ef5fd80508b828b | 20.72093 | 83 | 0.582441 | 4.512077 | false | false | false | false |
tgu/HAP | Sources/HAP/Endpoints/pairSetup().swift | 1 | 4573 | import Cryptor
import func Evergreen.getLogger
import Foundation
import SRP
fileprivate let logger = getLogger("hap.pairSetup")
fileprivate typealias Session = PairSetupController.Session
fileprivate let SESSION_KEY = "hap.pair-setup.session"
fileprivate enum Error: Swift.Error {
case noSession
}
// swiftlint:disable:next cyclomatic_complexity
func pairSetup(device: Device) -> Application {
let group = Group.N3072
let algorithm = Digest.Algorithm.sha512
let username = "Pair-Setup"
let (salt, verificationKey) = createSaltedVerificationKey(username: username,
password: device.setupCode,
group: group,
algorithm: algorithm)
let controller = PairSetupController(device: device)
func createSession() -> Session {
return Session(server: SRP.Server(username: username,
salt: salt,
verificationKey: verificationKey,
group: group,
algorithm: algorithm))
}
func getSession(_ connection: Server.Connection) throws -> Session {
guard let session = connection.context[SESSION_KEY] as? Session else {
throw Error.noSession
}
return session
}
return { connection, request in
var body = Data()
guard
(try? request.readAllData(into: &body)) != nil,
let data: PairTagTLV8 = try? decode(body),
let sequence = data[.state]?.first.flatMap({ PairSetupStep(rawValue: $0) })
else {
return .badRequest
}
let response: PairTagTLV8?
do {
switch sequence {
// M1: iOS Device -> Accessory -- `SRP Start Request'
case .startRequest:
let session = createSession()
response = try controller.startRequest(data, session)
connection.context[SESSION_KEY] = session
// M3: iOS Device -> Accessory -- `SRP Verify Request'
case .verifyRequest:
let session = try getSession(connection)
response = try controller.verifyRequest(data, session)
// M5: iOS Device -> Accessory -- `Exchange Request'
case .keyExchangeRequest:
let session = try getSession(connection)
response = try controller.keyExchangeRequest(data, session)
// Unknown state - return error and abort
default:
throw PairSetupController.Error.invalidParameters
}
} catch {
logger.warning(error)
connection.context[SESSION_KEY] = nil
try? device.changePairingState(.notPaired)
switch error {
case PairSetupController.Error.invalidParameters:
response = [
(.state, Data(bytes: [PairSetupStep.waiting.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.alreadyPaired:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.unavailable.rawValue]))
]
case PairSetupController.Error.alreadyPairing:
response = [
(.state, Data(bytes: [PairSetupStep.startResponse.rawValue])),
(.error, Data(bytes: [PairError.busy.rawValue]))
]
case PairSetupController.Error.invalidSetupState:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.unknown.rawValue]))
]
case PairSetupController.Error.authenticationFailed:
response = [
(.state, Data(bytes: [PairSetupStep.verifyResponse.rawValue])),
(.error, Data(bytes: [PairError.authenticationFailed.rawValue]))
]
default:
response = nil
}
}
if let response = response {
return Response(status: .ok, data: encode(response), mimeType: "application/pairing+tlv8")
} else {
return .badRequest
}
}
}
| mit | ffd49b5ebdd321f6943252676c77b155 | 41.738318 | 102 | 0.542314 | 5.597307 | false | false | false | false |
kysonyangs/ysbilibili | Pods/SwiftDate/Sources/SwiftDate/Date+Components.swift | 5 | 18652 | //
// SwiftDate, Full featured Swift date library for parsing, validating, manipulating, and formatting dates and timezones.
// Created by: Daniele Margutti
// Main contributors: Jeroen Houtzager
//
//
// 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
/// This is the default region set. It will be set automatically at each startup as the local device's region
internal var DateDefaultRegion: Region = Region.Local()
// MARK: - Date Extension to work with date components
public extension Date {
/// Define a default region to use when you work with components and function of SwiftDate
/// and `Date` objects. Default region is set automatically at runtime to `Region.Local()` which defines
/// a region identified by the device's current `TimeZone` (not updating), `Calendar` (not updating)
/// and `Locale` (not updating).
///
/// - parameter region: region to set. If nil is passed default region is set to Region.Local()
public static func setDefaultRegion(_ region: Region?) {
DateDefaultRegion = region ?? Region.Local()
}
/// Return the default region set.
///
/// - returns: region set; if not changed is set to `Region.Local()`
public static var defaultRegion: Region {
return DateDefaultRegion
}
/// Create a DateInRegion instance from given date expressing it in default region (locale+timezone+calendar)
///
/// - returns: a new DateInRegion object
internal func inDateDefaultRegion() -> DateInRegion {
return self.inRegion(region: DateDefaultRegion)
}
/// The number of era units for the receiver expressed in the context of `defaultRegion`.
public var era: Int {
return self.inDateDefaultRegion().era
}
/// The number of year units for the receiver expressed in the context of `defaultRegion`.
public var year: Int {
return self.inDateDefaultRegion().year
}
/// The number of month units for the receiver expressed in the context of `defaultRegion`.
public var month: Int {
return self.inDateDefaultRegion().month
}
/// The number of day units for the receiver expressed in the context of `defaultRegion`.
public var day: Int {
return self.inDateDefaultRegion().day
}
/// The number of hour units for the receiver expressed in the context of `defaultRegion`.
public var hour: Int {
return self.inDateDefaultRegion().hour
}
/// Nearest rounded hour from the date expressed in the context of `defaultRegion`.
public var nearestHour: Int {
return self.inDateDefaultRegion().nearestHour
}
/// The number of minute units for the receiver expressed in the context of `defaultRegion`.
public var minute: Int {
return self.inDateDefaultRegion().minute
}
/// The number of second units for the receiver expressed in the context of `defaultRegion`.
public var second: Int {
return self.inDateDefaultRegion().second
}
/// The number of nanosecond units for the receiver expressed in the context of `defaultRegion`.
public var nanosecond: Int {
return self.inDateDefaultRegion().nanosecond
}
/// The number of week-numbering units for the receiver expressed in the context of `defaultRegion`.
public var yearForWeekOfYear: Int {
return self.inDateDefaultRegion().yearForWeekOfYear
}
/// The week date of the year for the receiver expressed in the context of `defaultRegion`.
public var weekOfYear: Int {
return self.inDateDefaultRegion().weekOfYear
}
/// The number of weekday units for the receiver expressed in the context of `defaultRegion`.
public var weekday: Int {
return self.inDateDefaultRegion().weekday
}
/// The ordinal number of weekday units for the receiver expressed in the context of `defaultRegion`.
public var weekdayOrdinal: Int {
return self.inDateDefaultRegion().weekdayOrdinal
}
/// Week day name of the date expressed in the context of `defaultRegion`.
public var weekdayName: String {
return self.inDateDefaultRegion().weekdayName
}
/// Weekday short name
/// - note: This value is interpreted in the context of the calendar and timezone with which it is used
public var weekdayShortName: String {
return self.inDateDefaultRegion().weekdayShortName
}
/// Number of days into current's date month expressed in the context of `defaultRegion`.
public var monthDays: Int {
return self.inDateDefaultRegion().monthDays
}
/// he week number in the month expressed in the context of `defaultRegion`.
public var weekOfMonth: Int {
return self.inDateDefaultRegion().weekOfMonth
}
/// Month name of the date expressed in the context of `defaultRegion`.
public var monthName: String {
return self.inDateDefaultRegion().monthName
}
/// Short month name of the date expressed in the context of `defaultRegion`.
public var shortMonthName: String {
return self.inDateDefaultRegion().shortMonthName
}
/// Boolean value that indicates whether the month is a leap month.
/// Calculation is made in the context of `defaultRegion`.
public var leapMonth: Bool {
return self.inDateDefaultRegion().leapMonth
}
/// Boolean value that indicates whether the year is a leap year.
/// Calculation is made in the context of `defaultRegion`.
public var leapYear: Bool {
return self.inDateDefaultRegion().leapYear
}
/// Julian day is the continuous count of days since the beginning of the Julian Period used primarily by astronomers.
/// Calculation is made in the context of `defaultRegion`.
public var julianDay: Double {
return self.inDateDefaultRegion().julianDay
}
/// The Modified Julian Date (MJD) was introduced by the Smithsonian Astrophysical Observatory
/// in 1957 to record the orbit of Sputnik via an IBM 704 (36-bit machine) and using only 18 bits until August 7, 2576.
/// Calculation is made in the context of `defaultRegion`.
public var modifiedJulianDay: Double {
return self.inDateDefaultRegion().modifiedJulianDay
}
/// Return the next weekday after today.
/// For example using now.next(.friday) it will return the first Friday after self represented date.
///
/// - Parameter day: weekday you want to get
/// - Returns: the next weekday after sender date
public func next(day: WeekDay) -> Date? {
return self.inDateDefaultRegion().next(day: day)?.absoluteDate
}
/// Get the first day of the week according to the current calendar set
public var startWeek: Date {
return self.startOf(component: .weekOfYear)
}
/// Get the last day of the week according to the current calendar set
public var endWeek: Date {
return self.endOf(component: .weekOfYear)
}
/// Returns two `DateInRegion` objects indicating the start and the end of the current weekend.
/// Calculation is made in the context of `defaultRegion`.
public var thisWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().thisWeekend
}
/// Returns two `DateInRegion` objects indicating the start and the end
/// of the next weekend after the date.
/// Calculation is made in the context of `defaultRegion`.
public var nextWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().nextWeekend
}
/// Returns two `DateInRegion` objects indicating the start and the end of
/// the previous weekend before the date.
/// Calculation is made in the context of `defaultRegion`.
public var previousWeekend: (startDate: DateInRegion, endDate: DateInRegion)? {
return self.inDateDefaultRegion().previousWeekend
}
/// Returns whether the given date is in today as boolean.
/// Calculation is made in the context of `defaultRegion`.
public var isToday: Bool {
return self.inDateDefaultRegion().isToday
}
/// Returns whether the given date is in yesterday.
/// Calculation is made in the context of `defaultRegion`.
public var isYesterday: Bool {
return self.inDateDefaultRegion().isYesterday
}
/// Returns whether the given date is in tomorrow.
/// Calculation is made in the context of `defaultRegion`.
public var isTomorrow: Bool {
return self.inDateDefaultRegion().isTomorrow
}
/// Returns whether the given date is in the weekend.
/// Calculation is made in the context of `defaultRegion`.
public var isInWeekend: Bool {
return self.inDateDefaultRegion().isInWeekend
}
/// Return true if given date represent a passed date
/// Calculation is made in the context of `defaultRegion`.
public var isInPast: Bool {
return self.inDateDefaultRegion().isInPast
}
/// Return true if given date represent a future date
/// Calculation is made in the context of `defaultRegion`.
public var isInFuture: Bool {
return self.inDateDefaultRegion().isInFuture
}
/// Returns whether the given date is in the morning.
/// Calculation is made in the context of `defaultRegion`.
public var isMorning: Bool {
return self.inDateDefaultRegion().isMorning
}
/// Returns whether the given date is in the afternoon.
/// Calculation is made in the context of `defaultRegion`.
public var isAfternoon: Bool {
return self.inDateDefaultRegion().isAfternoon
}
/// Returns whether the given date is in the evening.
/// Calculation is made in the context of `defaultRegion`.
public var isEvening: Bool {
return self.inDateDefaultRegion().isEvening
}
/// Returns whether the given date is in the night.
/// Calculation is made in the context of `defaultRegion`.
public var isNight: Bool {
return self.inDateDefaultRegion().isNight
}
/// Returns whether the given date is on the same day as the receiver in the time zone and calendar of the receiver.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter date: a date to compare against
///
/// - returns: a boolean indicating whether the receiver is on the same day as the given date in
/// the time zone and calendar of the receiver.
public func isInSameDayOf(date: Date) -> Bool {
return self.inDateDefaultRegion().isInSameDayOf(date: date.inDateDefaultRegion())
}
/// Return the instance representing the first moment date of the given date expressed in the context of
/// Calculation is made in the context of `defaultRegion`.
public var startOfDay: Date {
return self.inDateDefaultRegion().startOfDay.absoluteDate
}
/// Return the instance representing the last moment date of the given date expressed in the context of
/// Calculation is made in the context of `defaultRegion`.
public var endOfDay: Date {
return self.inDateDefaultRegion().endOfDay.absoluteDate
}
/// Return a new instance of the date plus one month
/// Calculation is made in the context of `defaultRegion`.
@available(*, deprecated: 4.1.7, message: "Use nextMonth() function instead")
public var nextMonth: Date {
return self.inDateDefaultRegion().nextMonth.absoluteDate
}
/// Return a new instance of the date minus one month
/// Calculation is made in the context of `defaultRegion`.
@available(*, deprecated: 4.1.7, message: "Use prevMonth() function instead")
public var prevMonth: Date {
return self.inDateDefaultRegion().prevMonth.absoluteDate
}
/// Return the date by adding one month to the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one month to the current date.
/// If you pass `.start` result date is the first day of the next month (at 00:00:00).
/// If you pass `.end` result date is the last day of the next month (at 23:59:59).
/// - Returns: the new date at the next month
public func nextMonth(at time: TimeReference) -> Date {
return self.inDefaultRegion().nextMonth(at: time).absoluteDate
}
/// Return the date by subtracting one month from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by subtracting one month to the current date.
/// If you pass `.start` result date is the first day of the previous month (at 00:00:00).
/// If you pass `.end` result date is the last day of the previous month (at 23:59:59).
/// - Returns: the new date at the next month
public func prevMonth(at time: TimeReference) -> Date {
return self.inDefaultRegion().prevMonth(at: time).absoluteDate
}
/// Return the date by subtracting one week from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one week to the current date.
/// If you pass `.start` result date is the first day of the previous week (at 00:00:00).
/// If you pass `.end` result date is the last day of the previous week (at 23:59:59).
/// - Returns: the new date at the previous week
public func prevWeek(at time: TimeReference) -> Date {
return self.inDefaultRegion().prevWeek(at: time).absoluteDate
}
/// Return the date by adding one week from the current date
/// Calculation is made in the context of `defaultRegion`.
///
/// - Parameter time: when `.auto` evaluated date is calculated by adding one week to the current date.
/// If you pass `.start` result date is the first day of the next week (at 00:00:00).
/// If you pass `.end` result date is the last day of the next week (at 23:59:59).
/// - Returns: the new date at the next week
public func nextWeek(at time: TimeReference) -> Date {
return self.inDefaultRegion().nextWeek(at: time).absoluteDate
}
/// Takes a date unit and returns a date at the start of that unit.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter component: target component
///
/// - returns: the `Date` representing that start of that unit
public func startOf(component: Calendar.Component) -> Date {
return self.inDateDefaultRegion().startOf(component: component).absoluteDate
}
/// Takes a date unit and returns a date at the end of that unit.
/// Calculation is made in the context of `defaultRegion`.
///
/// - parameter component: target component
///
/// - returns: the `Date` representing that end of that unit
public func endOf(component: Calendar.Component) -> Date {
return self.inDateDefaultRegion().endOf(component: component).absoluteDate
}
/// Create a new instance calculated with the given time from self
///
/// - parameter hour: the hour value
/// - parameter minute: the minute value
/// - parameter second: the second value
///
/// - returns: a new `Date` object calculated at given time
public func atTime(hour: Int, minute: Int, second: Int) -> Date? {
return self.inDateDefaultRegion().atTime(hour: hour, minute: minute, second: second)?.absoluteDate
}
/// Create a new instance calculated by setting a specific component of a given date to a given value, while trying to keep lower
/// components the same.
///
/// - parameter unit: The unit to set with the given value
/// - parameter value: The value to set for the given calendar unit.
///
/// - returns: a new `Date` object calculated at given unit value
public func at(unit: Calendar.Component, value: Int) -> Date? {
return self.inDateDefaultRegion().at(unit: unit, value: value)?.absoluteDate
}
/// Create a new instance calculated by setting a list of components of a given date to given values (components
/// are evaluated serially - in order), while trying to keep lower components the same.
///
/// - parameter dict: a dictionary with `Calendar.Component` and it's value
///
/// - throws: throw a `FailedToCalculate` exception.
///
/// - returns: a new `Date` object calculated at given units values
@available(*, deprecated: 4.1.0, message: "This method has know issues. Use at(values:keep:) instead")
public func at(unitsWithValues dict: [Calendar.Component : Int]) throws -> Date {
return try self.inDateDefaultRegion().at(unitsWithValues: dict).absoluteDate
}
/// Create a new instance of the date by keeping passed calendar components and alter
///
/// - Parameters:
/// - values: values to alter in new instance
/// - keep: values to keep from self instance
/// - Returns: a new instance of `DateInRegion` with passed altered values
public func at(values: [Calendar.Component : Int], keep: Set<Calendar.Component>) -> Date? {
return self.inDateDefaultRegion().at(values: values, keep: keep)?.absoluteDate
}
/// Returns a `Date` object representing a date that is the earliest (old) from a given range
/// of dates.
/// The dates are compared in absolute time, i.e. time zones, locales and calendars have no
/// effect on the comparison.
///
/// - parameter list: a list of `Date` to evaluate
///
/// - returns: a `DateInRegion` object representing a date that is the earliest from a given
/// range of dates.
public static func oldestDate(_ list: [Date]) -> Date {
var currentMinimum = Date.distantFuture
list.forEach { cDate in
if currentMinimum > cDate {
currentMinimum = cDate
}
}
return currentMinimum
}
/// Returns a Date object representing a date that is the latest from a given range of
/// dates. The dates are compared in absolute time, i.e. time zones, locales and calendars have
/// no effect on the comparison.
///
/// - parameter list: a list of `Date` to evaluate
///
/// - returns: a `DateInRegion` object representing a date that is the latest from a given
/// range of dates.
public static func recentDate(_ list: [Date]) -> Date {
var currentMaximum = Date.distantPast
list.forEach { cDate in
if currentMaximum < cDate {
currentMaximum = cDate
}
}
return currentMaximum
}
}
| mit | 1b0d421b751b1d49494ef059213f10f9 | 39.45987 | 130 | 0.725874 | 4.182063 | false | false | false | false |
fellipecaetano/Democracy-iOS | Pods/RandomKit/Sources/RandomKit/Extensions/Swift/UnicodeScalar+RandomKit.swift | 1 | 4506 | //
// UnicodeScalar+RandomKit.swift
// RandomKit
//
// The MIT License (MIT)
//
// Copyright (c) 2015-2017 Nikolai Vazquez
//
// 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.
//
extension UnicodeScalar: Random, RandomInRange, RandomInClosedRange {
/// A unicode scalar range from `" "` through `"~"`.
public static let randomRange: ClosedRange<UnicodeScalar> = " "..."~"
/// Generates a random value of `Self`.
///
/// The random value is in `UnicodeScalar.randomRange`.
public static func random<R: RandomGenerator>(using randomGenerator: inout R) -> UnicodeScalar {
return random(in: UnicodeScalar.randomRange, using: &randomGenerator)
}
/// Returns a random value of `Self` inside of the closed range.
public static func uncheckedRandom<R: RandomGenerator>(in range: Range<UnicodeScalar>, using randomGenerator: inout R) -> UnicodeScalar {
let lower = range.lowerBound.value
let upper = range.upperBound.value
if lower._isLowerRange && !upper._isLowerRange {
let diff: UInt32 = 0xE000 - 0xD7FF - 1
let newRange = Range(uncheckedBounds: (lower, upper - diff))
let random = UInt32.uncheckedRandom(in: newRange, using: &randomGenerator)
if random._isLowerRange {
return _unsafeBitCast(random)
} else {
return _unsafeBitCast(random &+ diff)
}
} else {
let newRange = Range(uncheckedBounds: (lower, upper))
let random = UInt32.uncheckedRandom(in: newRange, using: &randomGenerator)
return _unsafeBitCast(random)
}
}
/// Returns a random value of `Self` inside of the closed range.
public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UnicodeScalar>,
using randomGenerator: inout R) -> UnicodeScalar {
let lower = closedRange.lowerBound.value
let upper = closedRange.upperBound.value
if lower._isLowerRange && !upper._isLowerRange {
let diff: UInt32 = 0xE000 - 0xD7FF - 1
let newRange = ClosedRange(uncheckedBounds: (lower, upper - diff))
let random = UInt32.random(in: newRange, using: &randomGenerator)
if random._isLowerRange {
return _unsafeBitCast(random)
} else {
return _unsafeBitCast(random &+ diff)
}
} else {
let newRange = ClosedRange(uncheckedBounds: (lower, upper))
let random = UInt32.random(in: newRange, using: &randomGenerator)
return _unsafeBitCast(random)
}
}
/// Returns an optional random value of `Self` inside of the range.
public static func random<R: RandomGenerator>(in range: Range<UInt8>,
using randomGenerator: inout R) -> UnicodeScalar? {
return UInt8.random(in: range, using: &randomGenerator).map(UnicodeScalar.init)
}
/// Returns a random value of `Self` inside of the closed range.
public static func random<R: RandomGenerator>(in closedRange: ClosedRange<UInt8>,
using randomGenerator: inout R) -> UnicodeScalar {
return UnicodeScalar(UInt8.random(in: closedRange, using: &randomGenerator))
}
}
private extension UInt32 {
var _isLowerRange: Bool {
return self <= 0xD7FF
}
}
| mit | 526ffd1b77b82f77420f60050d62d280 | 43.613861 | 141 | 0.648469 | 4.763214 | false | false | false | false |
karwa/swift-corelibs-foundation | Foundation/NSConcreteValue.swift | 3 | 6283 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
internal class NSConcreteValue : NSValue {
struct TypeInfo : Equatable {
let size : Int
let name : String
init?(objCType spec: String) {
var size: Int = 0
var align: Int = 0
var count : Int = 0
var type = _NSSimpleObjCType(spec)
guard type != nil else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
if type == .StructBegin {
fatalError("NSConcreteValue.TypeInfo: cannot encode structs")
} else if type == .ArrayBegin {
let scanner = NSScanner(string: spec)
scanner.scanLocation = 1
guard scanner.scanInteger(&count) && count > 0 else {
print("NSConcreteValue.TypeInfo: array count is missing or zero")
return nil
}
guard let elementType = _NSSimpleObjCType(scanner.scanUpToString(String(_NSSimpleObjCType.ArrayEnd))) else {
print("NSConcreteValue.TypeInfo: array type is missing")
return nil
}
guard _NSGetSizeAndAlignment(elementType, &size, &align) else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
type = elementType
}
guard _NSGetSizeAndAlignment(type!, &size, &align) else {
print("NSConcreteValue.TypeInfo: unsupported type encoding spec '\(spec)'")
return nil
}
self.size = count != 0 ? size * count : size
self.name = spec
}
}
private static var _cachedTypeInfo = Dictionary<String, TypeInfo>()
private static var _cachedTypeInfoLock = NSLock()
private var _typeInfo : TypeInfo
private var _storage : UnsafeMutablePointer<UInt8>
required init(bytes value: UnsafePointer<Void>, objCType type: UnsafePointer<Int8>) {
let spec = String(cString: type)
var typeInfo : TypeInfo? = nil
NSConcreteValue._cachedTypeInfoLock.synchronized {
typeInfo = NSConcreteValue._cachedTypeInfo[spec]
if typeInfo == nil {
typeInfo = TypeInfo(objCType: spec)
NSConcreteValue._cachedTypeInfo[spec] = typeInfo
}
}
guard typeInfo != nil else {
fatalError("NSConcreteValue.init: failed to initialize from type encoding spec '\(spec)'")
}
self._typeInfo = typeInfo!
self._storage = UnsafeMutablePointer<UInt8>(allocatingCapacity: self._typeInfo.size)
self._storage.initializeFrom(unsafeBitCast(value, to: UnsafeMutablePointer<UInt8>.self), count: self._typeInfo.size)
}
deinit {
self._storage.deinitialize(count: self._size)
self._storage.deallocateCapacity(self._size)
}
override func getValue(_ value: UnsafeMutablePointer<Void>) {
UnsafeMutablePointer<UInt8>(value).moveInitializeFrom(unsafeBitCast(self._storage, to: UnsafeMutablePointer<UInt8>.self), count: self._size)
}
override var objCType : UnsafePointer<Int8> {
return NSString(self._typeInfo.name).utf8String! // XXX leaky
}
override var classForCoder: AnyClass {
return NSValue.self
}
override var description : String {
return NSData.init(bytes: self.value, length: self._size).description
}
convenience required init?(coder aDecoder: NSCoder) {
if !aDecoder.allowsKeyedCoding {
NSUnimplemented()
} else {
guard let type = aDecoder.decodeObject() as? NSString else {
return nil
}
let typep = type._swiftObject
// FIXME: This will result in reading garbage memory.
self.init(bytes: [], objCType: typep)
aDecoder.decodeValueOfObjCType(typep, at: self.value)
}
}
override func encodeWithCoder(_ aCoder: NSCoder) {
if !aCoder.allowsKeyedCoding {
NSUnimplemented()
} else {
aCoder.encodeObject(String(cString: self.objCType).bridge())
aCoder.encodeValueOfObjCType(self.objCType, at: self.value)
}
}
private var _size : Int {
return self._typeInfo.size
}
private var value : UnsafeMutablePointer<Void> {
return unsafeBitCast(self._storage, to: UnsafeMutablePointer<Void>.self)
}
private func _isEqualToValue(_ other: NSConcreteValue) -> Bool {
if self === other {
return true
}
if self._size != other._size {
return false
}
let bytes1 = self.value
let bytes2 = other.value
if bytes1 == bytes2 {
return true
}
return memcmp(bytes1, bytes2, self._size) == 0
}
override func isEqual(_ object: AnyObject?) -> Bool {
if let other = object as? NSConcreteValue {
return self._typeInfo == other._typeInfo &&
self._isEqualToValue(other)
} else {
return false
}
}
override var hash: Int {
return self._typeInfo.name.hashValue &+
Int(bitPattern: CFHashBytes(unsafeBitCast(self.value, to: UnsafeMutablePointer<UInt8>.self), self._size))
}
}
internal func ==(x : NSConcreteValue.TypeInfo, y : NSConcreteValue.TypeInfo) -> Bool {
return x.name == y.name && x.size == y.size
}
| apache-2.0 | 5cc292758be2e43ea4b7936eee6de0bb | 32.59893 | 148 | 0.571383 | 5.227121 | false | false | false | false |
knorrium/MemeMe | MemeMe/SentMemesTableViewController.swift | 1 | 2255 | //
// SentMemesTableViewController.swift
// MemeMe
//
// Created by Felipe Kuhn on 10/16/15.
// Copyright © 2015 Knorrium. All rights reserved.
//
import UIKit
class SentMemesTableViewController: UIViewController, UITableViewDataSource {
@IBOutlet var tableView: UITableView!
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
override func viewDidLoad() {
tableView.registerClass(SentMemesTableViewCell.self, forCellReuseIdentifier: "SentMemesTableViewCell")
}
override func viewWillAppear(animated: Bool) {
tableView.reloadData()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return appDelegate.memes.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("SentMemesTableViewCell")!
let meme = appDelegate.memes[indexPath.row]
cell.textLabel?.text = meme.topText + " " + meme.bottomText
cell.imageView?.image = meme.memedImage
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let detailController = storyboard!.instantiateViewControllerWithIdentifier("SentMemesDetailViewController") as! SentMemesDetailViewController
detailController.memedImage = appDelegate.memes[indexPath.row].memedImage
detailController.savedIndex = indexPath.row
navigationController!.pushViewController(detailController, animated: true)
}
//Delete - https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/Lesson9.html
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
appDelegate.memes.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
} | mit | d5b1d8f2f5cb074d8cb1b3cf62ce26bb | 36.583333 | 149 | 0.728483 | 5.735369 | false | false | false | false |
someoneAnyone/Nightscouter | NightscouterToday/SiteNSNowTableViewCell.swift | 1 | 3091 | //
// SiteTableViewswift
// Nightscouter
//
// Created by Peter Ina on 6/16/15.
// Copyright © 2015 Peter Ina. All rights reserved.
//
import UIKit
import NightscouterKit
class SiteNSNowTableViewCell: UITableViewCell {
@IBOutlet weak var siteLastReadingHeader: UILabel!
@IBOutlet weak var siteLastReadingLabel: UILabel!
@IBOutlet weak var siteBatteryHeader: UILabel!
@IBOutlet weak var siteBatteryLabel: UILabel!
@IBOutlet weak var siteRawHeader: UILabel!
@IBOutlet weak var siteRawLabel: UILabel!
@IBOutlet weak var siteNameLabel: UILabel!
@IBOutlet weak var siteColorBlockView: UIView!
@IBOutlet weak var siteSgvLabel: UILabel!
@IBOutlet weak var siteDirectionLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.backgroundColor = UIColor.clear
}
func configure(withDataSource dataSource: TableViewRowWithCompassDataSource, delegate: TableViewRowWithCompassDelegate?) {
siteLastReadingHeader.text = LocalizedString.lastReadingLabel.localized
siteLastReadingLabel.text = dataSource.lastReadingDate.timeAgoSinceNow
siteLastReadingLabel.textColor = delegate?.lastReadingColor
siteBatteryHeader.text = LocalizedString.batteryLabel.localized
siteBatteryHeader.isHidden = dataSource.batteryHidden
siteBatteryLabel.isHidden = dataSource.batteryHidden
siteBatteryLabel.text = dataSource.batteryLabel
siteBatteryLabel.textColor = delegate?.batteryColor
siteRawHeader.text = LocalizedString.rawLabel.localized
siteRawLabel?.isHidden = dataSource.rawHidden
siteRawHeader?.isHidden = dataSource.rawHidden
siteRawLabel.text = dataSource.rawFormatedLabel
siteRawLabel.textColor = delegate?.rawColor
siteNameLabel.text = dataSource.nameLabel
siteColorBlockView.backgroundColor = delegate?.sgvColor
siteSgvLabel.text = dataSource.sgvLabel + " " + dataSource.direction.emojiForDirection
siteSgvLabel.textColor = delegate?.sgvColor
siteDirectionLabel.text = dataSource.deltaLabel
siteDirectionLabel.textColor = delegate?.deltaColor
}
override func prepareForReuse() {
super.prepareForReuse()
siteNameLabel.text = nil
siteBatteryLabel.text = nil
siteRawLabel.text = nil
siteLastReadingLabel.text = nil
siteColorBlockView.backgroundColor = DesiredColorState.neutral.colorValue
siteSgvLabel.text = nil
siteSgvLabel.textColor = Theme.AppColor.labelTextColor
siteDirectionLabel.text = nil
siteDirectionLabel.textColor = Theme.AppColor.labelTextColor
siteLastReadingLabel.text = LocalizedString.tableViewCellLoading.localized
siteLastReadingLabel.textColor = Theme.AppColor.labelTextColor
siteRawHeader.isHidden = false
siteRawLabel.isHidden = false
siteRawLabel.textColor = Theme.AppColor.labelTextColor
}
}
| mit | 39344ff80121f5b92e32bc37cefeae18 | 38.113924 | 126 | 0.719417 | 5.628415 | false | false | false | false |
liujinlongxa/AnimationTransition | testTransitioning/CustomSegue.swift | 1 | 821 | //
// CustomSegue.swift
// AnimationTransition
//
// Created by Liujinlong on 8/12/15.
// Copyright © 2015 Jaylon. All rights reserved.
//
import UIKit
class CustomSegue: UIStoryboardSegue {
override func perform() {
let fromVCView = self.source.view as UIView
let toVCView = self.destination.view as UIView
var frame = fromVCView.bounds
frame.origin.x += frame.width
toVCView.frame = frame
UIApplication.shared.keyWindow?.addSubview(toVCView)
frame.origin.x = 0
UIView.animate(withDuration: 1.0, animations: { () -> Void in
toVCView.frame = frame
}, completion: { (_) -> Void in
self.source.present(self.destination, animated: false, completion: nil)
})
}
}
| mit | 14db8969d5a088da646d5282da4abbac | 24.625 | 83 | 0.59878 | 4.226804 | false | false | false | false |
alvaromb/CS-Trivia | Swift Playground/MyPlayground.playground/section-1.swift | 1 | 1265 | // Álvaro Medina Ballester, 2014
import Cocoa
/**
* Given a inputString, find the longest palindrome inside it.
* Simple version, we just have to loop through all the possible
* centers and try to find the biggest palindrome with that center.
*/
let inputString = "abcbabcbabcba" //"abababa"
let inputNSString = inputString as NSString
let seqLen = countElements(inputString)
let centers = (seqLen * 2) + 1
var palindromeLengths: [Int] = []
var longestPalindromeLength = 0
var longestPalindrome = ""
for index in 0..<centers {
var leftIndex = index/2 - 1
var rightIndex = index - index/2 // Integer division alternate: Int(ceil(Double(index)/Double(2)))
var palindromeLength = index%2
while leftIndex >= 0 && rightIndex < seqLen && Array(inputString)[leftIndex] == Array(inputString)[rightIndex] {
leftIndex--
rightIndex++
palindromeLength += 2
}
if palindromeLength > longestPalindromeLength {
longestPalindrome = inputNSString.substringWithRange(NSMakeRange(leftIndex+1, rightIndex+1))
longestPalindromeLength = palindromeLength
}
palindromeLengths.append(palindromeLength)
}
println("Palindrome Lengths \(palindromeLengths)")
println("Longest palindrome '\(longestPalindrome)'")
| gpl-3.0 | 0069a79c3da5320a30dfdd54a7195f6d | 33.162162 | 116 | 0.723101 | 4.373702 | false | false | false | false |
daggmano/photo-management-studio | src/Client/OSX/PMS-2/Photo Management Studio/Photo Management Studio/ImportViewItem.swift | 1 | 2930 | //
// ImportViewItem.swift
// Photo Management Studio
//
// Created by Darren Oster on 29/04/2016.
// Copyright © 2016 Criterion Software. All rights reserved.
//
import Cocoa
class ImportViewItem: NSCollectionViewItem {
@IBOutlet weak var titleLabel: NSTextField!
@IBOutlet weak var subTitleLabel: NSTextField!
private func updateView() {
super.viewWillAppear()
self.imageView?.image = NSImage(named: "placeholder")
titleLabel.stringValue = ""
subTitleLabel.stringValue = ""
view.toolTip = ""
if let item = self.importableItem {
titleLabel.stringValue = item.title
if let subTitle = item.subTitle {
subTitleLabel.stringValue = subTitle
self.view.toolTip = "\(item.title)\n\n\(subTitle)"
} else {
subTitleLabel.stringValue = ""
self.view.toolTip = item.title
}
if !item.imageUrl.containsString("http:") {
imageView?.image = NSImage(named: item.imageUrl)
} else {
var url: String;
if (item.imageUrl.containsString("?")) {
url = "\(item.imageUrl)&size=500"
} else {
url = "\(item.imageUrl)?size=500"
}
print(url)
let thumbName = "\(item.identifier!)_500x500.jpg"
ImageCache.getImage(url, thumbName: thumbName, useCache: true, callback: { (image) in
self.imageView?.image = image
self.imageView?.needsDisplay = true
})
}
}
}
// MARK: properties
var importableItem: PhotoItem? {
return representedObject as? PhotoItem
}
override var representedObject: AnyObject? {
didSet {
super.representedObject = representedObject
if let _ = representedObject as? PhotoItem {
self.updateView()
}
}
}
override var selected: Bool {
didSet {
(self.view as! ImportViewItemView).selected = selected
}
}
override var highlightState: NSCollectionViewItemHighlightState {
didSet {
(self.view as! ImportViewItemView).highlightState = highlightState
}
}
// MARK: NSResponder
override func mouseDown(theEvent: NSEvent) {
if theEvent.clickCount == 2 {
// if let thumbUrl = importableItem?.thumbUrl {
// print("Double click \(importableItem!.fullPath)")
// Event.emit("display-preview", obj: thumbUrl)
// }
} else {
super.mouseDown(theEvent)
}
}
}
| mit | a9d8f78f4a4c3cfa6f1351c291e91c81 | 29.195876 | 101 | 0.513827 | 5.374312 | false | false | false | false |
cuappdev/tempo | Tempo/Views/HamburgerIconView.swift | 1 | 4203 | //
// HamburgerIconView.swift
// Tempo
//
// Created by Dennis Fedorko on 5/10/16.
// Copyright © 2016 Dennis Fedorko. All rights reserved.
//
import UIKit
import SWRevealViewController
let RevealControllerToggledNotification = "RevealControllerToggled"
class HamburgerIconView: UIButton {
var topBar: UIView!
var middleBar: UIView!
var bottomBar: UIView!
var isHamburgerMode = true
let spacingRatio: CGFloat = 0.2
//MARK: -
//MARK: Init
init(frame: CGRect, color: UIColor, lineWidth: CGFloat, iconWidthRatio: CGFloat) {
super.init(frame: frame)
func applyStyle(_ bar: UIView, heightMultiplier: CGFloat) {
bar.isUserInteractionEnabled = false
bar.center = CGPoint(x: bar.center.x, y: frame.height * heightMultiplier)
bar.layer.cornerRadius = lineWidth * 0.5
bar.backgroundColor = color
bar.layer.allowsEdgeAntialiasing = true
addSubview(bar)
}
topBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth))
middleBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth))
bottomBar = UIView(frame: CGRect(x: 0, y: 0, width: frame.width * iconWidthRatio, height: lineWidth))
applyStyle(topBar, heightMultiplier: 0.5 - spacingRatio)
applyStyle(middleBar, heightMultiplier: 0.5)
applyStyle(bottomBar, heightMultiplier: 0.5 + spacingRatio)
//be notified when hamburger menu opens/closes
NotificationCenter.default.addObserver(self, selector: #selector(hamburgerMenuToggled), name: NSNotification.Name(rawValue: RevealControllerToggledNotification), object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: -
//MARK: User Interaction
func hamburgerMenuToggled(_ notification: Notification) {
if let revealVC = notification.object as? SWRevealViewController {
if revealVC.frontViewController.view.isUserInteractionEnabled {
//turn on hamburger menu
animateToHamburger()
} else {
animateToClose()
}
}
}
func animateIcon() {
isUserInteractionEnabled = true
if isHamburgerMode {
animateToClose()
isHamburgerMode = false
} else {
animateToHamburger()
isHamburgerMode = true
}
}
func animateToClose() {
if !isHamburgerMode { return }
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 30, options: [], animations: {
self.middleBar.alpha = 0
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 30, options: [], animations: {
let rotationClockWise = CGAffineTransform(rotationAngle: CGFloat(M_PI_4))
let rotationCounterClockWise = CGAffineTransform(rotationAngle: CGFloat(-M_PI_4))
let moveDownToCenter = CGAffineTransform(translationX: 0, y: self.frame.height * self.spacingRatio)
let moveUpToCenter = CGAffineTransform(translationX: 0, y: -self.frame.height * self.spacingRatio)
self.topBar.transform = rotationClockWise.concatenating(moveDownToCenter)
self.bottomBar.transform = rotationCounterClockWise.concatenating(moveUpToCenter)
}, completion: { _ in
self.isUserInteractionEnabled = true
})
isHamburgerMode = false
}
func animateToHamburger() {
if isHamburgerMode { return }
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 30, options: [], animations: {
self.middleBar.alpha = 1
}, completion: nil)
UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 30, options: [], animations: {
self.topBar.transform = CGAffineTransform.identity
self.topBar.center = CGPoint(x: self.topBar.center.x, y: self.frame.height * (0.5 - self.spacingRatio))
self.bottomBar.transform = CGAffineTransform.identity
self.bottomBar.center = CGPoint(x: self.bottomBar.center.x, y: self.frame.height * (0.5 + self.spacingRatio))
}, completion: { _ in
self.isUserInteractionEnabled = true
})
isHamburgerMode = true
}
}
| mit | ec90b2c17959778790f9860e4407de4e | 33.442623 | 176 | 0.70871 | 4.04817 | false | false | false | false |
gcirone/Mama-non-mama | Mama non mama/FlowerRainbow.swift | 1 | 10037 | //
// FlowerRainbow.swift
// TestSpriteFlowers
//
// Created by Cirone, Gianluca on 10/02/15.
// Copyright (c) 2015 freshdev. All rights reserved.
//
import SpriteKit
class FlowerRainbow: SKNode {
let atlas = SKTextureAtlas(named: "flower-rainbow")
deinit {
//println("FlowerRainbow.deinit")
}
override init(){
super.init()
name = "flower"
let pistillo = SKSpriteNode(texture: atlas.textureNamed("5_pistillo"))
pistillo.name = "pistillo"
pistillo.position = CGPointMake(0.0, 0.0)
//pistillo.size = CGSizeMake(78.0, 80.0)
pistillo.zRotation = 0.0
pistillo.zPosition = 10.0
addChild(pistillo)
let gambo = SKSpriteNode(texture: atlas.textureNamed("5_gambo"))
gambo.name = "gambo"
gambo.position = CGPointMake(0.0, 0.0)
gambo.anchorPoint = CGPointMake(0.5, 1)
//gambo = CGSizeMake(22.0, 367.0)
gambo.zRotation = 0.0
gambo.zPosition = -1.0
addChild(gambo)
let petalo_0 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_0"))
petalo_0.name = "petalo"
petalo_0.position = CGPointMake(-73.3526458740234, -30.1807556152344)
//petalo_0.size = CGSizeMake(98.0, 30.0)
petalo_0.zRotation = 0.483552724123001
petalo_0.zPosition = 3.0
addChild(petalo_0)
let petalo_1 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_1"))
petalo_1.name = "petalo"
petalo_1.position = CGPointMake(-75.8443374633789, 6.2181396484375)
//petalo_1.size = CGSizeMake(99.0, 31.0)
petalo_1.zRotation = 0.0
petalo_1.zPosition = 3.0
addChild(petalo_1)
let petalo_2 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_2"))
petalo_2.name = "petalo"
petalo_2.position = CGPointMake(-69.0649261474609, 30.3306579589844)
//petalo_2.size = CGSizeMake(97.0, 29.0)
petalo_2.zRotation = -0.35145291686058
petalo_2.zPosition = 2.0
addChild(petalo_2)
let petalo_3 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_3"))
petalo_3.name = "petalo"
petalo_3.position = CGPointMake(-47.7362060546875, 56.2152099609375)
//petalo_3.size = CGSizeMake(29.0, 95.0)
petalo_3.zRotation = 0.648896634578705
petalo_3.zPosition = 3.0
addChild(petalo_3)
let petalo_4 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_4"))
petalo_4.name = "petalo"
petalo_4.position = CGPointMake(-1.37254333496094, 76.3231811523438)
//petalo_4.size = CGSizeMake(30.0, 96.0)
petalo_4.zRotation = 0.0604744032025337
petalo_4.zPosition = 3.0
addChild(petalo_4)
let petalo_5 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_5"))
petalo_5.name = "petalo"
petalo_5.position = CGPointMake(-25.5420379638672, 71.4871826171875)
//petalo_5.size = CGSizeMake(29.0, 92.0)
petalo_5.zRotation = 0.249543845653534
petalo_5.zPosition = 2.0
addChild(petalo_5)
let petalo_6 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_6"))
petalo_6.name = "petalo"
petalo_6.position = CGPointMake(-58.0411834716797, 45.7310791015625)
//petalo_6.size = CGSizeMake(90.0, 34.0)
petalo_6.zRotation = -0.65658438205719
petalo_6.zPosition = 1.0
addChild(petalo_6)
let petalo_7 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_7"))
petalo_7.name = "petalo"
petalo_7.position = CGPointMake(-49.8720245361328, -57.9573364257812)
//petalo_7.size = CGSizeMake(28.0, 96.0)
petalo_7.zRotation = -0.621631443500519
petalo_7.zPosition = 5.0
addChild(petalo_7)
let petalo_8 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_8"))
petalo_8.name = "petalo"
petalo_8.position = CGPointMake(-73.8744659423828, -11.1670227050781)
//petalo_8.size = CGSizeMake(96.0, 26.0)
petalo_8.zRotation = 0.110586866736412
petalo_8.zPosition = 2.0
addChild(petalo_8)
let petalo_9 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_9"))
petalo_9.name = "petalo"
petalo_9.position = CGPointMake(-60.8856887817383, -48.7349700927734)
//petalo_9.size = CGSizeMake(28.0, 97.0)
petalo_9.zRotation = -0.731421649456024
petalo_9.zPosition = 2.0
addChild(petalo_9)
let petalo_10 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_10"))
petalo_10.name = "petalo"
petalo_10.position = CGPointMake(-30.1141662597656, -73.4540405273438)
//petalo_10.size = CGSizeMake(29.0, 94.0)
petalo_10.zRotation = -0.329761922359467
petalo_10.zPosition = 4.0
addChild(petalo_10)
let petalo_11 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_11"))
petalo_11.name = "petalo"
petalo_11.position = CGPointMake(-2.47735595703125, -78.5593566894531)
//petalo_11.size = CGSizeMake(31.0, 96.0)
petalo_11.zRotation = 0.0570810660719872
petalo_11.zPosition = 3.0
addChild(petalo_11)
let petalo_12 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_12"))
petalo_12.name = "petalo"
petalo_12.position = CGPointMake(24.7819366455078, -76.9860382080078)
//petalo_12.size = CGSizeMake(32.0, 97.0)
petalo_12.zRotation = 0.2876937687397
petalo_12.zPosition = 2.0
addChild(petalo_12)
let petalo_13 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_13"))
petalo_13.name = "petalo"
petalo_13.position = CGPointMake(45.9588317871094, -68.5952453613281)
//petalo_13.size = CGSizeMake(29.0, 99.0)
petalo_13.zRotation = 0.628583908081055
petalo_13.zPosition = 1.0
addChild(petalo_13)
let petalo_14 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_14"))
petalo_14.name = "petalo"
petalo_14.position = CGPointMake(76.0393676757812, -30.5138092041016)
//petalo_14.size = CGSizeMake(94.0, 31.0)
petalo_14.zRotation = -0.365856379270554
petalo_14.zPosition = 2.0
addChild(petalo_14)
let petalo_15 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_15"))
petalo_15.name = "petalo"
petalo_15.position = CGPointMake(61.9654235839844, -51.4241638183594)
//petalo_15.size = CGSizeMake(98.0, 31.0)
petalo_15.zRotation = -0.669111967086792
petalo_15.zPosition = 0.0
addChild(petalo_15)
let petalo_16 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_16"))
petalo_16.name = "petalo"
petalo_16.position = CGPointMake(76.3208312988281, 17.4443969726562)
//petalo_16.size = CGSizeMake(95.0, 27.0)
petalo_16.zRotation = 0.23156164586544
petalo_16.zPosition = 3.0
addChild(petalo_16)
let petalo_17 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_17"))
petalo_17.name = "petalo"
petalo_17.position = CGPointMake(74.02685546875, -3.48822021484375)
//petalo_17.size = CGSizeMake(92.0, 27.0)
petalo_17.zRotation = 0.0
petalo_17.zPosition = 1.0
addChild(petalo_17)
let petalo_18 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_18"))
petalo_18.name = "petalo"
petalo_18.position = CGPointMake(62.664306640625, 51.2071228027344)
//petalo_18.size = CGSizeMake(31.0, 99.0)
petalo_18.zRotation = -0.747934758663177
petalo_18.zPosition = 3.0
addChild(petalo_18)
let petalo_19 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_19"))
petalo_19.name = "petalo"
petalo_19.position = CGPointMake(73.4706115722656, 36.2119445800781)
//petalo_19.size = CGSizeMake(28.0, 95.0)
petalo_19.zRotation = -0.943031191825867
petalo_19.zPosition = 2.0
addChild(petalo_19)
let petalo_20 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_20"))
petalo_20.name = "petalo"
petalo_20.position = CGPointMake(32.3933258056641, 69.6167602539062)
//petalo_20.size = CGSizeMake(31.0, 91.0)
petalo_20.zRotation = -0.359138071537018
petalo_20.zPosition = 3.0
addChild(petalo_20)
let petalo_21 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_21"))
petalo_21.name = "petalo"
petalo_21.position = CGPointMake(17.885498046875, 75.0881042480469)
//petalo_21.size = CGSizeMake(27.0, 85.0)
petalo_21.zRotation = -0.219870626926422
petalo_21.zPosition = 1.0
addChild(petalo_21)
let petalo_22 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_22"))
petalo_22.name = "petalo"
petalo_22.position = CGPointMake(49.2562408447266, 60.7242431640625)
//petalo_22.size = CGSizeMake(28.0, 96.0)
petalo_22.zRotation = -0.64398181438446
petalo_22.zPosition = 1.0
addChild(petalo_22)
// petalo speciale
let petalo_23 = SKSpriteNode(texture: atlas.textureNamed("5_petalo_17"))
petalo_23.name = "petalo_mama"
petalo_23.position = CGPointMake(73.9085083007812, -23.3897399902344)
//petalo_23.size = CGSizeMake(92.0, 27.0)
petalo_23.zRotation = -0.199623420834541
petalo_23.zPosition = 0.0
addChild(petalo_23)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | de8c273b4a604335b66ec46c2224a335 | 36.59176 | 80 | 0.602471 | 3.536646 | false | false | false | false |
depl0y/pixelbits | pixelbits/Converters/UIEdgeInsetsConverter.swift | 1 | 1647 | //
// UIEdgeInsetsConverter.swift
// pixelbits
//
// Created by Wim Haanstra on 17/01/16.
// Copyright © 2016 Wim Haanstra. All rights reserved.
//
import UIKit
internal class UIEdgeInsetsConverter {
/**
Converts a value `insets(4, 4, 4, 4)` to a UIEdgeInsets struct
- returns: A UIEdgeInsets object or nil if invalid
*/
static func fromString(valueString: String) -> NSValue? {
let expression = "insets\\(([0-9. ,a-zA-Z\\$\\-_]+?)\\)"
let matches = valueString.variableValue().matches(expression)
if matches.count == 0 {
return nil
}
let insets = matches[0]
let insetParts = insets.characters.split { $0 == "," }.map(String.init)
var insetValues: [CGFloat] = []
/**
* Check if all the inset values are convertible to NSNumber objects.
*/
for index in 0..<insetParts.count {
if let insetValue = insetParts[index].variableValue().toNumber() {
insetValues.append(CGFloat(insetValue))
}
}
switch (insetValues.count) {
case 1:
return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[0], insetValues[0], insetValues[0]))
case 2:
return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[1], insetValues[0], insetValues[1]))
case 4:
return NSValue(UIEdgeInsets: UIEdgeInsetsMake(insetValues[0], insetValues[1], insetValues[2], insetValues[3]))
default:
return nil
}
}
}
| mit | 399172f2dbbee4af431f4de0206c8022 | 30.056604 | 122 | 0.577157 | 4.572222 | false | false | false | false |
Echx/GridOptic | GridOptic/GridOptic/GameTestViewController.swift | 1 | 4920 | //
// GameTestViewController.swift
// GridOptic
//
// Created by Lei Mingyu on 01/04/15.
// Copyright (c) 2015 Echx. All rights reserved.
//
import UIKit
import SpriteKit
class GameTestViewController: UIViewController {
@IBOutlet var directionSlider: UISlider?
var grid: GOGrid?
var object: GOOpticRep?
var shapeLayer = CAShapeLayer()
override func viewDidLoad() {
super.viewDidLoad()
self.view.layer.addSublayer(shapeLayer)
shapeLayer.strokeEnd = 1.0
shapeLayer.strokeColor = UIColor.whiteColor().CGColor
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.lineWidth = 2.0
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.grayColor()
self.grid = GOGrid(width: 64, height: 48, andUnitLength: 16)
if self.object == nil {
self.directionSlider?.userInteractionEnabled = false
self.directionSlider?.alpha = 0
}
let swipeGesture = UISwipeGestureRecognizer(target: self, action: Selector("didSwipe:"))
swipeGesture.direction = UISwipeGestureRecognizerDirection.Down
self.view.addGestureRecognizer(swipeGesture)
self.directionSlider?.addTarget(self, action: "updateObjectDirection:", forControlEvents: UIControlEvents.ValueChanged)
}
func updateObjectDirection(sender: UISlider) {
self.object?.setDirection(CGVector.vectorFromXPlusRadius(CGFloat(sender.value)))
drawInitContent()
}
override func viewDidAppear(animated: Bool) {
drawInitContent()
}
func drawInitContent() {
if let opticRep = self.object {
shapeLayer.path = opticRep.bezierPath.CGPath
} else {
self.setUpGrid()
self.drawGrid()
self.drawRay()
}
}
private func setUpGrid() {
let mirror = GOFlatMirrorRep(center: GOCoordinate(x: 60, y: 35), thickness: 2, length: 6, direction: CGVectorMake(-0.3, 1), id: "MIRROR_1")
self.grid?.addInstrument(mirror)
let flatLens = GOFlatLensRep(center: GOCoordinate(x: 27, y: 29), thickness: 8, length: 8, direction: CGVectorMake(1, 1), refractionIndex: 1.33, id: "FLAT_LENS_1")
self.grid?.addInstrument(flatLens)
let concaveLens = GOConcaveLensRep(center: GOCoordinate(x: 44, y: 33), direction: CGVectorMake(0, 1), thicknessCenter: 1, thicknessEdge: 4, curvatureRadius: 5, id: "CONCAVE_LENS_1", refractionIndex: 1.50)
self.grid?.addInstrument(concaveLens)
let convexLens = GOConvexLensRep(center: GOCoordinate(x: 35, y: 26), direction: CGVectorMake(0, -1), thickness: 3, curvatureRadius: 20, id: "CONVEX_LENS_1", refractionIndex: 1.50)
self.grid?.addInstrument(convexLens)
let convexLens1 = GOConvexLensRep(center: GOCoordinate(x: 15, y: 25), direction: CGVectorMake(1, -1), thickness: 3, curvatureRadius: 8, id: "CONVEX_LENS_2", refractionIndex: 1.50)
self.grid?.addInstrument(convexLens1)
}
private func drawGrid() {
for (id, instrument) in self.grid!.instruments {
let layer = self.getPreviewShapeLayer()
layer.path = self.grid!.getInstrumentDisplayPathForID(id)?.CGPath
self.view.layer.addSublayer(layer)
}
}
private func drawRay() {
let ray = GORay(startPoint: CGPoint(x:0.1, y: 24), direction: CGVector(dx: 1, dy: 0))
let layer = self.getPreviewShapeLayer()
println("before path calculation")
let path = self.grid!.getRayPath(ray)
println("after path calculation")
println(path.CGPath)
layer.path = path.CGPath
self.view.layer.addSublayer(layer)
let pathAnimation = CABasicAnimation(keyPath: "strokeEnd")
pathAnimation.fromValue = 0.0;
pathAnimation.toValue = 1.0;
pathAnimation.duration = 3.0;
pathAnimation.repeatCount = 1.0
pathAnimation.fillMode = kCAFillModeForwards
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
layer.addAnimation(pathAnimation, forKey: "strokeEnd")
}
private func getPreviewShapeLayer() -> CAShapeLayer {
let layer = CAShapeLayer()
layer.strokeEnd = 1.0
layer.strokeColor = UIColor.whiteColor().CGColor
layer.fillColor = UIColor.clearColor().CGColor
layer.lineWidth = 2.0
return layer
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func didSwipe(sender: UISwipeGestureRecognizer) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func setUp(object: GOOpticRep?) {
self.object = object
}
}
| mit | 24ac6a7c4d6ca0bf279df995732ce4c1 | 37.139535 | 212 | 0.652439 | 4.369449 | false | false | false | false |
box/box-ios-sdk | Sources/Modules/WebLinksModule.swift | 1 | 11809 | //
// WebLinksModule.swift
// BoxSDK-iOS
//
// Created by Cary Cheng on 8/3/19.
// Copyright © 2019 box. All rights reserved.
//
import Foundation
/// Provides [Web Link](../Structs/WebLink.html) management.
public class WebLinksModule {
/// Required for communicating with Box APIs.
weak var boxClient: BoxClient!
// swiftlint:disable:previous implicitly_unwrapped_optional
/// Initializer
///
/// - Parameter boxClient: Required for communicating with Box APIs.
init(boxClient: BoxClient) {
self.boxClient = boxClient
}
/// Get information about a specified web link.
///
/// - Parameters:
/// - webLinkId: The ID of the web link on which to retrieve information.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full web link object or an error.
public func get(
webLinkId: String,
fields: [String]? = nil,
completion: @escaping Callback<WebLink>
) {
boxClient.get(
url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
completion: ResponseHandler.default(wrapping: completion)
)
}
// swiftlint:disable unused_param
/// Creates a new web link with the specified url on the specified item.
///
/// - Parameters:
/// - url: The specified url to create the web link for.
/// - parentId: The id of the folder item that the web link lives in.
/// - name: Optional name value for the created web link. If no name value is specified, defaults to url.
/// - description: Optional description value for the created web link.
/// - sharedLink: Shared links provide direct, read-only access to files or folder on Box using a URL.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full web link object or an error.
@available(*, deprecated, message: "Please use create(url:parentId:name:description:fields:completion:)'instead.")
public func create(
url: String,
parentId: String,
name: String? = nil,
description: String? = nil,
sharedLink _: NullableParameter<SharedLinkData>? = nil,
fields: [String]? = nil,
completion: @escaping Callback<WebLink>
) {
create(
url: url,
parentId: parentId,
name: name,
description: description,
fields: fields,
completion: completion
)
}
// swiftlint:enable unused_param
/// Creates a new web link with the specified url on the specified item.
///
/// - Parameters:
/// - url: The specified url to create the web link for.
/// - parentId: The id of the folder item that the web link lives in.
/// - name: Optional name value for the created web link. If no name value is specified, defaults to url.
/// - description: Optional description value for the created web link.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns a full web link object or an error.
public func create(
url: String,
parentId: String,
name: String? = nil,
description: String? = nil,
fields: [String]? = nil,
completion: @escaping Callback<WebLink>
) {
var body: [String: Any] = [:]
body["parent"] = ["id": parentId]
body["url"] = url
body["name"] = name
body["description"] = description
boxClient.post(
url: URL.boxAPIEndpoint("/2.0/web_links", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Update the specified web link info.
///
/// - Parameters:
/// - webLinkId: The id of the web link to update info for.
/// - url: The new url for the web link to update to.
/// - parentId: The id of the new parent folder to move the web link.
/// - name: The new name for the web link to update to.
/// - description: The new description for the web link to update to.
/// - sharedLink: Shared links provide direct, read-only access to web link on Box using a URL.
/// The canDownload which is inner property in sharedLink is not supported in web links.
/// - fields: Comma-separated list of [fields](https://developer.box.com/reference#fields) to
/// include in the response.
/// - completion: Returns the updated web link object or an error.
public func update(
webLinkId: String,
url: String? = nil,
parentId: String? = nil,
name: String? = nil,
description: String? = nil,
sharedLink: NullableParameter<SharedLinkData>? = nil,
fields: [String]? = nil,
completion: @escaping Callback<WebLink>
) {
var body: [String: Any] = [:]
body["url"] = url
body["name"] = name
body["description"] = description
if let parentId = parentId {
body["parent"] = ["id": parentId]
}
if let unwrappedSharedLink = sharedLink {
switch unwrappedSharedLink {
case .null:
body["shared_link"] = NSNull()
case let .value(sharedLinkValue):
var bodyDict = sharedLinkValue.bodyDict
// The permissions property is not supported in web link.
// So we need to remove this property in case when user set it.
bodyDict.removeValue(forKey: "permissions")
body["shared_link"] = bodyDict
}
}
boxClient.put(
url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration),
queryParameters: ["fields": FieldsQueryParam(fields)],
json: body,
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Delete a specified web link.
///
/// - Parameters:
/// - webLink: The ID of the web link to delete.
/// - completion: An empty response will be returned upon successful deletion.
public func delete(
webLinkId: String,
completion: @escaping Callback<Void>
) {
boxClient.delete(
url: URL.boxAPIEndpoint("/2.0/web_links/\(webLinkId)", configuration: boxClient.configuration),
completion: ResponseHandler.default(wrapping: completion)
)
}
/// Gets web link with updated shared link
///
/// - Parameters:
/// - webLinkId: The ID of the web link
/// - completion: Returns a standard shared link object or an error
public func getSharedLink(
forWebLink webLinkId: String,
completion: @escaping Callback<SharedLink>
) {
get(webLinkId: webLinkId, fields: ["shared_link"]) { result in
completion(WebLinksModule.unwrapSharedLinkObject(from: result))
}
}
// swiftlint:disable unused_param
/// Creates or updates shared link for a web link
///
/// - Parameters:
/// - webLink: The ID of the web link
/// - access: The level of access. If you omit this field then the access level will be set to the default access level specified by the enterprise admin
/// - unsharedAt: The date-time that this link will become disabled. This field can only be set by users with paid accounts
/// - vanityName: The custom name of a shared link, as used in the vanityUrl field.
/// It should be between 12 and 30 characters. This field can contains only letters, numbers, and hyphens.
/// - password: The password required to access the shared link. Set to .null to remove the password
/// - canDownload: Whether the shared link allows downloads. Applies to any items in the folder
/// - completion: Returns a standard SharedLink object or an error
@available(*, deprecated, message: "Please use setSharedLink(forWebLink:access:unsharedAt:vanityName:password:completion:)'instead.")
public func setSharedLink(
forWebLink webLinkId: String,
access: SharedLinkAccess? = nil,
unsharedAt: NullableParameter<Date>? = nil,
vanityName: NullableParameter<String>? = nil,
password: NullableParameter<String>? = nil,
canDownload _: Bool? = nil,
completion: @escaping Callback<SharedLink>
) {
setSharedLink(
forWebLink: webLinkId,
access: access,
unsharedAt: unsharedAt,
vanityName: vanityName,
password: password,
completion: completion
)
}
// swiftlint:enable unused_param
/// Creates or updates shared link for a web link
///
/// - Parameters:
/// - webLink: The ID of the web link
/// - access: The level of access. If you omit this field then the access level will be set to the default access level specified by the enterprise admin
/// - unsharedAt: The date-time that this link will become disabled. This field can only be set by users with paid accounts
/// - vanityName: The custom name of a shared link, as used in the vanity_url field.
/// It should be between 12 and 30 characters. This field can contains only letters, numbers, and hyphens.
/// - password: The password required to access the shared link. Set to .null to remove the password
/// - completion: Returns a standard SharedLink object or an error
public func setSharedLink(
forWebLink webLinkId: String,
access: SharedLinkAccess? = nil,
unsharedAt: NullableParameter<Date>? = nil,
vanityName: NullableParameter<String>? = nil,
password: NullableParameter<String>? = nil,
completion: @escaping Callback<SharedLink>
) {
update(
webLinkId: webLinkId,
sharedLink: .value(SharedLinkData(
access: access,
password: password,
unsharedAt: unsharedAt,
vanityName: vanityName
)),
fields: ["shared_link"]
) { result in
completion(WebLinksModule.unwrapSharedLinkObject(from: result))
}
}
/// Removes shared link for a web link
///
/// - Parameters:
/// - webLinkId: The ID of the web link
/// - completion: Returns an empty response or an error
public func deleteSharedLink(
forWebLink webLinkId: String,
completion: @escaping Callback<Void>
) {
update(webLinkId: webLinkId, sharedLink: .null) { result in
completion(result.map { _ in })
}
}
/// Unwrap a SharedLink object from web link
///
/// - Parameter result: A standard collection of objects with the web link object or an error
/// - Returns: Returns a standard SharedLink object or an error
static func unwrapSharedLinkObject(from result: Result<WebLink, BoxSDKError>) -> Result<SharedLink, BoxSDKError> {
switch result {
case let .success(webLink):
guard let sharedLink = webLink.sharedLink else {
return .failure(BoxSDKError(message: .notFound("Shared link for web link")))
}
return .success(sharedLink)
case let .failure(error):
return .failure(error)
}
}
}
| apache-2.0 | 2cec5c06b1e296490b42d140fd9f9218 | 39.717241 | 159 | 0.618987 | 4.713772 | false | false | false | false |
fernandomarins/food-drivr-pt | hackathon-for-hunger/Modules/Driver/Dashboards/Views/CurrentDonationsDashboard.swift | 1 | 7193 | //
// CurrentDonationsDashboard.swift
// hackathon-for-hunger
//
// Created by Ian Gristock on 4/22/16.
// Copyright © 2016 Hacksmiths. All rights reserved.
//
import UIKit
import RealmSwift
class CurrentDonationsDashboard: UIViewController {
// action for unwind segue
@IBAction func unwindForAccept(unwindSegue: UIStoryboardSegue, towardsViewController subsequentVC: UIViewController) {
}
@IBOutlet weak var noDonationsView: UIView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var tableView: UITableView!
private var refreshControl: UIRefreshControl!
var activityIndicator : ActivityIndicatorView!
private let dashboardPresenter = DashboardPresenter(donationService: DonationService())
var pendingDonations: Results<Donation>?
override func viewDidLoad() {
self.noDonationsView.hidden = true
super.viewDidLoad()
dashboardPresenter.attachView(self)
activityIndicator = ActivityIndicatorView(inview: self.view, messsage: "Syncing")
refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(PendingDonationsDashboard.refresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
tableView.addSubview(refreshControl)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
dashboardPresenter.fetch([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue])
}
func refresh(sender: AnyObject) {
self.startLoading()
dashboardPresenter.fetchRemotely([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue])
refreshControl?.endRefreshing()
}
@IBAction func toggleMenu(sender: AnyObject) {
self.slideMenuController()?.openLeft()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if (segue.identifier == "toDriverMapDetailCurrentFromDashboard") {
if let donation = sender as? Donation {
let donationVC = segue.destinationViewController as! DriverMapDetailPendingVC
donationVC.donation = donation
}
}
if (segue.identifier == "acceptedDonation") {
if let donation = sender as? Donation {
let donationVC = segue.destinationViewController as! DriverMapPickupVC
donationVC.donation = donation
}
}
}
}
extension CurrentDonationsDashboard: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?
{
let cancel = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Remove" , handler: { (action:UITableViewRowAction!, indexPath:NSIndexPath!) -> Void in
let donation = self.pendingDonations![indexPath.row]
self.startLoading()
self.dashboardPresenter.updateDonationStatus(donation, status: .Pending)
})
cancel.backgroundColor = UIColor.redColor()
return [cancel]
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return pendingDonations?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let identifier = "pendingDonation"
let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) as! PendingDonationsDashboardTableViewCell
cell.indexPath = indexPath
cell.information = pendingDonations![indexPath.row]
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
cell.layer.transform = CATransform3DMakeScale(0.1,0.1,1)
UIView.animateWithDuration(0.25, animations: {
cell.layer.transform = CATransform3DMakeScale(1,1,1)
})
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("toDriverMapDetailCurrentFromDashboard", sender: self)
}
//empty implementation
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
}
}
extension CurrentDonationsDashboard: DashboardView {
func startLoading() {
self.activityIndicator.startAnimating()
}
func finishLoading() {
self.activityIndicator.stopAnimating()
self.activityIndicator.title = "Syncing"
}
func donations(sender: DashboardPresenter, didSucceed donations: Results<Donation>) {
self.finishLoading()
self.pendingDonations = donations
self.tableView.reloadData()
}
func donations(sender: DashboardPresenter, didFail error: NSError) {
self.finishLoading()
if error.code == 401 {
let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
self.logout()
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
func donationStatusUpdate(sender: DashboardPresenter, didSucceed donation: Donation) {
self.finishLoading()
self.dashboardPresenter.fetch([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue])
}
func donationStatusUpdate(sender: DashboardPresenter, didFail error: NSError) {
self.finishLoading()
if error.code == 401 {
let refreshAlert = UIAlertController(title: "Unable To Sync.", message: "Your session has expired. Please log back in", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
self.logout()
}))
presentViewController(refreshAlert, animated: true, completion: nil)
} else {
let refreshAlert = UIAlertController(title: "Unable To Accept.", message: "Donation might have already been cancelled. Resync your donations?.", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
self.startLoading()
self.dashboardPresenter.fetchRemotely([DonationStatus.Accepted.rawValue, DonationStatus.PickedUp.rawValue])
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
}))
presentViewController(refreshAlert, animated: true, completion: nil)
}
}
}
| mit | 8d3fd0b280b17e118b74ed17f374f789 | 40.097143 | 202 | 0.678949 | 5.570875 | false | false | false | false |
HongliYu/firefox-ios | Client/Frontend/Settings/SettingsLoadingView.swift | 1 | 1265 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import SnapKit
class SettingsLoadingView: UIView {
var searchBarHeight: CGFloat = 0 {
didSet {
setNeedsUpdateConstraints()
}
}
lazy var indicator: UIActivityIndicatorView = {
let isDarkTheme = ThemeManager.instance.currentName == .dark
let indicator = UIActivityIndicatorView(activityIndicatorStyle: isDarkTheme ? .white : .gray)
indicator.hidesWhenStopped = false
return indicator
}()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(indicator)
backgroundColor = UIColor.theme.tableView.headerBackground
indicator.startAnimating()
}
internal override func updateConstraints() {
super.updateConstraints()
indicator.snp.remakeConstraints { make in
make.centerX.equalTo(self)
make.centerY.equalTo(self).offset(-(searchBarHeight / 2))
}
}
}
| mpl-2.0 | 5d8fa540557c7430faad3a292c925cb6 | 29.853659 | 101 | 0.659289 | 4.960784 | false | false | false | false |
pseudomuto/CircuitBreaker | Pod/Classes/Invoker.swift | 1 | 1319 | //
// Invoker.swift
// Pods
//
// Created by David Muto on 2016-02-05.
//
//
class Invoker {
private let queue: dispatch_queue_t!
init(_ queue: dispatch_queue_t) {
self.queue = queue
}
func invoke<T>(state: State, timeout: NSTimeInterval, block: () throws -> T) throws -> T {
var endResult: T? = nil
var error: ErrorType? = nil
exec(timeout.dispatchTime(), block: block) { (result, exc) in
error = exc
endResult = result
}
if error != nil {
state.onError()
throw error!
}
state.onSuccess()
return endResult!
}
private func exec<T>(timeout: dispatch_time_t, block: () throws -> T, handler: (T?, ErrorType?) -> Void) {
let semaphore = dispatch_semaphore_create(0)
var result: T? = nil
var handled = false
let handleError = { (error: ErrorType) in
if handled { return }
handled = true
handler(nil, error)
}
dispatch_async(queue) {
defer { dispatch_semaphore_signal(semaphore) }
do {
result = try block()
}
catch let err {
handleError(err)
}
}
if dispatch_semaphore_wait(semaphore, timeout) != 0 {
handleError(Error.InvocationTimeout)
}
if !handled {
handler(result, nil)
}
}
}
| mit | 4fafd1777d2ab915d5be7efd65b1d0dd | 18.984848 | 108 | 0.564822 | 3.801153 | false | false | false | false |
zyhndesign/SDX_DG | sdxdg/sdxdg/ConstantsUtil.swift | 1 | 3810 | //
// ConstantsUtil.swift
// sdxdg
//
// Created by lotusprize on 17/3/16.
// Copyright © 2017年 geekTeam. All rights reserved.
//
import Foundation
import UIKit
class ConstantsUtil : NSObject {
//static var WEB_API_BASE_URL:String = "http://cyzsk.fzcloud.design-engine.org/sdx_cloud"
static var WEB_API_BASE_URL:String = "http://192.168.3.166:8080/sdx"
static let APP_USER_LOGIN_URL:String = WEB_API_BASE_URL + "/dggl/appUser/authorityCheck"
static let APP_USER_UPDATE_URL:String = WEB_API_BASE_URL + "/dggl/appUser/updateUser"
static let APP_USER_GET_VIP_URL:String = WEB_API_BASE_URL + "/dggl/appVipUser/getVipuserByShoppingGuideId"
static let APP_USER_UPDATE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/appUser/appUpdateUser"
static let APP_USER_BACK_HELP_DATA_URL:String = WEB_API_BASE_URL + "/dggl/appHelper/createInfo"
static let ALL_USER_UPDATE_PWD:String = WEB_API_BASE_URL + "/dggl/appUser/updatePwd"
//创建搭配
static let APP_MATCH_CREATE_URL:String = WEB_API_BASE_URL + "/dggl/match/createMatch"
//获取已经分享数据
static let APP_MATCH_LIST_BY_SHARESTATUS_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByShareStatus"
//获取草稿箱数据
static let APP_MATCH_LIST_BY_DRAFT_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByDraftStatus"
//获取反馈数据
static let APP_MATCH_LIST_BY_BACK_URL:String = WEB_API_BASE_URL + "/dggl/match/getAppMatchByBackStatus"
//创建反馈
static let APP_MATCH_LIST_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/createFeedback"
//取消反馈
static let APP_MATCH_LIST_CANCEL_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/deleteFeedback"
//获取热门反馈
static let APP_MATCH_LIST_HOT_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/getDataByUserId"
//获取前3个热门反馈
static let APP_MATCH_THREE_HOT_FEEDBACK_URL:String = WEB_API_BASE_URL + "/dggl/feedback/getTopThreeDataByUserId"
//获取用户已经分享的数据
static let APP_GET_SHARE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/share/getShareData"
//创建分享
static let APP_CREATE_SHARE_DATA_URL:String = WEB_API_BASE_URL + "/dggl/share/createShare"
static let APP_GET_STATISTICS_YEAR_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByYear"
static let APP_GET_STATISTICS_MONTH_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByMonth"
static let APP_GET_STATISTICS_WEEK_DATA:String = WEB_API_BASE_URL + "/dggl/match/getStatisticsDataByWeek"
static let APP_UPDATE_SHARE_SUCESS_DATE_URL:String = WEB_API_BASE_URL + "/dggl/match/updateShareStatus";
static let APP_MATCH_LIST_BY_CATEGORY = WEB_API_BASE_URL + "/app/hpManage/getHpDataByCategoryId"
static let APP_FEEDBACK_VIP_NAMES = WEB_API_BASE_URL + "/dggl/feedback/getFeedbackVipName"
static let APP_HPGL_CATEGORY = WEB_API_BASE_URL + "/hpgl/category/getData"
static let APP_HPGL_INDEX = WEB_API_BASE_URL + "/hpgl/hpIndexManage/getAppData"
static let APP_SHARE_HISTORY_URL = WEB_API_BASE_URL + "/dggl/match/getPushHistoryByVipNameAndUserId"
static let APP_HPGL_HP_DETAIL = WEB_API_BASE_URL + "/hpgl/hpManage/productDetail/"
static let APP_DGGL_MATCH_DETAIL = WEB_API_BASE_URL + "/dggl/match/matchDetail/"
static let APP_DGGL_SHARE_DETAIL = WEB_API_BASE_URL + "/dggl/match/shareDetail/"
static let APP_DGGL_SHARE_RESULT_DETAIL = WEB_API_BASE_URL + "/dggl/share/shareDetail/"
static let APP_QINIU_TOKEN = WEB_API_BASE_URL + "/hpgl/hpManage/getUploadKey"
static let APP_QINIU_UPLOAD_URL = "http://upload.qiniu.com/"
static let APP_QINIU_IMAGE_URL_PREFIX = "http://oaycvzlnh.bkt.clouddn.com/"
}
| apache-2.0 | 0f237854512a5b181efda76cf8946a64 | 51.614286 | 116 | 0.711377 | 3.071726 | false | false | false | false |
LeeShiYoung/DouYu | DouYuAPP/DouYuAPP/Classes/Main/View/Yo_BaseSectionHeaderView.swift | 1 | 1683 | //
// Yo_BaseSectionHeaderView.swift
// DouYuAPP
//
// Created by shying li on 2017/3/31.
// Copyright © 2017年 李世洋. All rights reserved.
//
import UIKit
class Yo_BaseSectionHeaderView: GenericReusableView, Yo_BaseCollectionViewProtocol {
override func configureView() {
super.configureView()
setupUI()
}
public lazy var headerIcon: UIImageView = {[weak self] in
let headerIcon = UIImageView()
self?.addSubview(headerIcon)
return headerIcon
}()
public lazy var sectionName: UILabel = {[weak self] in
let sectionName = UILabel()
sectionName.font = UIFont.systemFont(ofSize: 16)
sectionName.textColor = UIColor.colorWithHex("#020202")
self?.addSubview(sectionName)
return sectionName
}()
fileprivate lazy var garyLayer: CALayer = {
let garyLayer = CALayer()
garyLayer.frame = CGRect(x: 0, y: 0, width: kScreenW, height: 10)
garyLayer.backgroundColor = UIColor.colorWithHex("#e5e5e5")?.cgColor
return garyLayer
}()
}
extension Yo_BaseSectionHeaderView {
fileprivate func setupUI() {
layer.addSublayer(garyLayer)
headerIcon.snp.makeConstraints { (maker) in
maker.left.equalTo(self.snp.left).offset(10)
maker.centerY.equalTo(self.snp.centerY).offset(5)
}
sectionName.snp.makeConstraints { (maker) in
maker.centerY.equalTo(headerIcon.snp.centerY)
maker.left.equalTo(headerIcon.snp.right).offset(5)
}
}
func configure(Item: Any, indexPath: IndexPath) {
}
}
| apache-2.0 | 79c392755f5f38adb5ede045b67f9b8b | 26.9 | 84 | 0.621266 | 4.561308 | false | false | false | false |
tinrobots/Mechanica | Tests/UIKitTests/UIViewUtilsTests.swift | 1 | 2533 | #if os(iOS) || os(tvOS) || os(watchOS)
import XCTest
@testable import Mechanica
final class UIWiewUtilsTests: XCTestCase {
func testCornerRadius() {
let view = UIView()
view.cornerRadius = 5.0
XCTAssertEqual(view.layer.cornerRadius, view.cornerRadius)
}
func testBorderWidth() {
let view = UIView()
view.borderWidth = 5.0
XCTAssertEqual(view.layer.borderWidth, view.borderWidth)
}
func testBorderColor() {
let view = UIView()
view.borderColor = .red
XCTAssertNotNil(view.borderColor)
let layerColor = view.layer.borderColor
XCTAssertEqual(layerColor, UIColor.red.cgColor)
view.borderColor = nil
XCTAssertNil(view.borderColor)
XCTAssertNil(view.layer.borderColor)
}
func testShadowRadius() {
let view = UIView()
view.shadowRadius = 15.0
XCTAssertEqual(view.layer.shadowRadius, view.shadowRadius)
}
func testShadowOpacity() {
let view = UIView()
view.shadowOpacity = 0.7
XCTAssertEqual(view.layer.shadowOpacity, view.shadowOpacity)
}
func testShadowOffset() {
let view = UIView()
view.shadowOffset = CGSize(width: 12.3, height: 45.6)
XCTAssertEqual(view.layer.shadowOffset, view.shadowOffset)
}
func testShadowColor() {
let view = UIView()
view.shadowColor = .red
XCTAssertNotNil(view.shadowColor)
let layerShadowColor = view.layer.shadowColor
XCTAssertEqual(layerShadowColor, UIColor.red.cgColor)
view.shadowColor = nil
XCTAssertNil(view.shadowColor)
XCTAssertNil(view.layer.shadowColor)
}
#if os(iOS) || os(tvOS)
func testUseAutolayout() {
let view = UIView()
let view2 = UIView()
view.usesAutoLayout = true
XCTAssertFalse(view.translatesAutoresizingMaskIntoConstraints)
view.usesAutoLayout = false
XCTAssertTrue(view.translatesAutoresizingMaskIntoConstraints)
view2.translatesAutoresizingMaskIntoConstraints = false
XCTAssertTrue(view2.usesAutoLayout)
}
func testScreenshot() {
let view1 = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 50)))
view1.backgroundColor = .red
let view2 = UIView(frame: CGRect(origin: .zero, size: CGSize(width: 50, height: 25)))
view2.backgroundColor = .green
view1.addSubview(view2)
let screenshot = view1.screenshot()
XCTAssertTrue(screenshot.size.width == 100)
XCTAssertTrue(screenshot.size.height == 50)
XCTAssertFalse(screenshot.size.width == 50)
XCTAssertFalse(screenshot.size.height == 100)
}
#endif
}
#endif
| mit | 17537b0d969bef8e90435fada899d549 | 23.355769 | 90 | 0.707462 | 4.25 | false | true | false | false |
benlangmuir/swift | stdlib/public/BackDeployConcurrency/AsyncThrowingFlatMapSequence.swift | 5 | 6431 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that concatenates the results of calling
/// the given error-throwing transformation with each element of this
/// sequence.
///
/// Use this method to receive a single-level asynchronous sequence when your
/// transformation produces an asynchronous sequence for each element.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `5`. The transforming closure takes the received `Int`
/// and returns a new `Counter` that counts that high. For example, when the
/// transform receives `3` from the base sequence, it creates a new `Counter`
/// that produces the values `1`, `2`, and `3`. The `flatMap(_:)` method
/// "flattens" the resulting sequence-of-sequences into a single
/// `AsyncSequence`. However, when the closure receives `4`, it throws an
/// error, terminating the sequence.
///
/// do {
/// let stream = Counter(howHigh: 5)
/// .flatMap { (value) -> Counter in
/// if value == 4 {
/// throw MyError()
/// }
/// return Counter(howHigh: value)
/// }
/// for try await number in stream {
/// print ("\(number)", terminator: " ")
/// }
/// } catch {
/// print(error)
/// }
/// // Prints: 1 1 2 1 2 3 MyError()
///
/// - Parameter transform: An error-throwing mapping closure. `transform`
/// accepts an element of this sequence as its parameter and returns an
/// `AsyncSequence`. If `transform` throws an error, the sequence ends.
/// - Returns: A single, flattened asynchronous sequence that contains all
/// elements in all the asychronous sequences produced by `transform`. The
/// sequence ends either when the the last sequence created from the last
/// element from base sequence ends, or when `transform` throws an error.
@inlinable
public __consuming func flatMap<SegmentOfResult: AsyncSequence>(
_ transform: @escaping (Element) async throws -> SegmentOfResult
) -> AsyncThrowingFlatMapSequence<Self, SegmentOfResult> {
return AsyncThrowingFlatMapSequence(self, transform: transform)
}
}
/// An asynchronous sequence that concatenates the results of calling a given
/// error-throwing transformation with each element of this sequence.
@available(SwiftStdlib 5.1, *)
public struct AsyncThrowingFlatMapSequence<Base: AsyncSequence, SegmentOfResult: AsyncSequence> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async throws -> SegmentOfResult
@usableFromInline
init(
_ base: Base,
transform: @escaping (Base.Element) async throws -> SegmentOfResult
) {
self.base = base
self.transform = transform
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingFlatMapSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The flat map sequence produces the type of element in the asynchronous
/// sequence produced by the `transform` closure.
public typealias Element = SegmentOfResult.Element
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the flat map sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async throws -> SegmentOfResult
@usableFromInline
var currentIterator: SegmentOfResult.AsyncIterator?
@usableFromInline
var finished = false
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async throws -> SegmentOfResult
) {
self.baseIterator = baseIterator
self.transform = transform
}
/// Produces the next element in the flat map sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns `nil`. Otherwise, `next()` calls the
/// transforming closure on the received element, takes the resulting
/// asynchronous sequence, and creates an asynchronous iterator from it.
/// `next()` then consumes values from this iterator until it terminates.
/// At this point, `next()` is ready to receive the next value from the base
/// sequence. If `transform` throws an error, the sequence terminates.
@inlinable
public mutating func next() async throws -> SegmentOfResult.Element? {
while !finished {
if var iterator = currentIterator {
do {
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
// restore the iterator since we just mutated it with next
currentIterator = iterator
return element
} catch {
finished = true
throw error
}
} else {
guard let item = try await baseIterator.next() else {
return nil
}
let segment: SegmentOfResult
do {
segment = try await transform(item)
var iterator = segment.makeAsyncIterator()
guard let element = try await iterator.next() else {
currentIterator = nil
continue
}
currentIterator = iterator
return element
} catch {
finished = true
currentIterator = nil
throw error
}
}
}
return nil
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
| apache-2.0 | fc8643fe7b233f01dca480cdc0a1409f | 36.608187 | 97 | 0.633805 | 5.128389 | false | false | false | false |
sharath-cliqz/browser-ios | SyncTests/MockSyncServer.swift | 2 | 17493 | /* 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 Shared
import GCDWebServers
@testable import Sync
import XCTest
private let log = Logger.syncLogger
private func optTimestamp(x: AnyObject?) -> Timestamp? {
guard let str = x as? String else {
return nil
}
return decimalSecondsStringToTimestamp(str)
}
private func optStringArray(x: AnyObject?) -> [String]? {
guard let str = x as? String else {
return nil
}
return str.componentsSeparatedByString(",").map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) }
}
private struct SyncRequestSpec {
let collection: String
let id: String?
let ids: [String]?
let limit: Int?
let offset: String?
let sort: SortOption?
let newer: Timestamp?
let full: Bool
static func fromRequest(request: GCDWebServerRequest) -> SyncRequestSpec? {
// Input is "/1.5/user/storage/collection", possibly with "/id" at the end.
// That means we get five or six path components here, the first being empty.
let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty }
let id: String?
let ids = optStringArray(request.query["ids"])
let newer = optTimestamp(request.query["newer"])
let full: Bool = request.query["full"] != nil
let limit: Int?
if let lim = request.query["limit"] as? String {
limit = Int(lim)
} else {
limit = nil
}
let offset = request.query["offset"] as? String
let sort: SortOption?
switch request.query["sort"] as? String ?? "" {
case "oldest":
sort = SortOption.OldestFirst
case "newest":
sort = SortOption.NewestFirst
case "index":
sort = SortOption.Index
default:
sort = nil
}
if parts.count < 4 {
return nil
}
if parts[2] != "storage" {
return nil
}
// Use dropFirst, you say! It's buggy.
switch parts.count {
case 4:
id = nil
case 5:
id = parts[4]
default:
// Uh oh.
return nil
}
return SyncRequestSpec(collection: parts[3], id: id, ids: ids, limit: limit, offset: offset, sort: sort, newer: newer, full: full)
}
}
struct SyncDeleteRequestSpec {
let collection: String?
let id: GUID?
let ids: [GUID]?
let wholeCollection: Bool
static func fromRequest(request: GCDWebServerRequest) -> SyncDeleteRequestSpec? {
// Input is "/1.5/user{/storage{/collection{/id}}}".
// That means we get four, five, or six path components here, the first being empty.
return SyncDeleteRequestSpec.fromPath(request.path!, withQuery: request.query)
}
static func fromPath(path: String, withQuery query: [NSObject: AnyObject]) -> SyncDeleteRequestSpec? {
let parts = path.componentsSeparatedByString("/").filter { !$0.isEmpty }
let queryIDs: [GUID]? = (query["ids"] as? String)?.componentsSeparatedByString(",")
guard [2, 4, 5].contains(parts.count) else {
return nil
}
if parts.count == 2 {
return SyncDeleteRequestSpec(collection: nil, id: nil, ids: queryIDs, wholeCollection: true)
}
if parts[2] != "storage" {
return nil
}
if parts.count == 4 {
let hasIDs = queryIDs != nil
return SyncDeleteRequestSpec(collection: parts[3], id: nil, ids: queryIDs, wholeCollection: !hasIDs)
}
return SyncDeleteRequestSpec(collection: parts[3], id: parts[4], ids: queryIDs, wholeCollection: false)
}
}
private struct SyncPutRequestSpec {
let collection: String
let id: String
static func fromRequest(request: GCDWebServerRequest) -> SyncPutRequestSpec? {
// Input is "/1.5/user/storage/collection/id}}}".
// That means we get six path components here, the first being empty.
let parts = request.path!.componentsSeparatedByString("/").filter { !$0.isEmpty }
guard parts.count == 5 else {
return nil
}
if parts[2] != "storage" {
return nil
}
return SyncPutRequestSpec(collection: parts[3], id: parts[4])
}
}
class MockSyncServer {
let server = GCDWebServer()
let username: String
var offsets: Int = 0
var continuations: [String: [EnvelopeJSON]] = [:]
var collections: [String: (modified: Timestamp, records: [String: EnvelopeJSON])] = [:]
var baseURL: String!
init(username: String) {
self.username = username
}
class func makeValidEnvelope(guid: GUID, modified: Timestamp) -> EnvelopeJSON {
let clientBody: [String: AnyObject] = [
"id": guid,
"name": "Foobar",
"commands": [],
"type": "mobile",
]
let clientBodyString = JSON(clientBody).toString(false)
let clientRecord: [String : AnyObject] = [
"id": guid,
"collection": "clients",
"payload": clientBodyString,
"modified": Double(modified) / 1000,
]
return EnvelopeJSON(JSON(clientRecord).toString(false))
}
class func withHeaders(response: GCDWebServerResponse, lastModified: Timestamp? = nil, records: Int? = nil, timestamp: Timestamp? = nil) -> GCDWebServerResponse {
let timestamp = timestamp ?? NSDate.now()
let xWeaveTimestamp = millisecondsToDecimalSeconds(timestamp)
response.setValue("\(xWeaveTimestamp)", forAdditionalHeader: "X-Weave-Timestamp")
if let lastModified = lastModified {
let xLastModified = millisecondsToDecimalSeconds(lastModified)
response.setValue("\(xLastModified)", forAdditionalHeader: "X-Last-Modified")
}
if let records = records {
response.setValue("\(records)", forAdditionalHeader: "X-Weave-Records")
}
return response;
}
func storeRecords(records: [EnvelopeJSON], inCollection collection: String, now: Timestamp? = nil) {
let now = now ?? NSDate.now()
let coll = self.collections[collection]
var out = coll?.records ?? [:]
records.forEach {
out[$0.id] = $0.withModified(now)
}
let newModified = max(now, coll?.modified ?? 0)
self.collections[collection] = (modified: newModified, records: out)
}
private func splitArray<T>(items: [T], at: Int) -> ([T], [T]) {
return (Array(items.dropLast(items.count - at)), Array(items.dropFirst(at)))
}
private func recordsMatchingSpec(spec: SyncRequestSpec) -> (records: [EnvelopeJSON], offsetID: String?)? {
// If we have a provided offset, handle that directly.
if let offset = spec.offset {
log.debug("Got provided offset \(offset).")
guard let remainder = self.continuations[offset] else {
log.error("Unknown offset.")
return nil
}
// Remove the old one.
self.continuations.removeValueForKey(offset)
// Handle the smaller-than-limit or no-provided-limit cases.
guard let limit = spec.limit where limit < remainder.count else {
log.debug("Returning all remaining items.")
return (remainder, nil)
}
// Record the next continuation and return the first slice of records.
let next = "\(self.offsets)"
self.offsets += 1
let (returned, remaining) = splitArray(remainder, at: limit)
self.continuations[next] = remaining
log.debug("Returning \(limit) items; next continuation is \(next).")
return (returned, next)
}
guard let records = self.collections[spec.collection]?.records.values else {
// No matching records.
return ([], nil)
}
var items = Array(records)
log.debug("Got \(items.count) candidate records.")
if spec.newer ?? 0 > 0 {
items = items.filter { $0.modified > spec.newer }
}
if let ids = spec.ids {
let ids = Set(ids)
items = items.filter { ids.contains($0.id) }
}
if let sort = spec.sort {
switch sort {
case SortOption.NewestFirst:
items = items.sort { $0.modified > $1.modified }
log.debug("Sorted items newest first: \(items.map { $0.modified })")
case SortOption.OldestFirst:
items = items.sort { $0.modified < $1.modified }
log.debug("Sorted items oldest first: \(items.map { $0.modified })")
case SortOption.Index:
log.warning("Index sorting not yet supported.")
}
}
if let limit = spec.limit where items.count > limit {
let next = "\(self.offsets)"
self.offsets += 1
let (returned, remaining) = splitArray(items, at: limit)
self.continuations[next] = remaining
return (returned, next)
}
return (items, nil)
}
private func recordResponse(record: EnvelopeJSON) -> GCDWebServerResponse {
let body = JSON(record.asJSON()).toString()
let bodyData = body.utf8EncodedData
let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")
return MockSyncServer.withHeaders(response, lastModified: record.modified)
}
private func modifiedResponse(timestamp: Timestamp) -> GCDWebServerResponse {
let body = JSON(["modified": NSNumber(value: timestamp)]).toString()
let bodyData = body.utf8EncodedData
let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")
return MockSyncServer.withHeaders(response)
}
func modifiedTimeForCollection(collection: String) -> Timestamp? {
return self.collections[collection]?.modified
}
func removeAllItemsFromCollection(collection: String, atTime: Timestamp) {
if self.collections[collection] != nil {
self.collections[collection] = (atTime, [:])
}
}
func start() {
let basePath = "/1.5/\(self.username)"
let storagePath = "\(basePath)/storage/"
let infoCollectionsPath = "\(basePath)/info/collections"
server.addHandlerForMethod("GET", path: infoCollectionsPath, requestClass: GCDWebServerRequest.self) { (request) -> GCDWebServerResponse! in
var ic = [String: NSNumber]()
var lastModified: Timestamp = 0
for collection in self.collections.keys {
if let timestamp = self.modifiedTimeForCollection(collection) {
ic[collection] = NSNumber(double: Double(timestamp) / 1000)
lastModified = max(lastModified, timestamp)
}
}
let body = JSON(ic).toString()
let bodyData = body.utf8EncodedData
let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")
return MockSyncServer.withHeaders(response, lastModified: lastModified, records: ic.count)
}
let matchPut: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in
guard method == "PUT" && path.startsWith(basePath) else {
return nil
}
return GCDWebServerDataRequest(method: method, url: url, headers: headers, path: path, query: query)
}
server.addHandlerWithMatchBlock(matchPut) { (request) -> GCDWebServerResponse! in
guard let request = request as? GCDWebServerDataRequest else {
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400))
}
guard let spec = SyncPutRequestSpec.fromRequest(request) else {
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400))
}
var body = JSON(request.jsonObject).asDictionary!
body["modified"] = JSON(millisecondsToDecimalSeconds(NSDate.now()))
let record = EnvelopeJSON(JSON(body))
self.storeRecords([record], inCollection: spec.collection)
let timestamp = self.modifiedTimeForCollection(spec.collection)!
let response = GCDWebServerDataResponse(data: millisecondsToDecimalSeconds(timestamp).utf8EncodedData, contentType: "application/json")
return MockSyncServer.withHeaders(response)
}
let matchDelete: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in
guard method == "DELETE" && path.startsWith(basePath) else {
return nil
}
return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query)
}
server.addHandlerWithMatchBlock(matchDelete) { (request) -> GCDWebServerResponse! in
guard let spec = SyncDeleteRequestSpec.fromRequest(request) else {
return GCDWebServerDataResponse(statusCode: 400)
}
if let collection = spec.collection, id = spec.id {
guard var items = self.collections[collection]?.records else {
// Unable to find the requested collection.
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404))
}
guard let item = items[id] else {
// Unable to find the requested id.
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404))
}
items.removeValueForKey(id)
return self.modifiedResponse(item.modified)
}
if let collection = spec.collection {
if spec.wholeCollection {
self.collections.removeValueForKey(collection)
} else {
if let ids = spec.ids,
var map = self.collections[collection]?.records {
for id in ids {
map.removeValueForKey(id)
}
self.collections[collection] = (modified: NSDate.now(), records: map)
}
}
return self.modifiedResponse(NSDate.now())
}
self.collections = [:]
return MockSyncServer.withHeaders(GCDWebServerDataResponse(data: "{}".utf8EncodedData, contentType: "application/json"))
}
let match: GCDWebServerMatchBlock = { method, url, headers, path, query -> GCDWebServerRequest! in
guard method == "GET" && path.startsWith(storagePath) else {
return nil
}
return GCDWebServerRequest(method: method, url: url, headers: headers, path: path, query: query)
}
server.addHandlerWithMatchBlock(match) { (request) -> GCDWebServerResponse! in
// 1. Decide what the URL is asking for. It might be a collection fetch or
// an individual record, and it might have query parameters.
guard let spec = SyncRequestSpec.fromRequest(request) else {
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400))
}
// 2. Grab the matching set of records. Prune based on TTL, exclude with X-I-U-S, etc.
if let id = spec.id {
guard let collection = self.collections[spec.collection], record = collection.records[id] else {
// Unable to find the requested collection/id.
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 404))
}
return self.recordResponse(record)
}
guard let (items, offset) = self.recordsMatchingSpec(spec) else {
// Unable to find the provided offset.
return MockSyncServer.withHeaders(GCDWebServerDataResponse(statusCode: 400))
}
// TODO: TTL
// TODO: X-I-U-S
let body = JSON(items.map { $0.asJSON() }).toString()
let bodyData = body.utf8EncodedData
let response = GCDWebServerDataResponse(data: bodyData, contentType: "application/json")
// 3. Compute the correct set of headers: timestamps, X-Weave-Records, etc.
if let offset = offset {
response.setValue(offset, forAdditionalHeader: "X-Weave-Next-Offset")
}
let timestamp = self.modifiedTimeForCollection(spec.collection)!
log.debug("Returning GET response with X-Last-Modified for \(items.count) records: \(timestamp).")
return MockSyncServer.withHeaders(response, lastModified: timestamp, records: items.count)
}
if server.startWithPort(0, bonjourName: nil) == false {
XCTFail("Can't start the GCDWebServer.")
}
baseURL = "http://localhost:\(server.port)\(basePath)"
}
}
| mpl-2.0 | 8afe5bab24eb1789fb2f95e070904ca7 | 37.78714 | 166 | 0.598468 | 4.983761 | false | false | false | false |
tungvoduc/DTButtonMenuController | Example/Tests/Tests.swift | 1 | 1172 | // https://github.com/Quick/Quick
import Quick
import Nimble
import DTButtonMenuController
class TableOfContentsSpec: QuickSpec {
override func spec() {
describe("these will fail") {
it("can do maths") {
expect(1) == 2
}
it("can read") {
expect("number") == "string"
}
it("will eventually fail") {
expect("time").toEventually( equal("done") )
}
context("these will pass") {
it("can do maths") {
expect(23) == 23
}
it("can read") {
expect("🐮") == "🐮"
}
it("will eventually pass") {
var time = "passing"
DispatchQueue.main.async {
time = "done"
}
waitUntil { done in
Thread.sleep(forTimeInterval: 0.5)
expect(time) == "done"
done()
}
}
}
}
}
}
| mit | edc5ad84241bf0a4b91fbdd93dc5527d | 22.32 | 60 | 0.364494 | 5.552381 | false | false | false | false |
aapierce0/MatrixClient | MatrixClient/AppDelegate.swift | 1 | 5755 | /*
Copyright 2017 Avery Pierce
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 Cocoa
import SwiftMatrixSDK
protocol MatrixSessionManagerDelegate {
func matrixDidStart(_ session: MXSession)
func matrixDidLogout()
}
class MatrixSessionManager {
static let shared = MatrixSessionManager()
static let credentialsDictionaryKey = "MatrixCredentials"
enum State {
case needsCredentials, notStarted, starting, started
}
private(set) var state: State
var credentials: MXCredentials? {
didSet {
// Make sure to synchronize the user defaults after we're done here
defer { UserDefaults.standard.synchronize() }
guard
let homeServer = credentials?.homeServer,
let userId = credentials?.userId,
let token = credentials?.accessToken
else { UserDefaults.standard.removeObject(forKey: "MatrixCredentials"); return }
let storedCredentials: [String: String] = [
"homeServer": homeServer,
"userId": userId,
"token": token
]
UserDefaults.standard.set(storedCredentials, forKey: "MatrixCredentials")
}
}
var session: MXSession?
var delegate: MatrixSessionManagerDelegate?
init() {
// Make sure that someone is logged in.
if let savedCredentials = UserDefaults.standard.dictionary(forKey: MatrixSessionManager.credentialsDictionaryKey),
let homeServer = savedCredentials["homeServer"] as? String,
let userId = savedCredentials["userId"] as? String,
let token = savedCredentials["token"] as? String {
credentials = MXCredentials(homeServer: homeServer, userId: userId, accessToken: token)
state = .notStarted
} else {
state = .needsCredentials
credentials = nil
}
}
func start() {
guard let credentials = credentials else { return }
let restClient = MXRestClient(credentials: credentials, unrecognizedCertificateHandler: nil)
session = MXSession(matrixRestClient: restClient)
state = .starting
let fileStore = MXFileStore()
session?.setStore(fileStore) { response in
if case .failure(let error) = response {
print("An error occurred setting the store: \(error)")
return
}
self.state = .starting
self.session?.start { response in
guard response.isSuccess else { return }
DispatchQueue.main.async {
self.state = .started
self.delegate?.matrixDidStart(self.session!);
}
}
}
}
func logout() {
UserDefaults.standard.removeObject(forKey: MatrixSessionManager.credentialsDictionaryKey)
UserDefaults.standard.synchronize()
self.credentials = nil
self.state = .needsCredentials
session?.logout { _ in
self.delegate?.matrixDidLogout()
}
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, MatrixSessionManagerDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
MatrixSessionManager.shared.delegate = self
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return false
}
func matrixDidStart(_ session: MXSession) {
let allViewControllers = NSApplication.shared().windows.flatMap({ return $0.descendentViewControllers })
allViewControllers.flatMap({ return $0 as? MatrixSessionManagerDelegate }).forEach { (delegate) in
delegate.matrixDidStart(session)
}
}
func matrixDidLogout() {
let allViewControllers = NSApplication.shared().windows.flatMap({ return $0.descendentViewControllers })
allViewControllers.flatMap({ return $0 as? MatrixSessionManagerDelegate }).forEach { (delegate) in
delegate.matrixDidLogout()
}
}
}
fileprivate extension NSWindow {
var descendentViewControllers: [NSViewController] {
var descendents = [NSViewController]()
if let rootViewController = windowController?.contentViewController {
descendents.append(rootViewController)
descendents.append(contentsOf: rootViewController.descendentViewControllers)
}
return descendents
}
}
fileprivate extension NSViewController {
var descendentViewControllers: [NSViewController] {
// Capture this view controller's children, and add their descendents
var descendents = childViewControllers
descendents.append(contentsOf: childViewControllers.flatMap({ return $0.descendentViewControllers }))
return descendents
}
}
| apache-2.0 | b25a9217602f71d1bbeb7019f8bc7186 | 32.852941 | 123 | 0.638923 | 5.801411 | false | false | false | false |
ryanfowler/RFTimer | RFTimer.swift | 1 | 7357 | //
// RFTimer.swift
//
// Copyright (c) 2014 Ryan Fowler
//
// 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
public class RFTimer {
//declare RFTimer properties
var startTime: NSDate?
var tagName: String
var timer = NSTimer()
var intervals = 0
var inTimer = false
var delegate: RFTimerDelegate?
let notifCenter = NSNotificationCenter.defaultCenter()
/**
Start the timer
*/
public func start() {
if !inTimer {
startTime = NSDate()
delegate?.timerStatusUpdated(self, isOn: true)
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerFireMethod", userInfo: nil, repeats: true)
if let err = SD.executeChange("INSERT INTO RFTimerTemp (StartingTime, Tag, Singleton) VALUES (?, ?, 0)", withArgs: [startTime!, tagName]) {
println("Error inserting item to RFTimerTemp")
}
intervals = 0
inTimer = true
println("Timer started")
}
}
/**
Stop the timer and save it in the database
*/
public func stopAndSave() {
if inTimer {
timer.invalidate()
delegate?.timerStatusUpdated(self, isOn: false)
//insert the new timer event
if let err = SD.executeChange("INSERT INTO RFTimer (StartingTime, EndingTime, Duration, Tag) VALUES (\(SD.escapeValue(startTime!)), \(SD.escapeValue(NSDate())), \(SD.escapeValue(Int(NSDate().timeIntervalSinceDate(startTime!)))), \(SD.escapeValue(tagName)))") {
println("Error inserting row into RFTimer")
}
//delete the temp timer
if let err = SD.executeChange("DELETE FROM RFTimerTemp") {
println("Error deleting row from RFTimerTemp")
}
inTimer = false
println("Timer stopped")
}
}
init(tag: String) {
//create RFTimerTemp table in the database if it does not already exist
if let err = SD.executeChange("CREATE TABLE IF NOT EXISTS RFTimerTemp (ID INTEGER PRIMARY KEY AUTOINCREMENT, StartingTime DATE, Tag TEXT, Singleton INTEGER UNIQUE)") {
println("Error attempting to create RFTimerTemp table in the RFTimer database")
}
//create RFTimer table in the database if it does not already exist
if let err = SD.executeChange("CREATE TABLE IF NOT EXISTS RFTimer (ID INTEGER PRIMARY KEY AUTOINCREMENT, StartingTime DATE, EndingTime DATE, Duration INTEGER, Tag TEXT)") {
println("Error attempting to create the RTTimer table in the database")
}
//create index on Tag column if it does not already exist
if let err = SD.executeChange("CREATE INDEX IF NOT EXISTS TagIndex ON RFTimer (Tag)") {
println("Error attempting to create TagIndex on the RFTimer table")
}
//add the tag
tagName = tag
//add self as an observer
notifCenter.addObserver(self, selector: "wakeTimer", name: UIApplicationDidBecomeActiveNotification, object: nil)
notifCenter.addObserver(self, selector: "sleepTimer", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
notifCenter.removeObserver(self)
}
@objc private func timerFireMethod() {
++intervals
if intervals % 20 == 0 {
intervals = Int(NSDate().timeIntervalSinceDate(startTime!)) * 10
}
delegate?.timerFired(self, seconds: intervals/10 % 60, minutes: intervals/600 % 60, hours: intervals/36000)
}
@objc private func wakeTimer() {
let (result, err) = SD.executeQuery("SELECT * FROM RFTimerTemp")
if err != nil {
println("Query of RFTimerTemp failed")
} else {
if result.count > 0 {
println("Timer awoken from sleep")
if let start = result[0]["StartingTime"]?.asDate() {
if let tag = result[0]["Tag"]?.asString() {
intervals = Int(NSDate().timeIntervalSinceDate(start)) * 10
inTimer = true
startTime = start
tagName = tag
delegate?.timerFired(self, seconds: intervals/10 % 60, minutes: intervals/600 % 60, hours: intervals/36000)
delegate?.timerStatusUpdated(self, isOn: true)
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "timerFireMethod", userInfo: nil, repeats: true)
}
}
}
}
}
@objc private func sleepTimer() {
if inTimer {
println("Timer sent to sleep")
delegate?.timerStatusUpdated(self, isOn: true)
timer.invalidate()
}
}
}
public protocol RFTimerDelegate {
/**
The timer has fired
Anything that needs to be done when there is a change of time, such as update the UI, should be done in this function.
This functions gets called roughly 10 times a second.
*/
func timerFired(timer: RFTimer, seconds: Int, minutes: Int, hours: Int)
/**
The timer status has been updated
This function gets called when the timer has been turned on, woken from sleep, turned off, or sent to sleep.
*/
func timerStatusUpdated(timer: RFTimer, isOn: Bool)
}
extension SwiftData {
/**
Get all existing tags
:returns: An array of strings with all existing tags, or nil if there was an error
*/
public static func getAllTags() -> [String]? {
var (results, err) = SD.executeQuery("SELECT DISTINCT Tag FROM RFTimer")
if err != nil {
println("Error finding tables")
} else {
var tables = [String]()
for result in results {
if let tag = result["Tag"]?.asString() {
tables.append(tag)
}
}
return tables
}
return nil
}
}
| mit | c6aa45ddc1fd8eea025b464440fd43fc | 34.887805 | 272 | 0.600245 | 5.101942 | false | false | false | false |
chicio/RangeUISlider | Source/UI/Progress.swift | 1 | 2307 | //
// ProgressView.swift
// RangeUISlider
//
// Created by Fabrizio Duroni on 29/09/2017.
// 2017 Fabrizio Duroni.
//
import Foundation
import UIKit
/**
The `Progress` UI view RangeUIslider. It is a customized `UIView`.
It is a subclass of `Gradient` view.
*/
public class Progress: Gradient {
func setup(
leftAnchorView: UIView,
rightAnchorView: UIView,
properties: ProgressProperties
) -> [NSLayoutConstraint] {
accessibilityIdentifier = "Progress"
translatesAutoresizingMaskIntoConstraints = false
backgroundColor = properties.color
let views = ConstraintViews(target: self, related: superview)
return [
DimensionConstraintFactory.equalHeight(views: views),
PositionConstraintFactory.centerY(views: views),
MarginConstraintFactory.leadingTo(
attribute: properties.leftAnchorConstraintAttribute,
views: ConstraintViews(target: self, related: leftAnchorView),
value: 0.0
),
MarginConstraintFactory.trailingTo(
attribute: properties.rightAnchorConstraintAttribute,
views: ConstraintViews(target: self, related: rightAnchorView),
value: 0.0
)
]
}
func addBackground(image: UIImage, edgeInset: UIEdgeInsets, corners: CGFloat) {
let backgroundImageView = createBackgroundUsing(image: image, edgeInset: edgeInset, corners: corners)
let views = ConstraintViews(target: backgroundImageView, related: self)
addSubview(backgroundImageView)
NSLayoutConstraint.activate(MatchingMarginConstraintFactory.make(views: views))
}
private func createBackgroundUsing(image: UIImage, edgeInset: UIEdgeInsets, corners: CGFloat) -> UIView {
let backgroundResizableImage = image.resizableImage(withCapInsets: edgeInset)
let backgroundImageView = UIImageView(image: backgroundResizableImage)
backgroundImageView.translatesAutoresizingMaskIntoConstraints = false
backgroundImageView.layer.masksToBounds = corners > 0
backgroundImageView.layer.cornerRadius = corners
backgroundImageView.accessibilityIdentifier = "ProgressBackground"
return backgroundImageView
}
}
| mit | ba3b9fb019ba37f41008abfd8cd0463a | 38.775862 | 109 | 0.693541 | 5.626829 | false | false | false | false |
wangela/wittier | wittier/Views/TweetCell.swift | 1 | 8890 | //
// TweetCell.swift
// wittier
//
// Created by Angela Yu on 9/26/17.
// Copyright © 2017 Angela Yu. All rights reserved.
//
import UIKit
import AFNetworking
@objc protocol TweetCellDelegate {
@objc optional func replyButtonTapped(tweetCell: TweetCell)
@objc optional func profileButtonTapped(tweetCell: TweetCell)
}
extension Date {
var yearsFromNow: Int { return Calendar.current.dateComponents([.year],
from: self, to: Date()).year ?? 0 }
var monthsFromNow: Int { return Calendar.current.dateComponents([.month],
from: self, to: Date()).month ?? 0 }
var weeksFromNow: Int { return Calendar.current.dateComponents([.weekOfYear],
from: self, to: Date()).weekOfYear ?? 0 }
var daysFromNow: Int { return Calendar.current.dateComponents([.day],
from: self, to: Date()).day ?? 0 }
var hoursFromNow: Int { return Calendar.current.dateComponents([.hour],
from: self, to: Date()).hour ?? 0 }
var minutesFromNow: Int { return Calendar.current.dateComponents([.minute],
from: self, to: Date()).minute ?? 0 }
var secondsFromNow: Int { return Calendar.current.dateComponents([.second],
from: self, to: Date()).second ?? 0 }
var relativeTime: String {
if yearsFromNow > 0 { return "\(yearsFromNow) year" + (yearsFromNow > 1 ? "s" : "") + " ago" }
if monthsFromNow > 0 { return "\(monthsFromNow) month" + (monthsFromNow > 1 ? "s" : "") + " ago" }
if weeksFromNow > 0 { return "\(weeksFromNow) week" + (weeksFromNow > 1 ? "s" : "") + " ago" }
if daysFromNow > 0 { return daysFromNow == 1 ? "Yesterday" : "\(daysFromNow) days ago" }
if hoursFromNow > 0 { return "\(hoursFromNow) hour" + (hoursFromNow > 1 ? "s" : "") + " ago" }
if minutesFromNow > 0 { return "\(minutesFromNow) minute" + (minutesFromNow > 1 ? "s" : "") + " ago" }
if secondsFromNow > 0 { return secondsFromNow < 15 ? "Just now"
: "\(secondsFromNow) second" + (secondsFromNow > 1 ? "s" : "") + " ago" }
return ""
}
}
class TweetCell: UITableViewCell {
@IBOutlet weak var profileButton: UIButton!
@IBOutlet weak var displayNameLabel: UILabel!
@IBOutlet weak var screennameLabel: UILabel!
@IBOutlet weak var tweetLabel: UILabel!
@IBOutlet weak var timestampLabel: UILabel!
@IBOutlet weak var retweetButton: UIButton!
@IBOutlet weak var rtCountLabel: UILabel!
@IBOutlet weak var favoriteButton: UIButton!
@IBOutlet weak var favCountLabel: UILabel!
@IBOutlet weak var superContentView: UIView!
@IBOutlet weak var retweetView: UIView!
@IBOutlet weak var retweeterLabel: UILabel!
var delegate: TweetCellDelegate?
var retweeter: User?
var tweet: Tweet! {
didSet {
guard let user = tweet.user else {
print("nil user")
return
}
displayNameLabel.text = user.name
screennameLabel.text = user.screenname
tweetLabel.text = tweet.text
tweetLabel.sizeToFit()
if let profileURL = user.profileURL {
profileButton.setBackgroundImageFor(.normal, with: profileURL)
} else {
profileButton.setImage(nil, for: .normal)
}
// Build relative timestamp
if let timestamp = tweet.timestamp {
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM d HH:mm:ss Z y"
if let timestampDate = formatter.date(from: timestamp) {
let relativeTimestamp = timestampDate.relativeTime
timestampLabel.text = relativeTimestamp
}
}
showStats()
showRetweet()
}
}
override func awakeFromNib() {
super.awakeFromNib()
profileButton.layer.cornerRadius = profileButton.frame.size.width * 0.5
profileButton.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func showStats() {
// Show retweet stats
if tweet.retweeted {
retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: .normal)
} else {
retweetButton.setImage(#imageLiteral(resourceName: "retweet-aaa"), for: .normal)
}
rtCountLabel.text = "\(tweet.retweetCount)"
// Show favorite stats
if tweet.favorited {
favoriteButton.setImage(#imageLiteral(resourceName: "favorite-blk"), for: .normal)
} else {
favoriteButton.setImage(#imageLiteral(resourceName: "favorite-aaa"), for: .normal)
}
favCountLabel.text = "\(tweet.favoritesCount)"
}
func showRetweet() {
// Show retweet info if this is a retweet
if let retweetUser = retweeter {
if let retweeterName = retweetUser.name {
retweeterLabel.text = "\(retweeterName) Retweeted"
} else {
retweeterLabel.text = "Somebody Retweeted"
}
retweetView.isHidden = false
} else {
retweetView.isHidden = true
}
}
@IBAction func onProfileButton(_ sender: Any) {
if let _ = delegate {
delegate?.profileButtonTapped?(tweetCell: self)
}
}
@IBAction func onReplyButton(_ sender: Any) {
if let _ = delegate {
delegate?.replyButtonTapped?(tweetCell: self)
}
}
@IBAction func onRetweetButton(_ sender: Any) {
guard let tweetID = tweet.idNum else {
print("bad tweet ID")
return
}
let rtState = tweet.retweeted
let rtCount = tweet.retweetCount
if rtState {
TwitterClient.sharedInstance.retweet(retweetMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.retweeted = !rtState
self.tweet.retweetCount = rtCount - 1
self.retweetButton.setImage(#imageLiteral(resourceName: "retweet-aaa"), for: .normal)
self.rtCountLabel.text = "\(self.tweet.retweetCount)"
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
} else {
TwitterClient.sharedInstance.retweet(retweetMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.retweeted = !rtState
self.tweet.retweetCount = rtCount + 1
self.retweetButton.setImage(#imageLiteral(resourceName: "retweet"), for: .normal)
self.rtCountLabel.text = "\(self.tweet.retweetCount)"
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
}
}
@IBAction func onFavoriteButton(_ sender: Any) {
guard let tweetID = tweet.idNum else {
print("bad tweet ID")
return
}
let faveState = tweet.favorited
let faveCount = tweet.favoritesCount
if faveState {
TwitterClient.sharedInstance.fave(faveMe: false, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.favorited = !faveState
self.tweet.favoritesCount = faveCount - 1
self.favoriteButton.setImage(#imageLiteral(resourceName: "favorite-aaa"), for: .normal)
self.favCountLabel.text = "\(self.tweet.favoritesCount)"
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
} else {
TwitterClient.sharedInstance.fave(faveMe: true, id: tweetID, success: { (newTweet: Tweet) -> Void in
self.tweet.favorited = !faveState
self.tweet.favoritesCount = faveCount + 1
self.favoriteButton.setImage(#imageLiteral(resourceName: "favorite-blk"), for: .normal)
self.favCountLabel.text = "\(self.tweet.favoritesCount)"
}, failure: { (error: Error) -> Void in
print("\(error.localizedDescription)")
})
}
}
}
| mit | 822ab54bc3916a8536ffda0d294dbcfc | 41.735577 | 119 | 0.549668 | 4.949332 | false | false | false | false |
nsutanto/ios-VirtualTourist | VirtualTourist/Model/CoreData/CoreDataStack.swift | 1 | 5761 | //
// CoreDataStack.swift
//
//
// Created by Fernando Rodríguez Romero on 21/02/16.
// Copyright © 2016 udacity.com. All rights reserved.
//
import CoreData
// MARK: - CoreDataStack
struct CoreDataStack {
// MARK: Properties
private let model: NSManagedObjectModel
internal let coordinator: NSPersistentStoreCoordinator
private let modelURL: URL
internal let dbURL: URL
internal let persistingContext: NSManagedObjectContext
internal let backgroundContext: NSManagedObjectContext
let context: NSManagedObjectContext
// MARK: Initializers
init?(modelName: String) {
// Assumes the model is in the main bundle
guard let modelURL = Bundle.main.url(forResource: modelName, withExtension: "momd") else {
print("Unable to find \(modelName)in the main bundle")
return nil
}
self.modelURL = modelURL
// Try to create the model from the URL
guard let model = NSManagedObjectModel(contentsOf: modelURL) else {
print("unable to create a model from \(modelURL)")
return nil
}
self.model = model
// Create the store coordinator
coordinator = NSPersistentStoreCoordinator(managedObjectModel: model)
// Create a persistingContext (private queue) and a child one (main queue)
// create a context and add connect it to the coordinator
persistingContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
persistingContext.persistentStoreCoordinator = coordinator
context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = persistingContext
// Create a background context child of main context
backgroundContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
backgroundContext.parent = context
// Add a SQLite store located in the documents folder
let fm = FileManager.default
guard let docUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first else {
print("Unable to reach the documents folder")
return nil
}
self.dbURL = docUrl.appendingPathComponent("model.sqlite")
// Options for migration
let options = [NSInferMappingModelAutomaticallyOption: true,NSMigratePersistentStoresAutomaticallyOption: true]
do {
try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: options as [NSObject : AnyObject]?)
} catch {
print("unable to add store at \(dbURL)")
}
}
// MARK: Utils
func addStoreCoordinator(_ storeType: String, configuration: String?, storeURL: URL, options : [NSObject:AnyObject]?) throws {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: dbURL, options: nil)
}
}
// MARK: - CoreDataStack (Removing Data)
internal extension CoreDataStack {
func dropAllData() throws {
// delete all the objects in the db. This won't delete the files, it will
// just leave empty tables.
try coordinator.destroyPersistentStore(at: dbURL, ofType: NSSQLiteStoreType , options: nil)
try addStoreCoordinator(NSSQLiteStoreType, configuration: nil, storeURL: dbURL, options: nil)
}
}
// MARK: - CoreDataStack (Batch Processing in the Background)
extension CoreDataStack {
typealias Batch = (_ workerContext: NSManagedObjectContext) -> ()
func performBackgroundBatchOperation(_ batch: @escaping Batch) {
backgroundContext.perform() {
batch(self.backgroundContext)
// Save it to the parent context, so normal saving
// can work
do {
try self.backgroundContext.save()
} catch {
fatalError("Error while saving backgroundContext: \(error)")
}
}
}
}
// MARK: - CoreDataStack (Save Data)
extension CoreDataStack {
func save() {
// We call this synchronously, but it's a very fast
// operation (it doesn't hit the disk). We need to know
// when it ends so we can call the next save (on the persisting
// context). This last one might take some time and is done
// in a background queue
context.performAndWait() {
if self.context.hasChanges {
do {
try self.context.save()
} catch {
fatalError("Error while saving main context: \(error)")
}
// now we save in the background
self.persistingContext.perform() {
do {
try self.persistingContext.save()
} catch {
fatalError("Error while saving persisting context: \(error)")
}
}
}
}
}
func autoSave(_ delayInSeconds : Int) {
if delayInSeconds > 0 {
do {
try self.context.save()
//print("Autosaving")
} catch {
print("Error while autosaving")
}
let delayInNanoSeconds = UInt64(delayInSeconds) * NSEC_PER_SEC
let time = DispatchTime.now() + Double(Int64(delayInNanoSeconds)) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {
self.autoSave(delayInSeconds)
}
}
}
}
| mit | 3329c16a2c2dbaf05cccc15706703ee9 | 33.279762 | 136 | 0.600799 | 5.629521 | false | false | false | false |
ceecer1/open-muvr | ios/Lift/DemoSessionController.swift | 5 | 4166 | import Foundation
struct DataFile {
var path: String
var size: NSNumber
var name: String
}
class DemoSessionTableModel : NSObject, UITableViewDataSource {
private var dataFiles: [DataFile]
init(muscleGroupKeys: [String]) {
dataFiles = NSBundle.mainBundle().pathsForResourcesOfType(".dat", inDirectory: nil)
.map { p -> String in return p as String }
.filter { p in return !muscleGroupKeys.filter { k in return p.lastPathComponent.hasPrefix(k) }.isEmpty }
.map { path in
let attrs = NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil)!
let size: NSNumber = attrs[NSFileSize] as NSNumber
return DataFile(path: path, size: size, name: path.lastPathComponent)
}
super.init()
}
// MARK: UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataFiles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let data = dataFiles[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("default") as UITableViewCell
cell.textLabel!.text = data.name
let fmt = NSNumberFormatter()
fmt.numberStyle = NSNumberFormatterStyle.DecimalStyle
let sizeString = fmt.stringFromNumber(data.size)!
cell.detailTextLabel!.text = "\(sizeString) B"
return cell
}
func filePathAtIndexPath(indexPath: NSIndexPath) -> String? {
return dataFiles[indexPath.row].path
}
}
class DemoSessionController : UIViewController, UITableViewDelegate, ExerciseSessionSettable {
@IBOutlet var tableView: UITableView!
@IBOutlet var stopSessionButton: UIBarButtonItem!
private var tableModel: DemoSessionTableModel?
private var session: ExerciseSession?
private var timer: NSTimer?
private var startTime: NSDate?
// MARK: main
override func viewWillDisappear(animated: Bool) {
timer!.invalidate()
navigationItem.prompt = nil
session?.end(const(()))
}
@IBAction
func stopSession() {
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Really?"
stopSessionButton.tag = 3
} else {
navigationItem.prompt = nil
navigationController!.popToRootViewControllerAnimated(true)
}
}
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = tableModel!
stopSessionButton.title = "Stop"
stopSessionButton.tag = 0
startTime = NSDate()
tabBarController?.tabBar.hidden = true
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "tick", userInfo: nil, repeats: true)
}
func tick() {
let elapsed = Int(NSDate().timeIntervalSinceDate(self.startTime!))
let minutes: Int = elapsed / 60
let seconds: Int = elapsed - minutes * 60
navigationItem.prompt = NSString(format: "Elapsed %d:%02d", minutes, seconds)
stopSessionButton.tag -= 1
if stopSessionButton.tag < 0 {
stopSessionButton.title = "Stop"
}
}
// MARK: ExerciseSessionSettable
func setExerciseSession(session: ExerciseSession) {
self.session = session
tableModel = DemoSessionTableModel(muscleGroupKeys: session.props.muscleGroupKeys)
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
fatalError("This needs work")
// let path = tableModel!.filePathAtIndexPath(indexPath)
// let data = NSFileManager.defaultManager().contentsAtPath(path!)!
// let mp = MutableMultiPacket().append(DeviceInfo.Location.Wrist, data: data)
// session?.submitData(mp, const(()))
// tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
} | apache-2.0 | 98975de7440305b9eea2497b3cb65a89 | 34.922414 | 119 | 0.654345 | 5.200999 | false | false | false | false |
swiftsanyue/TestKitchen | TestKitchen/TestKitchen/classes/ingredient(食材)/recommend(推荐)/main(主要模块)/foodCourse(食材课程)/view/FCVideoCell.swift | 1 | 1411 | //
// FCVideoCell.swift
// TestKitchen
//
// Created by ZL on 16/11/4.
// Copyright © 2016年 zl. All rights reserved.
//
import UIKit
class FCVideoCell: UITableViewCell {
//播放视频
var playClosure:(String-> Void)?
//显示数据
var cellModel: FoodCourseSerial? {
didSet{
if cellModel != nil {
showData()
}
}
}
func showData() {
//图片
let url = NSURL(string: (cellModel?.course_image)!)
bgImgeView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
//文字
numLabel.text = "\(cellModel!.video_watchcount!)人做过"
numLabel.textColor = UIColor.whiteColor()
}
@IBOutlet weak var bgImgeView: UIImageView!
@IBOutlet weak var numLabel: UILabel!
@IBAction func playBtn(sender: UIButton) {
if cellModel?.course_video != nil && playClosure != nil {
playClosure!((cellModel?.course_video)!)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 27b69cbaeff9722c8de283737c9e6943 | 21.590164 | 155 | 0.571118 | 4.655405 | false | false | false | false |
HJliu1123/LearningNotes-LHJ | April/swift基础.playground/Pages/集合类型.xcplaygroundpage/Contents.swift | 1 | 2607 | //: [Previous](@previous)
import Foundation
var str = "Hello, playground"
//: [Next](@next)
/*
数组
*/
var arr : Array<String>
arr = ["akf", "afhu"]
arr.insert("skf", atIndex: 1)
arr.removeAtIndex(1)
//删除前面一个
arr.removeFirst(1)
var array : Array<Int> = Array<Int>()
array.append(10)
var array1 = Array<Int>()
array1.append(100)
var array2 : [Int] = [3,5,6,3]
var array3 = [4,2,3]
var array4 = [String]()
array4.append("dlfk")
var shopList = ["泡面","牙膏"]
shopList += ["香烟"]
shopList.insert("饮料", atIndex: 1)
shopList.append("零食")
//var str1 = shopList.removeLast()
//
//shopList
//shopList.removeAtIndex(2)
//shopList
//var range = Range(start: 0, end: 2)
//shopList.removeRange(range)
//shopList
shopList[0] = "大米"
for shopping in shopList {
print(shopping)
}
for var i = 0; i < shopList.count; i++ {
print("第\(i)个位置的元素是\(shopList[i])")
}
//二维数组
let n = 9
var nine = [[Int]](count: n, repeatedValue: [Int](count: n, repeatedValue: 0))
assert(n % 2 != 0,"n必须是奇数")
var row = 0
var col = n / 2
for var i = 1; i <= n * n; i++ {
nine[row][col] = i
row--
col++
if row < 0 && col >= n {
row += 2
col--
} else if row < 0 {
row = n - 1
} else if col >= n {
col = 0
} else if nine[row][col] != 0 {
row += 2
col--
}
}
nine
//字典
var dict : Dictionary<String, Int> = Dictionary<String, Int>()
var dict2 = Dictionary<String, Int>()
var dict3 = [String : Int]()
dict3["sdk"] = 100
var airports : [String : String] = ["PEK":"北京首都机场","CAN":"广州白云机场"]
var airports2 : Dictionary<String,String> = ["sha":"上海"]
airports["SHA2"] = ""
airports.updateValue("上海虹桥机场", forKey: "SHA2")
airports2.removeValueForKey("sha")
for (key, value) in airports {
print("key = \(key),value = \(value)")
}
//引用类型
var dict4 = NSDictionary()
//选举计数
let ballot = ["shasha","lili","zhangsan","lishi","shasha","lili","shasha","lishi","shasha","zhangsan","lishi","lili"]
var vote = [String : Int]()
for name in ballot {
if let cnt = vote[name] {
vote[name] = cnt + 1
} else {
vote[name] = 1
}
}
vote
/*
*set集合
*/
var set1 : Set<String> = ["rock","classic","jazz","hip hop"]
set1.insert("afds")
if let str = set1.remove("afds") {
print("suc")
} else {
print("fail")
}
set1.contains("rock")
//遍历
for str in set1 {
print(str)
}
var sortArr : Array<String> = set1.sort()
for str in set1.sort() {
print(str)
}
| apache-2.0 | edeb978d6cfe8f93066144448190a141 | 13.331395 | 117 | 0.573631 | 2.760358 | false | false | false | false |
arvedviehweger/swift | test/Compatibility/tuple_arguments.swift | 1 | 39709 | // RUN: %target-typecheck-verify-swift -swift-version 3
// Tests for tuple argument behavior in Swift 3, which was broken.
// The Swift 4 test is in test/Constraints/tuple_arguments.swift.
// Key:
// - "Crashes in actual Swift 3" -- snippets which crashed in Swift 3.0.1.
// These don't have well-defined semantics in Swift 3 mode and don't
// matter for source compatibility purposes.
//
// - "Does not diagnose in Swift 3 mode" -- snippets which failed to typecheck
// in Swift 3.0.1, but now typecheck. This is fine.
//
// - "Diagnoses in Swift 3 mode" -- snippets which typechecked in Swift 3.0.1,
// but now fail to typecheck. These are bugs in Swift 3 mode that should be
// fixed.
//
// - "Crashes in Swift 3 mode" -- snippets which did not crash Swift 3.0.1,
// but now crash. These are bugs in Swift 3 mode that should be fixed.
func concrete(_ x: Int) {}
func concreteLabeled(x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
do {
concrete(3)
concrete((3))
concreteLabeled(x: 3)
concreteLabeled(x: (3))
concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}}
concreteTwo(3, 4)
concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(3, 4) // expected-error {{extra argument in call}}
concreteTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b))
concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
concreteTuple(a, b)
concreteTuple((a, b))
concreteTuple(d)
}
do {
var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var c = (3) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
concrete(a)
concrete((a))
concrete(c)
concreteTwo(a, b)
concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
concreteTuple(a, b) // expected-error {{extra argument in call}}
concreteTuple((a, b))
concreteTuple(d)
}
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
do {
generic(3)
generic(3, 4)
generic((3))
generic((3, 4))
genericLabeled(x: 3)
genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
genericLabeled(x: (3))
genericLabeled(x: (3, 4))
genericTwo(3, 4)
genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(3, 4) // expected-error {{extra argument in call}}
genericTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
generic(a)
generic(a, b)
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{extra argument in call}}
genericTuple((a, b))
genericTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
generic(a)
// generic(a, b) // Crashes in actual Swift 3
generic((a))
generic(c)
generic((a, b))
generic(d)
genericTwo(a, b)
genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
genericTuple(a, b) // expected-error {{extra argument in call}}
genericTuple((a, b))
genericTuple(d)
}
var function: (Int) -> ()
var functionTwo: (Int, Int) -> () // expected-note 3 {{'functionTwo' declared here}}
var functionTuple: ((Int, Int)) -> ()
do {
function(3)
function((3))
functionTwo(3, 4)
functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(3, 4) // expected-error {{extra argument in call}}
functionTuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (3)
let d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b))
functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
functionTuple(a, b)
functionTuple((a, b))
functionTuple(d)
}
do {
var a = 3
var b = 4
var c = (3)
var d = (a, b)
function(a)
function((a))
function(c)
functionTwo(a, b)
functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
functionTuple(a, b) // expected-error {{extra argument in call}}
functionTuple((a, b))
functionTuple(d)
}
struct Concrete {}
extension Concrete {
func concrete(_ x: Int) {}
func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'concreteTwo' declared here}}
func concreteTuple(_ x: (Int, Int)) {}
}
do {
let s = Concrete()
s.concrete(3)
s.concrete((3))
s.concreteTwo(3, 4)
s.concreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(3, 4) // expected-error {{extra argument in call}}
s.concreteTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b))
s.concreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.concreteTuple(a, b)
s.concreteTuple((a, b))
s.concreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.concrete(a)
s.concrete((a))
s.concrete(c)
s.concreteTwo(a, b)
s.concreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.concreteTuple(a, b) // expected-error {{extra argument in call}}
s.concreteTuple((a, b))
s.concreteTuple(d)
}
extension Concrete {
func generic<T>(_ x: T) {}
func genericLabeled<T>(x: T) {}
func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}}
func genericTuple<T, U>(_ x: (T, U)) {}
}
do {
let s = Concrete()
s.generic(3)
s.generic(3, 4)
s.generic((3))
s.generic((3, 4))
s.genericLabeled(x: 3)
s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.genericLabeled(x: (3))
s.genericLabeled(x: (3, 4))
s.genericTwo(3, 4)
s.genericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3, 4) // expected-error {{extra argument in call}}
s.genericTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.generic(a)
s.generic(a, b)
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{extra argument in call}}
s.genericTuple((a, b))
s.genericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.generic(a)
// s.generic(a, b) // Crashes in actual Swift 3
s.generic((a))
s.generic((a, b))
s.generic(d)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{extra argument in call}}
s.genericTuple((a, b))
s.genericTuple(d)
}
extension Concrete {
mutating func mutatingConcrete(_ x: Int) {}
mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 3 {{'mutatingConcreteTwo' declared here}}
mutating func mutatingConcreteTuple(_ x: (Int, Int)) {}
}
do {
var s = Concrete()
s.mutatingConcrete(3)
s.mutatingConcrete((3))
s.mutatingConcreteTwo(3, 4)
s.mutatingConcreteTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(3, 4) // expected-error {{extra argument in call}}
s.mutatingConcreteTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b))
s.mutatingConcreteTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.mutatingConcreteTuple(a, b)
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingConcrete(a)
s.mutatingConcrete((a))
s.mutatingConcrete(c)
s.mutatingConcreteTwo(a, b)
s.mutatingConcreteTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingConcreteTuple(a, b) // expected-error {{extra argument in call}}
s.mutatingConcreteTuple((a, b))
s.mutatingConcreteTuple(d)
}
extension Concrete {
mutating func mutatingGeneric<T>(_ x: T) {}
mutating func mutatingGenericLabeled<T>(x: T) {}
mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {}
}
do {
var s = Concrete()
s.mutatingGeneric(3)
s.mutatingGeneric(3, 4)
s.mutatingGeneric((3))
s.mutatingGeneric((3, 4))
s.mutatingGenericLabeled(x: 3)
s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericLabeled(x: (3))
s.mutatingGenericLabeled(x: (3, 4))
s.mutatingGenericTwo(3, 4)
s.mutatingGenericTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3, 4) // expected-error {{extra argument in call}}
s.mutatingGenericTuple((3, 4))
}
do {
var s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric(a, b)
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.mutatingGeneric(a)
// s.mutatingGeneric(a, b) // Crashes in actual Swift 3
s.mutatingGeneric((a))
s.mutatingGeneric((a, b))
s.mutatingGeneric(d)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}}
s.mutatingGenericTuple((a, b))
s.mutatingGenericTuple(d)
}
extension Concrete {
var function: (Int) -> () { return concrete }
var functionTwo: (Int, Int) -> () { return concreteTwo }
var functionTuple: ((Int, Int)) -> () { return concreteTuple }
}
do {
let s = Concrete()
s.function(3)
s.function((3))
s.functionTwo(3, 4)
s.functionTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(3, 4) // expected-error {{extra argument in call}}
s.functionTuple((3, 4))
}
do {
let s = Concrete()
let a = 3
let b = 4
let c = (3)
let d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b))
s.functionTwo(d) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
s.functionTuple(a, b)
s.functionTuple((a, b))
s.functionTuple(d)
}
do {
var s = Concrete()
var a = 3
var b = 4
var c = (3)
var d = (a, b)
s.function(a)
s.function((a))
s.function(c)
s.functionTwo(a, b)
s.functionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.functionTwo(d) // expected-error {{missing argument for parameter #2 in call}}
s.functionTuple(a, b) // expected-error {{extra argument in call}}
s.functionTuple((a, b))
s.functionTuple(d)
}
struct InitTwo {
init(_ x: Int, _ y: Int) {} // expected-note 3 {{'init' declared here}}
}
struct InitTuple {
init(_ x: (Int, Int)) {}
}
struct InitLabeledTuple {
init(x: (Int, Int)) {}
}
do {
_ = InitTwo(3, 4)
_ = InitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(3, 4) // expected-error {{extra argument in call}}
_ = InitTuple((3, 4))
_ = InitLabeledTuple(x: 3, 4) // expected-error {{extra argument in call}}
_ = InitLabeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = InitTwo(a, b)
_ = InitTwo((a, b))
_ = InitTwo(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = InitTuple(a, b)
_ = InitTuple((a, b))
_ = InitTuple(c)
}
do {
var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var c = (a, b) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}}
_ = InitTwo(a, b)
_ = InitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = InitTuple(a, b) // expected-error {{extra argument in call}}
_ = InitTuple((a, b))
_ = InitTuple(c)
}
struct SubscriptTwo {
subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 3 {{'subscript' declared here}}
}
struct SubscriptTuple {
subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } }
}
struct SubscriptLabeledTuple {
subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } }
}
do {
let s1 = SubscriptTwo()
_ = s1[3, 4]
_ = s1[(3, 4)] // expected-error {{missing argument for parameter #2 in call}}
let s2 = SubscriptTuple()
_ = s2[3, 4] // expected-error {{extra argument in call}}
_ = s2[(3, 4)]
let s3 = SubscriptLabeledTuple()
_ = s3[x: 3, 4] // expected-error {{extra argument in call}}
_ = s3[x: (3, 4)]
}
do {
let a = 3
let b = 4
let d = (a, b)
let s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)]
_ = s1[d]
let s2 = SubscriptTuple()
_ = s2[a, b]
_ = s2[(a, b)]
_ = s2[d]
}
do {
var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = SubscriptTwo()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{missing argument for parameter #2 in call}}
_ = s1[d] // expected-error {{missing argument for parameter #2 in call}}
var s2 = SubscriptTuple()
_ = s2[a, b] // expected-error {{extra argument in call}}}
_ = s2[(a, b)]
_ = s2[d]
}
enum Enum {
case two(Int, Int) // expected-note 3 {{'two' declared here}}
case tuple((Int, Int))
case labeledTuple(x: (Int, Int))
}
do {
_ = Enum.two(3, 4)
_ = Enum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(3, 4) // expected-error {{extra argument in call}}
_ = Enum.tuple((3, 4))
_ = Enum.labeledTuple(x: 3, 4) // expected-error {{extra argument in call}}
_ = Enum.labeledTuple(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b))
_ = Enum.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = Enum.tuple(a, b)
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = Enum.two(a, b)
_ = Enum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = Enum.tuple(a, b) // expected-error {{extra argument in call}}
_ = Enum.tuple((a, b))
_ = Enum.tuple(c)
}
struct Generic<T> {}
extension Generic {
func generic(_ x: T) {}
func genericLabeled(x: T) {}
func genericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'genericTwo' declared here}}
func genericTuple(_ x: (T, T)) {}
}
do {
let s = Generic<Double>()
s.generic(3.0)
s.generic((3.0))
s.genericLabeled(x: 3.0)
s.genericLabeled(x: (3.0))
s.genericTwo(3.0, 4.0)
s.genericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(3.0, 4.0) // expected-error {{extra argument in call}}
s.genericTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.generic((3.0, 4.0))
sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.genericLabeled(x: (3.0, 4.0))
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b))
s.genericTuple(a, b)
s.genericTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b)
sTwo.generic((a, b))
sTwo.generic(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.generic(a)
s.generic((a))
s.generic(c)
s.genericTwo(a, b)
s.genericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericTuple(a, b) // expected-error {{extra argument in call}}
s.genericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.generic(a, b) // expected-error {{extra argument in call}}
sTwo.generic((a, b))
sTwo.generic(d)
}
extension Generic {
mutating func mutatingGeneric(_ x: T) {}
mutating func mutatingGenericLabeled(x: T) {}
mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 2 {{'mutatingGenericTwo' declared here}}
mutating func mutatingGenericTuple(_ x: (T, T)) {}
}
do {
var s = Generic<Double>()
s.mutatingGeneric(3.0)
s.mutatingGeneric((3.0))
s.mutatingGenericLabeled(x: 3.0)
s.mutatingGenericLabeled(x: (3.0))
s.mutatingGenericTwo(3.0, 4.0)
s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(3.0, 4.0) // expected-error {{extra argument in call}}
s.mutatingGenericTuple((3.0, 4.0))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.mutatingGeneric((3.0, 4.0))
sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.mutatingGenericLabeled(x: (3.0, 4.0))
}
do {
var s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b))
s.mutatingGenericTuple(a, b)
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b)
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.mutatingGeneric(a)
s.mutatingGeneric((a))
s.mutatingGeneric(c)
s.mutatingGenericTwo(a, b)
s.mutatingGenericTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.mutatingGenericTuple(a, b) // expected-error {{extra argument in call}}
s.mutatingGenericTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.mutatingGeneric(a, b) // expected-error {{extra argument in call}}
sTwo.mutatingGeneric((a, b))
sTwo.mutatingGeneric(d)
}
extension Generic {
var genericFunction: (T) -> () { return generic }
var genericFunctionTwo: (T, T) -> () { return genericTwo }
var genericFunctionTuple: ((T, T)) -> () { return genericTuple }
}
do {
let s = Generic<Double>()
s.genericFunction(3.0)
s.genericFunction((3.0))
s.genericFunctionTwo(3.0, 4.0)
s.genericFunctionTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(3.0, 4.0) // expected-error {{extra argument in call}}
s.genericFunctionTuple((3.0, 4.0))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(3.0, 4.0)
sTwo.genericFunction((3.0, 4.0)) // Does not diagnose in Swift 3 mode
}
do {
let s = Generic<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b))
s.genericFunctionTuple(a, b)
s.genericFunctionTuple((a, b))
let sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b)
sTwo.genericFunction((a, b))
sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode
}
do {
var s = Generic<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.genericFunction(a)
s.genericFunction((a))
s.genericFunction(c)
s.genericFunctionTwo(a, b)
s.genericFunctionTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.genericFunctionTuple(a, b) // expected-error {{extra argument in call}}
s.genericFunctionTuple((a, b))
var sTwo = Generic<(Double, Double)>()
sTwo.genericFunction(a, b)
sTwo.genericFunction((a, b)) // Does not diagnose in Swift 3 mode
sTwo.genericFunction(d) // Does not diagnose in Swift 3 mode
}
struct GenericInit<T> { // expected-note 2 {{'T' declared as parameter to type 'GenericInit'}}
init(_ x: T) {}
}
struct GenericInitLabeled<T> {
init(x: T) {}
}
struct GenericInitTwo<T> {
init(_ x: T, _ y: T) {} // expected-note 8 {{'init' declared here}}
}
struct GenericInitTuple<T> {
init(_ x: (T, T)) {}
}
struct GenericInitLabeledTuple<T> {
init(x: (T, T)) {}
}
do {
_ = GenericInit(3, 4)
_ = GenericInit((3, 4))
_ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled(x: (3, 4))
_ = GenericInitTwo(3, 4)
_ = GenericInitTwo((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(3, 4) // expected-error {{extra argument in call}}
_ = GenericInitTuple((3, 4))
_ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeledTuple(x: (3, 4))
}
do {
_ = GenericInit<(Int, Int)>(3, 4)
_ = GenericInit<(Int, Int)>((3, 4)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeled<(Int, Int)>(x: (3, 4))
_ = GenericInitTwo<Int>(3, 4)
_ = GenericInitTwo<Int>((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(3, 4) // expected-error {{extra argument in call}}
_ = GenericInitTuple<Int>((3, 4))
_ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericInitLabeledTuple<Int>(x: (3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit(a, b)
_ = GenericInit((a, b))
_ = GenericInit(c)
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{extra argument in call}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericInit<(Int, Int)>(a, b)
_ = GenericInit<(Int, Int)>((a, b))
_ = GenericInit<(Int, Int)>(c)
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericInitTwo<Int>(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = GenericInitTuple<Int>(a, b) // Does not diagnose in Swift 3 mode
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
_ = GenericInit(a, b) // expected-error {{extra argument in call}}
_ = GenericInit((a, b)) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}}
_ = GenericInit(c) // expected-error {{generic parameter 'T' could not be inferred}} // expected-note {{explicitly specify the generic arguments to fix this issue}}
_ = GenericInitTwo(a, b)
_ = GenericInitTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple(a, b) // expected-error {{extra argument in call}}
_ = GenericInitTuple((a, b))
_ = GenericInitTuple(c)
}
do {
var a = 3 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var c = (a, b) // expected-warning {{variable 'c' was never mutated; consider changing to 'let' constant}}
// _ = GenericInit<(Int, Int)>(a, b) // Crashes in Swift 3
_ = GenericInit<(Int, Int)>((a, b)) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInit<(Int, Int)>(c) // expected-error {{expression type 'GenericInit<(Int, Int)>' is ambiguous without more context}}
_ = GenericInitTwo<Int>(a, b)
_ = GenericInitTwo<Int>((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTwo<Int>(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericInitTuple<Int>(a, b) // expected-error {{extra argument in call}}
_ = GenericInitTuple<Int>((a, b))
_ = GenericInitTuple<Int>(c)
}
struct GenericSubscript<T> {
subscript(_ x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeled<T> {
subscript(x x: T) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptTwo<T> {
subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note {{'subscript' declared here}}
}
struct GenericSubscriptTuple<T> {
subscript(_ x: (T, T)) -> Int { get { return 0 } set { } }
}
struct GenericSubscriptLabeledTuple<T> {
subscript(x x: (T, T)) -> Int { get { return 0 } set { } }
}
do {
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[3.0, 4.0]
_ = s1[(3.0, 4.0)] // expected-error {{expression type 'Int' is ambiguous without more context}}
let s1a = GenericSubscriptLabeled<(Double, Double)>()
_ = s1a [x: 3.0, 4.0] // expected-error {{extra argument in call}}
_ = s1a [x: (3.0, 4.0)]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[3.0, 4.0]
_ = s2[(3.0, 4.0)] // expected-error {{missing argument for parameter #2 in call}}
let s3 = GenericSubscriptTuple<Double>()
_ = s3[3.0, 4.0] // expected-error {{extra argument in call}}
_ = s3[(3.0, 4.0)]
let s3a = GenericSubscriptLabeledTuple<Double>()
_ = s3a[x: 3.0, 4.0] // expected-error {{extra argument in call}}
_ = s3a[x: (3.0, 4.0)]
}
do {
let a = 3.0
let b = 4.0
let d = (a, b)
let s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b]
_ = s1[(a, b)]
_ = s1[d]
let s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // Does not diagnose in Swift 3 mode
_ = s2[d] // Does not diagnose in Swift 3 mode
let s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // Does not diagnose in Swift 3 mode
_ = s3[(a, b)]
_ = s3[d]
}
do {
var a = 3.0 // expected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}}
var b = 4.0 // expected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}}
var d = (a, b) // expected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}}
var s1 = GenericSubscript<(Double, Double)>()
_ = s1[a, b]
_ = s1[(a, b)] // expected-error {{expression type '@lvalue Int' is ambiguous without more context}}
_ = s1[d] // expected-error {{expression type '@lvalue Int' is ambiguous without more context}}
var s2 = GenericSubscriptTwo<Double>()
_ = s2[a, b]
_ = s2[(a, b)] // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type '(_, _)'}}
_ = s2[d] // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type '(_, _)'}}
var s3 = GenericSubscriptTuple<Double>()
_ = s3[a, b] // expected-error {{extra argument in call}}
_ = s3[(a, b)]
_ = s3[d]
}
enum GenericEnum<T> {
case one(T)
case labeled(x: T)
case two(T, T) // expected-note 8 {{'two' declared here}}
case tuple((T, T))
}
do {
_ = GenericEnum.one(3, 4)
_ = GenericEnum.one((3, 4))
_ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled(x: (3, 4))
_ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum.two(3, 4)
_ = GenericEnum.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum.tuple((3, 4))
}
do {
_ = GenericEnum<(Int, Int)>.one(3, 4)
_ = GenericEnum<(Int, Int)>.one((3, 4)) // Does not diagnose in Swift 3 mode
_ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum<(Int, Int)>.labeled(x: (3, 4))
_ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}}
_ = GenericEnum<Int>.two(3, 4)
_ = GenericEnum<Int>.two((3, 4)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(3, 4) // expected-error {{extra argument in call}}
_ = GenericEnum<Int>.tuple((3, 4))
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum.one(a, b)
_ = GenericEnum.one((a, b))
_ = GenericEnum.one(c)
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
let a = 3
let b = 4
let c = (a, b)
_ = GenericEnum<(Int, Int)>.one(a, b)
_ = GenericEnum<(Int, Int)>.one((a, b))
_ = GenericEnum<(Int, Int)>.one(c)
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b))
_ = GenericEnum<Int>.two(c) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
_ = GenericEnum<Int>.tuple(a, b)
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
// _ = GenericEnum.one(a, b) // Crashes in actual Swift 3
_ = GenericEnum.one((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericEnum.one(c) // Does not diagnose in Swift 3 mode
_ = GenericEnum.two(a, b)
_ = GenericEnum.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum.tuple(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum.tuple((a, b))
_ = GenericEnum.tuple(c)
}
do {
var a = 3
var b = 4
var c = (a, b)
// _ = GenericEnum<(Int, Int)>.one(a, b) // Crashes in actual Swift 3
_ = GenericEnum<(Int, Int)>.one((a, b)) // Does not diagnose in Swift 3 mode
_ = GenericEnum<(Int, Int)>.one(c) // Does not diagnose in Swift 3 mode
_ = GenericEnum<Int>.two(a, b)
_ = GenericEnum<Int>.two((a, b)) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.two(c) // expected-error {{missing argument for parameter #2 in call}}
_ = GenericEnum<Int>.tuple(a, b) // expected-error {{extra argument in call}}
_ = GenericEnum<Int>.tuple((a, b))
_ = GenericEnum<Int>.tuple(c)
}
protocol Protocol {
associatedtype Element
}
extension Protocol {
func requirement(_ x: Element) {}
func requirementLabeled(x: Element) {}
func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 2 {{'requirementTwo' declared here}}
func requirementTuple(_ x: (Element, Element)) {}
}
struct GenericConforms<T> : Protocol {
typealias Element = T
}
do {
let s = GenericConforms<Double>()
s.requirement(3.0)
s.requirement((3.0))
s.requirementLabeled(x: 3.0)
s.requirementLabeled(x: (3.0))
s.requirementTwo(3.0, 4.0)
s.requirementTwo((3.0, 4.0)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(3.0, 4.0) // expected-error {{extra argument in call}}
s.requirementTuple((3.0, 4.0))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.requirement((3.0, 4.0))
sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{extra argument in call}}
sTwo.requirementLabeled(x: (3.0, 4.0))
}
do {
let s = GenericConforms<Double>()
let a = 3.0
let b = 4.0
let c = (3.0)
let d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // Does not diagnose in Swift 3 mode
s.requirementTuple(a, b) // Does not diagnose in Swift 3 mode
s.requirementTuple((a, b))
let sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b)
sTwo.requirement((a, b))
sTwo.requirement(d)
}
do {
var s = GenericConforms<Double>()
var a = 3.0
var b = 4.0
var c = (3.0)
var d = (a, b)
s.requirement(a)
s.requirement((a))
s.requirement(c)
s.requirementTwo(a, b)
s.requirementTwo((a, b)) // expected-error {{missing argument for parameter #2 in call}}
s.requirementTuple(a, b) // expected-error {{extra argument in call}}
s.requirementTuple((a, b))
var sTwo = GenericConforms<(Double, Double)>()
sTwo.requirement(a, b) // expected-error {{extra argument in call}}
sTwo.requirement((a, b))
sTwo.requirement(d)
}
extension Protocol {
func takesClosure(_ fn: (Element) -> ()) {}
func takesClosureTwo(_ fn: (Element, Element) -> ()) {}
func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {}
}
do {
let s = GenericConforms<Double>()
s.takesClosure({ _ = $0 })
s.takesClosure({ x in })
s.takesClosure({ (x: Double) in })
s.takesClosureTwo({ _ = $0 })
s.takesClosureTwo({ x in })
s.takesClosureTwo({ (x: (Double, Double)) in })
s.takesClosureTwo({ _ = $0; _ = $1 })
s.takesClosureTwo({ (x, y) in })
s.takesClosureTwo({ (x: Double, y:Double) in })
s.takesClosureTuple({ _ = $0 })
s.takesClosureTuple({ x in })
s.takesClosureTuple({ (x: (Double, Double)) in })
s.takesClosureTuple({ _ = $0; _ = $1 })
s.takesClosureTuple({ (x, y) in })
s.takesClosureTuple({ (x: Double, y:Double) in })
let sTwo = GenericConforms<(Double, Double)>()
sTwo.takesClosure({ _ = $0 })
sTwo.takesClosure({ x in })
sTwo.takesClosure({ (x: (Double, Double)) in })
sTwo.takesClosure({ _ = $0; _ = $1 })
sTwo.takesClosure({ (x, y) in })
sTwo.takesClosure({ (x: Double, y: Double) in })
}
do {
let _: ((Int, Int)) -> () = { _ = $0 }
let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) }
let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) }
let _: ((Int, Int)) -> () = { _ = ($0, $1) }
let _: ((Int, Int)) -> () = { t, u in _ = (t, u) }
let _: (Int, Int) -> () = { _ = $0 }
let _: (Int, Int) -> () = { _ = ($0.0, $0.1) }
let _: (Int, Int) -> () = { t in _ = (t.0, t.1) }
let _: (Int, Int) -> () = { _ = ($0, $1) }
let _: (Int, Int) -> () = { t, u in _ = (t, u) }
}
// rdar://problem/28952837 - argument labels ignored when calling function
// with single 'Any' parameter
func takesAny(_: Any) {}
enum HasAnyCase {
case any(_: Any)
}
do {
let fn: (Any) -> () = { _ in }
fn(123)
fn(data: 123)
takesAny(123)
takesAny(data: 123)
_ = HasAnyCase.any(123)
_ = HasAnyCase.any(data: 123)
}
// rdar://problem/29739905 - protocol extension methods on Array had
// ParenType sugar stripped off the element type
typealias BoolPair = (Bool, Bool)
func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()],
f2: [(Bool, Bool) -> ()],
c: Bool) {
let p = (c, c)
f1.forEach { block in
block(p)
block((c, c))
block(c, c)
}
f2.forEach { block in
block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
block((c, c))
block(c, c)
}
f2.forEach { (block: ((Bool, Bool)) -> ()) in
block(p)
block((c, c))
block(c, c)
}
f2.forEach { (block: (Bool, Bool) -> ()) in
block(p) // expected-error {{passing 2 arguments to a callee as a single tuple value has been removed in Swift 3}}
block((c, c))
block(c, c)
}
}
// expected-error@+1 {{cannot create a single-element tuple with an element label}}
func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) {
// TODO: Error could be improved.
// expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}}
completion((didAdjust: true))
}
// SR-4378 -- FIXME -- this should type check, it used to work in Swift 3.0
final public class MutableProperty<Value> {
public init(_ initialValue: Value) {}
}
enum DataSourcePage<T> {
case notLoaded
}
let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: _, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}}
data: .notLoaded,
totalCount: 0
))
let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{cannot convert value of type 'MutableProperty<(data: DataSourcePage<_>, totalCount: Int)>' to specified type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>'}}
data: DataSourcePage.notLoaded,
totalCount: 0
))
let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty((
// expected-error@-1 {{expression type 'MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)>' is ambiguous without more context}}
data: DataSourcePage<Int>.notLoaded,
totalCount: 0
))
| apache-2.0 | bd868be933237abba0036588c962caa9 | 25.93962 | 201 | 0.628825 | 3.237851 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/SwiftSpreadsheet-master/Example/SwiftSpreadsheet/ViewController.swift | 1 | 7718 | //
// ViewController.swift
// SwiftSpreadsheet
//
// Created by Wojtek Kordylewski on 03/23/2017.
// Copyright (c) 2017 Wojtek Kordylewski. All rights reserved.
//
import UIKit
import SwiftSpreadsheet
class DefaultCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var infoLabel: UILabel!
}
class SpreadsheetCollectionReusableView: UICollectionReusableView {
@IBOutlet weak var infoLabel: UILabel!
}
class ViewController: UIViewController {
let defaultCellIdentifier = "DefaultCellIdentifier"
let defaultSupplementaryViewIdentifier = "DefaultSupplementaryViewIdentifier"
struct DecorationViewNames {
static let topLeft = "SpreadsheetTopLeftDecorationView"
static let topRight = "SpreadsheetTopRightDecorationView"
static let bottomLeft = "SpreadsheetBottomLeftDecorationView"
static let bottomRight = "SpreadsheetBottomRightDecorationView"
}
struct SupplementaryViewNames {
static let left = "SpreadsheetLeftRowView"
static let right = "SpreadsheetRightRowView"
static let top = "SpreadsheetTopColumnView"
static let bottom = "SpreadsheetBottomColumnView"
}
@IBOutlet weak var collectionView: UICollectionView!
let dataArray: [[Double]]
let numberFormatter = NumberFormatter()
let personCount = 30
let lightGreyColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
required init?(coder aDecoder: NSCoder) {
//Setting up demo data
var finalArray = [[Double]]()
for _ in 0 ..< self.personCount {
var subArray = [Double]()
for _ in 0 ..< 12 {
subArray.append(Double(arc4random() % 4000))
}
finalArray.append(subArray)
}
self.dataArray = finalArray
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
//DecorationView Nibs
let topLeftDecorationViewNib = UINib(nibName: DecorationViewNames.topLeft, bundle: nil)
let topRightDecorationViewNib = UINib(nibName: DecorationViewNames.topRight, bundle: nil)
let bottomLeftDecorationViewNib = UINib(nibName: DecorationViewNames.bottomLeft, bundle: nil)
let bottomRightDecorationViewNib = UINib(nibName: DecorationViewNames.bottomRight, bundle: nil)
//SupplementaryView Nibs
let topSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.top, bundle: nil)
let bottomSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.bottom, bundle: nil)
let leftSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.left, bundle: nil)
let rightSupplementaryViewNib = UINib(nibName: SupplementaryViewNames.right, bundle: nil)
//Setup Layout
let layout = SpreadsheetLayout(delegate: self,
topLeftDecorationViewNib: topLeftDecorationViewNib,
topRightDecorationViewNib: topRightDecorationViewNib,
bottomLeftDecorationViewNib: bottomLeftDecorationViewNib,
bottomRightDecorationViewNib: bottomRightDecorationViewNib)
//Default is true, set false here if you do not want some of these sides to remain sticky
layout.stickyLeftRowHeader = true
layout.stickyRightRowHeader = true
layout.stickyTopColumnHeader = true
layout.stickyBottomColumnFooter = true
self.collectionView.collectionViewLayout = layout
//Register Supplementary-Viewnibs for the given ViewKindTypes
self.collectionView.register(leftSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.leftRowHeadline.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier)
self.collectionView.register(rightSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.rightRowHeadline.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier)
self.collectionView.register(topSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.topColumnHeader.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier)
self.collectionView.register(bottomSupplementaryViewNib, forSupplementaryViewOfKind: SpreadsheetLayout.ViewKindType.bottomColumnFooter.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier)
}
}
extension ViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.dataArray.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataArray[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.defaultCellIdentifier, for: indexPath) as? DefaultCollectionViewCell else { fatalError("Invalid cell dequeued") }
let value = self.dataArray[indexPath.section][indexPath.item]
cell.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value))
cell.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
guard let viewKind = SpreadsheetLayout.ViewKindType(rawValue: kind) else { fatalError("View Kind not available for string: \(kind)") }
let supplementaryView = collectionView.dequeueReusableSupplementaryView(ofKind: viewKind.rawValue, withReuseIdentifier: self.defaultSupplementaryViewIdentifier, for: indexPath) as! SpreadsheetCollectionReusableView
switch viewKind {
case .leftRowHeadline:
supplementaryView.infoLabel.text = "Section \(indexPath.section)"
case .rightRowHeadline:
let value = self.dataArray[indexPath.section].reduce(0) { $0 + $1 }
supplementaryView.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value))
case .topColumnHeader:
supplementaryView.infoLabel.text = "Item \(indexPath.item)"
supplementaryView.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white
case .bottomColumnFooter:
let value = self.dataArray.map { $0[indexPath.item] }.reduce(0) { $0 + $1 }
supplementaryView.infoLabel.text = self.numberFormatter.string(from: NSNumber(value: value))
supplementaryView.backgroundColor = indexPath.item % 2 == 1 ? self.lightGreyColor : UIColor.white
default:
break
}
return supplementaryView
}
}
//MARK: - Spreadsheet Layout Delegate
extension ViewController: SpreadsheetLayoutDelegate {
func spreadsheet(layout: SpreadsheetLayout, heightForRowsInSection section: Int) -> CGFloat {
return 50
}
func widthsOfSideRowsInSpreadsheet(layout: SpreadsheetLayout) -> (left: CGFloat?, right: CGFloat?) {
return (120, 120)
}
func spreadsheet(layout: SpreadsheetLayout, widthForColumnAtIndex index: Int) -> CGFloat {
return 80
}
func heightsOfHeaderAndFooterColumnsInSpreadsheet(layout: SpreadsheetLayout) -> (headerHeight: CGFloat?, footerHeight: CGFloat?) {
return (70, 70)
}
}
| mit | ebb188fc18f8ba11fe750f8a228aae4c | 46.349693 | 222 | 0.70653 | 5.721275 | false | false | false | false |
xxxAIRINxxx/ARNModalTransition | ARNModalTransition/ARNModalTransition/ModalViewController.swift | 1 | 2169 | //
// ModalViewController.swift
// ARNModalTransition
//
// Created by xxxAIRINxxx on 2015/01/17.
// Copyright (c) 2015 xxxAIRINxxx. All rights reserved.
//
import UIKit
class ModalViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tapCloseButtonHandler : (ModalViewController -> Void)?
var tableView : UITableView = UITableView(frame: CGRectZero, style: .Plain)
let cellIdentifier : String = "Cell"
deinit {
print("deinit ModalViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.frame = self.view.bounds
self.tableView.dataSource = self
self.tableView.delegate = self
self.tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: self.cellIdentifier)
self.view.addSubview(self.tableView)
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Close", style: .Plain, target: self, action: #selector(ModalViewController.tapCloseButton))
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.whiteColor()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print("ModalViewController viewWillAppear")
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
print("ModalViewController viewWillDisappear")
}
func tapCloseButton() {
self.tapCloseButtonHandler?(self)
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 50
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(self.cellIdentifier, forIndexPath: indexPath)
return cell
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
| mit | 946b24cfa2de178a41eb1b347d6e0ee4 | 32.369231 | 164 | 0.697095 | 5.604651 | false | false | false | false |
jubinjacob19/Catapult | NetworkingDemo/AsyncOperation.swift | 1 | 1822 | //
// AsyncOperation.swift
// NetworkingDemo
//
// Created by Jubin Jacob on 25/01/16.
// Copyright © 2016 J. All rights reserved.
//
import UIKit
infix operator |> { }
func |> (operation1: NSOperation, operation2: NSOperation) {
operation2.addDependency(operation1)
}
protocol ChecksReachabliy {
var isReachable : Bool {get set}
}
class AsyncOperation: NSOperation,ChecksReachabliy {
var isReachable = true // is reset in the reachablity check operation completion block
override var asynchronous: Bool {
return true
}
override init() {
}
private var _executing: Bool = false
override var executing: Bool {
get {
return _executing
}
set {
if _executing != newValue {
willChangeValueForKey("isExecuting")
_executing = newValue
didChangeValueForKey("isExecuting")
}
}
}
private var _finished: Bool = false;
override var finished: Bool {
get {
return _finished
}
set {
if _finished != newValue {
willChangeValueForKey("isFinished")
_finished = newValue
didChangeValueForKey("isFinished")
}
}
}
func completeOperation () {
executing = false
finished = true
}
override func start()
{
if cancelled {
finished = true
return
}
executing = true
main()
}
override func cancel() {
super.cancel()
if(executing) {
self.completeOperation()
}
}
}
extension String {
var length: Int {
return characters.count
}
}
| mit | e8e5cc52a025973c2184d188f38c642f | 18.793478 | 90 | 0.52883 | 5.10084 | false | false | false | false |
mmrmmlrr/ExamMaster | Pods/ModelsTreeKit/ModelsTreeKit/Classes/Bubble/BubbleNotification.swift | 1 | 1014 | //
// BubbleNotification.swift
// ModelsTreeKit
//
// Created by aleksey on 27.02.16.
// Copyright © 2016 aleksey chernish. All rights reserved.
//
import Foundation
public protocol BubbleNotificationName {
static var domain: String { get }
var rawValue: String { get }
}
public func ==(lhs: BubbleNotificationName, rhs: BubbleNotificationName) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public struct BubbleNotification {
public var name: BubbleNotificationName
public var domain: String {
get {
return name.dynamicType.domain
}
}
public var object: Any?
public var hashValue: Int { return (name.rawValue.hashValue &+ name.rawValue.hashValue).hashValue }
public init(name: BubbleNotificationName, object: Any? = nil) {
self.name = name
self.object = object
}
}
extension BubbleNotification: Hashable, Equatable {
}
public func ==(a: BubbleNotification, b: BubbleNotification) -> Bool {
return a.name == b.name && a.domain == b.domain
} | mit | d59f7613e90500068d5ddfa8f324be34 | 21.043478 | 101 | 0.697927 | 4.003953 | false | false | false | false |
noppoMan/aws-sdk-swift | Sources/Soto/Services/Translate/Translate_Paginator.swift | 1 | 5973 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension Translate {
/// Provides a list of custom terminologies associated with your account.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTerminologiesPaginator<Result>(
_ input: ListTerminologiesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTerminologiesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTerminologies,
tokenKey: \ListTerminologiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTerminologiesPaginator(
_ input: ListTerminologiesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTerminologiesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTerminologies,
tokenKey: \ListTerminologiesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Gets a list of the batch translation jobs that you have submitted.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listTextTranslationJobsPaginator<Result>(
_ input: ListTextTranslationJobsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListTextTranslationJobsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listTextTranslationJobs,
tokenKey: \ListTextTranslationJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used flot logging
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listTextTranslationJobsPaginator(
_ input: ListTextTranslationJobsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListTextTranslationJobsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listTextTranslationJobs,
tokenKey: \ListTextTranslationJobsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension Translate.ListTerminologiesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Translate.ListTerminologiesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension Translate.ListTextTranslationJobsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> Translate.ListTextTranslationJobsRequest {
return .init(
filter: self.filter,
maxResults: self.maxResults,
nextToken: token
)
}
}
| apache-2.0 | 005c78a72df0f4cea0cfb3f990b258f6 | 41.06338 | 168 | 0.641051 | 5.244074 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/00952-swift-constraints-constraintgraph-gatherconstraints.swift | 65 | 643 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
class A = a: a<T {
}
case A.E
i> (A? = a
protocol B == "a() { }
enum A where f..a(a(x)
typealias d>(n: A: k.a("
var _ = A.E == b: Int
protocol P {
struct A {
}(b(Any) -> String {
if true as Boolean>(i("](B)
typealias f : d where H) + seq
func d
| apache-2.0 | 7be363f4e401effb6816f75de58231cc | 28.227273 | 79 | 0.674961 | 3.091346 | false | false | false | false |
IdeasOnCanvas/Callisto | Callisto/URLSession+synchronousTask.swift | 1 | 904 | //
// URLSession+synchronousTask.swift
// clangParser
//
// Created by Patrick Kladek on 21.04.17.
// Copyright © 2017 Patrick Kladek. All rights reserved.
//
import Foundation
extension URLSession {
func synchronousDataTask(with request: URLRequest) throws -> (data: Data?, response: HTTPURLResponse?) {
let semaphore = DispatchSemaphore(value: 0)
var responseData: Data?
var theResponse: URLResponse?
var theError: Error?
dataTask(with: request) { (data, response, error) -> Void in
responseData = data
theResponse = response
theError = error
semaphore.signal()
}.resume()
_ = semaphore.wait(timeout: .distantFuture)
if let error = theError {
throw error
}
return (data: responseData, response: theResponse as! HTTPURLResponse?)
}
}
| mit | 8295a934ec011ff95e6f385a05ff9452 | 22.153846 | 108 | 0.614618 | 4.727749 | false | false | false | false |
cubixlabs/GIST-Framework | GISTFramework/Classes/Controls/AnimatedTextInput/AnimatedTextView.swift | 1 | 4074 | import UIKit
final class AnimatedTextView: UITextView {
public var textAttributes: [NSAttributedString.Key: Any]? {
didSet {
guard let attributes = textAttributes else { return }
typingAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value) })
}
}
public override var font: UIFont? {
didSet {
var attributes = typingAttributes
attributes[NSAttributedString.Key.font] = font
textAttributes = Dictionary(uniqueKeysWithValues: attributes.lazy.map { ($0.key, $0.value)})
}
}
public weak var textInputDelegate: TextInputDelegate?
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
fileprivate func setup() {
contentInset = UIEdgeInsets(top: 0, left: -4, bottom: 0, right: 0)
delegate = self
}
public override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
}
extension AnimatedTextView: TextInput {
public func configureInputView(newInputView: UIView) {
inputView = newInputView
}
public var currentText: String? {
get { return text }
set { self.text = newValue }
}
public var currentSelectedTextRange: UITextRange? {
get { return self.selectedTextRange }
set { self.selectedTextRange = newValue }
}
public var currentBeginningOfDocument: UITextPosition? {
return self.beginningOfDocument
}
public var currentKeyboardAppearance: UIKeyboardAppearance {
get { return self.keyboardAppearance }
set { self.keyboardAppearance = newValue}
}
public var autocorrection: UITextAutocorrectionType {
get { return self.autocorrectionType }
set { self.autocorrectionType = newValue }
}
public var autocapitalization: UITextAutocapitalizationType {
get { return self.autocapitalizationType }
set { self.autocapitalizationType = newValue }
}
public func changeReturnKeyType(with newReturnKeyType: UIReturnKeyType) {
returnKeyType = newReturnKeyType
}
public func currentPosition(from: UITextPosition, offset: Int) -> UITextPosition? {
return position(from: from, offset: offset)
}
public func changeClearButtonMode(with newClearButtonMode: UITextField.ViewMode) {}
public func updateData(_ data: Any?) {
// DO WHAT SO EVER
} //F.E.
}
extension AnimatedTextView: UITextViewDelegate {
public func textViewDidBeginEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidBeginEditing(textInput: self)
}
public func textViewDidEndEditing(_ textView: UITextView) {
textInputDelegate?.textInputDidEndEditing(textInput: self)
}
public func textViewDidChange(_ textView: UITextView) {
let range = textView.selectedRange
textView.attributedText = NSAttributedString(string: textView.text, attributes: textAttributes)
textView.selectedRange = range
textInputDelegate?.textInputDidChange(textInput: self)
}
public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == "\n" {
return textInputDelegate?.textInputShouldReturn(textInput: self) ?? true
}
return textInputDelegate?.textInput(textInput: self, shouldChangeCharactersIn: range, replacementString: text) ?? true
}
public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldBeginEditing(textInput: self) ?? true
}
public func textViewShouldEndEditing(_ textView: UITextView) -> Bool {
return textInputDelegate?.textInputShouldEndEditing(textInput: self) ?? true
}
}
| agpl-3.0 | 15a55f4a9e04f04a0faa71fe45f0261a | 31.333333 | 126 | 0.673294 | 5.573187 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/GutenbergViewController+Localization.swift | 1 | 1115 | import Foundation
extension GutenbergViewController {
enum Localization {
static let fileName = "Localizable"
}
func parseGutenbergTranslations(in bundle: Bundle = Bundle.main) -> [String: [String]]? {
guard let fileURL = bundle.url(
forResource: Localization.fileName,
withExtension: "strings",
subdirectory: nil,
localization: currentLProjFolderName()
) else {
return nil
}
if let dictionary = NSDictionary(contentsOf: fileURL) as? [String: String] {
var resultDict: [String: [String]] = [:]
for (key, value) in dictionary {
resultDict[key] = [value]
}
return resultDict
}
return nil
}
private func currentLProjFolderName() -> String? {
var lProjFolderName = Locale.current.identifier
if let identifierWithoutRegion = Locale.current.identifier.split(separator: "_").first {
lProjFolderName = String(identifierWithoutRegion)
}
return lProjFolderName
}
}
| gpl-2.0 | 1ec43e014425caffd56162370193ad08 | 30.857143 | 96 | 0.591031 | 5.114679 | false | false | false | false |
mmllr/CleanTweeter | CleanTweeter/UseCases/TweetList/UI/View/iOS/CircularImageView.swift | 1 | 765 | //
// CircularImageView.swift
// CleanTweeter
//
// Created by Markus Müller on 04.01.16.
// Copyright © 2016 Markus Müller. All rights reserved.
//
import UIKit
@IBDesignable class CircularImageView: UIView {
@IBInspectable var image: UIImage? {
didSet {
self.layer.masksToBounds = true;
self.layer.contents = image?.cgImage
self.layer.contentsGravity = CALayerContentsGravity.resizeAspectFill
}
}
override var frame: CGRect {
didSet {
layer.cornerRadius = frame.width/2
layer.masksToBounds = layer.cornerRadius > 0
}
}
@IBInspectable var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.cgColor
}
}
}
| mit | 13f36272d61e280e77076fb116f9677f | 20.771429 | 71 | 0.709974 | 3.611374 | false | false | false | false |
mightydeveloper/swift | test/1_stdlib/Bit.swift | 10 | 901 | //===--- Bit.swift --------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
let zero: Bit = .Zero
let one: Bit = .One
// CHECK: testing
print("testing")
// CHECK-NEXT: 1
print((one - zero).rawValue)
// CHECK-NEXT: 1
print(zero.successor().rawValue)
// CHECK-NEXT: 0
print(one.predecessor().rawValue)
// CHECK-NEXT: 0
print((one &+ one).rawValue)
// CHECK: done.
print("done.")
| apache-2.0 | a57f98718f53e2958b053c29f31252e0 | 26.30303 | 80 | 0.584906 | 4.004444 | false | true | false | false |
bryx-inc/BRYXStackView | Pod/Classes/StackView.swift | 1 | 10964 | // Copyright (c) 2015 Bryx, Inc. <[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
/// A struct for holding references to views and their corresponding insets.
private struct ViewBox {
let view: UIView
let edgeInsets: UIEdgeInsets
}
/// The StackView class provides a streamlined interface for
/// laying out a collection of views in a column.
/// StackView takes advantage of Auto Layout to make sure its
/// views size appropriately on all devices and orientations.
@availability(iOS, introduced=7.0)
public class StackView: UIView {
/// Holds a reference to the constraints placed on the
/// views in the stack.
///
/// When a new view is added, these constraints are
/// removed from the StackView and re-generated.
private var stackConstraints = [NSLayoutConstraint]()
/// Holds all the stacked views and their corresponding
/// edge insets so the constraints can be re-generated.
private var viewBoxes = [ViewBox]()
/// Tells whether or not we are currently batching updates.
/// If this proerty is true, then updateConstraints will only
/// call the superview's method.
private var isBatchingUpdates = false
public init() {
super.init(frame: CGRectZero)
self.setTranslatesAutoresizingMaskIntoConstraints(false)
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/// Removes all subviews from the StackView,
/// and all associated constraints.
@availability(iOS, introduced=7.0)
public func removeAllSubviews() {
self.batchUpdates({
for subview in self.subviews {
subview.removeFromSuperview()
}
self.stackConstraints.removeAll(keepCapacity: true)
self.viewBoxes.removeAll(keepCapacity: true)
})
}
/// Batches updates of views, and calls completion when finished.
/// Use this when you have many views to add, and only want to update
/// the constraints when all views have been added.
///
/// :param: updates The updates (view insertions or removals)
/// :param: completion An optional block to call once the updates have
/// finished and the constraints have been updated.
///
/// :note: This method is safe to call inside an existing batch update.
public func batchUpdates(updates: () -> (), completion: (() -> ())? = nil) {
if self.isBatchingUpdates {
// If we're already batching updates, don't modify the isBatchingUpdates
// value. Instead, just call the updates.
updates()
} else {
self.isBatchingUpdates = true
updates()
self.isBatchingUpdates = false
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
}
completion?()
}
/// If the view hierarchy has changed, and the StackView is not batching updates,
/// this method recomputes the constraints needed to represent the stacked views
/// with all of their edge insets.
override public func updateConstraints() {
if self.stackConstraints.isEmpty && !self.isBatchingUpdates {
var affectedBoxes = [ViewBox]()
for box in self.viewBoxes {
if box.view.hidden { continue }
// Horizontally constrain the new view with respect to the edge insets.
var views = ["view": box.view]
let horizontal = NSLayoutConstraint.constraintsWithVisualFormat(
"H:|-(\(box.edgeInsets.left))-[view]-(\(box.edgeInsets.right))-|",
options: .DirectionLeadingToTrailing,
metrics: nil, views: views
) as! [NSLayoutConstraint]
self.addConstraints(horizontal)
self.stackConstraints += horizontal
// If there isn't an existing view in the stack, we'll need
// to vertically constrain with respect to the superview,
// so use `|`. Otherwise, if we have a previously-added view,
// constrain vertically to that view and
let parent: String
var topInset = box.edgeInsets.top
if let last = affectedBoxes.last {
parent = "[parent]"
views["parent"] = last.view
// Add the previous view's 'bottom' to this view's
// 'top'.
topInset += last.edgeInsets.bottom
} else {
parent = "|"
}
// Vertically constrain the new view with respect to the edge insets.
// Also add the bottom from the previous view's edge insets.
let vertical = NSLayoutConstraint.constraintsWithVisualFormat(
"V:\(parent)-(\(topInset))-[view]",
options: .DirectionLeadingToTrailing,
metrics: nil, views: views
) as! [NSLayoutConstraint]
self.addConstraints(vertical)
self.stackConstraints += vertical
affectedBoxes.append(box)
}
if let box = affectedBoxes.last {
// Reset the lastViewConstraints to the constraints on this new view.
let lastConstraints = NSLayoutConstraint.constraintsWithVisualFormat(
"V:[view]-(\(box.edgeInsets.bottom))-|",
options: .DirectionLeadingToTrailing,
metrics: nil, views: ["view": box.view]
) as! [NSLayoutConstraint]
self.addConstraints(lastConstraints)
self.stackConstraints += lastConstraints
}
}
super.updateConstraints()
}
/// Adds a subview to the StackView with associated edge insets.
/// StackView will attempt to create constraints such that the view has
/// padding around it that matches the provided insets.
///
/// :param: view The view to add.
/// :param: edgeInsets A UIEdgeInsets struct containing top and bottom insets
/// that the view should respect within the stack.
public func addSubview(view: UIView, withEdgeInsets edgeInsets: UIEdgeInsets) {
// Remove the constraints on the view.
super.addSubview(view)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.viewBoxes.append(ViewBox(view: view, edgeInsets: edgeInsets))
self.invalidateConstraints()
}
/// Inserts a subview at the provided index in the stack. Also re-orders the views
/// in the stack such that the new order is respected.
///
/// :param: view The view to add.
/// :param: index The index, vertically, where the view should live in the stack.
/// :param: edgeInsets: The insets to apply around the view.
public func insertSubview(view: UIView, atIndex index: Int, withEdgeInsets edgeInsets: UIEdgeInsets) {
super.insertSubview(view, atIndex: index)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
self.viewBoxes.insert(ViewBox(view: view, edgeInsets: edgeInsets), atIndex: index)
self.invalidateConstraints()
}
/// Inserts a subview at the provided index in the stack. Also re-orders the views
/// in the stack such that the new order is respected.
///
/// :param: view The view to add.
/// :param: index The index, vertically, where the view should live in the stack.
public override func insertSubview(view: UIView, atIndex index: Int) {
self.insertSubview(view, atIndex: index, withEdgeInsets: UIEdgeInsetsZero)
}
/// Re-sets the edge insets associated with a view in the stack, and triggers a layout pass.
/// If the view is not found in the stack, this method does nothing.
///
/// :param: insets The new insets to apply to the view.
/// :param: view The view to update.
public func setEdgeInsets(insets: UIEdgeInsets, forView view: UIView) {
for (index, box) in enumerate(self.viewBoxes) {
if box.view === view {
self.viewBoxes[index] = ViewBox(view: view, edgeInsets: insets)
self.invalidateConstraints()
break
}
}
}
/// Adds all of the provided views to the stack with the provided edgeInsets applied to each of them.
///
/// :param: views An Array of UIViews to be added to the stack.
/// :param: insets UIEdgeInsets to apply around each view.
public func addSubviews(views: [UIView], withEdgeInsets edgeInsets: UIEdgeInsets = UIEdgeInsetsZero, completion: (() -> ())? = nil) {
self.batchUpdates({
for view in views {
self.addSubview(view, withEdgeInsets: edgeInsets)
}
}, completion: completion)
}
/// Removes all constraints added by the StackView and tells the
/// view to update the constraints if it's not currently batching requests.
public func invalidateConstraints() {
self.removeConstraints(self.stackConstraints)
self.stackConstraints.removeAll(keepCapacity: true)
if !self.isBatchingUpdates {
self.setNeedsUpdateConstraints()
self.updateConstraintsIfNeeded()
}
}
/// Adds a subview to the StackView with associated edge insets.
/// StackView will attempt to create constraints such that the view has
/// padding around it that matches the provided insets.
///
/// :param: view The view to add.
override public func addSubview(view: UIView) {
self.addSubview(view, withEdgeInsets: UIEdgeInsetsZero)
}
}
| mit | f35e89fa8b726c3ec583066b309b975d | 44.119342 | 137 | 0.630062 | 5.283855 | false | false | false | false |
CoderJChen/SWWB | CJWB/CJWB/Classes/Compose/picPicker/CJPicPickerViewCell.swift | 1 | 1339 | //
// CJPicPickerViewCell.swift
// CJWB
//
// Created by 星驿ios on 2017/9/13.
// Copyright © 2017年 CJ. All rights reserved.
//
import UIKit
class CJPicPickerViewCell: UICollectionViewCell {
//MARK:- 控件的属性
@IBOutlet weak var addPhotoBtn: UIButton!
@IBOutlet weak var removePhotoBtn: UIButton!
@IBOutlet weak var imageView: UIImageView!
//MARK:- 定义属性
var image : UIImage? {
didSet{
if image != nil {
imageView.image = image
addPhotoBtn.isUserInteractionEnabled = false
removePhotoBtn.isHidden = false
}else{
imageView.image = nil
addPhotoBtn.isUserInteractionEnabled = true
removePhotoBtn.isHidden = true
}
}
}
//MARK:- 事件监听
@IBAction func addPhotoClick(_ sender: Any) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: PicPickerAddPhotoNote), object: nil)
}
@IBAction func removePhotoClick(_ sender: UIButton) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue:PicPickerRemovePhotoNote), object: imageView.image)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
| apache-2.0 | a1d834349d940b3d2038f0516cbb96b5 | 26.208333 | 126 | 0.612557 | 4.873134 | false | false | false | false |
damienmsdevs/swift-mlibs | wyley-starwarsprofile.swift | 1 | 2737 | /* Words to Fill in Mad Lib */
//Let's create the nouns
var firstNoun: String
var secondNoun: String
var thirdNoun: String
//And the adjectives
var firstPastTenseAdjective: String
var secondAdjective: String
//And the verbs
var firstVerb: String
var secondVerb: String
var thirdVerb: String
var fourthVerb: String
//And the adverb
var firstAdverb: String
//Finally, I'll create some extra variables to spice up the story
var firstName: String
var firstLastName: String
var secondName: String
var firstNumber: String
var secondNumber: String
var firstRelative: String
/* Mad Lib Questionnaire */
print("Please enter a noun", terminator: ": ")
firstNoun = readLine()!
print("Please enter another noun", terminator: ": ")
secondNoun = readLine()!
print("Please enter one final noun", terminator: ": ")
thirdNoun = readLine()!
print("Please enter an adjective", terminator: ": ")
firstPastTenseAdjective = readLine()!
print("Please enter another adjective", terminator: ": ")
secondAdjective = readLine()!
print("Please enter a verb", terminator: ": ")
firstVerb = readLine()!
print("Please enter another verb", terminator: ": ")
secondVerb = readLine()!
print("Please enter another verb", terminator: ": ")
thirdVerb = readLine()!
print("Please enter one final verb (this is the last verb, we promise)", terminator: ": ")
fourthVerb = readLine()!
print("Please enter an adverb", terminator: ": ")
firstAdverb = readLine()!
print("Please enter a name", terminator: ": ")
firstName = readLine()!
print("Please enter a name", terminator: ": ")
firstLastName = readLine()!
print("Please enter another name", terminator: ": ")
secondName = readLine()!
print("Please enter a number", terminator: ": ")
firstNumber = readLine()!
print("Please enter another number", terminator: ": ")
secondNumber = readLine()!
print("Please enter a relative's name", terminator: ": ")
firstRelative = readLine()!
/* Mad Lib Story */
//Before we continue, we'll clear the screen for the player so they don't see anything else.
print("\u{001B}[2J")
print("Greetings imbeciles. I am Darth \(firstLastName), the most \(firstPastTenseAdjective) \(firstNoun) in the galaxy.\n")
print("I have destroyed \(firstNumber) planets using a \(secondNoun)-sized weapon called the Death \(thirdNoun). My reputation for killing \(firstAdverb) is something others \(firstVerb) at when they hear my name.'\n")
print("I hate seeing my army \(secondVerb), and the only thing that's worse is when they \(thirdVerb). I have a \(secondAdjective) son that defies me; his name is \(secondName), and he is \(secondNumber) years old.\n")
print("I hardly \(fourthVerb), except when someone decides to get in my way.\n")
print("By the way, I am your \(firstRelative)!")
| apache-2.0 | b47fb4b0fbb91d168f41069301136b58 | 30.825581 | 218 | 0.727073 | 3.955202 | false | false | false | false |
ngageoint/mage-ios | Mage/Navigation/NavigationOverlay.swift | 1 | 807 | //
// NavigationOverlay.swift
//
// Created by Tyler Burgett on 8/21/20.
// Copyright © 2020 NGA. All rights reserved.
//
import Foundation
import MapKit
class NavigationOverlay: MKPolyline, OverlayRenderable {
var color: UIColor = UIColor.systemRed
var lineWidth: CGFloat = 1.0
var renderer: MKOverlayRenderer {
get {
let renderer = MKPolylineRenderer(overlay: self);
renderer.strokeColor = self.color;
renderer.lineWidth = self.lineWidth;
return renderer;
}
}
public convenience init(points: UnsafePointer<MKMapPoint>, count: Int, color: UIColor = .systemRed, lineWidth: CGFloat = 8.0) {
self.init(points: points, count: count);
self.color = color;
self.lineWidth = lineWidth;
}
}
| apache-2.0 | e5b60572ec2b38349cd9bb09311c6135 | 26.793103 | 131 | 0.64268 | 4.380435 | false | false | false | false |
brightdigit/tubeswift | TubeSwift/SubscriptionClient.swift | 1 | 3258 | //
// SubscriptionClient.swift
// TubeSwift
//
// Created by Leo G Dion on 4/29/15.
// Copyright (c) 2015 Leo G Dion. All rights reserved.
//
public struct SubscriptionSubscriberSnippet {
public let title:String
public let description:String
public let channelId:String
public let thumbnails:[String:Thumbnail]
public init?(result:[String:AnyObject]?) {
if let dictionary = result,
let title = dictionary["title"] as? String,
let description = dictionary["description"] as? String,
let channelId = dictionary["channelId"] as? String,
let thumbnails = Thumbnail.Set((dictionary["thumbnails"] as? [String:[String:AnyObject]])) {
self.title = title
self.description = description
self.channelId = channelId
self.thumbnails = thumbnails
} else {
return nil
}
}
}
public struct SubscriptionSnippet {
public let publishedAt:NSDate
public let channelId: String?
public let title: String
public let description: String
public let thumbnails:[String:Thumbnail]
public let channelTitle:String?
public let tags:[String]
public init?(result: [String:AnyObject]?) {
if let publishAtStr = result?["publishedAt"] as? String,
let publishedAt = _dateFormatter.dateFromString(publishAtStr),
let title = result?["title"] as? String,
let description = result?["description"] as? String,
let thumbnails = Thumbnail.Set((result?["thumbnails"] as? [String:[String:AnyObject]])) {
self.publishedAt = publishedAt
self.channelId = result?["channelId"] as? String
self.title = title
self.description = description
self.thumbnails = thumbnails
self.channelTitle = result?["channelTitle"] as? String
self.tags = result?["tags"] as? [String] ?? [String]()
} else {
return nil
}
}
}
public struct Subscription {
public let etag:String
public let id:String
//public let contentDetails:ContentDetails
public let kind:YouTubeKind = YouTubeKind.Subscription
public let subscriberSnippet:SubscriptionSubscriberSnippet?
public let snippet:SubscriptionSnippet?
public init?(result: [String:AnyObject]) {
if let etag = result["etag"] as? String,
let id = result["id"] as? String {
self.etag = etag
self.id = id
self.subscriberSnippet = SubscriptionSubscriberSnippet(result: result["subscriberSnippet"] as? [String:AnyObject])
self.snippet = SubscriptionSnippet(result: result["snippet"] as? [String:AnyObject])
} else {
return nil
}
}
}
public class SubscriptionClient: NSObject {
public let client: TubeSwiftClient
public init (client: TubeSwiftClient) {
self.client = client
}
public func list (query: ResourceQuery, completion: (NSURLRequest, NSURLResponse?, Response<Subscription>?, NSError?) -> Void) {
request(.GET, "https://www.googleapis.com/youtube/v3/subscriptions", parameters: query.parameters).responseJSON(options: .allZeros) { (request, response, result, error) -> Void in
if let aError = error {
completion(request, response, nil, aError)
} else if let clRes = Response<Subscription>(kind: YouTubeKind.SubscriptionListResponse,result: result, itemFactory: {Subscription(result: $0)}) {
completion(request, response, clRes, nil)
} else {
completion(request, response, nil, NSError())
}
}
}
}
| mit | c5d95759482f8ea0c0f89360b0bd8cf6 | 31.909091 | 181 | 0.718846 | 3.797203 | false | false | false | false |
ProsoftEngineering/TimeMachineRemoteStatus | TimeMachineRemoteStatus/ProcessExtensions.swift | 1 | 2476 | // Copyright © 2016-2017, Prosoft Engineering, Inc. (A.K.A "Prosoft")
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of Prosoft nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL PROSOFT ENGINEERING, INC. BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
extension Process {
// http://stackoverflow.com/a/25729093/412179
static func run(launchPath: String, args: [String]) -> (status: Int32, output: String, error: String) {
let task = Process()
task.launchPath = launchPath
task.arguments = args
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
task.standardOutput = stdoutPipe
task.standardError = stderrPipe
task.launch()
let stdoutData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()
let stderrData = stderrPipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
let output = String(data: stdoutData, encoding: .utf8)
let error = String(data: stderrData, encoding: .utf8)
return (task.terminationStatus, output!, error!)
}
}
| bsd-3-clause | 9406ab37754304ea2ffdcd9d10297dda | 46.596154 | 107 | 0.712727 | 4.824561 | false | false | false | false |
asp2insp/yowl | yowl/ResultsStore.swift | 1 | 1171 | //
// ResultsStore.swift
// yowl
//
// Created by Josiah Gaskin on 5/17/15.
// Copyright (c) 2015 Josiah Gaskin. All rights reserved.
//
import Foundation
let RESULTS = Getter(keyPath:["results", "businesses"])
// ID: results
class SearchResultsStore : Store {
override func getInitialState() -> Immutable.State {
return Immutable.toState([])
}
override func initialize() {
self.on("setResults", handler: { (state, results, action) -> Immutable.State in
let offset = Reactor.instance.evaluateToSwift(OFFSET) as! Int
if offset == 0 {
return Immutable.toState(results as! AnyObject)
} else {
return state.mutateIn(["businesses"], withMutator: {(s) -> Immutable.State in
let newResults = results as! [String:AnyObject]
let newBiz = newResults["businesses"] as! [AnyObject]
var result = s!
for biz in newBiz {
result = result.push(Immutable.toState(biz))
}
return result
})
}
})
}
} | mit | 2f928d54b066924572c8943313f74001 | 29.842105 | 93 | 0.542272 | 4.665339 | false | false | false | false |
natecook1000/swift | stdlib/public/SDK/Foundation/NSDictionary.swift | 1 | 9274 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
//===----------------------------------------------------------------------===//
// Dictionaries
//===----------------------------------------------------------------------===//
extension NSDictionary : ExpressibleByDictionaryLiteral {
public required convenience init(
dictionaryLiteral elements: (Any, Any)...
) {
// FIXME: Unfortunate that the `NSCopying` check has to be done at runtime.
self.init(
objects: elements.map { $0.1 as AnyObject },
forKeys: elements.map { $0.0 as AnyObject as! NSCopying },
count: elements.count)
}
}
extension Dictionary {
/// Private initializer used for bridging.
///
/// The provided `NSDictionary` will be copied to ensure that the copy can
/// not be mutated by other code.
public init(_cocoaDictionary: _NSDictionary) {
assert(
_isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self),
"Dictionary can be backed by NSDictionary storage only when both key and value are bridged verbatim to Objective-C")
// FIXME: We would like to call CFDictionaryCreateCopy() to avoid doing an
// objc_msgSend() for instances of CoreFoundation types. We can't do that
// today because CFDictionaryCreateCopy() copies dictionary contents
// unconditionally, resulting in O(n) copies even for immutable dictionaries.
//
// <rdar://problem/20690755> CFDictionaryCreateCopy() does not call copyWithZone:
//
// The bug is fixed in: OS X 10.11.0, iOS 9.0, all versions of tvOS
// and watchOS.
self = Dictionary(
_immutableCocoaDictionary:
unsafeBitCast(_cocoaDictionary.copy(with: nil) as AnyObject,
to: _NSDictionary.self))
}
}
// Dictionary<Key, Value> is conditionally bridged to NSDictionary
extension Dictionary : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDictionary {
return unsafeBitCast(_bridgeToObjectiveCImpl() as AnyObject,
to: NSDictionary.self)
}
public static func _forceBridgeFromObjectiveC(
_ d: NSDictionary,
result: inout Dictionary?
) {
if let native = [Key : Value]._bridgeFromObjectiveCAdoptingNativeStorageOf(
d as AnyObject) {
result = native
return
}
if _isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self) {
result = [Key : Value](
_cocoaDictionary: unsafeBitCast(d as AnyObject, to: _NSDictionary.self))
return
}
if Key.self == String.self {
// String and NSString have different concepts of equality, so
// string-keyed NSDictionaries may generate key collisions when bridged
// over to Swift. See rdar://problem/35995647
var dict = Dictionary(minimumCapacity: d.count)
d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in
let key = Swift._forceBridgeFromObjectiveC(
anyKey as AnyObject, Key.self)
let value = Swift._forceBridgeFromObjectiveC(
anyValue as AnyObject, Value.self)
// FIXME: Log a warning if `dict` already had a value for `key`
dict[key] = value
})
result = dict
return
}
// `Dictionary<Key, Value>` where either `Key` or `Value` is a value type
// may not be backed by an NSDictionary.
var builder = _DictionaryBuilder<Key, Value>(count: d.count)
d.enumerateKeysAndObjects({ (anyKey: Any, anyValue: Any, _) in
let anyObjectKey = anyKey as AnyObject
let anyObjectValue = anyValue as AnyObject
builder.add(
key: Swift._forceBridgeFromObjectiveC(anyObjectKey, Key.self),
value: Swift._forceBridgeFromObjectiveC(anyObjectValue, Value.self))
})
result = builder.take()
}
public static func _conditionallyBridgeFromObjectiveC(
_ x: NSDictionary,
result: inout Dictionary?
) -> Bool {
let anyDict = x as [NSObject : AnyObject]
if _isBridgedVerbatimToObjectiveC(Key.self) &&
_isBridgedVerbatimToObjectiveC(Value.self) {
result = Swift._dictionaryDownCastConditional(anyDict)
return result != nil
}
result = anyDict as? Dictionary
return result != nil
}
public static func _unconditionallyBridgeFromObjectiveC(
_ d: NSDictionary?
) -> Dictionary {
// `nil` has historically been used as a stand-in for an empty
// dictionary; map it to an empty dictionary.
if _slowPath(d == nil) { return Dictionary() }
var result: Dictionary? = nil
_forceBridgeFromObjectiveC(d!, result: &result)
return result!
}
}
extension NSDictionary : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as! Dictionary<AnyHashable, AnyHashable>)
}
}
extension NSDictionary : Sequence {
// FIXME: A class because we can't pass a struct with class fields through an
// [objc] interface without prematurely destroying the references.
final public class Iterator : IteratorProtocol {
var _fastIterator: NSFastEnumerationIterator
var _dictionary: NSDictionary {
return _fastIterator.enumerable as! NSDictionary
}
public func next() -> (key: Any, value: Any)? {
if let key = _fastIterator.next() {
// Deliberately avoid the subscript operator in case the dictionary
// contains non-copyable keys. This is rare since NSMutableDictionary
// requires them, but we don't want to paint ourselves into a corner.
return (key: key, value: _dictionary.object(forKey: key)!)
}
return nil
}
internal init(_ _dict: NSDictionary) {
_fastIterator = NSFastEnumerationIterator(_dict)
}
}
// Bridging subscript.
@objc
public subscript(key: Any) -> Any? {
@objc(_swift_objectForKeyedSubscript:)
get {
// Deliberately avoid the subscript operator in case the dictionary
// contains non-copyable keys. This is rare since NSMutableDictionary
// requires them, but we don't want to paint ourselves into a corner.
return self.object(forKey: key)
}
}
/// Return an *iterator* over the elements of this *sequence*.
///
/// - Complexity: O(1).
public func makeIterator() -> Iterator {
return Iterator(self)
}
}
extension NSMutableDictionary {
// Bridging subscript.
@objc override public subscript(key: Any) -> Any? {
@objc(_swift_objectForKeyedSubscript:)
get {
return self.object(forKey: key)
}
@objc(_swift_setObject:forKeyedSubscript:)
set {
// FIXME: Unfortunate that the `NSCopying` check has to be done at
// runtime.
let copyingKey = key as AnyObject as! NSCopying
if let newValue = newValue {
self.setObject(newValue, forKey: copyingKey)
} else {
self.removeObject(forKey: copyingKey)
}
}
}
}
extension NSDictionary {
/// Initializes a newly allocated dictionary and adds to it objects from
/// another given dictionary.
///
/// - Returns: An initialized dictionary--which might be different
/// than the original receiver--containing the keys and values
/// found in `otherDictionary`.
@objc(_swiftInitWithDictionary_NSDictionary:)
public convenience init(dictionary otherDictionary: NSDictionary) {
// FIXME(performance)(compiler limitation): we actually want to do just
// `self = otherDictionary.copy()`, but Swift does not have factory
// initializers right now.
let numElems = otherDictionary.count
let stride = MemoryLayout<AnyObject>.stride
let alignment = MemoryLayout<AnyObject>.alignment
let singleSize = stride * numElems
let totalSize = singleSize * 2
assert(stride == MemoryLayout<NSCopying>.stride)
assert(alignment == MemoryLayout<NSCopying>.alignment)
// Allocate a buffer containing both the keys and values.
let buffer = UnsafeMutableRawPointer.allocate(
byteCount: totalSize, alignment: alignment)
defer {
buffer.deallocate()
_fixLifetime(otherDictionary)
}
let valueBuffer = buffer.bindMemory(to: AnyObject.self, capacity: numElems)
let buffer2 = buffer + singleSize
__NSDictionaryGetObjects(otherDictionary, buffer, buffer2, numElems)
let keyBufferCopying = buffer2.assumingMemoryBound(to: NSCopying.self)
self.init(objects: valueBuffer, forKeys: keyBufferCopying, count: numElems)
}
}
extension NSDictionary : CustomReflectable {
public var customMirror: Mirror {
return Mirror(reflecting: self as [NSObject : AnyObject])
}
}
extension Dictionary: CVarArg {}
| apache-2.0 | b8b60c51358386b3c5e322e0e99553db | 34.945736 | 122 | 0.666056 | 4.870798 | false | false | false | false |
sync/NearbyTrams | NearbyTramsKit/Source/RouteViewModel.swift | 1 | 1247 | //
// Copyright (c) 2014 Dblechoc. All rights reserved.
//
import Foundation
public class RouteViewModel: Equatable
{
public let identifier: String
public var routeNo: String
public var routeDescription: String
public var downDestination: String
public var upDestination: String
public let color: CGColorRef
public init (identifier: String, routeNo: String, routeDescription: String, downDestination: String, upDestination: String, color: CGColorRef = ColorUtility.generateRandomColor())
{
self.identifier = identifier
self.routeNo = routeNo
self.routeDescription = routeDescription
self.downDestination = downDestination
self.upDestination = upDestination
self.color = color
}
public func updateWithRouteNo(routeNo: String, routeDescription: String, downDestination: String, upDestination: String)
{
self.routeNo = routeNo
self.routeDescription = routeDescription
self.downDestination = downDestination
self.upDestination = upDestination
self.routeDescription = routeDescription
}
}
public func ==(lhs: RouteViewModel, rhs: RouteViewModel) -> Bool
{
return lhs.identifier == rhs.identifier
}
| mit | 12c1617fe74e8ffeff79db5a9fbd77c5 | 30.974359 | 183 | 0.712109 | 5.028226 | false | false | false | false |
wikimedia/wikipedia-ios | WMF Framework/TimelineView.swift | 1 | 11539 | import UIKit
public class TimelineView: UIView {
public enum Decoration {
case doubleDot, singleDot, squiggle
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
open func setup() {
}
public var decoration: Decoration = .doubleDot {
didSet {
guard oldValue != decoration else {
return
}
switch decoration {
case .squiggle:
innerDotShapeLayer.removeFromSuperlayer()
outerDotShapeLayer.removeFromSuperlayer()
layer.addSublayer(squiggleShapeLayer)
updateSquiggleCenterPoint()
case .doubleDot:
squiggleShapeLayer.removeFromSuperlayer()
layer.addSublayer(innerDotShapeLayer)
layer.addSublayer(outerDotShapeLayer)
case .singleDot:
squiggleShapeLayer.removeFromSuperlayer()
layer.addSublayer(innerDotShapeLayer)
}
setNeedsDisplay()
}
}
public var shouldAnimateDots: Bool = false
public var minimizeUnanimatedDots: Bool = false
public var timelineColor: UIColor? = nil {
didSet {
refreshColors()
}
}
private var color: CGColor {
return timelineColor?.cgColor ?? tintColor.cgColor
}
public var verticalLineWidth: CGFloat = 1.0 {
didSet {
squiggleShapeLayer.lineWidth = verticalLineWidth
setNeedsDisplay()
}
}
public var pauseDotsAnimation: Bool = true {
didSet {
displayLink?.isPaused = pauseDotsAnimation
}
}
private var dotRadius: CGFloat {
switch decoration {
case .singleDot: return 7.0
default: return 9.0
}
}
private let dotMinRadiusNormal: CGFloat = 0.4
// At a height of less than 30, (due to rounding) the squiggle's curves don't perfectly align with the straight lines.
private let squiggleHeight: CGFloat = 30.0
public var dotsY: CGFloat = 0 {
didSet {
guard shouldAnimateDots == false || decoration == .squiggle else {
return
}
switch decoration {
case .doubleDot, .singleDot: updateDotsRadii(to: minimizeUnanimatedDots ? 0.0 : 1.0, at: CGPoint(x: bounds.midX, y: dotsY))
case .squiggle: updateSquiggleCenterPoint()
}
setNeedsDisplay()
}
}
override public func tintColorDidChange() {
super.tintColorDidChange()
refreshColors()
}
override public var backgroundColor: UIColor? {
didSet {
outerDotShapeLayer.fillColor = backgroundColor?.cgColor
squiggleShapeLayer.fillColor = backgroundColor?.cgColor
}
}
private lazy var outerDotShapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.fillColor = backgroundColor?.cgColor ?? UIColor.white.cgColor
shape.strokeColor = color
shape.lineWidth = 1.0
if decoration == .doubleDot {
self.layer.addSublayer(shape)
}
return shape
}()
private lazy var innerDotShapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.fillColor = color
shape.strokeColor = color
shape.lineWidth = 1.0
if decoration == .doubleDot {
self.layer.addSublayer(shape)
}
return shape
}()
private lazy var squiggleShapeLayer: CAShapeLayer = {
let shape = CAShapeLayer()
shape.updateSquiggleLocation(height: squiggleHeight, decorationMidY: dotsY, midX: bounds.midX)
shape.strokeColor = color
shape.fillColor = backgroundColor?.cgColor ?? UIColor.white.cgColor
shape.lineWidth = verticalLineWidth
if decoration == .squiggle {
self.layer.addSublayer(shape)
}
return shape
}()
private lazy var displayLink: CADisplayLink? = {
guard decoration == .doubleDot, shouldAnimateDots == true else {
return nil
}
let link = CADisplayLink(target: self, selector: #selector(maybeUpdateDotsRadii))
link.add(to: RunLoop.main, forMode: RunLoop.Mode.common)
return link
}()
override public func removeFromSuperview() {
displayLink?.invalidate()
displayLink = nil
super.removeFromSuperview()
}
override public func draw(_ rect: CGRect) {
super.draw(rect)
guard let context = UIGraphicsGetCurrentContext() else {
return
}
drawVerticalLine(in: context, rect: rect)
}
public var extendTimelineAboveDot: Bool = true {
didSet {
if oldValue != extendTimelineAboveDot {
setNeedsDisplay()
}
}
}
private func drawVerticalLine(in context: CGContext, rect: CGRect) {
context.setLineWidth(verticalLineWidth)
context.setStrokeColor(color)
let lineTopY = extendTimelineAboveDot ? rect.minY : dotsY
switch decoration {
case .doubleDot, .singleDot:
context.move(to: CGPoint(x: rect.midX, y: lineTopY))
context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
case .squiggle:
if extendTimelineAboveDot {
context.move(to: CGPoint(x: rect.midX, y: lineTopY))
context.addLine(to: CGPoint(x: rect.midX, y: dotsY-squiggleHeight/2))
}
context.move(to: CGPoint(x: rect.midX, y: dotsY+squiggleHeight/2))
context.addLine(to: CGPoint(x: rect.midX, y: rect.maxY))
}
context.strokePath()
}
private func refreshColors() {
outerDotShapeLayer.strokeColor = color
innerDotShapeLayer.fillColor = color
innerDotShapeLayer.strokeColor = color
squiggleShapeLayer.strokeColor = color
setNeedsDisplay()
}
// Returns CGFloat in range from 0.0 to 1.0. 0.0 indicates dot should be minimized.
// 1.0 indicates dot should be maximized. Approaches 1.0 as timelineView.dotY
// approaches vertical center. Approaches 0.0 as timelineView.dotY approaches top
// or bottom.
private func dotRadiusNormal(with y:CGFloat, in container:UIView) -> CGFloat {
let yInContainer = convert(CGPoint(x:0, y:y), to: container).y
let halfContainerHeight = container.bounds.size.height * 0.5
return max(0.0, 1.0 - (abs(yInContainer - halfContainerHeight) / halfContainerHeight))
}
private var lastDotRadiusNormal: CGFloat = -1.0 // -1.0 so dots with dotAnimationNormal of "0.0" are visible initially
@objc private func maybeUpdateDotsRadii() {
guard let containerView = window else {
return
}
// Shift the "full-width dot" point up a bit - otherwise it's in the vertical center of screen.
let yOffset = containerView.bounds.size.height * 0.15
var radiusNormal = dotRadiusNormal(with: dotsY + yOffset, in: containerView)
// Reminder: can reduce precision to 1 (significant digit) to reduce how often dot radii are updated.
let precision: CGFloat = 2
let roundingNumber = pow(10, precision)
radiusNormal = (radiusNormal * roundingNumber).rounded(.up) / roundingNumber
guard radiusNormal != lastDotRadiusNormal else {
return
}
updateDotsRadii(to: radiusNormal, at: CGPoint(x: bounds.midX, y: dotsY))
// Progressively fade the inner dot when it gets tiny.
innerDotShapeLayer.opacity = easeInOutQuart(number: Float(radiusNormal))
lastDotRadiusNormal = radiusNormal
}
private func updateDotsRadii(to radiusNormal: CGFloat, at center: CGPoint) {
outerDotShapeLayer.updateDotRadius(dotRadius * max(radiusNormal, dotMinRadiusNormal), center: center)
innerDotShapeLayer.updateDotRadius(dotRadius * max((radiusNormal - dotMinRadiusNormal), 0.0), center: center)
}
private func updateSquiggleCenterPoint() {
squiggleShapeLayer.updateSquiggleLocation(height: squiggleHeight, decorationMidY: dotsY, midX: bounds.midX)
}
private func easeInOutQuart(number:Float) -> Float {
return number < 0.5 ? 8.0 * pow(number, 4) : 1.0 - 8.0 * (number - 1.0) * pow(number, 3)
}
}
extension CAShapeLayer {
fileprivate func updateDotRadius(_ radius: CGFloat, center: CGPoint) {
path = UIBezierPath(arcCenter: center, radius: radius, startAngle: 0.0, endAngle:CGFloat.pi * 2.0, clockwise: true).cgPath
}
fileprivate func updateSquiggleLocation(height: CGFloat, decorationMidY: CGFloat, midX: CGFloat) {
let startY = decorationMidY - height/2 // squiggle's middle (not top) should be startY
let topPoint = CGPoint(x: midX, y: startY)
let quarterOnePoint = CGPoint(x: midX, y: startY + (height*1/4))
let midPoint = CGPoint(x: midX, y: startY + (height*2/4))
let quarterThreePoint = CGPoint(x: midX, y: startY + (height*3/4))
let bottomPoint = CGPoint(x: midX, y: startY + height)
/// Math for curves shown/explained on Phab ticket: https://phabricator.wikimedia.org/T258209#6363389
let eighthOfHeight = height/8
let circleDiameter = sqrt(2*(eighthOfHeight*eighthOfHeight))
let radius = circleDiameter/2
/// Without this adjustment, the `arcCenter`s are not the true center of circle and the squiggle has some jagged edges.
let centerAdjustedRadius = radius - 1
let arc1Start = CGPoint(x: midX - radius*3, y: topPoint.y + radius*3)
let arc1Center = CGPoint(x: arc1Start.x + centerAdjustedRadius, y: arc1Start.y + centerAdjustedRadius)
let arc2Start = CGPoint(x: midX + radius*1, y: quarterOnePoint.y - radius*1)
let arc2Center = CGPoint(x: arc2Start.x + centerAdjustedRadius, y: arc2Start.y + centerAdjustedRadius)
let arc3Start = CGPoint(x: midX - radius*3, y: midPoint.y + radius*3)
let arc3Center = CGPoint(x: arc3Start.x + centerAdjustedRadius, y: arc3Start.y + centerAdjustedRadius)
let arc4Start = CGPoint(x: midX + radius*1, y: quarterThreePoint.y - radius*1)
let arc4Center = CGPoint(x: arc4Start.x + centerAdjustedRadius, y: arc4Start.y + centerAdjustedRadius)
let squiggle = UIBezierPath()
let fullCircle = 2 * CGFloat.pi // addArc's angles are in radians, let's make it easier
squiggle.move(to: topPoint)
squiggle.addLine(to: arc1Start)
squiggle.addArc(withCenter: arc1Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: false)
squiggle.addLine(to: arc2Start)
squiggle.addArc(withCenter: arc2Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: true)
squiggle.addLine(to: arc3Start)
squiggle.addArc(withCenter: arc3Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: false)
squiggle.addLine(to: arc4Start)
squiggle.addArc(withCenter: arc4Center, radius: radius, startAngle: fullCircle * 5/8, endAngle: fullCircle * 1/8, clockwise: true)
squiggle.addLine(to: bottomPoint)
path = squiggle.cgPath
}
}
| mit | 4333939d173c696237cff418e50357f3 | 37.335548 | 139 | 0.634457 | 4.669769 | false | false | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitNotes.swift | 1 | 5777 | //
// GameNotes.swift
// MEGameTracker
//
// Created by Emily Ivie on 12/31/16.
// Copyright © 2016 Emily Ivie. All rights reserved.
//
import Foundation
import CoreData
import CloudKit
extension Note: CloudDataStorable {
/// (CloudDataStorable Protocol)
/// Set any additional fields, specific to the object in question, for a cloud kit object.
public func setAdditionalCloudFields(
record: CKRecord
) {
record.setValue(uuid.uuidString as NSString, forKey: "id")
record.setValue((gameSequenceUuid?.uuidString ?? "") as NSString, forKey: "gameSequenceUuid")
record.setValue(gameVersion.stringValue as NSString, forKey: "gameVersion")
record.setValue((shepardUuid?.uuidString ?? "") as NSString, forKey: "shepardUuid")
record.setValue(identifyingObject.serializedString, forKey: "identifyingObject")
record.setValue(text, forKey: "text")
}
/// (CloudDataStorable Protocol)
/// Alter any CK items before handing to codable to modify/create object
public func getAdditionalCloudFields(changeRecord: CloudDataRecordChange) -> [String: Any?] {
var changes = changeRecord.changeSet
changes["gameSequenceUuid"] = self.gameSequenceUuid //?
changes.removeValue(forKey: "identifyingObject") // fallback to element's value
// changes.removeValue(forKey: "lastRecordData")
return changes
}
/// (CloudDataStorable Protocol)
/// Takes one serialized cloud change and saves it.
public static func saveOneFromCloud(
changeRecord: CloudDataRecordChange,
with manager: CodableCoreDataManageable?
) -> Bool {
let recordId = changeRecord.recordId
if let (id, gameUuid) = parseIdentifyingName(name: recordId),
let noteUuid = UUID(uuidString: id),
let shepardUuidString = changeRecord.changeSet["shepardUuid"] as? String,
let shepardUuid = UUID(uuidString: shepardUuidString) {
// if identifyingObject fails, throw this note away - it can't be recovered :(
guard let json = changeRecord.changeSet["identifyingObject"] as? String,
let decoder = manager?.decoder,
let identifyingObject = try? decoder.decode(
IdentifyingObject.self,
from: json.data(using: .utf8) ?? Data()
)
else {
return true
}
var element = Note.get(uuid: noteUuid) ?? Note(
identifyingObject: identifyingObject,
uuid: noteUuid,
shepardUuid: shepardUuid,
gameSequenceUuid: gameUuid
)
// apply cloud changes
element.rawData = nil
let changes = element.getAdditionalCloudFields(changeRecord: changeRecord)
element = element.changed(changes)
element.isSavedToCloud = true
// reapply any local changes
if !element.pendingCloudChanges.isEmpty {
element = element.changed(element.pendingCloudChanges.dictionary)
element.isSavedToCloud = false
}
// save locally
if element.save(with: manager) {
print("Saved from cloud \(recordId)")
return true
} else {
print("Save from cloud failed \(recordId)")
}
}
return false
}
/// (CloudDataStorable Protocol)
/// Delete a local object after directed by the cloud to do so.
public static func deleteOneFromCloud(recordId: String) -> Bool {
guard let (noteUuid, gameUuid) = parseIdentifyingName(name: recordId) else { return false }
if let noteUuid = UUID(uuidString: noteUuid) {
return delete(uuid: noteUuid, gameSequenceUuid: gameUuid)
} else {
defaultManager.log("Failed to parse note uuid: \(recordId)")
return false
}
}
/// (CloudDataStorable Protocol)
/// Create a recordName for any cloud kit object.
public static func getIdentifyingName(
id: String,
gameSequenceUuid: UUID?
) -> String {
return "\(gameSequenceUuid?.uuidString ?? "")||\(id)"
}
/// Convenience version - get the static getIdentifyingName for easy instance reference.
public func getIdentifyingName() -> String {
return Note.getIdentifyingName(id: uuid.uuidString, gameSequenceUuid: gameSequenceUuid)
}
/// (CloudDataStorable Protocol)
/// Parses a cloud identifier into the parts needed to retrieve it from core data.
public static func parseIdentifyingName(
name: String
) -> (id: String, gameSequenceUuid: UUID)? {
let pieces = name.components(separatedBy: "||")
guard pieces.count == 2 else { return nil }
if let gameSequenceUuid = UUID(uuidString: pieces[0]) {
return (id: pieces[1], gameSequenceUuid: gameSequenceUuid)
} else {
defaultManager.log("No Game UUID found for: \(name)")
return nil
}
}
/// Used for parsing from records
public static func getAll(
identifiers: [String],
with manager: CodableCoreDataManageable?
) -> [Note] {
return identifiers.map { (identifier: String) in
if let (id, _) = parseIdentifyingName(name: identifier),
let uuid = UUID(uuidString: id) {
return get(uuid: uuid, with: manager)
}
return nil
}.filter({ $0 != nil }).map({ $0! })
}
}
| mit | e6b011fc779269f2eae42ab9e94c6bc9 | 39.964539 | 101 | 0.598511 | 5.294225 | false | false | false | false |
hellogaojun/Swift-coding | 03-运算符/03-运算符/main.swift | 1 | 2058 | //
// main.swift
// 03-运算符
//
// Created by gaojun on 16/4/2.
// Copyright © 2016年 高军. All rights reserved.
//
import Foundation
print("Hello, World!")
/*
算术运算符: 除了取模, 其它和OC一样, 包括优先级
+ - * / % ++ --
*/
var result = 10 + 10
result = 10 * 10
result = 10 - 10
result = 10 / 10
print(result)
/*
取模 %
OC: 只能对整数取模
NSLog(@"%tu", 10 % 3);
Swift: 支持小数取模
*/
print(10 % 3.2)
/*
注意:Swift是安全严格的编程语言, 会在编译时候检查是否溢出, 但是只会检查字面量而不会检查变量, 所以在Swift中一定要注意隐式溢出
可以检测
var num1:UInt8 = 255 + 1;
无法检测
var num1:UInt8 = 255
var num2:UInt8 = 250
var result = num1 + num2
println(result)
遇到这种问题可以利用溢出运算符解决该问题:http://www.yiibai.com/swift/overflow_operators.html
&+ &- &* &/ &%
*/
//var over1 : UInt8 = 255
//var over2 : UInt8 = 250
//var result1 = over1 + over2
//print(result1)
//自增,自减
var number = 10
number++
print(number)
number--
print(number)
//赋值运算符
var num1 = 10
num1 = 20
num1 += 10
num1 -= 10
num1 *= 10
num1 /= 10
num1 %= 10
print(num1)
//关系运算符
var res:Bool = 123 > 12
print(res)//true
var res2 = 123 > 12 ? 123:12
print(res2)
//逻辑运算符,Swift中的逻辑运算符只能操作Bool类型数据, 而OC可以操作整形(非0即真
//if 5 {//错误写法
// print("5")
//}
var open = false
if !open {
print("开房")
}else {
print("开你个头")
}
var age = 25
var height = 185
var wage = 30000
if age > 25 && age < 40 && height > 175 || wage > 20000 {
print("约炮")
}else {
print("约你个蛋")
}
/*
区间
闭区间: 包含区间内所有值 a...b 例如: 1...5
半闭区间: 包含头不包含尾 a..<b 例如: 1..<5
注意: 1.Swift刚出来时的写法是 a..b
2.区间只能用于整数, 写小数会有问题
应用场景: 遍历, 数组等
*/
for i in 1...5 {
print("闭区间--i:",i)
}
for i in 1..<5 {
print("半闭区间--i:",i)
}
| apache-2.0 | 4570126cbc5166b4d701ebf0597afbd3 | 12.194915 | 72 | 0.606936 | 2.221113 | false | false | false | false |
gusrsilva/Picture-Perfect-iOS | PicturePerfect/ShadowImageView.swift | 1 | 843 | //
// ShadowImageView.swift
// PicturePerfect
//
// Created by Gus Silva on 4/16/17.
// Copyright © 2017 Gus Silva. All rights reserved.
//
import UIKit
class ShadowImageView: UIImageView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
var shadowLayer: CAShapeLayer!
override func layoutSubviews() {
super.layoutSubviews()
layer.masksToBounds = false
clipsToBounds = false
layer.shadowPath = UIBezierPath(rect: bounds).cgPath
layer.shadowColor = UIColor.black.cgColor
layer.shadowOffset = CGSize(width: 0, height: 0)
layer.shadowOpacity = 0.35
layer.shadowRadius = 5
}
}
| apache-2.0 | 991ed665242b16e338deb01379c8c7b7 | 23.764706 | 78 | 0.646081 | 4.601093 | false | false | false | false |
ustwo/mockingbird | Sources/ResourceKit/Helpers/ResourceHandler.swift | 1 | 1444 | //
// SwaggerParser.swift
// Mockingbird
//
// Created by Aaron McTavish on 20/12/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
import LoggerAPI
public struct ResourceHandler {
// MARK: - Properties
private static let sampleName = "sample_swagger"
private static let sampleExtension = "json"
private static let sampleFullName = ResourceHandler.sampleName + "." + ResourceHandler.sampleExtension
public static var swaggerSampleURL: URL {
#if os(Linux)
// swiftlint:disable:next force_unwrapping
return URL(string: "file:///root/Resources/" + ResourceHandler.sampleFullName)!
#else
// If in Xcode, grab from the resource bundle
let frameworkBundle = Bundle(for: DummyClass.self)
if let url = frameworkBundle.url(forResource:ResourceHandler.sampleName,
withExtension: ResourceHandler.sampleExtension) {
return url
}
// If using the Swift compiler (i.e. `swift build` or `swift test`, use the absolute path.
// swiftlint:disable:next force_unwrapping
let frameworkURL = Bundle(for: DummyClass.self).resourceURL!
return frameworkURL.appendingPathComponent("../../../../../Resources/" + ResourceHandler.sampleFullName)
#endif
}
}
private class DummyClass: NSObject { }
| mit | f0dffc9c0bf4277222aa09240d2a6e72 | 32.55814 | 116 | 0.644491 | 4.941781 | false | false | false | false |
gabrielfalcao/MusicKit | MusicKit/ScaleQuality.swift | 1 | 1199 | // Copyright (c) 2015 Ben Guo. All rights reserved.
import Foundation
public enum ScaleQuality : String {
case Chromatic = "Chromatic"
case Wholetone = "Wholetone"
case Octatonic1 = "Octatonic mode 1"
case Octatonic2 = "Octatonic mode 2"
case Major = "Major"
case Dorian = "Dorian"
case Phrygian = "Phrygian"
case Lydian = "Lydian"
case Mixolydian = "Mixolydian"
case Minor = "Minor"
case Locrian = "Locrian"
public var intervals : [Float] {
switch self {
case Chromatic: return [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
case Wholetone: return [2, 2, 2, 2, 2, 2]
case Octatonic1: return [2, 1, 2, 1, 2, 1, 2]
case Octatonic2: return [1, 2, 1, 2, 1, 2, 1]
case Major: return [2, 2, 1, 2, 2, 2]
case Dorian: return [2, 1, 2, 2, 2, 1]
case Phrygian: return [1, 2, 2, 2, 1, 2]
case Lydian: return [2, 2, 2, 1, 2, 2]
case Mixolydian: return [2, 2, 1, 2, 2, 1]
case Minor: return [2, 1, 2, 2, 1, 2]
case Locrian: return [1, 2, 2, 1, 2, 2]
}
}
}
extension ScaleQuality : Printable {
public var description : String {
return rawValue
}
}
| mit | 3a1bc89f4f9074e0e0a4bb58ea1b11af | 29.74359 | 64 | 0.562135 | 3.146982 | false | false | false | false |
casd82/powerup-iOS | Powerup/OOC-Event-Classes/SoundPlayer.swift | 1 | 1532 | import UIKit
import AVFoundation
import AudioToolbox
/**
Creates a strong reference to AVAudioPlayer and plays a sound file. Convenience class to declutter controller classes.
Example Use
```
let soundPlayer : SoundPlayer? = SoundPlayer()
guard let player = self.soundPlayer else {return}
// player.playSound(fileName: String, volume: Float)
player.playSound("sound.mp3", 0.5)
```
- Author: Cadence Holmes 2018
*/
class SoundPlayer {
var player: AVAudioPlayer?
var numberOfLoops: Int = 1
init () {
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
} catch let error {
print(error.localizedDescription)
}
}
/**
Handles checking for AVAudioPlayer and playing a sound.
- throws: print(error.localizedDescription)
- parameters:
- fileName : String - file name as it appears in Sounds.xcassets
- volume : Float - volume scaled 0.0 - 1.0
*/
func playSound(_ fileName: String, _ volume: Float) {
guard let sound = NSDataAsset(name: fileName) else { return }
do {
player = try AVAudioPlayer(data: sound.data)
guard let soundplayer = player else { return }
soundplayer.numberOfLoops = numberOfLoops
soundplayer.volume = volume
soundplayer.play()
} catch let error {
print(error.localizedDescription)
}
}
}
| gpl-2.0 | 8ed31576442c25bda2fa5e099b54de43 | 26.854545 | 119 | 0.643603 | 4.81761 | false | false | false | false |
mownier/photostream | Photostream/Module Extensions/FollowListModuleExtension.swift | 1 | 1214 | //
// FollowListModuleExtension.swift
// Photostream
//
// Created by Mounir Ybanez on 17/01/2017.
// Copyright © 2017 Mounir Ybanez. All rights reserved.
//
import UIKit
extension FollowListModule {
convenience init() {
self.init(view: FollowListViewController())
}
}
extension FollowListDisplayDataItem: UserTableCellItem { }
extension FollowListModuleInterface {
func presentUserTimeline(for index: Int) {
guard let presenter = self as? FollowListPresenter,
let item = listItem(at: index) else {
return
}
presenter.wireframe.showUserTimeline(
from: presenter.view.controller,
userId: item.userId
)
}
}
extension FollowListWireframeInterface {
func showUserTimeline(from parent: UIViewController?, userId: String) {
let userTimeline = UserTimelineViewController()
userTimeline.root = root
userTimeline.style = .push
userTimeline.userId = userId
var property = WireframeEntryProperty()
property.parent = parent
property.controller = userTimeline
userTimeline.enter(with: property)
}
}
| mit | c72851422d04d8d3542aac9771b03be8 | 23.755102 | 75 | 0.646331 | 5.012397 | false | false | false | false |
huangxinping/XPKit-swift | Source/Extensions/UIKit/UINavigationBar+XPKit.swift | 1 | 2097 | //
// UINavigationBar+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 UINavigationBar
public extension UINavigationBar {
// MARK: - Instance functions -
/**
Set the UINavigationBar to transparent or not
- parameter transparent: true to set it transparent, false to not
- parameter translucent: A Boolean value indicating whether the navigation bar is translucent or not
*/
public func setTransparent(transparent: Bool, translucent: Bool = true) {
if transparent {
self.setBackgroundImage(UIImage(), forBarMetrics: .Default)
self.shadowImage = UIImage()
self.translucent = translucent
} else {
self.setBackgroundImage(nil, forBarMetrics: .Default)
self.shadowImage = nil
self.translucent = translucent
}
}
}
| mit | 1b592b3e1dde36818ce2c01fa688b25e | 40.117647 | 105 | 0.710062 | 4.722973 | false | false | false | false |
lhx931119/DouYuTest | DouYu/DouYu/Classes/Tools/NetWorkTools.swift | 1 | 791 | //
// NetWorkTools.swift
// DouYu
//
// Created by 李宏鑫 on 17/1/15.
// Copyright © 2017年 hongxinli. All rights reserved.
//
import UIKit
import Alamofire
enum MethodType {
case GET
case POST
}
class NetWorkTools{
class func requestForData(methodType: MethodType, urlString: String, parpams: [String: NSString]? = nil, finishCallBack:(result: AnyObject)->()){
//获取类型
let method = methodType == .GET ? Method.GET : Method.POST
Alamofire.request(method, urlString).responseJSON { (response) in
guard let result = response.result.value else{
print(response.result.error)
return
}
finishCallBack(result: result)
}
}
}
| mit | e9a696b03fc3cd6bae12ae5c50ab8097 | 20.5 | 149 | 0.587855 | 4.3 | false | false | false | false |
alessiobrozzi/firefox-ios | Storage/SQL/DeferredDBOperation.swift | 2 | 3685 | /* 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 Shared
import XCGLogger
import Deferred
private let log = Logger.syncLogger
private let DeferredQueue = DispatchQueue(label: "BrowserDBQueue", attributes: [])
/**
This class is written to mimick an NSOperation, but also provide Deferred capabilities as well.
Usage:
let deferred = DeferredDBOperation({ (db, err) -> Int
// ... Do something long running
return 1
}, withDb: myDb, onQueue: myQueue).start(onQueue: myQueue)
deferred.upon { res in
// if cancelled res.isFailure = true
})
// ... Some time later
deferred.cancel()
*/
class DeferredDBOperation<T>: Deferred<Maybe<T>>, Cancellable {
/// Cancelled is wrapping a ReadWrite lock to make access to it thread-safe.
fileprivate var cancelledLock = LockProtected<Bool>(item: false)
var cancelled: Bool {
get {
return self.cancelledLock.withReadLock({ cancelled -> Bool in
return cancelled
})
}
set {
let _ = cancelledLock.withWriteLock { cancelled -> T? in
cancelled = newValue
return nil
}
}
}
/// Executing is wrapping a ReadWrite lock to make access to it thread-safe.
fileprivate var connectionLock = LockProtected<SQLiteDBConnection?>(item: nil)
fileprivate var connection: SQLiteDBConnection? {
get {
// We want to avoid leaking this connection. If you want access to it,
// you should use a read/write lock directly.
return nil
}
set {
let _ = connectionLock.withWriteLock { connection -> T? in
connection = newValue
return nil
}
}
}
fileprivate var db: SwiftData
fileprivate var block: (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T
init(db: SwiftData, block: @escaping (_ connection: SQLiteDBConnection, _ err: inout NSError?) -> T) {
self.block = block
self.db = db
super.init()
}
func start(onQueue queue: DispatchQueue = DeferredQueue) -> DeferredDBOperation<T> {
queue.async(execute: self.main)
return self
}
fileprivate func main() {
if self.cancelled {
let err = NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"])
fill(Maybe(failure: DatabaseError(err: err)))
return
}
var result: T? = nil
let err = db.withConnection(SwiftData.Flags.readWriteCreate) { (db) -> NSError? in
self.connection = db
if self.cancelled {
return NSError(domain: "mozilla", code: 9, userInfo: [NSLocalizedDescriptionKey: "Operation was cancelled before starting"])
}
var error: NSError? = nil
result = self.block(db, &error)
if error == nil {
log.verbose("Modified rows: \(db.numberOfRowsModified).")
}
self.connection = nil
return error
}
if let result = result {
fill(Maybe(success: result))
return
}
fill(Maybe(failure: DatabaseError(err: err)))
}
func cancel() {
self.cancelled = true
self.connectionLock.withReadLock({ connection -> Void in
connection?.interrupt()
return ()
})
}
}
| mpl-2.0 | 014fc3f3333f9e2bc8e39ce875d9b510 | 31.901786 | 140 | 0.593758 | 4.835958 | false | false | false | false |
rlopezdiez/RLDNavigationSwift | Classes/UINavigationController+RLDNavigationSetup.swift | 1 | 2691 | import UIKit
extension UINavigationController {
func findDestination(navigationSetup navigationSetup:RLDNavigationSetup) -> UIViewController? {
for viewController:UIViewController in Array((viewControllers ).reverse()) {
if viewController.isDestinationOf(navigationSetup) {
return viewController
}
}
return nil
}
}
private extension UIViewController {
func isDestinationOf(navigationSetup:RLDNavigationSetup) -> Bool {
if self.isKindOfClass(NSClassFromString(navigationSetup.destination)!) == false {
return false
}
if let properties = navigationSetup.properties {
for (key, value) in properties {
if has(property:key) && valueForKey(key)!.isEqual(value) == false {
return false
}
}
}
return true
}
}
extension NSObject {
func has(property property:String) -> Bool {
let expectedProperty = objcProperty(name:property)
return expectedProperty != nil
}
func canSet(property property:String) -> Bool {
var canSet = false
let expectedProperty = objcProperty(name:property)
if expectedProperty != nil {
let isReadonly = property_copyAttributeValue(expectedProperty, "R")
canSet = isReadonly == nil
}
return canSet
}
func set(properties properties:[String:AnyObject]?) {
if let properties = properties {
for (key, value) in properties {
if canSet(property:key) {
self.setValue(value, forKey:key)
}
}
}
}
private func objcProperty(name name:String) -> objc_property_t {
if name.characters.count == 0 {
return nil
}
var propertyCount:UInt32 = 0
var sourceClass:AnyClass? = self.dynamicType
repeat {
let objcProperties:UnsafeMutablePointer<objc_property_t> = class_copyPropertyList(sourceClass, &propertyCount)
for index in 0..<Int(propertyCount) {
let property:objc_property_t = objcProperties[index]
let propertyName = NSString(UTF8String:property_getName(property))!
if propertyName == name {
return property
}
}
free(objcProperties)
sourceClass = sourceClass!.superclass()
} while sourceClass != nil
return nil
}
} | apache-2.0 | 10f3e4a88e81b449714dc170a4e1cf61 | 28.26087 | 122 | 0.554069 | 5.469512 | false | false | false | false |
esttorhe/SlackTeamExplorer | SlackTeamExplorer/Pods/Nimble/Nimble/Wrappers/MatcherFunc.swift | 74 | 3742 | /// A convenience API to build matchers that allow full control over
/// to() and toNot() match cases.
///
/// The final bool argument in the closure is if the match is for negation.
///
/// You may use this when implementing your own custom matchers.
///
/// Use the Matcher protocol instead of this type to accept custom matchers as
/// input parameters.
/// @see allPass for an example that uses accepts other matchers as input.
public struct FullMatcherFunc<T>: Matcher {
public let matcher: (Expression<T>, FailureMessage, Bool) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage, Bool) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage, false)
}
public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage, true)
}
}
/// A convenience API to build matchers that don't need special negation
/// behavior. The toNot() behavior is the negation of to().
///
/// @see NonNilMatcherFunc if you prefer to have this matcher fail when nil
/// values are recieved in an expectation.
///
/// You may use this when implementing your own custom matchers.
///
/// Use the Matcher protocol instead of this type to accept custom matchers as
/// input parameters.
/// @see allPass for an example that uses accepts other matchers as input.
public struct MatcherFunc<T>: Matcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return matcher(actualExpression, failureMessage)
}
public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
return !matcher(actualExpression, failureMessage)
}
}
/// A convenience API to build matchers that don't need special negation
/// behavior. The toNot() behavior is the negation of to().
///
/// Unlike MatcherFunc, this will always fail if an expectation contains nil.
/// This applies regardless of using to() or toNot().
///
/// You may use this when implementing your own custom matchers.
///
/// Use the Matcher protocol instead of this type to accept custom matchers as
/// input parameters.
/// @see allPass for an example that uses accepts other matchers as input.
public struct NonNilMatcherFunc<T>: Matcher {
public let matcher: (Expression<T>, FailureMessage) -> Bool
public init(_ matcher: (Expression<T>, FailureMessage) -> Bool) {
self.matcher = matcher
}
public func matches(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let pass = matcher(actualExpression, failureMessage)
if attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) {
return false
}
return pass
}
public func doesNotMatch(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
let pass = !matcher(actualExpression, failureMessage)
if attachNilErrorIfNeeded(actualExpression, failureMessage: failureMessage) {
return false
}
return pass
}
internal func attachNilErrorIfNeeded(actualExpression: Expression<T>, failureMessage: FailureMessage) -> Bool {
if actualExpression.evaluate() == nil {
failureMessage.postfixActual = " (use beNil() to match nils)"
return true
}
return false
}
}
| mit | f410f926d83491f8fa3d487f2861040c | 38.389474 | 115 | 0.69829 | 5.016086 | false | false | false | false |
BareFeetWare/BFWControls | BFWControls/Modules/Transition/View/UIViewController+Segue.swift | 1 | 683 | //
// UIViewController+Segue.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 21/04/2016.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
public extension UIViewController {
func canPerformSegue(identifier: String) -> Bool {
var can = false
if let templates = self.value(forKey: "storyboardSegueTemplates") as? NSArray
{
let predicate = NSPredicate(format: "identifier=%@", identifier)
let filteredtemplates = templates.filtered(using: predicate)
can = !filteredtemplates.isEmpty
}
return can
}
}
| mit | 52e90ffba0f4bcf00b53163133f5d750 | 26.28 | 85 | 0.648094 | 4.577181 | false | false | false | false |
ksco/swift-algorithm-club-cn | Breadth-First Search/BreadthFirstSearch.playground/Pages/Simple example.xcplaygroundpage/Contents.swift | 1 | 1187 | func breadthFirstSearch(graph: Graph, source: Node) -> [String] {
var queue = Queue<Node>()
queue.enqueue(source)
var nodesExplored = [source.label]
source.visited = true
while let node = queue.dequeue() {
for edge in node.neighbors {
let neighborNode = edge.neighbor
if !neighborNode.visited {
queue.enqueue(neighborNode)
neighborNode.visited = true
nodesExplored.append(neighborNode.label)
}
}
}
return nodesExplored
}
let graph = Graph()
let nodeA = graph.addNode("a")
let nodeB = graph.addNode("b")
let nodeC = graph.addNode("c")
let nodeD = graph.addNode("d")
let nodeE = graph.addNode("e")
let nodeF = graph.addNode("f")
let nodeG = graph.addNode("g")
let nodeH = graph.addNode("h")
graph.addEdge(nodeA, neighbor: nodeB)
graph.addEdge(nodeA, neighbor: nodeC)
graph.addEdge(nodeB, neighbor: nodeD)
graph.addEdge(nodeB, neighbor: nodeE)
graph.addEdge(nodeC, neighbor: nodeF)
graph.addEdge(nodeC, neighbor: nodeG)
graph.addEdge(nodeE, neighbor: nodeH)
graph.addEdge(nodeE, neighbor: nodeF)
graph.addEdge(nodeF, neighbor: nodeG)
let nodesExplored = breadthFirstSearch(graph, source: nodeA)
print(nodesExplored)
| mit | 4f70435e9bce48cddcc59dda3e2d345b | 24.255319 | 65 | 0.709351 | 3.532738 | false | false | false | false |
ifels/swiftDemo | SnapKitDrawer/SnapKitDrawer/src/home/HomeController.swift | 1 | 1699 | //
// ViewController.swift
// SnapKitDrawer
//
// Created by 聂鑫鑫 on 16/11/10.
// Copyright © 2016年 ifels. All rights reserved.
//
import UIKit
class HomeController: DPDrawerViewController {
var drawerView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationController?.setNavigationBarHidden(true, animated: true)
initDrawer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initDrawer(){
// 1. get the drawer
// embed in storyboard
let drawer: DPDrawerViewController = self
// not embed in storyboard? add it manually
// let drawer: DPDrawerViewController? = self.storyboard?.instantiateViewController(withIdentifier: "DPDrawerViewController") as? DPDrawerViewController
// self.addChildViewController(drawer!)
// self.view.addSubview(drawer!.view)
// 2. create the first view controller
let homeViewController: ContentController? = ContentController();
// 4. create leftMenuViewController with DPSlideMenuModel array, then reset the drawer
//let leftMenuViewController: DPLeftMenuViewController = DPLeftMenuViewController(slideMenuModels: slideMenuModels, storyboard: self.storyboard)
let menuController: MenuController = MenuController()
drawer.reset(leftViewController: menuController,
centerViewController: homeViewController)
}
}
| apache-2.0 | e214e02476d5d1ef7a8ccd906ccf4482 | 32.137255 | 160 | 0.678107 | 5.522876 | false | false | false | false |
okkhoury/SafeNights_iOS | SafeNights/HistoryController.swift | 1 | 16829 | //
// HistoryController.swift
// SafeNights
//
// Created by Owen Khoury on 5/13/17.
// Copyright © 2017 SafeNights. All rights reserved.
//
import UIKit
import Siesta
import Charts
/**
* Controller for getting history of previous nights.
* Currently just tests that controller can get previous night
* history from database.
*/
class HistoryController: UIViewController {
@IBOutlet weak var moneyChartView: LineChartView!
@IBOutlet weak var alcoholChartView: LineChartView!
@IBOutlet weak var totalSpendingLabel: UILabel!
@IBOutlet weak var monthLabel: UILabel!
@IBOutlet weak var monthStepper: UIStepper!
@IBOutlet weak var loadingMoneyIndicator: UIActivityIndicatorView!
@IBOutlet weak var loadingAlcoholIndicator: UIActivityIndicatorView!
let API = MyAPI()
let preferences = UserDefaults.standard
var allData : [Fields] = []
var monthsDictionary = [String: [Fields]]()
var todayKey : String = ""
var displayMonth : Int = 1
var displayYear : Int = 2017
var totalSpent : Int = 0
//Used to track the months the stepper will go. Starts on max so user can't go into future
var stepperOldVal : Int = 100
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated) // No need for semicolon
// Do any additional setup after loading the view, typically from a nib.
// Clear old data because they can persist from last on appear not load (when user toggles between tabs after initial load
self.allData.removeAll()
self.monthsDictionary.removeAll()
self.totalSpent = 0
//Starts loading indicator while API is called
loadingMoneyIndicator.isHidden = false
loadingAlcoholIndicator.isHidden = false
loadingMoneyIndicator.startAnimating()
loadingAlcoholIndicator.startAnimating()
// Sets up all the styling for the graph
styling()
// Calls API to get the information. Only needs once, it is parsed so can just update dictionary array in future
callGetHistoryAPI()
}
@IBAction func monthStepperAction(_ sender: Any) {
if (Int(monthStepper.value) > stepperOldVal) {
stepperOldVal=stepperOldVal+1;
//Your Code You Wanted To Perform On Increment
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.year = self.displayYear
dateComponents.month = self.displayMonth
let thisCalMonth = calendar.date(from: dateComponents)
let nextCalMonth = calendar.date(byAdding: .month, value: 1, to: thisCalMonth!)
let components = calendar.dateComponents([.year, .month, .day], from: nextCalMonth!)
self.displayMonth = components.month!
self.displayYear = components.year!
monthLabel.text = getMonthFromInt(month: components.month!)
// Update Graph Again
updateGraph()
}
else {
stepperOldVal=stepperOldVal-1;
//Your Code You Wanted To Perform On Decrement
let calendar = Calendar.current
var dateComponents = DateComponents()
dateComponents.year = self.displayYear
dateComponents.month = self.displayMonth
let thisCalMonth = calendar.date(from: dateComponents)
let nextCalMonth = calendar.date(byAdding: .month, value: -1, to: thisCalMonth!)
let components = calendar.dateComponents([.year, .month, .day], from: nextCalMonth!)
self.displayMonth = components.month!
self.displayYear = components.year!
monthLabel.text = getMonthFromInt(month: components.month!)
// Update Graph Again
updateGraph()
}
}
func callGetHistoryAPI() {
let resource = API.getHistory
// Get the global values for username and password
let username = self.preferences.string(forKey: "username")!
let password = self.preferences.string(forKey: "password")!
let postData = ["username": username,
"pwd": password]
resource.request(.post, urlEncoded: postData).onSuccess() { data in
var response = data.jsonDict
let answer = response["alcoholtable"] as! NSArray!
let arr = Alcoholtable.modelsFromDictionaryArray(array: answer!)
for item in arr {
self.allData.append(item.fields!)
}
// Then we parse months. Should only do this once, so after this we can update graph
self.parseDataByMonths()
}.onFailure { _ in
// Display alert to screen to let user know error
let OKAction = UIAlertAction(title: "Ok", style: .default){ (action:UIAlertAction) in
//print("Request failed")
}
let alert = UIAlertController(title: "Warning", message: "Something went wrong :( Make sure you have internet access", preferredStyle: .alert)
alert.addAction(OKAction)
self.present(alert, animated: true, completion: nil)
}
}
func parseDataByMonths() {
let calendar = Calendar.current
for night in allData {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" //Your date format
let day = dateFormatter.date(from: night.day!)
let components = calendar.dateComponents([.year, .month, .day], from: day!)
let key = String(components.month!) + String(components.year!)
if self.monthsDictionary[key] != nil {
// now val is not nil and the Optional has been unwrapped, so use it
self.monthsDictionary[key]?.append(night)
} else {
var newMonth : [Fields] = []
newMonth.append(night)
monthsDictionary[key] = newMonth
}
}
// This is done for a check to make this months graph nicer and not look at future months
let today = Date()
let components = calendar.dateComponents([.year, .month, .day], from: today)
self.displayMonth = components.month!
self.displayYear = components.year!
todayKey = String(components.month!) + String(components.year!)
monthLabel.text = getMonthFromInt(month: components.month!)
//Stop the loading animation. Update graph takes less that 1 second and so can do this now
loadingMoneyIndicator.stopAnimating()
loadingAlcoholIndicator.stopAnimating()
loadingMoneyIndicator.isHidden = true
loadingAlcoholIndicator.isHidden = true
// This should only be called once, so we now update the Graph.
// Note- update graph will be called again every other time when Month is updated
updateGraph()
}
func calculateDrunkness(field : Fields) -> Double {
let total = 100.0*((Double(field.beer!) + Double(field.wine!) + Double(field.hardliquor!) + Double(field.shots!))/40.0)
return Double(total)
}
//Logic for setting up months. Called every time month changed
func updateGraph(){
let thisMonthKey = String(displayMonth) + String(displayYear)
// Null check so no error thrown.
if(monthsDictionary[thisMonthKey] == nil){
// Clears data. No data text is set up in styling()
moneyChartView.clear();
alcoholChartView.clear();
//Change Label so it doesn't show last months spending
totalSpendingLabel.text = "Total= $0"
return
}
//Booleans are to give start and end to month if there is no data for the 1st and 31st
var missing1st = true
var missing31st = true
totalSpent = 0
//Start Charts logic
var money_lineChartEntry = [ChartDataEntry]() //this is the Array that will eventually be displayed on the graph.
var alcohol_lineChartEntry = [ChartDataEntry]()
//here is the for loop
for datapoint in monthsDictionary[thisMonthKey]! {
let alcoholY = calculateDrunkness(field: datapoint)
// Checking for the 1st and 31st
if(getDay(date: datapoint.day!) == 0) {
missing1st = false
} else if(getDay(date: datapoint.day!) == 31) {
missing31st = false
}
let newMoneyEntry = ChartDataEntry(x: getDay(date: datapoint.day!), y: Double(datapoint.money!)) // here we set the X and Y status in a data chart entry
money_lineChartEntry.append(newMoneyEntry) // here we add it to the data set
let newAlcoholEntry = ChartDataEntry(x: getDay(date: datapoint.day!), y: alcoholY) // here we set the X and Y status in a data chart entry
alcohol_lineChartEntry.append(newAlcoholEntry) // here we add it to the data set
totalSpent += datapoint.money!
}
// Set label for total spending
totalSpendingLabel.text = "Total= $" + String(totalSpent)
//Add Missing if Needed
if(missing1st) {
money_lineChartEntry.append(ChartDataEntry(x: 0.0, y: 0.0))
alcohol_lineChartEntry.append(ChartDataEntry(x: 0.0, y: 0.0))
}
if(todayKey != thisMonthKey) {
if(missing31st) {
money_lineChartEntry.append(ChartDataEntry(x: 31.0, y: 0.0))
alcohol_lineChartEntry.append(ChartDataEntry(x: 31.0, y: 0.0))
}
}
//Needs to be sorted to work :)
money_lineChartEntry = money_lineChartEntry.sorted { $0.x < $1.x }
alcohol_lineChartEntry = alcohol_lineChartEntry.sorted { $0.x < $1.x }
let moneySet = LineChartDataSet(values: money_lineChartEntry, label: "money") //Here we convert lineChartEntry to a LineChartDataSet
let alcoholSet = LineChartDataSet(values: alcohol_lineChartEntry, label: "alcohol") //Here we convert lineChartEntry to a LineChartDataSet
// Styling #1 - some of styling needs to be done to the set
moneySet.lineWidth = 3.0
moneySet.circleRadius = 4.0
moneySet.setColor(UIColor.purple)
moneySet.circleColors = [UIColor.purple]
moneySet.circleHoleColor = UIColor.purple
moneySet.drawValuesEnabled = false
alcoholSet.lineWidth = 3.0
alcoholSet.circleRadius = 4.0
alcoholSet.setColor(UIColor.red)
alcoholSet.circleColors = [UIColor.red]
alcoholSet.circleHoleColor = UIColor.red
alcoholSet.drawValuesEnabled = false
// Add the set to the chart, then we style the chart
let moneyData = LineChartData() //This is the object that will be added to the chart
moneyData.addDataSet(moneySet) //Adds the line to the dataSet
let alcoholData = LineChartData() //This is the object that will be added to the chart
alcoholData.addDataSet(alcoholSet) //Adds the line to the dataSet
moneyChartView.data = moneyData //finally - it adds the chart data to the chart and causes an update
alcoholChartView.data = alcoholData
}
func styling() {
// WHAT IF THERE IS NO DATA?!?!?!
moneyChartView.noDataText = "No Data!" + "\n" + "Please record any activity in Confess"
alcoholChartView.noDataText = "No Data!" + "\n" + "Please record any activity in Confess"
moneyChartView.noDataTextColor = UIColor.white
alcoholChartView.noDataTextColor = UIColor.white
// Styling #2
// moneySet.setAxisDependency(YAxis.AxisDependency.LEFT);
// moneyChartView.leftAxis.axisDependency = true
//FIX TOUCH
moneyChartView.isMultipleTouchEnabled = false
moneyChartView.xAxis.drawGridLinesEnabled = false
moneyChartView.leftAxis.drawGridLinesEnabled = false
moneyChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
moneyChartView.rightAxis.enabled = false
moneyChartView.legend.enabled = false
moneyChartView.chartDescription?.enabled = false
moneyChartView.xAxis.axisMinimum = 0.0
moneyChartView.xAxis.axisMaximum = 31.0
moneyChartView.xAxis.labelCount = 3
moneyChartView.leftAxis.labelCount = 5
moneyChartView.xAxis.labelFont.withSize(10.0)
moneyChartView.leftAxis.labelFont.withSize(14.0)
moneyChartView.leftAxis.labelTextColor = UIColor.white
moneyChartView.xAxis.labelTextColor = UIColor.white
moneyChartView.leftAxis.axisLineColor = UIColor.white
moneyChartView.xAxis.axisLineColor = UIColor.white
moneyChartView.backgroundColor = UIColor.black
//Axis Dependency and Touch
alcoholChartView.isMultipleTouchEnabled = false
alcoholChartView.xAxis.drawGridLinesEnabled = false
alcoholChartView.leftAxis.drawGridLinesEnabled = false
alcoholChartView.xAxis.labelPosition = XAxis.LabelPosition.bottom
alcoholChartView.rightAxis.enabled = false
alcoholChartView.legend.enabled = false
alcoholChartView.chartDescription?.enabled = false
alcoholChartView.xAxis.axisMinimum = 0.0
alcoholChartView.xAxis.axisMaximum = 31.0
alcoholChartView.xAxis.labelCount = 3
alcoholChartView.leftAxis.labelCount = 5
alcoholChartView.xAxis.labelFont.withSize(10.0)
alcoholChartView.leftAxis.labelFont.withSize(14.0)
alcoholChartView.leftAxis.labelTextColor = UIColor.white
alcoholChartView.xAxis.labelTextColor = UIColor.white
alcoholChartView.leftAxis.axisLineColor = UIColor.white
alcoholChartView.xAxis.axisLineColor = UIColor.white
alcoholChartView.backgroundColor = UIColor.black
//Styling #3 - Axis Scaling and Such
//moneyChartView.autoScaleMinMaxEnabled = true
moneyChartView.leftAxis.axisMinimum = 0.0
moneyChartView.leftAxis.axisMaximum = 200.0
moneyChartView.leftAxis.valueFormatter = DollarFormatter()
alcoholChartView.leftAxis.axisMinimum = 0.0
alcoholChartView.leftAxis.axisMaximum = 100.0
alcoholChartView.leftAxis.valueFormatter = PercentFormatter()
}
class DollarFormatter: NSObject, IAxisValueFormatter {
let numFormatter: NumberFormatter
override init() {
numFormatter = NumberFormatter()
numFormatter.minimumFractionDigits = 0
numFormatter.maximumFractionDigits = 1
// if number is less than 1 add 0 before decimal
numFormatter.minimumIntegerDigits = 1 // how many digits do want before decimal
numFormatter.paddingPosition = .beforePrefix
numFormatter.paddingCharacter = "0"
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return "$" + numFormatter.string(from: NSNumber(floatLiteral: value))!
}
}
class PercentFormatter: NSObject, IAxisValueFormatter {
let numFormatter: NumberFormatter
override init() {
numFormatter = NumberFormatter()
numFormatter.minimumFractionDigits = 0
numFormatter.maximumFractionDigits = 1
// if number is less than 1 add 0 before decimal
numFormatter.minimumIntegerDigits = 1 // how many digits do want before decimal
numFormatter.paddingPosition = .beforePrefix
numFormatter.paddingCharacter = "0"
}
public func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return numFormatter.string(from: NSNumber(floatLiteral: value))! + "%"
}
}
func getDay(date : String) -> Double {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" //Your date format
let day = dateFormatter.date(from: date)
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: day!)
return Double(components.day!)
}
func getMonthFromInt(month : Int) -> String {
let dateFormatter: DateFormatter = DateFormatter()
let months = dateFormatter.shortMonthSymbols
let monthSymbol = months?[month-1]
return monthSymbol!
}
}
| mit | b8ddd8c3c855772f4e2b21cbc7656372 | 43.518519 | 164 | 0.638757 | 5.16038 | false | false | false | false |
sdhzwm/BaiSI-Swift- | BaiSi/Pods/Kingfisher/Kingfisher/UIImageView+Kingfisher.swift | 1 | 10593 | //
// UIImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Set Images
/**
* Set image to use from web.
*/
public extension UIImageView {
/**
Set an image with a URL.
It will ask for Kingfisher's manager to get the image for the URL.
The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this URL and store it for next use.
- parameter URL: The URL of image.
- returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: nil, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL and a placeholder image.
- parameter URL: The URL of image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placaholder image and options.
- parameter URL: The URL of image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: nil)
}
/**
Set an image with a URL, a placeholder image, options and completion handler.
- parameter URL: The URL of image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: optionsInfo, progressBlock: nil, completionHandler: completionHandler)
}
/**
Set an image with a URL, a placeholder image, options, progress handler and completion handler.
- parameter URL: The URL of image.
- parameter placeholderImage: A placeholder image when retrieving the image at URL.
- parameter optionsInfo: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retriving process.
*/
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
let showIndicatorWhenLoading = kf_showIndicatorWhenLoading
var indicator: UIActivityIndicatorView? = nil
if showIndicatorWhenLoading {
indicator = kf_indicator
indicator?.hidden = false
indicator?.startAnimating()
}
image = placeholderImage
kf_setWebURL(URL)
let task = KingfisherManager.sharedManager.retrieveImageWithURL(URL, optionsInfo: optionsInfo, progressBlock: { (receivedSize, totalSize) -> () in
if let progressBlock = progressBlock {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
progressBlock(receivedSize: receivedSize, totalSize: totalSize)
})
}
}, completionHandler: {[weak self] (image, error, cacheType, imageURL) -> () in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if let sSelf = self where imageURL == sSelf.kf_webURL && image != nil {
sSelf.image = image;
indicator?.stopAnimating()
}
completionHandler?(image: image, error: error, cacheType: cacheType, imageURL: imageURL)
})
})
return task
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var showIndicatorWhenLoadingKey: Void?
public extension UIImageView {
/// Get the image URL binded to this image view.
public var kf_webURL: NSURL? {
get {
return objc_getAssociatedObject(self, &lastURLKey) as? NSURL
}
}
private func kf_setWebURL(URL: NSURL) {
objc_setAssociatedObject(self, &lastURLKey, URL, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Whether show an animating indicator when the image view is loading an image or not.
/// Default is false.
public var kf_showIndicatorWhenLoading: Bool {
get {
if let result = objc_getAssociatedObject(self, &showIndicatorWhenLoadingKey) as? NSNumber {
return result.boolValue
} else {
return false
}
}
set {
if kf_showIndicatorWhenLoading == newValue {
return
} else {
if newValue {
let indicator = UIActivityIndicatorView(activityIndicatorStyle:.Gray)
indicator.center = center
indicator.autoresizingMask = [.FlexibleLeftMargin, .FlexibleRightMargin, .FlexibleBottomMargin, .FlexibleTopMargin]
indicator.hidden = true
indicator.hidesWhenStopped = true
self.addSubview(indicator)
kf_setIndicator(indicator)
} else {
kf_indicator?.removeFromSuperview()
kf_setIndicator(nil)
}
objc_setAssociatedObject(self, &showIndicatorWhenLoadingKey, NSNumber(bool: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
/// The indicator view showing when loading. This will be `nil` if `kf_showIndicatorWhenLoading` is false.
/// You may want to use this to set the indicator style or color when you set `kf_showIndicatorWhenLoading` to true.
public var kf_indicator: UIActivityIndicatorView? {
get {
return objc_getAssociatedObject(self, &indicatorKey) as? UIActivityIndicatorView
}
}
private func kf_setIndicator(indicator: UIActivityIndicatorView?) {
objc_setAssociatedObject(self, &indicatorKey, indicator, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated
public extension UIImageView {
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: nil)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: nil, completionHandler: completionHandler)
}
@available(*, deprecated=1.2, message="Use -kf_setImageWithURL:placeholderImage:optionsInfo:progressBlock:completionHandler: instead.")
public func kf_setImageWithURL(URL: NSURL,
placeholderImage: UIImage?,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return kf_setImageWithURL(URL, placeholderImage: placeholderImage, optionsInfo: [.Options: options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| apache-2.0 | 4ebc52b134e3c7adb0b7cb821c745b85 | 42.413934 | 176 | 0.641461 | 5.601798 | false | false | false | false |
josve05a/wikipedia-ios | Wikipedia/Code/ArticlePlaceView.swift | 1 | 22597 | import UIKit
import WMF
import MapKit
protocol ArticlePlaceViewDelegate: NSObjectProtocol {
func articlePlaceViewWasTapped(_ articlePlaceView: ArticlePlaceView)
}
class ArticlePlaceView: MapAnnotationView {
static let smallDotImage = #imageLiteral(resourceName: "places-dot-small")
static let mediumDotImage = #imageLiteral(resourceName: "places-dot-medium")
static let mediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-medium-opaque")
static let mediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-medium")
static let extraMediumOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-medium-opaque")
static let extraMediumOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-medium")
static let largeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-large-opaque")
static let largeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-large")
static let extraLargeOpaqueDotImage = #imageLiteral(resourceName: "places-dot-extra-large-opaque")
static let extraLargeOpaqueDotOutlineImage = #imageLiteral(resourceName: "places-dot-outline-extra-large ")
static let mediumPlaceholderImage = #imageLiteral(resourceName: "places-w-medium")
static let largePlaceholderImage = #imageLiteral(resourceName: "places-w-large")
static let extraMediumPlaceholderImage = #imageLiteral(resourceName: "places-w-extra-medium")
static let extraLargePlaceholderImage = #imageLiteral(resourceName: "places-w-extra-large")
public weak var delegate: ArticlePlaceViewDelegate?
var imageView: UIView!
private var imageImageView: UIImageView!
private var imageImagePlaceholderView: UIImageView!
private var imageOutlineView: UIView!
private var imageBackgroundView: UIView!
private var selectedImageView: UIView!
private var selectedImageImageView: UIImageView!
private var selectedImageImagePlaceholderView: UIImageView!
private var selectedImageOutlineView: UIView!
private var selectedImageBackgroundView: UIView!
private var dotView: UIView!
private var groupView: UIView!
private var countLabel: UILabel!
private var dimension: CGFloat!
private var collapsedDimension: CGFloat!
var groupDimension: CGFloat!
var imageDimension: CGFloat!
var selectedImageButton: UIButton!
private var alwaysShowImage = false
private let selectionAnimationDuration = 0.3
private let springDamping: CGFloat = 0.5
private let crossFadeRelativeHalfDuration: TimeInterval = 0.1
private let alwaysRasterize = true // set this or rasterize on animations, not both
private let rasterizeOnAnimations = false
override func setup() {
selectedImageView = UIView()
imageView = UIView()
selectedImageImageView = UIImageView()
imageImageView = UIImageView()
selectedImageImageView.accessibilityIgnoresInvertColors = true
imageImageView.accessibilityIgnoresInvertColors = true
countLabel = UILabel()
dotView = UIView()
groupView = UIView()
imageOutlineView = UIView()
selectedImageOutlineView = UIView()
imageBackgroundView = UIView()
selectedImageBackgroundView = UIView()
selectedImageButton = UIButton()
imageImagePlaceholderView = UIImageView()
selectedImageImagePlaceholderView = UIImageView()
let scale = ArticlePlaceView.mediumDotImage.scale
let mediumOpaqueDotImage = ArticlePlaceView.mediumOpaqueDotImage
let mediumOpaqueDotOutlineImage = ArticlePlaceView.mediumOpaqueDotOutlineImage
let largeOpaqueDotImage = ArticlePlaceView.largeOpaqueDotImage
let largeOpaqueDotOutlineImage = ArticlePlaceView.largeOpaqueDotOutlineImage
let mediumPlaceholderImage = ArticlePlaceView.mediumPlaceholderImage
let largePlaceholderImage = ArticlePlaceView.largePlaceholderImage
collapsedDimension = ArticlePlaceView.smallDotImage.size.width
groupDimension = ArticlePlaceView.mediumDotImage.size.width
dimension = largeOpaqueDotOutlineImage.size.width
imageDimension = mediumOpaqueDotOutlineImage.size.width
let gravity = CALayerContentsGravity.bottomRight
isPlaceholderHidden = false
frame = CGRect(x: 0, y: 0, width: dimension, height: dimension)
dotView.bounds = CGRect(x: 0, y: 0, width: collapsedDimension, height: collapsedDimension)
dotView.layer.contentsGravity = gravity
dotView.layer.contentsScale = scale
dotView.layer.contents = ArticlePlaceView.smallDotImage.cgImage
dotView.center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height)
addSubview(dotView)
groupView.bounds = CGRect(x: 0, y: 0, width: groupDimension, height: groupDimension)
groupView.layer.contentsGravity = gravity
groupView.layer.contentsScale = scale
groupView.layer.contents = ArticlePlaceView.mediumDotImage.cgImage
addSubview(groupView)
imageView.bounds = CGRect(x: 0, y: 0, width: imageDimension, height: imageDimension)
imageView.layer.rasterizationScale = scale
addSubview(imageView)
imageBackgroundView.frame = imageView.bounds
imageBackgroundView.layer.contentsGravity = gravity
imageBackgroundView.layer.contentsScale = scale
imageBackgroundView.layer.contents = mediumOpaqueDotImage.cgImage
imageView.addSubview(imageBackgroundView)
imageImagePlaceholderView.frame = imageView.bounds
imageImagePlaceholderView.contentMode = .center
imageImagePlaceholderView.image = mediumPlaceholderImage
imageView.addSubview(imageImagePlaceholderView)
var inset: CGFloat = 3.5
var imageViewFrame = imageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset))
imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset)
imageImageView.frame = imageViewFrame
imageImageView.contentMode = .scaleAspectFill
imageImageView.layer.masksToBounds = true
imageImageView.layer.cornerRadius = imageImageView.bounds.size.width * 0.5
imageImageView.backgroundColor = UIColor.white
imageView.addSubview(imageImageView)
imageOutlineView.frame = imageView.bounds
imageOutlineView.layer.contentsGravity = gravity
imageOutlineView.layer.contentsScale = scale
imageOutlineView.layer.contents = mediumOpaqueDotOutlineImage.cgImage
imageView.addSubview(imageOutlineView)
selectedImageView.bounds = bounds
selectedImageView.layer.rasterizationScale = scale
addSubview(selectedImageView)
selectedImageBackgroundView.frame = selectedImageView.bounds
selectedImageBackgroundView.layer.contentsGravity = gravity
selectedImageBackgroundView.layer.contentsScale = scale
selectedImageBackgroundView.layer.contents = largeOpaqueDotImage.cgImage
selectedImageView.addSubview(selectedImageBackgroundView)
selectedImageImagePlaceholderView.frame = selectedImageView.bounds
selectedImageImagePlaceholderView.contentMode = .center
selectedImageImagePlaceholderView.image = largePlaceholderImage
selectedImageView.addSubview(selectedImageImagePlaceholderView)
inset = imageDimension > 40 ? 3.5 : 5.5
imageViewFrame = selectedImageView.bounds.inset(by: UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset))
imageViewFrame.origin = CGPoint(x: frame.origin.x + inset, y: frame.origin.y + inset)
selectedImageImageView.frame = imageViewFrame
selectedImageImageView.contentMode = .scaleAspectFill
selectedImageImageView.layer.cornerRadius = selectedImageImageView.bounds.size.width * 0.5
selectedImageImageView.layer.masksToBounds = true
selectedImageImageView.backgroundColor = UIColor.white
selectedImageView.addSubview(selectedImageImageView)
selectedImageOutlineView.frame = selectedImageView.bounds
selectedImageOutlineView.layer.contentsGravity = gravity
selectedImageOutlineView.layer.contentsScale = scale
selectedImageOutlineView.layer.contents = largeOpaqueDotOutlineImage.cgImage
selectedImageView.addSubview(selectedImageOutlineView)
selectedImageButton.frame = selectedImageView.bounds
selectedImageButton.accessibilityTraits = UIAccessibilityTraits.none
selectedImageView.addSubview(selectedImageButton)
countLabel.frame = groupView.bounds
countLabel.textColor = UIColor.white
countLabel.textAlignment = .center
countLabel.font = UIFont.boldSystemFont(ofSize: 16)
groupView.addSubview(countLabel)
prepareForReuse()
super.setup()
updateLayout()
update(withArticlePlace: annotation as? ArticlePlace)
}
func set(alwaysShowImage: Bool, animated: Bool) {
self.alwaysShowImage = alwaysShowImage
let scale = collapsedDimension/imageDimension
let imageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale)
let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/scale, y: 1.0/scale)
if alwaysShowImage {
loadImage()
imageView.alpha = 0
imageView.isHidden = false
dotView.alpha = 1
dotView.isHidden = false
imageView.transform = imageViewScaleDownTransform
dotView.transform = CGAffineTransform.identity
} else {
dotView.transform = dotViewScaleUpTransform
imageView.transform = CGAffineTransform.identity
imageView.alpha = 1
imageView.isHidden = false
dotView.alpha = 0
dotView.isHidden = false
}
let transforms = {
if alwaysShowImage {
self.imageView.transform = CGAffineTransform.identity
self.dotView.transform = dotViewScaleUpTransform
} else {
self.imageView.transform = imageViewScaleDownTransform
self.dotView.transform = CGAffineTransform.identity
}
}
let fadesIn = {
if alwaysShowImage {
self.imageView.alpha = 1
} else {
self.dotView.alpha = 1
}
}
let fadesOut = {
if alwaysShowImage {
self.dotView.alpha = 0
} else {
self.imageView.alpha = 0
}
}
if (animated && rasterizeOnAnimations) {
self.imageView.layer.shouldRasterize = true
}
let done = {
if (animated && self.rasterizeOnAnimations) {
self.imageView.layer.shouldRasterize = false
}
guard let articlePlace = self.annotation as? ArticlePlace else {
return
}
self.updateDotAndImageHiddenState(with: articlePlace.articles.count)
}
if animated {
if alwaysShowImage {
UIView.animate(withDuration: 2*selectionAnimationDuration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil)
UIView.animateKeyframes(withDuration: 2*selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut)
}) { (didFinish) in
done()
}
} else {
UIView.animateKeyframes(withDuration: selectionAnimationDuration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms)
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut)
}) { (didFinish) in
done()
}
}
} else {
transforms()
fadesIn()
fadesOut()
done()
}
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
guard superview != nil else {
selectedImageButton.removeTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside)
return
}
selectedImageButton.addTarget(self, action: #selector(selectedImageViewWasTapped), for: .touchUpInside)
}
@objc func selectedImageViewWasTapped(_ sender: UIButton) {
delegate?.articlePlaceViewWasTapped(self)
}
var zPosition: CGFloat = 1 {
didSet {
guard !isSelected else {
return
}
layer.zPosition = zPosition
}
}
var isPlaceholderHidden: Bool = true {
didSet {
selectedImageImagePlaceholderView.isHidden = isPlaceholderHidden
imageImagePlaceholderView.isHidden = isPlaceholderHidden
imageImageView.isHidden = !isPlaceholderHidden
selectedImageImageView.isHidden = !isPlaceholderHidden
}
}
private var shouldRasterize = false {
didSet {
imageView.layer.shouldRasterize = shouldRasterize
selectedImageView.layer.shouldRasterize = shouldRasterize
}
}
private var isImageLoaded = false
func loadImage() {
guard !isImageLoaded, let articlePlace = annotation as? ArticlePlace, articlePlace.articles.count == 1 else {
return
}
if alwaysRasterize {
shouldRasterize = false
}
isPlaceholderHidden = false
isImageLoaded = true
let article = articlePlace.articles[0]
if let thumbnailURL = article.thumbnailURL {
imageImageView.wmf_setImage(with: thumbnailURL, detectFaces: true, onGPU: true, failure: { (error) in
if self.alwaysRasterize {
self.shouldRasterize = true
}
}, success: {
self.selectedImageImageView.image = self.imageImageView.image
self.selectedImageImageView.layer.contentsRect = self.imageImageView.layer.contentsRect
self.isPlaceholderHidden = true
if self.alwaysRasterize {
self.shouldRasterize = true
}
})
}
}
func update(withArticlePlace articlePlace: ArticlePlace?) {
let articleCount = articlePlace?.articles.count ?? 1
switch articleCount {
case 0:
zPosition = 1
isPlaceholderHidden = false
imageImagePlaceholderView.image = #imageLiteral(resourceName: "places-show-more")
accessibilityLabel = WMFLocalizedString("places-accessibility-show-more", value:"Show more articles", comment:"Accessibility label for a button that shows more articles")
case 1:
zPosition = 1
isImageLoaded = false
if isSelected || alwaysShowImage {
loadImage()
}
accessibilityLabel = articlePlace?.articles.first?.displayTitle
default:
zPosition = 2
let countString = "\(articleCount)"
countLabel.text = countString
accessibilityLabel = String.localizedStringWithFormat(WMFLocalizedString("places-accessibility-group", value:"%1$@ articles", comment:"Accessibility label for a map icon - %1$@ is replaced with the number of articles in the group {{Identical|Article}}"), countString)
}
updateDotAndImageHiddenState(with: articleCount)
}
func updateDotAndImageHiddenState(with articleCount: Int) {
switch articleCount {
case 0:
fallthrough
case 1:
imageView.isHidden = !alwaysShowImage
dotView.isHidden = alwaysShowImage
groupView.isHidden = true
default:
imageView.isHidden = true
dotView.isHidden = true
groupView.isHidden = false
}
}
override var annotation: MKAnnotation? {
didSet {
guard isSetup, let articlePlace = annotation as? ArticlePlace else {
return
}
update(withArticlePlace: articlePlace)
}
}
override func prepareForReuse() {
super.prepareForReuse()
if alwaysRasterize {
shouldRasterize = false
}
isPlaceholderHidden = false
isImageLoaded = false
delegate = nil
imageImageView.wmf_reset()
selectedImageImageView.wmf_reset()
countLabel.text = nil
set(alwaysShowImage: false, animated: false)
setSelected(false, animated: false)
alpha = 1
transform = CGAffineTransform.identity
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
guard let place = annotation as? ArticlePlace, place.articles.count == 1 else {
selectedImageView.alpha = 0
return
}
let dotScale = collapsedDimension/dimension
let imageViewScale = imageDimension/dimension
let scale = alwaysShowImage ? imageViewScale : dotScale
let selectedImageViewScaleDownTransform = CGAffineTransform(scaleX: scale, y: scale)
let dotViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/dotScale, y: 1.0/dotScale)
let imageViewScaleUpTransform = CGAffineTransform(scaleX: 1.0/imageViewScale, y: 1.0/imageViewScale)
layer.zPosition = 3
if selected {
loadImage()
selectedImageView.transform = selectedImageViewScaleDownTransform
dotView.transform = CGAffineTransform.identity
imageView.transform = CGAffineTransform.identity
selectedImageView.alpha = 0
imageView.alpha = 1
dotView.alpha = 1
} else {
selectedImageView.transform = CGAffineTransform.identity
dotView.transform = dotViewScaleUpTransform
imageView.transform = imageViewScaleUpTransform
selectedImageView.alpha = 1
imageView.alpha = 0
dotView.alpha = 0
}
let transforms = {
if selected {
self.selectedImageView.transform = CGAffineTransform.identity
self.dotView.transform = dotViewScaleUpTransform
self.imageView.transform = imageViewScaleUpTransform
} else {
self.selectedImageView.transform = selectedImageViewScaleDownTransform
self.dotView.transform = CGAffineTransform.identity
self.imageView.transform = CGAffineTransform.identity
}
}
let fadesIn = {
if selected {
self.selectedImageView.alpha = 1
} else {
self.imageView.alpha = 1
self.dotView.alpha = 1
}
}
let fadesOut = {
if selected {
self.imageView.alpha = 0
self.dotView.alpha = 0
} else {
self.selectedImageView.alpha = 0
}
}
if (animated && rasterizeOnAnimations) {
shouldRasterize = true
}
let done = {
if (animated && self.rasterizeOnAnimations) {
self.shouldRasterize = false
}
if !selected {
self.layer.zPosition = self.zPosition
}
}
if animated {
let duration = 2*selectionAnimationDuration
if selected {
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: springDamping, initialSpringVelocity: 0, options: [.allowUserInteraction], animations: transforms, completion:nil)
UIView.animateKeyframes(withDuration: duration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: self.crossFadeRelativeHalfDuration, relativeDuration: self.crossFadeRelativeHalfDuration, animations:fadesOut)
}) { (didFinish) in
done()
}
} else {
UIView.animateKeyframes(withDuration: 0.5*duration, delay: 0, options: [.allowUserInteraction], animations: {
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 1, animations:transforms)
UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5, animations:fadesIn)
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5, animations:fadesOut)
}) { (didFinish) in
done()
}
}
} else {
transforms()
fadesIn()
fadesOut()
done()
}
}
func updateLayout() {
let center = CGPoint(x: 0.5*bounds.size.width, y: 0.5*bounds.size.height)
selectedImageView.center = center
imageView.center = center
dotView.center = center
groupView.center = center
}
override var frame: CGRect {
didSet {
guard isSetup else {
return
}
updateLayout()
}
}
override var bounds: CGRect {
didSet {
guard isSetup else {
return
}
updateLayout()
}
}
}
| mit | b4f117f5f1b0dfa6a72fcc037c0dce10 | 41.635849 | 279 | 0.646502 | 6.264763 | false | false | false | false |
mrdepth/Neocom | Legacy/Neocom/Neocom/UIColor+NC.swift | 2 | 1216 | //
// UIColor+NC.swift
// Neocom
//
// Created by Artem Shimanski on 14.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(security: Float) {
if security >= 1.0 {
self.init(number: 0x2FEFEFFF)
}
else if security >= 0.9 {
self.init(number: 0x48F0C0FF)
}
else if security >= 0.8 {
self.init(number: 0x00EF47FF)
}
else if security >= 0.7 {
self.init(number: 0x00F000FF)
}
else if security >= 0.6 {
self.init(number: 0x8FEF2FFF)
}
else if security >= 0.5 {
self.init(number: 0xEFEF00FF)
}
else if security >= 0.4 {
self.init(number: 0xD77700FF)
}
else if security >= 0.3 {
self.init(number: 0xF06000FF)
}
else if security >= 0.2 {
self.init(number: 0xF04800FF)
}
else if security >= 0.1 {
self.init(number: 0xD73000FF)
}
else {
self.init(number: 0xF00000FF)
}
}
var css:String {
let rgba = UnsafeMutablePointer<CGFloat>.allocate(capacity: 4)
defer {rgba.deallocate(capacity: 4)}
getRed(&rgba[0], green: &rgba[1], blue: &rgba[2], alpha: &rgba[3])
return String(format: "#%.2x%.2x%.2x", Int(rgba[0] * 255.0), Int(rgba[1] * 255.0), Int(rgba[2] * 255.0))
}
}
| lgpl-2.1 | 01e8e975987deb68a91b71263b27ab98 | 21.5 | 106 | 0.62963 | 2.510331 | false | false | false | false |
Decybel07/L10n-swift | Source/Core/Plural/Plural.swift | 1 | 3670 | //
// Plural.swift
// L10n_swift
//
// Created by Adrian Bobrowski on 09.11.2017.
// Copyright © 2017 Adrian Bobrowski (Decybel07), [email protected]. All rights reserved.
//
import Foundation
internal enum Plural: String {
case zero
case one
case two
case few
case many
case other
case floating
}
extension Plural {
private static let format = Plural.createFormat()
static func variants(for number: NSNumber, with locale: Locale?) -> [Plural] {
var variants: [Plural] = []
if Double(number.int64Value) != number.doubleValue {
variants.append(.floating)
}
let format = String(format: self.format, locale: locale, number.int64Value)
variants.append(contentsOf: self.variants(base: Plural(rawValue: format), alternative: .other))
if variants.last != .other {
variants.append(.other)
}
return variants
}
private static func variants(base: Plural?, alternative: Plural) -> [Plural] {
let variant = base ?? alternative
return variant == alternative ? [alternative] : [variant, alternative]
}
private static func createFormat() -> String {
let table = "Plural"
let `extension` = "stringsdict"
#if SWIFT_PACKAGE
var bundle = Bundle.module
#else
var bundle = Bundle(for: L10n.self)
#endif
if bundle.url(forResource: table, withExtension: `extension`) == nil {
self.createFileIfNeeded(table: table, extension: `extension`, bundle: &bundle)
}
return bundle.localizedString(forKey: "integer", value: "other", table: table)
}
/**
This is temporary solution for Swift Package Manager.
- SeeAlso:
[Issue #21](https://github.com/Decybel07/L10n-swift/issues/21)
*/
private static func createFileIfNeeded(table: String, `extension`: String, bundle: inout Bundle) {
let subdirectory = "spmResources"
if bundle.url(forResource: table, withExtension: `extension`, subdirectory: subdirectory) == nil {
let baseUrl = bundle.bundleURL.appendingPathComponent(subdirectory)
let url = baseUrl.appendingPathComponent(table).appendingPathExtension(`extension`)
let fileContent = """
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>integer</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@value@</string>
<key>value</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>ld</string>
<key>zero</key>
<string>zero</string>
<key>one</key>
<string>one</string>
<key>two</key>
<string>two</string>
<key>few</key>
<string>few</string>
<key>many</key>
<string>many</string>
<key>other</key>
<string>other</string>
</dict>
</dict>
</dict>
</plist>
"""
do {
try FileManager.default.createDirectory(at: baseUrl, withIntermediateDirectories: true)
try fileContent.write(to: url, atomically: true, encoding: .utf8)
bundle = Bundle(url: baseUrl) ?? bundle
} catch {
L10n.shared.logger?.log("Can't create \(url): \(error.localizedDescription)")
}
}
}
}
| mit | 5212a1053abe7a4a5f55fd9becc326d0 | 31.469027 | 106 | 0.592259 | 4.217241 | false | false | false | false |