repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
lukejmann/FBLA2017 | FBLA2017/WalkthroughContainerViewController.swift | 1 | 1646 | //
// WalkthroughMainViewController.swift
// FBLA2017
//
// Created by Luke Mann on 5/7/17.
// Copyright © 2017 Luke Mann. All rights reserved.
//
import UIKit
protocol WalkthroughDismissedDelegate {
func walkthroughDismissed()
}
//Class to control and contain the walkthrough pages
class WalkthroughMainViewController: UIViewController, UIPageViewControllerDelegate, PageControlDelegate {
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var pageIndicator: UIPageControl!
var pages = [UIViewController]()
var delegate: WalkthroughDismissedDelegate?
override func viewDidLoad() {
super.viewDidLoad()
doneButton.layer.cornerRadius = doneButton.layer.frame.height / 2
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "mainWTtoPages" {
let vc = segue.destination as! WalkthroughPageViewController
vc.pageControlDelegate = self
}
}
func update(count: Int, index: Int) {
self.pageIndicator.currentPage = index
self.pageIndicator.numberOfPages = count
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func DoneButtonPressed() {
self.dismiss(animated: true, completion: nil)
delegate?.walkthroughDismissed()
}
}
| mit | 8c5b50e07f6990c573bbcfd0c1266752 | 27.362069 | 106 | 0.694225 | 4.895833 | false | false | false | false |
kagenZhao/cnBeta | iOS/CnBeta/Business Modules/News Module/Home Page/View Model/NewsListViewModel.swift | 1 | 1777 | //
// NewsListViewModel.swift
// CnBeta
//
// Created by 赵国庆 on 2017/8/28.
// Copyright © 2017年 Kagen. All rights reserved.
//
import UIKit
import RxSwift
class NewsListViewModel {
private(set) var page = 1
var limit = 20
var newsList = [ArticleModel]() {
didSet {
lastID = newsList.last?.id
}
}
private var lastID: String?
private let disposeBag = DisposeBag()
init() {
// requestFirstPage()
}
func requestFirstPage() -> Observable<[ArticleModel]> {
let subject = ReplaySubject<[ArticleModel]>.create(bufferSize: 1)
_ = ArticleService.requestHome(limit: limit).subscribe(onNext: { [weak self] res in
guard case let .json(value) = res, self != nil else { return }
let news = value["result"].arrayValue
self!.newsList = ArticleModel.instanceArray(jsons: news)
subject.onNext(self!.newsList)
}, onError: { err in
subject.onError(err)
log.error(err)
})
return subject
}
func requestNextPage() -> Observable<([ArticleModel], noMoreData: Bool)> {
let subject = ReplaySubject<([ArticleModel], noMoreData: Bool)>.create(bufferSize: 1)
_ = ArticleService.requestHome(lastId: lastID, limit: limit).subscribe(onNext: { [weak self] res in
guard self != nil, case let .json(value) = res else { return }
let news = value["result"].arrayValue
self!.newsList = self!.newsList + ArticleModel.instanceArray(jsons: news)
subject.onNext((self!.newsList, noMoreData: news.count < self!.limit))
}, onError: { err in
subject.onError(err)
log.error(err)
})
return subject
}
}
| mit | 115c5f9fa52abcc545462d9f3a42a820 | 32.358491 | 107 | 0.598982 | 4.239808 | false | false | false | false |
dwsjoquist/ELWebService | Source/Core/Mocking.swift | 3 | 6076 | //
// Mocking.swift
// ELWebService
//
// Created by Angelo Di Paolo on 3/1/16.
// Copyright © 2016 WalmartLabs. All rights reserved.
//
import Foundation
// MARK: - MockableResponse
/// Defined an interface for mocking data task result data for a given request.
public protocol MockableDataTaskResult {
/**
Returns data that will be passed to the data task's completion handler
- parameter request: The request that the data task result is responding to.
- returns: Data that will be passed to the completion handler of the task.
*/
func dataTaskResult(_ request: URLRequestEncodable) -> (Data?, URLResponse?, Error?)
}
// MARK: - MockResponse
/// Encapsulates the meta and body data of a response.
public struct MockResponse {
enum MockError: Error {
case invalidURL
}
/// HTTP status code.
public let statusCode: Int
/// Response body data
public var data: Data?
/// Response URL
public var url: URL?
/// HTTP header fields
public var headers: [String : String]?
/// Version of the HTTP response as represented by the server. Typically this is represented as "HTTP/1.1".
public var version: String?
/// Create a mock response with a given status code.
public init(statusCode: Int) {
self.statusCode = statusCode
}
/// Create a mock response with a status code and response body data.
public init(statusCode: Int, data: Data) {
self.init(statusCode: statusCode)
self.data = data
}
/// Create a mocked response with a JSON object to use as the stubbed response body data.
public init(statusCode: Int, json: Any) {
self.init(statusCode: statusCode)
self.data = try? JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions(rawValue: 0))
}
}
extension MockResponse: MockableDataTaskResult {
/// Creates a data task result from the mock response data
public func dataTaskResult(_ request: URLRequestEncodable) -> (Data?, URLResponse?, Error?) {
guard let responseURL = url ?? request.urlRequestValue.url else {
return (nil, nil, MockError.invalidURL as NSError)
}
let response = HTTPURLResponse(url: responseURL, statusCode: statusCode, httpVersion: version, headerFields: headers)
return (data, response, nil)
}
}
extension URLResponse: MockableDataTaskResult {
/// Creates a data task result with NSURLResponse instance as the response parameter
public func dataTaskResult(_ request: URLRequestEncodable) -> (Data?, URLResponse?, Error?) {
return (nil, self, nil)
}
}
// MARK: - Mocking Errors
extension NSError: MockableDataTaskResult {
/// Creates a data task result with NSError instance as the error parameter
public func dataTaskResult(_ request: URLRequestEncodable) -> (Data?, URLResponse?, Error?) {
return (nil, nil, self)
}
}
// MARK: - MockSession
/// Implements the `Session` protocol and provides an API for adding mocked responses as stubs.
open class MockSession: Session {
typealias Stub = (MockableDataTaskResult, (URLRequestEncodable) -> (Bool))
var stubs = [Stub]()
public init() {
}
/// Creates a data task for a given request and calls the completion handler on a background queue.
open func dataTask(request: URLRequestEncodable, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTask {
requestSent(request)
let (data, response, error) = stubbedResponse(request: request)
DispatchQueue.global(qos: .default).async {
completion(data, response, error)
}
return MockDataTask()
}
open func requestSent(_ request: URLRequestEncodable) {
}
// MARK: Stubbing API
/**
Add a stub that will be used as the response of a request.
- parameter response: A mockable data task result that provides the mocked
response value.
- parameter requestMatcher: A matcher closure that determines if the mocked
response is used as a response stub for a given request.
*/
open func addStub(_ response: MockableDataTaskResult, requestMatcher: @escaping (URLRequestEncodable) -> (Bool)) {
stubs.append((response, requestMatcher))
}
/**
Add a stub that will be used as the response of any request.
The added stub will match any request.
- parameter response: A mockable data task result that provides the mocked
response value.
*/
open func addStub(_ response: MockableDataTaskResult) {
stubs.append((response, { _ in return true}))
}
/**
Retrieve a response stub for a given request.
- parameter request: The request that needs a stubbed response.
*/
open func stubbedResponse(request: URLRequestEncodable) -> (Data?, URLResponse?, Error?) {
for (response, matcher) in stubs.reversed() where matcher(request) {
return response.dataTaskResult(request)
}
return (nil, nil, nil)
}
}
// MARK: - Mocked Sessions
/// A MockableSession that records all of the requests that are sent during its lifetime.
open class RequestRecordingSession: MockSession {
/// The requests that were sent during the lifetime of the session.
open fileprivate(set) var recordedRequests = [URLRequestEncodable]()
open override func requestSent(_ request: URLRequestEncodable) {
recordedRequests.append(request)
}
}
// MARK: - Data Task Mocking
/// A concrete implementation of DataTask for mocking purposes.
public final class MockDataTask: DataTask {
fileprivate(set) public var state = URLSessionTask.State.suspended
public init() {
}
public func suspend() {
state = .suspended
}
public func resume() {
state = .running
}
public func cancel() {
state = .canceling
}
}
| mit | cb6e87b3881027f411f51d59465e712c | 30.640625 | 127 | 0.66107 | 4.760972 | false | false | false | false |
diegosanchezr/Chatto | ChattoAdditions/Source/Chat Items/BaseMessage/BaseMessageViewModel.swift | 1 | 4091 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import Foundation
public enum MessageViewModelStatus {
case Success
case Sending
case Failed
}
public extension MessageStatus {
public func viewModelStatus() -> MessageViewModelStatus {
switch self {
case .Success:
return MessageViewModelStatus.Success
case .Failed:
return MessageViewModelStatus.Failed
case .Sending:
return MessageViewModelStatus.Sending
}
}
}
public protocol MessageViewModelProtocol: class { // why class? https://gist.github.com/diegosanchezr/29979d22c995b4180830
var isIncoming: Bool { get }
var showsTail: Bool { get set }
var showsFailedIcon: Bool { get }
var date: String { get }
var status: MessageViewModelStatus { get }
var messageModel: MessageModelProtocol { get }
}
public protocol DecoratedMessageViewModelProtocol: MessageViewModelProtocol {
var messageViewModel: MessageViewModelProtocol { get }
}
extension DecoratedMessageViewModelProtocol {
public var isIncoming: Bool {
return self.messageViewModel.isIncoming
}
public var showsTail: Bool {
get {
return self.messageViewModel.showsTail
}
set {
self.messageViewModel.showsTail = newValue
}
}
public var date: String {
return self.messageViewModel.date
}
public var status: MessageViewModelStatus {
return self.messageViewModel.status
}
public var showsFailedIcon: Bool {
return self.messageViewModel.showsFailedIcon
}
public var messageModel: MessageModelProtocol {
return self.messageViewModel.messageModel
}
}
public class MessageViewModel: MessageViewModelProtocol {
public var isIncoming: Bool {
return self.messageModel.isIncoming
}
public var status: MessageViewModelStatus {
return self.messageModel.status.viewModelStatus()
}
public var showsTail: Bool
public lazy var date: String = {
return self.dateFormatter.stringFromDate(self.messageModel.date)
}()
public let dateFormatter: NSDateFormatter
public private(set) var messageModel: MessageModelProtocol
public init(dateFormatter: NSDateFormatter, showsTail: Bool, messageModel: MessageModelProtocol) {
self.dateFormatter = dateFormatter
self.showsTail = showsTail
self.messageModel = messageModel
}
public var showsFailedIcon: Bool {
return self.status == .Failed
}
}
public class MessageViewModelDefaultBuilder {
public init() {}
static let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateFormat = "HH:mm"
return formatter
}()
public func createMessageViewModel(message: MessageModelProtocol) -> MessageViewModelProtocol {
return MessageViewModel(dateFormatter: self.dynamicType.dateFormatter, showsTail: false, messageModel: message)
}
}
| mit | 5c0758ac126df454259f3cda661ee3bb | 30.713178 | 122 | 0.719873 | 5.001222 | false | false | false | false |
tensorflow/swift-apis | Sources/TensorFlow/Core/Utilities.swift | 1 | 5482 | // Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CTensorFlow
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Windows)
import CRT
#else
import Glibc
#endif
//===------------------------------------------------------------------------------------------===//
// Runtime Checkers
//===------------------------------------------------------------------------------------------===//
/// These checks run in both debug and release modes (while assert() only runs in debug mode), to
/// help shake out more bugs and facilitate debugging in the early project phases. It can be
/// replaced with plain assert() later, when we have a more mature code base.
@usableFromInline
internal func internalConsistencyCheck(
_ predicate: Bool,
_ errMessage: String = "TF runtime assertion failure",
file: StaticString = #file,
line: UInt = #line
) {
guard predicate else {
fatalError(errMessage, file: file, line: line)
}
}
@usableFromInline
internal func checkOk(
_ s: CTFStatus?,
file: StaticString = #file,
line: UInt = #line
) {
internalConsistencyCheck(
TF_GetCode(s) == TF_OK,
String(cString: TF_Message(s)),
file: file,
line: line)
}
//===------------------------------------------------------------------------------------------===//
// Type Aliases
//===------------------------------------------------------------------------------------------===//
// Before assigning a C pointer to one of the pointer type aliases below, caller should check that
// the pointer is not NULL.
/// The `TF_Session *` type.
@usableFromInline
internal typealias CTFSession = OpaquePointer
/// The `TF_Status *` type.
@usableFromInline
internal typealias CTFStatus = OpaquePointer
/// The `TF_Graph*` type.
@usableFromInline
internal typealias CTFGraph = OpaquePointer
/// The `TF_Function*` type.
@usableFromInline
internal typealias CTFFunction = OpaquePointer
/// The `TF_Tensor *` type.
@usableFromInline
internal typealias CTensor = OpaquePointer
/// The `TF_TensorHandle *` type.
///
/// - Note: This is public so that compiler generated code can read/write tensor handles when
/// calling runtime APIs.
public typealias CTensorHandle = OpaquePointer
/// The `TFE_Context *` type.
@usableFromInline
internal typealias CTFEContext = OpaquePointer
/// The `TFE_Op *` type.
@usableFromInline
internal typealias CTFEOp = OpaquePointer
/// The `TF_OperationDescription *` type.
@usableFromInline
internal typealias CTFOperationDescription = OpaquePointer
/// The `TFE_TraceContext *` type.
@usableFromInline
internal typealias CTFETraceContext = OpaquePointer
//===------------------------------------------------------------------------------------------===//
// Logging
//===------------------------------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@usableFromInline internal let stderr = __stderrp
@usableFromInline internal let stdout = __stdoutp
#endif
/// Log to standard error.
@usableFromInline
internal func logToStderr(_ message: StaticString) {
message.utf8Start.withMemoryRebound(to: Int8.self, capacity: message.utf8CodeUnitCount) {
_ = fputs($0, stderr)
}
}
/// Log to standard error.
@usableFromInline
internal func logToStderr(_ message: String) {
_ = fputs(message, stderr)
}
@usableFromInline
internal func debugLog(
_ message: @autoclosure () -> String,
file: StaticString = #file,
line: UInt = #line
) {
if _RuntimeConfig.printsDebugLog {
print("[\(file):\(line)] \(message())")
// This helps dump more log before a crash.
fflush(stdout)
}
}
//===------------------------------------------------------------------------------------------===//
// File Writing
//===------------------------------------------------------------------------------------------===//
/// Given the address of a `TF_Buffer` and a file path, write the buffer's contents to the file.
@usableFromInline
internal func writeContents(of buffer: UnsafePointer<TF_Buffer>, toFile path: String) {
let fp = fopen(path, "w+")
fwrite(buffer.pointee.data, /*size*/ 1, /*count*/ buffer.pointee.length, fp)
fclose(fp)
}
//===------------------------------------------------------------------------------------------===//
// Unit Test Utilities
//===------------------------------------------------------------------------------------------===//
// TODO: Consider revising the call sites where this is necessary to only need UnsafeMutablePointer
// to optional when it is the actual c-api call site.
extension UnsafeMutablePointer where Pointee == CTensorHandle? {
@usableFromInline
init(_ other: UnsafeMutablePointer<CTensorHandle>) {
self.init(other._rawValue)
}
@usableFromInline
init?(_ other: UnsafeMutablePointer<CTensorHandle>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
| apache-2.0 | 9c18b15789d0653f665dc07ccedd3ce6 | 31.05848 | 100 | 0.591755 | 4.705579 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/TextFormattingTableViewCell.swift | 3 | 2060 | class TextFormattingTableViewCell: UITableViewCell {
let topSeparator = UIView()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
addSeparator()
configureSeparator()
backgroundView = UIView()
selectedBackgroundView = UIView()
updateFonts()
}
private func addSeparator() {
topSeparator.translatesAutoresizingMaskIntoConstraints = false
addSubview(topSeparator)
}
private func configureSeparator() {
let topSeparatorHeightConstraint = topSeparator.heightAnchor.constraint(equalToConstant: 1)
let topSeparatorTopConstraint = topSeparator.topAnchor.constraint(equalTo: contentView.topAnchor)
let topSeparatorLeadingConstraint = topSeparator.leadingAnchor.constraint(equalTo: leadingAnchor)
let topSeparatorTrailingConstraint = topSeparator.trailingAnchor.constraint(equalTo: trailingAnchor)
NSLayoutConstraint.activate([
topSeparatorHeightConstraint,
topSeparatorTopConstraint,
topSeparatorLeadingConstraint,
topSeparatorTrailingConstraint
])
}
@IBInspectable var isTopSeparatorHidden: Bool = false {
didSet {
topSeparator.isHidden = isTopSeparatorHidden
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
open func updateFonts() {
}
}
extension TextFormattingTableViewCell: Themeable {
func apply(theme: Theme) {
topSeparator.backgroundColor = theme.colors.border
backgroundView?.backgroundColor = theme.colors.inputAccessoryBackground
selectedBackgroundView?.backgroundColor = theme.colors.inputAccessoryBackground
textLabel?.textColor = theme.colors.primaryText
detailTextLabel?.textColor = theme.colors.primaryText
textLabel?.backgroundColor = .clear
detailTextLabel?.backgroundColor = .clear
}
}
| mit | 9157b229a3004e7cc2991c6b0b6348b4 | 34.517241 | 108 | 0.712621 | 6.477987 | false | false | false | false |
caobo56/Juyou | JuYou/JuYou/Pubilc/Extension/UIView+DDAddition.swift | 1 | 4100 | //
// UIView+DDAddition.swift
// JuYou
//
// Created by caobo56 on 16/5/18.
// Copyright © 2016年 caobo56. All rights reserved.
//
import UIKit
import QuartzCore
/**
几点说明
1)四边按照内正外负,到superView的边框距离
left right top bottom
2)中心点的坐标依照左上角为原点
center centerX centerY
*/
extension UIView{
var left:CGFloat {
return self.frame.origin.x
}
func setLeft(left:CGFloat){
var frame:CGRect = self.frame
frame.origin.x = left
self.frame = frame
}
var right:CGFloat {
return self.frame.origin.x+self.frame.size.width
}
func setRight(right:CGFloat){
var frame:CGRect = self.frame
let spW = self.superview?.width
frame.origin.x = spW!-right-frame.size.width
self.frame = frame
}
var top:CGFloat {
return self.frame.origin.y
}
func setTop(top:CGFloat){
var frame:CGRect = self.frame
frame.origin.y = top
self.frame = frame
}
var bottom:CGFloat {
return self.frame.origin.y+self.frame.size.height
}
func setBottom(bottom:CGFloat){
var frame:CGRect = self.frame
let spH = self.superview?.height
frame.origin.y = spH! - bottom - frame.size.height
self.frame = frame
}
var centerX:CGFloat {
return self.center.x
}
func setCenterX(centerX:CGFloat){
self.center = CGPointMake(centerX, self.center.y)
}
var centerY:CGFloat {
return self.center.y
}
func setCenterY(centerY:CGFloat){
self.center = CGPointMake(self.center.x, centerY)
}
var width:CGFloat {
return self.frame.size.width
}
func setWidth(width:CGFloat){
var frame:CGRect = self.frame
frame.size.width = width
self.frame = frame
}
var height:CGFloat {
return self.frame.size.height
}
func setHeight(height:CGFloat){
var frame:CGRect = self.frame
frame.size.height = height
self.frame = frame
}
var origin:CGPoint {
return self.frame.origin
}
func setOrigin(origin:CGPoint){
var frame:CGRect = self.frame
frame.origin = origin
self.frame = frame
}
var size:CGSize{
return self.frame.size
}
func setSize(size:CGSize){
var frame:CGRect = self.frame
frame.size = size
self.frame = frame
}
func removeAllSubviews(){
while (self.subviews.count != 0){
let child:UIView = self.subviews.last!
child.removeFromSuperview()
}
}
func subviewWithTag(tag:Int) -> AnyObject {
for child:UIView in self.subviews {
if (child.tag == tag) {
return child
}
}
return self
}
func viewController(aClass: AnyClass) -> UIViewController?{
var next=self.superview
while next != nil {
let nextResponder = next?.nextResponder()
if((nextResponder?.isKindOfClass(aClass)) != nil){
return nextResponder as? UIViewController
}else{
next=next?.superview
}
}
return nil
// for(var next=self.superview;(next != nil);next=next?.superview){
// let nextResponder = next?.nextResponder()
// if((nextResponder?.isKindOfClass(aClass)) != nil){
// return nextResponder as? UIViewController
// }
// }
// return nil
}
func setRoundedCorner(cornerRadius:CGFloat){
self.layer.masksToBounds = true
self.layer.cornerRadius = cornerRadius
}
func setborderWidthAndColor(borderWidth:CGFloat,borderColor:UIColor){
self.layer.masksToBounds = true
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.CGColor
}
}
| apache-2.0 | 5353f3caf7d3fd26168b2c9e94658e8a | 20.534759 | 74 | 0.565433 | 4.316184 | false | false | false | false |
yanfeng0107/ios-charts | Charts/Classes/Charts/BarLineChartViewBase.swift | 19 | 59925 | //
// BarLineChartViewBase.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
/// Base-class of LineChart, BarChart, ScatterChart and CandleStickChart.
public class BarLineChartViewBase: ChartViewBase, UIGestureRecognizerDelegate
{
/// the maximum number of entried to which values will be drawn
internal var _maxVisibleValueCount = 100
/// flag that indicates if auto scaling on the y axis is enabled
private var _autoScaleMinMaxEnabled = false
private var _autoScaleLastLowestVisibleXIndex: Int!
private var _autoScaleLastHighestVisibleXIndex: Int!
private var _pinchZoomEnabled = false
private var _doubleTapToZoomEnabled = true
private var _dragEnabled = true
private var _scaleXEnabled = true
private var _scaleYEnabled = true
/// the color for the background of the chart-drawing area (everything behind the grid lines).
public var gridBackgroundColor = UIColor(red: 240/255.0, green: 240/255.0, blue: 240/255.0, alpha: 1.0)
public var borderColor = UIColor.blackColor()
public var borderLineWidth: CGFloat = 1.0
/// flag indicating if the grid background should be drawn or not
public var drawGridBackgroundEnabled = true
/// Sets drawing the borders rectangle to true. If this is enabled, there is no point drawing the axis-lines of x- and y-axis.
public var drawBordersEnabled = false
/// the object representing the labels on the y-axis, this object is prepared
/// in the pepareYLabels() method
internal var _leftAxis: ChartYAxis!
internal var _rightAxis: ChartYAxis!
/// the object representing the labels on the x-axis
internal var _xAxis: ChartXAxis!
internal var _leftYAxisRenderer: ChartYAxisRenderer!
internal var _rightYAxisRenderer: ChartYAxisRenderer!
internal var _leftAxisTransformer: ChartTransformer!
internal var _rightAxisTransformer: ChartTransformer!
internal var _xAxisRenderer: ChartXAxisRenderer!
internal var _tapGestureRecognizer: UITapGestureRecognizer!
internal var _doubleTapGestureRecognizer: UITapGestureRecognizer!
internal var _pinchGestureRecognizer: UIPinchGestureRecognizer!
internal var _panGestureRecognizer: UIPanGestureRecognizer!
/// flag that indicates if a custom viewport offset has been set
private var _customViewPortEnabled = false
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
deinit
{
stopDeceleration()
}
internal override func initialize()
{
super.initialize()
_leftAxis = ChartYAxis(position: .Left)
_rightAxis = ChartYAxis(position: .Right)
_xAxis = ChartXAxis()
_leftAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_rightAxisTransformer = ChartTransformer(viewPortHandler: _viewPortHandler)
_leftYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _leftAxis, transformer: _leftAxisTransformer)
_rightYAxisRenderer = ChartYAxisRenderer(viewPortHandler: _viewPortHandler, yAxis: _rightAxis, transformer: _rightAxisTransformer)
_xAxisRenderer = ChartXAxisRenderer(viewPortHandler: _viewPortHandler, xAxis: _xAxis, transformer: _leftAxisTransformer)
_highlighter = ChartHighlighter(chart: self)
_tapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("tapGestureRecognized:"))
_doubleTapGestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("doubleTapGestureRecognized:"))
_doubleTapGestureRecognizer.numberOfTapsRequired = 2
_pinchGestureRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("pinchGestureRecognized:"))
_panGestureRecognizer = UIPanGestureRecognizer(target: self, action: Selector("panGestureRecognized:"))
_pinchGestureRecognizer.delegate = self
_panGestureRecognizer.delegate = self
self.addGestureRecognizer(_tapGestureRecognizer)
self.addGestureRecognizer(_doubleTapGestureRecognizer)
self.addGestureRecognizer(_pinchGestureRecognizer)
self.addGestureRecognizer(_panGestureRecognizer)
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
_panGestureRecognizer.enabled = _dragEnabled
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let context = UIGraphicsGetCurrentContext()
calcModulus()
if (_xAxisRenderer !== nil)
{
_xAxisRenderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
if (renderer !== nil)
{
renderer!.calcXBounds(chart: self, xAxisModulus: _xAxis.axisLabelModulus)
}
// execute all drawing commands
drawGridBackground(context: context)
if (_leftAxis.isEnabled)
{
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
}
if (_rightAxis.isEnabled)
{
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
}
_xAxisRenderer?.renderAxisLine(context: context)
_leftYAxisRenderer?.renderAxisLine(context: context)
_rightYAxisRenderer?.renderAxisLine(context: context)
if (_autoScaleMinMaxEnabled)
{
let lowestVisibleXIndex = self.lowestVisibleXIndex,
highestVisibleXIndex = self.highestVisibleXIndex
if (_autoScaleLastLowestVisibleXIndex == nil || _autoScaleLastLowestVisibleXIndex != lowestVisibleXIndex ||
_autoScaleLastHighestVisibleXIndex == nil || _autoScaleLastHighestVisibleXIndex != highestVisibleXIndex)
{
calcMinMax()
calculateOffsets()
_autoScaleLastLowestVisibleXIndex = lowestVisibleXIndex
_autoScaleLastHighestVisibleXIndex = highestVisibleXIndex
}
}
// make sure the graph values and grid cannot be drawn outside the content-rect
CGContextSaveGState(context)
CGContextClipToRect(context, _viewPortHandler.contentRect)
if (_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
_xAxisRenderer?.renderGridLines(context: context)
_leftYAxisRenderer?.renderGridLines(context: context)
_rightYAxisRenderer?.renderGridLines(context: context)
renderer?.drawData(context: context)
if (!_xAxis.isDrawLimitLinesBehindDataEnabled)
{
_xAxisRenderer?.renderLimitLines(context: context)
}
if (!_leftAxis.isDrawLimitLinesBehindDataEnabled)
{
_leftYAxisRenderer?.renderLimitLines(context: context)
}
if (!_rightAxis.isDrawLimitLinesBehindDataEnabled)
{
_rightYAxisRenderer?.renderLimitLines(context: context)
}
// if highlighting is enabled
if (valuesToHighlight())
{
renderer?.drawHighlighted(context: context, indices: _indicesToHightlight)
}
// Removes clipping rectangle
CGContextRestoreGState(context)
renderer!.drawExtras(context: context)
_xAxisRenderer.renderAxisLabels(context: context)
_leftYAxisRenderer.renderAxisLabels(context: context)
_rightYAxisRenderer.renderAxisLabels(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
// drawLegend()
drawMarkers(context: context)
drawDescription(context: context)
}
internal func prepareValuePxMatrix()
{
_rightAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_rightAxis.axisRange), chartYMin: _rightAxis.axisMinimum)
_leftAxisTransformer.prepareMatrixValuePx(chartXMin: _chartXMin, deltaX: _deltaX, deltaY: CGFloat(_leftAxis.axisRange), chartYMin: _leftAxis.axisMinimum)
}
internal func prepareOffsetMatrix()
{
_rightAxisTransformer.prepareMatrixOffset(_rightAxis.isInverted)
_leftAxisTransformer.prepareMatrixOffset(_leftAxis.isInverted)
}
public override func notifyDataSetChanged()
{
if (_dataNotSet)
{
return
}
calcMinMax()
_leftAxis?._defaultValueFormatter = _defaultValueFormatter
_rightAxis?._defaultValueFormatter = _defaultValueFormatter
_leftYAxisRenderer?.computeAxis(yMin: _leftAxis.axisMinimum, yMax: _leftAxis.axisMaximum)
_rightYAxisRenderer?.computeAxis(yMin: _rightAxis.axisMinimum, yMax: _rightAxis.axisMaximum)
_xAxisRenderer?.computeAxis(xValAverageLength: _data.xValAverageLength, xValues: _data.xVals)
if (_legend !== nil)
{
_legendRenderer?.computeLegend(_data)
}
calculateOffsets()
setNeedsDisplay()
}
internal override func calcMinMax()
{
if (_autoScaleMinMaxEnabled)
{
_data.calcMinMax(start: lowestVisibleXIndex, end: highestVisibleXIndex)
}
var minLeft = _data.getYMin(.Left)
var maxLeft = _data.getYMax(.Left)
var minRight = _data.getYMin(.Right)
var maxRight = _data.getYMax(.Right)
var leftRange = abs(maxLeft - (_leftAxis.isStartAtZeroEnabled ? 0.0 : minLeft))
var rightRange = abs(maxRight - (_rightAxis.isStartAtZeroEnabled ? 0.0 : minRight))
// in case all values are equal
if (leftRange == 0.0)
{
maxLeft = maxLeft + 1.0
if (!_leftAxis.isStartAtZeroEnabled)
{
minLeft = minLeft - 1.0
}
}
if (rightRange == 0.0)
{
maxRight = maxRight + 1.0
if (!_rightAxis.isStartAtZeroEnabled)
{
minRight = minRight - 1.0
}
}
var topSpaceLeft = leftRange * Double(_leftAxis.spaceTop)
var topSpaceRight = rightRange * Double(_rightAxis.spaceTop)
var bottomSpaceLeft = leftRange * Double(_leftAxis.spaceBottom)
var bottomSpaceRight = rightRange * Double(_rightAxis.spaceBottom)
_chartXMax = Double(_data.xVals.count - 1)
_deltaX = CGFloat(abs(_chartXMax - _chartXMin))
// Consider sticking one of the edges of the axis to zero (0.0)
if _leftAxis.isStartAtZeroEnabled
{
if minLeft < 0.0 && maxLeft < 0.0
{
// If the values are all negative, let's stay in the negative zone
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = 0.0
}
else if minLeft >= 0.0
{
// We have positive values only, stay in the positive zone
_leftAxis.axisMinimum = 0.0
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_leftAxis.axisMinimum = min(0.0, !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft))
_leftAxis.axisMaximum = max(0.0, !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft))
}
}
else
{
// Use the values as they are
_leftAxis.axisMinimum = !isnan(_leftAxis.customAxisMin) ? _leftAxis.customAxisMin : (minLeft - bottomSpaceLeft)
_leftAxis.axisMaximum = !isnan(_leftAxis.customAxisMax) ? _leftAxis.customAxisMax : (maxLeft + topSpaceLeft)
}
if _rightAxis.isStartAtZeroEnabled
{
if minRight < 0.0 && maxRight < 0.0
{
// If the values are all negative, let's stay in the negative zone
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = 0.0
}
else if minRight >= 0.0
{
// We have positive values only, stay in the positive zone
_rightAxis.axisMinimum = 0.0
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
else
{
// Stick the minimum to 0.0 or less, and maximum to 0.0 or more (startAtZero for negative/positive at the same time)
_rightAxis.axisMinimum = min(0.0, !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight))
_rightAxis.axisMaximum = max(0.0, !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight))
}
}
else
{
_rightAxis.axisMinimum = !isnan(_rightAxis.customAxisMin) ? _rightAxis.customAxisMin : (minRight - bottomSpaceRight)
_rightAxis.axisMaximum = !isnan(_rightAxis.customAxisMax) ? _rightAxis.customAxisMax : (maxRight + topSpaceRight)
}
_leftAxis.axisRange = abs(_leftAxis.axisMaximum - _leftAxis.axisMinimum)
_rightAxis.axisRange = abs(_rightAxis.axisMaximum - _rightAxis.axisMinimum)
}
internal override func calculateOffsets()
{
if (!_customViewPortEnabled)
{
var offsetLeft = CGFloat(0.0)
var offsetRight = CGFloat(0.0)
var offsetTop = CGFloat(0.0)
var offsetBottom = CGFloat(0.0)
// setup offsets for legend
if (_legend !== nil && _legend.isEnabled)
{
if (_legend.position == .RightOfChart
|| _legend.position == .RightOfChartCenter)
{
offsetRight += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
if (_legend.position == .LeftOfChart
|| _legend.position == .LeftOfChartCenter)
{
offsetLeft += min(_legend.neededWidth, _viewPortHandler.chartWidth * _legend.maxSizePercent) + _legend.xOffset * 2.0
}
else if (_legend.position == .BelowChartLeft
|| _legend.position == .BelowChartRight
|| _legend.position == .BelowChartCenter)
{
var yOffset = _legend.textHeightMax; // It's possible that we do not need this offset anymore as it is available through the extraOffsets
offsetBottom += min(_legend.neededHeight + yOffset, _viewPortHandler.chartHeight * _legend.maxSizePercent)
}
}
// offsets for y-labels
if (leftAxis.needsOffset)
{
offsetLeft += leftAxis.requiredSize().width
}
if (rightAxis.needsOffset)
{
offsetRight += rightAxis.requiredSize().width
}
if (xAxis.isEnabled && xAxis.isDrawLabelsEnabled)
{
var xlabelheight = xAxis.labelHeight * 2.0
// offsets for x-labels
if (xAxis.labelPosition == .Bottom)
{
offsetBottom += xlabelheight
}
else if (xAxis.labelPosition == .Top)
{
offsetTop += xlabelheight
}
else if (xAxis.labelPosition == .BothSided)
{
offsetBottom += xlabelheight
offsetTop += xlabelheight
}
}
offsetTop += self.extraTopOffset
offsetRight += self.extraRightOffset
offsetBottom += self.extraBottomOffset
offsetLeft += self.extraLeftOffset
var minOffset = CGFloat(10.0)
_viewPortHandler.restrainViewPort(
offsetLeft: max(minOffset, offsetLeft),
offsetTop: max(minOffset, offsetTop),
offsetRight: max(minOffset, offsetRight),
offsetBottom: max(minOffset, offsetBottom))
}
prepareOffsetMatrix()
prepareValuePxMatrix()
}
/// calculates the modulus for x-labels and grid
internal func calcModulus()
{
if (_xAxis === nil || !_xAxis.isEnabled)
{
return
}
if (!_xAxis.isAxisModulusCustom)
{
_xAxis.axisLabelModulus = Int(ceil((CGFloat(_data.xValCount) * _xAxis.labelWidth) / (_viewPortHandler.contentWidth * _viewPortHandler.touchMatrix.a)))
}
if (_xAxis.axisLabelModulus < 1)
{
_xAxis.axisLabelModulus = 1
}
}
public override func getMarkerPosition(#entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let dataSetIndex = highlight.dataSetIndex
var xPos = CGFloat(entry.xIndex)
var yPos = entry.value
if (self.isKindOfClass(BarChartView))
{
var bd = _data as! BarChartData
var space = bd.groupSpace
var x = CGFloat(entry.xIndex * (_data.dataSetCount - 1) + dataSetIndex) + space * CGFloat(entry.xIndex) + space / 2.0
xPos += x
if let barEntry = entry as? BarChartDataEntry
{
if barEntry.values != nil && highlight.range !== nil
{
yPos = highlight.range!.to
}
}
}
// position of the marker depends on selected value index and value
var pt = CGPoint(x: xPos, y: CGFloat(yPos) * _animator.phaseY)
getTransformer(_data.getDataSetByIndex(dataSetIndex)!.axisDependency).pointValueToPixel(&pt)
return pt
}
/// draws the grid background
internal func drawGridBackground(#context: CGContext)
{
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextSaveGState(context)
}
if (drawGridBackgroundEnabled)
{
// draw the grid background
CGContextSetFillColorWithColor(context, gridBackgroundColor.CGColor)
CGContextFillRect(context, _viewPortHandler.contentRect)
}
if (drawBordersEnabled)
{
CGContextSetLineWidth(context, borderLineWidth)
CGContextSetStrokeColorWithColor(context, borderColor.CGColor)
CGContextStrokeRect(context, _viewPortHandler.contentRect)
}
if (drawGridBackgroundEnabled || drawBordersEnabled)
{
CGContextRestoreGState(context)
}
}
/// Returns the Transformer class that contains all matrices and is
/// responsible for transforming values into pixels on the screen and
/// backwards.
public func getTransformer(which: ChartYAxis.AxisDependency) -> ChartTransformer
{
if (which == .Left)
{
return _leftAxisTransformer
}
else
{
return _rightAxisTransformer
}
}
// MARK: - Gestures
private enum GestureScaleAxis
{
case Both
case X
case Y
}
private var _isDragging = false
private var _isScaling = false
private var _gestureScaleAxis = GestureScaleAxis.Both
private var _closestDataSetToTouch: ChartDataSet!
private var _panGestureReachedEdge: Bool = false
private weak var _outerScrollView: UIScrollView?
private var _lastPanPoint = CGPoint() /// This is to prevent using setTranslation which resets velocity
private var _decelerationLastTime: NSTimeInterval = 0.0
private var _decelerationDisplayLink: CADisplayLink!
private var _decelerationVelocity = CGPoint()
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self))
if (h === nil || h!.isEqual(self.lastHighlighted))
{
self.highlightValue(highlight: nil, callDelegate: true)
self.lastHighlighted = nil
}
else
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
@objc private func doubleTapGestureRecognized(recognizer: UITapGestureRecognizer)
{
if (_dataNotSet)
{
return
}
if (recognizer.state == UIGestureRecognizerState.Ended)
{
if (!_dataNotSet && _doubleTapToZoomEnabled)
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(self.bounds.size.height - location.y - _viewPortHandler.offsetBottom)
}
self.zoom(isScaleXEnabled ? 1.4 : 1.0, scaleY: isScaleYEnabled ? 1.4 : 1.0, x: location.x, y: location.y)
}
}
}
@objc private func pinchGestureRecognized(recognizer: UIPinchGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began)
{
stopDeceleration()
if (!_dataNotSet && (_pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled))
{
_isScaling = true
if (_pinchZoomEnabled)
{
_gestureScaleAxis = .Both
}
else
{
var x = abs(recognizer.locationInView(self).x - recognizer.locationOfTouch(1, inView: self).x)
var y = abs(recognizer.locationInView(self).y - recognizer.locationOfTouch(1, inView: self).y)
if (x > y)
{
_gestureScaleAxis = .X
}
else
{
_gestureScaleAxis = .Y
}
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended ||
recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isScaling)
{
_isScaling = false
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
var isZoomingOut = (recognizer.scale < 1)
var canZoomMoreX = isZoomingOut ? _viewPortHandler.canZoomOutMoreX : _viewPortHandler.canZoomInMoreX
if (_isScaling)
{
if (canZoomMoreX || (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y && _scaleYEnabled))
{
var location = recognizer.locationInView(self)
location.x = location.x - _viewPortHandler.offsetLeft
if (isAnyAxisInverted && _closestDataSetToTouch !== nil && getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
location.y = -(location.y - _viewPortHandler.offsetTop)
}
else
{
location.y = -(_viewPortHandler.chartHeight - location.y - _viewPortHandler.offsetBottom)
}
var scaleX = (_gestureScaleAxis == .Both || _gestureScaleAxis == .X) && _scaleXEnabled ? recognizer.scale : 1.0
var scaleY = (_gestureScaleAxis == .Both || _gestureScaleAxis == .Y) && _scaleYEnabled ? recognizer.scale : 1.0
var matrix = CGAffineTransformMakeTranslation(location.x, location.y)
matrix = CGAffineTransformScale(matrix, scaleX, scaleY)
matrix = CGAffineTransformTranslate(matrix,
-location.x, -location.y)
matrix = CGAffineTransformConcat(_viewPortHandler.touchMatrix, matrix)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartScaled?(self, scaleX: scaleX, scaleY: scaleY)
}
}
recognizer.scale = 1.0
}
}
}
@objc private func panGestureRecognized(recognizer: UIPanGestureRecognizer)
{
if (recognizer.state == UIGestureRecognizerState.Began && recognizer.numberOfTouches() > 0)
{
stopDeceleration()
if ((!_dataNotSet && _dragEnabled && !self.hasNoDragOffset) || !self.isFullyZoomedOut)
{
_isDragging = true
_closestDataSetToTouch = getDataSetByTouchPoint(recognizer.locationOfTouch(0, inView: self))
var translation = recognizer.translationInView(self)
if (!performPanChange(translation: translation))
{
if (_outerScrollView !== nil)
{
// We can stop dragging right now, and let the scroll view take control
_outerScrollView = nil
_isDragging = false
}
}
else
{
if (_outerScrollView !== nil)
{
// Prevent the parent scroll view from scrolling
_outerScrollView?.scrollEnabled = false
}
}
_lastPanPoint = recognizer.translationInView(self)
}
}
else if (recognizer.state == UIGestureRecognizerState.Changed)
{
if (_isDragging)
{
var originalTranslation = recognizer.translationInView(self)
var translation = CGPoint(x: originalTranslation.x - _lastPanPoint.x, y: originalTranslation.y - _lastPanPoint.y)
performPanChange(translation: translation)
_lastPanPoint = originalTranslation
}
else if (isHighlightPerDragEnabled)
{
var h = getHighlightByTouchPoint(recognizer.locationInView(self))
let lastHighlighted = self.lastHighlighted
if ((h === nil && lastHighlighted !== nil) ||
(h !== nil && lastHighlighted === nil) ||
(h !== nil && lastHighlighted !== nil && !h!.isEqual(lastHighlighted)))
{
self.lastHighlighted = h
self.highlightValue(highlight: h, callDelegate: true)
}
}
}
else if (recognizer.state == UIGestureRecognizerState.Ended || recognizer.state == UIGestureRecognizerState.Cancelled)
{
if (_isDragging)
{
if (recognizer.state == UIGestureRecognizerState.Ended && isDragDecelerationEnabled)
{
stopDeceleration()
_decelerationLastTime = CACurrentMediaTime()
_decelerationVelocity = recognizer.velocityInView(self)
_decelerationDisplayLink = CADisplayLink(target: self, selector: Selector("decelerationLoop"))
_decelerationDisplayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
}
_isDragging = false
}
if (_outerScrollView !== nil)
{
_outerScrollView?.scrollEnabled = true
_outerScrollView = nil
}
}
}
private func performPanChange(var #translation: CGPoint) -> Bool
{
if (isAnyAxisInverted && _closestDataSetToTouch !== nil
&& getAxis(_closestDataSetToTouch.axisDependency).isInverted)
{
if (self is HorizontalBarChartView)
{
translation.x = -translation.x
}
else
{
translation.y = -translation.y
}
}
var originalMatrix = _viewPortHandler.touchMatrix
var matrix = CGAffineTransformMakeTranslation(translation.x, translation.y)
matrix = CGAffineTransformConcat(originalMatrix, matrix)
matrix = _viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
if (delegate !== nil)
{
delegate?.chartTranslated?(self, dX: translation.x, dY: translation.y)
}
// Did we managed to actually drag or did we reach the edge?
return matrix.tx != originalMatrix.tx || matrix.ty != originalMatrix.ty
}
public func stopDeceleration()
{
if (_decelerationDisplayLink !== nil)
{
_decelerationDisplayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes)
_decelerationDisplayLink = nil
}
}
@objc private func decelerationLoop()
{
var currentTime = CACurrentMediaTime()
_decelerationVelocity.x *= self.dragDecelerationFrictionCoef
_decelerationVelocity.y *= self.dragDecelerationFrictionCoef
var timeInterval = CGFloat(currentTime - _decelerationLastTime)
var distance = CGPoint(
x: _decelerationVelocity.x * timeInterval,
y: _decelerationVelocity.y * timeInterval
)
if (!performPanChange(translation: distance))
{
// We reached the edge, stop
_decelerationVelocity.x = 0.0
_decelerationVelocity.y = 0.0
}
_decelerationLastTime = currentTime
if (abs(_decelerationVelocity.x) < 0.001 && abs(_decelerationVelocity.y) < 0.001)
{
stopDeceleration()
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
}
public override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool
{
if (!super.gestureRecognizerShouldBegin(gestureRecognizer))
{
return false
}
if (gestureRecognizer == _panGestureRecognizer)
{
if (_dataNotSet || !_dragEnabled || !self.hasNoDragOffset ||
(self.isFullyZoomedOut && !self.isHighlightPerDragEnabled))
{
return false
}
}
else if (gestureRecognizer == _pinchGestureRecognizer)
{
if (_dataNotSet || (!_pinchZoomEnabled && !_scaleXEnabled && !_scaleYEnabled))
{
return false
}
}
return true
}
public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool
{
if ((gestureRecognizer.isKindOfClass(UIPinchGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer)) ||
(gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPinchGestureRecognizer)))
{
return true
}
if (gestureRecognizer.isKindOfClass(UIPanGestureRecognizer) &&
otherGestureRecognizer.isKindOfClass(UIPanGestureRecognizer) && (
gestureRecognizer == _panGestureRecognizer
))
{
var scrollView = self.superview
while (scrollView !== nil && !scrollView!.isKindOfClass(UIScrollView))
{
scrollView = scrollView?.superview
}
var foundScrollView = scrollView as? UIScrollView
if (foundScrollView !== nil && !foundScrollView!.scrollEnabled)
{
foundScrollView = nil
}
var scrollViewPanGestureRecognizer: UIGestureRecognizer!
if (foundScrollView !== nil)
{
for scrollRecognizer in foundScrollView!.gestureRecognizers as! [UIGestureRecognizer]
{
if (scrollRecognizer.isKindOfClass(UIPanGestureRecognizer))
{
scrollViewPanGestureRecognizer = scrollRecognizer as! UIPanGestureRecognizer
break
}
}
}
if (otherGestureRecognizer === scrollViewPanGestureRecognizer)
{
_outerScrollView = foundScrollView
return true
}
}
return false
}
/// MARK: Viewport modifiers
/// Zooms in by 1.4, into the charts center. center.
public func zoomIn()
{
var matrix = _viewPortHandler.zoomIn(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms out by 0.7, from the charts center. center.
public func zoomOut()
{
var matrix = _viewPortHandler.zoomOut(x: self.bounds.size.width / 2.0, y: -(self.bounds.size.height / 2.0))
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: true)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Zooms in or out by the given scale factor. x and y are the coordinates
/// (in pixels) of the zoom center.
///
/// :param: scaleX if < 1 --> zoom out, if > 1 --> zoom in
/// :param: scaleY if < 1 --> zoom out, if > 1 --> zoom in
/// :param: x
/// :param: y
public func zoom(scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat)
{
var matrix = _viewPortHandler.zoom(scaleX: scaleX, scaleY: scaleY, x: x, y: -y)
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen()
{
var matrix = _viewPortHandler.fitScreen()
_viewPortHandler.refresh(newMatrix: matrix, chart: self, invalidate: false)
// Range might have changed, which means that Y-axis labels could have changed in size, affecting Y-axis size. So we need to recalculate offsets.
calculateOffsets()
setNeedsDisplay()
}
/// Sets the minimum scale value to which can be zoomed out. 1 = fitScreen
public func setScaleMinima(scaleX: CGFloat, scaleY: CGFloat)
{
_viewPortHandler.setMinimumScaleX(scaleX)
_viewPortHandler.setMinimumScaleY(scaleY)
}
/// Sets the size of the area (range on the x-axis) that should be maximum visible at once (no further zomming out allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMaximum(maxXRange: CGFloat)
{
var xScale = _deltaX / maxXRange
_viewPortHandler.setMinimumScaleX(xScale)
}
/// Sets the size of the area (range on the x-axis) that should be minimum visible at once (no further zooming in allowed).
/// If this is e.g. set to 10, no more than 10 values on the x-axis can be viewed at once without scrolling.
public func setVisibleXRangeMinimum(minXRange: CGFloat)
{
var xScale = _deltaX / minXRange
_viewPortHandler.setMaximumScaleX(xScale)
}
/// Limits the maximum and minimum value count that can be visible by pinching and zooming.
/// e.g. minRange=10, maxRange=100 no less than 10 values and no more that 100 values can be viewed
/// at once without scrolling
public func setVisibleXRange(#minXRange: CGFloat, maxXRange: CGFloat)
{
var maxScale = _deltaX / minXRange
var minScale = _deltaX / maxXRange
_viewPortHandler.setMinMaxScaleX(minScaleX: minScale, maxScaleX: maxScale)
}
/// Sets the size of the area (range on the y-axis) that should be maximum visible at once.
///
/// :param: yRange
/// :param: axis - the axis for which this limit should apply
public func setVisibleYRangeMaximum(maxYRange: CGFloat, axis: ChartYAxis.AxisDependency)
{
var yScale = getDeltaY(axis) / maxYRange
_viewPortHandler.setMinimumScaleY(yScale)
}
/// Moves the left side of the current viewport to the specified x-index.
public func moveViewToX(xIndex: Int)
{
if (_viewPortHandler.hasChartDimens)
{
var pt = CGPoint(x: CGFloat(xIndex), y: 0.0)
getTransformer(.Left).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToX(xIndex); })
}
}
/// Centers the viewport to the specified y-value on the y-axis.
///
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewToY(yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: 0.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewToY(yValue, axis: axis); })
}
}
/// This will move the left side of the current viewport to the specified x-index on the x-axis, and center the viewport to the specified y-value on the y-axis.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func moveViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var pt = CGPoint(x: CGFloat(xIndex), y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.moveViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// This will move the center of the current viewport to the specified x-index and y-value.
///
/// :param: xIndex
/// :param: yValue
/// :param: axis - which axis should be used as a reference for the y-axis
public func centerViewTo(#xIndex: Int, yValue: CGFloat, axis: ChartYAxis.AxisDependency)
{
if (_viewPortHandler.hasChartDimens)
{
var valsInView = getDeltaY(axis) / _viewPortHandler.scaleY
var xsInView = CGFloat(xAxis.values.count) / _viewPortHandler.scaleX
var pt = CGPoint(x: CGFloat(xIndex) - xsInView / 2.0, y: yValue + valsInView / 2.0)
getTransformer(axis).pointValueToPixel(&pt)
_viewPortHandler.centerViewPort(pt: pt, chart: self)
}
else
{
_sizeChangeEventActions.append({[weak self] () in self?.centerViewTo(xIndex: xIndex, yValue: yValue, axis: axis); })
}
}
/// Sets custom offsets for the current ViewPort (the offsets on the sides of the actual chart window). Setting this will prevent the chart from automatically calculating it's offsets. Use resetViewPortOffsets() to undo this.
/// ONLY USE THIS WHEN YOU KNOW WHAT YOU ARE DOING, else use setExtraOffsets(...).
public func setViewPortOffsets(#left: CGFloat, top: CGFloat, right: CGFloat, bottom: CGFloat)
{
_customViewPortEnabled = true
if (NSThread.isMainThread())
{
self._viewPortHandler.restrainViewPort(offsetLeft: left, offsetTop: top, offsetRight: right, offsetBottom: bottom)
prepareOffsetMatrix()
prepareValuePxMatrix()
}
else
{
dispatch_async(dispatch_get_main_queue(), {
self.setViewPortOffsets(left: left, top: top, right: right, bottom: bottom)
})
}
}
/// Resets all custom offsets set via setViewPortOffsets(...) method. Allows the chart to again calculate all offsets automatically.
public func resetViewPortOffsets()
{
_customViewPortEnabled = false
calculateOffsets()
}
// MARK: - Accessors
/// Returns the delta-y value (y-value range) of the specified axis.
public func getDeltaY(axis: ChartYAxis.AxisDependency) -> CGFloat
{
if (axis == .Left)
{
return CGFloat(leftAxis.axisRange)
}
else
{
return CGFloat(rightAxis.axisRange)
}
}
/// Returns the position (in pixels) the provided Entry has inside the chart view
public func getPosition(e: ChartDataEntry, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var vals = CGPoint(x: CGFloat(e.xIndex), y: CGFloat(e.value))
getTransformer(axis).pointValueToPixel(&vals)
return vals
}
/// the number of maximum visible drawn values on the chart
/// only active when setDrawValues() is enabled
public var maxVisibleValueCount: Int
{
get
{
return _maxVisibleValueCount
}
set
{
_maxVisibleValueCount = newValue
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var dragEnabled: Bool
{
get
{
return _dragEnabled
}
set
{
if (_dragEnabled != newValue)
{
_dragEnabled = newValue
}
}
}
/// is dragging enabled? (moving the chart with the finger) for the chart (this does not affect scaling).
public var isDragEnabled: Bool
{
return dragEnabled
}
/// is scaling enabled? (zooming in and out by gesture) for the chart (this does not affect dragging).
public func setScaleEnabled(enabled: Bool)
{
if (_scaleXEnabled != enabled || _scaleYEnabled != enabled)
{
_scaleXEnabled = enabled
_scaleYEnabled = enabled
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
}
}
public var scaleXEnabled: Bool
{
get
{
return _scaleXEnabled
}
set
{
if (_scaleXEnabled != newValue)
{
_scaleXEnabled = newValue
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
}
}
}
public var scaleYEnabled: Bool
{
get
{
return _scaleYEnabled
}
set
{
if (_scaleYEnabled != newValue)
{
_scaleYEnabled = newValue
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
}
}
}
public var isScaleXEnabled: Bool { return scaleXEnabled; }
public var isScaleYEnabled: Bool { return scaleYEnabled; }
/// flag that indicates if double tap zoom is enabled or not
public var doubleTapToZoomEnabled: Bool
{
get
{
return _doubleTapToZoomEnabled
}
set
{
if (_doubleTapToZoomEnabled != newValue)
{
_doubleTapToZoomEnabled = newValue
_doubleTapGestureRecognizer.enabled = _doubleTapToZoomEnabled
}
}
}
/// :returns: true if zooming via double-tap is enabled false if not.
/// :default: true
public var isDoubleTapToZoomEnabled: Bool
{
return doubleTapToZoomEnabled
}
/// flag that indicates if highlighting per dragging over a fully zoomed out chart is enabled
public var highlightPerDragEnabled = true
/// If set to true, highlighting per dragging over a fully zoomed out chart is enabled
/// You might want to disable this when using inside a UIScrollView
/// :default: true
public var isHighlightPerDragEnabled: Bool
{
return highlightPerDragEnabled
}
/// :returns: true if drawing the grid background is enabled, false if not.
/// :default: true
public var isDrawGridBackgroundEnabled: Bool
{
return drawGridBackgroundEnabled
}
/// :returns: true if drawing the borders rectangle is enabled, false if not.
/// :default: false
public var isDrawBordersEnabled: Bool
{
return drawBordersEnabled
}
/// Returns the Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the Line-, Scatter-, or CandleStick-Chart.
public func getHighlightByTouchPoint(pt: CGPoint) -> ChartHighlight?
{
if (_dataNotSet || _data === nil)
{
println("Can't select by touch. No data set.")
return nil
}
return _highlighter?.getHighlight(x: Double(pt.x), y: Double(pt.y))
}
/// Returns the x and y values in the chart at the given touch point
/// (encapsulated in a PointD). This method transforms pixel coordinates to
/// coordinates / values in the chart. This is the opposite method to
/// getPixelsForValues(...).
public func getValueByTouchPoint(var #pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGPoint
{
getTransformer(axis).pixelToValue(&pt)
return pt
}
/// Transforms the given chart values into pixels. This is the opposite
/// method to getValueByTouchPoint(...).
public func getPixelForValue(x: Double, y: Double, axis: ChartYAxis.AxisDependency) -> CGPoint
{
var pt = CGPoint(x: CGFloat(x), y: CGFloat(y))
getTransformer(axis).pointValueToPixel(&pt)
return pt
}
/// returns the y-value at the given touch position (must not necessarily be
/// a value contained in one of the datasets)
public func getYValueByTouchPoint(#pt: CGPoint, axis: ChartYAxis.AxisDependency) -> CGFloat
{
return getValueByTouchPoint(pt: pt, axis: axis).y
}
/// returns the Entry object displayed at the touched position of the chart
public func getEntryByTouchPoint(pt: CGPoint) -> ChartDataEntry!
{
var h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data!.getEntryForHighlight(h!)
}
return nil
}
///returns the DataSet object displayed at the touched position of the chart
public func getDataSetByTouchPoint(pt: CGPoint) -> BarLineScatterCandleChartDataSet!
{
var h = getHighlightByTouchPoint(pt)
if (h !== nil)
{
return _data.getDataSetByIndex(h!.dataSetIndex) as! BarLineScatterCandleChartDataSet!
}
return nil
}
/// Returns the lowest x-index (value on the x-axis) that is still visible on he chart.
public var lowestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentLeft, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (pt.x <= 0.0) ? 0 : Int(pt.x + 1.0)
}
/// Returns the highest x-index (value on the x-axis) that is still visible on the chart.
public var highestVisibleXIndex: Int
{
var pt = CGPoint(x: viewPortHandler.contentRight, y: viewPortHandler.contentBottom)
getTransformer(.Left).pixelToValue(&pt)
return (Int(pt.x) >= _data.xValCount) ? _data.xValCount - 1 : Int(pt.x)
}
/// returns the current x-scale factor
public var scaleX: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleX
}
/// returns the current y-scale factor
public var scaleY: CGFloat
{
if (_viewPortHandler === nil)
{
return 1.0
}
return _viewPortHandler.scaleY
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool { return _viewPortHandler.isFullyZoomedOut; }
/// Returns the left y-axis object. In the horizontal bar-chart, this is the
/// top axis.
public var leftAxis: ChartYAxis
{
return _leftAxis
}
/// Returns the right y-axis object. In the horizontal bar-chart, this is the
/// bottom axis.
public var rightAxis: ChartYAxis { return _rightAxis; }
/// Returns the y-axis object to the corresponding AxisDependency. In the
/// horizontal bar-chart, LEFT == top, RIGHT == BOTTOM
public func getAxis(axis: ChartYAxis.AxisDependency) -> ChartYAxis
{
if (axis == .Left)
{
return _leftAxis
}
else
{
return _rightAxis
}
}
/// Returns the object representing all x-labels, this method can be used to
/// acquire the XAxis object and modify it (e.g. change the position of the
/// labels)
public var xAxis: ChartXAxis
{
return _xAxis
}
/// flag that indicates if pinch-zoom is enabled. if true, both x and y axis can be scaled with 2 fingers, if false, x and y axis can be scaled separately
public var pinchZoomEnabled: Bool
{
get
{
return _pinchZoomEnabled
}
set
{
if (_pinchZoomEnabled != newValue)
{
_pinchZoomEnabled = newValue
_pinchGestureRecognizer.enabled = _pinchZoomEnabled || _scaleXEnabled || _scaleYEnabled
}
}
}
/// returns true if pinch-zoom is enabled, false if not
/// :default: false
public var isPinchZoomEnabled: Bool { return pinchZoomEnabled; }
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_viewPortHandler.setDragOffsetX(offset)
}
/// Set an offset in dp that allows the user to drag the chart over it's
/// bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_viewPortHandler.setDragOffsetY(offset)
}
/// :returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool { return _viewPortHandler.hasNoDragOffset; }
/// The X axis renderer. This is a read-write property so you can set your own custom renderer here.
/// :default: An instance of ChartXAxisRenderer
/// :returns: The current set X axis renderer
public var xAxisRenderer: ChartXAxisRenderer
{
get { return _xAxisRenderer }
set { _xAxisRenderer = newValue }
}
/// The left Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// :default: An instance of ChartYAxisRenderer
/// :returns: The current set left Y axis renderer
public var leftYAxisRenderer: ChartYAxisRenderer
{
get { return _leftYAxisRenderer }
set { _leftYAxisRenderer = newValue }
}
/// The right Y axis renderer. This is a read-write property so you can set your own custom renderer here.
/// :default: An instance of ChartYAxisRenderer
/// :returns: The current set right Y axis renderer
public var rightYAxisRenderer: ChartYAxisRenderer
{
get { return _rightYAxisRenderer }
set { _rightYAxisRenderer = newValue }
}
public override var chartYMax: Double
{
return max(leftAxis.axisMaximum, rightAxis.axisMaximum)
}
public override var chartYMin: Double
{
return min(leftAxis.axisMinimum, rightAxis.axisMinimum)
}
/// Returns true if either the left or the right or both axes are inverted.
public var isAnyAxisInverted: Bool
{
return _leftAxis.isInverted || _rightAxis.isInverted
}
/// flag that indicates if auto scaling on the y axis is enabled.
/// if yes, the y axis automatically adjusts to the min and max y values of the current x axis range whenever the viewport changes
public var autoScaleMinMaxEnabled: Bool
{
get { return _autoScaleMinMaxEnabled; }
set { _autoScaleMinMaxEnabled = newValue; }
}
/// returns true if auto scaling on the y axis is enabled.
/// :default: false
public var isAutoScaleMinMaxEnabled : Bool { return autoScaleMinMaxEnabled; }
/// Sets a minimum width to the specified y axis.
public func setYAxisMinWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.minWidth = width
}
else
{
_rightAxis.minWidth = width
}
}
/// Returns the (custom) minimum width of the specified Y axis.
/// :default 0.0
public func getYAxisMinWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.minWidth
}
else
{
return _rightAxis.minWidth
}
}
/// Sets a maximum width to the specified y axis.
/// Zero (0.0) means there's no maximum width
public func setYAxisMaxWidth(which: ChartYAxis.AxisDependency, width: CGFloat)
{
if (which == .Left)
{
_leftAxis.maxWidth = width
}
else
{
_rightAxis.maxWidth = width
}
}
/// Returns the (custom) maximum width of the specified Y axis.
/// Zero (0.0) means there's no maximum width
/// :default 0.0 (no maximum specified)
public func getYAxisMaxWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.maxWidth
}
else
{
return _rightAxis.maxWidth
}
}
/// Returns the width of the specified y axis.
public func getYAxisWidth(which: ChartYAxis.AxisDependency) -> CGFloat
{
if (which == .Left)
{
return _leftAxis.requiredSize().width
}
else
{
return _rightAxis.requiredSize().width
}
}
}
/// Default formatter that calculates the position of the filled line.
internal class BarLineChartFillFormatter: NSObject, ChartFillFormatter
{
private weak var _chart: BarLineChartViewBase!
internal init(chart: BarLineChartViewBase)
{
_chart = chart
}
internal func getFillLinePosition(#dataSet: LineChartDataSet, data: LineChartData, chartMaxY: Double, chartMinY: Double) -> CGFloat
{
var fillMin = CGFloat(0.0)
if (dataSet.yMax > 0.0 && dataSet.yMin < 0.0)
{
fillMin = 0.0
}
else
{
if (!_chart.getAxis(dataSet.axisDependency).isStartAtZeroEnabled)
{
var max: Double, min: Double
if (data.yMax > 0.0)
{
max = 0.0
}
else
{
max = chartMaxY
}
if (data.yMin < 0.0)
{
min = 0.0
}
else
{
min = chartMinY
}
fillMin = CGFloat(dataSet.yMin >= 0.0 ? min : max)
}
else
{
fillMin = 0.0
}
}
return fillMin
}
}
| apache-2.0 | f6b1f391437d7625eeb12350220301d1 | 34.990991 | 229 | 0.583796 | 5.626761 | false | false | false | false |
rechsteiner/Parchment | Example/ExamplesViewController.swift | 1 | 4520 | import UIKit
enum Example: CaseIterable {
case basic
case selfSizing
case calendar
case sizeDelegate
case images
case icons
case storyboard
case navigationBar
case largeTitles
case scroll
case header
case multipleCells
case pageViewController
var title: String {
switch self {
case .basic:
return "Basic"
case .selfSizing:
return "Self sizing cells"
case .calendar:
return "Calendar"
case .sizeDelegate:
return "Size delegate"
case .images:
return "Images"
case .icons:
return "Icons"
case .storyboard:
return "Storyboard"
case .navigationBar:
return "Navigation bar"
case .largeTitles:
return "Large titles"
case .scroll:
return "Hide menu on scroll"
case .header:
return "Header above menu"
case .multipleCells:
return "Multiple cells"
case .pageViewController:
return "PageViewController"
}
}
}
final class ExamplesViewController: UITableViewController {
static let CellIdentifier = "CellIdentifier"
var isUITesting: Bool {
return ProcessInfo.processInfo.arguments.contains("--ui-testing")
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Self.CellIdentifier)
if isUITesting {
let viewController = createViewController(for: .basic)
navigationController?.setViewControllers([viewController], animated: false)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Self.CellIdentifier, for: indexPath)
let example = Example.allCases[indexPath.row]
cell.textLabel?.text = example.title
return cell
}
override func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int {
return Example.allCases.count
}
override func tableView(_: UITableView, didSelectRowAt indexPath: IndexPath) {
let example = Example.allCases[indexPath.row]
let viewController = createViewController(for: example)
viewController.title = example.title
switch example {
case .largeTitles:
let navigationController = UINavigationController(rootViewController: viewController)
navigationController.modalPresentationStyle = .fullScreen
viewController.navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .done,
target: self,
action: #selector(handleDismiss)
)
present(navigationController, animated: true)
default:
viewController.view.backgroundColor = .white
navigationController?.pushViewController(viewController, animated: true)
}
}
private func createViewController(for example: Example) -> UIViewController {
switch example {
case .basic:
return BasicViewController(nibName: nil, bundle: nil)
case .calendar:
return CalendarViewController(nibName: nil, bundle: nil)
case .selfSizing:
return SelfSizingViewController()
case .sizeDelegate:
return SizeDelegateViewController(nibName: nil, bundle: nil)
case .images:
return UnsplashViewController(nibName: nil, bundle: nil)
case .icons:
return IconsViewController(nibName: nil, bundle: nil)
case .storyboard:
return StoryboardViewController(nibName: nil, bundle: nil)
case .navigationBar:
return NavigationBarViewController(nibName: nil, bundle: nil)
case .largeTitles:
return LargeTitlesViewController(nibName: nil, bundle: nil)
case .scroll:
return ScrollViewController(nibName: nil, bundle: nil)
case .header:
return HeaderViewController(nibName: nil, bundle: nil)
case .multipleCells:
return MultipleCellsViewController(nibName: nil, bundle: nil)
case .pageViewController:
return PageViewExampleViewController(nibName: nil, bundle: nil)
}
}
@objc private func handleDismiss() {
dismiss(animated: true)
}
}
| mit | 3ab3e08cd82e8c1e3cfb2195575ce4c9 | 32.984962 | 109 | 0.635619 | 5.614907 | false | false | false | false |
MKGitHub/MessageBox-Concept | Sources/MessageBox.swift | 1 | 2942 | //
// MessageBox
// Copyright © 2016/2017/2018 Mohsan Khan. All rights reserved.
//
//
// https://github.com/MKGitHub/MessageBox-Concept
// http://www.xybernic.com
//
//
// Copyright 2016/2017/2018 Mohsan Khan
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/**
Example Usage:
```swift
let messageBox = MessageBox()
// set
messageBox.setObject("TestObject1", forKey:"TestKey1")
// get
// but don't remove it, keep it stored, so that it can still be retrieved later
let someObject = messageBox.getObject(forKey:"TestKey1", removeIfFound:false)
// get
// and remove it
let someObject = messageBox.getObject(forKey:"TestKey1", removeIfFound:true)
```
*/
final class MessageBox
{
// MARK: Private Member
private var mMessageDictionary:Dictionary<String, Any> = Dictionary<String, Any>()
// MARK:- Public Methods
/**
Set an object for a key.
- Parameters:
- object: An object.
- key: A key name.
*/
func setObject(_ object:Any, forKey key:String)
{
mMessageDictionary[key] = object
}
/**
Get an object for a key.
- Parameters:
- key: A key name.
- removeIfFound: If the object is found then remove it upon retrieval, otherwise let it remain.
- Returns: The found object, or `nil` if the object does not exist.
*/
func getObject(forKey key:String, removeIfFound:Bool) -> Any?
{
let obj:Any? = mMessageDictionary[key]
if (removeIfFound) {
mMessageDictionary.removeValue(forKey:key)
}
return obj
}
/**
Check if an object exists for a key.
- Parameter key: A key name.
- Returns: `true` or `false`.
*/
func containsObject(forKey key:String) -> Bool
{
if (mMessageDictionary[key] != nil) {
return true
}
return false
}
/**
- Returns: The number of messages in the box.
*/
func count() -> Int
{
return mMessageDictionary.count
}
/**
Remove all messages in the box.
*/
func removeAll()
{
mMessageDictionary.removeAll()
}
/**
- Returns: Returns the underlaying dictionary.
*/
func dictionary() -> Dictionary<String, Any>
{
return mMessageDictionary
}
}
| apache-2.0 | cb8463fd79651519fc95ed1956317ccf | 20.947761 | 107 | 0.609997 | 4.124825 | false | false | false | false |
skonb/YapDatabaseExtensions | examples/iOS/YapDBExtensionsMobile/Models.swift | 2 | 8927 | //
// Models.swift
// YapDBExtensionsMobile
//
// Created by Daniel Thorpe on 15/04/2015.
// Copyright (c) 2015 Daniel Thorpe. All rights reserved.
//
import Foundation
import YapDatabase
import YapDatabaseExtensions
public enum Barcode: Equatable {
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
public struct Product: Identifiable, Equatable {
public struct Category: Identifiable {
public let identifier: Int
let name: String
}
public struct Metadata: Equatable {
let categoryIdentifier: Int
public init(categoryIdentifier: Int) {
self.categoryIdentifier = categoryIdentifier
}
}
public let metadata: Metadata
public let identifier: Identifier
internal let name: String
internal let barcode: Barcode
public init(metadata: Metadata, identifier: Identifier, name: String, barcode: Barcode) {
self.metadata = metadata
self.identifier = identifier
self.name = name
self.barcode = barcode
}
}
public class Person: NSObject, NSCoding, Equatable {
public let identifier: Identifier
public let name: String
public init(id: String, name n: String) {
identifier = id
name = n
}
public required init(coder aDecoder: NSCoder) {
identifier = aDecoder.decodeObjectForKey("identifier") as! Identifier
name = aDecoder.decodeObjectForKey("name") as! String
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(identifier, forKey: "identifier")
aCoder.encodeObject(name, forKey: "name")
}
}
// MARK: - Hashable etc
extension Barcode: Hashable {
public var hashValue: Int {
return identifier
}
}
public func == (a: Barcode, b: Barcode) -> Bool {
switch (a, b) {
case let (.UPCA(aNS, aM, aP, aC), .UPCA(bNS, bM, bP, bC)):
return (aNS == bNS) && (aM == bM) && (aP == bP) && (aC == bC)
case let (.QRCode(aCode), .QRCode(bCode)):
return aCode == bCode
default:
return false
}
}
public func == (a: Product, b: Product) -> Bool {
return a.identifier == b.identifier
}
public func == (a: Product.Metadata, b: Product.Metadata) -> Bool {
return a.categoryIdentifier == b.categoryIdentifier
}
public func == (a: Person, b: Person) -> Bool {
return (a.identifier == b.identifier) && (a.name == b.name)
}
extension Person: Printable {
public override var description: String {
return "id: \(identifier), name: \(name)"
}
}
// MARK: - Persistable
extension Barcode: Persistable {
public static var collection: String {
return "Barcodes"
}
public var identifier: Int {
switch self {
case let .UPCA(numberSystem, manufacturer, product, check):
return "\(numberSystem).\(manufacturer).\(product).\(check)".hashValue
case let .QRCode(code):
return code.hashValue
}
}
}
extension Product.Category: Persistable {
public static var collection: String {
return "Categories"
}
}
extension Product: ValueMetadataPersistable {
public static var collection: String {
return "Products"
}
}
extension Person: Persistable {
public static var collection: String {
return "People"
}
}
// MARK: - Saveable
extension Barcode: Saveable {
public typealias Archive = BarcodeArchiver
enum Kind: Int { case UPCA = 1, QRCode }
public var archive: Archive {
return Archive(self)
}
var kind: Kind {
switch self {
case UPCA(_): return Kind.UPCA
case QRCode(_): return Kind.QRCode
}
}
}
extension Product.Category: Saveable {
public typealias Archive = ProductCategoryArchiver
public var archive: Archive {
return Archive(self)
}
}
extension Product.Metadata: Saveable {
public typealias Archive = ProductMetadataArchiver
public var archive: Archive {
return Archive(self)
}
}
extension Product: Saveable {
public typealias Archive = ProductArchiver
public var archive: Archive {
return Archive(self)
}
}
// MARK: - Archivers
public class BarcodeArchiver: NSObject, NSCoding, Archiver {
public let value: Barcode
public required init(_ v: Barcode) {
value = v
}
public required init(coder aDecoder: NSCoder) {
if let kind = Barcode.Kind(rawValue: aDecoder.decodeIntegerForKey("kind")) {
switch kind {
case .UPCA:
let numberSystem = aDecoder.decodeIntegerForKey("numberSystem")
let manufacturer = aDecoder.decodeIntegerForKey("manufacturer")
let product = aDecoder.decodeIntegerForKey("product")
let check = aDecoder.decodeIntegerForKey("check")
value = .UPCA(numberSystem, manufacturer, product, check)
case .QRCode:
let code = aDecoder.decodeObjectForKey("code") as! String
value = .QRCode(code)
}
}
else {
preconditionFailure("Barcode.Kind not correctly encoded.")
}
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(value.kind.rawValue, forKey: "kind")
switch value {
case let .UPCA(numberSystem, manufacturer, product, check):
aCoder.encodeInteger(numberSystem, forKey: "numberSystem")
aCoder.encodeInteger(manufacturer, forKey: "manufacturer")
aCoder.encodeInteger(product, forKey: "product")
aCoder.encodeInteger(check, forKey: "check")
case let .QRCode(code):
aCoder.encodeObject(code, forKey: "code")
}
}
}
public class ProductCategoryArchiver: NSObject, NSCoding, Archiver {
public let value: Product.Category
public required init(_ v: Product.Category) {
value = v
}
public required init(coder aDecoder: NSCoder) {
let identifier = aDecoder.decodeIntegerForKey("identifier")
let name = aDecoder.decodeObjectForKey("name") as? String
value = Product.Category(identifier: identifier, name: name!)
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(value.identifier, forKey: "identifier")
aCoder.encodeObject(value.name, forKey: "name")
}
}
public class ProductMetadataArchiver: NSObject, NSCoding, Archiver {
public let value: Product.Metadata
public required init(_ v: Product.Metadata) {
value = v
}
public required init(coder aDecoder: NSCoder) {
let categoryIdentifier = aDecoder.decodeIntegerForKey("categoryIdentifier")
value = Product.Metadata(categoryIdentifier: categoryIdentifier)
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(value.categoryIdentifier, forKey: "categoryIdentifier")
}
}
public class ProductArchiver: NSObject, NSCoding, Archiver {
public let value: Product
public required init(_ v: Product) {
value = v
}
public required init(coder aDecoder: NSCoder) {
let metadata: Product.Metadata? = valueFromArchive(aDecoder.decodeObjectForKey("metadata"))
let identifier = aDecoder.decodeObjectForKey("identifier") as! String
let name = aDecoder.decodeObjectForKey("name") as! String
let barcode: Barcode? = valueFromArchive(aDecoder.decodeObjectForKey("barcode"))
value = Product(metadata: metadata!, identifier: identifier, name: name, barcode: barcode!)
}
public func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(archiveFromValue(value.metadata), forKey: "metadata")
aCoder.encodeObject(value.identifier, forKey: "identifier")
aCoder.encodeObject(value.name, forKey: "name")
aCoder.encodeObject(archiveFromValue(value.barcode), forKey: "barcode")
}
}
// MARK: - Database Views
public func products() -> YapDB.Fetch {
let grouping: YapDB.View.Grouping = .ByMetadata({ (collection, key, metadata) -> String! in
if collection == Product.collection {
if let metadata: Product.Metadata = valueFromArchive(metadata) {
return "category: \(metadata.categoryIdentifier)"
}
}
return nil
})
let sorting: YapDB.View.Sorting = .ByObject({ (group, collection1, key1, object1, collection2, key2, object2) -> NSComparisonResult in
if let product1: Product = valueFromArchive(object1) {
if let product2: Product = valueFromArchive(object2) {
return product1.name.caseInsensitiveCompare(product2.name)
}
}
return .OrderedSame
})
let view = YapDB.View(
name: "Products grouped by category",
grouping: grouping,
sorting: sorting,
collections: [Product.collection])
return .View(view)
}
| mit | 2f0a2a3cde962a7ac55ba1888937ed1e | 26.552469 | 138 | 0.644001 | 4.580298 | false | false | false | false |
minimoog/MetalToy | MetalToy/CompilerMessageButton.swift | 1 | 1696 | //
// CompilerMessageButton.swift
// MetalToy
//
// Created by minimoog on 12/26/17.
// Copyright © 2017 Toni Jovanoski. All rights reserved.
//
import UIKit
// Button showed in the gutter in code editor when there is compiler error
class CompilerMessageButton: UIView {
open var message: String?
fileprivate var button: UIButton?
internal var rootvc: UIViewController? = nil
required init?(coder aDecoder: NSCoder) {
fatalError("not implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
button = UIButton(frame: bounds)
button?.contentMode = .scaleAspectFill
button?.setImage(#imageLiteral(resourceName: "gutter"), for: .normal)
button?.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
addSubview(button!)
}
convenience init(frame: CGRect, rootViewController: UIViewController) {
self.init(frame: frame)
self.rootvc = rootViewController
}
// ### TODO: Actually this should be closure instead passing root view controller
@objc func buttonTapped(sender: UIButton) {
// Show the error message when button is tapped
if let message = message {
let messageViewController = PopupMessageViewController()
messageViewController.message = message
messageViewController.modalPresentationStyle = .popover
let popVc = messageViewController.popoverPresentationController
popVc?.sourceView = button
rootvc?.present(messageViewController, animated: true)
}
}
}
| mit | c28774052e659d254dffa2f11b5795ed | 29.818182 | 85 | 0.644248 | 5.199387 | false | false | false | false |
DrabWeb/Keijiban | Keijiban/Keijiban/KJExtensions.swift | 1 | 6971 | //
// KJExtensions.swift
// Keijiban
//
// Created by Seth on 2016-06-04.
//
import Cocoa
extension String {
/// Returns this string without any special HTML characters/tags that arent needed for parsing
var cleanedString : String {
/// This string, cleaned
var cleanedString : String = self;
// Replace the special characters
cleanedString = cleanedString.stringByReplacingOccurrencesOfString("'", withString: "'");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString(">", withString: ">");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString("<", withString: "<");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString(""", withString: "\"");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString("&", withString: "&");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString(""", withString: "\"");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString("<br>", withString: "\n");
cleanedString = cleanedString.stringByReplacingOccurrencesOfString("<wbr>", withString: "");
// Return the cleaned string
return cleanedString;
}
/// Return the content inside the href tag(If any) of this string
func hrefContent() -> String? {
/// The href content of this string
var hrefContent : String? = nil;
// If this string contains a "href=""...
if(self.containsString("href=\"")) {
/// The start index of the href tag
let hrefStartIndex : String.Index = self.rangeOfString("href=\"")!.last!.advancedBy(1);
/// The string after "href=""
let hrefContentWithEnd : String = self.substringFromIndex(hrefStartIndex);
// Set hrefContent
hrefContent = hrefContentWithEnd.substringToIndex(hrefContentWithEnd.rangeOfString("\"")!.last!);
}
// Return the href content
return hrefContent;
}
}
extension NSImage {
/// Returns this image overlayed with the given color
func withColorOverlay(overlayColor : NSColor) -> NSImage {
/// This image with the color overlay
let coloredImage : NSImage = self.copy() as! NSImage;
/// The pixel size of this image
let imageSize : NSSize = self.pixelSize;
// Lock drawing focus on coloredImage
coloredImage.lockFocus();
// Draw the image
coloredImage.drawInRect(NSRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), fromRect: NSRect.zero, operation: NSCompositingOperation.CompositeSourceOver, fraction: 1);
// Set the overlay color
overlayColor.set();
// Fill the image with the overlay color
NSRectFillUsingOperation(NSRect(x: 0, y: 0, width: imageSize.width, height: imageSize.height), NSCompositingOperation.CompositeSourceAtop);
// Unlock drawing focus on coloredImage
coloredImage.unlockFocus();
// Return the new image
return coloredImage;
}
/// The pixel size of this image
var pixelSize : NSSize {
/// The NSBitmapImageRep to the image
let imageRep : NSBitmapImageRep = (NSBitmapImageRep(data: self.TIFFRepresentation!))!;
/// The size of the iamge
let imageSize : NSSize = NSSize(width: imageRep.pixelsWide, height: imageRep.pixelsHigh);
// Return the image size
return imageSize;
}
/// Saves this image to the given path with the given file type
func saveTo(filePath : String, fileType : NSBitmapImageFileType) {
// Save the image data to the given path
self.dataForFileType(fileType)?.writeToFile(filePath, atomically: false);
}
/// Returns the NSData for this image with the given NSBitmapImageFileType
func dataForFileType(fileType : NSBitmapImageFileType) -> NSData? {
// If the bitmap representation isnt nil...
if let imageRepresentation = self.representations[0] as? NSBitmapImageRep {
// If the data using the given file type isnt nil...
if let data = imageRepresentation.representationUsingType(fileType, properties: [:]) {
// Return the data
return data;
}
}
// Return nil
return nil;
}
}
extension Array where Element:KJ4CPost {
/// Returns the KJ4CPost with the given post number in this array(If there is none it returns nil)
func findPostByNumber(postNumber : Int) -> KJ4CPost? {
/// The post that was possibly found in this array
var foundPost : KJ4CPost? = nil;
// For every post in this array...
for(_, currentPost) in self.enumerate() {
// If the current post's post number is equal to the given post number...
if(currentPost.postNumber == postNumber) {
// Set foundPost to this post
foundPost = currentPost;
}
}
// Return the post
return foundPost;
}
}
extension NSView {
/// Adds constraints for the top, bottom, leading and trailing edges of this view with the given constant
func addOuterConstraints(constant : CGFloat) {
/// The constraint for the bottom edge
let bottomConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.superview!, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: constant);
// Add the constraint
self.superview!.addConstraint(bottomConstraint);
/// The constraint for the top edge
let topConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.superview!, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: constant);
// Add the constraint
self.superview!.addConstraint(topConstraint);
/// The constraint for the trailing edge
let trailingConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.superview!, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: constant);
// Add the constraint
self.superview!.addConstraint(trailingConstraint);
/// The constraint for the leading edge
let leadingConstraint = NSLayoutConstraint(item: self, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.superview!, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: constant);
// Add the constraint
self.superview!.addConstraint(leadingConstraint);
}
} | gpl-3.0 | c5611750af296f5bb0e71355b1cd5d02 | 42.304348 | 237 | 0.647253 | 5.345859 | false | false | false | false |
filipealva/WWDC15-Scholarship | Filipe Alvarenga/View/DotView.swift | 1 | 2003 | //
// DotView.swift
// Filipe Alvarenga
//
// Created by Filipe Alvarenga on 18/04/15.
// Copyright (c) 2015 Filipe Alvarenga. All rights reserved.
//
import UIKit
class DotView: UIView {
// MARK: - Properties
@IBOutlet weak var storyContainerHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var dot: UIView!
@IBOutlet weak var storyContainer: UIView!
@IBOutlet weak var storyTitle: UILabel!
@IBOutlet weak var storyDescription: UILabel!
@IBOutlet weak var storyDate: UILabel!
var story: Story! {
didSet {
configureStory()
}
}
// MARK: - Life Cycle
override func drawRect(rect: CGRect) {
super.drawRect(rect)
let shadowPath = UIBezierPath(rect: storyContainer.bounds)
storyContainer.layer.masksToBounds = false
storyContainer.layer.shadowColor = UIColor.blackColor().CGColor
storyContainer.layer.shadowOffset = CGSize(width: 0.0, height: 0.0)
storyContainer.layer.shadowOpacity = 0.5
storyContainer.layer.shadowRadius = 1.0
storyContainer.layer.shadowPath = shadowPath.CGPath
storyContainer.layer.cornerRadius = 2.0
dot.layer.cornerRadius = dot.bounds.height / 2
}
override func layoutSubviews() {
super.layoutSubviews()
frame = CGRect(x: frame.origin.x, y: frame.origin.y, width: superview!.bounds.width, height: superview!.bounds.height)
adjustConstraintsToFit()
}
// MARK: - Data Binding
func configureStory() {
self.storyTitle.text = self.story.title
self.storyDescription.text = self.story.description
self.storyDate.text = self.story.date
}
// MARK: - Resizing Helpers
func adjustConstraintsToFit() {
storyDescription.layoutIfNeeded()
storyContainerHeightConstraint.constant = storyDescription.frame.origin.y + storyDescription.frame.size.height + 8.0
}
}
| mit | 8a90307e8ae46dac8dac8a64eb6aa13f | 28.455882 | 126 | 0.652022 | 4.511261 | false | false | false | false |
wilzh40/SoundSieve | SwiftSkeleton/AnimatedStartButton.swift | 1 | 3936 | //
// AnimatedStartButton.swift
// walktracker
//
// Created by Kevin VanderLugt on 1/13/15.
// Copyright (c) 2015 Alpine Pipeline. All rights reserved.
//
import CoreGraphics
import QuartzCore
import UIKit
class AnimatedStartButton : UIButton {
// The horizontal disantce between the two lines in pause mode
let pauseSpace: CGFloat = 10.0
// This is due to the graphic being larger from the drop shadows
let shadowPadding: CGFloat = 8.0
let linePath: CGPath = {
let path = CGPathCreateMutable()
CGPathMoveToPoint(path, nil, 0, 0)
CGPathAddLineToPoint(path, nil, 0, 12)
return path
}()
let bottomTransform = CATransform3DRotate(CATransform3DMakeTranslation(0, 2, 0), CGFloat(M_PI/4), 0, 0, 1)
let topTransform = CATransform3DRotate(CATransform3DMakeTranslation(-10, -2, 0), CGFloat(-M_PI/4), 0, 0, 1)
override var selected: Bool {
didSet {
addTransforms()
}
}
var top: CAShapeLayer! = CAShapeLayer()
var bottom: CAShapeLayer! = CAShapeLayer()
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setupPaths()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.setupPaths()
}
func setupPaths() {
let lineWidth: CGFloat = 2
self.top.path = linePath
self.bottom.path = linePath
for layer in [ self.top, self.bottom ] {
layer.fillColor = nil
layer.strokeColor = UIColor.whiteColor().CGColor
layer.lineWidth = lineWidth
layer.lineCap = kCALineCapSquare
layer.masksToBounds = true
let strokingPath = CGPathCreateCopyByStrokingPath(layer.path, nil, lineWidth*2, kCGLineCapSquare, kCGLineJoinMiter, 0)
layer.bounds = CGPathGetPathBoundingBox(strokingPath)
layer.actions = [
"strokeStart": NSNull(),
"strokeEnd": NSNull(),
"transform": NSNull()
]
self.layer.addSublayer(layer)
}
self.top.anchorPoint = CGPointMake(0.5, 0.0)
self.top.position = CGPointMake(self.frame.size.width/2 + pauseSpace/2, (self.frame.size.height-shadowPadding)/2 - 12/2 )
self.top.transform = topTransform
self.bottom.anchorPoint = CGPointMake(0.5, 1.0)
self.bottom.position = CGPointMake(self.frame.size.width/2 - pauseSpace/2, self.top.position.y + 12 + shadowPadding/2)
self.bottom.transform = bottomTransform
}
func addTransforms() {
let bottomAnimation = CABasicAnimation(keyPath: "transform")
bottomAnimation.duration = 0.4
bottomAnimation.fillMode = kCAFillModeBackwards
bottomAnimation.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, -0.8, 0.5, 1.85)
let topAnimation = bottomAnimation.copy() as! CABasicAnimation
if (selected) {
bottomAnimation.toValue = NSValue(CATransform3D: CATransform3DIdentity)
topAnimation.toValue = NSValue(CATransform3D: CATransform3DIdentity)
}
else {
bottomAnimation.toValue = NSValue(CATransform3D: bottomTransform)
topAnimation.toValue = NSValue(CATransform3D: topTransform)
}
self.bottom.kv_applyAnimation(bottomAnimation)
self.top.kv_applyAnimation(topAnimation)
}
}
extension CALayer {
func kv_applyAnimation(animation: CABasicAnimation) {
let copy = animation.copy() as! CABasicAnimation
if copy.fromValue == nil {
copy.fromValue = self.presentationLayer().valueForKeyPath(copy.keyPath)
}
self.addAnimation(copy, forKey: copy.keyPath)
self.setValue(copy.toValue, forKeyPath:copy.keyPath)
}
}
| mit | f50a277e143e5f8e7b056e32843da8c1 | 32.355932 | 130 | 0.622713 | 4.503432 | false | false | false | false |
arinjoy/Landmark-Remark | LandmarkRemark/LandmarkCustomCell.swift | 1 | 4839 | //
// LandmarkCustomCell.swift
// LandmarkRemark
//
// Created by Arinjoy Biswas on 7/06/2016.
// Copyright © 2016 Arinjoy Biswas. All rights reserved.
//
import UIKit
import MapKit
class LandmarkCustomCell: UITableViewCell, MKMapViewDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var remarkLabel: UILabel!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var latitudeLabel: UILabel!
@IBOutlet weak var longitudeLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
// to let the view know about the current username
var currentUserName = ""
/**
View life-cycle method
*/
override func awakeFromNib() {
super.awakeFromNib()
mapView.delegate = self
mapView.layer.cornerRadius = 10.0
mapView.layer.masksToBounds = true
}
/**
To bind the view-model properties with the cell view
- parameter viewModel: The view-model to bind
- parameter currentUserName: The currently logged-in username to save as information to this class
*/
func bindViewModel(viewModel: AnyObject, currentUserName: String) {
self.currentUserName = currentUserName
if let landmarkViewModel = viewModel as? AnnotationViewModel {
dispatch_async(dispatch_get_main_queue(), {
let region:MKCoordinateRegion = MKCoordinateRegionMakeWithDistance(landmarkViewModel.coordinate, 2000, 2000)
self.mapView.setRegion(self.mapView.regionThatFits(region), animated: true)
self.mapView.removeAnnotations(self.mapView.annotations)
let annotation = AnnotationViewModel(message: landmarkViewModel.title!, username: landmarkViewModel.userName, location: landmarkViewModel.coordinate)
self.mapView.addAnnotation(annotation)
// binding the UI elements of the view with view model properties, and apply some formatting
self.remarkLabel.text = landmarkViewModel.title!
self.userNameLabel.text = "user: " + landmarkViewModel.userName
self.latitudeLabel.text = "\(Double(round(100000 * viewModel.coordinate.latitude) / 100000))"
self.longitudeLabel.text = "\(Double(round(100000 * viewModel.coordinate.longitude) / 100000))"
// the view model might not have distance info, if the location was not updated yet
self.distanceLabel.text = ""
if let info = landmarkViewModel.distanceInfo {
self.distanceLabel.text = info
}
})
}
}
//-----------------------------------------------
// MARK: - MKMapViewDelegate method
//-----------------------------------------------
/** Returns the view associated with the specified annotation object
- parameter mapView: The map view that requested the annotation view.
- parameter annotation: The object representing the annotation that is about to be displayed.
- returns: The annotation view to display for the specified annotation or nil if you want to display a standard annotation view.
*/
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
if let annotation = annotation as? AnnotationViewModel {
// there could be two kinds of pin: current user landmark (purple) or other user landmark (red)
var identifier = ""
var targetAnnotationImage: UIImage? = nil
if annotation.userName == currentUserName {
identifier = "my_saved_landmark"
targetAnnotationImage = Icon.myLandmarkAnnotationImage
}
else {
identifier = "others_saved_landmark"
targetAnnotationImage = Icon.othersLandmarkAnnotationImage
}
var view: MKAnnotationView
// try to re-use and deque the view
if let dequeuedView = mapView.dequeueReusableAnnotationViewWithIdentifier(identifier) {
dequeuedView.annotation = annotation
view = dequeuedView
} else {
view = MKAnnotationView(annotation: annotation, reuseIdentifier: identifier)
view.canShowCallout = true
view.calloutOffset = CGPoint(x: 0, y: -2)
view.image = targetAnnotationImage
view.centerOffset = CGPointMake(0, -15)
}
return view
}
return nil
}
}
| mit | 66e0c0b7465cc7bd30709575828c8fbd | 36.215385 | 165 | 0.596734 | 5.752675 | false | false | false | false |
penniooi/TestKichen | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendNewCell.swift | 1 | 3283 | //
// CBRecommendNewCell.swift
// TestKitchen
//
// Created by aloha on 16/8/19.
// Copyright © 2016年 胡颉禹. All rights reserved.
//
import UIKit
class CBRecommendNewCell: UITableViewCell {
//显示数据
var model:CBRecommendwidgetListModel?{
didSet{
showData()
}
}
@IBAction func clickBtn(sender: UIButton) {
}
@IBAction func palyAction(sender: UIButton) {
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func showData(){
for i in 0..<3{
//图片
if model?.widget_data?.count>i*4{
let imagemodel = model?.widget_data![i*4]
if imagemodel?.type == "image"{
let dImage = UIImage(named: "sdefaultImage")
let subView = contentView.viewWithTag(200+i)
if subView?.isKindOfClass(UIImageView.self) == true{
let imageView = subView as! UIImageView
imageView.kf_setImageWithURL(NSURL(string: (imagemodel?.content)!), placeholderImage: dImage, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//视频
//标题文字
if model?.widget_data?.count > i*4+2{
let titleModel = model?.widget_data![i*4+2]
if titleModel?.type == "text"{
//获取标题的label
let subView = contentView.viewWithTag(400+i)
if subView?.isKindOfClass(UILabel.self) == true{
let titleLabel = subView as! UILabel
titleLabel.text = titleModel?.content
}
}
}
//详情文字
if model?.widget_data?.count > i*4+3{
let descModel = model?.widget_data![i*4+3]
if descModel?.type == "text"{
let subView = contentView.viewWithTag(500+i)
if subView?.isKindOfClass(UILabel.self) == true{
let descLabel = subView as! UILabel
descLabel.text = descModel?.content
}
}
}
}
}
//创建cell的方法
class func creatNewCellForTabView(tabView:UITableView,atIdexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendwidgetListModel)->CBRecommendNewCell{
let cellId = "NewCellId"
var cell = tabView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendNewCell
if nil == cell{
cell = NSBundle.mainBundle().loadNibNamed("CBRecommendNewCell", owner: nil, options: nil).last as? CBRecommendNewCell
}
cell?.model = listModel
return cell!
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 044861e11159bd258940529c5672daa0 | 28.290909 | 183 | 0.501552 | 5.256117 | false | false | false | false |
alessandrostone/MusicTheory | MusicTheory/NoteWithIntervals.swift | 1 | 798 | //
// NoteWithIntervals.swift
// MusicTheory
//
// Created by Daniel Breves Ribeiro on 2/04/2015.
// Copyright (c) 2015 Daniel Breves. All rights reserved.
//
import Foundation
public class RootWithIntervals {
public let notes: [Note]
public init(root: Note, intervals: [String]) {
var currentNote = root
var notes = [currentNote]
for interval in intervals {
currentNote = currentNote.add(interval)
notes.append(currentNote)
}
self.notes = notes
}
private(set) public lazy var names: [String] = {
return self.notes.map {
(var note) -> String in
return note.name
}
}()
private(set) public lazy var values: [Int8] = {
return self.notes.map {
(var note) -> Int8 in
return note.value
}
}()
} | mit | 2e033ef7bc1059a06cda354bbfb5cb2f | 19.487179 | 58 | 0.621554 | 3.627273 | false | false | false | false |
space150/spaceLock | ios/spacelab/SLNewKeyViewController.swift | 3 | 19468 | //
// SLNewKeyViewController.swift
// spacelab
//
// Created by Shawn Roske on 5/18/15.
// Copyright (c) 2015 space150. 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 UIKit
import LockKit
class SLNewKeyViewController: UITableViewController,
SLKeyOutputViewCellDelegate,
UIImagePickerControllerDelegate,
UINavigationControllerDelegate
{
@IBOutlet weak var lockIdLabel: UITextField!
@IBOutlet weak var lockNameLabel: UITextField!
@IBOutlet weak var iconImageButton: UIButton!
@IBOutlet weak var outputLabel: UILabel!
@IBOutlet weak var saveButton: UIBarButtonItem!
private var security: LKSecurityManager!
private var sectionCount: Int!
private var takenImage: UIImage!
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
security = LKSecurityManager()
sectionCount = 1
setupIconImageCircle()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func setupIconImageCircle()
{
var path = UIBezierPath(ovalInRect: iconImageButton.bounds)
var maskLayer = CAShapeLayer()
maskLayer.path = path.CGPath
iconImageButton.layer.mask = maskLayer
var outlineLayer = CAShapeLayer()
outlineLayer.lineWidth = 10.0
outlineLayer.fillColor = UIColor.clearColor().CGColor
outlineLayer.strokeColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1.0).CGColor
outlineLayer.path = path.CGPath
iconImageButton.layer.addSublayer(outlineLayer)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return sectionCount
}
/*
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 0
}
*/
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
// MARK: - UITextField Validations
@IBAction func lockIdEditingChanged(sender: AnyObject)
{
checkMaxLength(lockIdLabel, maxLength: 15)
}
@IBAction func lockNameEditingChanged(sender: AnyObject)
{
checkMaxLength(lockNameLabel, maxLength: 20)
}
func checkMaxLength(textField: UITextField!, maxLength: Int)
{
if (count(textField.text!) > maxLength)
{
textField.deleteBackward()
}
}
// MARK: - SLKeyOutputViewCellDelegate Methods
func doCopy(sender: AnyObject?)
{
let cell: SLKeyOutputViewCell = sender as! SLKeyOutputViewCell
cell.delegate = nil
UIPasteboard.generalPasteboard().string = outputLabel.text
println("added: \(outputLabel.text) to the pasteboard")
}
// MARK: - UITableViewDelegate Methods
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
if ( indexPath.section == 1 && indexPath.row == 0 )
{
let cell: SLKeyOutputViewCell = tableView.cellForRowAtIndexPath(indexPath) as! SLKeyOutputViewCell
cell.delegate = self
cell.becomeFirstResponder()
let controller = UIMenuController.sharedMenuController()
controller.setTargetRect(cell.frame, inView: view)
controller.setMenuVisible(true, animated: true)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
// MARK: - Key Generation
@IBAction func generateKeyTouched(sender: AnyObject)
{
saveButton.enabled = false
let lockId = lockIdLabel.text
let lockName = lockNameLabel.text
// simple validation of input
if ( lockId == "" || lockName == "" )
{
let alertController = UIAlertController(title: "Invalid", message: "Lock ID and Name are required", preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { (action) in
self.saveButton.enabled = true
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true) {
// nothing
}
return;
}
// check to see if this key already exists
if ( validateKey(lockId, name: lockName) )
{
saveKey()
}
else
{
let alertController = UIAlertController(title: "A key with that ID already exists!", message: "Are you positive you would like to generate a new key? DOING SO WILL DESTROY THE EXISTING KEY!", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action) in
self.saveButton.enabled = true
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "Yes", style: .Default) { (action) in
self.saveKey()
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true) {
// nothing
}
}
}
private func validateKey(id: String, name: String) -> Bool
{
let fetchRequest = NSFetchRequest(entityName: "LKKey")
fetchRequest.predicate = NSPredicate(format: "lockId == %@", id)
let fetchResults = LKLockRepository.sharedInstance().managedObjectContext!!.executeFetchRequest(fetchRequest, error: nil)
if ( fetchResults?.count == 0 ) {
return true
}
return false
}
private func saveKey()
{
let lockId = lockIdLabel.text
let lockName = lockNameLabel.text
// generate key and store it in the keychain
let keyData: NSData = security.generateNewKeyForLockName(lockId)!
let handshakeData: NSData = security.encryptString(lockId, withKey: keyData)
// force save by deleting the existing key from the keychain
// the user was warned previously about this if the entry exists in coredata
// if the key exists without being in coredata just toss it aside anyway!
let key = security.findKey(lockId)
if ( key != nil )
{
security.deleteKey(lockId)
}
let error = security.saveKey(lockId, key: keyData)
if ( error != nil )
{
let alertController = UIAlertController(title: "Unable to save key in keychain!", message: error?.localizedDescription, preferredStyle: .Alert)
let okAction = UIAlertAction(title: "OK", style: .Cancel) { (action) in
// nothing
}
alertController.addAction(okAction)
self.presentViewController(alertController, animated: true) {
// nothing
}
}
else
{
// update the UI on the main thread
dispatch_async(dispatch_get_main_queue(), {
// find or update coredata entry
var key: LKKey;
let fetchRequest = NSFetchRequest(entityName: "LKKey")
fetchRequest.predicate = NSPredicate(format: "lockId == %@", lockId)
let fetchResults = LKLockRepository.sharedInstance().managedObjectContext!!.executeFetchRequest(fetchRequest, error: nil)
if ( fetchResults?.count > 0 )
{
key = fetchResults?.first as! LKKey
key.lockName = lockName
}
else
{
key = NSEntityDescription.insertNewObjectForEntityForName("LKKey", inManagedObjectContext: LKLockRepository.sharedInstance().managedObjectContext!!) as! LKKey
key.lockId = lockId
key.lockName = lockName
}
// save the image to the filesystem
if ( self.takenImage != nil )
{
var path = NSHomeDirectory().stringByAppendingPathComponent(NSString(format: "Documents/key-%@.png", lockId) as! String)
let success = UIImagePNGRepresentation(self.takenImage)
.writeToFile(path, atomically: true)
if ( success == true ) {
println("saved image to: \(path)")
key.imageFilename = path
}
}
LKLockRepository.sharedInstance().saveContext()
// display sketch info
self.outputLabel.text = NSString(format: "#define LOCK_NAME \"%@\"\nbyte key[] = {\n%@\n};\nchar handshake[] = {\n%@\n};", lockId,
keyData.hexadecimalString(),
handshakeData.hexadecimalString()) as String
// update the table view so it displays the sketch info
self.sectionCount = 2
self.tableView.reloadData()
})
}
}
// MARK: - Icon Image Selection
@IBAction func iconImageButtonTouched(sender: AnyObject)
{
var picker = UIImagePickerController()
picker.delegate = self
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.Camera
picker.cameraCaptureMode = .Photo
presentViewController(picker, animated: true, completion: nil)
}
//MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
var chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
takenImage = RBSquareImageTo(fixImageOrientation(chosenImage), size:CGSize(width: 300.0, height: 300.0))
iconImageButton.setImage(takenImage, forState: UIControlState.Normal)
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - Image Manipulation
// image orientation fix from http://stackoverflow.com/a/27083555
private func fixImageOrientation(img:UIImage) -> UIImage
{
// No-op if the orientation is already correct
if (img.imageOrientation == UIImageOrientation.Up) {
return img;
}
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
var transform:CGAffineTransform = CGAffineTransformIdentity
if (img.imageOrientation == UIImageOrientation.Down
|| img.imageOrientation == UIImageOrientation.DownMirrored) {
transform = CGAffineTransformTranslate(transform, img.size.width, img.size.height)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI))
}
if (img.imageOrientation == UIImageOrientation.Left
|| img.imageOrientation == UIImageOrientation.LeftMirrored) {
transform = CGAffineTransformTranslate(transform, img.size.width, 0)
transform = CGAffineTransformRotate(transform, CGFloat(M_PI_2))
}
if (img.imageOrientation == UIImageOrientation.Right
|| img.imageOrientation == UIImageOrientation.RightMirrored) {
transform = CGAffineTransformTranslate(transform, 0, img.size.height);
transform = CGAffineTransformRotate(transform, CGFloat(-M_PI_2));
}
if (img.imageOrientation == UIImageOrientation.UpMirrored
|| img.imageOrientation == UIImageOrientation.DownMirrored) {
transform = CGAffineTransformTranslate(transform, img.size.width, 0)
transform = CGAffineTransformScale(transform, -1, 1)
}
if (img.imageOrientation == UIImageOrientation.LeftMirrored
|| img.imageOrientation == UIImageOrientation.RightMirrored) {
transform = CGAffineTransformTranslate(transform, img.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
var ctx:CGContextRef = CGBitmapContextCreate(nil, Int(img.size.width), Int(img.size.height),
CGImageGetBitsPerComponent(img.CGImage), 0,
CGImageGetColorSpace(img.CGImage),
CGImageGetBitmapInfo(img.CGImage));
CGContextConcatCTM(ctx, transform)
if (img.imageOrientation == UIImageOrientation.Left
|| img.imageOrientation == UIImageOrientation.LeftMirrored
|| img.imageOrientation == UIImageOrientation.Right
|| img.imageOrientation == UIImageOrientation.RightMirrored
)
{
CGContextDrawImage(ctx, CGRectMake(0,0,img.size.height,img.size.width), img.CGImage)
} else {
CGContextDrawImage(ctx, CGRectMake(0,0,img.size.width,img.size.height), img.CGImage)
}
// And now we just create a new UIImage from the drawing context
var cgimg:CGImageRef = CGBitmapContextCreateImage(ctx)
var imgEnd:UIImage = UIImage(CGImage: cgimg)!
return imgEnd
}
// square cropped image from https://gist.github.com/hcatlin/180e81cd961573e3c54d
func RBSquareImageTo(image: UIImage, size: CGSize) -> UIImage
{
return RBResizeImage(RBSquareImage(image), targetSize: size)
}
func RBSquareImage(image: UIImage) -> UIImage
{
var originalWidth = image.size.width
var originalHeight = image.size.height
var edge: CGFloat
if originalWidth > originalHeight {
edge = originalHeight
} else {
edge = originalWidth
}
var posX = (originalWidth - edge) / 2.0
var posY = (originalHeight - edge) / 2.0
var cropSquare = CGRectMake(posX, posY, edge, edge)
var imageRef = CGImageCreateWithImageInRect(image.CGImage, cropSquare);
return UIImage(CGImage: imageRef, scale: UIScreen.mainScreen().scale, orientation: image.imageOrientation)!
}
func RBResizeImage(image: UIImage, targetSize: CGSize) -> UIImage
{
let size = image.size
let widthRatio = targetSize.width / image.size.width
let heightRatio = targetSize.height / image.size.height
// Figure out what our orientation is, and use that to form the rectangle
var newSize: CGSize
if(widthRatio > heightRatio) {
newSize = CGSizeMake(size.width * heightRatio, size.height * heightRatio)
} else {
newSize = CGSizeMake(size.width * widthRatio, size.height * widthRatio)
}
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRectMake(0, 0, newSize.width, newSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
image.drawInRect(rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| mit | eb765b402bf20efc8eb5cedb8c6f7e49 | 38.569106 | 227 | 0.626978 | 5.391304 | false | false | false | false |
TBXark/TKSwitcherCollection | TKSwitcherCollection/TKBaseSwitcher.swift | 1 | 2324 | //
// TKBaseSwitcher.swift
// SwitcherCollection
//
// Created by Tbxark on 15/10/25.
// Copyright © 2015年 TBXark. All rights reserved.
//
import UIKit
public typealias TKSwitchValueChangeHook = (_ value: Bool) -> Void
// 自定义 Switch 基类
@IBDesignable
open class TKBaseSwitch: UIControl {
// MARK: - Property
open var valueChange: TKSwitchValueChangeHook?
@IBInspectable open var animateDuration: Double = 0.4
@IBInspectable open var isOn: Bool {
set {
on = newValue
}
get {
return on
}
}
internal var on: Bool = true
internal var sizeScale: CGFloat {
return min(self.bounds.width, self.bounds.height)/100.0
}
open override var frame: CGRect {
didSet {
guard frame.size != oldValue.size else { return }
resetView()
}
}
open override var bounds: CGRect {
didSet {
guard frame.size != oldValue.size else { return }
resetView()
}
}
// MARK: - Getter
final public func setOn(_ on: Bool, animate: Bool = true) {
guard on != isOn else { return }
toggleValue()
}
// MARK: - Init
convenience public init() {
self.init(frame: CGRect(x: 0, y: 0, width: 80, height: 40))
}
override public init(frame: CGRect) {
super.init(frame: frame)
setUpView()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpView()
}
// MARK: - Internal
internal func resetView() {
gestureRecognizers?.forEach(self.removeGestureRecognizer)
layer.sublayers?.forEach({ $0.removeFromSuperlayer()})
setUpView()
}
internal func setUpView() {
let tap = UITapGestureRecognizer(target: self, action: #selector(TKBaseSwitch.toggleValue))
self.addGestureRecognizer(tap)
for view in self.subviews {
view.removeFromSuperview()
}
}
@objc internal func toggleValue() {
self.on.toggle()
valueChange?(!isOn)
sendActions(for: UIControlEvents.valueChanged)
changeValueAnimate(isOn, duration: animateDuration)
}
internal func changeValueAnimate(_ value: Bool, duration: Double) {
}
}
| mit | 46f1706745980cf14e4a6beeadb83263 | 22.824742 | 99 | 0.596711 | 4.36862 | false | false | false | false |
nicolastinkl/swift | AdventureBuildingaSpriteKitgameusingSwift/Adventure/Adventure Shared/Sprites/Character.swift | 1 | 8267 | /*
Copyright (C) 2014 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Defines the class for a character in Adventure
*/
import SpriteKit
enum AnimationState: UInt32 {
case Idle = 0, Walk, Attack, GetHit, Death
}
enum MoveDirection {
case Forward, Left, Right, Back
}
enum ColliderType: UInt32 {
case Hero = 1
case GoblinOrBoss = 2
case Projectile = 4
case Wall = 8
case Cave = 16
}
class Character: ParallaxSprite {
var dying = false
var attacking = false
var health = 100.0
var animated = true
var animationSpeed: CGFloat = 1.0/28.0
var movementSpeed: CGFloat = 200.0
var rotationSpeed: CGFloat = 0.06
var requestedAnimation = AnimationState.Idle
var characterScene: LayeredCharacterScene {
return self.scene as LayeredCharacterScene
}
var shadowBlob = SKSpriteNode()
func idleAnimationFrames() -> SKTexture[] {
return []
}
func walkAnimationFrames() -> SKTexture[] {
return []
}
func attackAnimationFrames() -> SKTexture[] {
return []
}
func getHitAnimationFrames() -> SKTexture[] {
return []
}
func deathAnimationFrames() -> SKTexture[] {
return []
}
func damageEmitter() -> SKEmitterNode {
return SKEmitterNode()
}
func damageAction() -> SKAction {
return SKAction()
}
init(sprites: SKSpriteNode[], atPosition position: CGPoint, usingOffset offset: CGFloat) {
super.init(sprites: sprites, usingOffset: offset)
sharedInitAtPosition(position)
}
init(texture: SKTexture?, atPosition position: CGPoint) {
let size = texture ? texture!.size() : CGSize(width: 0, height: 0)
super.init(texture: texture, color: SKColor.whiteColor(), size: size)
sharedInitAtPosition(position)
}
func sharedInitAtPosition(position: CGPoint) {
let atlas = SKTextureAtlas(named: "Environment")
shadowBlob = SKSpriteNode(texture: atlas.textureNamed("blobShadow.png"))
shadowBlob.zPosition = -1.0
self.position = position
configurePhysicsBody()
}
func reset() {
health = 100.0
dying = false
attacking = false
animated = true
requestedAnimation = .Idle
shadowBlob.alpha = 1.0
}
// OVERRIDDEN METHODS
func performAttackAction() {
if attacking {
return
}
attacking = true
requestedAnimation = .Attack
}
func performDeath() {
health = 0.0
dying = true
requestedAnimation = .Death
}
func configurePhysicsBody() {
}
func animationDidComplete(animation: AnimationState) {
}
func collidedWith(other: SKPhysicsBody) {
}
// DAMAGE
func applyDamage(var damage: Double, projectile: SKNode? = nil) -> Bool {
if let proj = projectile {
damage *= Double(proj.alpha)
}
health -= damage
if health > 0.0 {
let emitter = damageEmitter().copy() as SKEmitterNode
characterScene.addNode(emitter, atWorldLayer: .AboveCharacter)
emitter.position = position
runOneShotEmitter(emitter, withDuration: 0.15)
runAction(damageAction())
return false
}
performDeath()
return true
}
// SHADOW BLOB
override func setScale(scale: CGFloat) {
super.setScale(scale)
shadowBlob.setScale(scale)
}
// LOOP UPDATE
func updateWithTimeSinceLastUpdate(interval: NSTimeInterval) {
shadowBlob.position = position
if !animated {
return
}
resolveRequestedAnimation()
}
// ANIMATION
func resolveRequestedAnimation() {
var (frames, key) = animationFramesAndKeyForState(requestedAnimation)
fireAnimationForState(requestedAnimation, usingTextures: frames, withKey: key)
requestedAnimation = dying ? .Death : .Idle
}
func animationFramesAndKeyForState(state: AnimationState) -> (SKTexture[], String) {
switch state {
case .Walk:
return (walkAnimationFrames(), "anim_walk")
case .Attack:
return (attackAnimationFrames(), "anim_attack")
case .GetHit:
return (getHitAnimationFrames(), "anim_gethit")
case .Death:
return (deathAnimationFrames(), "anim_death")
case .Idle:
return (idleAnimationFrames(), "anim_idle")
}
}
func fireAnimationForState(animationState: AnimationState, usingTextures frames: SKTexture[], withKey key: String) {
var animAction = actionForKey(key)
if animAction != nil || frames.count < 1 {
return
}
let animationAction = SKAction.animateWithTextures(frames, timePerFrame: NSTimeInterval(animationSpeed), resize: true, restore: false)
let blockAction = SKAction.runBlock {
self.animationHasCompleted(animationState)
}
runAction(SKAction.sequence([animationAction, blockAction]), withKey: key)
}
func animationHasCompleted(animationState: AnimationState) {
if dying {
animated = false
shadowBlob.runAction(SKAction.fadeOutWithDuration(1.5))
}
animationDidComplete(animationState)
if attacking {
attacking = false
}
}
func fadeIn(duration: NSTimeInterval) {
let fadeAction = SKAction.fadeInWithDuration(duration)
alpha = 0.0
runAction(fadeAction)
shadowBlob.alpha = 0.0
shadowBlob.runAction(fadeAction)
}
// WORKING WITH SCENES
func addToScene(scene: LayeredCharacterScene) {
scene.addNode(self, atWorldLayer: .Character)
scene.addNode(shadowBlob, atWorldLayer: .BelowCharacter)
}
override func removeFromParent() {
shadowBlob.removeFromParent()
super.removeFromParent()
}
// Movement
func move(direction: MoveDirection, withTimeInterval timeInterval: NSTimeInterval) {
var action: SKAction
switch direction {
case .Forward:
let x = -sin(zRotation) * movementSpeed * CGFloat(timeInterval)
let y = cos(zRotation) * movementSpeed * CGFloat(timeInterval)
action = SKAction.moveByX(x, y: y, duration: timeInterval)
case .Back:
let x = sin(zRotation) * movementSpeed * CGFloat(timeInterval)
let y = -cos(zRotation) * movementSpeed * CGFloat(timeInterval)
action = SKAction.moveByX(x, y: y, duration: timeInterval)
case .Left:
action = SKAction.rotateByAngle(rotationSpeed, duration:timeInterval)
case .Right:
action = SKAction.rotateByAngle(-rotationSpeed, duration:timeInterval)
}
if action != nil {
requestedAnimation = .Walk
runAction(action)
}
}
func faceTo(position: CGPoint) -> CGFloat {
var angle = adjustAssetOrientation(position.radiansToPoint(self.position))
var action = SKAction.rotateToAngle(angle, duration: 0)
runAction(action)
return angle
}
func moveTowards(targetPosition: CGPoint, withTimeInterval timeInterval: NSTimeInterval) {
// Grab an immutable position in case Sprite Kit changes it underneath us.
let current = position
var deltaX = targetPosition.x - current.x
var deltaY = targetPosition.y - current.y
var deltaT = movementSpeed * CGFloat(timeInterval)
var angle = adjustAssetOrientation(targetPosition.radiansToPoint(current))
var action = SKAction.rotateToAngle(angle, duration: 0)
runAction(action)
var distRemaining = hypot(deltaX, deltaY)
if distRemaining < deltaT {
position = targetPosition
} else {
let x = current.x - (deltaT * sin(angle))
let y = current.y + (deltaT * cos(angle))
position = CGPoint(x: x, y: y)
}
requestedAnimation = .Walk
}
}
| mit | f2492c23cf947ee182cd7451fa11d4be | 26.1875 | 142 | 0.614882 | 4.808028 | false | false | false | false |
iOS-mamu/SS | P/PotatsoModel/Proxy.swift | 1 | 10944 | //
// Proxy.swift
// Potatso
//
// Created by LEI on 4/6/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import RealmSwift
import CloudKit
public enum ProxyType: String {
case Shadowsocks = "SS"
case ShadowsocksR = "SSR"
case Https = "HTTPS"
case Socks5 = "SOCKS5"
case None = "NONE"
}
extension ProxyType: CustomStringConvertible {
public var description: String {
return rawValue
}
public var isShadowsocks: Bool {
return self == .Shadowsocks || self == .ShadowsocksR
}
}
public enum ProxyError: Error {
case invalidType
case invalidName
case invalidHost
case invalidPort
case invalidAuthScheme
case nameAlreadyExists
case invalidUri
case invalidPassword
}
extension ProxyError: CustomStringConvertible {
public var description: String {
switch self {
case .invalidType:
return "Invalid type"
case .invalidName:
return "Invalid name"
case .invalidHost:
return "Invalid host"
case .invalidAuthScheme:
return "Invalid encryption"
case .invalidUri:
return "Invalid uri"
case .nameAlreadyExists:
return "Name already exists"
case .invalidPassword:
return "Invalid password"
case .invalidPort:
return "Invalid port"
}
}
}
open class Proxy: BaseModel {
open dynamic var typeRaw = ProxyType.Shadowsocks.rawValue
open dynamic var name = ""
open dynamic var host = ""
open dynamic var port = 0
open dynamic var authscheme: String? // method in SS
open dynamic var user: String?
open dynamic var password: String?
open dynamic var ota: Bool = false
open dynamic var ssrProtocol: String?
open dynamic var ssrObfs: String?
open dynamic var ssrObfsParam: String?
open static let ssUriPrefix = "ss://"
open static let ssrUriPrefix = "ssr://"
open static let ssrSupportedProtocol = [
"origin",
"verify_simple",
"auth_simple",
"auth_sha1",
"auth_sha1_v2"
]
open static let ssrSupportedObfs = [
"plain",
"http_simple",
"tls1.0_session_auth",
"tls1.2_ticket_auth"
]
open static let ssSupportedEncryption = [
"table",
"rc4",
"rc4-md5",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"bf-cfb",
"camellia-128-cfb",
"camellia-192-cfb",
"camellia-256-cfb",
"cast5-cfb",
"des-cfb",
"idea-cfb",
"rc2-cfb",
"seed-cfb",
"salsa20",
"chacha20",
"chacha20-ietf"
]
open override static func indexedProperties() -> [String] {
return ["name"]
}
open override func validate(inRealm realm: Realm) throws {
guard let _ = ProxyType(rawValue: typeRaw)else {
throw ProxyError.invalidType
}
guard name.characters.count > 0 else{
throw ProxyError.invalidName
}
guard host.characters.count > 0 else {
throw ProxyError.invalidHost
}
guard port > 0 && port <= Int(UINT16_MAX) else {
throw ProxyError.invalidPort
}
switch type {
case .Shadowsocks, .ShadowsocksR:
guard let _ = authscheme else {
throw ProxyError.invalidAuthScheme
}
default:
break
}
}
}
// Public Accessor
extension Proxy {
public var type: ProxyType {
get {
return ProxyType(rawValue: typeRaw) ?? .Shadowsocks
}
set(v) {
typeRaw = v.rawValue
}
}
public var uri: String {
switch type {
case .Shadowsocks:
if let authscheme = authscheme, let password = password {
return "ss://\(authscheme):\(password)@\(host):\(port)"
}
default:
break
}
return ""
}
open override var description: String {
return name
}
}
// API
extension Proxy {
}
// Import
extension Proxy {
public convenience init(dictionary: [String: AnyObject], inRealm realm: Realm) throws {
self.init()
if let uriString = dictionary["uri"] as? String {
guard let name = dictionary["name"] as? String else{
throw ProxyError.invalidName
}
self.name = name
if uriString.lowercased().hasPrefix(Proxy.ssUriPrefix) {
// Shadowsocks
let undecodedString = uriString.substring(from: uriString.characters.index(uriString.startIndex, offsetBy: Proxy.ssUriPrefix.characters.count))
guard let proxyString = base64DecodeIfNeeded(undecodedString), let _ = proxyString.range(of: ":")?.lowerBound else {
throw ProxyError.invalidUri
}
guard let pc1 = proxyString.range(of: ":")?.lowerBound, let pc2 = proxyString.range(of: ":", options: .backwards)?.lowerBound, let pcm = proxyString.range(of: "@", options: .backwards)?.lowerBound else {
throw ProxyError.invalidUri
}
if !(pc1 < pcm && pcm < pc2) {
throw ProxyError.invalidUri
}
let fullAuthscheme = proxyString.lowercased().substring(with: proxyString.startIndex..<pc1)
if let pOTA = fullAuthscheme.range(of: "-auth", options: .backwards)?.lowerBound {
self.authscheme = fullAuthscheme.substring(to: pOTA)
self.ota = true
}else {
self.authscheme = fullAuthscheme
}
self.password = proxyString.substring(with: proxyString.index(after: pc1)..<pcm)
self.host = proxyString.substring(with: proxyString.index(after: pcm)..<pc2)
guard let p = Int(proxyString.substring(with: proxyString.index(after: pc2)..<proxyString.endIndex)) else {
throw ProxyError.invalidPort
}
self.port = p
self.type = .Shadowsocks
}else if uriString.lowercased().hasPrefix(Proxy.ssrUriPrefix) {
let undecodedString = uriString.substring(from: uriString.characters.index(uriString.startIndex, offsetBy: Proxy.ssrUriPrefix.characters.count))
guard let proxyString = base64DecodeIfNeeded(undecodedString), let _ = proxyString.range(of: ":")?.lowerBound else {
throw ProxyError.invalidUri
}
var hostString: String = proxyString
var queryString: String = ""
if let queryMarkIndex = proxyString.range(of: "?", options: .backwards)?.lowerBound {
hostString = proxyString.substring(to: queryMarkIndex)
queryString = proxyString.substring(from: proxyString.index(after: queryMarkIndex))
}
if let hostSlashIndex = hostString.range(of: "/", options: .backwards)?.lowerBound {
hostString = hostString.substring(to: hostSlashIndex)
}
let hostComps = hostString.components(separatedBy: ":")
guard hostComps.count == 6 else {
throw ProxyError.invalidUri
}
self.host = hostComps[0]
guard let p = Int(hostComps[1]) else {
throw ProxyError.invalidPort
}
self.port = p
self.ssrProtocol = hostComps[2]
self.authscheme = hostComps[3]
self.ssrObfs = hostComps[4]
self.password = base64DecodeIfNeeded(hostComps[5])
for queryComp in queryString.components(separatedBy: "&") {
let comps = queryComp.components(separatedBy: "=")
guard comps.count == 2 else {
continue
}
switch comps[0] {
case "obfsparam":
self.ssrObfsParam = comps[1]
case "remarks":
self.name = comps[1]
default:
continue
}
}
self.type = .ShadowsocksR
}else {
// Not supported yet
throw ProxyError.invalidUri
}
}else {
guard let name = dictionary["name"] as? String else{
throw ProxyError.invalidName
}
guard let host = dictionary["host"] as? String else{
throw ProxyError.invalidHost
}
guard let typeRaw = (dictionary["type"] as? String)?.uppercased(), let type = ProxyType(rawValue: typeRaw) else{
throw ProxyError.invalidType
}
guard let portStr = (dictionary["port"] as? String), let port = Int(portStr) else{
throw ProxyError.invalidPort
}
guard let encryption = dictionary["encryption"] as? String else{
throw ProxyError.invalidAuthScheme
}
guard let password = dictionary["password"] as? String else{
throw ProxyError.invalidPassword
}
self.host = host
self.port = port
self.password = password
self.authscheme = encryption
self.name = name
self.type = type
}
if realm.objects(Proxy).filter("name = '\(name)'").first != nil {
self.name = "\(name) \(Proxy.dateFormatter.string(from: Date()))"
}
try validate(inRealm: realm)
}
fileprivate func base64DecodeIfNeeded(_ proxyString: String) -> String? {
if let _ = proxyString.range(of: ":")?.lowerBound {
return proxyString
}
let base64String = proxyString.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
let padding = base64String.characters.count + (base64String.characters.count % 4 != 0 ? (4 - base64String.characters.count % 4) : 0)
if let decodedData = Data(base64Encoded: base64String.padding(toLength: padding, withPad: "=", startingAt: 0), options: NSData.Base64DecodingOptions(rawValue: 0)), let decodedString = NSString(data: decodedData, encoding: String.Encoding.utf8.rawValue) {
return decodedString as String
}
return nil
}
public class func uriIsShadowsocks(_ uri: String) -> Bool {
return uri.lowercased().hasPrefix(Proxy.ssUriPrefix) || uri.lowercased().hasPrefix(Proxy.ssrUriPrefix)
}
}
public func ==(lhs: Proxy, rhs: Proxy) -> Bool {
return lhs.uuid == rhs.uuid
}
| mit | 48a135bb9efc6f9d748028524531b03b | 33.304075 | 262 | 0.555972 | 4.619249 | false | false | false | false |
richardbuckle/Laurine | Example/Pods/Warp/Source/WRPStructs.swift | 1 | 5988 | //
// WRPStructs.swift
//
// Copyright (c) 2016 Jiri Trecak (http://jiritrecak.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.
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Imports
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
//MARK: - Structures
public struct WRPProperty {
// All remote names that can be used as source of property content
var remoteNames : [String]
// Remote name that will be used for rebuilding of the value
var masterRemoteName : String
// Local property name
var localName : String
// Data type of the property
var elementDataType : WRPPropertyType
var optional : Bool = true
var format : String?
public init(remote : String, bindTo : String, type : WRPPropertyType) {
self.remoteNames = [remote]
self.masterRemoteName = remote
self.localName = bindTo
self.elementDataType = type
}
public init(remote : String, type : WRPPropertyType) {
self.remoteNames = [remote]
self.masterRemoteName = remote
self.localName = remote
self.elementDataType = type
}
public init(remote : String, type : WRPPropertyType, optional : Bool) {
self.optional = optional
self.remoteNames = [remote]
self.masterRemoteName = remote
self.localName = remote
self.elementDataType = type
}
public init(remote : String, bindTo : String, type : WRPPropertyType, optional : Bool) {
self.remoteNames = [remote]
self.masterRemoteName = remote
self.localName = bindTo
self.elementDataType = type
self.optional = optional
self.format = nil
}
public init(remote : String, bindTo : String, type : WRPPropertyType, optional : Bool, format : String?) {
self.remoteNames = [remote]
self.masterRemoteName = remote
self.localName = bindTo
self.elementDataType = type
self.optional = optional
self.format = format
}
public init(remotes : [String], primaryRemote : String, bindTo : String, type : WRPPropertyType) {
self.remoteNames = remotes
self.masterRemoteName = primaryRemote
self.localName = bindTo
self.elementDataType = type
self.optional = false
// Remote names cannot be null - if there is such case, just force masterRemoteName to be remote name
if self.remoteNames.count == 0 {
self.remoteNames.append(self.masterRemoteName)
}
}
public init(remotes : [String], primaryRemote : String, bindTo : String, type : WRPPropertyType, format : String?) {
self.remoteNames = remotes
self.masterRemoteName = primaryRemote
self.localName = bindTo
self.elementDataType = type
self.optional = false
self.format = format
// Remote names cannot be null - if there is such case, just force masterRemoteName to be remote name
if self.remoteNames.count == 0 {
self.remoteNames.append(self.masterRemoteName)
}
}
}
public struct WRPRelation {
var remoteName : String
var localName : String
var className : WRPObject.Type
var inverseName : String
var relationshipType : WRPRelationType
var inverseRelationshipType : WRPRelationType
var optional : Bool = true
public init(remote : String, bindTo : String, inverseBindTo : String, modelClass : WRPObject.Type, optional : Bool, relationType : WRPRelationType, inverseRelationType : WRPRelationType) {
self.remoteName = remote
self.localName = bindTo
self.inverseName = inverseBindTo
self.className = modelClass
self.relationshipType = relationType
self.inverseRelationshipType = inverseRelationType
self.optional = optional
}
}
struct AnyKey: Hashable {
private let underlying: Any
private let hashValueFunc: () -> Int
private let equalityFunc: (Any) -> Bool
init<T: Hashable>(_ key: T) {
// Capture the key's hashability and equatability using closures.
// The Key shares the hash of the underlying value.
underlying = key
hashValueFunc = { key.hashValue }
// The Key is equal to a Key of the same underlying type,
// whose underlying value is "==" to ours.
equalityFunc = {
if let other = $0 as? T {
return key == other
}
return false
}
}
var hashValue: Int { return hashValueFunc() }
}
func ==(x: AnyKey, y: AnyKey) -> Bool {
return x.equalityFunc(y.underlying)
}
| mit | 0af7f92634fc23c5deaab63eda5adb35 | 31.193548 | 192 | 0.619906 | 4.794235 | false | false | false | false |
ngoctuanqt/IOS | Twitter/Pods/LBTAComponents/LBTAComponents/Classes/DefaultCells.swift | 2 | 1476 | //
// DefaultCell.swift
// Pods
//
// Created by Brian Voong on 11/22/16.
//
//
import UIKit
class DefaultHeader: DefaultCell {
override var datasourceItem: Any? {
didSet {
if datasourceItem == nil {
label.text = "This is your default header"
}
}
}
override func setupViews() {
super.setupViews()
label.text = "Header Cell"
label.textAlignment = .center
}
}
class DefaultFooter: DefaultCell {
override var datasourceItem: Any? {
didSet {
if datasourceItem == nil {
label.text = "This is your default footer"
}
}
}
override func setupViews() {
super.setupViews()
label.text = "Footer Cell"
label.textAlignment = .center
}
}
class DefaultCell: DatasourceCell {
override var datasourceItem: Any? {
didSet {
if let text = datasourceItem as? String {
label.text = text
} else {
label.text = datasourceItem.debugDescription
}
}
}
let label = UILabel()
override func setupViews() {
super.setupViews()
addSubview(label)
label.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 10, bottomConstant: 0, rightConstant: 10, widthConstant: 0, heightConstant: 0)
}
}
| mit | e4717132689aad4924a26db271e42c2c | 21.707692 | 200 | 0.553523 | 4.685714 | false | false | false | false |
artsy/eigen | ios/Artsy/Views/Auction/SaleArtworkViewModel.swift | 1 | 1960 | import Foundation
import UIKit
@objc class SaleArtworkViewModel: NSObject {
fileprivate let saleArtwork: SaleArtwork
@objc init(saleArtwork: SaleArtwork) {
self.saleArtwork = saleArtwork
}
}
private typealias PublicComputedProperties = SaleArtworkViewModel
extension PublicComputedProperties {
@objc var thumbnailURL: URL? {
return saleArtwork.artwork.defaultImage.urlForThumbnailImage()
}
@objc var aspectRatio: CGFloat {
return saleArtwork.artwork.defaultImage.aspectRatio
}
@objc var artistName: String {
return saleArtwork.artwork.artist?.name ?? ""
}
@objc var artworkName: String {
return saleArtwork.artwork.title ?? ""
}
@objc var artworkDate: String {
return saleArtwork.artwork.date
}
@objc var lotLabel: String {
return saleArtwork.lotLabel ?? ""
}
@objc var isAuctionOpen: Bool {
// If we have no sale state, assume auction is closed to prevent leaking info post-sale.
guard let saleState = saleArtwork.auction?.saleState else { return false }
// For our purposes, an auction is "open" if its sale state is open or in preview.
return [SaleStateOpen, SaleStatePreview].contains(saleState)
}
@objc var numberOfBids: String {
return saleArtwork.numberOfBidsString()
}
@objc var artworkID: String {
return saleArtwork.artwork.artworkID
}
@objc func currentOrStartingBidWithNumberOfBids(_ includeNumberOfBids: Bool) -> String {
if saleArtwork.auctionState.contains(.ended) {
return ""
}
let bidString = saleArtwork.highestOrStartingBidString()
if includeNumberOfBids && (saleArtwork.bidCount?.intValue ?? 0) > 0 {
let numberOfBidsString = saleArtwork.numberOfBidsString()
return "\(bidString) \(numberOfBidsString)"
} else {
return bidString
}
}
}
| mit | 4a8cc3e9f95459a0ebc7d62d2922cb87 | 28.69697 | 96 | 0.664796 | 4.875622 | false | false | false | false |
curoo/IOSKeychain | ConfidoIOS/Keychain.swift | 3 | 11134 | //
// Keychain.swift
// ExpendSecurity
//
// Created by Rudolph van Graan on 18/08/2015.
//
//
import Foundation
public typealias SecItemAttributes = [ String : AnyObject]
public typealias ItemReference = AnyObject
public typealias KeyChainPropertiesData = [ String : AnyObject]
public typealias KeychainItemData = [ String : AnyObject]
func += <KeyType, ValueType> (left: inout Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
public enum KeychainError : Error, CustomStringConvertible {
case
noSecIdentityReference,
noSecCertificateReference,
noSecKeyReference,
unimplementedSecurityClass,
unimplementedKeyType(reason: String?),
mismatchedResultType(returnedType: AnyClass, declaredType: Any),
invalidCertificateData,
trustError(trustResult: TrustResult, reason: String?),
dataExceedsBlockSize(size: Int),
initialVectorMismatch(size: Int),
cryptoOperationFailed(status: Int32)
public var description : String {
switch self {
case .noSecIdentityReference: return "NoSecIdentityReference"
case .noSecCertificateReference: return "NoSecCertificateReference"
case .noSecKeyReference: return "NoSecKeyReference"
case .unimplementedSecurityClass: return "UnimplementedSecurityClass"
case .unimplementedKeyType(let reason): return "UnimplementedKeyType \(reason)"
case .mismatchedResultType(let returnedType, let declaredType) : return "MismatchedResultType (returned \(returnedType)) declared \(declaredType)"
case .invalidCertificateData: return "InvalidCertificateData"
case .trustError(_, let reason) : return "TrustError \(reason)"
case .dataExceedsBlockSize(let size) : return "Data exceeds cipher block size of \(size)"
case .initialVectorMismatch(let size) : return "Size of Initial Vector does not match block size of cipher (\(size))"
case .cryptoOperationFailed(let status): return "Common Crypto Operation Failed (\(status))"
}
}
}
/**
Wraps the raw secXYZ APIs
*/
open class SecurityWrapper {
/**
A typical query consists of:
* a kSecClass key, whose value is a constant from the Class
Constants section that specifies the class of item(s) to be searched
* one or more keys from the "Attribute Key Constants" section, whose value
is the attribute data to be matched
* one or more keys from the "Search Constants" section, whose value is
used to further refine the search
* a key from the "Return Type Key Constants" section, specifying the type of
results desired
Result types are specified as follows:
* To obtain the data of a matching item (CFDataRef), specify
kSecReturnData with a value of kCFBooleanTrue.
* To obtain the attributes of a matching item (CFDictionaryRef), specify
kSecReturnAttributes with a value of kCFBooleanTrue.
* To obtain a reference to a matching item (SecKeychainItemRef,
SecKeyRef, SecCertificateRef, or SecIdentityRef), specify kSecReturnRef
with a value of kCFBooleanTrue.
* To obtain a persistent reference to a matching item (CFDataRef),
specify kSecReturnPersistentRef with a value of kCFBooleanTrue. Note
that unlike normal references, a persistent reference may be stored
on disk or passed between processes.
* If more than one of these result types is specified, the result is
returned as a CFDictionaryRef containing all the requested data.
* If a result type is not specified, no results are returned.
By default, this function returns only the first match found. To obtain
more than one matching item at a time, specify kSecMatchLimit with a value
greater than 1. The result will be a CFArrayRef containing up to that
number of matching items; the items' types are described above.
To filter a provided list of items down to those matching the query,
specify a kSecMatchItemList whose value is a CFArray of SecKeychainItemRef,
SecKeyRef, SecCertificateRef, or SecIdentityRef items. The objects in the
provided array must be of the same type.
To convert from a persistent item reference to a normal item reference,
specify a kSecValuePersistentRef whose value a CFDataRef (the persistent
reference), and a kSecReturnRef whose value is kCFBooleanTrue.
*/
open class func secItemCopyMatching<T>(_ query: KeyChainPropertiesData) throws -> T {
var result: AnyObject?
let status = KeychainStatus.statusFromOSStatus(
withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
)
if status == .ok, let returnValue = result as? T {
return returnValue
} else if status == .ok, let returnValue = result {
throw KeychainError.mismatchedResultType(returnedType: type(of: returnValue), declaredType: T.self)
} else if status == .ok {
throw KeychainStatus.itemNotFoundError
}
throw status
}
open class func secItemAdd(_ attributes: KeychainItemData) throws -> AnyObject? {
var persistedRef: AnyObject?
let status = KeychainStatus.statusFromOSStatus(
withUnsafeMutablePointer(to: &persistedRef) { SecItemAdd(attributes as CFDictionary, UnsafeMutablePointer($0)) }
)
if status == .ok {
return persistedRef
}
throw status
}
open class func secItemDelete(_ query: KeyChainPropertiesData) throws {
let dictionary = NSMutableDictionary()
dictionary.addEntries(from: query)
let status = KeychainStatus.statusFromOSStatus(SecItemDelete(dictionary))
if status == .ok {
return
}
throw status
}
open class func secPKCS12Import(_ pkcs12Data: Data, options: KeyChainPropertiesData) throws -> [SecItemAttributes] {
var result: CFArray?
let osStatus = withUnsafeMutablePointer(to: &result) { SecPKCS12Import(pkcs12Data as CFData, options as CFDictionary, UnsafeMutablePointer($0)) }
let status = KeychainStatus.statusFromOSStatus(osStatus)
if status == .ok, let items = result as? [SecItemAttributes]
{
return items
}
else if status == .ok {
return []
}
throw status
}
}
public enum KeychainReturnLimit {
case one, all
}
open class Keychain {
open class func keyChainItems(_ securityClass: SecurityClass) throws -> [KeychainItem] {
return try fetchItems(matchingDescriptor: KeychainDescriptor(securityClass: securityClass), returning: .all)
}
open class func fetchItems(matchingDescriptor attributes: KeychainMatchable, returning: KeychainReturnLimit, returnData: Bool = false, returnRef: Bool = true) throws -> [KeychainItem] {
var query : KeyChainPropertiesData = [ : ]
query[String(kSecClass)] = SecurityClass.kSecClass(attributes.securityClass)
// kSecReturnAttributes true to ensure we don't get a raw SecKeychainItemRef or NSData back, this function can't handle it
// This means we should get either a Dictionary or [Dictionary]
query[String(kSecReturnAttributes)] = kCFBooleanTrue
query[String(kSecReturnData)] = returnData ? kCFBooleanTrue : kCFBooleanFalse
query[String(kSecReturnRef)] = returnRef ? kCFBooleanTrue : kCFBooleanFalse
query[String(kSecMatchLimit)] = returning == .one ? kSecMatchLimitOne : kSecMatchLimitAll
query += attributes.keychainMatchPropertyValues()
do {
var keychainItemDicts : [SecItemAttributes] = []
let itemDictOrDicts : NSObject = try SecurityWrapper.secItemCopyMatching(query)
if let itemDicts = itemDictOrDicts as? [SecItemAttributes] {
keychainItemDicts = itemDicts
} else if let itemDict = itemDictOrDicts as? SecItemAttributes {
keychainItemDicts.append(itemDict)
}
return try keychainItemDicts.flatMap { try makeKeyChainItem(attributes.securityClass, keychainItemAttributes: $0) }
}
catch KeychainStatus.itemNotFoundError {
return []
}
}
open class func fetchItem(matchingDescriptor attributes: KeychainMatchable, returnData: Bool = false, returnRef: Bool = true) throws -> KeychainItem {
let results = try self.fetchItems(matchingDescriptor: attributes, returning: .one, returnData: returnData, returnRef: returnRef)
if results.count == 1 { return results[0] }
throw KeychainStatus.itemNotFoundError
}
open class func deleteKeyChainItem(itemDescriptor descriptor: KeychainMatchable) throws {
try SecurityWrapper.secItemDelete(descriptor.keychainMatchPropertyValues())
}
class func makeKeyChainItem(_ securityClass: SecurityClass, keychainItemAttributes attributes: SecItemAttributes) throws -> KeychainItem? {
return try KeychainItem.itemFromAttributes(securityClass, SecItemAttributes: attributes)
}
// public class func addIdentity(identity: IdentityImportSpecifier) throws -> (KeychainStatus, Identity?) {
// var item : KeyChainPropertiesData = [ : ]
// item[String(kSecReturnPersistentRef)] = NSNumber(bool: true);
//
// item += identity.keychainMatchPropertyValues()
//
// //There seems to be a bug in the keychain that causes the SecItemAdd for Identities to fail silently when kSecClass is specified :S
// item.removeValueForKey(String(kSecClass))
//
// let itemRefs: AnyObject? = try SecurityWrapper.secItemAdd(item)
//
// }
open class func keyData(_ key: KeychainPublicKey) throws -> Data {
var query : KeyChainPropertiesData = [ : ]
let descriptor = key.keychainMatchPropertyValues()
query[String(kSecClass)] = SecurityClass.kSecClass(key.securityClass)
query[String(kSecReturnData)] = kCFBooleanTrue
query[String(kSecMatchLimit)] = kSecMatchLimitOne
query += descriptor.keychainMatchPropertyValues()
let keyData: Data = try SecurityWrapper.secItemCopyMatching(query)
return keyData
}
/**
Attempts to delete all items of a specific security class
:param: securityClass the class of item to delete
:returns: (successCount:Int, failureCount:Int)
*/
open class func deleteAllItemsOfClass(_ securityClass: SecurityClass) -> (Int,Int) {
do {
let items = try Keychain.keyChainItems(securityClass)
var successCount = 0
var failCount = 0
for item in items {
do {
try Keychain.deleteKeyChainItem(itemDescriptor: item.keychainMatchPropertyValues())
successCount += 1
} catch {
failCount += 1
}
}
return (successCount, failCount)
} catch {
return (0,0)
}
}
}
| mit | 5cc12681ebbca2dcd998c6808a72faeb | 41.334601 | 189 | 0.690228 | 4.972756 | false | false | false | false |
nearfri/Strix | Sources/StrixParsers/JSONParser.swift | 1 | 3224 | import Foundation
import Strix
public struct JSONParser {
private let parser: Parser<JSON>
public init() {
let ws = Parser.many(.whitespace)
parser = ws *> Parser.json <* ws <* .endOfStream
}
public func parse(_ jsonString: String) throws -> JSON {
return try parser.run(jsonString)
}
public func callAsFunction(_ jsonString: String) throws -> JSON {
return try parse(jsonString)
}
}
extension Parser where T == JSON {
public static var json: Parser<JSON> { JSONParserGenerator().json }
}
private struct JSONParserGenerator {
var json: Parser<JSON> {
return .recursive { placeholder in
return .any(of: [
objectJSON(json: placeholder), arrayJSON(json: placeholder),
stringJSON, numberJSON, trueJSON, falseJSON, nullJSON
])
}
}
private func objectJSON(json: Parser<JSON>) -> Parser<JSON> {
let pair: Parser<(String, JSON)> = .tuple(stringLiteral <* ws, colon *> ws *> json)
let pairs: Parser<[String: JSON]> = Parser.many(pair <* ws, separatedBy: comma *> ws).map {
Dictionary($0, uniquingKeysWith: { _, last in last })
}
return (.character("{") *> ws *> pairs <* .character("}")).map({ .object($0) })
}
private func arrayJSON(json: Parser<JSON>) -> Parser<JSON> {
let values: Parser<[JSON]> = Parser.many(json <* ws, separatedBy: comma *> ws)
return (.character("[") *> ws *> values <* .character("]")).map({ .array($0) })
}
private var stringJSON: Parser<JSON> { stringLiteral.map({ .string($0) }) }
private let numberJSON: Parser<JSON> = Parser.number().map({ .number($0) })
private let trueJSON: Parser<JSON> = .string("true") *> .just(.bool(true))
private let falseJSON: Parser<JSON> = .string("false") *> .just(.bool(false))
private let nullJSON: Parser<JSON> = .string("null") *> .just(.null)
private let ws: Parser<[Character]> = .many(.whitespace)
private let hex: Parser<Character> = .hexadecimalDigit
private let colon: Parser<Character> = .character(":")
private let comma: Parser<Character> = .character(",")
private var stringLiteral: Parser<String> {
let text = Parser.many(nonEscape <|> escape).map({ String($0) })
return .character("\"") *> text <* .character("\"")
}
private var nonEscape: Parser<Character> {
return .satisfy({ $0 != "\"" && $0 != "\\" }, label: "non-escaped character")
}
private var escape: Parser<Character> {
let escapeMap: [Character: Character] = [
"b": "\u{0008}", "f": "\u{000C}", "n": "\n", "r": "\r", "t": "\t"
]
let asciiEscape: Parser<Character> = Parser.any(of: "\"\\/bfnrt").map {
return escapeMap[$0] ?? $0
}
let unicodeEscape: Parser<Character> = (.character("u") *> .tuple(hex, hex, hex, hex)).map {
let scalar = Int(String([$0, $1, $2, $3]), radix: 16).flatMap({ UnicodeScalar($0) })
return Character(scalar ?? UnicodeScalar(0))
}
return .character("\\") *> (asciiEscape <|> unicodeEscape)
}
}
| mit | 44f8af54e95a765f21ff4040136f95c6 | 37.843373 | 100 | 0.57165 | 4.024969 | false | false | false | false |
lgrzywac/SWAPI-Swift | Sources/Networking/Extensions/DataRequest+SwiftyJSON.swift | 1 | 691 | //
// DataRequest+SwiftyJSON.swift
// SWAPI-Swift
//
// Created by Łukasz Grzywacz on 19/02/2017.
//
//
import Alamofire
import SwiftyJSON
public extension DataRequest {
@discardableResult
public func responseSwiftyJSON(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse, JSON?) -> Void) -> Self {
return response(queue: queue, completionHandler: { handler in
var responseJson: JSON? = nil
if let response = handler.response {
if response.statusCode == 200 {
if let data = handler.data {
responseJson = JSON(data)
}
}
}
completionHandler(handler, responseJson)
})
}
}
| apache-2.0 | 7718c62606043f833a5f3724cdf04280 | 23.642857 | 138 | 0.647826 | 4.394904 | false | false | false | false |
kunsy/DYZB | DYZB/DYZB/Classes/Main/Controller/CustomNavigationController.swift | 1 | 1801 | //
// CustomNavigationController.swift
// DYZB
//
// Created by Anyuting on 2017/9/4.
// Copyright © 2017年 Anyuting. All rights reserved.
//
import UIKit
class CustomNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//获取系统pop手势
guard let systemGes = interactivePopGestureRecognizer else { return }
//获取手势所在到view
guard let gesView = systemGes.view else { return }
//获取target&action
//利用运行时机制获取所有属性
/*var count : UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}*/
let targets = systemGes.value(forKey: "_targets") as? [NSObject]
guard let targetObjc = targets?.first else { return }
//取出target&action
print(targetObjc)
guard let target = targetObjc.value(forKey: "target") else { return }
//guard let action = targetObjc.value(forKey: "aciton") as? Selector else { return }
let action = Selector(("handleNavigationTransition:"))
//创建自己的pan手势
let panGes = UIPanGestureRecognizer()
gesView.addGestureRecognizer(panGes)
panGes.addTarget(target, action: action)
}
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
//隐藏一些tabbar
viewController.hidesBottomBarWhenPushed = true
super.pushViewController(viewController, animated: animated)
}
}
| mit | 0540f964444f1095e430bd6591f3fc0f | 31.377358 | 92 | 0.628788 | 4.753463 | false | false | false | false |
mitochrome/complex-gestures-demo | apps/GestureRecognizer/Carthage/Checkouts/RxSwift/RxExample/RxExample/Examples/UIPickerViewExample/CustomPickerViewAdapterExampleViewController.swift | 5 | 2104 | //
// CustomPickerViewAdapterExampleViewController.swift
// RxExample
//
// Created by Sergey Shulga on 12/07/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
final class CustomPickerViewAdapterExampleViewController: ViewController {
@IBOutlet weak var pickerView: UIPickerView!
override func viewDidLoad() {
super.viewDidLoad()
Observable.just([[1, 2, 3], [5, 8, 13], [21, 34]])
.bind(to: pickerView.rx.items(adapter: PickerViewViewAdapter()))
.disposed(by: disposeBag)
pickerView.rx.modelSelected(Int.self)
.subscribe(onNext: { models in
print(models)
})
.disposed(by: disposeBag)
}
}
final class PickerViewViewAdapter
: NSObject
, UIPickerViewDataSource
, UIPickerViewDelegate
, RxPickerViewDataSourceType
, SectionedViewDataSourceType {
typealias Element = [[CustomStringConvertible]]
private var items: [[CustomStringConvertible]] = []
func model(at indexPath: IndexPath) throws -> Any {
return items[indexPath.section][indexPath.row]
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return items.count
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return items[component].count
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
let label = UILabel()
label.text = items[component][row].description
label.textColor = UIColor.orange
label.font = UIFont.preferredFont(forTextStyle: .headline)
label.textAlignment = .center
return label
}
func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>) {
Binder(self) { (adapter, items) in
adapter.items = items
pickerView.reloadAllComponents()
}.on(observedEvent)
}
}
| mit | add50d527e0ee3490ee37f15f40faf68 | 28.619718 | 132 | 0.652401 | 4.93662 | false | false | false | false |
tzongw/ReactiveCocoa | ReactiveCocoa/Swift/Signal.swift | 1 | 49967 | import Foundation
import Result
/// A push-driven stream that sends Events over time, parameterized by the type
/// of values being sent (`Value`) and the type of failure that can occur (`Error`).
/// If no failures should be possible, NoError can be specified for `Error`.
///
/// An observer of a Signal will see the exact same sequence of events as all
/// other observers. In other words, events will be sent to all observers at the
/// same time.
///
/// Signals are generally used to represent event streams that are already “in
/// progress,” like notifications, user input, etc. To represent streams that
/// must first be _started_, see the SignalProducer type.
///
/// Signals do not need to be retained. A Signal will be automatically kept
/// alive until the event stream has terminated.
public final class Signal<Value, Error: ErrorType> {
public typealias Observer = ReactiveCocoa.Observer<Value, Error>
private let atomicObservers: Atomic<Bag<Observer>?> = Atomic(Bag())
/// Initializes a Signal that will immediately invoke the given generator,
/// then forward events sent to the given observer.
///
/// The disposable returned from the closure will be automatically disposed
/// if a terminating event is sent to the observer. The Signal itself will
/// remain alive until the observer is released.
public init(@noescape _ generator: Observer -> Disposable?) {
/// Used to ensure that events are serialized during delivery to observers.
let sendLock = NSLock()
sendLock.name = "org.reactivecocoa.ReactiveCocoa.Signal"
let generatorDisposable = SerialDisposable()
/// When set to `true`, the Signal should interrupt as soon as possible.
let interrupted = Atomic(false)
let observer = Observer { event in
if case .Interrupted = event {
// Normally we disallow recursive events, but
// Interrupted is kind of a special snowflake, since it
// can inadvertently be sent by downstream consumers.
//
// So we'll flag Interrupted events specially, and if it
// happened to occur while we're sending something else,
// we'll wait to deliver it.
interrupted.value = true
if sendLock.tryLock() {
self.interrupt()
sendLock.unlock()
generatorDisposable.dispose()
}
} else {
if let observers = (event.isTerminating ? self.atomicObservers.swap(nil) : self.atomicObservers.value) {
sendLock.lock()
for observer in observers {
observer.action(event)
}
let shouldInterrupt = !event.isTerminating && interrupted.value
if shouldInterrupt {
self.interrupt()
}
sendLock.unlock()
if event.isTerminating || shouldInterrupt {
// Dispose only after notifying observers, so disposal logic
// is consistently the last thing to run.
generatorDisposable.dispose()
}
}
}
}
generatorDisposable.innerDisposable = generator(observer)
}
/// A Signal that never sends any events to its observers.
public static var never: Signal {
return self.init { _ in nil }
}
/// A Signal that completes immediately without emitting any value.
public static var empty: Signal {
return self.init { observer in
observer.sendCompleted()
return nil
}
}
/// Creates a Signal that will be controlled by sending events to the given
/// observer.
///
/// The Signal will remain alive until a terminating event is sent to the
/// observer.
public static func pipe() -> (Signal, Observer) {
var observer: Observer!
let signal = self.init { innerObserver in
observer = innerObserver
return nil
}
return (signal, observer)
}
/// Interrupts all observers and terminates the stream.
private func interrupt() {
if let observers = self.atomicObservers.swap(nil) {
for observer in observers {
observer.sendInterrupted()
}
}
}
/// Observes the Signal by sending any future events to the given observer. If
/// the Signal has already terminated, the observer will immediately receive an
/// `Interrupted` event.
///
/// Returns a Disposable which can be used to disconnect the observer. Disposing
/// of the Disposable will have no effect on the Signal itself.
public func observe(observer: Observer) -> Disposable? {
var token: RemovalToken?
atomicObservers.modify { observers in
guard var observers = observers else {
return nil
}
token = observers.insert(observer)
return observers
}
if let token = token {
return ActionDisposable { [weak self] in
self?.atomicObservers.modify { observers in
guard var observers = observers else {
return nil
}
observers.removeValueForToken(token)
return observers
}
}
} else {
observer.sendInterrupted()
return nil
}
}
}
public protocol SignalType {
/// The type of values being sent on the signal.
associatedtype Value
/// The type of error that can occur on the signal. If errors aren't possible
/// then `NoError` can be used.
associatedtype Error: ErrorType
/// Extracts a signal from the receiver.
var signal: Signal<Value, Error> { get }
/// Observes the Signal by sending any future events to the given observer.
func observe(observer: Signal<Value, Error>.Observer) -> Disposable?
}
extension Signal: SignalType {
public var signal: Signal {
return self
}
}
extension SignalType {
/// Convenience override for observe(_:) to allow trailing-closure style
/// invocations.
public func observe(action: Signal<Value, Error>.Observer.Action) -> Disposable? {
return observe(Observer(action))
}
/// Observes the Signal by invoking the given callback when `next` events are
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callbacks. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeNext(next: Value -> Void) -> Disposable? {
return observe(Observer(next: next))
}
/// Observes the Signal by invoking the given callback when a `completed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeCompleted(completed: () -> Void) -> Disposable? {
return observe(Observer(completed: completed))
}
/// Observes the Signal by invoking the given callback when a `failed` event is
/// received.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeFailed(error: Error -> Void) -> Disposable? {
return observe(Observer(failed: error))
}
/// Observes the Signal by invoking the given callback when an `interrupted` event is
/// received. If the Signal has already terminated, the callback will be invoked
/// immediately.
///
/// Returns a Disposable which can be used to stop the invocation of the
/// callback. Disposing of the Disposable will have no effect on the Signal
/// itself.
public func observeInterrupted(interrupted: () -> Void) -> Disposable? {
return observe(Observer(interrupted: interrupted))
}
/// Maps each value in the signal to a new value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func map<U>(transform: Value -> U) -> Signal<U, Error> {
return Signal { observer in
return self.observe { event in
observer.action(event.map(transform))
}
}
}
/// Maps errors in the signal to a new error.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func mapError<F>(transform: Error -> F) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
observer.action(event.mapError(transform))
}
}
}
/// Preserves only the values of the signal that pass the given predicate.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func filter(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { (event: Event<Value, Error>) -> Void in
if case let .Next(value) = event {
if predicate(value) {
observer.sendNext(value)
}
} else {
observer.action(event)
}
}
}
}
}
extension SignalType where Value: OptionalType {
/// Unwraps non-`nil` values and forwards them on the returned signal, `nil`
/// values are dropped.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func ignoreNil() -> Signal<Value.Wrapped, Error> {
return filter { $0.optional != nil }.map { $0.optional! }
}
}
extension SignalType {
/// Returns a signal that will yield the first `count` values from `self`
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func take(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
return Signal { observer in
if count == 0 {
observer.sendCompleted()
return nil
}
var taken = 0
return self.observe { event in
if case let .Next(value) = event {
if taken < count {
taken += 1
observer.sendNext(value)
}
if taken == count {
observer.sendCompleted()
}
} else {
observer.action(event)
}
}
}
}
}
/// A reference type which wraps an array to auxiliate the collection of values
/// for `collect` operator.
private final class CollectState<Value> {
var values: [Value] = []
/// Collects a new value.
func append(value: Value) {
values.append(value)
}
/// Check if there are any items remaining.
///
/// - Note: This method also checks if there weren't collected any values
/// and, in that case, it means an empty array should be sent as the result
/// of collect.
var isEmpty: Bool {
/// We use capacity being zero to determine if we haven't collected any
/// value since we're keeping the capacity of the array to avoid
/// unnecessary and expensive allocations). This also guarantees
/// retro-compatibility around the original `collect()` operator.
return values.isEmpty && values.capacity > 0
}
/// Removes all values previously collected if any.
func flush() {
// Minor optimization to avoid consecutive allocations. Can
// be useful for sequences of regular or similar size and to
// track if any value was ever collected.
values.removeAll(keepCapacity: true)
}
}
extension SignalType {
/// Returns a signal that will yield an array of values when `self` completes.
///
/// - Note: When `self` completes without collecting any value, it will sent
/// an empty array of values.
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect() -> Signal<[Value], Error> {
return collect { _,_ in false }
}
/// Returns a signal that will yield an array of values until it reaches a
/// certain count.
///
/// When the count is reached the array is sent and the signal starts over
/// yielding a new array of values.
///
/// - Precondition: `count` should be greater than zero.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not have `count` values. Alternatively, if were not collected
/// any values will sent an empty array of values.
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(count count: Int) -> Signal<[Value], Error> {
precondition(count > 0)
return collect { values in values.count == count }
}
/// Returns a signal that will yield an array of values based on a predicate
/// which matches the values collected.
///
/// - parameter predicate: Predicate to match when values should be sent
/// (returning `true`) or alternatively when they should be collected (where
/// it should return `false`). The most recent value (`next`) is included in
/// `values` and will be the end of the current array of values if the
/// predicate returns `true`.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not match `predicate`. Alternatively, if were not collected any
/// values will sent an empty array of values.
///
/// #### Example
///
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values in values.reduce(0, combine: +) == 8 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(3)
/// observer.sendNext(4)
/// observer.sendNext(7)
/// observer.sendNext(1)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 3, 4]
/// // [7, 1]
/// // [5, 6]
///
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(predicate: (values: [Value]) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .Next(value):
state.append(value)
if predicate(values: state.values) {
observer.sendNext(state.values)
state.flush()
}
case .Completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .Failed(error):
observer.sendFailed(error)
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Returns a signal that will yield an array of values based on a predicate
/// which matches the values collected and the next value.
///
/// - parameter predicate: Predicate to match when values should be sent
/// (returning `true`) or alternatively when they should be collected (where
/// it should return `false`). The most recent value (`next`) is not included
/// in `values` and will be the start of the next array of values if the
/// predicate returns `true`.
///
/// - Note: When `self` completes any remaining values will be sent, the last
/// array may not match `predicate`. Alternatively, if were not collected any
/// values will sent an empty array of values.
///
/// #### Example
///
/// let (signal, observer) = Signal<Int, NoError>.pipe()
///
/// signal
/// .collect { values, next in next == 7 }
/// .observeNext { print($0) }
///
/// observer.sendNext(1)
/// observer.sendNext(1)
/// observer.sendNext(7)
/// observer.sendNext(7)
/// observer.sendNext(5)
/// observer.sendNext(6)
/// observer.sendCompleted()
///
/// // Output:
/// // [1, 1]
/// // [7]
/// // [7, 5, 6]
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func collect(predicate: (values: [Value], next: Value) -> Bool) -> Signal<[Value], Error> {
return Signal { observer in
let state = CollectState<Value>()
return self.observe { event in
switch event {
case let .Next(value):
if predicate(values: state.values, next: value) {
observer.sendNext(state.values)
state.flush()
}
state.append(value)
case .Completed:
if !state.isEmpty {
observer.sendNext(state.values)
}
observer.sendCompleted()
case let .Failed(error):
observer.sendFailed(error)
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forwards all events onto the given scheduler, instead of whichever
/// scheduler they originally arrived upon.
public func observeOn(scheduler: SchedulerType) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
scheduler.schedule {
observer.action(event)
}
}
}
}
}
private final class CombineLatestState<Value> {
var latestValue: Value?
var completed = false
}
extension SignalType {
private func observeWithStates<U>(signalState: CombineLatestState<Value>, _ otherState: CombineLatestState<U>, _ lock: NSLock, _ onBothNext: () -> Void, _ onFailed: Error -> Void, _ onBothCompleted: () -> Void, _ onInterrupted: () -> Void) -> Disposable? {
return self.observe { event in
switch event {
case let .Next(value):
lock.lock()
signalState.latestValue = value
if otherState.latestValue != nil {
onBothNext()
}
lock.unlock()
case let .Failed(error):
onFailed(error)
case .Completed:
lock.lock()
signalState.completed = true
if otherState.completed {
onBothCompleted()
}
lock.unlock()
case .Interrupted:
onInterrupted()
}
}
}
/// Combines the latest value of the receiver with the latest value from
/// the given signal.
///
/// The returned signal will not send a value until both inputs have sent
/// at least one value each. If either signal is interrupted, the returned signal
/// will also be interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatestWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let lock = NSLock()
lock.name = "org.reactivecocoa.ReactiveCocoa.combineLatestWith"
let signalState = CombineLatestState<Value>()
let otherState = CombineLatestState<U>()
let onBothNext = {
observer.sendNext((signalState.latestValue!, otherState.latestValue!))
}
let onFailed = observer.sendFailed
let onBothCompleted = observer.sendCompleted
let onInterrupted = observer.sendInterrupted
let disposable = CompositeDisposable()
disposable += self.observeWithStates(signalState, otherState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
disposable += otherSignal.observeWithStates(otherState, signalState, lock, onBothNext, onFailed, onBothCompleted, onInterrupted)
return disposable
}
}
/// Delays `Next` and `Completed` events by the given interval, forwarding
/// them on the given scheduler.
///
/// `Failed` and `Interrupted` events are always scheduled immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func delay(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
return self.observe { event in
switch event {
case .Failed, .Interrupted:
scheduler.schedule {
observer.action(event)
}
case .Next, .Completed:
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
scheduler.scheduleAfter(date) {
observer.action(event)
}
}
}
}
}
/// Returns a signal that will skip the first `count` values, then forward
/// everything afterward.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skip(count: Int) -> Signal<Value, Error> {
precondition(count >= 0)
if count == 0 {
return signal
}
return Signal { observer in
var skipped = 0
return self.observe { event in
if case .Next = event where skipped < count {
skipped += 1
} else {
observer.action(event)
}
}
}
}
/// Treats all Events from `self` as plain values, allowing them to be manipulated
/// just like any other value.
///
/// In other words, this brings Events “into the monad.”
///
/// When a Completed or Failed event is received, the resulting signal will send
/// the Event itself and then complete. When an Interrupted event is received,
/// the resulting signal will send the Event itself and then interrupt.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func materialize() -> Signal<Event<Value, Error>, NoError> {
return Signal { observer in
return self.observe { event in
observer.sendNext(event)
switch event {
case .Interrupted:
observer.sendInterrupted()
case .Completed, .Failed:
observer.sendCompleted()
case .Next:
break
}
}
}
}
}
extension SignalType where Value: EventType, Error == NoError {
/// The inverse of materialize(), this will translate a signal of `Event`
/// _values_ into a signal of those events themselves.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func dematerialize() -> Signal<Value.Value, Value.Error> {
return Signal<Value.Value, Value.Error> { observer in
return self.observe { event in
switch event {
case let .Next(innerEvent):
observer.action(innerEvent.event)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
extension SignalType {
/// Injects side effects to be performed upon the specified signal events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func on(event event: (Event<Value, Error> -> Void)? = nil, failed: (Error -> Void)? = nil, completed: (() -> Void)? = nil, interrupted: (() -> Void)? = nil, terminated: (() -> Void)? = nil, disposed: (() -> Void)? = nil, next: (Value -> Void)? = nil) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
_ = disposed.map(disposable.addDisposable)
disposable += signal.observe { receivedEvent in
event?(receivedEvent)
switch receivedEvent {
case let .Next(value):
next?(value)
case let .Failed(error):
failed?(error)
case .Completed:
completed?()
case .Interrupted:
interrupted?()
}
if receivedEvent.isTerminating {
terminated?()
}
observer.action(receivedEvent)
}
return disposable
}
}
}
private struct SampleState<Value> {
var latestValue: Value? = nil
var signalCompleted: Bool = false
var samplerCompleted: Bool = false
}
extension SignalType {
/// Forwards the latest value from `self` with the value from `sampler` as a tuple,
/// only when`sampler` sends a Next event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a signal that will send values from `self` and `sampler`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func sampleWith<T>(sampler: Signal<T, NoError>) -> Signal<(Value, T), Error> {
return Signal { observer in
let state = Atomic(SampleState<Value>())
let disposable = CompositeDisposable()
disposable += self.observe { event in
switch event {
case let .Next(value):
state.modify { st in
var st = st
st.latestValue = value
return st
}
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
let oldState = state.modify { st in
var st = st
st.signalCompleted = true
return st
}
if oldState.samplerCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
}
}
disposable += sampler.observe { event in
switch event {
case .Next(let samplerValue):
if let value = state.value.latestValue {
observer.sendNext((value, samplerValue))
}
case .Completed:
let oldState = state.modify { st in
var st = st
st.samplerCompleted = true
return st
}
if oldState.signalCompleted {
observer.sendCompleted()
}
case .Interrupted:
observer.sendInterrupted()
case .Failed:
break
}
}
return disposable
}
}
/// Forwards the latest value from `self` whenever `sampler` sends a Next
/// event.
///
/// If `sampler` fires before a value has been observed on `self`, nothing
/// happens.
///
/// Returns a signal that will send values from `self`, sampled (possibly
/// multiple times) by `sampler`, then complete once both input signals have
/// completed, or interrupt if either input signal is interrupted.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func sampleOn(sampler: Signal<(), NoError>) -> Signal<Value, Error> {
return sampleWith(sampler)
.map { $0.0 }
}
/// Forwards events from `self` until `trigger` sends a Next or Completed
/// event, at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
disposable += self.observe(observer)
disposable += trigger.observe { event in
switch event {
case .Next, .Completed:
observer.sendCompleted()
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Does not forward any values from `self` until `trigger` sends a Next or
/// Completed event, at which point the returned signal behaves exactly like
/// `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipUntil(trigger: Signal<(), NoError>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = SerialDisposable()
disposable.innerDisposable = trigger.observe { event in
switch event {
case .Next, .Completed:
disposable.innerDisposable = self.observe(observer)
case .Failed, .Interrupted:
break
}
}
return disposable
}
}
/// Forwards events from `self` with history: values of the returned signal
/// are a tuple whose first member is the previous value and whose second member
/// is the current value. `initial` is supplied as the first member when `self`
/// sends its first value.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combinePrevious(initial: Value) -> Signal<(Value, Value), Error> {
return scan((initial, initial)) { previousCombinedValues, newValue in
return (previousCombinedValues.1, newValue)
}
}
/// Like `scan`, but sends only the final value and then immediately completes.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func reduce<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
// We need to handle the special case in which `signal` sends no values.
// We'll do that by sending `initial` on the output signal (before taking
// the last value).
let (scannedSignalWithInitialValue, outputSignalObserver) = Signal<U, Error>.pipe()
let outputSignal = scannedSignalWithInitialValue.takeLast(1)
// Now that we've got takeLast() listening to the piped signal, send that initial value.
outputSignalObserver.sendNext(initial)
// Pipe the scanned input signal into the output signal.
scan(initial, combine).observe(outputSignalObserver)
return outputSignal
}
/// Aggregates `selfs`'s values into a single combined value. When `self` emits
/// its first value, `combine` is invoked with `initial` as the first argument and
/// that emitted value as the second argument. The result is emitted from the
/// signal returned from `scan`. That result is then passed to `combine` as the
/// first argument when the next value is emitted, and so on.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func scan<U>(initial: U, _ combine: (U, Value) -> U) -> Signal<U, Error> {
return Signal { observer in
var accumulator = initial
return self.observe { event in
observer.action(event.map { value in
accumulator = combine(accumulator, value)
return accumulator
})
}
}
}
}
extension SignalType where Value: Equatable {
/// Forwards only those values from `self` which are not duplicates of the
/// immedately preceding value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats() -> Signal<Value, Error> {
return skipRepeats(==)
}
}
extension SignalType {
/// Forwards only those values from `self` which do not pass `isRepeat` with
/// respect to the previous value. The first value is always forwarded.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipRepeats(isRepeat: (Value, Value) -> Bool) -> Signal<Value, Error> {
return self
.scan((nil, false)) { (accumulated: (Value?, Bool), next: Value) -> (value: Value?, repeated: Bool) in
switch accumulated.0 {
case nil:
return (next, false)
case let prev? where isRepeat(prev, next):
return (prev, true)
case _?:
return (Optional(next), false)
}
}
.filter { !$0.repeated }
.map { $0.value }
.ignoreNil()
}
/// Does not forward any values from `self` until `predicate` returns false,
/// at which point the returned signal behaves exactly like `signal`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func skipWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
var shouldSkip = true
return self.observe { event in
switch event {
case let .Next(value):
shouldSkip = shouldSkip && predicate(value)
if !shouldSkip {
fallthrough
}
case .Failed, .Completed, .Interrupted:
observer.action(event)
}
}
}
}
/// Forwards events from `self` until `replacement` begins sending events.
///
/// Returns a signal which passes through `Next`, `Failed`, and `Interrupted`
/// events from `signal` until `replacement` sends an event, at which point the
/// returned signal will send that event and switch to passing through events
/// from `replacement` instead, regardless of whether `self` has sent events
/// already.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeUntilReplacement(replacement: Signal<Value, Error>) -> Signal<Value, Error> {
return Signal { observer in
let disposable = CompositeDisposable()
let signalDisposable = self.observe { event in
switch event {
case .Completed:
break
case .Next, .Failed, .Interrupted:
observer.action(event)
}
}
disposable += signalDisposable
disposable += replacement.observe { event in
signalDisposable?.dispose()
observer.action(event)
}
return disposable
}
}
/// Waits until `self` completes and then forwards the final `count` values
/// on the returned signal.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeLast(count: Int) -> Signal<Value, Error> {
return Signal { observer in
var buffer: [Value] = []
buffer.reserveCapacity(count)
return self.observe { event in
switch event {
case let .Next(value):
// To avoid exceeding the reserved capacity of the buffer, we remove then add.
// Remove elements until we have room to add one more.
while (buffer.count + 1) > count {
buffer.removeAtIndex(0)
}
buffer.append(value)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
buffer.forEach(observer.sendNext)
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Forwards any values from `self` until `predicate` returns false,
/// at which point the returned signal will complete.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func takeWhile(predicate: Value -> Bool) -> Signal<Value, Error> {
return Signal { observer in
return self.observe { event in
if case let .Next(value) = event where !predicate(value) {
observer.sendCompleted()
} else {
observer.action(event)
}
}
}
}
}
private struct ZipState<Left, Right> {
var values: (left: [Left], right: [Right]) = ([], [])
var completed: (left: Bool, right: Bool) = (false, false)
var isFinished: Bool {
return (completed.left && values.left.isEmpty) || (completed.right && values.right.isEmpty)
}
}
extension SignalType {
/// Zips elements of two signals into pairs. The elements of any Nth pair
/// are the Nth elements of the two input signals.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zipWith<U>(otherSignal: Signal<U, Error>) -> Signal<(Value, U), Error> {
return Signal { observer in
let state = Atomic(ZipState<Value, U>())
let disposable = CompositeDisposable()
let flush = {
var tuple: (Value, U)?
var isFinished = false
state.modify { state in
var state = state
guard !state.values.left.isEmpty && !state.values.right.isEmpty else {
return state
}
tuple = (state.values.left.removeFirst(), state.values.right.removeFirst())
isFinished = state.isFinished
return state
}
if let tuple = tuple {
observer.sendNext(tuple)
}
if isFinished {
observer.sendCompleted()
}
}
let onFailed = observer.sendFailed
let onInterrupted = observer.sendInterrupted
disposable += self.observe { event in
switch event {
case let .Next(value):
state.modify { state in
var state = state
state.values.left.append(value)
return state
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
state.modify { state in
var state = state
state.completed.left = true
return state
}
flush()
case .Interrupted:
onInterrupted()
}
}
disposable += otherSignal.observe { event in
switch event {
case let .Next(value):
state.modify { state in
var state = state
state.values.right.append(value)
return state
}
flush()
case let .Failed(error):
onFailed(error)
case .Completed:
state.modify { state in
var state = state
state.completed.right = true
return state
}
flush()
case .Interrupted:
onInterrupted()
}
}
return disposable
}
}
/// Applies `operation` to values from `self` with `Success`ful results
/// forwarded on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attempt(operation: Value -> Result<(), Error>) -> Signal<Value, Error> {
return attemptMap { value in
return operation(value).map {
return value
}
}
}
/// Applies `operation` to values from `self` with `Success`ful results mapped
/// on the returned signal and `Failure`s sent as `Failed` events.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func attemptMap<U>(operation: Value -> Result<U, Error>) -> Signal<U, Error> {
return Signal { observer in
self.observe { event in
switch event {
case let .Next(value):
operation(value).analysis(
ifSuccess: observer.sendNext,
ifFailure: observer.sendFailed
)
case let .Failed(error):
observer.sendFailed(error)
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
/// Throttle values sent by the receiver, so that at least `interval`
/// seconds pass between each, then forwards them on the given scheduler.
///
/// If multiple values are received before the interval has elapsed, the
/// latest value is the one that will be passed on.
///
/// If the input signal terminates while a value is being throttled, that value
/// will be discarded and the returned signal will terminate immediately.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func throttle(interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let state: Atomic<ThrottleState<Value>> = Atomic(ThrottleState())
let schedulerDisposable = SerialDisposable()
let disposable = CompositeDisposable()
disposable.addDisposable(schedulerDisposable)
disposable += self.observe { event in
if case let .Next(value) = event {
var scheduleDate: NSDate!
state.modify { state in
var state = state
state.pendingValue = value
let proposedScheduleDate = state.previousDate?.dateByAddingTimeInterval(interval) ?? scheduler.currentDate
scheduleDate = proposedScheduleDate.laterDate(scheduler.currentDate)
return state
}
schedulerDisposable.innerDisposable = scheduler.scheduleAfter(scheduleDate) {
let previousState = state.modify { state in
var state = state
if state.pendingValue != nil {
state.pendingValue = nil
state.previousDate = scheduleDate
}
return state
}
if let pendingValue = previousState.pendingValue {
observer.sendNext(pendingValue)
}
}
} else {
schedulerDisposable.innerDisposable = scheduler.schedule {
observer.action(event)
}
}
}
return disposable
}
}
}
extension SignalType {
/// Forwards only those values from `self` that have unique identities across the set of
/// all values that have been seen.
///
/// Note: This causes the identities to be retained to check for uniqueness.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func uniqueValues<Identity: Hashable>(transform: Value -> Identity) -> Signal<Value, Error> {
return Signal { observer in
var seenValues: Set<Identity> = []
return self
.observe { event in
switch event {
case let .Next(value):
let identity = transform(value)
if !seenValues.contains(identity) {
seenValues.insert(identity)
fallthrough
}
case .Failed, .Completed, .Interrupted:
observer.action(event)
}
}
}
}
}
extension SignalType where Value: Hashable {
/// Forwards only those values from `self` that are unique across the set of
/// all values that have been seen.
///
/// Note: This causes the values to be retained to check for uniqueness. Providing
/// a function that returns a unique value for each sent value can help you reduce
/// the memory footprint.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func uniqueValues() -> Signal<Value, Error> {
return uniqueValues { $0 }
}
}
private struct ThrottleState<Value> {
var previousDate: NSDate? = nil
var pendingValue: Value? = nil
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.combineLatestWith(b)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return combineLatest(a, b)
.combineLatestWith(c)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return combineLatest(a, b, c)
.combineLatestWith(d)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return combineLatest(a, b, c, d)
.combineLatestWith(e)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return combineLatest(a, b, c, d, e)
.combineLatestWith(f)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return combineLatest(a, b, c, d, e, f)
.combineLatestWith(g)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return combineLatest(a, b, c, d, e, f, g)
.combineLatestWith(h)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return combineLatest(a, b, c, d, e, f, g, h)
.combineLatestWith(i)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return combineLatest(a, b, c, d, e, f, g, h, i)
.combineLatestWith(j)
.map(repack)
}
/// Combines the values of all the given signals, in the manner described by
/// `combineLatestWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func combineLatest<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.combineLatestWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>) -> Signal<(A, B), Error> {
return a.zipWith(b)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>) -> Signal<(A, B, C), Error> {
return zip(a, b)
.zipWith(c)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>) -> Signal<(A, B, C, D), Error> {
return zip(a, b, c)
.zipWith(d)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>) -> Signal<(A, B, C, D, E), Error> {
return zip(a, b, c, d)
.zipWith(e)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>) -> Signal<(A, B, C, D, E, F), Error> {
return zip(a, b, c, d, e)
.zipWith(f)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>) -> Signal<(A, B, C, D, E, F, G), Error> {
return zip(a, b, c, d, e, f)
.zipWith(g)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>) -> Signal<(A, B, C, D, E, F, G, H), Error> {
return zip(a, b, c, d, e, f, g)
.zipWith(h)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>) -> Signal<(A, B, C, D, E, F, G, H, I), Error> {
return zip(a, b, c, d, e, f, g, h)
.zipWith(i)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<A, B, C, D, E, F, G, H, I, J, Error>(a: Signal<A, Error>, _ b: Signal<B, Error>, _ c: Signal<C, Error>, _ d: Signal<D, Error>, _ e: Signal<E, Error>, _ f: Signal<F, Error>, _ g: Signal<G, Error>, _ h: Signal<H, Error>, _ i: Signal<I, Error>, _ j: Signal<J, Error>) -> Signal<(A, B, C, D, E, F, G, H, I, J), Error> {
return zip(a, b, c, d, e, f, g, h, i)
.zipWith(j)
.map(repack)
}
/// Zips the values of all the given signals, in the manner described by
/// `zipWith`. No events will be sent if the sequence is empty.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func zip<S: SequenceType, Value, Error where S.Generator.Element == Signal<Value, Error>>(signals: S) -> Signal<[Value], Error> {
var generator = signals.generate()
if let first = generator.next() {
let initial = first.map { [$0] }
return GeneratorSequence(generator).reduce(initial) { signal, next in
signal.zipWith(next).map { $0.0 + [$0.1] }
}
}
return .never
}
extension SignalType {
/// Forwards events from `self` until `interval`. Then if signal isn't completed yet,
/// fails with `error` on `scheduler`.
///
/// If the interval is 0, the timeout will be scheduled immediately. The signal
/// must complete synchronously (or on a faster scheduler) to avoid the timeout.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func timeoutWithError(error: Error, afterInterval interval: NSTimeInterval, onScheduler scheduler: DateSchedulerType) -> Signal<Value, Error> {
precondition(interval >= 0)
return Signal { observer in
let disposable = CompositeDisposable()
let date = scheduler.currentDate.dateByAddingTimeInterval(interval)
disposable += scheduler.scheduleAfter(date) {
observer.sendFailed(error)
}
disposable += self.observe(observer)
return disposable
}
}
}
extension SignalType where Error == NoError {
/// Promotes a signal that does not generate failures into one that can.
///
/// This does not actually cause failures to be generated for the given signal,
/// but makes it easier to combine with other signals that may fail; for
/// example, with operators like `combineLatestWith`, `zipWith`, `flatten`, etc.
@warn_unused_result(message="Did you forget to call `observe` on the signal?")
public func promoteErrors<F: ErrorType>(_: F.Type) -> Signal<Value, F> {
return Signal { observer in
return self.observe { event in
switch event {
case let .Next(value):
observer.sendNext(value)
case .Failed:
fatalError("NoError is impossible to construct")
case .Completed:
observer.sendCompleted()
case .Interrupted:
observer.sendInterrupted()
}
}
}
}
}
| mit | b4d7b7c9753d8ba0219e2457deae15da | 32.306 | 341 | 0.67131 | 3.622055 | false | false | false | false |
andriitishchenko/tratata | tratata/tratata/RecorderViewController.swift | 1 | 2190 | //
// RecorderViewController.swift
// tratata
//
// Created by Andrii Tishchenko on 19.05.15.
// Copyright (c) 2015 Andrii Tishchenko. All rights reserved.
//
import UIKit
import Social
import MapKit
class RecorderViewController: BaseViewController {
@IBOutlet var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
var buttonRecording : UIBarButtonItem = UIBarButtonItem(title: "Start", style: UIBarButtonItemStyle.Plain, target: self, action: "buttonRecording_click:")
self.navigationItem.rightBarButtonItem = buttonRecording
// Do any additional setup after loading the view.
}
@IBAction func buttonShare_click(sender: UIBarButtonItem) {
let textToShare = "Swift is awesome! Check out this website about it!"
if let myWebsite = NSURL(string: "http://www.codingexplorer.com/")
{
let objectsToShare = [textToShare, myWebsite]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
//New Excluded Activities Code
activityVC.excludedActivityTypes = [UIActivityTypeAirDrop, UIActivityTypeAddToReadingList]
//
self.presentViewController(activityVC, animated: true, completion: nil)
}
}
@IBAction func buttonMap_click(sender: UIBarButtonItem) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// override var tableView:UITableView! {
// return self.tableViewStats
// }
@IBAction func buttonShowNewTrack_click(sender:UIBarButtonItem!)
{
sender.title = "Stop";
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 1adc5b63f75976caa7140d66345b8f08 | 30.285714 | 162 | 0.664384 | 5.046083 | false | false | false | false |
acrocat/EverLayout | Source/Model/ViewIndex.swift | 1 | 3992 | // EverLayout
//
// Copyright (c) 2017 Dale Webster
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public class ViewIndex: NSObject {
/// Dictionary of every ELViewModel in the layout, with its ID as the key
private(set) public var contents : [String : ELViewModel?] = [:]
/// An array of the ELViewModels in the layout, but ordered by the Z Index
public var contentsByZIndex : [ELViewModel?] {
return self.contents.values.sorted { (modelA, modelB) -> Bool in
guard let parentA = modelA?.parentModel?.id , let parentB = modelB?.parentModel?.id else { return false }
if parentA == parentB {
return (modelA?.zIndex ?? 0) < (modelB?.zIndex ?? 0)
} else {
return parentA < parentB
}
}
}
/// The view on which everything in this layout is built
///
/// - Returns: Root View model
public func rootViewModel () -> ELViewModel? {
return self.contents.first?.value
}
/// The root view's actual UIView
///
/// - Returns: Root View
public func rootView () -> UIView? {
return self.rootViewModel()?.target
}
/// Get a view by its ID in this layout
///
/// - Parameter key: ID
/// - Returns: UIView for this key
public func view (forKey key : String) -> UIView? {
return self.contents[key]??.target
}
/// Get view model by its ID in this layout
///
/// - Parameter key: ID
/// - Returns: ELViewModel
public func viewModel (forKey key : String) -> ELViewModel? {
if let viewModel = self.contents[key] {
return viewModel
}
return nil
}
/// Get array of all constraints that are described by the views in this index
///
/// - Returns: [ELConstraintModel]
public func getAllConstraints () -> [ELConstraintModel] {
var allConstraints : [ELConstraintModel] = []
for (_ , viewModel) in self.contents {
let toAdd = viewModel?.getAllAffectingLayoutConstraintModels().filter({ (constraintModel) -> Bool in
return constraintModel != nil
}) as! [ELConstraintModel]
allConstraints.append(contentsOf: toAdd)
}
return allConstraints
}
/// Add a new view mode to this index
///
/// - Parameters:
/// - key: The ID to uniquely identify this model
/// - viewModel: Model to be added
public func addViewModel (forKey key : String , viewModel : ELViewModel) {
if self.contents.keys.contains(key) {
// Element with this key already exists in the contents
// TODO: Throw a warning
} else {
self.contents[key] = viewModel
}
}
/// Remove all models
public func clear () {
self.contents = [:]
}
}
| mit | 73f3f0ca9ea2a8cf5a213558ec69b78c | 34.963964 | 117 | 0.619489 | 4.551881 | false | false | false | false |
jpedrosa/sua | examples/snippets/xorshift128plus.swift | 1 | 249 |
var state0: UInt64 = 1
var state1: UInt64 = 2
func xorshift128plus() {
var s1 = state0
let s0 = state1
state0 = s0
s1 ^= s1 << 23
s1 ^= s1 >> 17
s1 ^= s0
s1 ^= s0 >> 26
state1 = s1
}
xorshift128plus()
debugPrint(state0, state1)
| apache-2.0 | c3820dc1489acd860f8d1b3de4558c3f | 12.105263 | 26 | 0.594378 | 2.394231 | false | false | false | false |
jinseokpark6/u-team | Code/Controllers/CVCalendarMenuView.swift | 1 | 3431 | //
// CVCalendarMenuView.swift
// CVCalendar
//
// Created by E. Mozharovsky on 12/26/14.
// Copyright (c) 2014 GameApp. All rights reserved.
//
import UIKit
class CVCalendarMenuView: UIView {
var symbols = [String]()
var symbolViews: [UILabel]?
var firstWeekday: Weekday {
get {
if let delegate = delegate {
return delegate.firstWeekday()
} else {
return .Sunday
}
}
}
@IBOutlet weak var menuViewDelegate: AnyObject? {
set {
if let delegate = newValue as? MenuViewDelegate {
self.delegate = delegate
}
}
get {
return delegate as? AnyObject
}
}
var delegate: MenuViewDelegate? {
didSet {
setupWeekdaySymbols()
createDaySymbols()
}
}
init() {
super.init(frame: CGRectZero)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
}
func setupWeekdaySymbols() {
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
calendar.components([.Month, .Day], fromDate: NSDate())
calendar.firstWeekday = firstWeekday.rawValue
symbols = calendar.weekdaySymbols
}
func createDaySymbols() {
// Change symbols with their places if needed.
let dateFormatter = NSDateFormatter()
var weekdays = dateFormatter.shortWeekdaySymbols as NSArray
let firstWeekdayIndex = firstWeekday.rawValue - 1
if (firstWeekdayIndex > 0) {
let copy = weekdays
weekdays = (weekdays.subarrayWithRange(NSMakeRange(firstWeekdayIndex, 7 - firstWeekdayIndex)))
weekdays = weekdays.arrayByAddingObjectsFromArray(copy.subarrayWithRange(NSMakeRange(0, firstWeekdayIndex)))
}
self.symbols = weekdays as! [String]
// Add symbols.
self.symbolViews = [UILabel]()
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<7 {
x = CGFloat(i) * width + space
let symbol = UILabel(frame: CGRectMake(x, y, width, height))
symbol.textAlignment = .Center
symbol.text = (self.symbols[i]).uppercaseString
symbol.font = UIFont.boldSystemFontOfSize(10) // may be provided as a delegate property
symbol.textColor = UIColor.darkGrayColor()
self.symbolViews?.append(symbol)
self.addSubview(symbol)
}
}
func commitMenuViewUpdate() {
if let delegate = delegate {
let space = 0 as CGFloat
let width = self.frame.width / 7 - space
let height = self.frame.height
var x: CGFloat = 0
let y: CGFloat = 0
for i in 0..<self.symbolViews!.count {
x = CGFloat(i) * width + space
let frame = CGRectMake(x, y, width, height)
let symbol = self.symbolViews![i]
symbol.frame = frame
}
}
}
}
| apache-2.0 | 46c656d8f368dcb922007182ddd42262 | 27.831933 | 120 | 0.54299 | 5.045588 | false | false | false | false |
mnisn/zhangchu | zhangchu/Pods/SnapKit/Source/Debugging.swift | 30 | 6759 | //
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// 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 os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to allow adding a snp_label to a View for debugging purposes
*/
public extension View {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}
/**
Used to allow adding a snp_label to a LayoutConstraint for debugging purposes
*/
public extension LayoutConstraint {
public var snp_label: String? {
get {
return objc_getAssociatedObject(self, &labelKey) as? String
}
set {
objc_setAssociatedObject(self, &labelKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
override public var description: String {
var description = "<"
description += descriptionForObject(self)
if let firstItem: AnyObject = self.firstItem {
description += " \(descriptionForObject(firstItem))"
}
if self.firstAttribute != .NotAnAttribute {
description += ".\(self.firstAttribute.snp_description)"
}
description += " \(self.relation.snp_description)"
if let secondItem: AnyObject = self.secondItem {
description += " \(descriptionForObject(secondItem))"
}
if self.secondAttribute != .NotAnAttribute {
description += ".\(self.secondAttribute.snp_description)"
}
if self.multiplier != 1.0 {
description += " * \(self.multiplier)"
}
if self.secondAttribute == .NotAnAttribute {
description += " \(self.constant)"
} else {
if self.constant > 0.0 {
description += " + \(self.constant)"
} else if self.constant < 0.0 {
description += " - \(CGFloat.abs(self.constant))"
}
}
if self.priority != 1000.0 {
description += " ^\(self.priority)"
}
description += ">"
return description
}
internal var snp_makerFile: String? {
return self.snp_constraint?.makerFile
}
internal var snp_makerLine: UInt? {
return self.snp_constraint?.makerLine
}
}
private var labelKey = ""
private func descriptionForObject(object: AnyObject) -> String {
let pointerDescription = NSString(format: "%p", ObjectIdentifier(object).uintValue)
var desc = ""
desc += object.dynamicType.description()
if let object = object as? View {
desc += ":\(object.snp_label ?? pointerDescription)"
} else if let object = object as? LayoutConstraint {
desc += ":\(object.snp_label ?? pointerDescription)"
} else {
desc += ":\(pointerDescription)"
}
if let object = object as? LayoutConstraint, let file = object.snp_makerFile, let line = object.snp_makerLine {
desc += "@\(file)#\(line)"
}
desc += ""
return desc
}
private extension NSLayoutRelation {
private var snp_description: String {
switch self {
case .Equal: return "=="
case .GreaterThanOrEqual: return ">="
case .LessThanOrEqual: return "<="
}
}
}
private extension NSLayoutAttribute {
private var snp_description: String {
#if os(iOS) || os(tvOS)
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .LastBaseline: return "baseline"
case .FirstBaseline: return "firstBaseline"
case .TopMargin: return "topMargin"
case .LeftMargin: return "leftMargin"
case .BottomMargin: return "bottomMargin"
case .RightMargin: return "rightMargin"
case .LeadingMargin: return "leadingMargin"
case .TrailingMargin: return "trailingMargin"
case .CenterXWithinMargins: return "centerXWithinMargins"
case .CenterYWithinMargins: return "centerYWithinMargins"
}
#else
switch self {
case .NotAnAttribute: return "notAnAttribute"
case .Top: return "top"
case .Left: return "left"
case .Bottom: return "bottom"
case .Right: return "right"
case .Leading: return "leading"
case .Trailing: return "trailing"
case .Width: return "width"
case .Height: return "height"
case .CenterX: return "centerX"
case .CenterY: return "centerY"
case .LastBaseline: return "baseline"
default: return "default"
}
#endif
}
}
| mit | f116a5911f340c53452a10ebcfabb7b3 | 32.964824 | 119 | 0.572274 | 4.93718 | false | false | false | false |
andrew804/vapor-apns-1.2.2 | Sources/VaporAPNS/Payload.swift | 1 | 7673 | //
// Payload.swift
// VaporAPNS
//
// Created by Matthijs Logemann on 01/10/2016.
//
//
import Foundation
import JSON
import Core
open class Payload: JSONRepresentable {
/// The number to display as the badge of the app icon.
public var badge: Int?
/// A short string describing the purpose of the notification. Apple Watch displays this string as part of the notification interface. This string is displayed only briefly and should be crafted so that it can be understood quickly. This key was added in iOS 8.2.
public var title: String?
// A secondary description of the reason for the alert.
public var subtitle: String?
/// The text of the alert message. Can be nil if using titleLocKey
public var body: String?
/// The key to a title string in the Localizable.strings file for the current localization. The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the titleLocArgs array.
public var titleLocKey: String?
/// Variable string values to appear in place of the format specifiers in titleLocKey.
public var titleLocArgs: [String]?
/// If a string is specified, the system displays an alert that includes the Close and View buttons. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”.
public var actionLocKey: String?
/// A key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference). The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the bodyLocArgs array.
public var bodyLocKey: String?
/// Variable string values to appear in place of the format specifiers in bodyLocKey.
public var bodyLocArgs: [String]?
/// The filename of an image file in the app bundle, with or without the filename extension. The image is used as the launch image when users tap the action button or move the action slider. If this property is not specified, the system either uses the previous snapshot, uses the image identified by the UILaunchImageFile key in the app’s Info.plist file, or falls back to Default.png.
public var launchImage: String?
/// The name of a sound file in the app bundle or in the Library/Sounds folder of the app’s data container. The sound in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value, the default alert sound is played.
public var sound: String?
/// a category that is used by iOS 10+ notifications
public var category: String?
/// Silent push notification. This automatically ignores any other push message keys (title, body, ect.) and only the extra key-value pairs are added to the final payload
public var contentAvailable: Bool = false
/// A Boolean indicating whether the payload contains content that can be modified by an iOS 10+ Notification Service Extension (media, encrypted content, ...)
public var hasMutableContent: Bool = false
/// When displaying notifications, the system visually groups notifications with the same thread identifier together.
public var threadId: String?
// Any extra key-value pairs to add to the JSON
public var extra: [String: NodeRepresentable] = [:]
// Simple, empty initializer
public init() {}
open func makeJSON() throws -> JSON {
var payloadData: [String: NodeRepresentable] = [:]
var apsPayloadData: [String: NodeRepresentable] = [:]
if contentAvailable {
apsPayloadData["content-available"] = true
} else {
// Create alert dictionary
var alert: [String: NodeRepresentable] = [:]
if let title = title {
alert["title"] = title
}
if let titleLocKey = titleLocKey {
alert["title-loc-key"] = titleLocKey
if let titleLocArgs = titleLocArgs {
alert["title-loc-args"] = try titleLocArgs.makeNode()
}
}
if let subtitle = subtitle {
alert["subtitle"] = subtitle
}
if let body = body {
alert["body"] = body
}else {
if let bodyLocKey = bodyLocKey {
alert["loc-key"] = bodyLocKey
if let bodyLocArgs = bodyLocArgs {
alert["loc-args"] = try bodyLocArgs.makeNode()
}
}
}
if let actionLocKey = actionLocKey {
alert["action-loc-key"] = actionLocKey
}
if let launchImage = launchImage {
alert["launch-image"] = launchImage
}
// Alert dictionary created
apsPayloadData["alert"] = try alert.makeNode()
if let badge = badge {
apsPayloadData["badge"] = badge
}
if let sound = sound {
apsPayloadData["sound"] = sound
}
if let category = category {
apsPayloadData["category"] = category
}
if hasMutableContent {
apsPayloadData["mutable-content"] = 1
}
}
payloadData["aps"] = try apsPayloadData.makeNode()
for (key, value) in extra {
payloadData[key] = value
}
let json = try JSON(node: try payloadData.makeNode())
return json
}
}
public extension Payload {
public convenience init(message: String) {
self.init()
self.body = message
}
public convenience init(title: String, body: String) {
self.init()
self.title = title
self.body = body
}
public convenience init(title: String, body: String, badge: Int) {
self.init()
self.title = title
self.body = body
self.badge = badge
}
/// A simple, already made, Content-Available payload
public static var contentAvailable: Payload {
let payload = Payload()
payload.contentAvailable = true
return payload
}
}
extension Payload: Equatable {
public static func ==(lhs: Payload, rhs: Payload) -> Bool {
guard lhs.badge == rhs.badge else {
return false
}
guard lhs.title == rhs.title else {
return false
}
guard lhs.body == rhs.body else {
return false
}
guard lhs.titleLocKey == rhs.titleLocKey else {
return false
}
guard lhs.titleLocArgs != nil && rhs.titleLocArgs != nil && lhs.titleLocArgs! == rhs.titleLocArgs! else {
return false
}
guard lhs.actionLocKey == rhs.actionLocKey else {
return false
}
guard lhs.bodyLocKey == rhs.bodyLocKey else {
return false
}
guard lhs.bodyLocArgs != nil && rhs.bodyLocArgs != nil && lhs.bodyLocArgs! == rhs.bodyLocArgs! else {
return false
}
guard lhs.launchImage == rhs.launchImage else {
return false
}
guard lhs.sound == rhs.sound else {
return false
}
guard lhs.contentAvailable == rhs.contentAvailable else {
return false
}
guard lhs.threadId == rhs.threadId else {
return false
}
// guard lhs.extra == rhs.extra else {
// return false
// }
return true
}
}
| mit | f5fd642681292af9d3a983e48eeb2329 | 32.445415 | 390 | 0.607912 | 4.780899 | false | false | false | false |
milseman/swift | test/IRGen/protocol_metadata.swift | 11 | 4065 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
protocol A { func a() }
protocol B { func b() }
protocol C : class { func c() }
@objc protocol O { func o() }
@objc protocol OPT {
@objc optional func opt()
@objc optional static func static_opt()
@objc optional var prop: O { get }
@objc optional subscript (x: O) -> O { get }
}
protocol AB : A, B { func ab() }
protocol ABO : A, B, O { func abo() }
// CHECK: @_T017protocol_metadata1AMp = hidden constant %swift.protocol {
// -- size 72
// -- flags: 1 = Swift | 2 = Not Class-Constrained | 4 = Needs Witness Table
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: @_T017protocol_metadata1BMp = hidden constant %swift.protocol {
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: @_T017protocol_metadata1CMp = hidden constant %swift.protocol {
// -- flags: 1 = Swift | 4 = Needs Witness Table
// CHECK: i32 72, i32 5,
// CHECK: i16 0, i16 0
// CHECK: }
// -- @objc protocol O uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata1O_ = private constant { {{.*}} i32, [1 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS__TtP17protocol_metadata1O_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata1O_
// CHECK-SAME: }
// -- @objc protocol OPT uses ObjC symbol mangling and layout
// CHECK: @_PROTOCOL__TtP17protocol_metadata3OPT_ = private constant { {{.*}} i32, [4 x i8*]*, i8*, i8* } {
// CHECK-SAME: @_PROTOCOL_INSTANCE_METHODS_OPT__TtP17protocol_metadata3OPT_,
// CHECK-SAME: @_PROTOCOL_CLASS_METHODS_OPT__TtP17protocol_metadata3OPT_,
// -- size, flags: 1 = Swift
// CHECK-SAME: i32 96, i32 1
// CHECK-SAME: @_PROTOCOL_METHOD_TYPES__TtP17protocol_metadata3OPT_
// CHECK-SAME: }
// -- inheritance lists for refined protocols
// CHECK: [[AB_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 2,
// CHECK: %swift.protocol* @_T017protocol_metadata1AMp,
// CHECK: %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: }
// CHECK: @_T017protocol_metadata2ABMp = hidden constant %swift.protocol {
// CHECK: [[AB_INHERITED]]
// CHECK: i32 72, i32 7,
// CHECK: i16 0, i16 0
// CHECK: }
// CHECK: [[ABO_INHERITED:@.*]] = private constant { {{.*}}* } {
// CHECK: i64 3,
// CHECK: %swift.protocol* @_T017protocol_metadata1AMp,
// CHECK: %swift.protocol* @_T017protocol_metadata1BMp,
// CHECK: {{.*}}* @_PROTOCOL__TtP17protocol_metadata1O_
// CHECK: }
func reify_metadata<T>(_ x: T) {}
// CHECK: define hidden swiftcc void @_T017protocol_metadata0A6_types{{[_0-9a-zA-Z]*}}F
func protocol_types(_ a: A,
abc: A & B & C,
abco: A & B & C & O) {
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 true, %swift.type* null, i64 1, %swift.protocol** {{%.*}})
reify_metadata(a)
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1CMp
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 3, %swift.protocol** {{%.*}})
reify_metadata(abc)
// CHECK: store %swift.protocol* @_T017protocol_metadata1AMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1BMp
// CHECK: store %swift.protocol* @_T017protocol_metadata1CMp
// CHECK: [[O_REF:%.*]] = load i8*, i8** @"\01l_OBJC_PROTOCOL_REFERENCE_$__TtP17protocol_metadata1O_"
// CHECK: [[O_REF_BITCAST:%.*]] = bitcast i8* [[O_REF]] to %swift.protocol*
// CHECK: store %swift.protocol* [[O_REF_BITCAST]]
// CHECK: call %swift.type* @swift_rt_swift_getExistentialTypeMetadata(i1 false, %swift.type* null, i64 4, %swift.protocol** {{%.*}})
reify_metadata(abco)
}
| apache-2.0 | 0bbef37e8a14cf6ee742fbd75d8cdc34 | 40.060606 | 160 | 0.651907 | 3.117331 | false | false | false | false |
milseman/swift | test/SILGen/protocol_class_refinement.swift | 5 | 4807 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
protocol UID {
func uid() -> Int
var clsid: Int { get set }
var iid: Int { get }
}
extension UID {
var nextCLSID: Int {
get { return clsid + 1 }
set { clsid = newValue - 1 }
}
}
protocol ObjectUID : class, UID {}
extension ObjectUID {
var secondNextCLSID: Int {
get { return clsid + 2 }
set { }
}
}
class Base {}
// CHECK-LABEL: sil hidden @_T025protocol_class_refinement12getObjectUID{{[_0-9a-zA-Z]*}}F
func getObjectUID<T: ObjectUID>(x: T) -> (Int, Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ObjectUID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// -- call x.uid()
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSifs
// -- call x.uid()
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
// -- call x.uid()
// CHECK: [[READ1:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X1:%.*]] = load [copy] [[READ1]]
// CHECK: [[SET_SECONDNEXT:%.*]] = function_ref @_T025protocol_class_refinement9ObjectUIDPAAE15secondNextCLSIDSifs
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call secondNextCLSID from class-constrained protocol ext
// CHECK: apply [[SET_SECONDNEXT]]<T>([[UID]], [[X1]])
// CHECK: destroy_value [[X1]]
x.secondNextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID, x.secondNextCLSID)
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T025protocol_class_refinement16getBaseObjectUID{{[_0-9a-zA-Z]*}}F
func getBaseObjectUID<T: UID where T: Base>(x: T) -> (Int, Int, Int) {
var x = x
// CHECK: [[XBOX:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : Base, τ_0_0 : UID> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[XBOX]]
// CHECK: [[SET_CLSID:%.*]] = witness_method $T, #UID.clsid!setter.1
// -- call x.uid()
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call set x.clsid
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: apply [[SET_CLSID]]<T>([[UID]], [[WRITE]])
x.clsid = x.uid()
// CHECK: [[SET_NEXTCLSID:%.*]] = function_ref @_T025protocol_class_refinement3UIDPAAE9nextCLSIDSifs
// -- call x.uid()
// CHECK: [[GET_UID:%.*]] = witness_method $T, #UID.uid!1
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*T
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[X_TMP:%.*]] = alloc_stack
// CHECK: store [[X]] to [init] [[X_TMP]]
// CHECK: [[UID:%.*]] = apply [[GET_UID]]<T>([[X_TMP]])
// CHECK: [[X2:%.*]] = load [take] [[X_TMP]]
// CHECK: destroy_value [[X2]]
// -- call nextCLSID from protocol ext
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB]] : $*T
// CHECK: apply [[SET_NEXTCLSID]]<T>([[UID]], [[WRITE]])
x.nextCLSID = x.uid()
return (x.iid, x.clsid, x.nextCLSID)
// CHECK: return
}
| apache-2.0 | 3ee5c287c5db376b2f5e8edb6f96bf0c | 38.344262 | 116 | 0.533958 | 2.898551 | false | false | false | false |
IvanVorobei/TwitterLaunchAnimation | TwitterLaunchAnimation - project/TwitterLaucnhAnimation/sparrow/modules/request-permissions/managers/presenters/universal/controls/SPRequestPermissionTwiceControl.swift | 1 | 8011 | // The MIT License (MIT)
// Copyright © 2017 Ivan Vorobei ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
class SPRequestPermissionTwiceControl: UIButton, SPRequestPermissionTwiceControlInterface {
var permission: SPRequestPermissionType
var iconView: SPRequestPermissionIconView!
var normalColor: UIColor
var selectedColor: UIColor
init(permissionType: SPRequestPermissionType, title: String, normalIconImage: UIImage, selectedIconImage: UIImage, normalColor: UIColor, selectedColor: UIColor) {
self.permission = permissionType
let renderingNormalIconImage = normalIconImage.withRenderingMode(.alwaysTemplate)
let renderingSelectedIconImage = selectedIconImage.withRenderingMode(.alwaysTemplate)
self.iconView = SPRequestPermissionIconView(iconImage: renderingNormalIconImage, selectedIconImage: renderingSelectedIconImage)
self.normalColor = normalColor
self.selectedColor = selectedColor
super.init(frame: CGRect.zero)
self.setTitle(title, for: UIControlState.normal)
self.commonInit()
//self.iconView.backgroundColor = UIColor.red
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func commonInit() {
self.layer.borderWidth = 1
self.setTitleColor(self.selectedColor.withAlphaComponent(0.62), for: UIControlState.highlighted)
self.addSubview(self.iconView)
self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 14)
if UIScreen.main.bounds.width < 335 {
self.titleLabel?.font = UIFont.init(name: SPRequestPermissionData.fonts.base() + "-Medium", size: 12)
}
self.titleLabel?.minimumScaleFactor = 0.5
self.titleLabel?.adjustsFontSizeToFitWidth = true
self.setNormalState(animated: false)
}
func setNormalState(animated: Bool) {
self.layer.borderColor = self.selectedColor.cgColor
self.backgroundColor = self.normalColor
self.setTitleColor(self.selectedColor, for: UIControlState.normal)
self.iconView.setColor(self.selectedColor)
}
func setSelectedState(animated: Bool) {
self.layer.borderColor = self.normalColor.cgColor
if animated{
UIView.animate(withDuration: 0.4, animations: {
self.backgroundColor = self.selectedColor
})
} else {
self.backgroundColor = self.selectedColor
}
var colorForTitle = self.normalColor
if self.normalColor == UIColor.clear {
colorForTitle = UIColor.white
}
self.setTitleColor(colorForTitle, for: UIControlState.normal)
self.setTitleColor(colorForTitle.withAlphaComponent(0.62), for: UIControlState.highlighted)
self.iconView.setSelectedState(with: self.normalColor)
}
internal func addAction(_ target: Any?, action: Selector) {
self.addTarget(target, action: action, for: UIControlEvents.touchUpInside)
}
internal func addAsSubviewTo(_ view: UIView) {
view.addSubview(self)
}
override func layoutSubviews() {
super.layoutSubviews()
self.layer.cornerRadius = self.frame.height / 2
let sideSize: CGFloat = self.frame.height * 0.45
let xTranslationIconView: CGFloat = self.frame.width * 0.075
iconView.frame = CGRect.init(
x: xTranslationIconView,
y: (self.frame.height - sideSize) / 2,
width: sideSize,
height: sideSize
)
}
}
class SPRequestPermissionIconView: UIView {
private var imageView: UIImageView?
private var iconImage: UIImage?
private var selectedIconImage: UIImage?
init(iconImage: UIImage, selectedIconImage: UIImage) {
super.init(frame: CGRect.zero)
self.imageView = UIImageView()
self.imageView?.contentMode = .scaleAspectFit
self.addSubview(imageView!)
self.iconImage = iconImage
self.selectedIconImage = selectedIconImage
self.setIconImageView(self.iconImage!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setSelectedState(with color: UIColor = .white) {
var settingColor = color
if settingColor == UIColor.clear {
settingColor = UIColor.white
}
self.setColor(settingColor)
self.imageView?.layer.shadowRadius = 0
self.imageView?.layer.shadowOffset = CGSize.init(width: 0, height: 1)
let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = Double.pi * 2
rotationAnimation.duration = 0.18
rotationAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseInEaseOut)
self.imageView?.layer.shouldRasterize = true
self.imageView?.layer.rasterizationScale = UIScreen.main.scale
self.imageView?.layer.add(rotationAnimation, forKey: nil)
var blurView = UIView()
if #available(iOS 9, *) {
blurView = SPBlurView()
}
blurView.backgroundColor = UIColor.clear
self.addSubview(blurView)
blurView.frame = CGRect.init(x: 0, y: 0, width: self.frame.height, height: self.frame.height)
blurView.center = (self.imageView?.center)!
SPAnimation.animate(0.1, animations: {
if #available(iOS 9, *) {
if let view = blurView as? SPBlurView {
view.setBlurRadius(1.2)
}
}
}, options: UIViewAnimationOptions.curveEaseIn,
withComplection: {
SPAnimation.animate(0.1, animations: {
if #available(iOS 9, *) {
if let view = blurView as? SPBlurView {
view.setBlurRadius(0)
}
}
}, options: UIViewAnimationOptions.curveEaseOut,
withComplection: {
finished in
blurView.removeFromSuperview()
})
})
delay(0.05, closure: {
self.setIconImageView(self.selectedIconImage!)
})
}
func setColor(_ color: UIColor) {
UIView.transition(with: self.imageView!, duration: 0.2, options: UIViewAnimationOptions.beginFromCurrentState, animations: {
self.imageView?.tintColor = color
}, completion: nil)
}
private func setIconImageView(_ iconImageView: UIImage) {
self.imageView?.image = iconImageView
}
override func layoutSubviews() {
super.layoutSubviews()
self.imageView?.frame = self.bounds
}
}
| mit | 0b15860be1de6a05ab213631993441b9 | 38.850746 | 166 | 0.65593 | 5.053628 | false | false | false | false |
gerlandiolucena/iosvisits | iOSVisits/iOSVisits/Model/MyPlaces.swift | 1 | 555 | //
// MyPlaces.swift
// iOSVisits
//
// Created by Gerlandio da Silva Lucena on 6/3/16.
// Copyright © 2016 ZAP Imóveis. All rights reserved.
//
import Foundation
import CoreLocation
import RealmSwift
class MyPlaces: Object {
dynamic var latitude: Double = 0.0
dynamic var longitude: Double = 0.0
dynamic var chegada: Date = Date()
dynamic var saida: Date = Date()
dynamic var Nome: String?
func saveObject(){
let realm = try! Realm()
try! realm.write {
realm.add(self)
}
}
}
| gpl-3.0 | 9edd1a93ecbdab3ea792422c613d7a5b | 19.481481 | 54 | 0.622061 | 3.590909 | false | false | false | false |
LinDing/Positano | Positano/Extensions/UIImage+Yep.swift | 1 | 15399 | //
// UIImage+Yep.swift
// Yep
//
// Created by NIX on 16/8/10.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
// MARK: - Badges
extension UIImage {
static func yep_badgeWithName(_ name: String) -> UIImage {
return UIImage(named: "badge_" + name)!
}
}
// MARK: - Images
// nix love awk, in Images.xcassets
// $ ls -l | awk '{print $9}' | awk -F"." '{print $1}' | awk -F"_" '{out=$0" ";for(i=1;i<=NF;i++){if(i==1){out=out""tolower($i)}else{out=out""toupper(substr($i,1,1))substr($i,2)}};print out}' | awk '{print "static var yep_"$2": UIImage {\n\treturn UIImage(named: \""$1"\")!\n}\n"}' > ~/Downloads/images.swift
// ref https://github.com/nixzhu/dev-blog/blob/master/2016-08-11-awk.md
extension UIImage {
static var yep_bubbleBody: UIImage {
return UIImage(named: "bubble_body")!
}
static var yep_bubbleLeftTail: UIImage {
return UIImage(named: "bubble_left_tail")!
}
static var yep_bubbleRightTail: UIImage {
return UIImage(named: "bubble_right_tail")!
}
static var yep_buttonCameraRoll: UIImage {
return UIImage(named: "button_camera_roll")!
}
static var yep_buttonCapture: UIImage {
return UIImage(named: "button_capture")!
}
static var yep_buttonCaptureOk: UIImage {
return UIImage(named: "button_capture_ok")!
}
static var yep_buttonSkillCategory: UIImage {
return UIImage(named: "button_skill_category")!
}
static var yep_buttonVoicePause: UIImage {
return UIImage(named: "button_voice_pause")!
}
static var yep_buttonVoicePlay: UIImage {
return UIImage(named: "button_voice_play")!
}
static var yep_buttonVoiceReset: UIImage {
return UIImage(named: "button_voice_reset")!
}
static var yep_chatSharetopicbubble: UIImage {
return UIImage(named: "chat_sharetopicbubble")!
}
static var yep_defaultAvatar: UIImage {
return UIImage(named: "default_avatar")!
}
static var yep_defaultAvatar30: UIImage {
return UIImage(named: "default_avatar_30")!
}
static var yep_defaultAvatar40: UIImage {
return UIImage(named: "default_avatar_40")!
}
static var yep_defaultAvatar60: UIImage {
return UIImage(named: "default_avatar_60")!
}
static var yep_feedAudioBubble: UIImage {
return UIImage(named: "feed_audio_bubble")!
}
static var yep_feedContainerBackground: UIImage {
return UIImage(named: "feed_container_background")!
}
static var yep_feedMediaAdd: UIImage {
return UIImage(named: "feed_media_add")!
}
static var yep_feedSkillChannelArrow: UIImage {
return UIImage(named: "feed_skill_channel_arrow")!
}
static var yep_flatArrowDown: UIImage {
return UIImage(named: "flat_arrow_down")!
}
static var yep_flatArrowLeft: UIImage {
return UIImage(named: "flat_arrow_left")!
}
static var yep_gradientArt: UIImage {
return UIImage(named: "gradient_art")!
}
static var yep_gradientLife: UIImage {
return UIImage(named: "gradient_life")!
}
static var yep_gradientSport: UIImage {
return UIImage(named: "gradient_sport")!
}
static var yep_gradientTech: UIImage {
return UIImage(named: "gradient_tech")!
}
static var yep_iconAccessory: UIImage {
return UIImage(named: "icon_accessory")!
}
static var yep_iconAccessoryMini: UIImage {
return UIImage(named: "icon_accessory_mini")!
}
static var yep_iconArrowDown: UIImage {
return UIImage(named: "icon_arrow_down")!
}
static var yep_iconArrowUp: UIImage {
return UIImage(named: "icon_arrow_up")!
}
static var yep_iconBack: UIImage {
return UIImage(named: "icon_back")!
}
static var yep_iconBlog: UIImage {
return UIImage(named: "icon_blog")!
}
static var yep_iconChat: UIImage {
return UIImage(named: "icon_chat")!
}
static var yep_iconChatActive: UIImage {
return UIImage(named: "icon_chat_active")!
}
static var yep_iconChatActiveUnread: UIImage {
return UIImage(named: "icon_chat_active_unread")!
}
static var yep_iconChatUnread: UIImage {
return UIImage(named: "icon_chat_unread")!
}
static var yep_iconContact: UIImage {
return UIImage(named: "icon_contact")!
}
static var yep_iconContactActive: UIImage {
return UIImage(named: "icon_contact_active")!
}
static var yep_iconCurrentLocation: UIImage {
return UIImage(named: "icon_current_location")!
}
static var yep_iconDiscussion: UIImage {
return UIImage(named: "icon_discussion")!
}
static var yep_iconDotFailed: UIImage {
return UIImage(named: "icon_dot_failed")!
}
static var yep_iconDotSending: UIImage {
return UIImage(named: "icon_dot_sending")!
}
static var yep_iconDotUnread: UIImage {
return UIImage(named: "icon_dot_unread")!
}
static var yep_iconDribbble: UIImage {
return UIImage(named: "icon_dribbble")!
}
static var yep_iconExplore: UIImage {
return UIImage(named: "icon_explore")!
}
static var yep_iconExploreActive: UIImage {
return UIImage(named: "icon_explore_active")!
}
static var yep_iconFeedText: UIImage {
return UIImage(named: "icon_feed_text")!
}
static var yep_iconFeeds: UIImage {
return UIImage(named: "icon_feeds")!
}
static var yep_iconFeedsActive: UIImage {
return UIImage(named: "icon_feeds_active")!
}
static var yep_iconGhost: UIImage {
return UIImage(named: "icon_ghost")!
}
static var yep_iconGithub: UIImage {
return UIImage(named: "icon_github")!
}
static var yep_iconImagepickerCheck: UIImage {
return UIImage(named: "icon_imagepicker_check")!
}
static var yep_iconInstagram: UIImage {
return UIImage(named: "icon_instagram")!
}
static var yep_iconKeyboard: UIImage {
return UIImage(named: "icon_keyboard")!
}
static var yep_iconLink: UIImage {
return UIImage(named: "icon_link")!
}
static var yep_iconList: UIImage {
return UIImage(named: "icon_list")!
}
static var yep_iconLocation: UIImage {
return UIImage(named: "icon_location")!
}
static var yep_iconLocationCheckmark: UIImage {
return UIImage(named: "icon_location_checkmark")!
}
static var yep_iconMe: UIImage {
return UIImage(named: "icon_me")!
}
static var yep_iconMeActive: UIImage {
return UIImage(named: "icon_me_active")!
}
static var yep_iconMediaDelete: UIImage {
return UIImage(named: "icon_media_delete")!
}
static var yep_iconMinicard: UIImage {
return UIImage(named: "icon_minicard")!
}
static var yep_iconMore: UIImage {
return UIImage(named: "icon_more")!
}
static var yep_iconMoreImage: UIImage {
return UIImage(named: "icon_more_image")!
}
static var yep_iconPause: UIImage {
return UIImage(named: "icon_pause")!
}
static var yep_iconPin: UIImage {
return UIImage(named: "icon_pin")!
}
static var yep_iconPinMiniGray: UIImage {
return UIImage(named: "icon_pin_mini_gray")!
}
static var yep_iconPinShadow: UIImage {
return UIImage(named: "icon_pin_shadow")!
}
static var yep_iconPlay: UIImage {
return UIImage(named: "icon_play")!
}
static var yep_iconPlayvideo: UIImage {
return UIImage(named: "icon_playvideo")!
}
static var yep_iconProfilePhone: UIImage {
return UIImage(named: "icon_profile_phone")!
}
static var yep_iconQuickCamera: UIImage {
return UIImage(named: "icon_quick_camera")!
}
static var yep_iconRemove: UIImage {
return UIImage(named: "icon_remove")!
}
static var yep_iconRepo: UIImage {
return UIImage(named: "icon_repo")!
}
static var yep_iconSettings: UIImage {
return UIImage(named: "icon_settings")!
}
static var yep_iconShare: UIImage {
return UIImage(named: "icon_share")!
}
static var yep_iconSkillArt: UIImage {
return UIImage(named: "icon_skill_art")!
}
static var yep_iconSkillBall: UIImage {
return UIImage(named: "icon_skill_ball")!
}
static var yep_iconSkillCategoryArrow: UIImage {
return UIImage(named: "icon_skill_category_arrow")!
}
static var yep_iconSkillLife: UIImage {
return UIImage(named: "icon_skill_life")!
}
static var yep_iconSkillMusic: UIImage {
return UIImage(named: "icon_skill_music")!
}
static var yep_iconSkillTech: UIImage {
return UIImage(named: "icon_skill_tech")!
}
static var yep_iconStars: UIImage {
return UIImage(named: "icon_stars")!
}
static var yep_iconSubscribeClose: UIImage {
return UIImage(named: "icon_subscribe_close")!
}
static var yep_iconSubscribeNotify: UIImage {
return UIImage(named: "icon_subscribe_notify")!
}
static var yep_iconTopic: UIImage {
return UIImage(named: "icon_topic")!
}
static var yep_iconTopicReddot: UIImage {
return UIImage(named: "icon_topic_reddot")!
}
static var yep_iconTopicText: UIImage {
return UIImage(named: "icon_topic_text")!
}
static var yep_iconVoiceLeft: UIImage {
return UIImage(named: "icon_voice_left")!
}
static var yep_iconVoiceRight: UIImage {
return UIImage(named: "icon_voice_right")!
}
static var yep_imageRectangleBorder: UIImage {
return UIImage(named: "image_rectangle_border")!
}
static var yep_itemMic: UIImage {
return UIImage(named: "item_mic")!
}
static var yep_itemMore: UIImage {
return UIImage(named: "item_more")!
}
static var yep_leftTailBubble: UIImage {
return UIImage(named: "left_tail_bubble")!
}
static var yep_leftTailImageBubble: UIImage {
return UIImage(named: "left_tail_image_bubble")!
}
static var yep_leftTailImageBubbleBorder: UIImage {
return UIImage(named: "left_tail_image_bubble_border")!
}
static var yep_locationBottomShadow: UIImage {
return UIImage(named: "location_bottom_shadow")!
}
static var yep_minicardBubble: UIImage {
return UIImage(named: "minicard_bubble")!
}
static var yep_minicardBubbleMore: UIImage {
return UIImage(named: "minicard_bubble_more")!
}
static var yep_pickSkillsDismissBackground: UIImage {
return UIImage(named: "pick_skills_dismiss_background")!
}
static var yep_profileAvatarFrame: UIImage {
return UIImage(named: "profile_avatar_frame")!
}
static var yep_rightTailBubble: UIImage {
return UIImage(named: "right_tail_bubble")!
}
static var yep_rightTailImageBubble: UIImage {
return UIImage(named: "right_tail_image_bubble")!
}
static var yep_rightTailImageBubbleBorder: UIImage {
return UIImage(named: "right_tail_image_bubble_border")!
}
static var yep_searchbarTextfieldBackground: UIImage {
return UIImage(named: "searchbar_textfield_background")!
}
static var yep_shareFeedBubbleLeft: UIImage {
return UIImage(named: "share_feed_bubble_left")!
}
static var yep_skillAdd: UIImage {
return UIImage(named: "skill_add")!
}
static var yep_skillBubble: UIImage {
return UIImage(named: "skill_bubble")!
}
static var yep_skillBubbleEmpty: UIImage {
return UIImage(named: "skill_bubble_empty")!
}
static var yep_skillBubbleEmptyGray: UIImage {
return UIImage(named: "skill_bubble_empty_gray")!
}
static var yep_skillBubbleLarge: UIImage {
return UIImage(named: "skill_bubble_large")!
}
static var yep_skillBubbleLargeEmpty: UIImage {
return UIImage(named: "skill_bubble_large_empty")!
}
static var yep_socialMediaImageMask: UIImage {
return UIImage(named: "social_media_image_mask")!
}
static var yep_socialMediaImageMaskFull: UIImage {
return UIImage(named: "social_media_image_mask_full")!
}
static var yep_socialWorkBorder: UIImage {
return UIImage(named: "social_work_border")!
}
static var yep_socialWorkBorderLine: UIImage {
return UIImage(named: "social_work_border_line")!
}
static var yep_swipeUp: UIImage {
return UIImage(named: "swipe_up")!
}
static var yep_topShadow: UIImage {
return UIImage(named: "top_shadow")!
}
static var yep_unreadRedDot: UIImage {
return UIImage(named: "unread_red_dot")!
}
static var yep_urlContainerLeftBackground: UIImage {
return UIImage(named: "url_container_left_background")!
}
static var yep_urlContainerRightBackground: UIImage {
return UIImage(named: "url_container_right_background")!
}
static var yep_voiceIndicator: UIImage {
return UIImage(named: "voice_indicator")!
}
static var yep_white: UIImage {
return UIImage(named: "white")!
}
static var yep_yepIconSolo: UIImage {
return UIImage(named: "yep_icon_solo")!
}
}
// MARK: - Activities
extension UIImage {
static var yep_wechatSession: UIImage {
return UIImage(named: "wechat_session")!
}
static var yep_wechatTimeline: UIImage {
return UIImage(named: "wechat_timeline")!
}
}
// MARK: - Badges
extension UIImage {
static var yep_badgeAndroid: UIImage {
return UIImage(named: "badge_android")!
}
static var yep_badgeApple: UIImage {
return UIImage(named: "badge_apple")!
}
static var yep_badgeBall: UIImage {
return UIImage(named: "badge_ball")!
}
static var yep_badgeBubble: UIImage {
return UIImage(named: "badge_bubble")!
}
static var yep_badgeCamera: UIImage {
return UIImage(named: "badge_camera")!
}
static var yep_badgeGame: UIImage {
return UIImage(named: "badge_game")!
}
static var yep_badgeHeart: UIImage {
return UIImage(named: "badge_heart")!
}
static var yep_badgeMusic: UIImage {
return UIImage(named: "badge_music")!
}
static var yep_badgePalette: UIImage {
return UIImage(named: "badge_palette")!
}
static var yep_badgePet: UIImage {
return UIImage(named: "badge_pet")!
}
static var yep_badgePlane: UIImage {
return UIImage(named: "badge_plane")!
}
static var yep_badgeStar: UIImage {
return UIImage(named: "badge_star")!
}
static var yep_badgeSteve: UIImage {
return UIImage(named: "badge_steve")!
}
static var yep_badgeTech: UIImage {
return UIImage(named: "badge_tech")!
}
static var yep_badgeWine: UIImage {
return UIImage(named: "badge_wine")!
}
static var yep_enabledBadgeBackground: UIImage {
return UIImage(named: "enabled_badge_background")!
}
}
| mit | 10d8d1bb8cb21da9b39129090d0733e9 | 24.574751 | 308 | 0.627501 | 3.987568 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/TableViewDataSources/FeedViewDataSource.swift | 1 | 2894 | //
// FeedViewDataSource.swift
// Habitica
//
// Created by Phillip Thelen on 17.04.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
import ReactiveSwift
@objc
public protocol FeedViewDataSourceProtocol {
@objc weak var tableView: UITableView? { get set }
@objc
func food(at indexPath: IndexPath?) -> FoodProtocol?
}
@objc
class FeedViewDataSourceInstantiator: NSObject {
@objc
static func instantiate() -> FeedViewDataSourceProtocol {
return FeedViewDataSource()
}
}
class FeedViewDataSource: BaseReactiveTableViewDataSource<FoodProtocol>, FeedViewDataSourceProtocol {
private let inventoryRepository = InventoryRepository()
private var ownedItems = [String: Int]()
override init() {
super.init()
sections.append(ItemSection<FoodProtocol>())
disposable.add(inventoryRepository.getOwnedItems()
.map({ (items) -> [OwnedItemProtocol] in
let filteredItems = items.value.filter({ (ownedItem) -> Bool in
return ownedItem.itemType == "food"
})
return filteredItems
})
.on(value: {[weak self] ownedItems in
self?.ownedItems.removeAll()
ownedItems.forEach({ (item) in
self?.ownedItems[(item.key ?? "") + (item.itemType ?? "")] = item.numberOwned
})
})
.map({ (data) -> [String] in
return data.map({ ownedItem -> String in
return ownedItem.key ?? ""
}).filter({ (key) -> Bool in
return !key.isEmpty
})
})
.flatMap(.latest, {[weak self] (keys) in
return self?.inventoryRepository.getFood(keys: keys) ?? SignalProducer.empty
})
.on(value: {[weak self](food) in
self?.sections[0].items = food.value
self?.notify(changes: food.changes)
})
.start()
)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
if let ownedItem = item(at: indexPath) {
let label = cell.viewWithTag(1) as? UILabel
label?.text = ownedItem.text
let detailLabel = cell.viewWithTag(2) as? UILabel
detailLabel?.text = "\(ownedItems[(ownedItem.key ?? "") + (ownedItem.itemType ?? "")] ?? 0)"
let imageView = cell.viewWithTag(3) as? NetworkImageView
imageView?.setImagewith(name: ownedItem.imageName)
}
return cell
}
func food(at indexPath: IndexPath?) -> FoodProtocol? {
return item(at: indexPath)
}
}
| gpl-3.0 | 86fed747533f044bcca6af2d09112eb8 | 33.035294 | 109 | 0.577601 | 4.781818 | false | false | false | false |
CaiMiao/CGSSGuide | DereGuide/Toolbox/Colleague/View/ColleagueTableViewCell.swift | 1 | 6904 | //
// ColleagueTableViewCell.swift
// DereGuide
//
// Created by zzk on 2017/8/15.
// Copyright © 2017年 zzk. All rights reserved.
//
import UIKit
import SnapKit
protocol ColleagueTableViewCellDelegate: class {
func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap gameID: String)
func colleagueTableViewCell(_ cell: ColleagueTableViewCell, didTap cardIcon: CGSSCardIconView)
}
class ColleagueTableViewCell: ReadableWidthTableViewCell {
weak var delegate: ColleagueTableViewCellDelegate?
var gameIDView: UIView!
var gameIDCopyIcon: UIImageView!
var gameIDLabel: UILabel!
var nameLabel: UILabel!
var createdDateLabel: UILabel!
var messageLabel: UILabel!
var myCenterLabel: UILabel!
var myCenterGroupView: MyCenterGroupView!
var centerWantedLabel: UILabel!
var centerWantedGroupView: CenterWantedGroupView!
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
gameIDView = UIView()
readableContentView.addSubview(gameIDView)
gameIDView.snp.makeConstraints { (make) in
make.top.equalTo(10)
make.left.equalTo(10)
make.height.equalTo(26)
}
gameIDView.backgroundColor = Color.parade
gameIDView.layer.cornerRadius = 3
gameIDView.layer.masksToBounds = true
gameIDCopyIcon = UIImageView()
gameIDCopyIcon.image = #imageLiteral(resourceName: "511-copy-documents").withRenderingMode(.alwaysTemplate)
gameIDCopyIcon.tintColor = UIColor.white
gameIDView.addSubview(gameIDCopyIcon)
gameIDCopyIcon.snp.makeConstraints { (make) in
make.centerY.equalToSuperview()
make.left.equalTo(5)
make.height.width.equalTo(18)
}
gameIDLabel = UILabel()
gameIDView.addSubview(gameIDLabel)
gameIDLabel.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 3, left: 27, bottom: 3, right: 3))
}
gameIDLabel.textColor = UIColor.white
gameIDLabel.font = UIFont.boldSystemFont(ofSize: 16)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTapGesture(_:)))
gameIDView.addGestureRecognizer(tap)
gameIDView.isUserInteractionEnabled = true
nameLabel = UILabel()
readableContentView.addSubview(nameLabel)
nameLabel.font = UIFont.systemFont(ofSize: 16)
nameLabel.snp.makeConstraints { (make) in
make.left.equalTo(gameIDView.snp.right).offset(5)
make.lastBaseline.equalTo(gameIDLabel)
}
createdDateLabel = UILabel()
readableContentView.addSubview(createdDateLabel)
createdDateLabel.font = UIFont.systemFont(ofSize: 14)
createdDateLabel.textColor = UIColor.lightGray
createdDateLabel.snp.makeConstraints { (make) in
make.left.greaterThanOrEqualTo(gameIDLabel.snp.right).offset(5)
make.right.equalTo(-10)
make.lastBaseline.equalTo(nameLabel)
}
nameLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultLow, for: .horizontal)
gameIDView.setContentCompressionResistancePriority(UILayoutPriority.required, for: .horizontal)
createdDateLabel.setContentCompressionResistancePriority(UILayoutPriority.defaultHigh, for: .horizontal)
messageLabel = UILabel()
readableContentView.addSubview(messageLabel)
messageLabel.numberOfLines = 7
messageLabel.font = UIFont.systemFont(ofSize: 11)
messageLabel.textColor = UIColor.darkGray
messageLabel.snp.makeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(gameIDView.snp.bottom).offset(5)
make.right.equalTo(-10)
}
myCenterGroupView = MyCenterGroupView()
readableContentView.addSubview(myCenterGroupView)
myCenterGroupView.snp.makeConstraints { (make) in
make.left.equalToSuperview()
make.top.equalTo(messageLabel.snp.bottom).offset(5)
make.height.lessThanOrEqualTo(89.5)
make.bottom.equalTo(-10)
}
myCenterGroupView.delegate = self
selectionStyle = .none
}
@objc func handleTapGesture(_ tap: UITapGestureRecognizer) {
delegate?.colleagueTableViewCell(self, didTap: gameIDLabel.text ?? "")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setup(_ profile: Profile) {
gameIDLabel.text = profile.gameID
nameLabel.text = profile.nickName
messageLabel.text = profile.message
createdDateLabel.text = profile.remoteCreatedAt?.getElapsedInterval()
for (index, center) in profile.myCenters.enumerated() {
myCenterGroupView.setupWith(cardID: center.0, potential: center.1, at: index, hidesIfNeeded: true)
}
// for (index, center) in profile.centersWanted.enumerated() {
// centerWantedGroupView.setupWith(cardID: center.0, minLevel: center.1, at: index, hidesIfNeeded: true)
// }
}
// override func setSelected(_ selected: Bool, animated: Bool) {
// super.setSelected(selected, animated: animated)
//
// if selected {
// readableContentView.addSubview(centerWantedLabel)
// centerWantedLabel.snp.makeConstraints { (make) in
// make.left.equalTo(10)
// make.top.equalTo(myCenterGroupView.snp.bottom).offset(10)
// }
// readableContentView.addSubview(centerWantedGroupView)
// centerWantedGroupView.snp.makeConstraints { (make) in
// make.left.equalToSuperview()
// make.top.equalTo(centerWantedLabel.snp.bottom).offset(5)
// make.height.lessThanOrEqualTo(89.5)
// make.bottom.equalTo(-10)
// }
// } else {
// centerWantedGroupView.removeFromSuperview()
// centerWantedLabel.removeFromSuperview()
// }
// layoutIfNeeded()
//
// }
}
extension ColleagueTableViewCell: MyCenterGroupViewDelegate {
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didLongPressAt item: MyCenterItemView) {
}
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didDoubleTap item: MyCenterItemView) {
}
func profileMemberEditableView(_ profileMemberEditableView: MyCenterGroupView, didTap item: MyCenterItemView) {
delegate?.colleagueTableViewCell(self, didTap: item.cardView.icon)
}
}
| mit | 1d47a1fb12d2cb7f9e91c7f647572838 | 37.769663 | 123 | 0.661209 | 4.729952 | false | false | false | false |
corin8823/SwiftyExtensions | SwiftyExtensions/UICollectionView+Register.swift | 1 | 1466 | //
// UICollectionView+Register.swift
// SwiftyExtensions
//
// Created by yusuke takahashi on 8/2/15.
// Copyright (c) 2015 yusuke takahashi. All rights reserved.
//
import UIKit
extension UICollectionView {
public func registerNibFromClass<T: UICollectionViewCell>(type: T.Type) {
let className = StringFromClass(T)
let nib = UINib(nibName: className, bundle: nil)
registerNib(nib, forCellWithReuseIdentifier: className)
}
public func registerNibFromClass<T: UICollectionReusableView>(type: T.Type, forSupplementaryViewOfKind kind: String) {
let className = StringFromClass(T)
let nib = UINib(nibName: className, bundle: nil)
registerNib(nib, forSupplementaryViewOfKind: kind, withReuseIdentifier: className)
}
public func registerClassFromClass<T: UICollectionViewCell>(type: T.Type) {
let className = StringFromClass(T)
registerClass(T.self, forCellWithReuseIdentifier: className)
}
public func dequeueReusableCell<T: UICollectionViewCell>(type: T.Type,
forIndexPath indexPath: NSIndexPath) -> T {
return dequeueReusableCellWithReuseIdentifier(StringFromClass(T), forIndexPath: indexPath) as! T
}
public func dequeueReusableCell<T: UICollectionReusableView>(kind: String, withReuseType type: T.Type,
forIndexPath indexPath: NSIndexPath) -> T {
return dequeueReusableSupplementaryViewOfKind(kind,
withReuseIdentifier: StringFromClass(T), forIndexPath: indexPath) as! T
}
} | mit | e7aa4ce90d9a3bf284335174fad5682b | 35.675 | 120 | 0.757844 | 4.729032 | false | false | false | false |
stockx/PinEntryView | PinEntryView/Classes/UIView+Autolayout.swift | 1 | 9433 | //
// UIView+AutoLayout.swift
// PinEntryView
//
// Created by Josh Sklar on 2/1/17.
// Copyright © 2017 StockX. All rights reserved.
//
import UIKit
extension UIView {
// MARK: Edges
/**
Makes the edges of the receiver equal to the edges of `view`.
Note: `view` must already be constrained, and both the receiver
and `view` must have a common superview.
*/
func makeEdgesEqualTo(_ view: UIView) {
makeAttribute(.leading, equalToOtherView: view, attribute: .leading)
makeAttribute(.trailing, equalToOtherView: view, attribute: .trailing)
makeAttribute(.top, equalToOtherView: view, attribute: .top)
makeAttribute(.bottom, equalToOtherView: view, attribute: .bottom)
}
/**
Makes the edges of the receiver equal to its superview with an otion to
specify an inset value.
If the receiver does not have a superview, this does nothing.
*/
func makeEdgesEqualToSuperview(inset: CGFloat = 0) {
makeAttributesEqualToSuperview([.leading, .top], offset: inset)
makeAttributesEqualToSuperview([.trailing, .bottom], offset: -inset)
}
// MARK: Attributes
/**
Creates and applies a constraint with the given attribute equal to that
same attribute of the superview, and returns the constraint.
*/
func makeConstraintEqualToSuperview(_ attribute: NSLayoutConstraint.Attribute) -> NSLayoutConstraint? {
guard let superview = superview else {
return nil
}
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: superview,
attribute: attribute,
multiplier: 1.0,
constant: 0.0)
superview.addConstraint(constraint)
return constraint
}
/**
Applies constraints to the receiver with attributes `attributes` all
equal to its superview.
*/
func makeAttributesEqualToSuperview(_ attributes: [NSLayoutConstraint.Attribute], offset: CGFloat = 0) {
makeAttributes(attributes, relationToSuperview: .equal, offset: offset)
}
func makeAttributesGreaterThanOrEqualToSuperview(_ attributes: [NSLayoutConstraint.Attribute], offset: CGFloat = 0) {
makeAttributes(attributes, relationToSuperview: .greaterThanOrEqual, offset: offset)
}
func makeAttributesLessThanOrEqualToSuperview(_ attributes: [NSLayoutConstraint.Attribute], offset: CGFloat = 0) {
makeAttributes(attributes, relationToSuperview: .lessThanOrEqual, offset: offset)
}
func makeAttributes(_ attributes: [NSLayoutConstraint.Attribute], relationToSuperview relation: NSLayoutConstraint.Relation = .equal, offset: CGFloat = 0) {
guard let superview = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
attributes.forEach {
superview.addConstraint(NSLayoutConstraint(item: self,
attribute: $0,
relatedBy: relation,
toItem: superview,
attribute: $0,
multiplier: 1.0,
constant: offset))
}
}
/**
Creates and applies a constraint to the receiver with attribute
`attribute` and the specified constant, and returns the constraint.
*/
func makeConstraint(for attribute: NSLayoutConstraint.Attribute, equalTo constant: CGFloat) -> NSLayoutConstraint? {
guard let superview = superview else {
return nil
}
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: constant)
superview.addConstraint(constraint)
return constraint
}
/**
Applies a constraint to the receiver with attribute `attribute` and
the specified constant.
*/
func makeAttribute(_ attribute: NSLayoutConstraint.Attribute, equalTo constant: CGFloat) {
guard let superview = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: constant)
superview.addConstraint(constraint)
}
/**
Applies a constraint to the receiver with attribute `attribute` and
the specified constant.
*/
func makeAttribute(_ attribute: NSLayoutConstraint.Attribute, greaterThanOrEqualTo constant: CGFloat) {
guard let superview = superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
let constraint = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .greaterThanOrEqual,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 1.0,
constant: constant)
superview.addConstraint(constraint)
}
/**
Applies a constraint with the attribute `attribute` from the receiver to
the view `otherView` with attribute `attribute`.
*/
func makeAttribute(_ attribute: NSLayoutConstraint.Attribute,
equalToOtherView otherView: UIView,
attribute otherAttribute: NSLayoutConstraint.Attribute,
constant: CGFloat = 0,
multiplier: CGFloat = 1) {
guard let sv = otherView.superview,
sv == self.superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
let attribute = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .equal,
toItem: otherView,
attribute: otherAttribute,
multiplier: multiplier,
constant: constant)
sv.addConstraint(attribute)
}
/**
Applies a constraint with the attribute `attribute` from the receiver to
the view `otherView` with attribute `attribute`.
*/
func makeAttribute(_ attribute: NSLayoutConstraint.Attribute,
greaterThanOrEqualToOtherView otherView: UIView,
attribute otherAttribute: NSLayoutConstraint.Attribute,
constant: CGFloat = 0,
multiplier: CGFloat = 1) {
guard let sv = otherView.superview,
sv == self.superview else {
return
}
translatesAutoresizingMaskIntoConstraints = false
let attribute = NSLayoutConstraint(item: self,
attribute: attribute,
relatedBy: .greaterThanOrEqual,
toItem: otherView,
attribute: otherAttribute,
multiplier: multiplier,
constant: constant)
sv.addConstraint(attribute)
}
// MARK: Utility
/**
Removes all the constrains where the receiver is either the
firstItem or secondItem.
If the receiver does not have a superview, this only removes the
constraints that the receiver owns.
*/
func removeAllConstraints() {
guard let superview = superview else {
removeConstraints(constraints)
return
}
for constraint in superview.constraints where (constraint.firstItem as? UIView == self || constraint.secondItem as? UIView == self) {
superview.removeConstraint(constraint)
}
removeConstraints(constraints)
}
}
| mit | a80c15047afd71ff55bb1a8ebb908e9e | 39.480687 | 160 | 0.525339 | 6.829833 | false | false | false | false |
NoManTeam/Hole | CryptoFramework/Crypto/Algorithm/AES_256_ECB/NSAESString.swift | 1 | 958 | //
// NSAESString.swift
// 密语输入法
//
// Created by macsjh on 15/10/17.
// Copyright © 2015年 macsjh. All rights reserved.
//
import Foundation
class NSAESString:NSObject
{
internal static func aes256_encrypt(PlainText:NSString, Key:NSString) -> NSString?
{
let cstr:UnsafePointer<Int8> = PlainText.cStringUsingEncoding(NSUTF8StringEncoding)
let data = NSData(bytes: cstr, length:PlainText.length)
//对数据进行加密
let result = data.aes256_encrypt(Key)
if (result != nil && result!.length > 0 ) {
return result!.toHexString()
}
return nil
}
internal static func aes256_decrypt(CipherText:String, key:NSString) -> NSString?
{
//转换为2进制Data
guard let data = CipherText.hexStringToData() else {return nil}
//对数据进行解密
let result = data.aes256_decrypt(key)
if (result != nil && result!.length > 0) {
return NSString(data:result!, encoding:NSUTF8StringEncoding)
}
return nil
}
} | unlicense | 8ce00b9b0062e786e1f1b0c07c7dc88f | 24.942857 | 85 | 0.708931 | 3.160279 | false | false | false | false |
toadzky/SLF4Swift | Backend/CocoaLumberJack/CocoaLumberJack.swift | 1 | 4657 | //
// CocoaLumberJack.swift
// SLF4Swift
/*
The MIT License (MIT)
Copyright (c) 2015 Eric Marchand (phimage)
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
#if EXTERNAL
import SLF4Swift
#endif
import CocoaLumberjack
/* Log with SwiftLogMacro from CocoaLumberjack */
public class CocoaLumberjackMacroLogger: LoggerType {
public class var instance : CocoaLumberjackMacroLogger {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : CocoaLumberjackMacroLogger?
}
dispatch_once(&Static.onceToken) {
Static.instance = CocoaLumberjackMacroLogger()
}
return Static.instance!
}
public var level: SLFLogLevel {
get {
return CocoaLumberjackMacroLogger.toLevel(defaultDebugLevel)
}
set {
defaultDebugLevel = CocoaLumberjackMacroLogger.fromLevel(newValue)
}
}
public var name: LoggerKeyType = "macro"
public var isAsynchronous = true
public func info(message: LogMessageType) {
DDLogInfo(message, asynchronous: isAsynchronous)
}
public func error(message: LogMessageType) {
DDLogError(message, asynchronous: isAsynchronous)
}
public func severe(message: LogMessageType) {
error(message) // no fatal or severe level
}
public func warn(message: LogMessageType) {
DDLogWarn(message, asynchronous: isAsynchronous)
}
public func debug(message: LogMessageType) {
DDLogDebug(message, asynchronous: isAsynchronous)
}
public func verbose(message: LogMessageType) {
DDLogVerbose(message, asynchronous: isAsynchronous)
}
public func log(level: SLFLogLevel,_ message: LogMessageType) {
SwiftLogMacro(self.isAsynchronous, level: defaultDebugLevel, flag: DDLogFlag.fromLogLevel(CocoaLumberjackMacroLogger.fromLevel(level)), string: message)
}
public func isLoggable(level: SLFLogLevel) -> Bool {
return level <= self.level
}
public static func toLevel(level:DDLogLevel) -> SLFLogLevel {
switch(level){
case .Off: return SLFLogLevel.Off
case .Error: return SLFLogLevel.Error
case .Warning: return SLFLogLevel.Warn
case .Info: return SLFLogLevel.Info
case .Debug: return SLFLogLevel.Debug
case .Verbose: return SLFLogLevel.Verbose
case .All: return SLFLogLevel.Off
}
}
public static func fromLevel(level:SLFLogLevel) -> DDLogLevel {
switch(level){
case .Off: return DDLogLevel.Off
case .Severe: return DDLogLevel.Error
case .Error: return DDLogLevel.Error
case .Warn: return DDLogLevel.Warning
case .Info: return DDLogLevel.Info
case .Debug: return DDLogLevel.Debug
case .Verbose: return DDLogLevel.Verbose
case .All: return DDLogLevel.Off
}
}
}
public class CocoaLumberjackMacroLoggerFactory: SingleLoggerFactory {
public class var instance : CocoaLumberjackMacroLoggerFactory {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : CocoaLumberjackMacroLoggerFactory?
}
dispatch_once(&Static.onceToken) {
Static.instance = CocoaLumberjackMacroLoggerFactory()
}
return Static.instance!
}
public init(logger: CocoaLumberjackMacroLogger = CocoaLumberjackMacroLogger.instance) {
super.init(logger: logger)
}
public override func removeAllLoggers() {
// DDLog.removeAllLoggers()
}
} | mit | de7f014b53361606e5ab5f2109ec5a8e | 33.25 | 160 | 0.690788 | 4.825907 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Components/Benchmark.swift | 1 | 1150 | //
// Xcore
// Copyright © 2015 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
// Credit: http://stackoverflow.com/a/31412302
/// A convenience function to measure code execution.
///
/// **Asynchronous code:**
///
/// ```swift
/// measure(label: "some title") { finish in
/// myAsyncCall {
/// finish()
/// }
/// // ...
/// }
/// ```
///
/// **Synchronous code:**
///
/// ```swift
/// measure(label: "some title") { finish in
/// // code to benchmark
/// finish()
/// // ...
/// }
/// ```
///
/// - Parameters:
/// - label: Measure block name.
/// - block: Call `finish` block to measure test.
public func measure(label: String, block: (_ finish: () -> Void) -> Void) {
let startTime = CFAbsoluteTimeGetCurrent()
block {
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("\(label):: Time: \(timeElapsed)", format(seconds: timeElapsed))
}
}
private func format(seconds: TimeInterval) -> String {
let value = Int(seconds)
let seconds = value % 60
let minutes = value / 60
return String(format: "%02d:%02d", minutes, seconds)
}
| mit | c73f217e98326f361e2d95852c4aabf1 | 21.529412 | 78 | 0.580505 | 3.779605 | false | false | false | false |
ORT-Interactive-GmbH/OnlineL10n | OnlineL10n/UI/CountryController.swift | 1 | 5140 | //
// CountryController.swift
// ORT Interactive
//
// Created by Alexander Vorobjov on 22/01/15.
// Copyright (c) 2015 Alexander Vorobjov. All rights reserved.
//
public class CountryController: UIViewController {
// localization manager has to be set before opening view
@objc public var localizationManager: LocalizationProvider!
public var hideBackButton = false
private var previousLanguage: String?
private var selectedLanguage = ""
var selectedRow: IndexPath? {
didSet {
self.selectionChanged(old: oldValue)
}
}
@IBOutlet var tableView: UITableView!
@IBOutlet weak var backButton: UIBarButtonItem!
@IBOutlet weak var doneButton: UIBarButtonItem!
@objc public var delegate: CountryControllerDelegate?
override public func viewDidLoad() {
// bundle identifier might be something like org.cocoapods.OnlineL10n when installed through CocoaPods
let bundleIdentifier = Bundle(for: CountryController.self).bundleIdentifier!
// set title string here
self.subscribeToLanguage(manager: self.localizationManager, key: "\(bundleIdentifier).countrycontroller.title")
// set back button title
self.backButton.subscribeToLanguage(manager: self.localizationManager, key: "\(bundleIdentifier).countrycontroller.back")
// set done button title
self.doneButton.subscribeToLanguage(manager: self.localizationManager, key: "\(bundleIdentifier).countrycontroller.done")
// keep initial language
self.previousLanguage = self.localizationManager.currentLanguage()
doneButton.isEnabled = false
selectDefaultRow()
super.viewDidLoad()
}
public override func viewWillAppear(_ animated: Bool) {
// might not need back button
if self.hideBackButton {
self.navigationItem.leftBarButtonItem?.isEnabled = false
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.clear
}
super.viewWillAppear(animated)
}
func selectionChanged(old oldSelection: IndexPath? = nil) {
doneButton.isEnabled = selectedRow != nil
if let old = oldSelection {
tableView.cellForRow(at: old)?.accessoryType = .none
}
if let current = selectedRow {
tableView.cellForRow(at: current)?.accessoryType = .checkmark
// select language
self.selectedLanguage = self.localizationManager.selectLanguageBy(index: selectedRow!.row)
// notify delegate
if let del = delegate {
del.selected(language: self.selectedLanguage)
}
}
}
func selectDefaultRow() {
selectedRow = findDefaultRow()
if let sel = selectedRow {
tableView.scrollToRow(at: sel, at: .middle, animated: false)
}
}
func findDefaultRow() -> IndexPath? {
if let selectedLocale = self.localizationManager.currentLanguage() {
let allLocales = self.localizationManager.languages()
if let index = allLocales.firstIndex(of: selectedLocale) {
return IndexPath(row: index, section: 0)
}
}
return nil
}
@IBAction func onDone() {
// notify delegate
if let del = delegate {
del.onDoneButton(fromLanguage: self.previousLanguage, toLanguage: self.selectedLanguage)
} else {
_ = self.navigationController?.popViewController(animated: true)
}
}
@IBAction func onBack() {
// notify delegate
if let del = delegate {
del.onBackButton()
} else {
_ = self.navigationController?.popViewController(animated: true)
}
}
}
extension CountryController : UITableViewDataSource {
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.localizationManager == nil ? 0 : self.localizationManager.languageCount()
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let country = self.localizationManager.languages()[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: CountryCellStoryboardId, for: indexPath) as! CountryCell
cell.accessoryType = (indexPath == selectedRow) ? .checkmark : .none
cell.labelName.text = country
cell.layoutMargins = UIEdgeInsets.zero
if (self.localizationManager.hasFlags()) {
if let flag = self.localizationManager.flag(language: country) {
cell.display(flag: flag)
} else {
self.localizationManager.flag(language: country) { (cntry: String, image: Data?) in
cell.display(flag: image)
}
}
} else {
cell.display(flag: nil)
}
return cell
}
}
extension CountryController : UITableViewDelegate {
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedRow = indexPath
}
}
| mit | aee9488aa693db162c46740ef8587ef6 | 33.965986 | 129 | 0.65 | 5.165829 | false | false | false | false |
konanxu/WeiBoWithSwift | WeiBo/WeiBo/Classes/Tools/Category/UIView+Category.swift | 1 | 677 | //
// UIView+Category.swift
// WeiBo
//
// Created by Konan on 16/3/21.
// Copyright © 2016年 Konan. All rights reserved.
//
import UIKit
extension UIView{
func getConstraintWidth() ->NSLayoutConstraint?{
let arr = self.constraints
for cons in arr{
if(cons.firstAttribute == NSLayoutAttribute.Width){
return cons
}
}
return nil
}
func getConstraintHeight() ->NSLayoutConstraint?{
let arr = self.constraints
for cons in arr{
if(cons.firstAttribute == NSLayoutAttribute.Height){
return cons
}
}
return nil
}
} | mit | 8ead7fd4cd4034897be5eee1f96b6d2b | 20.09375 | 64 | 0.559347 | 4.648276 | false | false | false | false |
Jnosh/swift | stdlib/public/core/ArrayType.swift | 1 | 2718 | //===--- ArrayType.swift - Protocol for Array-like types ------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
internal protocol _ArrayProtocol
: RangeReplaceableCollection,
ExpressibleByArrayLiteral
{
//===--- public interface -----------------------------------------------===//
/// The number of elements the Array stores.
var count: Int { get }
/// The number of elements the Array can store without reallocation.
var capacity: Int { get }
/// `true` if and only if the Array is empty.
var isEmpty: Bool { get }
/// An object that guarantees the lifetime of this array's elements.
var _owner: AnyObject? { get }
/// If the elements are stored contiguously, a pointer to the first
/// element. Otherwise, `nil`.
var _baseAddressIfContiguous: UnsafeMutablePointer<Element>? { get }
subscript(index: Int) -> Element { get set }
//===--- basic mutations ------------------------------------------------===//
/// Reserve enough space to store minimumCapacity elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
mutating func reserveCapacity(_ minimumCapacity: Int)
/// Insert `newElement` at index `i`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`self.count`).
///
/// - Precondition: `startIndex <= i`, `i <= endIndex`.
mutating func insert(_ newElement: Element, at i: Int)
/// Remove and return the element at the given index.
///
/// - returns: The removed element.
///
/// - Complexity: Worst case O(*n*).
///
/// - Precondition: `count > index`.
@discardableResult
mutating func remove(at index: Int) -> Element
//===--- implementation detail -----------------------------------------===//
associatedtype _Buffer : _ArrayBufferProtocol
init(_ buffer: _Buffer)
// For testing.
var _buffer: _Buffer { get }
}
extension _ArrayProtocol {
// Since RangeReplaceableCollection now has a version of filter that is less
// efficient, we should make the default implementation coming from Sequence
// preferred.
@_inlineable
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> [Element] {
return try _filter(isIncluded)
}
}
| apache-2.0 | 1e893416fe8d50bc0b57fd6587e1fe7e | 31.357143 | 80 | 0.611847 | 4.84492 | false | false | false | false |
coach-plus/ios | Pods/RxSwift/RxSwift/Observables/ShareReplayScope.swift | 6 | 14262 | //
// ShareReplayScope.swift
// RxSwift
//
// Created by Krunoslav Zaher on 5/28/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Subject lifetime scope
public enum SubjectLifetimeScope {
/**
**Each connection will have it's own subject instance to store replay events.**
**Connections will be isolated from each another.**
Configures the underlying implementation to behave equivalent to.
```
source.multicast(makeSubject: { MySubject() }).refCount()
```
**This is the recommended default.**
This has the following consequences:
* `retry` or `concat` operators will function as expected because terminating the sequence will clear internal state.
* Each connection to source observable sequence will use it's own subject.
* When the number of subscribers drops from 1 to 0 and connection to source sequence is disposed, subject will be cleared.
```
let xs = Observable.deferred { () -> Observable<TimeInterval> in
print("Performing work ...")
return Observable.just(Date().timeIntervalSince1970)
}
.share(replay: 1, scope: .whileConnected)
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
```
Notice how time interval is different and `Performing work ...` is printed each time)
```
Performing work ...
next 1495998900.82141
completed
Performing work ...
next 1495998900.82359
completed
Performing work ...
next 1495998900.82444
completed
```
*/
case whileConnected
/**
**One subject will store replay events for all connections to source.**
**Connections won't be isolated from each another.**
Configures the underlying implementation behave equivalent to.
```
source.multicast(MySubject()).refCount()
```
This has the following consequences:
* Using `retry` or `concat` operators after this operator usually isn't advised.
* Each connection to source observable sequence will share the same subject.
* After number of subscribers drops from 1 to 0 and connection to source observable sequence is dispose, this operator will
continue holding a reference to the same subject.
If at some later moment a new observer initiates a new connection to source it can potentially receive
some of the stale events received during previous connection.
* After source sequence terminates any new observer will always immediately receive replayed elements and terminal event.
No new subscriptions to source observable sequence will be attempted.
```
let xs = Observable.deferred { () -> Observable<TimeInterval> in
print("Performing work ...")
return Observable.just(Date().timeIntervalSince1970)
}
.share(replay: 1, scope: .forever)
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
_ = xs.subscribe(onNext: { print("next \($0)") }, onCompleted: { print("completed\n") })
```
Notice how time interval is the same, replayed, and `Performing work ...` is printed only once
```
Performing work ...
next 1495999013.76356
completed
next 1495999013.76356
completed
next 1495999013.76356
completed
```
*/
case forever
}
extension ObservableType {
/**
Returns an observable sequence that **shares a single subscription to the underlying sequence**, and immediately upon subscription replays elements in buffer.
This operator is equivalent to:
* `.whileConnected`
```
// Each connection will have it's own subject instance to store replay events.
// Connections will be isolated from each another.
source.multicast(makeSubject: { Replay.create(bufferSize: replay) }).refCount()
```
* `.forever`
```
// One subject will store replay events for all connections to source.
// Connections won't be isolated from each another.
source.multicast(Replay.create(bufferSize: replay)).refCount()
```
It uses optimized versions of the operators for most common operations.
- parameter replay: Maximum element count of the replay buffer.
- parameter scope: Lifetime scope of sharing subject. For more information see `SubjectLifetimeScope` enum.
- seealso: [shareReplay operator on reactivex.io](http://reactivex.io/documentation/operators/replay.html)
- returns: An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
public func share(replay: Int = 0, scope: SubjectLifetimeScope = .whileConnected)
-> Observable<Element> {
switch scope {
case .forever:
switch replay {
case 0: return self.multicast(PublishSubject()).refCount()
default: return self.multicast(ReplaySubject.create(bufferSize: replay)).refCount()
}
case .whileConnected:
switch replay {
case 0: return ShareWhileConnected(source: self.asObservable())
case 1: return ShareReplay1WhileConnected(source: self.asObservable())
default: return self.multicast(makeSubject: { ReplaySubject.create(bufferSize: replay) }).refCount()
}
}
}
}
private final class ShareReplay1WhileConnectedConnection<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareReplay1WhileConnected<Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private let _lock: RecursiveLock
private var _disposed: Bool = false
fileprivate var _observers = Observers()
private var _element: Element?
init(parent: Parent, lock: RecursiveLock) {
self._parent = parent
self._lock = lock
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
final func on(_ event: Event<Element>) {
self._lock.lock()
let observers = self._synchronized_on(event)
self._lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<Element>) -> Observers {
if self._disposed {
return Observers()
}
switch event {
case .next(let element):
self._element = element
return self._observers
case .error, .completed:
let observers = self._observers
self._synchronized_dispose()
return observers
}
}
final func connect() {
self._subscription.setDisposable(self._parent._source.subscribe(self))
}
final func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock(); defer { self._lock.unlock() }
if let element = self._element {
observer.on(.next(element))
}
let disposeKey = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: disposeKey)
}
final private func _synchronized_dispose() {
self._disposed = true
if self._parent._connection === self {
self._parent._connection = nil
}
self._observers = Observers()
}
final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
let shouldDisconnect = self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
if shouldDisconnect {
self._subscription.dispose()
}
}
@inline(__always)
final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool {
// if already unsubscribed, just return
if self._observers.removeKey(disposeKey) == nil {
return false
}
if self._observers.count == 0 {
self._synchronized_dispose()
return true
}
return false
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
// optimized version of share replay for most common case
final private class ShareReplay1WhileConnected<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareReplay1WhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
private let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let connection = self._synchronized_subscribe(observer)
let count = connection._observers.count
let disposable = connection._synchronized_subscribe(observer)
self._lock.unlock()
if count == 0 {
connection.connect()
}
return disposable
}
@inline(__always)
private func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element {
let connection: Connection
if let existingConnection = self._connection {
connection = existingConnection
}
else {
connection = ShareReplay1WhileConnectedConnection<Element>(
parent: self,
lock: self._lock)
self._connection = connection
}
return connection
}
}
private final class ShareWhileConnectedConnection<Element>
: ObserverType
, SynchronizedUnsubscribeType {
typealias Observers = AnyObserver<Element>.s
typealias DisposeKey = Observers.KeyType
typealias Parent = ShareWhileConnected<Element>
private let _parent: Parent
private let _subscription = SingleAssignmentDisposable()
private let _lock: RecursiveLock
private var _disposed: Bool = false
fileprivate var _observers = Observers()
init(parent: Parent, lock: RecursiveLock) {
self._parent = parent
self._lock = lock
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
}
final func on(_ event: Event<Element>) {
self._lock.lock()
let observers = self._synchronized_on(event)
self._lock.unlock()
dispatch(observers, event)
}
final private func _synchronized_on(_ event: Event<Element>) -> Observers {
if self._disposed {
return Observers()
}
switch event {
case .next:
return self._observers
case .error, .completed:
let observers = self._observers
self._synchronized_dispose()
return observers
}
}
final func connect() {
self._subscription.setDisposable(self._parent._source.subscribe(self))
}
final func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock(); defer { self._lock.unlock() }
let disposeKey = self._observers.insert(observer.on)
return SubscriptionDisposable(owner: self, key: disposeKey)
}
final private func _synchronized_dispose() {
self._disposed = true
if self._parent._connection === self {
self._parent._connection = nil
}
self._observers = Observers()
}
final func synchronizedUnsubscribe(_ disposeKey: DisposeKey) {
self._lock.lock()
let shouldDisconnect = self._synchronized_unsubscribe(disposeKey)
self._lock.unlock()
if shouldDisconnect {
self._subscription.dispose()
}
}
@inline(__always)
final private func _synchronized_unsubscribe(_ disposeKey: DisposeKey) -> Bool {
// if already unsubscribed, just return
if self._observers.removeKey(disposeKey) == nil {
return false
}
if self._observers.count == 0 {
self._synchronized_dispose()
return true
}
return false
}
#if TRACE_RESOURCES
deinit {
_ = Resources.decrementTotal()
}
#endif
}
// optimized version of share replay for most common case
final private class ShareWhileConnected<Element>
: Observable<Element> {
fileprivate typealias Connection = ShareWhileConnectedConnection<Element>
fileprivate let _source: Observable<Element>
private let _lock = RecursiveLock()
fileprivate var _connection: Connection?
init(source: Observable<Element>) {
self._source = source
}
override func subscribe<Observer: ObserverType>(_ observer: Observer) -> Disposable where Observer.Element == Element {
self._lock.lock()
let connection = self._synchronized_subscribe(observer)
let count = connection._observers.count
let disposable = connection._synchronized_subscribe(observer)
self._lock.unlock()
if count == 0 {
connection.connect()
}
return disposable
}
@inline(__always)
private func _synchronized_subscribe<Observer: ObserverType>(_ observer: Observer) -> Connection where Observer.Element == Element {
let connection: Connection
if let existingConnection = self._connection {
connection = existingConnection
}
else {
connection = ShareWhileConnectedConnection<Element>(
parent: self,
lock: self._lock)
self._connection = connection
}
return connection
}
}
| mit | fba516958e9914031149ae6bd79b35a8 | 30.274123 | 164 | 0.634387 | 5.037443 | false | false | false | false |
duliodenis/v | V/V/Model/FirebaseStore.swift | 1 | 4127 | //
// FirebaseStore.swift
// V
//
// Created by Dulio Denis on 8/18/16.
// Copyright © 2016 Dulio Denis. All rights reserved.
//
import Foundation
import Firebase
import CoreData
class FirebaseStore {
private let context: NSManagedObjectContext
private let rootRef = Firebase(url: FIREBASE_URL)
private(set) static var currentPhoneNumber: String? {
set(phoneNumber) {
NSUserDefaults.standardUserDefaults().setObject(phoneNumber, forKey:"phoneNumber")
}
get {
return NSUserDefaults.standardUserDefaults().objectForKey("phoneNumber") as? String
}
}
init(context: NSManagedObjectContext) {
self.context = context
}
func hasAuth() -> Bool {
return rootRef.authData != nil
}
private func upload(model: NSManagedObject) {
guard let model = model as? FirebaseModel else {return}
model.upload(rootRef, context: context)
}
private func fetchAppContacts() -> [Contact] {
// use a do-catch statement to make a request for our Contact instances
do {
// set-up a fetch request for Contact instances
let request = NSFetchRequest(entityName: "Contact")
// constrain the results to those in Firebase
request.predicate = NSPredicate(format: "storageID != nil")
// get results back by executing the fetch request
if let results = try self.context.executeFetchRequest(request) as? [Contact] {
// and returning the results as an array of Contact instances
return results
}
// otherwise print an error
} catch {
print("Firebase Store error fetching App Contacts.")
}
// and return an empty array
return []
}
private func observeUserStatus(contact: Contact) {
contact.observeStatus(rootRef, context: context)
}
private func observeStatuses() {
let contacts = fetchAppContacts()
contacts.forEach(observeUserStatus)
}
}
extension FirebaseStore: RemoteStore {
func startSyncing() {
context.performBlock {
self.observeStatuses()
}
}
func store(inserted inserted: [NSManagedObject], updated: [NSManagedObject], deleted: [NSManagedObject]) {
inserted.forEach(upload)
do {
try context.save()
} catch {
print("FirebaseStore: RemoteStore error saving.")
}
}
func signUp(phoneNumber phoneNumber: String, email: String, password: String, success: () -> (), error errorCallback: (errorMessage: String) -> ()) {
rootRef.createUser(email, password: password, withValueCompletionBlock: {
error, result in
if error != nil {
errorCallback(errorMessage: error.description)
} else {
// generate a new user with a key-value pair of a phone number
let newUser = [
"phoneNumber": phoneNumber
]
// update our current phone number to persist in NSUserDefaults
FirebaseStore.currentPhoneNumber = phoneNumber
// get our Unique ID from the result
let uid = result["uid"] as! String
// set the rootRef/users/uid value = newUser
self.rootRef.childByAppendingPath("users").childByAppendingPath(uid).setValue(newUser)
// and authenticate the user
self.rootRef.authUser(email, password: password, withCompletionBlock: {
error, authData in
if error != nil {
errorCallback(errorMessage: error.description)
} else {
success()
}
})
}
})
}
} | mit | d644742a2a2cb4e9eb6942877eaa86e1 | 29.124088 | 153 | 0.55332 | 5.583221 | false | false | false | false |
sora0077/iTunesMusic | Demo/Views/PlaybackViewController.swift | 1 | 2435 | //
// PlaybackViewController.swift
// iTunesMusic
//
// Created by 林達也 on 2016/10/17.
// Copyright © 2016年 jp.sora0077. All rights reserved.
//
import UIKit
import iTunesMusic
private final class InnerShadowView: UIView {
private var shadowLayer = CALayer()
override func layoutSubviews() {
super.layoutSubviews()
makeShadow(to: self)
}
func makeShadow(to view: UIView) {
let sublayer = CALayer()
shadowLayer.removeFromSuperlayer()
shadowLayer = sublayer
sublayer.frame = view.bounds
view.layer.addSublayer(sublayer)
sublayer.masksToBounds = true
let width: CGFloat = 20
let size = sublayer.bounds.size
var point = CGPoint(x: -width, y: -width)
let path = CGMutablePath()
path.move(to: point)
point.x += size.width + width
path.addLine(to: point)
point.y += width
path.addLine(to: point)
point.x -= size.width
path.addLine(to: point)
point.y += size.height
path.addLine(to: point)
point.x -= width
path.addLine(to: point)
point.y -= size.height + width
path.addLine(to: point)
path.closeSubpath()
sublayer.shadowOffset = CGSize(width: 10, height: 10)
sublayer.shadowOpacity = 0.8
sublayer.shadowRadius = 10
sublayer.shadowPath = path
}
}
final class PlaybackViewController: UIViewController {
private let artworkImageView = UIImageView()
private let shadowView = InnerShadowView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(artworkImageView)
artworkImageView.contentMode = .scaleAspectFill
artworkImageView.snp.makeConstraints { make in
make.top.equalTo(-20)
make.bottom.equalTo(20)
make.left.right.equalTo(-20)
}
artworkImageView.addTiltEffects(tilt: .background(depth: 10))
artworkImageView.layer.zPosition = -1000
view.addSubview(shadowView)
shadowView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
shadowView.snp.makeConstraints { make in
make.edges.equalTo(0)
}
}
func setArtwork(of collection: iTunesMusic.Collection, size: CGFloat) {
//animator.fractionComplete = 0.9
artworkImageView.setArtwork(of: collection, size: size)
}
}
| mit | 48201be7bcc31838c01948f4b510326f | 26.258427 | 75 | 0.63108 | 4.526119 | false | false | false | false |
HolidayAdvisorIOS/HolidayAdvisor | HolidayAdvisor/HolidayAdvisor/UserListTableViewController.swift | 1 | 5550 | //
// UserListTableViewController.swift
// HolidayAdvisor
//
// Created by Iliyan Gogov on 4/4/17.
// Copyright © 2017 Iliyan Gogov. All rights reserved.
//
import UIKit
class UserTableViewCell: UITableViewCell {
@IBOutlet weak var userName: UILabel!
@IBOutlet weak var age: UILabel!
@IBOutlet weak var gender: UILabel!
@IBOutlet weak var userImage: UIImageView!
}
class UserListTableViewController: UITableViewController, HttpRequesterDelegate {
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
var users: [User] = []
var animator: UIDynamicAnimator?
var gravity: UIGravityBehavior?
var collision: UICollisionBehavior?
var url: String {
get{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return "\(appDelegate.baseUrl)/users"
}
}
var http: HttpRequester? {
get{
let appDelegate = UIApplication.shared.delegate as! AppDelegate
return appDelegate.http
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.gravity = UIGravityBehavior()
self.gravity?.magnitude = 0.2
self.collision = UICollisionBehavior()
self.collision?.translatesReferenceBoundsIntoBoundary = true
self.animator = UIDynamicAnimator(referenceView: self.view)
self.animator?.addBehavior(self.gravity!)
self.animator?.addBehavior(self.collision!)
//let obstacle = UIView(frame: CGRect(x: 50, y : self.view.bounds.height - 100, width: self.view.bounds.width, height: 10))
self.collision?.addBoundary(withIdentifier: "obstacle" as NSCopying, from: CGPoint(x:50, y:self.view.bounds.height - 100), to: CGPoint(x: self.view.bounds.width - 50, y: self.view.bounds.height - 100))
self.loadUsers()
}
func loadUsers () {
self.http?.delegate = self
self.http?.get(fromUrl: self.url)
}
func didReceiveData(data: Any) {
let dataArray = data as! [Dictionary<String, Any>]
self.users = dataArray.map(){User(withDict: $0)}
DispatchQueue.main.async {
self.tableView.reloadData()
}
self.activityIndicator.isHidden = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! UserTableViewCell
cell.userName?.text = self.users[indexPath.row].userName
cell.gender?.text = self.users[indexPath.row].gender
cell.age?.text = "\(self.users[indexPath.row].age ?? 0)"
if let url = URL(string: self.users[indexPath.row].image!){
DispatchQueue.global().async {
if let data = try? Data(contentsOf: url) {
DispatchQueue.main.async {
cell.userImage.image = UIImage(data: data)
}
}
}
}
self.gravity?.addItem(cell)
self.collision?.addItem(cell)
return cell
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | db3049ad241df3492e7cbe863a33ff4c | 31.261628 | 209 | 0.631105 | 4.954464 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Profile/Calculators/ProfileHeaderNamesSizeCalculator.swift | 1 | 1566 | ////
/// ProfileHeaderNamesSizeCalculator.swift
//
import PromiseKit
class ProfileHeaderNamesSizeCalculator: CellSizeCalculator {
override func process() {
guard
let user = cellItem.jsonable as? User
else {
assignCellHeight(all: 0)
return
}
let nameFont = StyledLabel.Style.large.fontFamily.font
let usernameFont = StyledLabel.Style.gray.fontFamily.font
let viewWidth = width - ProfileHeaderNamesCell.Size.outerMargins.sides
let maxSize = CGSize(width: viewWidth, height: CGFloat.greatestFiniteMagnitude)
let nameSize: CGSize
if user.name.isEmpty {
nameSize = .zero
}
else {
nameSize =
user.name.boundingRect(
with: maxSize,
options: [],
attributes: [
.font: nameFont,
],
context: nil
).size.integral
}
let usernameSize = user.atName.boundingRect(
with: maxSize,
options: [],
attributes: [
.font: usernameFont,
],
context: nil
).size.integral
let (height, _) = ProfileHeaderNamesCell.preferredHeight(
nameSize: nameSize,
usernameSize: usernameSize,
width: width
)
let totalHeight = height + ProfileHeaderNamesCell.Size.outerMargins.tops
assignCellHeight(all: totalHeight)
}
}
| mit | 6682fcad4da83e981b42f93d813dfabe | 26.473684 | 87 | 0.538314 | 5.18543 | false | false | false | false |
Feverup/braintree_ios | UnitTests/BTJSON_Tests.swift | 1 | 10389 | import XCTest
class BTJSON_Tests: XCTestCase {
func testEmptyJSON() {
let empty = BTJSON()
XCTAssertNotNil(empty)
XCTAssertTrue(empty.isObject)
XCTAssertNil(empty.asString())
XCTAssertNil(empty.asArray())
XCTAssertNil(empty.asNumber())
XCTAssertNil(empty.asURL())
XCTAssertNil(empty.asStringArray())
XCTAssertNil(empty.asError())
XCTAssertFalse(empty.isString)
XCTAssertFalse(empty.isNumber)
XCTAssertFalse(empty.isArray)
XCTAssertFalse(empty.isTrue)
XCTAssertFalse(empty.isFalse)
XCTAssertFalse(empty.isNull)
}
func testInitializationFromValue() {
let string = BTJSON(value: "")
XCTAssertTrue(string.isString)
let truth = BTJSON(value: true)
XCTAssertTrue(truth.isTrue)
let falsehood = BTJSON(value: false)
XCTAssertTrue(falsehood.isFalse)
let number = BTJSON(value: 42)
XCTAssertTrue(number.isNumber)
let ary = BTJSON(value: [1,2,3])
XCTAssertTrue(ary.isArray)
let obj = BTJSON(value: ["one": 1, "two": 2])
XCTAssertTrue(obj.isObject)
let null = BTJSON(value: NSNull())
XCTAssertTrue(null.isNull)
}
func testInitializationFromEmptyData() {
let emptyDataJSON = BTJSON(data: NSData())
XCTAssertTrue(emptyDataJSON.isError)
}
func testStringJSON() {
let JSON = "\"Hello, JSON!\"".dataUsingEncoding(NSUTF8StringEncoding)!
let string = BTJSON(data: JSON)
XCTAssertTrue(string.isString)
XCTAssertEqual(string.asString()!, "Hello, JSON!")
}
func testArrayJSON() {
let JSON = "[\"One\", \"Two\", \"Three\"]".dataUsingEncoding(NSUTF8StringEncoding)!
let array = BTJSON(data: JSON)
XCTAssertTrue(array.isArray)
XCTAssertEqual(array.asArray()!, ["One", "Two", "Three"])
}
func testArrayAccess() {
let JSON = "[\"One\", \"Two\", \"Three\"]".dataUsingEncoding(NSUTF8StringEncoding)!
let array = BTJSON(data: JSON)
XCTAssertTrue(array[0].isString)
XCTAssertEqual(array[0].asString()!, "One")
XCTAssertEqual(array[1].asString()!, "Two")
XCTAssertEqual(array[2].asString()!, "Three")
XCTAssertNil(array[3].asString())
XCTAssertFalse(array[3].isString)
XCTAssertNil(array["hello"].asString())
}
func testObjectAccess() {
let JSON = "{ \"key\": \"value\" }".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj["key"].asString()!, "value")
XCTAssertNil(obj["not present"].asString())
XCTAssertNil(obj[0].asString())
XCTAssertFalse(obj["not present"].isError as Bool)
XCTAssertTrue(obj[0].isError)
}
func testParsingError() {
let JSON = "INVALID JSON".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertTrue(obj.isError)
XCTAssertEqual((obj.asError()?.domain)!, NSCocoaErrorDomain)
}
func testMultipleErrorsTakesFirst() {
let JSON = "INVALID JSON".dataUsingEncoding(NSUTF8StringEncoding)!
let string = BTJSON(data: JSON)
let error = string[0]["key"][0]
XCTAssertTrue(error.isError as Bool)
XCTAssertEqual((error.asError()?.domain)!, NSCocoaErrorDomain)
}
func testNestedObjects() {
let JSON = "{ \"numbers\": [\"one\", \"two\", { \"tens\": 0, \"ones\": 1 } ], \"truthy\": true }".dataUsingEncoding(NSUTF8StringEncoding)!
let nested = BTJSON(data: JSON)
XCTAssertEqual(nested["numbers"][0].asString()!, "one")
XCTAssertEqual(nested["numbers"][1].asString()!, "two")
XCTAssertEqual(nested["numbers"][2]["tens"].asNumber()!, NSDecimalNumber.zero())
XCTAssertEqual(nested["numbers"][2]["ones"].asNumber()!, NSDecimalNumber.one())
XCTAssertTrue(nested["truthy"].isTrue as Bool)
}
func testTrueBoolInterpretation() {
let JSON = "true".dataUsingEncoding(NSUTF8StringEncoding)!
let truthy = BTJSON(data: JSON)
XCTAssertTrue(truthy.isTrue)
XCTAssertFalse(truthy.isFalse)
}
func testFalseBoolInterpretation() {
let JSON = "false".dataUsingEncoding(NSUTF8StringEncoding)!
let truthy = BTJSON(data: JSON)
XCTAssertFalse(truthy.isTrue)
XCTAssertTrue(truthy.isFalse)
}
func testAsURL() {
let JSON = "{ \"url\": \"http://example.com\" }".dataUsingEncoding(NSUTF8StringEncoding)!
let url = BTJSON(data: JSON)
XCTAssertEqual(url["url"].asURL()!, NSURL(string: "http://example.com")!)
}
func testAsURLForInvalidValue() {
let JSON = "{ \"url\": 42 }".dataUsingEncoding(NSUTF8StringEncoding)!
let url = BTJSON(data: JSON)
XCTAssertNil(url["url"].asURL())
}
func testAsStringArray() {
let JSON = "[\"one\", \"two\", \"three\"]".dataUsingEncoding(NSUTF8StringEncoding)!
let stringArray = BTJSON(data: JSON)
XCTAssertEqual(stringArray.asStringArray()!, ["one", "two", "three"])
}
func testAsStringArrayForInvalidValue() {
let JSON = "[1, 2, false]".dataUsingEncoding(NSUTF8StringEncoding)!
let stringArray = BTJSON(data: JSON)
XCTAssertNil(stringArray.asStringArray())
}
func testAsStringArrayForHeterogeneousValue() {
let JSON = "[\"string\", false]".dataUsingEncoding(NSUTF8StringEncoding)!
let stringArray = BTJSON(data: JSON)
XCTAssertNil(stringArray.asStringArray())
}
func testAsStringArrayForEmptyArray() {
let JSON = "[]".dataUsingEncoding(NSUTF8StringEncoding)!
let stringArray = BTJSON(data: JSON)
XCTAssertEqual(stringArray.asStringArray()!, [])
}
func testAsDictionary() {
let JSON = "{ \"key\": \"value\" }".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj.asDictionary()!, ["key":"value"] as NSDictionary)
}
func testAsDictionaryInvalidValue() {
let JSON = "[]".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertNil(obj.asDictionary())
}
func testAsIntegerOrZero() {
let cases = [
"1": 1,
"1.2": 1,
"1.5": 1,
"1.9": 1,
"-4": -4,
"0": 0,
"\"Hello\"": 0,
]
for (k,v) in cases {
let JSON = BTJSON(data: k.dataUsingEncoding(NSUTF8StringEncoding)!)
XCTAssertEqual(JSON.asIntegerOrZero(), v)
}
}
func testAsEnumOrDefault() {
let JSON = "\"enum one\"".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj.asEnum(["enum one" : 1], orDefault: 0), 1)
}
func testAsEnumOrDefaultWhenMappingNotPresentReturnsDefault() {
let JSON = "\"enum one\"".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj.asEnum(["enum two" : 2], orDefault: 1000), 1000)
}
func testAsEnumOrDefaultWhenMapValueIsNotNumberReturnsDefault() {
let JSON = "\"enum one\"".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj.asEnum(["enum one" : "one"], orDefault: 1000), 1000)
}
func testIsNull() {
let JSON = "null".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertTrue(obj.isNull);
}
func testIsObject() {
let JSON = "{}".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertTrue(obj.isObject);
}
func testIsObjectForNonObject() {
let JSON = "[]".dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertFalse(obj.isObject);
}
func testLargerMixedJSONWithEmoji() {
let JSON = ("{" +
"\"aString\": \"Hello, JSON 😍!\"," +
"\"anArray\": [1, 2, 3 ]," +
"\"aSetOfValues\": [\"a\", \"b\", \"c\"]," +
"\"aSetWithDuplicates\": [\"a\", \"a\", \"b\", \"b\" ]," +
"\"aLookupDictionary\": {" +
"\"foo\": { \"definition\": \"A meaningless word\"," +
"\"letterCount\": 3," +
"\"meaningful\": false }" +
"}," +
"\"aURL\": \"https://test.example.com:1234/path\"," +
"\"anInvalidURL\": \":™£¢://://://???!!!\"," +
"\"aTrue\": true," +
"\"aFalse\": false" +
"}").dataUsingEncoding(NSUTF8StringEncoding)!
let obj = BTJSON(data: JSON)
XCTAssertEqual(obj["aString"].asString(), "Hello, JSON 😍!")
XCTAssertNil(obj["notAString"].asString()) // nil for absent keys
XCTAssertNil(obj["anArray"].asString()) // nil for invalid values
XCTAssertEqual(obj["anArray"].asArray()!, [1, 2, 3])
XCTAssertNil(obj["notAnArray"].asArray()) // nil for absent keys
XCTAssertNil(obj["aString"].asArray()) // nil for invalid values
// sets can be parsed as arrays:
XCTAssertEqual(obj["aSetOfValues"].asArray()!, ["a", "b", "c"])
XCTAssertEqual(obj["aSetWithDuplicates"].asArray()!, ["a", "a", "b", "b"])
let dictionary = obj["aLookupDictionary"].asDictionary()!
let foo = dictionary["foo"]! as! Dictionary<String, AnyObject>
XCTAssertEqual((foo["definition"] as! String), "A meaningless word")
let letterCount = foo["letterCount"] as! NSNumber
XCTAssertEqual(letterCount, 3)
XCTAssertFalse(foo["meaningful"] as! Bool)
XCTAssertNil(obj["notADictionary"].asDictionary())
XCTAssertNil(obj["aString"].asDictionary())
XCTAssertEqual(obj["aURL"].asURL(), NSURL(string: "https://test.example.com:1234/path"))
XCTAssertNil(obj["notAURL"].asURL())
XCTAssertNil(obj["aString"].asURL())
XCTAssertNil(obj["anInvalidURL"].asURL()) // nil for invalid URLs
// nested resources:
let btJson = obj["aLookupDictionary"]
XCTAssertEqual(btJson["foo"]["definition"].asString(), "A meaningless word")
XCTAssert(btJson["aString"]["anything"].isError as Bool) // indicates error when value type is invalid
}
}
| mit | 30816f349f1042f83d4dee2f10ec0aa2 | 34.302721 | 146 | 0.600636 | 4.542232 | false | true | false | false |
tuffz/pi-weather-app | Carthage/Checkouts/realm-cocoa/Realm/Tests/Swift/SwiftDynamicTests.swift | 1 | 12747 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import XCTest
import Foundation
import Realm.Private
import Realm.Dynamic
#if swift(>=3.0)
class SwiftDynamicTests: RLMTestCase {
// Swift models
func testDynamicRealmExists() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(url: RLMTestRealmURL())
realm.beginWriteTransaction()
_ = SwiftDynamicObject.create(in: realm, withValue: ["column1", 1])
_ = SwiftDynamicObject.create(in: realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
let dyrealm = realm(withTestPathAndSchema: nil)
XCTAssertNotNil(dyrealm, "realm should not be nil")
// verify schema
let dynSchema = dyrealm.schema[SwiftDynamicObject.className()]
XCTAssertNotNil(dynSchema, "Should be able to get object schema dynamically")
XCTAssertEqual(dynSchema.properties.count, Int(2))
XCTAssertEqual(dynSchema.properties[0].name, "stringCol")
XCTAssertEqual(dynSchema.properties[1].type, RLMPropertyType.int)
// verify object type
let array = SwiftDynamicObject.allObjects(in: dyrealm)
XCTAssertEqual(array.count, UInt(2))
XCTAssertEqual(array.objectClassName, SwiftDynamicObject.className())
}
func testDynamicProperties() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(url: RLMTestRealmURL())
realm.beginWriteTransaction()
_ = SwiftDynamicObject.create(in: realm, withValue: ["column1", 1])
_ = SwiftDynamicObject.create(in: realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realm(withTestPathAndSchema: nil)
let array = dyrealm.allObjects("SwiftDynamicObject")
XCTAssertTrue(array[0]["intCol"] as! NSNumber == 1)
XCTAssertTrue(array[1]["stringCol"] as! String == "column2")
}
// Objective-C models
func testDynamicRealmExists_objc() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(url: RLMTestRealmURL())
realm.beginWriteTransaction()
_ = DynamicObject.create(in: realm, withValue: ["column1", 1])
_ = DynamicObject.create(in: realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
let dyrealm = realm(withTestPathAndSchema: nil)
XCTAssertNotNil(dyrealm, "realm should not be nil")
// verify schema
let dynSchema = dyrealm.schema[DynamicObject.className()]
XCTAssertNotNil(dynSchema, "Should be able to get object schema dynamically")
XCTAssertTrue(dynSchema.properties.count == 2)
XCTAssertTrue(dynSchema.properties[0].name == "stringCol")
XCTAssertTrue(dynSchema.properties[1].type == RLMPropertyType.int)
// verify object type
let array = DynamicObject.allObjects(in: dyrealm)
XCTAssertEqual(array.count, UInt(2))
XCTAssertEqual(array.objectClassName, DynamicObject.className())
}
func testDynamicProperties_objc() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(url: RLMTestRealmURL())
realm.beginWriteTransaction()
_ = DynamicObject.create(in: realm, withValue: ["column1", 1])
_ = DynamicObject.create(in: realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realm(withTestPathAndSchema: nil)
let array = dyrealm.allObjects("DynamicObject")
XCTAssertTrue(array[0]["intCol"] as! NSNumber == 1)
XCTAssertTrue(array[1]["stringCol"] as! String == "column2")
}
func testDynamicTypes_objc() {
let date = Date(timeIntervalSince1970: 100000)
let data = "a".data(using: String.Encoding.utf8)!
let obj1: [Any] = [true, 1, 1.1 as Float, 1.11, "string",
data, date, true, 11, NSNull()]
let obj = StringObject()
obj.stringCol = "string"
let data2 = "b".data(using: String.Encoding.utf8)!
let obj2: [Any] = [false, 2, 2.2 as Float, 2.22, "string2",
data2, date, false, 22, obj]
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = self.realmWithTestPath()
realm.beginWriteTransaction()
_ = AllTypesObject.create(in: realm, withValue: obj1)
_ = AllTypesObject.create(in: realm, withValue: obj2)
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realm(withTestPathAndSchema: nil)
let results = dyrealm.allObjects(AllTypesObject.className())
XCTAssertEqual(results.count, UInt(2))
let robj1 = results[0]
let robj2 = results[1]
let schema = dyrealm.schema[AllTypesObject.className()]
for idx in 0..<obj1.count - 1 {
let prop = schema.properties[idx]
XCTAssertTrue((obj1[idx] as AnyObject).isEqual(robj1[prop.name]))
XCTAssertTrue((obj2[idx] as AnyObject).isEqual(robj2[prop.name]))
}
// check sub object type
XCTAssertTrue(schema.properties[9].objectClassName! == "StringObject")
// check object equality
XCTAssertNil(robj1["objectCol"], "object should be nil")
XCTAssertTrue((robj2["objectCol"] as! RLMObject)["stringCol"] as! String == "string")
}
}
#else
class SwiftDynamicTests: RLMTestCase {
// Swift models
func testDynamicRealmExists() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(URL: RLMTestRealmURL())
realm.beginWriteTransaction()
SwiftDynamicObject.createInRealm(realm, withValue: ["column1", 1])
SwiftDynamicObject.createInRealm(realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
let dyrealm = realmWithTestPathAndSchema(nil)
XCTAssertNotNil(dyrealm, "realm should not be nil")
XCTAssertTrue(dyrealm.isKindOfClass(RLMRealm))
// verify schema
let dynSchema = dyrealm.schema[SwiftDynamicObject.className()]
XCTAssertNotNil(dynSchema, "Should be able to get object schema dynamically")
XCTAssertEqual(dynSchema.properties.count, Int(2))
XCTAssertEqual(dynSchema.properties[0].name, "stringCol")
XCTAssertEqual(dynSchema.properties[1].type, RLMPropertyType.Int)
// verify object type
let array = SwiftDynamicObject.allObjectsInRealm(dyrealm)
XCTAssertEqual(array.count, UInt(2))
XCTAssertEqual(array.objectClassName, SwiftDynamicObject.className())
}
func testDynamicProperties() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(URL: RLMTestRealmURL())
realm.beginWriteTransaction()
SwiftDynamicObject.createInRealm(realm, withValue: ["column1", 1])
SwiftDynamicObject.createInRealm(realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realmWithTestPathAndSchema(nil)
let array = dyrealm.allObjects("SwiftDynamicObject")
XCTAssertTrue(array[0]["intCol"] as! NSNumber == 1)
XCTAssertTrue(array[1]["stringCol"] as! String == "column2")
}
// Objective-C models
func testDynamicRealmExists_objc() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(URL: RLMTestRealmURL())
realm.beginWriteTransaction()
DynamicObject.createInRealm(realm, withValue: ["column1", 1])
DynamicObject.createInRealm(realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
let dyrealm = realmWithTestPathAndSchema(nil)
XCTAssertNotNil(dyrealm, "realm should not be nil")
// verify schema
let dynSchema = dyrealm.schema[DynamicObject.className()]
XCTAssertNotNil(dynSchema, "Should be able to get object schema dynamically")
XCTAssertTrue(dynSchema.properties.count == 2)
XCTAssertTrue(dynSchema.properties[0].name == "stringCol")
XCTAssertTrue(dynSchema.properties[1].type == RLMPropertyType.Int)
// verify object type
let array = DynamicObject.allObjectsInRealm(dyrealm)
XCTAssertEqual(array.count, UInt(2))
XCTAssertEqual(array.objectClassName, DynamicObject.className())
}
func testDynamicProperties_objc() {
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = RLMRealm(URL: RLMTestRealmURL())
realm.beginWriteTransaction()
DynamicObject.createInRealm(realm, withValue: ["column1", 1])
DynamicObject.createInRealm(realm, withValue: ["column2", 2])
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realmWithTestPathAndSchema(nil)
let array = dyrealm.allObjects("DynamicObject")
XCTAssertTrue(array[0]["intCol"] as! NSNumber == 1)
XCTAssertTrue(array[1]["stringCol"] as! String == "column2")
}
// these helper functions make the below test not take five minutes to compile
// I suspect a type inference bug
func Ni(x: Int) -> AnyObject {
return NSNumber(integer: x)
}
func Nb(x: Bool) -> AnyObject {
return NSNumber(bool: x)
}
func Nd(x: Double) -> AnyObject {
return NSNumber(double: x)
}
func Nf(x: Float) -> AnyObject {
return NSNumber(float: x)
}
func testDynamicTypes_objc() {
let date = NSDate(timeIntervalSince1970: 100000)
let data = "a".dataUsingEncoding(NSUTF8StringEncoding)!
let obj1 = [Nb(true), Ni(1), Nf(1.1), Nd(1.11), "string" as NSString,
data as AnyObject, date, Nb(true), Ni(11), NSNull()] as NSArray
let obj = StringObject()
obj.stringCol = "string"
let data2 = "b".dataUsingEncoding(NSUTF8StringEncoding)!
let obj2 = [Nb(false), Ni(2), Nf(2.2), Nd(2.22), "string2" as NSString,
data2 as AnyObject, date, Nb(false), Ni(22), obj] as NSArray
autoreleasepool {
// open realm in autoreleasepool to create tables and then dispose
let realm = self.realmWithTestPath()
realm.beginWriteTransaction()
AllTypesObject.createInRealm(realm, withValue: obj1)
AllTypesObject.createInRealm(realm, withValue: obj2)
try! realm.commitWriteTransaction()
}
// verify properties
let dyrealm = realmWithTestPathAndSchema(nil)
let results = dyrealm.allObjects(AllTypesObject.className())
XCTAssertEqual(results.count, UInt(2))
let robj1 = results[0]
let robj2 = results[1]
let schema = dyrealm.schema[AllTypesObject.className()]
for idx in 0..<obj1.count - 1 {
let prop = schema.properties[idx]
XCTAssertTrue(obj1[idx].isEqual(robj1[prop.name]))
XCTAssertTrue(obj2[idx].isEqual(robj2[prop.name]))
}
// check sub object type
XCTAssertTrue(schema.properties[9].objectClassName! == "StringObject")
// check object equality
XCTAssertNil(robj1["objectCol"], "object should be nil")
XCTAssertTrue((robj2["objectCol"] as! RLMObject)["stringCol"] as! String == "string")
}
}
#endif
| mit | 8d7d6286a0046d1893149c6ae72387c7 | 38.71028 | 93 | 0.634188 | 4.792105 | false | true | false | false |
apple/swift | test/PrintAsObjC/blocks.swift | 7 | 7436 | // Please keep this file in alphabetical order!
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-module -o %t %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -parse-as-library %t/blocks.swiftmodule -typecheck -emit-objc-header-path %t/blocks.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/blocks.h
// RUN: %check-in-clang %t/blocks.h
// REQUIRES: objc_interop
import ObjectiveC
typealias MyInt = Int
typealias MyBlockWithEscapingParam = (@escaping () -> ()) -> Int
typealias MyBlockWithNoescapeParam = (() -> ()) -> Int
// Please see related tests in PrintAsObjC/imported-block-typedefs.swift.
// CHECK-LABEL: @interface Callbacks
@objc class Callbacks {
// CHECK-NEXT: - (void (^ _Nonnull)(void))voidBlocks:(void (^ _Nonnull)(void))input SWIFT_WARN_UNUSED_RESULT;
@objc func voidBlocks(_ input: @escaping () -> ()) -> () -> () {
return input
}
// CHECK-NEXT: - (void)manyArguments:(void (^ _Nonnull)(float, float, double, double))input;
@objc func manyArguments(_ input: @escaping (Float, Float, Double, Double) -> ()) {}
// CHECK-NEXT: - (void)blockTakesBlock:(void (^ _Nonnull)(SWIFT_NOESCAPE void (^ _Nonnull)(void)))input;
@objc func blockTakesBlock(_ input: @escaping (() -> ()) -> ()) {}
// CHECK-NEXT: - (void)blockReturnsBlock:(void (^ _Nonnull (^ _Nonnull)(void))(void))input;
@objc func blockReturnsBlock(_ input: @escaping () -> () -> ()) {}
// CHECK-NEXT: - (void)blockTakesAndReturnsBlock:(SWIFT_NOESCAPE uint8_t (^ _Nonnull (^ _Nonnull)(SWIFT_NOESCAPE uint16_t (^ _Nonnull)(int16_t)))(int8_t))input;
@objc func blockTakesAndReturnsBlock(_ input:
((Int16) -> (UInt16)) ->
((Int8) -> (UInt8))) {}
// CHECK-NEXT: - (void)blockTakesTwoBlocksAndReturnsBlock:(SWIFT_NOESCAPE uint8_t (^ _Nonnull (^ _Nonnull)(SWIFT_NOESCAPE uint16_t (^ _Nonnull)(int16_t), SWIFT_NOESCAPE uint32_t (^ _Nonnull)(int32_t)))(int8_t))input;
@objc func blockTakesTwoBlocksAndReturnsBlock(_ input:
((Int16) -> (UInt16),
(Int32) -> (UInt32)) ->
((Int8) -> (UInt8))) {}
// CHECK-NEXT: - (void (^ _Nullable)(NSObject * _Nonnull))returnsBlockWithInput SWIFT_WARN_UNUSED_RESULT;
@objc func returnsBlockWithInput() -> ((NSObject) -> ())? {
return nil
}
// CHECK-NEXT: - (void (^ _Nullable)(NSObject * _Nonnull))returnsBlockWithParenthesizedInput SWIFT_WARN_UNUSED_RESULT;
@objc func returnsBlockWithParenthesizedInput() -> ((NSObject) -> ())? {
return nil
}
// CHECK-NEXT: - (void (^ _Nullable)(NSObject * _Nonnull, NSObject * _Nonnull))returnsBlockWithTwoInputs SWIFT_WARN_UNUSED_RESULT;
@objc func returnsBlockWithTwoInputs() -> ((NSObject, NSObject) -> ())? {
return nil
}
// CHECK-NEXT: - (void)blockWithSimpleTypealias:(NSInteger (^ _Nonnull)(NSInteger))input;
@objc func blockWithSimpleTypealias(_ input: @escaping (MyInt) -> MyInt) {}
// CHECK-NEXT: - (void)namedArguments:(void (^ _Nonnull)(float, float, double, double))input;
@objc func namedArguments(_ input: @escaping (_ f1: Float, _ f2: Float, _ d1: Double, _ d2: Double) -> ()) {}
// CHECK-NEXT: - (void)blockTakesNamedBlock:(void (^ _Nonnull)(SWIFT_NOESCAPE void (^ _Nonnull)(void)))input;
@objc func blockTakesNamedBlock(_ input: @escaping (_ block: () -> ()) -> ()) {}
// CHECK-NEXT: - (void (^ _Nullable)(NSObject * _Nonnull))returnsBlockWithNamedInput SWIFT_WARN_UNUSED_RESULT;
@objc func returnsBlockWithNamedInput() -> ((_ object: NSObject) -> ())? {
return nil
}
// CHECK-NEXT: - (void)blockWithKeyword:(SWIFT_NOESCAPE NSInteger (^ _Nonnull)(NSInteger))_Nullable_;
@objc func blockWithKeyword(_ _Nullable: (_ `class`: Int) -> Int) {}
// CHECK-NEXT: - (NSInteger (* _Nonnull)(NSInteger))functionPointers:(NSInteger (* _Nonnull)(NSInteger))input SWIFT_WARN_UNUSED_RESULT;
@objc func functionPointers(_ input: @escaping @convention(c) (Int) -> Int)
-> @convention(c) (Int) -> Int {
return input
}
// CHECK-NEXT: - (void)blockWithBlockTypealias:(SWIFT_NOESCAPE NSInteger (^ _Nonnull)(void (^ _Nonnull)(void)))block;
@objc func blockWithBlockTypealias(_ block: MyBlockWithEscapingParam) {}
// CHECK-NEXT: - (void)blockWithBlockTypealias2:(NSInteger (^ _Nonnull)(void (^ _Nonnull)(void)))block;
@objc func blockWithBlockTypealias2(_ block: @escaping MyBlockWithEscapingParam) {}
// CHECK-NEXT: - (void)blockWithBlockTypealias3:(SWIFT_NOESCAPE NSInteger (^ _Nonnull)(SWIFT_NOESCAPE void (^ _Nonnull)(void)))block;
@objc func blockWithBlockTypealias3(_ block: MyBlockWithNoescapeParam) {}
// CHECK-NEXT: - (void)blockWithBlockTypealias4:(NSInteger (^ _Nonnull)(SWIFT_NOESCAPE void (^ _Nonnull)(void)))block;
@objc func blockWithBlockTypealias4(_ block: @escaping MyBlockWithNoescapeParam) {}
// CHECK-NEXT: - (void)functionPointerTakesAndReturnsFunctionPointer:(NSInteger (* _Nonnull (^ _Nonnull (* _Nonnull)(NSInteger))(NSInteger))(NSInteger))input;
@objc func functionPointerTakesAndReturnsFunctionPointer(
_ input: @escaping @convention(c) (Int) -> (Int)
-> @convention(c) (Int) -> Int
) {
}
// CHECK-NEXT: - (void (* _Nonnull)(NSInteger (* _Nonnull)(NSInteger, NSInteger)))returnsFunctionPointerThatTakesFunctionPointer SWIFT_WARN_UNUSED_RESULT;
@objc func returnsFunctionPointerThatTakesFunctionPointer() ->
@convention(c) (_ comparator: @convention(c) (_ x: Int, _ y: Int) -> Int) -> Void {
fatalError()
}
// CHECK-NEXT: - (NSInteger (* _Nonnull)(NSInteger))functionPointersWithName:(NSInteger (* _Nonnull)(NSInteger))input SWIFT_WARN_UNUSED_RESULT;
@objc func functionPointersWithName(_ input: @escaping @convention(c) (_ value: Int) -> Int)
-> @convention(c) (_ result: Int) -> Int {
return input
}
// CHECK-NEXT: - (void)blockWithConsumingArgument:(void (^ _Nonnull)(SWIFT_RELEASES_ARGUMENT NSObject * _Nonnull))block;
@objc func blockWithConsumingArgument(_ block: @escaping (__owned NSObject) -> ()) {}
// CHECK-NEXT: @property (nonatomic, copy) NSInteger (^ _Nullable savedBlock)(NSInteger);
@objc var savedBlock: ((Int) -> Int)?
// CHECK-NEXT: @property (nonatomic, copy) NSInteger (^ _Nullable savedBlockWithName)(NSInteger);
@objc var savedBlockWithName: ((_ x: Int) -> Int)?
// CHECK-NEXT: @property (nonatomic) NSInteger (* _Nonnull savedFunctionPointer)(NSInteger);
@objc var savedFunctionPointer: @convention(c) (Int) -> Int = { $0 }
// CHECK-NEXT: @property (nonatomic) NSInteger (* _Nullable savedFunctionPointer2)(NSInteger);
@objc var savedFunctionPointer2: (@convention(c) (Int) -> Int)? = { $0 }
// CHECK-NEXT: @property (nonatomic) NSInteger (* _Nonnull savedFunctionPointerWithName)(NSInteger);
@objc var savedFunctionPointerWithName: @convention(c) (_ x: Int) -> Int = { $0 }
// The following uses a clang keyword as the name.
// CHECK-NEXT: @property (nonatomic, copy, getter=this, setter=setThis:) NSInteger (^ _Nonnull this_)(NSInteger);
@objc var this: (_ block: Int) -> Int = { $0 }
// CHECK-NEXT: @property (nonatomic, getter=class, setter=setClass:) NSInteger (* _Nonnull class_)(NSInteger);
@objc var `class`: @convention(c) (_ function: Int) -> Int = { $0 }
// CHECK-NEXT: init
@objc init() {}
}
// CHECK-NEXT: @end
| apache-2.0 | 47066d732f19af419724d0040f396f74 | 49.931507 | 234 | 0.669984 | 3.751766 | false | false | false | false |
auth0/Lock.swift | Lock/Validators.swift | 1 | 5674 | // Validators.swift
//
// Copyright (c) 2016 Auth0 (http://auth0.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 Foundation
protocol InputValidator {
func validate(_ value: String?) -> Error?
}
public class PhoneValidator: InputValidator {
let predicate: NSPredicate
public init() {
let regex = "^[0-9]{8,15}$"
self.predicate = NSPredicate(format: "SELF MATCHES %@", regex)
}
func validate(_ value: String?) -> Error? {
guard let email = value?.trimmed, !email.isEmpty else { return InputValidationError.mustNotBeEmpty }
guard self.predicate.evaluate(with: email) else { return InputValidationError.notAPhoneNumber }
return nil
}
}
public class OneTimePasswordValidator: InputValidator {
func validate(_ value: String?) -> Error? {
guard let value = value?.trimmed, !value.isEmpty else { return InputValidationError.mustNotBeEmpty }
#if swift(>=3.2)
guard value.count > 3, value.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else { return InputValidationError.notAOneTimePassword }
#else
guard value.characters.count > 3, value.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil else { return InputValidationError.notAOneTimePassword }
#endif
return nil
}
}
public class NonEmptyValidator: InputValidator {
func validate(_ value: String?) -> Error? {
guard let value = value?.trimmed, !value.isEmpty else { return InputValidationError.mustNotBeEmpty }
return nil
}
}
public class UsernameValidator: InputValidator {
let invalidSet: CharacterSet?
let range: CountableClosedRange<Int>
let emailValidator = EmailValidator()
var min: Int { return self.range.lowerBound }
var max: Int { return self.range.upperBound }
public init() {
self.range = 1...Int.max
self.invalidSet = nil
}
public init(withLength range: CountableClosedRange<Int>, characterSet: CharacterSet) {
self.invalidSet = characterSet
self.range = range
}
func validate(_ value: String?) -> Error? {
guard let username = value?.trimmed, !username.isEmpty else { return InputValidationError.mustNotBeEmpty }
#if swift(>=3.2)
guard self.range ~= username.count else { return self.invalidSet == nil ? InputValidationError.mustNotBeEmpty : InputValidationError.notAUsername }
#else
guard self.range ~= username.characters.count else { return self.invalidSet == nil ? InputValidationError.mustNotBeEmpty : InputValidationError.notAUsername }
#endif
guard let characterSet = self.invalidSet else { return nil }
guard username.rangeOfCharacter(from: characterSet) == nil else { return InputValidationError.notAUsername }
guard self.emailValidator.validate(username) != nil else { return InputValidationError.notAUsername }
return nil
}
public static var auth0: CharacterSet {
let set = NSMutableCharacterSet()
set.formUnion(with: CharacterSet.alphanumerics)
set.addCharacters(in: "_.-!#$'^`~@+")
return set.inverted
}
}
public class EmailValidator: InputValidator {
let predicate: NSPredicate
public init() {
let regex = "[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?"
self.predicate = NSPredicate(format: "SELF MATCHES %@", regex)
}
func validate(_ value: String?) -> Error? {
guard let email = value?.trimmed, !email.isEmpty else { return InputValidationError.mustNotBeEmpty }
guard self.predicate.evaluate(with: email) else { return InputValidationError.notAnEmailAddress }
return nil
}
}
protocol PasswordPolicyValidatorDelegate: AnyObject {
func update(withRules rules: [RuleResult])
}
public class PasswordPolicyValidator: InputValidator {
let policy: PasswordPolicy
weak var delegate: PasswordPolicyValidatorDelegate?
public init(policy: PasswordPolicy) {
self.policy = policy
}
func validate(_ value: String?) -> Error? {
let result = self.policy.on(value)
self.delegate?.update(withRules: result)
let valid = result.allSatisfy { $0.valid }
guard !valid else { return nil }
return InputValidationError.passwordPolicyViolation(result: result.filter { !$0.valid })
}
}
private extension String {
var trimmed: String {
return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
}
| mit | cc77d074cb35428eec3076e90f8a4d56 | 38.678322 | 181 | 0.688756 | 4.39845 | false | false | false | false |
wawandco/away | Pod/Classes/Away.swift | 1 | 2359 | import Foundation
import CoreLocation
public class Away {
public class func buildLocation(distanceInMeters: Double, from: CLLocation, bearing: Double=90)-> CLLocation{
var distanceInKm = (distanceInMeters / 1000.0)
distanceInKm = distanceInKm / 6371.0
let bearingRad = bearing.toRadians // Degrees to move to
let baseLatitude = from.coordinate.latitude.toRadians
let baseLongitude = from.coordinate.longitude.toRadians
var resultLatitude = determineNewLatitude(baseLatitude, distanceInKm, bearingRad)
var resultLongitude = determineNewLongitude(baseLatitude, baseLongitude, resultLatitude, bearingRad, distanceInKm)
resultLatitude = resultLatitude.toDegrees
resultLongitude = resultLongitude.toDegrees
let newLocation = CLLocation(latitude: resultLatitude, longitude: resultLongitude)
return newLocation
}
public class func buildTrip(distanceInMeters: Double, from: CLLocation, locations: Int=3)-> [CLLocation]{
if locations < 2 {
NSException(name:"InvalidArgument", reason:"Locations number should be greater than 1.", userInfo:nil).raise()
}
var result : [CLLocation] = [from]
let distanceBetweenLocations = distanceInMeters / Double(locations-1)
for _ in (1...locations-1) {
let location = buildLocation(distanceBetweenLocations, from: result.last!)
result.append(location)
}
return result
}
class func determineNewLatitude( baseLatitude : Double,_ distanceInKm : Double,_ bearingRad: Double) -> Double {
return asin(sin(baseLatitude) * cos(distanceInKm) + cos(baseLatitude) * sin(distanceInKm) * cos(bearingRad))
}
class func determineNewLongitude( baseLatitude: Double,_ baseLongitude : Double, _ resultLatitude: Double, _ bearingRad: Double,_ distanceInKm: Double )-> Double {
return baseLongitude + atan2( sin(bearingRad) * sin(distanceInKm) * cos(baseLatitude),cos(distanceInKm) - sin(baseLatitude) * sin(resultLatitude));
}
}
public extension Double {
var toRadians : Double {
return self * M_PI / 180.0
}
var toDegrees : Double {
return self * 180.0 / M_PI
}
var miles : Double {
return self * 1600
}
var Km: Double {
return self * 1000
}
}
| mit | 6e5365e3c62c469f181ae9c4f641762e | 36.444444 | 167 | 0.679949 | 4.442561 | false | false | false | false |
antigp/Alamofire | Tests/RedirectHandlerTests.swift | 1 | 8452 | //
// RedirectHandlerTests.swift
//
// Copyright (c) 2019 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
// Disabled due to HTTPBin issue: https://github.com/postmanlabs/httpbin/issues/617
// final class RedirectHandlerTestCase: BaseTestCase {
// // MARK: - Properties
//
// private var redirectURLString: String { URL.makeHTTPBinURL().absoluteString }
// private var urlString: String { "\(String.httpBinURLString)/redirect-to?url=\(redirectURLString)" }
//
// // MARK: - Tests - Per Request
//
// func testThatRequestRedirectHandlerCanFollowRedirects() {
// // Given
// let session = Session()
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).redirect(using: Redirector.follow).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNotNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString)
// XCTAssertEqual(response?.response?.statusCode, 200)
// }
//
// func testThatRequestRedirectHandlerCanNotFollowRedirects() {
// // Given
// let session = Session()
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should NOT redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).redirect(using: Redirector.doNotFollow).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, urlString)
// XCTAssertEqual(response?.response?.statusCode, 302)
// }
//
// func testThatRequestRedirectHandlerCanModifyRedirects() {
// // Given
// let session = Session()
// let redirectURLString = URL.makeHTTPBinURL().absoluteString
// let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!)
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)")
//
// // When
// let redirector = Redirector(behavior: .modify { _, _, _ in redirectURLRequest })
//
// session.request(urlString).redirect(using: redirector).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNotNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString)
// XCTAssertEqual(response?.response?.statusCode, 200)
// }
//
// // MARK: - Tests - Per Session
//
// func testThatSessionRedirectHandlerCanFollowRedirects() {
// // Given
// let session = Session(redirectHandler: Redirector.follow)
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNotNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString)
// XCTAssertEqual(response?.response?.statusCode, 200)
// }
//
// func testThatSessionRedirectHandlerCanNotFollowRedirects() {
// // Given
// let session = Session(redirectHandler: Redirector.doNotFollow)
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should NOT redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, urlString)
// XCTAssertEqual(response?.response?.statusCode, 302)
// }
//
// func testThatSessionRedirectHandlerCanModifyRedirects() {
// // Given
// let redirectURLString = URL.makeHTTPBinURL().absoluteString
// let redirectURLRequest = URLRequest(url: URL(string: redirectURLString)!)
//
// let redirector = Redirector(behavior: .modify { _, _, _ in redirectURLRequest })
// let session = Session(redirectHandler: redirector)
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNotNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString)
// XCTAssertEqual(response?.response?.statusCode, 200)
// }
//
// // MARK: - Tests - Per Request Prioritization
//
// func testThatRequestRedirectHandlerIsPrioritizedOverSessionRedirectHandler() {
// // Given
// let session = Session(redirectHandler: Redirector.doNotFollow)
//
// var response: DataResponse<Data?, AFError>?
// let expectation = self.expectation(description: "Request should redirect to \(redirectURLString)")
//
// // When
// session.request(urlString).redirect(using: Redirector.follow).response { resp in
// response = resp
// expectation.fulfill()
// }
//
// waitForExpectations(timeout: timeout)
//
// // Then
// XCTAssertNotNil(response?.request)
// XCTAssertNotNil(response?.response)
// XCTAssertNotNil(response?.data)
// XCTAssertNil(response?.error)
//
// XCTAssertEqual(response?.response?.url?.absoluteString, redirectURLString)
// XCTAssertEqual(response?.response?.statusCode, 200)
// }
// }
| mit | 569c99c84c061dd63b7e0be786f64512 | 36.732143 | 112 | 0.64955 | 4.422815 | false | true | false | false |
apple/swift-lldb | packages/Python/lldbsuite/test/lang/swift/zero_size_generic_self/main.swift | 2 | 1083 | // main.swift
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
func use<T>(_ t : T) {}
struct GenericSelf<T> {
init(x: T) {
use(x) //%self.expect('frame variable -d run -- self', substrs=['GenericSelf<String>'])
}
}
// More complex example with protocol extensions.
protocol MyKey {}
extension Int : MyKey {}
protocol MyProtocol {
associatedtype Key : MyKey
}
struct MyStruct<S : MyKey> : MyProtocol {
typealias Key = S
}
extension MyProtocol {
func decode() {
use(self) //%self.expect('frame variable -d run -- self', substrs=['(a.MyStruct<Int>)', 'self', '=', '{}'])
return
}
}
// Run.
GenericSelf(x: "hello world")
let s = MyStruct<Int>()
s.decode()
| apache-2.0 | a3c252aabc2279389f8c33d4e3e6aefd | 25.414634 | 115 | 0.613112 | 3.773519 | false | false | false | false |
wireapp/wire-ios-sync-engine | Tests/Source/Integration/ConversationTests+MessageTimer.swift | 1 | 5516 | ////
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
class ConversationMessageTimerTests: IntegrationTest {
override func setUp() {
super.setUp()
createSelfUserAndConversation()
createExtraUsersAndConversations()
createTeamAndConversations()
}
private func responsePayload(for conversation: ZMConversation, timeout: MessageDestructionTimeoutValue) -> ZMTransportData {
var payload: [String: Any] = [
"from": user1.identifier,
"conversation": conversation.remoteIdentifier!.transportString(),
"time": NSDate().transportString(),
"type": "conversation.message-timer-update"
]
switch timeout {
case .none:
payload["data"] = ["message_timer": NSNull()]
default:
let timeoutInMiliseconds = timeout.rawValue * 1000
payload["data"] = ["message_timer": Int(timeoutInMiliseconds)]
}
return payload as ZMTransportData
}
func testThatItUpdatesTheDestructionTimerOneDay() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
XCTAssertNil(sut.activeMessageDestructionTimeoutValue)
// when
setGlobalTimeout(for: sut, timeout: .oneDay)
// then
XCTAssertEqual(sut.activeMessageDestructionTimeoutValue, .oneDay)
XCTAssertEqual(sut.activeMessageDestructionTimeoutType, .groupConversation)
}
func testThatItRemovesTheDestructionTimer() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
// given
userSession?.enqueue {
sut.setMessageDestructionTimeoutValue(.oneDay, for: .groupConversation)
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
XCTAssertNotNil(sut.activeMessageDestructionTimeoutValue)
setGlobalTimeout(for: sut, timeout: .none)
// then
guard let request = mockTransportSession.receivedRequests().first else {
XCTFail()
return
}
XCTAssertNotNil(request.payload?.asDictionary()?["message_timer"] as? NSNull)
XCTAssertNil(sut.activeMessageDestructionTimeoutValue)
}
func testThatItCanSetASyncedTimerWithExistingLocalOneAndFallsBackToTheLocalAfterRemovingSyncedTimer() {
// given
XCTAssert(login())
let sut = conversation(for: groupConversation)!
userSession?.enqueue {
sut.setMessageDestructionTimeoutValue(.oneDay, for: .selfUser)
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1))
XCTAssertEqual(sut.activeMessageDestructionTimeoutValue, .oneDay)
XCTAssertEqual(sut.activeMessageDestructionTimeoutType, .selfUser)
// when
setGlobalTimeout(for: sut, timeout: .tenSeconds)
// then
XCTAssertEqual(sut.activeMessageDestructionTimeoutValue, .tenSeconds)
XCTAssertEqual(sut.activeMessageDestructionTimeoutType, .groupConversation)
// when
setGlobalTimeout(for: sut, timeout: .none)
// then
XCTAssertEqual(sut.activeMessageDestructionTimeoutValue, .oneDay)
XCTAssertEqual(sut.activeMessageDestructionTimeoutType, .selfUser)
}
// MARK: - Helper
private func setGlobalTimeout(
for conversation: ZMConversation,
timeout: MessageDestructionTimeoutValue,
file: StaticString = #file,
line: UInt = #line
) {
mockTransportSession.resetReceivedRequests()
let identifier = conversation.remoteIdentifier!.transportString()
mockTransportSession.responseGeneratorBlock = { request in
guard request.path == "/conversations/\(identifier)/message-timer" else { return nil }
return ZMTransportResponse(payload: self.responsePayload(for: conversation, timeout: timeout), httpStatus: 200, transportSessionError: nil, apiVersion: APIVersion.v0.rawValue)
}
// when
conversation.setMessageDestructionTimeout(timeout, in: userSession!) { result in
switch result {
case .success: break
case .failure(let error): XCTFail("failed to update timeout \(error)", file: file, line: line)
}
}
XCTAssert(waitForAllGroupsToBeEmpty(withTimeout: 0.1), file: file, line: line)
// then
XCTAssertEqual(mockTransportSession.receivedRequests().count, 1, "wrong request count", file: file, line: line)
guard let request = mockTransportSession.receivedRequests().first else { return }
XCTAssertEqual(request.path, "/conversations/\(identifier)/message-timer", "wrong path \(request.path)", file: file, line: line)
XCTAssertEqual(request.method, .methodPUT, "wrong method", file: file, line: line)
}
}
| gpl-3.0 | bc319e0d871ea2f7969d9d872cf9c966 | 36.780822 | 187 | 0.67694 | 5.051282 | false | false | false | false |
Tantalum73/GradientView | GradientView.swift | 1 | 3275 | //
// GradientView.swift
// ClubNews
//
// Created by Andreas Neusüß on 31.03.15.
// Copyright (c) 2015 Anerma. All rights reserved.
//
import UIKit
/**
A gradient to lay behind any view that will also be rendered in Interface Builder.
*/
@IBDesignable
final class GradientView: UIView {
/**
One of the two colors of the gradient
*/
@IBInspectable
var startColor : UIColor = UIColor.whiteColor() {
didSet {
updateTheView()
}
}
/**
One of the two colors of the gradient
*/
@IBInspectable
var endColor : UIColor = UIColor.orangeColor() {
didSet {
updateTheView()
}
}
/**
Corner radius of the gradient. 0 as default, may be unimportant if the superview has a corner radius and clipsToBounds.
*/
@IBInspectable
var cornerRadius : CGFloat = 0.0 {
didSet {
updateTheView()
}
}
/**
X value of start coordinate. Between 0 and 1.
Will construct a CGPoint together with the Y variable.
*/
@IBInspectable
var startX : CGFloat = 0.5 {
didSet {
updateTheView()
}
}
/**
Y value of start coordinate. Between 0 and 1.
Will construct a CGPoint together with the X variable.
*/
@IBInspectable
var startY : CGFloat = 0.0 {
didSet {
updateTheView()
}
}
/**
X value of end coordinate. Between 0 and 1.
Will construct a CGPoint together with the Y variable.
*/
@IBInspectable
var endX : CGFloat = 0.5 {
didSet {
updateTheView()
}
}
/**
Y value of end coordinate. Between 0 and 1.
Will construct a CGPoint together with the X variable.
*/
@IBInspectable
var endY : CGFloat = 1.0 {
didSet {
updateTheView()
}
}
//MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
setUp()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setUp()
}
//MARK: - Updating the View
///The private gradient layer.
private var gradientLayer = CAGradientLayer()
///Ensures that the view will have its desired (and in IB specified) bounds.
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer.frame = bounds
}
private func setUp() {
layer.insertSublayer(gradientLayer, atIndex: 0)
updateTheView()
}
///Applies the given attributes to the view.
func updateTheView() {
let colors = [startColor.CGColor, endColor.CGColor]
gradientLayer.colors = colors
layer.cornerRadius = cornerRadius
clipsToBounds = true
gradientLayer.startPoint = CGPoint(x: startX, y: startY)
gradientLayer.endPoint = CGPoint(x: endX, y: endY)
// if gradientLayer != nil {
self.setNeedsDisplay()
// }
}
}
| mit | 4b3c859860a9cda4cc8691081c4005e2 | 22.546763 | 123 | 0.571036 | 4.689112 | false | false | false | false |
grafiti-io/SwiftCharts | Examples/Examples/BarsPlusMinusAndLinesExample.swift | 1 | 7533 | //
// BarsPlusMinusAndLinesExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class BarsPlusMinusAndLinesExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let barsData: [(title: String, min: Double, max: Double)] = [
("A", -65, 40),
("B", -30, 50),
("C", -40, 35),
("D", -50, 40),
("E", -60, 30),
("F", -35, 47),
("G", -30, 60),
("H", -46, 48)
]
let lineData: [(title: String, val: Double)] = [
("A", -10),
("B", 20),
("C", -20),
("D", 10),
("E", -20),
("F", 23),
("G", 10),
("H", 45)
]
let alpha: CGFloat = 0.5
let posColor = UIColor.green.withAlphaComponent(alpha)
let negColor = UIColor.red.withAlphaComponent(alpha)
let zero = ChartAxisValueDouble(0)
let bars: [ChartBarModel] = barsData.enumerated().flatMap {index, tuple in
[
ChartBarModel(constant: ChartAxisValueDouble(index), axisValue1: zero, axisValue2: ChartAxisValueDouble(tuple.min), bgColor: negColor),
ChartBarModel(constant: ChartAxisValueDouble(index), axisValue1: zero, axisValue2: ChartAxisValueDouble(tuple.max), bgColor: posColor)
]
}
let yValues = stride(from: -80, through: 80, by: 20).map {ChartAxisValueDouble(Double($0), labelSettings: labelSettings)}
let xValues =
[ChartAxisValueString(order: -1)] +
barsData.enumerated().map {index, tuple in ChartAxisValueString(tuple.0, order: index, labelSettings: labelSettings)} +
[ChartAxisValueString(order: barsData.count)]
let xGenerator = ChartAxisGeneratorMultiplier(1)
let yGenerator = ChartAxisGeneratorMultiplier(20)
let labelsGenerator = ChartAxisLabelsGeneratorFunc {scalar in
return ChartAxisLabel(text: "\(scalar)", settings: labelSettings)
}
let xModel = ChartAxisModel(firstModelValue: -1, lastModelValue: Double(barsData.count), axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings)], axisValuesGenerator: xGenerator, labelsGenerator: labelsGenerator)
let yModel = ChartAxisModel(firstModelValue: -80, lastModelValue: 80, axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical())], axisValuesGenerator: yGenerator, labelsGenerator: labelsGenerator)
let chartFrame = ExamplesDefaults.chartFrame(view.bounds)
let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxisLayer, yAxisLayer, innerFrame) = (coordsSpace.xAxisLayer, coordsSpace.yAxisLayer, coordsSpace.chartInnerFrame)
let barViewSettings = ChartBarViewSettings(animDuration: 0.5)
let barsLayer = ChartBarsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, bars: bars, horizontal: false, barWidth: Env.iPad ? 40 : 25, settings: barViewSettings)
// labels layer
// create chartpoints for the top and bottom of the bars, where we will show the labels
let labelChartPoints = bars.map {bar in
ChartPoint(x: bar.constant, y: bar.axisValue2)
}
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
let labelsLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: labelChartPoints, viewGenerator: {(chartPointModel, layer, chart, isTransform) -> UIView? in
let label = HandlingLabel()
let posOffset: CGFloat = 10
let pos = chartPointModel.chartPoint.y.scalar > 0
let yOffset = pos ? -posOffset : posOffset
label.text = "\(formatter.string(from: NSNumber(value: chartPointModel.chartPoint.y.scalar))!)%"
label.font = ExamplesDefaults.labelFont
label.sizeToFit()
label.center = CGPoint(x: chartPointModel.screenLoc.x, y: pos ? innerFrame.origin.y : innerFrame.origin.y + innerFrame.size.height)
label.alpha = 0
label.movedToSuperViewHandler = {[weak label] in
func targetState() {
label?.alpha = 1
label?.center.y = chartPointModel.screenLoc.y + yOffset
}
if isTransform {
targetState()
} else {
UIView.animate(withDuration: 0.3, animations: {
targetState()
})
}
}
return label
}, displayDelay: 0.5) // show after bars animation
// line layer
let lineChartPoints = lineData.enumerated().map {index, tuple in ChartPoint(x: ChartAxisValueDouble(index), y: ChartAxisValueDouble(tuple.val))}
let lineModel = ChartLineModel(chartPoints: lineChartPoints, lineColor: UIColor.black, lineWidth: 2, animDuration: 0.5, animDelay: 1)
let lineLayer = ChartPointsLineLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, lineModels: [lineModel])
let circleViewGenerator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart, isTransform: Bool) -> UIView? in
let color = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 1)
let circleView = ChartPointEllipseView(center: chartPointModel.screenLoc, diameter: 6)
circleView.animDuration = isTransform ? 0 : 0.5
circleView.fillColor = color
return circleView
}
let lineCirclesLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: lineChartPoints, viewGenerator: circleViewGenerator, displayDelay: 1.5, delayBetweenItems: 0.05)
// show a gap between positive and negative bar
let dummyZeroYChartPoint = ChartPoint(x: ChartAxisValueDouble(0), y: ChartAxisValueDouble(0))
let yZeroGapLayer = ChartPointsViewsLayer(xAxis: xAxisLayer.axis, yAxis: yAxisLayer.axis, chartPoints: [dummyZeroYChartPoint], viewGenerator: {(chartPointModel, layer, chart, isTransform) -> UIView? in
let height: CGFloat = 2
let v = UIView(frame: CGRect(x: chart.contentView.frame.origin.x + 2, y: chartPointModel.screenLoc.y - height / 2, width: chart.contentView.frame.origin.x + chart.contentView.frame.height, height: height))
v.backgroundColor = UIColor.white
return v
})
let chart = Chart(
frame: chartFrame,
innerFrame: innerFrame,
settings: chartSettings,
layers: [
xAxisLayer,
yAxisLayer,
barsLayer,
labelsLayer,
yZeroGapLayer,
lineLayer,
lineCirclesLayer
]
)
view.addSubview(chart.view)
self.chart = chart
}
}
| apache-2.0 | 25633a37da7491175a1b046aff9ac6b8 | 46.08125 | 243 | 0.610912 | 5.001992 | false | false | false | false |
Draveness/RbSwift | RbSwiftTests/Sequence/Sequence+BoolSpec.swift | 1 | 1375 | //
// Sequence+BoolSpec.swift
// RbSwift
//
// Created by draveness on 22/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Quick
import Nimble
import RbSwift
class SequenceBoolSpec: BaseSpec {
override func spec() {
describe("isAny(closure:)") {
it("returns true if array has an element satisfy specific condition") {
expect([1, 2, 3].isAny { $0 == 1 }).to(beTrue())
expect(["a", "b", "c"].isAny { $0 == "b" }).to(beTrue())
}
it("returns true if any element of the array satisfy specific condition") {
expect([1, 2, 3].isAny { $0 == 100 }).to(beFalse())
expect(["a", "b", "c"].isAny { $0 == "bbb" }).to(beFalse())
}
}
describe("isAll(closure:)") {
it("returns true if all the element in array satisfy specific condition") {
expect([1, 2, 3].isAll { $0.isPositive }).to(beTrue())
expect(["a", "a", "a"].isAll { $0 == "a" }).to(beTrue())
}
it("returns true if some of the element in array does not satify specific condition") {
expect([1, 2, 3].isAll { $0 == 100 }).to(beFalse())
expect(["a", "b", "c"].isAll { $0 == "bbb" }).to(beFalse())
}
}
}
}
| mit | 0fee9d89c5ff82afd0caff570fbbe5d8 | 33.35 | 99 | 0.488355 | 3.925714 | false | false | false | false |
P0ed/SWLABR | SWLABR/GameView.swift | 1 | 1451 | import SceneKit
final class GameView: SCNView {
func updateDrawableSize() {
let layer = self.layer! as! CAMetalLayer
layer.drawableSize = bounds.size
}
override func mouseDown(with event: NSEvent) {
/* Called when a mouse click occurs */
// // check what nodes are clicked
// let p = self.convertPoint(theEvent.locationInWindow, fromView: nil)
// let hitResults = self.hitTest(p, options: nil)
// // check that we clicked on at least one object
// if hitResults.count > 0 {
// // retrieved the first clicked object
// let result: AnyObject = hitResults[0]
//
// // get its material
// let material = result.node!.geometry!.firstMaterial!
//
// // highlight it
// SCNTransaction.begin()
// SCNTransaction.setAnimationDuration(0.5)
//
// // on completion - unhighlight
// SCNTransaction.setCompletionBlock() {
// SCNTransaction.begin()
// SCNTransaction.setAnimationDuration(0.5)
//
// material.emission.contents = NSColor.blackColor()
//
// SCNTransaction.commit()
// }
//
// material.emission.contents = NSColor.redColor()
//
// SCNTransaction.commit()
// }
super.mouseDown(with: event)
}
}
| mit | 9c6c2b18088739df499b733c3195004d | 31.244444 | 77 | 0.541006 | 4.606349 | false | false | false | false |
tsjamm/swift-utils | OptionParser.swift | 1 | 2680 | ///// OptionParser.swift
//// Command Line Options Parser in Swift
/// Author: Sai Teja Jammalamadaka
//
class OptionParser {
//// Returns true if parsed correctly, or false if error
class func parse(optionsMap:[String:((String?)->Bool)], usage:String) -> Bool {
let numOfArgs = Process.arguments.count
for var i=1;i<numOfArgs;i++ {
let currentArg = Process.arguments[i]
if let callback = optionsMap[currentArg] {
let j = i+1
if j<numOfArgs {
let futureArg = Process.arguments[j]
if let _ = optionsMap[futureArg] {
if !callback(nil) {
print("Usage :: \(usage)")
print("\(currentArg) was not handled. Error. Terminating.")
return false
}
} else {
if callback(futureArg) {
i=i+1 /// doing this so future arg is skipped
} else {
print("Usage :: \(usage)")
print("\"\(currentArg) \(futureArg)\" was not handled. Error. Terminating.")
return false
}
}
}
} else {
print("\(currentArg) not defined")
print("Usage :: \(usage)")
}
}
return true
}
}
///// ParamRepeater
//// Test Class the shows how to use OptionParser
/// call the start() function
//
class ParamRepeater {
static var parameter = ""
static var numOfTimes = 1
class func start() {
let usageString = "Options: -p <param> = to print the parameter, -r <int> = number of times"
let optionsMap = [
"-p":saveParam,
"-r":saveNumOfRepeats
]
if OptionParser.parse(optionsMap,usage:usageString) {
for var i=0;i<numOfTimes;i++ {
print(parameter)
}
}
}
class func saveParam(param:String?) -> Bool {
if let unwrapped = param {
parameter = unwrapped
return true
}
return false
}
class func saveNumOfRepeats(numStr:String?) -> Bool {
if let unwrapped = numStr {
if let didCast = Int(unwrapped) {
numOfTimes = didCast
return true
}
}
return false
}
}
////
/// The ParamRepeater executes here
//
ParamRepeater.start()
//
///
////
| mit | acaf34a9fa4eec4a0c65074665ae97bd | 27.210526 | 104 | 0.459328 | 4.890511 | false | false | false | false |
blasut/fredrik | fredrik/Place.swift | 1 | 2694 | //
// Place.swift
// fredrik
//
// Created by jite on 28/10/2015.
// Copyright © 2015 Tre Bitar. All rights reserved.
//
import Foundation
import MapKit
import AddressBook
class Place: NSObject, MKAnnotation {
let coordinate: CLLocationCoordinate2D
let title: String?
let age_limit: String
let opening_hours: Dictionary<String, JSON>
let contact: Dictionary<String, JSON>
let street: String
let city: String
init(title: String,
age_limit: String,
opening_hours: Dictionary<String, JSON>,
contact: Dictionary<String, JSON>,
street: String,
city: String,
coordinate: CLLocationCoordinate2D) {
self.title = title
self.age_limit = age_limit
self.opening_hours = opening_hours
self.contact = contact
self.street = street
self.city = city
self.coordinate = coordinate
super.init()
}
class func fromJSON(json: JSON) -> Place? {
let title: String = json["name"].stringValue
let age_limit: String = json["age-limit"].stringValue
let opening_hours: Dictionary<String, JSON> = json["opening-hours"].dictionaryValue
let contact: Dictionary<String, JSON> = json["contact"].dictionaryValue
let street: String = json["location"]["street"].stringValue
let city: String = json["location"]["city"].stringValue
let latitude = json["location"]["latitude"].doubleValue
let longitude = json["location"]["longitude"].doubleValue
let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
return Place(title: title,
age_limit: age_limit,
opening_hours: opening_hours,
contact: contact,
street: street,
city: city,
coordinate: coordinate)
}
var subtitle: String? {
return "Öppet! Stänger kl.03. 18-årsgräns";
}
// annotation callout info button opens this mapItem in Maps app
func mapItem() -> MKMapItem {
let addressDictionary = [String(kABPersonAddressStreetKey): subtitle!]
let placemark = MKPlacemark(coordinate: coordinate, addressDictionary: addressDictionary)
let mapItem = MKMapItem(placemark: placemark)
mapItem.name = title
return mapItem
}
func pinColor() -> UIColor! {
switch age_limit {
case "20":
return UIColor.blueColor()
case "18":
return UIColor.purpleColor()
default:
return UIColor.redColor()
}
}
} | mit | db0d88d103104957a0396a062155ca40 | 28.888889 | 97 | 0.600967 | 4.76773 | false | false | false | false |
hsoi/RxSwift | RxSwift/Observables/Observable+Creation.swift | 2 | 12852 | //
// Observable+Creation.swift
// Rx
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
@available(*, deprecated=2.0.0, message="Please use `Observable.create`")
public func create<E>(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> {
return Observable.create(subscribe)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.empty`")
public func empty<E>(type: E.Type = E.self) -> Observable<E> {
return Observable.empty()
}
@available(*, deprecated=2.0.0, message="Please use `Observable.never`")
public func never<E>(type: E.Type = E.self) -> Observable<E> {
return Observable.never()
}
@available(*, deprecated=2.0.0, message="Please use `Observable.just`")
public func just<E>(element: E) -> Observable<E> {
return Observable.just(element)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.just`")
public func just<E>(element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return Observable.just(element, scheduler: scheduler)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.error`")
public func failWith<E>(error: ErrorType, _ type: E.Type = E.self) -> Observable<E> {
return Observable.error(error)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.of`")
public func sequenceOf<E>(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable<E> {
return Sequence(elements: elements, scheduler: scheduler)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.deferred`")
public func deferred<E>(observableFactory: () throws -> Observable<E>) -> Observable<E> {
return Observable.deferred(observableFactory)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.generate` with named initialState parameter.")
public func generate<E>(initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> {
return Observable.generate(initialState: initialState, condition: condition, scheduler: scheduler, iterate: iterate)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.range` with named start, count, scheduler parameters.")
public func range(start: Int, _ count: Int, _ scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<Int> {
return Observable.range(start: start, count: count, scheduler: scheduler)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.repeatElement` with named scheduler parameter.")
public func repeatElement<E>(element: E, _ scheduler: ImmediateSchedulerType) -> Observable<E> {
return Observable.repeatElement(element, scheduler: scheduler)
}
@available(*, deprecated=2.0.0, message="Please use `Observable.using`.")
public func using<S, R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<S>) -> Observable<S> {
return Observable.using(resourceFactory, observableFactory: observableFactory)
}
extension Observable {
// MARK: create
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func create(subscribe: (AnyObserver<E>) -> Disposable) -> Observable<E> {
return AnonymousObservable(subscribe)
}
// MARK: empty
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func empty() -> Observable<E> {
return Empty<E>()
}
// MARK: never
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func never() -> Observable<E> {
return Never()
}
// MARK: just
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func just(element: E) -> Observable<E> {
return Just(element: element)
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func just(element: E, scheduler: ImmediateSchedulerType) -> Observable<E> {
return JustScheduled(element: element, scheduler: scheduler)
}
// MARK: fail
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func error(error: ErrorType) -> Observable<E> {
return Error(error: error)
}
// MARK: of
/**
This method creates a new Observable instance with a variable number of elements.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter elements: Elements to generate.
- parameter scheduler: Scheduler to send elements on. If `nil`, elements are sent immediatelly on subscription.
- returns: The observable sequence whose elements are pulled from the given arguments.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func of(elements: E ..., scheduler: ImmediateSchedulerType? = nil) -> Observable<E> {
return Sequence(elements: elements, scheduler: scheduler)
}
// MARK: defer
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func deferred(observableFactory: () throws -> Observable<E>)
-> Observable<E> {
return Deferred(observableFactory: observableFactory)
}
/**
Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler
to run the loop send out observer messages.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter initialState: Initial state.
- parameter condition: Condition to terminate generation (upon returning `false`).
- parameter iterate: Iteration step function.
- parameter scheduler: Scheduler on which to run the generator loop.
- returns: The generated sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func generate(initialState initialState: E, condition: E throws -> Bool, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance, iterate: E throws -> E) -> Observable<E> {
return Generate(initialState: initialState, condition: condition, iterate: iterate, resultSelector: { $0 }, scheduler: scheduler)
}
/**
Generates an observable sequence that repeats the given element infinitely, using the specified scheduler to send out observer messages.
- seealso: [repeat operator on reactivex.io](http://reactivex.io/documentation/operators/repeat.html)
- parameter element: Element to repeat.
- parameter scheduler: Scheduler to run the producer loop on.
- returns: An observable sequence that repeats the given element infinitely.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func repeatElement(element: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RepeatElement(element: element, scheduler: scheduler)
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter observableFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func using<R: Disposable>(resourceFactory: () throws -> R, observableFactory: R throws -> Observable<E>) -> Observable<E> {
return Using(resourceFactory: resourceFactory, observableFactory: observableFactory)
}
}
extension Observable where Element : SignedIntegerType {
/**
Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to generate and send out observer messages.
- seealso: [range operator on reactivex.io](http://reactivex.io/documentation/operators/range.html)
- parameter start: The value of the first integer in the sequence.
- parameter count: The number of sequential integers to generate.
- parameter scheduler: Scheduler to run the generator loop on.
- returns: An observable sequence that contains a range of sequential integral numbers.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public static func range(start start: E, count: E, scheduler: ImmediateSchedulerType = CurrentThreadScheduler.instance) -> Observable<E> {
return RangeProducer<E>(start: start, count: count, scheduler: scheduler)
}
}
extension SequenceType {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
@available(*, deprecated=2.0.0, message="Please use toObservable extension.")
public func asObservable() -> Observable<Generator.Element> {
return Sequence(elements: Array(self), scheduler: nil)
}
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: Array(self), scheduler: scheduler)
}
}
extension Array {
/**
Converts a sequence to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- returns: The observable sequence whose elements are pulled from the given enumerable sequence.
*/
@warn_unused_result(message="http://git.io/rxs.uo")
public func toObservable(scheduler: ImmediateSchedulerType? = nil) -> Observable<Generator.Element> {
return Sequence(elements: self, scheduler: scheduler)
}
} | mit | f15644e9062ea106a875220203635de4 | 43.013699 | 202 | 0.72259 | 4.434438 | false | false | false | false |
customerly/Customerly-iOS-SDK | Pods/Socket.IO-Client-Swift/Source/SocketIO/Manager/SocketManager.swift | 2 | 19916 | //
// Created by Erik Little on 10/14/17.
//
// 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 Dispatch
import Foundation
///
/// A manager for a socket.io connection.
///
/// A `SocketManager` is responsible for multiplexing multiple namespaces through a single `SocketEngineSpec`.
///
/// Example:
///
/// ```swift
/// let manager = SocketManager(socketURL: URL(string:"http://localhost:8080/")!)
/// let defaultNamespaceSocket = manager.defaultSocket
/// let swiftSocket = manager.socket(forNamespace: "/swift")
///
/// // defaultNamespaceSocket and swiftSocket both share a single connection to the server
/// ```
///
/// Sockets created through the manager are retained by the manager. So at the very least, a single strong reference
/// to the manager must be maintained to keep sockets alive.
///
/// To disconnect a socket and remove it from the manager, either call `SocketIOClient.disconnect()` on the socket,
/// or call one of the `disconnectSocket` methods on this class.
///
/// **NOTE**: The manager is not thread/queue safe, all interaction with the manager should be done on the `handleQueue`
///
open class SocketManager : NSObject, SocketManagerSpec, SocketParsable, SocketDataBufferable, ConfigSettable {
private static let logType = "SocketManager"
// MARK: Properties
/// The socket associated with the default namespace ("/").
public var defaultSocket: SocketIOClient {
return socket(forNamespace: "/")
}
/// The URL of the socket.io server.
///
/// If changed after calling `init`, `forceNew` must be set to `true`, or it will only connect to the url set in the
/// init.
public let socketURL: URL
/// The configuration for this client.
///
/// **Some configs will not take affect until after a reconnect if set after calling a connect method**.
public var config: SocketIOClientConfiguration {
get {
return _config
}
set {
if status.active {
DefaultSocketLogger.Logger.log("Setting configs on active manager. Some configs may not be applied until reconnect",
type: SocketManager.logType)
}
setConfigs(newValue)
}
}
/// The engine for this manager.
public var engine: SocketEngineSpec?
/// If `true` then every time `connect` is called, a new engine will be created.
public var forceNew = false
/// The queue that all interaction with the client should occur on. This is the queue that event handlers are
/// called on.
///
/// **This should be a serial queue! Concurrent queues are not supported and might cause crashes and races**.
public var handleQueue = DispatchQueue.main
/// The sockets in this manager indexed by namespace.
public var nsps = [String: SocketIOClient]()
/// If `true`, this client will try and reconnect on any disconnects.
public var reconnects = true
/// The minimum number of seconds to wait before attempting to reconnect.
public var reconnectWait = 10
/// The maximum number of seconds to wait before attempting to reconnect.
public var reconnectWaitMax = 30
/// The randomization factor for calculating reconnect jitter.
public var randomizationFactor = 0.5
/// The status of this manager.
public private(set) var status: SocketIOStatus = .notConnected {
didSet {
switch status {
case .connected:
reconnecting = false
currentReconnectAttempt = 0
default:
break
}
}
}
/// A list of packets that are waiting for binary data.
///
/// The way that socket.io works all data should be sent directly after each packet.
/// So this should ideally be an array of one packet waiting for data.
///
/// **This should not be modified directly.**
public var waitingPackets = [SocketPacket]()
private(set) var reconnectAttempts = -1
private var _config: SocketIOClientConfiguration
private var currentReconnectAttempt = 0
private var reconnecting = false
// MARK: Initializers
/// Type safe way to create a new SocketIOClient. `opts` can be omitted.
///
/// - parameter socketURL: The url of the socket.io server.
/// - parameter config: The config for this socket.
public init(socketURL: URL, config: SocketIOClientConfiguration = []) {
self._config = config
self.socketURL = socketURL
super.init()
setConfigs(_config)
}
/// Not so type safe way to create a SocketIOClient, meant for Objective-C compatiblity.
/// If using Swift it's recommended to use `init(socketURL: NSURL, options: Set<SocketIOClientOption>)`
///
/// - parameter socketURL: The url of the socket.io server.
/// - parameter config: The config for this socket.
@objc
public convenience init(socketURL: URL, config: [String: Any]?) {
self.init(socketURL: socketURL, config: config?.toSocketConfiguration() ?? [])
}
/// :nodoc:
deinit {
DefaultSocketLogger.Logger.log("Manager is being released", type: SocketManager.logType)
engine?.disconnect(reason: "Manager Deinit")
}
// MARK: Methods
private func addEngine() {
DefaultSocketLogger.Logger.log("Adding engine", type: SocketManager.logType)
engine?.engineQueue.sync {
self.engine?.client = nil
// Close old engine so it will not leak because of URLSession if in polling mode
self.engine?.disconnect(reason: "Adding new engine")
}
engine = SocketEngine(client: self, url: socketURL, config: config)
}
/// Connects the underlying transport and the default namespace socket.
///
/// Override if you wish to attach a custom `SocketEngineSpec`.
open func connect() {
guard !status.active else {
DefaultSocketLogger.Logger.log("Tried connecting an already active socket", type: SocketManager.logType)
return
}
if engine == nil || forceNew {
addEngine()
}
status = .connecting
engine?.connect()
}
/// Connects a socket through this manager's engine.
///
/// - parameter socket: The socket who we should connect through this manager.
open func connectSocket(_ socket: SocketIOClient) {
guard status == .connected else {
DefaultSocketLogger.Logger.log("Tried connecting socket when engine isn't open. Connecting",
type: SocketManager.logType)
connect()
return
}
engine?.send("0\(socket.nsp),", withData: [])
}
/// Called when the manager has disconnected from socket.io.
///
/// - parameter reason: The reason for the disconnection.
open func didDisconnect(reason: String) {
forAll {socket in
socket.didDisconnect(reason: reason)
}
}
/// Disconnects the manager and all associated sockets.
open func disconnect() {
DefaultSocketLogger.Logger.log("Manager closing", type: SocketManager.logType)
status = .disconnected
engine?.disconnect(reason: "Disconnect")
}
/// Disconnects the given socket.
///
/// This will remove the socket for the manager's control, and make the socket instance useless and ready for
/// releasing.
///
/// - parameter socket: The socket to disconnect.
open func disconnectSocket(_ socket: SocketIOClient) {
engine?.send("1\(socket.nsp),", withData: [])
socket.didDisconnect(reason: "Namespace leave")
}
/// Disconnects the socket associated with `forNamespace`.
///
/// This will remove the socket for the manager's control, and make the socket instance useless and ready for
/// releasing.
///
/// - parameter nsp: The namespace to disconnect from.
open func disconnectSocket(forNamespace nsp: String) {
guard let socket = nsps.removeValue(forKey: nsp) else {
DefaultSocketLogger.Logger.log("Could not find socket for \(nsp) to disconnect",
type: SocketManager.logType)
return
}
disconnectSocket(socket)
}
/// Sends a client event to all sockets in `nsps`
///
/// - parameter clientEvent: The event to emit.
open func emitAll(clientEvent event: SocketClientEvent, data: [Any]) {
forAll {socket in
socket.handleClientEvent(event, data: data)
}
}
/// Sends an event to the server on all namespaces in this manager.
///
/// - parameter event: The event to send.
/// - parameter items: The data to send with this event.
open func emitAll(_ event: String, _ items: SocketData...) {
guard let emitData = try? items.map({ try $0.socketRepresentation() }) else {
DefaultSocketLogger.Logger.error("Error creating socketRepresentation for emit: \(event), \(items)",
type: SocketManager.logType)
return
}
emitAll(event, withItems: emitData)
}
/// Sends an event to the server on all namespaces in this manager.
///
/// Same as `emitAll(_:_:)`, but meant for Objective-C.
///
/// - parameter event: The event to send.
/// - parameter items: The data to send with this event.
open func emitAll(_ event: String, withItems items: [Any]) {
forAll {socket in
socket.emit(event, with: items, completion: nil)
}
}
/// Called when the engine closes.
///
/// - parameter reason: The reason that the engine closed.
open func engineDidClose(reason: String) {
handleQueue.async {
self._engineDidClose(reason: reason)
}
}
private func _engineDidClose(reason: String) {
waitingPackets.removeAll()
if status != .disconnected {
status = .notConnected
}
if status == .disconnected || !reconnects {
didDisconnect(reason: reason)
} else if !reconnecting {
reconnecting = true
tryReconnect(reason: reason)
}
}
/// Called when the engine errors.
///
/// - parameter reason: The reason the engine errored.
open func engineDidError(reason: String) {
handleQueue.async {
self._engineDidError(reason: reason)
}
}
private func _engineDidError(reason: String) {
DefaultSocketLogger.Logger.error("\(reason)", type: SocketManager.logType)
emitAll(clientEvent: .error, data: [reason])
}
/// Called when the engine opens.
///
/// - parameter reason: The reason the engine opened.
open func engineDidOpen(reason: String) {
handleQueue.async {
self._engineDidOpen(reason: reason)
}
}
private func _engineDidOpen(reason: String) {
DefaultSocketLogger.Logger.log("Engine opened \(reason)", type: SocketManager.logType)
status = .connected
nsps["/"]?.didConnect(toNamespace: "/")
for (nsp, socket) in nsps where nsp != "/" && socket.status == .connecting {
connectSocket(socket)
}
}
/// Called when the engine receives a pong message.
open func engineDidReceivePong() {
handleQueue.async {
self._engineDidReceivePong()
}
}
private func _engineDidReceivePong() {
emitAll(clientEvent: .pong, data: [])
}
/// Called when the sends a ping to the server.
open func engineDidSendPing() {
handleQueue.async {
self._engineDidSendPing()
}
}
private func _engineDidSendPing() {
emitAll(clientEvent: .ping, data: [])
}
private func forAll(do: (SocketIOClient) throws -> ()) rethrows {
for (_, socket) in nsps {
try `do`(socket)
}
}
/// Called when when upgrading the http connection to a websocket connection.
///
/// - parameter headers: The http headers.
open func engineDidWebsocketUpgrade(headers: [String: String]) {
handleQueue.async {
self._engineDidWebsocketUpgrade(headers: headers)
}
}
private func _engineDidWebsocketUpgrade(headers: [String: String]) {
emitAll(clientEvent: .websocketUpgrade, data: [headers])
}
/// Called when the engine has a message that must be parsed.
///
/// - parameter msg: The message that needs parsing.
open func parseEngineMessage(_ msg: String) {
handleQueue.async {
self._parseEngineMessage(msg)
}
}
private func _parseEngineMessage(_ msg: String) {
guard let packet = parseSocketMessage(msg) else { return }
guard !packet.type.isBinary else {
waitingPackets.append(packet)
return
}
nsps[packet.nsp]?.handlePacket(packet)
}
/// Called when the engine receives binary data.
///
/// - parameter data: The data the engine received.
open func parseEngineBinaryData(_ data: Data) {
handleQueue.async {
self._parseEngineBinaryData(data)
}
}
private func _parseEngineBinaryData(_ data: Data) {
guard let packet = parseBinaryData(data) else { return }
nsps[packet.nsp]?.handlePacket(packet)
}
/// Tries to reconnect to the server.
///
/// This will cause a `SocketClientEvent.reconnect` event to be emitted, as well as
/// `SocketClientEvent.reconnectAttempt` events.
open func reconnect() {
guard !reconnecting else { return }
engine?.disconnect(reason: "manual reconnect")
}
/// Removes the socket from the manager's control. One of the disconnect methods should be called before calling this
/// method.
///
/// After calling this method the socket should no longer be considered usable.
///
/// - parameter socket: The socket to remove.
/// - returns: The socket removed, if it was owned by the manager.
@discardableResult
open func removeSocket(_ socket: SocketIOClient) -> SocketIOClient? {
return nsps.removeValue(forKey: socket.nsp)
}
private func tryReconnect(reason: String) {
guard reconnecting else { return }
DefaultSocketLogger.Logger.log("Starting reconnect", type: SocketManager.logType)
// Set status to connecting and emit reconnect for all sockets
forAll {socket in
guard socket.status == .connected else { return }
socket.setReconnecting(reason: reason)
}
_tryReconnect()
}
private func _tryReconnect() {
guard reconnects && reconnecting && status != .disconnected else { return }
if reconnectAttempts != -1 && currentReconnectAttempt + 1 > reconnectAttempts {
return didDisconnect(reason: "Reconnect Failed")
}
DefaultSocketLogger.Logger.log("Trying to reconnect", type: SocketManager.logType)
emitAll(clientEvent: .reconnectAttempt, data: [(reconnectAttempts - currentReconnectAttempt)])
currentReconnectAttempt += 1
connect()
let interval = reconnectInterval(attempts: currentReconnectAttempt)
DefaultSocketLogger.Logger.log("Scheduling reconnect in \(interval)s", type: SocketManager.logType)
handleQueue.asyncAfter(deadline: DispatchTime.now() + interval, execute: _tryReconnect)
}
func reconnectInterval(attempts: Int) -> Double {
// apply exponential factor
let backoffFactor = pow(1.5, attempts)
let interval = Double(reconnectWait) * Double(truncating: backoffFactor as NSNumber)
// add in a random factor smooth thundering herds
let rand = Double.random(in: 0 ..< 1)
let randomFactor = rand * randomizationFactor * Double(truncating: interval as NSNumber)
// add in random factor, and clamp to min and max values
let combined = interval + randomFactor
return Double(fmax(Double(reconnectWait), fmin(combined, Double(reconnectWaitMax))))
}
/// Sets manager specific configs.
///
/// parameter config: The configs that should be set.
open func setConfigs(_ config: SocketIOClientConfiguration) {
for option in config {
switch option {
case let .forceNew(new):
self.forceNew = new
case let .handleQueue(queue):
self.handleQueue = queue
case let .reconnects(reconnects):
self.reconnects = reconnects
case let .reconnectAttempts(attempts):
self.reconnectAttempts = attempts
case let .reconnectWait(wait):
reconnectWait = abs(wait)
case let .reconnectWaitMax(wait):
reconnectWaitMax = abs(wait)
case let .randomizationFactor(factor):
randomizationFactor = factor
case let .log(log):
DefaultSocketLogger.Logger.log = log
case let .logger(logger):
DefaultSocketLogger.Logger = logger
case _:
continue
}
}
_config = config
if socketURL.absoluteString.hasPrefix("https://") {
_config.insert(.secure(true))
}
_config.insert(.path("/socket.io/"), replacing: false)
// If `ConfigSettable` & `SocketEngineSpec`, update its configs.
if var settableEngine = engine as? ConfigSettable & SocketEngineSpec {
settableEngine.engineQueue.sync {
settableEngine.setConfigs(self._config)
}
engine = settableEngine
}
}
/// Returns a `SocketIOClient` for the given namespace. This socket shares a transport with the manager.
///
/// Calling multiple times returns the same socket.
///
/// Sockets created from this method are retained by the manager.
/// Call one of the `disconnectSocket` methods on this class to remove the socket from manager control.
/// Or call `SocketIOClient.disconnect()` on the client.
///
/// - parameter nsp: The namespace for the socket.
/// - returns: A `SocketIOClient` for the given namespace.
open func socket(forNamespace nsp: String) -> SocketIOClient {
assert(nsp.hasPrefix("/"), "forNamespace must have a leading /")
if let socket = nsps[nsp] {
return socket
}
let client = SocketIOClient(manager: self, nsp: nsp)
nsps[nsp] = client
return client
}
// Test properties
func setTestStatus(_ status: SocketIOStatus) {
self.status = status
}
}
| apache-2.0 | 38db2d44d09c4a22f3358f9c7c256d79 | 33.516464 | 132 | 0.632155 | 4.850463 | false | true | false | false |
MateuszKarwat/Napi | Napi/Models/Subtitle Provider/Supported Subtitle Providers/NapiProjekt.swift | 1 | 4838 | //
// Created by Mateusz Karwat on 14/01/2017.
// Copyright © 2017 Mateusz Karwat. All rights reserved.
//
import Foundation
struct NapiProjekt: SubtitleProvider {
let name = "NapiProjekt"
let homepage = URL(string: "http://www.napiprojekt.pl")!
func searchSubtitles(using searchCritera: SearchCriteria, completionHandler: @escaping ([SubtitleEntity]) -> Void) {
log.info("Sending search request.")
guard let searchRequest = searchRequest(with: searchCritera) else {
log.warning("Search request couldn't be created.")
completionHandler([])
return
}
let dataTask = URLSession.shared.dataTask(with: searchRequest) { data, _ in
log.info("Search response received.")
guard
let data = data,
let stringResponse = String(data: data, encoding: .windowsCP1250),
let subtitleEntity = self.subtitleEntity(from: stringResponse, in: searchCritera.language)
else {
completionHandler([])
return
}
completionHandler([subtitleEntity])
}
dataTask.resume()
}
func download(_ subtitleEntity: SubtitleEntity, completionHandler: @escaping (SubtitleEntity?) -> Void) {
log.info("Downloading subtitles.")
guard
subtitleEntity.format == .text,
subtitleEntity.url.isFile,
subtitleEntity.url.exists
else {
log.error("Download failed.")
completionHandler(nil)
return
}
log.info("Subtitles downloaded.")
completionHandler(subtitleEntity)
}
private func subtitleEntity(from stringResponse: String, in language: Language) -> SubtitleEntity? {
log.verbose("Parsing search response.")
if stringResponse == "NPc0" {
log.verbose("Subtitles has not been found.")
return nil
}
let directoryManager = TemporaryDirectoryManager.default
directoryManager.createTemporaryDirectory()
let subtitleEntity = SubtitleEntity(language: language, format: .text)
do {
try stringResponse.write(to: subtitleEntity.url, atomically: true, encoding: .windowsCP1250)
log.verbose("Subtitles has been found.")
return subtitleEntity
} catch let error {
log.error(error.localizedDescription)
return nil
}
}
private func searchRequest(with searchCriteria: SearchCriteria) -> URLRequest? {
guard
let fileInformation = FileInformation(url: searchCriteria.fileURL),
let md5 = fileInformation.md5(chunkSize: 10 * 1024 * 1024),
let md5Hash = mysteriousHash(of: md5)
else {
return nil
}
var parameters = [String: String]()
parameters["l"] = searchCriteria.language.isoCode.uppercased()
parameters["f"] = md5
parameters["t"] = md5Hash
parameters["v"] = "pynapi"
parameters["kolejka"] = "false"
parameters["nick"] = ""
parameters["pass"] = ""
parameters["napios"] = "macOS"
// NapiProject requires ISO-639-2 for English.
if parameters["l"] == "EN" {
parameters["l"] = "ENG"
}
guard let baseURL = URL(string: "http://napiprojekt.pl/unit_napisy/dl.php?".appending(parameters.httpBodyFormat)) else {
return nil
}
return URLRequest(url: baseURL)
}
private func mysteriousHash(of md5Hash: String) -> String? {
if md5Hash.count != 32 {
return nil
}
let idx = [0xe, 0x3, 0x6, 0x8, 0x2]
let mul = [2, 2, 5, 4, 3]
let add = [0x0, 0xd, 0x10, 0xb, 0x5]
var t = 0
var tmp: UInt32 = 0
var v: UInt32 = 0
var generatedHash = ""
for i in 0 ..< 5 {
var scanner = Scanner(string: String(format: "%c", (md5Hash as NSString).character(at: idx[i])))
scanner.scanHexInt32(&tmp)
t = add[i] + Int(tmp)
var subString = ""
if (t > 30) {
subString = md5Hash.substring(from: t)
} else {
let characterIndex = md5Hash.index(md5Hash.startIndex, offsetBy: t)
subString = String(md5Hash[characterIndex ..< md5Hash.index(characterIndex, offsetBy: 2)])
}
scanner = Scanner(string: subString)
scanner.scanHexInt32(&v)
let hexResult = String(format: "%x", Int(v) * mul[i])
let lastHexCharacter = hexResult.last ?? Character("")
generatedHash.append(lastHexCharacter)
}
return generatedHash.trimmingCharacters(in: .newlines)
}
}
| mit | a3bb5da9b42f83763a922d20c8fbfd54 | 30.822368 | 128 | 0.575977 | 4.482854 | false | false | false | false |
apple/swift | test/Runtime/concurrentTypeByName.swift | 2 | 34614 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import StdlibUnittest
import SwiftPrivateThreadExtras
protocol P {}
class GenericWrapper<T: P> {}
let ConcurrentTypeByNameTests = TestSuite("ConcurrentTypeByName")
// We're testing for a race in looking up types by name, when there's a protocol
// constraint on a generic argument, and that constraint is fulfilled by a
// superclass. This race is more easily exposed when the superclass's metadata
// takes a long time to fill out, so we make it have a ton of properties here.
class Super<T>: P {
var val0: T?
var val1: T?
var val2: T?
var val3: T?
var val4: T?
var val5: T?
var val6: T?
var val7: T?
var val8: T?
var val9: T?
var val10: T?
var val11: T?
var val12: T?
var val13: T?
var val14: T?
var val15: T?
var val16: T?
var val17: T?
var val18: T?
var val19: T?
var val20: T?
var val21: T?
var val22: T?
var val23: T?
var val24: T?
var val25: T?
var val26: T?
var val27: T?
var val28: T?
var val29: T?
var val30: T?
var val31: T?
var val32: T?
var val33: T?
var val34: T?
var val35: T?
var val36: T?
var val37: T?
var val38: T?
var val39: T?
var val40: T?
var val41: T?
var val42: T?
var val43: T?
var val44: T?
var val45: T?
var val46: T?
var val47: T?
var val48: T?
var val49: T?
var val50: T?
var val51: T?
var val52: T?
var val53: T?
var val54: T?
var val55: T?
var val56: T?
var val57: T?
var val58: T?
var val59: T?
var val60: T?
var val61: T?
var val62: T?
var val63: T?
var val64: T?
var val65: T?
var val66: T?
var val67: T?
var val68: T?
var val69: T?
var val70: T?
var val71: T?
var val72: T?
var val73: T?
var val74: T?
var val75: T?
var val76: T?
var val77: T?
var val78: T?
var val79: T?
var val80: T?
var val81: T?
var val82: T?
var val83: T?
var val84: T?
var val85: T?
var val86: T?
var val87: T?
var val88: T?
var val89: T?
var val90: T?
var val91: T?
var val92: T?
var val93: T?
var val94: T?
var val95: T?
var val96: T?
var val97: T?
var val98: T?
var val99: T?
var val100: T?
var val101: T?
var val102: T?
var val103: T?
var val104: T?
var val105: T?
var val106: T?
var val107: T?
var val108: T?
var val109: T?
var val110: T?
var val111: T?
var val112: T?
var val113: T?
var val114: T?
var val115: T?
var val116: T?
var val117: T?
var val118: T?
var val119: T?
var val120: T?
var val121: T?
var val122: T?
var val123: T?
var val124: T?
var val125: T?
var val126: T?
var val127: T?
var val128: T?
var val129: T?
var val130: T?
var val131: T?
var val132: T?
var val133: T?
var val134: T?
var val135: T?
var val136: T?
var val137: T?
var val138: T?
var val139: T?
var val140: T?
var val141: T?
var val142: T?
var val143: T?
var val144: T?
var val145: T?
var val146: T?
var val147: T?
var val148: T?
var val149: T?
var val150: T?
var val151: T?
var val152: T?
var val153: T?
var val154: T?
var val155: T?
var val156: T?
var val157: T?
var val158: T?
var val159: T?
var val160: T?
var val161: T?
var val162: T?
var val163: T?
var val164: T?
var val165: T?
var val166: T?
var val167: T?
var val168: T?
var val169: T?
var val170: T?
var val171: T?
var val172: T?
var val173: T?
var val174: T?
var val175: T?
var val176: T?
var val177: T?
var val178: T?
var val179: T?
var val180: T?
var val181: T?
var val182: T?
var val183: T?
var val184: T?
var val185: T?
var val186: T?
var val187: T?
var val188: T?
var val189: T?
var val190: T?
var val191: T?
var val192: T?
var val193: T?
var val194: T?
var val195: T?
var val196: T?
var val197: T?
var val198: T?
var val199: T?
var val200: T?
var val201: T?
var val202: T?
var val203: T?
var val204: T?
var val205: T?
var val206: T?
var val207: T?
var val208: T?
var val209: T?
var val210: T?
var val211: T?
var val212: T?
var val213: T?
var val214: T?
var val215: T?
var val216: T?
var val217: T?
var val218: T?
var val219: T?
var val220: T?
var val221: T?
var val222: T?
var val223: T?
var val224: T?
var val225: T?
var val226: T?
var val227: T?
var val228: T?
var val229: T?
var val230: T?
var val231: T?
var val232: T?
var val233: T?
var val234: T?
var val235: T?
var val236: T?
var val237: T?
var val238: T?
var val239: T?
var val240: T?
var val241: T?
var val242: T?
var val243: T?
var val244: T?
var val245: T?
var val246: T?
var val247: T?
var val248: T?
var val249: T?
var val250: T?
var val251: T?
var val252: T?
var val253: T?
var val254: T?
var val255: T?
var val256: T?
var val257: T?
var val258: T?
var val259: T?
var val260: T?
var val261: T?
var val262: T?
var val263: T?
var val264: T?
var val265: T?
var val266: T?
var val267: T?
var val268: T?
var val269: T?
var val270: T?
var val271: T?
var val272: T?
var val273: T?
var val274: T?
var val275: T?
var val276: T?
var val277: T?
var val278: T?
var val279: T?
var val280: T?
var val281: T?
var val282: T?
var val283: T?
var val284: T?
var val285: T?
var val286: T?
var val287: T?
var val288: T?
var val289: T?
var val290: T?
var val291: T?
var val292: T?
var val293: T?
var val294: T?
var val295: T?
var val296: T?
var val297: T?
var val298: T?
var val299: T?
var val300: T?
var val301: T?
var val302: T?
var val303: T?
var val304: T?
var val305: T?
var val306: T?
var val307: T?
var val308: T?
var val309: T?
var val310: T?
var val311: T?
var val312: T?
var val313: T?
var val314: T?
var val315: T?
var val316: T?
var val317: T?
var val318: T?
var val319: T?
var val320: T?
var val321: T?
var val322: T?
var val323: T?
var val324: T?
var val325: T?
var val326: T?
var val327: T?
var val328: T?
var val329: T?
var val330: T?
var val331: T?
var val332: T?
var val333: T?
var val334: T?
var val335: T?
var val336: T?
var val337: T?
var val338: T?
var val339: T?
var val340: T?
var val341: T?
var val342: T?
var val343: T?
var val344: T?
var val345: T?
var val346: T?
var val347: T?
var val348: T?
var val349: T?
var val350: T?
var val351: T?
var val352: T?
var val353: T?
var val354: T?
var val355: T?
var val356: T?
var val357: T?
var val358: T?
var val359: T?
var val360: T?
var val361: T?
var val362: T?
var val363: T?
var val364: T?
var val365: T?
var val366: T?
var val367: T?
var val368: T?
var val369: T?
var val370: T?
var val371: T?
var val372: T?
var val373: T?
var val374: T?
var val375: T?
var val376: T?
var val377: T?
var val378: T?
var val379: T?
var val380: T?
var val381: T?
var val382: T?
var val383: T?
var val384: T?
var val385: T?
var val386: T?
var val387: T?
var val388: T?
var val389: T?
var val390: T?
var val391: T?
var val392: T?
var val393: T?
var val394: T?
var val395: T?
var val396: T?
var val397: T?
var val398: T?
var val399: T?
var val400: T?
var val401: T?
var val402: T?
var val403: T?
var val404: T?
var val405: T?
var val406: T?
var val407: T?
var val408: T?
var val409: T?
var val410: T?
var val411: T?
var val412: T?
var val413: T?
var val414: T?
var val415: T?
var val416: T?
var val417: T?
var val418: T?
var val419: T?
var val420: T?
var val421: T?
var val422: T?
var val423: T?
var val424: T?
var val425: T?
var val426: T?
var val427: T?
var val428: T?
var val429: T?
var val430: T?
var val431: T?
var val432: T?
var val433: T?
var val434: T?
var val435: T?
var val436: T?
var val437: T?
var val438: T?
var val439: T?
var val440: T?
var val441: T?
var val442: T?
var val443: T?
var val444: T?
var val445: T?
var val446: T?
var val447: T?
var val448: T?
var val449: T?
var val450: T?
var val451: T?
var val452: T?
var val453: T?
var val454: T?
var val455: T?
var val456: T?
var val457: T?
var val458: T?
var val459: T?
var val460: T?
var val461: T?
var val462: T?
var val463: T?
var val464: T?
var val465: T?
var val466: T?
var val467: T?
var val468: T?
var val469: T?
var val470: T?
var val471: T?
var val472: T?
var val473: T?
var val474: T?
var val475: T?
var val476: T?
var val477: T?
var val478: T?
var val479: T?
var val480: T?
var val481: T?
var val482: T?
var val483: T?
var val484: T?
var val485: T?
var val486: T?
var val487: T?
var val488: T?
var val489: T?
var val490: T?
var val491: T?
var val492: T?
var val493: T?
var val494: T?
var val495: T?
var val496: T?
var val497: T?
var val498: T?
var val499: T?
var val500: T?
var val501: T?
var val502: T?
var val503: T?
var val504: T?
var val505: T?
var val506: T?
var val507: T?
var val508: T?
var val509: T?
var val510: T?
var val511: T?
var val512: T?
var val513: T?
var val514: T?
var val515: T?
var val516: T?
var val517: T?
var val518: T?
var val519: T?
var val520: T?
var val521: T?
var val522: T?
var val523: T?
var val524: T?
var val525: T?
var val526: T?
var val527: T?
var val528: T?
var val529: T?
var val530: T?
var val531: T?
var val532: T?
var val533: T?
var val534: T?
var val535: T?
var val536: T?
var val537: T?
var val538: T?
var val539: T?
var val540: T?
var val541: T?
var val542: T?
var val543: T?
var val544: T?
var val545: T?
var val546: T?
var val547: T?
var val548: T?
var val549: T?
var val550: T?
var val551: T?
var val552: T?
var val553: T?
var val554: T?
var val555: T?
var val556: T?
var val557: T?
var val558: T?
var val559: T?
var val560: T?
var val561: T?
var val562: T?
var val563: T?
var val564: T?
var val565: T?
var val566: T?
var val567: T?
var val568: T?
var val569: T?
var val570: T?
var val571: T?
var val572: T?
var val573: T?
var val574: T?
var val575: T?
var val576: T?
var val577: T?
var val578: T?
var val579: T?
var val580: T?
var val581: T?
var val582: T?
var val583: T?
var val584: T?
var val585: T?
var val586: T?
var val587: T?
var val588: T?
var val589: T?
var val590: T?
var val591: T?
var val592: T?
var val593: T?
var val594: T?
var val595: T?
var val596: T?
var val597: T?
var val598: T?
var val599: T?
var val600: T?
var val601: T?
var val602: T?
var val603: T?
var val604: T?
var val605: T?
var val606: T?
var val607: T?
var val608: T?
var val609: T?
var val610: T?
var val611: T?
var val612: T?
var val613: T?
var val614: T?
var val615: T?
var val616: T?
var val617: T?
var val618: T?
var val619: T?
var val620: T?
var val621: T?
var val622: T?
var val623: T?
var val624: T?
var val625: T?
var val626: T?
var val627: T?
var val628: T?
var val629: T?
var val630: T?
var val631: T?
var val632: T?
var val633: T?
var val634: T?
var val635: T?
var val636: T?
var val637: T?
var val638: T?
var val639: T?
var val640: T?
var val641: T?
var val642: T?
var val643: T?
var val644: T?
var val645: T?
var val646: T?
var val647: T?
var val648: T?
var val649: T?
var val650: T?
var val651: T?
var val652: T?
var val653: T?
var val654: T?
var val655: T?
var val656: T?
var val657: T?
var val658: T?
var val659: T?
var val660: T?
var val661: T?
var val662: T?
var val663: T?
var val664: T?
var val665: T?
var val666: T?
var val667: T?
var val668: T?
var val669: T?
var val670: T?
var val671: T?
var val672: T?
var val673: T?
var val674: T?
var val675: T?
var val676: T?
var val677: T?
var val678: T?
var val679: T?
var val680: T?
var val681: T?
var val682: T?
var val683: T?
var val684: T?
var val685: T?
var val686: T?
var val687: T?
var val688: T?
var val689: T?
var val690: T?
var val691: T?
var val692: T?
var val693: T?
var val694: T?
var val695: T?
var val696: T?
var val697: T?
var val698: T?
var val699: T?
var val700: T?
var val701: T?
var val702: T?
var val703: T?
var val704: T?
var val705: T?
var val706: T?
var val707: T?
var val708: T?
var val709: T?
var val710: T?
var val711: T?
var val712: T?
var val713: T?
var val714: T?
var val715: T?
var val716: T?
var val717: T?
var val718: T?
var val719: T?
var val720: T?
var val721: T?
var val722: T?
var val723: T?
var val724: T?
var val725: T?
var val726: T?
var val727: T?
var val728: T?
var val729: T?
var val730: T?
var val731: T?
var val732: T?
var val733: T?
var val734: T?
var val735: T?
var val736: T?
var val737: T?
var val738: T?
var val739: T?
var val740: T?
var val741: T?
var val742: T?
var val743: T?
var val744: T?
var val745: T?
var val746: T?
var val747: T?
var val748: T?
var val749: T?
var val750: T?
var val751: T?
var val752: T?
var val753: T?
var val754: T?
var val755: T?
var val756: T?
var val757: T?
var val758: T?
var val759: T?
var val760: T?
var val761: T?
var val762: T?
var val763: T?
var val764: T?
var val765: T?
var val766: T?
var val767: T?
var val768: T?
var val769: T?
var val770: T?
var val771: T?
var val772: T?
var val773: T?
var val774: T?
var val775: T?
var val776: T?
var val777: T?
var val778: T?
var val779: T?
var val780: T?
var val781: T?
var val782: T?
var val783: T?
var val784: T?
var val785: T?
var val786: T?
var val787: T?
var val788: T?
var val789: T?
var val790: T?
var val791: T?
var val792: T?
var val793: T?
var val794: T?
var val795: T?
var val796: T?
var val797: T?
var val798: T?
var val799: T?
var val800: T?
var val801: T?
var val802: T?
var val803: T?
var val804: T?
var val805: T?
var val806: T?
var val807: T?
var val808: T?
var val809: T?
var val810: T?
var val811: T?
var val812: T?
var val813: T?
var val814: T?
var val815: T?
var val816: T?
var val817: T?
var val818: T?
var val819: T?
var val820: T?
var val821: T?
var val822: T?
var val823: T?
var val824: T?
var val825: T?
var val826: T?
var val827: T?
var val828: T?
var val829: T?
var val830: T?
var val831: T?
var val832: T?
var val833: T?
var val834: T?
var val835: T?
var val836: T?
var val837: T?
var val838: T?
var val839: T?
var val840: T?
var val841: T?
var val842: T?
var val843: T?
var val844: T?
var val845: T?
var val846: T?
var val847: T?
var val848: T?
var val849: T?
var val850: T?
var val851: T?
var val852: T?
var val853: T?
var val854: T?
var val855: T?
var val856: T?
var val857: T?
var val858: T?
var val859: T?
var val860: T?
var val861: T?
var val862: T?
var val863: T?
var val864: T?
var val865: T?
var val866: T?
var val867: T?
var val868: T?
var val869: T?
var val870: T?
var val871: T?
var val872: T?
var val873: T?
var val874: T?
var val875: T?
var val876: T?
var val877: T?
var val878: T?
var val879: T?
var val880: T?
var val881: T?
var val882: T?
var val883: T?
var val884: T?
var val885: T?
var val886: T?
var val887: T?
var val888: T?
var val889: T?
var val890: T?
var val891: T?
var val892: T?
var val893: T?
var val894: T?
var val895: T?
var val896: T?
var val897: T?
var val898: T?
var val899: T?
var val900: T?
var val901: T?
var val902: T?
var val903: T?
var val904: T?
var val905: T?
var val906: T?
var val907: T?
var val908: T?
var val909: T?
var val910: T?
var val911: T?
var val912: T?
var val913: T?
var val914: T?
var val915: T?
var val916: T?
var val917: T?
var val918: T?
var val919: T?
var val920: T?
var val921: T?
var val922: T?
var val923: T?
var val924: T?
var val925: T?
var val926: T?
var val927: T?
var val928: T?
var val929: T?
var val930: T?
var val931: T?
var val932: T?
var val933: T?
var val934: T?
var val935: T?
var val936: T?
var val937: T?
var val938: T?
var val939: T?
var val940: T?
var val941: T?
var val942: T?
var val943: T?
var val944: T?
var val945: T?
var val946: T?
var val947: T?
var val948: T?
var val949: T?
var val950: T?
var val951: T?
var val952: T?
var val953: T?
var val954: T?
var val955: T?
var val956: T?
var val957: T?
var val958: T?
var val959: T?
var val960: T?
var val961: T?
var val962: T?
var val963: T?
var val964: T?
var val965: T?
var val966: T?
var val967: T?
var val968: T?
var val969: T?
var val970: T?
var val971: T?
var val972: T?
var val973: T?
var val974: T?
var val975: T?
var val976: T?
var val977: T?
var val978: T?
var val979: T?
var val980: T?
var val981: T?
var val982: T?
var val983: T?
var val984: T?
var val985: T?
var val986: T?
var val987: T?
var val988: T?
var val989: T?
var val990: T?
var val991: T?
var val992: T?
var val993: T?
var val994: T?
var val995: T?
var val996: T?
var val997: T?
var val998: T?
var val999: T?
var val1000: T?
var val1001: T?
var val1002: T?
var val1003: T?
var val1004: T?
var val1005: T?
var val1006: T?
var val1007: T?
var val1008: T?
var val1009: T?
var val1010: T?
var val1011: T?
var val1012: T?
var val1013: T?
var val1014: T?
var val1015: T?
var val1016: T?
var val1017: T?
var val1018: T?
var val1019: T?
var val1020: T?
var val1021: T?
var val1022: T?
var val1023: T?
}
class Sub<T>: Super<T> {}
struct S1000 {}
struct S1001 {}
struct S1002 {}
struct S1003 {}
struct S1004 {}
struct S1005 {}
struct S1006 {}
struct S1007 {}
struct S1008 {}
struct S1009 {}
struct S1010 {}
struct S1011 {}
struct S1012 {}
struct S1013 {}
struct S1014 {}
struct S1015 {}
struct S1016 {}
struct S1017 {}
struct S1018 {}
struct S1019 {}
struct S1020 {}
struct S1021 {}
struct S1022 {}
struct S1023 {}
struct S1024 {}
struct S1025 {}
struct S1026 {}
struct S1027 {}
struct S1028 {}
struct S1029 {}
struct S1030 {}
struct S1031 {}
struct S1032 {}
struct S1033 {}
struct S1034 {}
struct S1035 {}
struct S1036 {}
struct S1037 {}
struct S1038 {}
struct S1039 {}
struct S1040 {}
struct S1041 {}
struct S1042 {}
struct S1043 {}
struct S1044 {}
struct S1045 {}
struct S1046 {}
struct S1047 {}
struct S1048 {}
struct S1049 {}
struct S1050 {}
struct S1051 {}
struct S1052 {}
struct S1053 {}
struct S1054 {}
struct S1055 {}
struct S1056 {}
struct S1057 {}
struct S1058 {}
struct S1059 {}
struct S1060 {}
struct S1061 {}
struct S1062 {}
struct S1063 {}
struct S1064 {}
struct S1065 {}
struct S1066 {}
struct S1067 {}
struct S1068 {}
struct S1069 {}
struct S1070 {}
struct S1071 {}
struct S1072 {}
struct S1073 {}
struct S1074 {}
struct S1075 {}
struct S1076 {}
struct S1077 {}
struct S1078 {}
struct S1079 {}
struct S1080 {}
struct S1081 {}
struct S1082 {}
struct S1083 {}
struct S1084 {}
struct S1085 {}
struct S1086 {}
struct S1087 {}
struct S1088 {}
struct S1089 {}
struct S1090 {}
struct S1091 {}
struct S1092 {}
struct S1093 {}
struct S1094 {}
struct S1095 {}
struct S1096 {}
struct S1097 {}
struct S1098 {}
struct S1099 {}
struct S1100 {}
struct S1101 {}
struct S1102 {}
struct S1103 {}
struct S1104 {}
struct S1105 {}
struct S1106 {}
struct S1107 {}
struct S1108 {}
struct S1109 {}
struct S1110 {}
struct S1111 {}
struct S1112 {}
struct S1113 {}
struct S1114 {}
struct S1115 {}
struct S1116 {}
struct S1117 {}
struct S1118 {}
struct S1119 {}
struct S1120 {}
struct S1121 {}
struct S1122 {}
struct S1123 {}
struct S1124 {}
struct S1125 {}
struct S1126 {}
struct S1127 {}
struct S1128 {}
struct S1129 {}
struct S1130 {}
struct S1131 {}
struct S1132 {}
struct S1133 {}
struct S1134 {}
struct S1135 {}
struct S1136 {}
struct S1137 {}
struct S1138 {}
struct S1139 {}
struct S1140 {}
struct S1141 {}
struct S1142 {}
struct S1143 {}
struct S1144 {}
struct S1145 {}
struct S1146 {}
struct S1147 {}
struct S1148 {}
struct S1149 {}
struct S1150 {}
struct S1151 {}
struct S1152 {}
struct S1153 {}
struct S1154 {}
struct S1155 {}
struct S1156 {}
struct S1157 {}
struct S1158 {}
struct S1159 {}
struct S1160 {}
struct S1161 {}
struct S1162 {}
struct S1163 {}
struct S1164 {}
struct S1165 {}
struct S1166 {}
struct S1167 {}
struct S1168 {}
struct S1169 {}
struct S1170 {}
struct S1171 {}
struct S1172 {}
struct S1173 {}
struct S1174 {}
struct S1175 {}
struct S1176 {}
struct S1177 {}
struct S1178 {}
struct S1179 {}
struct S1180 {}
struct S1181 {}
struct S1182 {}
struct S1183 {}
struct S1184 {}
struct S1185 {}
struct S1186 {}
struct S1187 {}
struct S1188 {}
struct S1189 {}
struct S1190 {}
struct S1191 {}
struct S1192 {}
struct S1193 {}
struct S1194 {}
struct S1195 {}
struct S1196 {}
struct S1197 {}
struct S1198 {}
struct S1199 {}
struct S1200 {}
struct S1201 {}
struct S1202 {}
struct S1203 {}
struct S1204 {}
struct S1205 {}
struct S1206 {}
struct S1207 {}
struct S1208 {}
struct S1209 {}
struct S1210 {}
struct S1211 {}
struct S1212 {}
struct S1213 {}
struct S1214 {}
struct S1215 {}
struct S1216 {}
struct S1217 {}
struct S1218 {}
struct S1219 {}
struct S1220 {}
struct S1221 {}
struct S1222 {}
struct S1223 {}
struct S1224 {}
struct S1225 {}
struct S1226 {}
struct S1227 {}
struct S1228 {}
struct S1229 {}
struct S1230 {}
struct S1231 {}
struct S1232 {}
struct S1233 {}
struct S1234 {}
struct S1235 {}
struct S1236 {}
struct S1237 {}
struct S1238 {}
struct S1239 {}
struct S1240 {}
struct S1241 {}
struct S1242 {}
struct S1243 {}
struct S1244 {}
struct S1245 {}
struct S1246 {}
struct S1247 {}
struct S1248 {}
struct S1249 {}
struct S1250 {}
struct S1251 {}
struct S1252 {}
struct S1253 {}
struct S1254 {}
struct S1255 {}
struct S1256 {}
struct S1257 {}
struct S1258 {}
struct S1259 {}
struct S1260 {}
struct S1261 {}
struct S1262 {}
struct S1263 {}
struct S1264 {}
struct S1265 {}
struct S1266 {}
struct S1267 {}
struct S1268 {}
struct S1269 {}
struct S1270 {}
struct S1271 {}
struct S1272 {}
struct S1273 {}
struct S1274 {}
struct S1275 {}
struct S1276 {}
struct S1277 {}
struct S1278 {}
struct S1279 {}
struct S1280 {}
struct S1281 {}
struct S1282 {}
struct S1283 {}
struct S1284 {}
struct S1285 {}
struct S1286 {}
struct S1287 {}
struct S1288 {}
struct S1289 {}
struct S1290 {}
struct S1291 {}
struct S1292 {}
struct S1293 {}
struct S1294 {}
struct S1295 {}
struct S1296 {}
struct S1297 {}
struct S1298 {}
struct S1299 {}
struct S1300 {}
struct S1301 {}
struct S1302 {}
struct S1303 {}
struct S1304 {}
struct S1305 {}
struct S1306 {}
struct S1307 {}
struct S1308 {}
struct S1309 {}
struct S1310 {}
struct S1311 {}
struct S1312 {}
struct S1313 {}
struct S1314 {}
struct S1315 {}
struct S1316 {}
struct S1317 {}
struct S1318 {}
struct S1319 {}
struct S1320 {}
struct S1321 {}
struct S1322 {}
struct S1323 {}
struct S1324 {}
struct S1325 {}
struct S1326 {}
struct S1327 {}
struct S1328 {}
struct S1329 {}
struct S1330 {}
struct S1331 {}
struct S1332 {}
struct S1333 {}
struct S1334 {}
struct S1335 {}
struct S1336 {}
struct S1337 {}
struct S1338 {}
struct S1339 {}
struct S1340 {}
struct S1341 {}
struct S1342 {}
struct S1343 {}
struct S1344 {}
struct S1345 {}
struct S1346 {}
struct S1347 {}
struct S1348 {}
struct S1349 {}
struct S1350 {}
struct S1351 {}
struct S1352 {}
struct S1353 {}
struct S1354 {}
struct S1355 {}
struct S1356 {}
struct S1357 {}
struct S1358 {}
struct S1359 {}
struct S1360 {}
struct S1361 {}
struct S1362 {}
struct S1363 {}
struct S1364 {}
struct S1365 {}
struct S1366 {}
struct S1367 {}
struct S1368 {}
struct S1369 {}
struct S1370 {}
struct S1371 {}
struct S1372 {}
struct S1373 {}
struct S1374 {}
struct S1375 {}
struct S1376 {}
struct S1377 {}
struct S1378 {}
struct S1379 {}
struct S1380 {}
struct S1381 {}
struct S1382 {}
struct S1383 {}
struct S1384 {}
struct S1385 {}
struct S1386 {}
struct S1387 {}
struct S1388 {}
struct S1389 {}
struct S1390 {}
struct S1391 {}
struct S1392 {}
struct S1393 {}
struct S1394 {}
struct S1395 {}
struct S1396 {}
struct S1397 {}
struct S1398 {}
struct S1399 {}
struct S1400 {}
struct S1401 {}
struct S1402 {}
struct S1403 {}
struct S1404 {}
struct S1405 {}
struct S1406 {}
struct S1407 {}
struct S1408 {}
struct S1409 {}
struct S1410 {}
struct S1411 {}
struct S1412 {}
struct S1413 {}
struct S1414 {}
struct S1415 {}
struct S1416 {}
struct S1417 {}
struct S1418 {}
struct S1419 {}
struct S1420 {}
struct S1421 {}
struct S1422 {}
struct S1423 {}
struct S1424 {}
struct S1425 {}
struct S1426 {}
struct S1427 {}
struct S1428 {}
struct S1429 {}
struct S1430 {}
struct S1431 {}
struct S1432 {}
struct S1433 {}
struct S1434 {}
struct S1435 {}
struct S1436 {}
struct S1437 {}
struct S1438 {}
struct S1439 {}
struct S1440 {}
struct S1441 {}
struct S1442 {}
struct S1443 {}
struct S1444 {}
struct S1445 {}
struct S1446 {}
struct S1447 {}
struct S1448 {}
struct S1449 {}
struct S1450 {}
struct S1451 {}
struct S1452 {}
struct S1453 {}
struct S1454 {}
struct S1455 {}
struct S1456 {}
struct S1457 {}
struct S1458 {}
struct S1459 {}
struct S1460 {}
struct S1461 {}
struct S1462 {}
struct S1463 {}
struct S1464 {}
struct S1465 {}
struct S1466 {}
struct S1467 {}
struct S1468 {}
struct S1469 {}
struct S1470 {}
struct S1471 {}
struct S1472 {}
struct S1473 {}
struct S1474 {}
struct S1475 {}
struct S1476 {}
struct S1477 {}
struct S1478 {}
struct S1479 {}
struct S1480 {}
struct S1481 {}
struct S1482 {}
struct S1483 {}
struct S1484 {}
struct S1485 {}
struct S1486 {}
struct S1487 {}
struct S1488 {}
struct S1489 {}
struct S1490 {}
struct S1491 {}
struct S1492 {}
struct S1493 {}
struct S1494 {}
struct S1495 {}
struct S1496 {}
struct S1497 {}
struct S1498 {}
struct S1499 {}
struct S1500 {}
struct S1501 {}
struct S1502 {}
struct S1503 {}
struct S1504 {}
struct S1505 {}
struct S1506 {}
struct S1507 {}
struct S1508 {}
struct S1509 {}
struct S1510 {}
struct S1511 {}
struct S1512 {}
struct S1513 {}
struct S1514 {}
struct S1515 {}
struct S1516 {}
struct S1517 {}
struct S1518 {}
struct S1519 {}
struct S1520 {}
struct S1521 {}
struct S1522 {}
struct S1523 {}
struct S1524 {}
struct S1525 {}
struct S1526 {}
struct S1527 {}
struct S1528 {}
struct S1529 {}
struct S1530 {}
struct S1531 {}
struct S1532 {}
struct S1533 {}
struct S1534 {}
struct S1535 {}
struct S1536 {}
struct S1537 {}
struct S1538 {}
struct S1539 {}
struct S1540 {}
struct S1541 {}
struct S1542 {}
struct S1543 {}
struct S1544 {}
struct S1545 {}
struct S1546 {}
struct S1547 {}
struct S1548 {}
struct S1549 {}
struct S1550 {}
struct S1551 {}
struct S1552 {}
struct S1553 {}
struct S1554 {}
struct S1555 {}
struct S1556 {}
struct S1557 {}
struct S1558 {}
struct S1559 {}
struct S1560 {}
struct S1561 {}
struct S1562 {}
struct S1563 {}
struct S1564 {}
struct S1565 {}
struct S1566 {}
struct S1567 {}
struct S1568 {}
struct S1569 {}
struct S1570 {}
struct S1571 {}
struct S1572 {}
struct S1573 {}
struct S1574 {}
struct S1575 {}
struct S1576 {}
struct S1577 {}
struct S1578 {}
struct S1579 {}
struct S1580 {}
struct S1581 {}
struct S1582 {}
struct S1583 {}
struct S1584 {}
struct S1585 {}
struct S1586 {}
struct S1587 {}
struct S1588 {}
struct S1589 {}
struct S1590 {}
struct S1591 {}
struct S1592 {}
struct S1593 {}
struct S1594 {}
struct S1595 {}
struct S1596 {}
struct S1597 {}
struct S1598 {}
struct S1599 {}
struct S1600 {}
struct S1601 {}
struct S1602 {}
struct S1603 {}
struct S1604 {}
struct S1605 {}
struct S1606 {}
struct S1607 {}
struct S1608 {}
struct S1609 {}
struct S1610 {}
struct S1611 {}
struct S1612 {}
struct S1613 {}
struct S1614 {}
struct S1615 {}
struct S1616 {}
struct S1617 {}
struct S1618 {}
struct S1619 {}
struct S1620 {}
struct S1621 {}
struct S1622 {}
struct S1623 {}
struct S1624 {}
struct S1625 {}
struct S1626 {}
struct S1627 {}
struct S1628 {}
struct S1629 {}
struct S1630 {}
struct S1631 {}
struct S1632 {}
struct S1633 {}
struct S1634 {}
struct S1635 {}
struct S1636 {}
struct S1637 {}
struct S1638 {}
struct S1639 {}
struct S1640 {}
struct S1641 {}
struct S1642 {}
struct S1643 {}
struct S1644 {}
struct S1645 {}
struct S1646 {}
struct S1647 {}
struct S1648 {}
struct S1649 {}
struct S1650 {}
struct S1651 {}
struct S1652 {}
struct S1653 {}
struct S1654 {}
struct S1655 {}
struct S1656 {}
struct S1657 {}
struct S1658 {}
struct S1659 {}
struct S1660 {}
struct S1661 {}
struct S1662 {}
struct S1663 {}
struct S1664 {}
struct S1665 {}
struct S1666 {}
struct S1667 {}
struct S1668 {}
struct S1669 {}
struct S1670 {}
struct S1671 {}
struct S1672 {}
struct S1673 {}
struct S1674 {}
struct S1675 {}
struct S1676 {}
struct S1677 {}
struct S1678 {}
struct S1679 {}
struct S1680 {}
struct S1681 {}
struct S1682 {}
struct S1683 {}
struct S1684 {}
struct S1685 {}
struct S1686 {}
struct S1687 {}
struct S1688 {}
struct S1689 {}
struct S1690 {}
struct S1691 {}
struct S1692 {}
struct S1693 {}
struct S1694 {}
struct S1695 {}
struct S1696 {}
struct S1697 {}
struct S1698 {}
struct S1699 {}
struct S1700 {}
struct S1701 {}
struct S1702 {}
struct S1703 {}
struct S1704 {}
struct S1705 {}
struct S1706 {}
struct S1707 {}
struct S1708 {}
struct S1709 {}
struct S1710 {}
struct S1711 {}
struct S1712 {}
struct S1713 {}
struct S1714 {}
struct S1715 {}
struct S1716 {}
struct S1717 {}
struct S1718 {}
struct S1719 {}
struct S1720 {}
struct S1721 {}
struct S1722 {}
struct S1723 {}
struct S1724 {}
struct S1725 {}
struct S1726 {}
struct S1727 {}
struct S1728 {}
struct S1729 {}
struct S1730 {}
struct S1731 {}
struct S1732 {}
struct S1733 {}
struct S1734 {}
struct S1735 {}
struct S1736 {}
struct S1737 {}
struct S1738 {}
struct S1739 {}
struct S1740 {}
struct S1741 {}
struct S1742 {}
struct S1743 {}
struct S1744 {}
struct S1745 {}
struct S1746 {}
struct S1747 {}
struct S1748 {}
struct S1749 {}
struct S1750 {}
struct S1751 {}
struct S1752 {}
struct S1753 {}
struct S1754 {}
struct S1755 {}
struct S1756 {}
struct S1757 {}
struct S1758 {}
struct S1759 {}
struct S1760 {}
struct S1761 {}
struct S1762 {}
struct S1763 {}
struct S1764 {}
struct S1765 {}
struct S1766 {}
struct S1767 {}
struct S1768 {}
struct S1769 {}
struct S1770 {}
struct S1771 {}
struct S1772 {}
struct S1773 {}
struct S1774 {}
struct S1775 {}
struct S1776 {}
struct S1777 {}
struct S1778 {}
struct S1779 {}
struct S1780 {}
struct S1781 {}
struct S1782 {}
struct S1783 {}
struct S1784 {}
struct S1785 {}
struct S1786 {}
struct S1787 {}
struct S1788 {}
struct S1789 {}
struct S1790 {}
struct S1791 {}
struct S1792 {}
struct S1793 {}
struct S1794 {}
struct S1795 {}
struct S1796 {}
struct S1797 {}
struct S1798 {}
struct S1799 {}
struct S1800 {}
struct S1801 {}
struct S1802 {}
struct S1803 {}
struct S1804 {}
struct S1805 {}
struct S1806 {}
struct S1807 {}
struct S1808 {}
struct S1809 {}
struct S1810 {}
struct S1811 {}
struct S1812 {}
struct S1813 {}
struct S1814 {}
struct S1815 {}
struct S1816 {}
struct S1817 {}
struct S1818 {}
struct S1819 {}
struct S1820 {}
struct S1821 {}
struct S1822 {}
struct S1823 {}
struct S1824 {}
struct S1825 {}
struct S1826 {}
struct S1827 {}
struct S1828 {}
struct S1829 {}
struct S1830 {}
struct S1831 {}
struct S1832 {}
struct S1833 {}
struct S1834 {}
struct S1835 {}
struct S1836 {}
struct S1837 {}
struct S1838 {}
struct S1839 {}
struct S1840 {}
struct S1841 {}
struct S1842 {}
struct S1843 {}
struct S1844 {}
struct S1845 {}
struct S1846 {}
struct S1847 {}
struct S1848 {}
struct S1849 {}
struct S1850 {}
struct S1851 {}
struct S1852 {}
struct S1853 {}
struct S1854 {}
struct S1855 {}
struct S1856 {}
struct S1857 {}
struct S1858 {}
struct S1859 {}
struct S1860 {}
struct S1861 {}
struct S1862 {}
struct S1863 {}
struct S1864 {}
struct S1865 {}
struct S1866 {}
struct S1867 {}
struct S1868 {}
struct S1869 {}
struct S1870 {}
struct S1871 {}
struct S1872 {}
struct S1873 {}
struct S1874 {}
struct S1875 {}
struct S1876 {}
struct S1877 {}
struct S1878 {}
struct S1879 {}
struct S1880 {}
struct S1881 {}
struct S1882 {}
struct S1883 {}
struct S1884 {}
struct S1885 {}
struct S1886 {}
struct S1887 {}
struct S1888 {}
struct S1889 {}
struct S1890 {}
struct S1891 {}
struct S1892 {}
struct S1893 {}
struct S1894 {}
struct S1895 {}
struct S1896 {}
struct S1897 {}
struct S1898 {}
struct S1899 {}
struct S1900 {}
struct S1901 {}
struct S1902 {}
struct S1903 {}
struct S1904 {}
struct S1905 {}
struct S1906 {}
struct S1907 {}
struct S1908 {}
struct S1909 {}
struct S1910 {}
struct S1911 {}
struct S1912 {}
struct S1913 {}
struct S1914 {}
struct S1915 {}
struct S1916 {}
struct S1917 {}
struct S1918 {}
struct S1919 {}
struct S1920 {}
struct S1921 {}
struct S1922 {}
struct S1923 {}
struct S1924 {}
struct S1925 {}
struct S1926 {}
struct S1927 {}
struct S1928 {}
struct S1929 {}
struct S1930 {}
struct S1931 {}
struct S1932 {}
struct S1933 {}
struct S1934 {}
struct S1935 {}
struct S1936 {}
struct S1937 {}
struct S1938 {}
struct S1939 {}
struct S1940 {}
struct S1941 {}
struct S1942 {}
struct S1943 {}
struct S1944 {}
struct S1945 {}
struct S1946 {}
struct S1947 {}
struct S1948 {}
struct S1949 {}
struct S1950 {}
struct S1951 {}
struct S1952 {}
struct S1953 {}
struct S1954 {}
struct S1955 {}
struct S1956 {}
struct S1957 {}
struct S1958 {}
struct S1959 {}
struct S1960 {}
struct S1961 {}
struct S1962 {}
struct S1963 {}
struct S1964 {}
struct S1965 {}
struct S1966 {}
struct S1967 {}
struct S1968 {}
struct S1969 {}
struct S1970 {}
struct S1971 {}
struct S1972 {}
struct S1973 {}
struct S1974 {}
struct S1975 {}
struct S1976 {}
struct S1977 {}
struct S1978 {}
struct S1979 {}
struct S1980 {}
struct S1981 {}
struct S1982 {}
struct S1983 {}
struct S1984 {}
struct S1985 {}
struct S1986 {}
struct S1987 {}
struct S1988 {}
struct S1989 {}
struct S1990 {}
struct S1991 {}
struct S1992 {}
struct S1993 {}
struct S1994 {}
struct S1995 {}
struct S1996 {}
struct S1997 {}
struct S1998 {}
struct S1999 {}
ConcurrentTypeByNameTests.test("concurrent _typeByName") {
if #available(SwiftStdlib 5.1, *) {
func printTypeByName() {
for n in 1000..<2000 {
let name = "4main14GenericWrapperCyAA3SubCyAA5S\(n)VGG"
print(String(describing: _typeByName(name)! as Any))
}
}
let (createRet1, tid1) = _stdlib_thread_create_block(printTypeByName, ())
let (createRet2, tid2) = _stdlib_thread_create_block(printTypeByName, ())
expectEqual(0, createRet1)
expectEqual(0, createRet2)
_ = _stdlib_thread_join(tid1!, Void.self)
_ = _stdlib_thread_join(tid2!, Void.self)
}
}
runAllTests()
| apache-2.0 | 5b5d1c067b951d2cf357bbcb44c2b031 | 15.746009 | 80 | 0.637574 | 2.672896 | false | false | false | false |
hgl888/firefox-ios | Utils/Extensions/StringExtensions.swift | 30 | 3168 | /* 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
public extension String {
public func contains(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
return self.rangeOfString(other) != nil
}
public func startsWith(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.rangeOfString(other,
options: NSStringCompareOptions.AnchoredSearch) {
return range.startIndex == self.startIndex
}
return false
}
public func endsWith(other: String) -> Bool {
// rangeOfString returns nil if other is empty, destroying the analogy with (ordered) sets.
if other.isEmpty {
return true
}
if let range = self.rangeOfString(other,
options: [NSStringCompareOptions.AnchoredSearch, NSStringCompareOptions.BackwardsSearch]) {
return range.endIndex == self.endIndex
}
return false
}
func escape() -> String {
let raw: NSString = self
let str = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
raw,
"[].",":/?&=;+!@#$()',*",
CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
return str as String
}
func unescape() -> String {
let raw: NSString = self
let str = CFURLCreateStringByReplacingPercentEscapes(kCFAllocatorDefault, raw, "[].")
return str as String
}
/**
Ellipsizes a String only if it's longer than `maxLength`
"ABCDEF".ellipsize(4)
// "AB…EF"
:param: maxLength The maximum length of the String.
:returns: A String with `maxLength` characters or less
*/
func ellipsize(let maxLength maxLength: Int) -> String {
if (maxLength >= 2) && (self.characters.count > maxLength) {
let index1 = self.startIndex.advancedBy((maxLength + 1) / 2) // `+ 1` has the same effect as an int ceil
let index2 = self.endIndex.advancedBy(maxLength / -2)
return self.substringToIndex(index1) + "…\u{2060}" + self.substringFromIndex(index2)
}
return self
}
private var stringWithAdditionalEscaping: String {
return self.stringByReplacingOccurrencesOfString("|", withString: "%7C", options: NSStringCompareOptions(), range: nil)
}
public var asURL: NSURL? {
// Firefox and NSURL disagree about the valid contents of a URL.
// Let's escape | for them.
// We'd love to use one of the more sophisticated CFURL* or NSString.* functions, but
// none seem to be quite suitable.
return NSURL(string: self) ??
NSURL(string: self.stringWithAdditionalEscaping)
}
}
| mpl-2.0 | 06d242f44ea5e4788783ca3dcaccfceb | 35.367816 | 127 | 0.624842 | 4.772247 | false | false | false | false |
apple/swift | test/AutoDiff/Sema/DerivedConformances/derived_differentiable.swift | 2 | 7920 | // RUN: %target-swift-frontend -print-ast-decl %s | %FileCheck %s --check-prefix=CHECK-AST
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s --check-prefix=CHECK-SIL
import _Differentiation
struct GenericTangentVectorMember<T: Differentiable>: Differentiable,
AdditiveArithmetic
{
var x: T.TangentVector
}
// CHECK-AST-LABEL: internal struct GenericTangentVectorMember<T> : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}} where T : Differentiable
// CHECK-AST: internal var x: T.TangentVector
// CHECK-AST: internal static func + (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T>
// CHECK-AST: internal static func - (lhs: GenericTangentVectorMember<T>, rhs: GenericTangentVectorMember<T>) -> GenericTangentVectorMember<T>
// CHECK-AST: @_implements(Equatable, ==(_:_:)) internal static func __derived_struct_equals(_ a: GenericTangentVectorMember<T>, _ b: GenericTangentVectorMember<T>) -> Bool
// CHECK-AST: internal typealias TangentVector = GenericTangentVectorMember<T>
// CHECK-AST: internal init(x: T.TangentVector)
// CHECK-AST: internal static var zero: GenericTangentVectorMember<T> { get }
public struct ConditionallyDifferentiable<T> {
public var x: T
}
extension ConditionallyDifferentiable: Differentiable where T: Differentiable {}
// CHECK-AST-LABEL: public struct ConditionallyDifferentiable<T> {
// CHECK-AST: @differentiable(reverse, wrt: self where T : Differentiable)
// CHECK-AST: public var x: T
// CHECK-AST: internal init(x: T)
// CHECK-AST: }
// Verify that `TangentVector` is not synthesized to be `Self` for
// `AdditiveArithmetic`-conforming classes.
final class AdditiveArithmeticClass<T: AdditiveArithmetic & Differentiable>: AdditiveArithmetic,
Differentiable
{
var x, y: T
init(x: T, y: T) {
self.x = x
self.y = y
}
// Dummy `AdditiveArithmetic` requirements.
static func == (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Bool
{
fatalError()
}
static var zero: AdditiveArithmeticClass {
fatalError()
}
static func + (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Self
{
fatalError()
}
static func - (lhs: AdditiveArithmeticClass, rhs: AdditiveArithmeticClass)
-> Self
{
fatalError()
}
}
// CHECK-AST-LABEL: final internal class AdditiveArithmeticClass<T> : AdditiveArithmetic, Differentiable where T : AdditiveArithmetic, T : Differentiable {
// CHECK-AST: final internal var x: T, y: T
// CHECK-AST: internal struct TangentVector : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}}
// CHECK-AST: }
@frozen
public struct FrozenStruct: Differentiable {}
// CHECK-AST-LABEL: @frozen public struct FrozenStruct : Differentiable {
// CHECK-AST: @frozen public struct TangentVector : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}} {
// CHECK-AST: internal init()
@usableFromInline
struct UsableFromInlineStruct: Differentiable {}
// CHECK-AST-LABEL: @usableFromInline
// CHECK-AST: struct UsableFromInlineStruct : Differentiable {
// CHECK-AST: @usableFromInline
// CHECK-AST: struct TangentVector : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}} {
// CHECK-AST: internal init()
// Test property wrappers.
@propertyWrapper
struct Wrapper<Value> {
var wrappedValue: Value
}
struct WrappedPropertiesStruct: Differentiable {
@Wrapper @Wrapper var x: Float
@Wrapper var y: Float
var z: Float
@noDerivative @Wrapper var nondiff: Float
}
// CHECK-AST-LABEL: internal struct WrappedPropertiesStruct : Differentiable {
// CHECK-AST: internal struct TangentVector : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}} {
// CHECK-AST: internal var x: Float.TangentVector
// CHECK-AST: internal var y: Float.TangentVector
// CHECK-AST: internal var z: Float.TangentVector
// CHECK-AST: }
// CHECK-AST: }
class WrappedPropertiesClass: Differentiable {
@Wrapper @Wrapper var x: Float = 1
@Wrapper var y: Float = 2
var z: Float = 3
@noDerivative @Wrapper var noDeriv: Float = 4
}
// CHECK-AST-LABEL: internal class WrappedPropertiesClass : Differentiable {
// CHECK-AST: internal struct TangentVector : {{(Differentiable, AdditiveArithmetic)|(AdditiveArithmetic, Differentiable)}} {
// CHECK-AST: internal var x: Float.TangentVector
// CHECK-AST: internal var y: Float.TangentVector
// CHECK-AST: internal var z: Float.TangentVector
// CHECK-AST: }
// CHECK-AST: }
protocol TangentVectorMustBeEncodable: Differentiable where TangentVector: Encodable {}
struct AutoDeriveEncodableTV1: TangentVectorMustBeEncodable {
var x: Float
}
// CHECK-AST-LABEL: internal struct AutoDeriveEncodableTV1 : TangentVectorMustBeEncodable {
// CHECK-AST: internal struct TangentVector : {{(Encodable, Differentiable, AdditiveArithmetic)|(Encodable, AdditiveArithmetic, Differentiable)|(Differentiable, Encodable, AdditiveArithmetic)|(AdditiveArithmetic, Encodable, Differentiable)|(Differentiable, AdditiveArithmetic, Encodable)|(AdditiveArithmetic, Differentiable, Encodable)}} {
struct AutoDeriveEncodableTV2 {
var x: Float
}
extension AutoDeriveEncodableTV2: TangentVectorMustBeEncodable {}
// CHECK-AST-LABEL: extension AutoDeriveEncodableTV2 : TangentVectorMustBeEncodable {
// CHECK-AST: internal struct TangentVector : {{(Encodable, Differentiable, AdditiveArithmetic)|(Encodable, AdditiveArithmetic, Differentiable)|(Differentiable, Encodable, AdditiveArithmetic)|(AdditiveArithmetic, Encodable, Differentiable)|(Differentiable, AdditiveArithmetic, Encodable)|(AdditiveArithmetic, Differentiable, Encodable)}} {
protocol TangentVectorP: Differentiable {
var requirement: Int { get }
}
protocol TangentVectorConstrained: Differentiable where TangentVector: TangentVectorP {}
struct StructWithTangentVectorConstrained: TangentVectorConstrained {
var x: Float
}
// `extension StructWithTangentVectorConstrained.TangentVector: TangentVectorP` gives
// "error: type 'StructWithTangentVectorConstrained.TangentVector' does not conform to protocol 'TangentVectorP'",
// maybe because it typechecks the conformance before seeing the extension. But this roundabout way
// of stating the same thing works.
extension TangentVectorP where Self == StructWithTangentVectorConstrained.TangentVector {
var requirement: Int { 42 }
}
// CHECK-AST-LABEL: internal struct StructWithTangentVectorConstrained : TangentVectorConstrained {
// CHECK-AST: internal struct TangentVector : {{(TangentVectorP, Differentiable, AdditiveArithmetic)|(TangentVectorP, AdditiveArithmetic, Differentiable)|(Differentiable, TangentVectorP, AdditiveArithmetic)|(AdditiveArithmetic, TangentVectorP, Differentiable)|(Differentiable, AdditiveArithmetic, TangentVectorP)|(AdditiveArithmetic, Differentiable, TangentVectorP)}} {
// https://github.com/apple/swift/issues/56601
public struct S1: Differentiable {
public var simd: [Float]
public var scalar: Float
}
// CHECK-AST-LABEL: public struct S1 : Differentiable {
// CHECK-AST: public var simd: [Float]
// CHECK-AST: public var scalar: Float
// CHECK-AST: struct TangentVector : AdditiveArithmetic, Differentiable {
// CHECK-AST: var simd: Array<Float>.TangentVector
// CHECK-AST: var scalar: Float
// CHECK-SIL-LABEL: public struct S1 : Differentiable {
// CHECK-SIL: @differentiable(reverse, wrt: self)
// CHECK-SIL: @_hasStorage public var simd: [Float] { get set }
// CHECK-SIL: @differentiable(reverse, wrt: self)
// CHECK-SIL: @_hasStorage public var scalar: Float { get set }
// CHECK-SIL: struct TangentVector : AdditiveArithmetic, Differentiable {
// CHECK-SIL: @_hasStorage var simd: Array<Float>.DifferentiableView { get set }
// CHECK-SIL: @_hasStorage var scalar: Float { get set }
| apache-2.0 | a9d884fad69cffe1847a382537a2f432 | 42.516484 | 371 | 0.755682 | 4.47205 | false | false | false | false |
think-dev/MadridBUS | MadridBUS/Source/UI/WelcomeView.swift | 1 | 9630 | import UIKit
import MapKit
enum WelcomeViewMode {
case fullMap(shouldReset: Bool, completionHandler: (()->())?)
case foundNodesAround
case zeroNodesAround
case noLocationPermission
}
protocol WelcomeView: View {
var nodesTableDataSet: [BusGeoNode] { get set }
func updateMap(with location: CLLocation)
func updateNodesTable()
func enable(mode: WelcomeViewMode)
}
class WelcomeViewBase: UIViewController, WelcomeView {
internal var presenter: WelcomePresenter
internal var manualSearch = ManualSearchViewBase()
internal var nodesTable = NodesNearTable()
internal var nodesTableDataSet: [BusGeoNode] = [] {
didSet {
if nodesTableDataSet.count > 0 {
enable(mode: .foundNodesAround)
}
}
}
@IBOutlet weak var locationMap: MKMapView!
@IBOutlet weak var locationMap_heightConstraint: NSLayoutConstraint!
@IBOutlet weak var contentWrapper: UIView!
init(injector: Injector = SwinjectInjectorProvider.injector, nibName: String? = "WelcomeView") {
self.presenter = injector.instanceOf(WelcomePresenter.self)
super.init(nibName: nibName, bundle: nil)
presenter.config(using: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
contentWrapper.backgroundColor = Colors.blue
locationMap.delegate = self
let favsButton = UIBarButtonItem(image: #imageLiteral(resourceName: "Fav").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(didTapFavButton))
let codeButton = UIBarButtonItem(image: #imageLiteral(resourceName: "QRCode").withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(didTapScanCodeButton))
navigationItem.leftBarButtonItem = favsButton
navigationItem.rightBarButtonItem = codeButton
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
title = LocalizedLiteral.localize(using: "WELCOMETITLE")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidDisappear(animated)
presenter.nodesAround(using: 50)
}
func didTapFavButton() {
}
func didTapScanCodeButton() {
}
func updateMap(with location: CLLocation) {
let region = MKCoordinateRegion(center: location.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
locationMap.setRegion(region, animated: true)
locationMap.showsUserLocation = true
}
func updateMapForAnnotations() {
for aNode in nodesTableDataSet {
let annotation = NodeAnnotation()
annotation.coordinate = CLLocationCoordinate2D(latitude: aNode.latitude, longitude: aNode.longitude)
annotation.title = "(\(aNode.id)) \(aNode.name)"
annotation.nodeId = aNode.id
locationMap.addAnnotation(annotation)
}
}
func updateNodesTable() {
enable(mode: .foundNodesAround)
nodesTable.reloadData()
}
func updateNodesTable(with annotation: NodeAnnotation?) {
if let selectedAnnotation = annotation {
let section = nodesTableDataSet.index { (aNode) -> Bool in aNode.id == selectedAnnotation.nodeId }!
nodesTable.reloadData()
nodesTable.scrollToRow(at: IndexPath(item: 0, section: section), at: .middle, animated: true)
}
}
func enable(mode: WelcomeViewMode) {
switch mode {
case .fullMap(let shouldReset, let completionHandler):
locationMap_heightConstraint.constant = 0
animateBottomWrapper(forShowing: false, shouldReset: shouldReset, completionHandler: completionHandler)
case .foundNodesAround:
nodesTable.show(over: contentWrapper, delegating: self, sourcing: self)
view.layoutIfNeeded()
animateBottomWrapper(forShowing: true)
case .zeroNodesAround:
manualSearch.show(over: contentWrapper, mode: .unableToLocate ,delegating: self)
view.layoutIfNeeded()
animateBottomWrapper(forShowing: true)
case .noLocationPermission:
manualSearch.show(over: contentWrapper, mode: .noLocationPermission ,delegating: self)
view.layoutIfNeeded()
animateBottomWrapper(forShowing: true, fullscreen: true)
}
}
private func animateBottomWrapper(forShowing shouldShow: Bool, fullscreen: Bool = false, shouldReset: Bool = false, completionHandler: (() -> ())? = nil) {
if shouldShow {
if fullscreen {
locationMap_heightConstraint.constant = -view.bounds.size.height + 64
} else {
locationMap_heightConstraint.constant = -view.bounds.size.height * 0.5
}
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
}) { (completed) in
if completed {
self.updateMapForAnnotations()
}
}
} else {
locationMap_heightConstraint.constant = 0
UIView.animate(withDuration: 0.5, animations: {
self.view.layoutIfNeeded()
}) { (completed) in
if completed {
self.nodesTable.hide()
self.manualSearch.hide()
if shouldReset {
self.nodesTableDataSet.removeAll()
self.locationMap.removeAnnotations(self.locationMap.annotations)
}
completionHandler?()
}
}
}
}
}
extension WelcomeViewBase: UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return nodesTableDataSet.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 30
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: nodesTable.headerReuseId) as! NodesNearTableHeader
header.titleLabel.text = nodesTableDataSet[section].address
return header
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nodesTableDataSet[section].lines.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: nodesTable.cellReuseId, for: indexPath) as! NodesNearTableCellBase
let model = nodesTableDataSet[indexPath.section].lines[indexPath.row]
if shouldHighlightNodeCell(at: indexPath.section) {
cell.configure(using: model, on: nodesTableDataSet[indexPath.section], highlighted: true)
} else {
cell.configure(using: model, on: nodesTableDataSet[indexPath.section], highlighted: false)
}
return cell
}
private func shouldHighlightNodeCell(at section: Int) -> Bool {
if let currentNodeId = (locationMap.selectedAnnotations.first as? NodeAnnotation)?.nodeId {
if nodesTableDataSet[section].id == currentNodeId {
return true
} else {
return false
}
} else {
return false
}
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath) as! NodesNearTableCell
guard let line = cell.line, let node = cell.node else {
return
}
presenter.nodes(on: line, from: node)
}
}
extension WelcomeViewBase: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if (annotation is MKUserLocation) {
return nil
}
let nodeAnnotation = annotation as! NodeAnnotation
let annotationReuseId = "BusNodeAnnotation"
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: annotationReuseId) as? MKPinAnnotationView
if annotationView == nil {
annotationView = MKPinAnnotationView(annotation: nodeAnnotation, reuseIdentifier: annotationReuseId)
annotationView?.canShowCallout = true
annotationView?.animatesDrop = true
annotationView?.pinTintColor = Colors.blue
} else {
annotationView?.annotation = nodeAnnotation
}
return annotationView
}
func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView) {
updateNodesTable(with: view.annotation as? NodeAnnotation)
}
func mapView(_ mapView: MKMapView, didDeselect view: MKAnnotationView) {
updateNodesTable(with: nil)
}
}
extension WelcomeViewBase: ManualSearchViewDelegate {
func didSelect(radius: Int) {
enable(mode: .fullMap(shouldReset: true, completionHandler: {
self.presenter.nodesAround(using: radius)
}))
}
}
| mit | 253bf1b72bc7f5616f463d9b9f27d5e4 | 36.181467 | 191 | 0.634476 | 5.208221 | false | false | false | false |
haddenkim/dew | Sources/App/Models/Place.swift | 1 | 1208 | //
// Place.swift
// dew
//
// Created by Hadden Kim on 4/26/17.
//
//
import Foundation
import MongoKitten
final class Place {
var id: ObjectId
var name: String
var coordinate: Coordinate
var creatingUser: User
var creationDate: Date
var openHours: [Weekday:OpenHour]
init(id: ObjectId?,
name: String,
coordinate: Coordinate,
creatingUser: User,
creationDate: Date = Date(),
openHours: [Weekday:OpenHour] = [:]) {
self.id = id ?? ObjectId()
self.name = name
self.coordinate = coordinate
self.creatingUser = creatingUser
self.creationDate = creationDate
self.openHours = openHours
}
}
// Type definitions
extension Place {
// Coordinate
// note: choosing not to use CoreLocation.CLLocationCoordinate2d because there's no need for that library
typealias Coordinate = (latitude: Double, longitude: Double)
// Weekday
enum Weekday: Int {
case sun = 1, mon, tue, wed, thu, fri, sat
}
enum OpenHour {
case allDay
case closed
case range(from: Int, to: Int)
}
}
| mit | b9a8edde6e7efae4924f0ea94f374427 | 19.827586 | 109 | 0.586093 | 4.283688 | false | false | false | false |
WhisperSystems/Signal-iOS | Signal/src/ViewControllers/ConversationView/ConversationViewController+OWS.swift | 1 | 4444 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
extension ConversationViewController {
@objc
func ensureIndexPath(of interaction: TSMessage) -> IndexPath? {
return databaseStorage.uiReadReturningResult { transaction in
self.conversationViewModel.ensureLoadWindowContainsInteractionId(interaction.uniqueId,
transaction: transaction)
}
}
}
extension ConversationViewController: MediaPresentationContextProvider {
func mediaPresentationContext(galleryItem: MediaGalleryItem, in coordinateSpace: UICoordinateSpace) -> MediaPresentationContext? {
guard let indexPath = ensureIndexPath(of: galleryItem.message) else {
owsFailDebug("indexPath was unexpectedly nil")
return nil
}
// `indexPath(of:)` can change the load window which requires re-laying out our view
// in order to correctly determine:
// - `indexPathsForVisibleItems`
// - the correct presentation frame
collectionView.layoutIfNeeded()
guard let visibleIndex = collectionView.indexPathsForVisibleItems.firstIndex(of: indexPath) else {
// This could happen if, after presenting media, you navigated within the gallery
// to media not withing the collectionView's visible bounds.
return nil
}
guard let messageCell = collectionView.visibleCells[safe: visibleIndex] as? OWSMessageCell else {
owsFailDebug("messageCell was unexpectedly nil")
return nil
}
guard let mediaView = messageCell.messageBubbleView.albumItemView(forAttachment: galleryItem.attachmentStream) else {
owsFailDebug("itemView was unexpectedly nil")
return nil
}
guard let mediaSuperview = mediaView.superview else {
owsFailDebug("mediaSuperview was unexpectedly nil")
return nil
}
let presentationFrame = coordinateSpace.convert(mediaView.frame, from: mediaSuperview)
// TODO exactly match corner radius for collapsed cells - maybe requires passing a masking view?
return MediaPresentationContext(mediaView: mediaView, presentationFrame: presentationFrame, cornerRadius: kOWSMessageCellCornerRadius_Small * 2)
}
func snapshotOverlayView(in coordinateSpace: UICoordinateSpace) -> (UIView, CGRect)? {
return nil
}
func mediaWillDismiss(toContext: MediaPresentationContext) {
guard let messageBubbleView = toContext.messageBubbleView else { return }
// To avoid flicker when transition view is animated over the message bubble,
// we initially hide the overlaying elements and fade them in.
messageBubbleView.footerView.alpha = 0
messageBubbleView.bodyMediaGradientView?.alpha = 0.0
}
func mediaDidDismiss(toContext: MediaPresentationContext) {
guard let messageBubbleView = toContext.messageBubbleView else { return }
// To avoid flicker when transition view is animated over the message bubble,
// we initially hide the overlaying elements and fade them in.
let duration: TimeInterval = kIsDebuggingMediaPresentationAnimations ? 1.5 : 0.2
UIView.animate(
withDuration: duration,
animations: {
messageBubbleView.footerView.alpha = 1.0
messageBubbleView.bodyMediaGradientView?.alpha = 1.0
})
}
}
private extension MediaPresentationContext {
var messageBubbleView: OWSMessageBubbleView? {
guard let messageBubbleView = mediaView.firstAncestor(ofType: OWSMessageBubbleView.self) else {
owsFailDebug("unexpected mediaView: \(mediaView)")
return nil
}
return messageBubbleView
}
}
extension OWSMessageBubbleView {
func albumItemView(forAttachment attachment: TSAttachmentStream) -> UIView? {
guard let mediaAlbumCellView = bodyMediaView as? MediaAlbumCellView else {
owsFailDebug("mediaAlbumCellView was unexpectedly nil")
return nil
}
guard let albumItemView = (mediaAlbumCellView.itemViews.first { $0.attachment == attachment }) else {
assert(mediaAlbumCellView.moreItemsView != nil)
return mediaAlbumCellView.moreItemsView
}
return albumItemView
}
}
| gpl-3.0 | 11ddd1b62bf2d26ae3a58541dbbe0ed2 | 40.148148 | 152 | 0.680693 | 5.582915 | false | false | false | false |
yourtion/HTTPDNS-Swift | HTTPDNS/HTTPDNS.swift | 1 | 3566 | //
// HTTPDNS.swift
// HTTPDNS-SwiftDemo
//
// Created by YourtionGuo on 12/4/15.
// Copyright © 2015 Yourtion. All rights reserved.
//
import Foundation
/**
* HTTPDNS Result
*/
public struct HTTPDNSResult {
/// IP address
public let ip : String
/// IP array
public let ips : Array<String>
/// Timeout
let timeout : TimeInterval
/// is Cached
public var cached : Bool
/// Description
public var description : String {
return "ip: \(ip) \n ips: \(ips) \n cached: \(cached)"
}
}
/**
HTTPDNS Provider
- DNSPod: [DNSPod](https://www.dnspod.cn/httpdns)
- AliYun: [AliYun](https://help.aliyun.com/product/9173596_30100.html)
*/
public enum Provider {
/// DNSPod
case dnsPod
/// AliYun
case aliYun
/// Google
case google
}
/// HTTPDNS Client
open class HTTPDNS {
fileprivate init() {}
fileprivate var cache = Dictionary<String,HTTPDNSResult>()
fileprivate var DNS = HTTPDNSFactory().getDNSPod()
/// HTTPDNS sharedInstance
open static let sharedInstance = HTTPDNS()
/**
Switch HTTPDNS provider
- parameter provider: DNSPod or AliYun
- parameter key: provider key
*/
open func switchProvider (_ provider:Provider, key:String!) {
self.cleanCache()
switch provider {
case .dnsPod:
DNS = HTTPDNSFactory().getDNSPod()
break
case .aliYun:
DNS = HTTPDNSFactory().getAliYun(key)
break
case .google:
DNS = HTTPDNSFactory().getGoogle()
break
}
}
/**
Get DNS record async
- parameter domain: domain name
- parameter callback: callback block with DNS record
*/
open func getRecord(_ domain: String, callback: @escaping (_ result:HTTPDNSResult?) -> Void) {
let res = getCacheResult(domain)
if (res != nil) {
return callback(res)
}
DNS.requsetRecord(domain, callback: { (res) -> Void in
if let res = res {
callback(self.setCache(domain, record: res))
} else {
return callback(nil)
}
})
}
/**
Get DNS record sync (if not exist in cache return nil)
- parameter domain: domain name
- returns: DSN record
*/
open func getRecordSync(_ domain: String) -> HTTPDNSResult! {
guard let res = getCacheResult(domain) else {
guard let res = self.DNS.requsetRecordSync(domain) else {
return nil
}
return self.setCache(domain, record: res)
}
return res
}
/**
Clean all DNS record cahce
*/
open func cleanCache() {
self.cache.removeAll()
}
func setCache(_ domain: String, record: DNSRecord?) -> HTTPDNSResult? {
guard let _record = record else { return nil }
let timeout = Date().timeIntervalSince1970 + Double(_record.ttl) * 1000
var res = HTTPDNSResult.init(ip: _record.ip, ips: _record.ips, timeout: timeout, cached: true)
self.cache.updateValue(res, forKey:domain)
res.cached = false
return res
}
func getCacheResult(_ domain: String) -> HTTPDNSResult! {
guard let res = self.cache[domain] else {
return nil
}
if (res.timeout <= Date().timeIntervalSince1970){
self.cache.removeValue(forKey: domain)
return nil
}
return res
}
}
| mit | ec72e96a7f04d273c28a4f498206672d | 24.464286 | 102 | 0.5669 | 4.16472 | false | false | false | false |
IngmarStein/swift | stdlib/public/SDK/Intents/INSetDefrosterSettingsInCarIntent.swift | 5 | 934 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
@_exported import Intents
import Foundation
#if os(iOS)
@available(iOS 10.0, *)
extension INSetDefrosterSettingsInCarIntent {
@nonobjc
public convenience init(
enable: Bool? = nil, defroster: INCarDefroster = .unknown
) {
self.init(__enable: enable.map { NSNumber(value: $0) },
defroster: defroster)
}
@nonobjc
public final var enable: Bool? {
return __enable?.boolValue
}
}
#endif
| apache-2.0 | a2e6a01f986a8b1a38cda087a4f222ac | 28.1875 | 80 | 0.586724 | 4.42654 | false | false | false | false |
wufeiyue/FYBannerView | FYBannerView/Classes/View/BannerCollectionView.swift | 2 | 2482 | //
// BannerCollectionView.swift
// FYBannerView
//
// Created by 武飞跃 on 2016/10/2.
//
import UIKit
open class BannerCollectionView: UICollectionView {
weak var bannerDataSource: BannerDataSource?
weak var bannerDisplayDelegate: BannerDisplayDelegate?
weak var bannerLayoutDelegate: BannerLayoutDelegate?
/// 获取当前cell的索引值
var currentIndex: Int {
guard bounds != .zero else { return 0 }
var index: CGFloat = 0.0
guard let layout = collectionViewLayout as? BannerViewLayout else { return 0 }
//FIXME: - 有问题
if case .horizontal = layout.scrollDirection {
index = (contentOffset.x + layout.itemWidth * 0.5) / layout.itemWidth
}
else {
index = (contentOffset.y + layout.itemHeight * 0.5) / layout.itemHeight
}
return max(0, Int(index))
}
func scrollToIndex(index: Int, animated: Bool) {
//FIXME: - 移动的是section 不是item
if visibleCells.isEmpty == false {
scrollToItem(at: IndexPath(item: 0, section: index), at: .init(rawValue: 0), animated: animated)
}
}
func reset() {
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
if case .horizontal = layout.scrollDirection {
contentOffset.x = 0
}
else {
contentOffset.y = 0
}
}
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
scrollsToTop = false
showsVerticalScrollIndicator = false
showsHorizontalScrollIndicator = false
isScrollEnabled = true
isPagingEnabled = true
isDirectionalLockEnabled = true
backgroundColor = .clear
}
public convenience init() {
self.init(frame: .zero, collectionViewLayout: BannerViewLayout())
}
public func setScrollDirection(_ direction: BannerViewScrollDirection) {
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else {
return
}
layout.scrollDirection = direction
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | bb859b7b160e4557569652bbe2798464 | 26.75 | 108 | 0.603194 | 5.274298 | false | false | false | false |
theMatys/myWatch | myWatch/Source/UI/Core/MWTabBar.swift | 1 | 17308 | //
// MWTabBar.swift
// myWatch
//
// Created by Máté on 2017. 07. 13..
// Copyright © 2017. theMatys. All rights reserved.
//
import UIKit
/// The custom-designed tab bar of the application.
@IBDesignable
class MWTabBar: UITabBar
{
//MARK: Inspectables
/// An Interface Builder-compatible representation of the style of the tab bar.
///
/// Whenever it is set, the tab bar will clamp its value, so it does not go out of bounds when instantiating an `MWTabBarStyle`.
///
/// The variable's value is provided as the raw value of the new `MWTabBarStyle` instance.
@IBInspectable var style: Int = 1
{
didSet
{
//Create the instance from the clamped value
_style = MWTabBarStyle(rawValue: MWUtil.clamp(style - 1, min: 0, max: MWTabBarStyle.count))! //It should not be nil, because the raw value is clamped between the minimum (0) and the maximum value (declared in "MWTabBarStyle").
}
}
/// A boolean which indicates whether the tab bar should hide the titles of the items.
///
/// Whenever it is set, the tab bar either hides or restores the titles.
///
/// If the case is the latter, the tab bar will restore the titles from the `titles` array.
@IBInspectable var hidesTitles: Bool = false
{
didSet
{
//Check if the value has changed
if(oldValue != hidesTitles)
{
//Update the titles based on the new value
updateTitles()
}
}
}
//MARK: Instance variables
/// The style of the tab bar.
///
/// Whenever it is set, the tab bar will redraw/update itself to the new look.
///
/// - For more information on the styles, see: `MWTabBarStyle`.
internal var _style: MWTabBarStyle = .system
{
didSet
{
//Update/redraw the tab bar based on the new value.
_init()
}
}
/// The corresponding controls for every item of the tab bar.
///
/// Whenever items are modified, this array modifies as well, but only if the count of the items change.
///
/// The controls held in this array allow the tab bar to have access to the internal view of a tab bar item.
///
/// To retrieve the image view which displays the tab bar item's icon:
///
/// let imageViewIcon: UIImageView = controls[0].imageView
///
/// To retrieve the label which displays the title of the tab bar item:
///
/// let labelTitle: UILabel = controls[0].label
///
private var controls: [MWTabBarControl] = [MWTabBarControl]()
/// Holds the control of the currently selected item.
private var selectedControl: UIControl?
/// An integer whose value indicates whether the next animatable operation of the tab bar should be animated.
///
/// If its value is `0`, the tab bar will not animate at all.
///
/// If its value is `1`, or more, it will animate operations with each operation decreasing its value by 1. If it reaches `0`, the tab bar will not animate.
///
/// Outside of this class, its value may be increased by 1 using modifier `animating()`.
///
/// Example (from a tab bar controller):
///
/// myTabBar.hidesTitles = true //Will not animate
///
/// myTabBar.animating().hidesTitles = true //Will animate
///
/// myTabBar.animating().animating().hidesTitles = true //Will animate
///
/// myTabBar.setItems(newItems, animated: true/false) //Will animate no matter of the "animated" parameter, because in the previous line, 2 animating operations were requested.
///
private var animated: Int = 0
private var shadowLayer: CALayer = CALayer()
private var clippingLayer: CALayer = CALayer()
private var removedSeparatorLine: Bool = false
//MARK: - Inherited initializers from: UITabBar
override init(frame: CGRect)
{
//Supercall
super.init(frame: frame)
//Initialize using custom initializer
_init()
}
required init?(coder aDecoder: NSCoder)
{
//Supercall
super.init(coder: aDecoder)
//Initialize using custom initializer
_init()
}
//MARK: Inherited functions from: UITabBar
override func setItems(_ items: [UITabBarItem]?, animated: Bool)
{
//Check if we should animate
if(self.animated >= 1)
{
//Supercall
super.setItems(items, animated: true)
//Decrease "(self.)animated"
self.animated -= 1
}
else
{
//Supercall
super.setItems(items, animated: false)
}
//Iterate though the subviews and get the titles of the items if the the titles array has not yet been initialized, or if the the number of items changed.
//NOTE: In the supercall, views for the items, provided in the "items" parameter, are created and added to the subviews of the tab bar
// These views are all inherit "UIControl", and have two subviews: the icon (image view) of the item, and its title.
if(controls.count == 0)
{
//Iterate through the subviews
for subview in self.subviews
{
//Check if the subview is one of the views of the items
if(subview is UIControl)
{
let control: MWTabBarControl = MWTabBarControl(control: subview as! UIControl)
control.control.addTarget(self, action: #selector(selectItem(control:)), for: .touchUpInside)
controls.append(control)
}
}
}
else if(controls.count != self.items?.count)
{
//Check which direction the count has changed
if(controls.count < self.items!.count)
{
//Iterate through the subviews
for subview in self.subviews
{
//Check if the subview is one of the views of the items
if(subview is UIControl)
{
//Create a new "MWTabBarItemControl" instance out of this control
let control: MWTabBarControl = MWTabBarControl(control: subview as! UIControl)
control.control.addTarget(self, action: #selector(selectItem(control:)), for: .touchUpInside)
if(!controls.contains(control))
{
controls.append(control)
}
}
}
}
else if(controls.count > self.items!.count) //"items" cannot be nil, because if it would be, this block would not be executed
{
//Iterate through the controls
//NOTE: The "itemControls" array at this point still contains the control of the removed item.
for control in controls
{
//Check if the control is added to the view hierarchy. If the control is not added to it, it is likely that the current item is a removed item
if(!control.isInViewHierarchy())
{
//Remove the title if it is not in the hierarchy anymore
controls.remove(at: controls.index(of: control)!)
}
}
}
}
}
override func layoutSubviews()
{
//Supercall
super.layoutSubviews()
//Call the function with the layout implementation
self.layoutIfNeeded()
}
override func layoutIfNeeded()
{
//Supercall
super.layoutIfNeeded()
//Update the titles if necessary
updateTitles()
//Update the style of the button if necessary
//Update/redraw the custom tab bar if the style is custom
if(_style == .custom)
{
//Remove the separator line if we have not removed it already
if(!removedSeparatorLine)
{
if let separatorLine = getSeparatorLine(for: self)
{
separatorLine.isHidden = true
removedSeparatorLine = true
}
}
//Update/redraw
clippingLayer.frame = self.bounds.offsetBy(dx: 0.0, dy: -(self.bounds.height -- 30.0)).withSize(width: self.bounds.width, height: 30.0)
let shadowPath = UIBezierPath(rect: self.bounds.scaleBy(width: -10.0, height: 0.0))
shadowLayer.frame = clippingLayer.bounds.offsetBy(dx: 0.0, dy: clippingLayer.bounds.height)
shadowLayer.shadowOffset = CGSize(width: 5.0, height: -4.0)
shadowLayer.shadowPath = shadowPath.cgPath
}
}
//MARK: Instance functions
/// A modifier which forces the tab bar to perform the next redraw/update animated.
///
/// - Returns: This tab bar.
func animating() -> MWTabBar
{
animated += 1
return self
}
/// The tab bar's custom initializer.
///
/// Initializes the tab bar based on its style.
private func _init()
{
//Check which style the tab bar is set to
switch _style
{
//For case "system" we do not do anything - leave the system default
case .system:
break
//For case "custom" we draw a shadow, which is clipped outside of the tab bar, so it does not effect the translucency
case .custom:
//Set the tab bar's layer allow drawing outside of its region
self.layer.masksToBounds = false
//Setup the layer which the shadow will be clipped to
clippingLayer.frame = self.bounds.offsetBy(dx: 0.0, dy: -(self.bounds.height -- 30.0)).withSize(width: self.bounds.width, height: 30.0)
clippingLayer.masksToBounds = true
//Create the shadow's layer
let shadowPath = UIBezierPath(rect: self.bounds.scaleByCentered(width: -10.0, height: 0.0))
shadowLayer.frame = clippingLayer.bounds.offsetBy(dx: 0.0, dy: clippingLayer.bounds.height)
//Setup the shadow
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowRadius = 7.0
shadowLayer.shadowOpacity = 0.5
shadowLayer.shadowOffset = CGSize(width: 5.0, height: -4.0)
shadowLayer.shadowPath = shadowPath.cgPath
shadowLayer.masksToBounds = false
//Clip the shadow by adding it to the clipping layer, then add the final result to the tab bar's layer
clippingLayer.addSublayer(shadowLayer)
self.layer.addSublayer(clippingLayer)
break
}
}
/// Updates the titles of the tab bar based on the value of `hidesTitles`.
///
/// If the tab bar does not hide the titles, but it did previously, it will restore them from the `titles` array.
///
/// Otherwise, the tab bar will simply remove the titles from its subviews.
private func updateTitles()
{
for control in controls
{
if(animated >= 1)
{
UIView.animate(withDuration: 0.35, delay: 0.0, options: .curveEaseOut, animations: {
control.imageView.frame = control.control.frame.withPosition(x: control.control.frame.origin.x, y: self.hidesTitles ? ((self.frame.height - control.imageView.frame.height) / 2) - control.imageView.frame.origin.y : 1)
control.label.isHidden = self.hidesTitles
}, completion: nil)
}
else
{
//Reposition the image view
control.control.frame = control.control.frame.withPosition(x: control.control.frame.origin.x, y: hidesTitles ? ((self.frame.height - control.imageView.frame.height) / 2) - control.imageView.frame.origin.y : 1)
//Hide/show the title
control.label.isHidden = hidesTitles
}
}
if(animated >= 1)
{
animated -= 1
}
}
/// Animates the selection of the control provided in the parameter and the unselection of the currently selected control.
///
/// - Parameter control: The control which is about to be selected.
@objc private func selectItem(control: UIControl)
{
//Animate the selection of the new control
UIView.transition(with: control, duration: 0.1, options: .transitionCrossDissolve, animations: {
control.isSelected = true
}, completion: nil)
//Check if we have a currently selected control
selectedControl ?! {
//Animate the unselection of the currently selected control
UIView.transition(with: self.selectedControl!, duration: 0.1, options: .transitionCrossDissolve, animations: {
self.selectedControl!.isSelected = false
}, completion: nil)
}
//Set the new control as the selected control
selectedControl = control
}
/// Searches for a separator line in subviews of the given view
///
/// - Parameter view: The view whose subviews the function should search for the separator line in.
/// - Returns: The separator line (default shadow image) of the tab bar.
private func getSeparatorLine(for view: UIView) -> UIImageView?
{
//Check if the current view is the separator line
if(view is UIImageView && view.frame.height <= 1)
{
//If it is, return it as a "UIImageView"
return view as? UIImageView
}
//If it is not, search for it in its subviews
for subview in view.subviews
{
//For optimization puposes, we exclude the buttons from the search
//(We are looking for a view with type "_UIBarBackground", but that is not a public view type available in UIKit.)
if(!(subview is UIControl))
{
if let shadowImage = getSeparatorLine(for: subview)
{
return shadowImage
}
}
}
return nil
}
}
/// A basic class which collects the two main views of a tab bar item control and the control itself.
fileprivate class MWTabBarControl: NSObject
{
/// The corresponding control of the tab bar item.
var control: UIControl
/// The image view which displays the icon of the tab bar item.
var imageView: UIImageView
/// The label which displays the title of the tab bar item.
var label: UILabel
/// Makes an `MWTabBarControl` instance out of the given parameters.
///
/// - Parameter control: The control which must have an image view as its subview at slot `0` and a label at slot `1`. (Can be directly extracted from the subviews of any tab bar.)
///
/// __NOTE:__ This specific control type is called `UITabBarButton`, but it is not released in the public version of UIKit. Therefore, the way we check whether a control is an instance of this type is by checking whether the control's structure matches the structure of a `UITabBarButton`.
init(control: UIControl)
{
//Store the control
self.control = control
//Check if the control is an item's control directly extracted from the tab bar.
if(control.subviews[0] is UIImageView && control.subviews[1] is UILabel)
{
//Store the image view and the label
self.imageView = control.subviews[0] as! UIImageView
self.label = control.subviews[1] as! UILabel
}
else
{
//Assert the application if the control is not compatible
fatalError("The control provided in the initializer of \"MWTabBarItemControl\" does not seem like it's an instance of \"UITabBarButton\"!")
}
}
/// Checks and returns whether the control is in the view hierarchy.
///
/// - Returns: A boolean which indicates whether the control is in the view hierarchy.
func isInViewHierarchy() -> Bool
{
return control.window != nil
}
}
/// The enumeration which holds all tab bar styles that currently exist in myWatch.
enum MWTabBarStyle: Int
{
/// Case __system__ involves having a tab bar which looks like the system default
case system
/// Case __custom__ involves having a tab bar with a custom shadow and with the 1px separator line removed.
case custom
///Holds the total amount of styles in this enumeration.
///
///This is required to make clamping the value given in `style` in `MWTabBar` possible.
static var count: Int
{
return self.custom.hashValue + 1
}
}
| gpl-3.0 | 55c1b85d405df4bf38ba465d4d6bad73 | 37.800448 | 295 | 0.58694 | 4.931604 | false | false | false | false |
maarten/Ximian | Ximian/StringExtensions.swift | 4 | 3876 | /*
* StringExtensions.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/* Required for localeconv(3) */
#if os(OSX)
import Darwin
#elseif os(Linux)
import Glibc
#endif
internal extension String {
/* Retrieves locale-specified decimal separator from the environment
* using localeconv(3).
*/
private func _localDecimalPoint() -> Character {
guard let locale = localeconv(), let decimalPoint = locale.pointee.decimal_point else {
return "."
}
return Character(UnicodeScalar(UInt8(bitPattern: decimalPoint.pointee)))
}
/**
* Attempts to parse the string value into a Double.
*
* - returns: A Double if the string can be parsed, nil otherwise.
*/
func toDouble() -> Double? {
let decimalPoint = String(self._localDecimalPoint())
guard decimalPoint == "." || self.range(of: ".") == nil else { return nil }
let localeSelf = self.replacingOccurrences(of: decimalPoint, with: ".")
return Double(localeSelf)
}
/**
* Splits a string into an array of string components.
*
* - parameter by: The character to split on.
* - parameter maxSplits: The maximum number of splits to perform. If 0, all possible splits are made.
*
* - returns: An array of string components.
*/
func split(by: Character, maxSplits: Int = 0) -> [String] {
var s = [String]()
var numSplits = 0
var curIdx = self.startIndex
for i in self.characters.indices {
let c = self[i]
if c == by && (maxSplits == 0 || numSplits < maxSplits) {
s.append(self[curIdx..<i])
curIdx = self.index(after: i)
numSplits += 1
}
}
if curIdx != self.endIndex {
s.append(self[curIdx..<self.endIndex])
}
return s
}
/**
* Pads a string to the specified width.
*
* - parameter toWidth: The width to pad the string to.
* - parameter by: The character to use for padding.
*
* - returns: A new string, padded to the given width.
*/
func padded(toWidth width: Int, with padChar: Character = " ") -> String {
var s = self
var currentLength = self.characters.count
while currentLength < width {
s.append(padChar)
currentLength += 1
}
return s
}
/**
* Wraps a string to the specified width.
*
* This just does simple greedy word-packing, it doesn't go full Knuth-Plass.
* If a single word is longer than the line width, it will be placed (unsplit)
* on a line by itself.
*
* - parameter atWidth: The maximum length of a line.
* - parameter wrapBy: The line break character to use.
* - parameter splitBy: The character to use when splitting the string into words.
*
* - returns: A new string, wrapped at the given width.
*/
func wrapped(atWidth width: Int, wrapBy: Character = "\n", splitBy: Character = " ") -> String {
var s = ""
var currentLineWidth = 0
for word in self.split(by: splitBy) {
let wordLength = word.characters.count
if currentLineWidth + wordLength + 1 > width {
/* Word length is greater than line length, can't wrap */
if wordLength >= width {
s += word
}
s.append(wrapBy)
currentLineWidth = 0
}
currentLineWidth += wordLength + 1
s += word
s.append(splitBy)
}
return s
}
}
| mit | 2a14a087ee5398e4008a92d23ede8ec6 | 27.711111 | 104 | 0.640867 | 4.058639 | false | false | false | false |
wangxin20111/WaterFlowView | WaterFlowViewDemo/WaterFlowViewDemo/ViewController.swift | 1 | 1920 | //
// ViewController.swift
// WaterFlowViewDemo
//
// Created by 王鑫 on 17/4/25.
// Copyright © 2017年 王鑫. All rights reserved.
//
import UIKit
import MJExtension
let WaterFlowCellReuseIndentifier = "WaterFlowCellReuseIndentifier"
class ViewController: UIViewController {
private lazy var waterFlowView:WaterFlowView = WaterFlowView()
fileprivate lazy var shops:Array = Array<WaterFlowModel>()
override func viewDidLoad() {
super.viewDidLoad()
//刷新数据
let data = WaterFlowModel.mj_objectArray(withFilename: "1.plist")
shops = data as! Array
// self.collectionView.reloadData()
waterFlowView.delegateOfWaterFlow = self
waterFlowView.dataSourceOfWaterFlow = self
waterFlowView.frame = view.bounds
view.addSubview(waterFlowView)
waterFlowView.reloadData()
}
}
extension ViewController:WaterFlowViewDelegate,WaterFlowViewDataSource{
func numberOfCells(_ waterFlowView: WaterFlowView) -> Int {
return shops.count
}
func waterFlowView(_ waterFlowView: WaterFlowView, cellForRowAt index: NSInteger) -> WaterFlowCell {
var cell = waterFlowView.dequeueReusableCellWithIndentifier(reuseIdentifier: WaterFlowCellReuseIndentifier)
if cell == nil {
cell = WaterFlowCell()
cell?.identifier = WaterFlowCellReuseIndentifier
}
let m = shops[index]
cell?.shopM = m
return cell!
}
func waterFlowView(_ waterFlowView: WaterFlowView, heightForRowAt index: NSInteger, cellWidth width: CGFloat) -> CGFloat {
let shop = shops[index]
if shop.widhtForPresent == 0 {
shop.widhtForPresent = width / (shop.w/shop.h)
// print("走这里了")
}
return shop.widhtForPresent
}
}
| mit | 849794dd1f1dfc243d63224f37b260e3 | 28.123077 | 126 | 0.64448 | 4.708955 | false | false | false | false |
lanserxt/teamwork-ios-sdk | TeamWorkClient/TeamWorkClient/ResponseContainer.swift | 1 | 1267 | //
// ResponseContainer.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 14.01.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
public enum TWApiStatusCode: String {
case OK = "OK"
case Undefined = "Other"
}
public class ResponseContainer<T: Model>{
//MARK:- Variables
public var status : TWApiStatusCode?
public var rootObject: T {
return self.object as! T
}
private var object : Model?
private var rootObjectName : String
//MARK:- Init
required public init?(rootObjectName: String, dictionary: NSDictionary) {
self.rootObjectName = rootObjectName
status = dictionary[TWApiClientConstants.kStatus] as? String == TWApiStatusCode.OK.rawValue ? .OK : .Undefined
if (dictionary[self.rootObjectName] != nil){
object = T(dictionary: dictionary[self.rootObjectName] as! NSDictionary)
}
}
//MARK:- Methods
public func dictionaryRepresentation() -> NSDictionary {
let dictionary = NSMutableDictionary()
dictionary.setValue(self.status, forKey: TWApiClientConstants.kStatus)
dictionary.setValue(self.object?.dictionaryRepresentation(), forKey: self.rootObjectName)
return dictionary
}
}
| mit | a9b76e2d211395f6eccfa4fe22ddf9e5 | 24.836735 | 118 | 0.688784 | 4.489362 | false | false | false | false |
kstaring/swift | stdlib/public/core/OptionSet.swift | 4 | 15045 | //===--- OptionSet.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that presents a mathematical set interface to a bit mask.
///
/// You use the `OptionSet` protocol to represent bit mask types, where
/// individual bits represent members of the set. Adopting this protocol in
/// your custom types lets you perform set-related operations such as
/// membership tests, unions, and intersections on those types. What's more,
/// when implemented using specific criteria, adoption of this protocol
/// requires no extra work on your part.
///
/// When creating an option set, include a `rawValue` property in your type
/// declaration. The `rawValue` property must be of a type that conforms to
/// the `BitwiseOperations` protocol, such as `Int` or `UInt8`. Next, create
/// unique options as static properties of your custom type using unique
/// powers of two (1, 2, 4, 8, 16, and so forth) for each individual
/// property's raw value so that each property can be represented by a single
/// bit of the type's raw value.
///
/// For example, consider a custom type called `ShippingOptions` that is an
/// option set of the possible ways to ship a customer's purchase.
/// `ShippingOptions` includes a `rawValue` property of type `Int` that stores
/// the bit mask of available shipping options. The static members `NextDay`,
/// `SecondDay`, `Priority`, and `Standard` are unique, individual options.
///
/// struct ShippingOptions: OptionSet {
/// let rawValue: Int
///
/// static let nextDay = ShippingOptions(rawValue: 1 << 0)
/// static let secondDay = ShippingOptions(rawValue: 1 << 1)
/// static let priority = ShippingOptions(rawValue: 1 << 2)
/// static let standard = ShippingOptions(rawValue: 1 << 3)
///
/// static let express: ShippingOptions = [.nextDay, .secondDay]
/// static let all: ShippingOptions = [.express, .priority, .standard]
/// }
///
/// Declare additional preconfigured option set values as static properties
/// initialized with an array literal containing other option values. In the
/// example, because the `express` static property is assigned an array
/// literal with the `nextDay` and `secondDay` options, it will contain those
/// two elements.
///
/// Using an Option Set Type
/// ========================
///
/// When you need to create an instance of an option set, assign one of the
/// type's static members to your variable or constant. Alternatively, to
/// create an option set instance with multiple members, assign an array
/// literal with multiple static members of the option set. To create an empty
/// instance, assign an empty array literal to your variable.
///
/// let singleOption: ShippingOptions = .priority
/// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
/// let noOptions: ShippingOptions = []
///
/// Use set-related operations to check for membership and to add or remove
/// members from an instance of your custom option set type. The following
/// example shows how you can determine free shipping options based on a
/// customer's purchase price:
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = []
/// if purchasePrice > 50 {
/// freeOptions.insert(.priority)
/// }
///
/// if freeOptions.contains(.priority) {
/// print("You've earned free priority shipping!")
/// } else {
/// print("Add more to your cart for free priority shipping!")
/// }
/// // Prints "You've earned free priority shipping!"
///
/// - SeeAlso: `BitwiseOperations`, `SetAlgebra`
public protocol OptionSet : SetAlgebra, RawRepresentable {
// We can't constrain the associated Element type to be the same as
// Self, but we can do almost as well with a default and a
// constrained extension
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
associatedtype Element = Self
// FIXME: This initializer should just be the failable init from
// RawRepresentable. Unfortunately, current language limitations
// that prevent non-failable initializers from forwarding to
// failable ones would prevent us from generating the non-failing
// default (zero-argument) initializer. Since OptionSet's main
// purpose is to create convenient conformances to SetAlgebra,
// we opt for a non-failable initializer.
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
init(rawValue: RawValue)
}
/// `OptionSet` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet {
/// Returns a new option set of the elements contained in this set, in the
/// given set, or in both.
///
/// This example uses the `union(_:)` method to add two more shipping options
/// to the default set.
///
/// let defaultShipping = ShippingOptions.standard
/// let memberShipping = defaultShipping.union([.secondDay, .priority])
/// print(memberShipping.contains(.priority))
/// // Prints "true"
///
/// - Parameter other: An option set.
/// - Returns: A new option set made up of the elements contained in this
/// set, in `other`, or in both.
public func union(_ other: Self) -> Self {
var r: Self = Self(rawValue: self.rawValue)
r.formUnion(other)
return r
}
/// Returns a new option set with only the elements contained in both this
/// set and the given set.
///
/// This example uses the `intersection(_:)` method to limit the available
/// shipping options to what can be used with a PO Box destination.
///
/// // Can only ship standard or priority to PO Boxes
/// let poboxShipping: ShippingOptions = [.standard, .priority]
/// let memberShipping: ShippingOptions =
/// [.standard, .priority, .secondDay]
///
/// let availableOptions = memberShipping.intersection(poboxShipping)
/// print(availableOptions.contains(.priority))
/// // Prints "true"
/// print(availableOptions.contains(.secondDay))
/// // Prints "false"
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in both this
/// set and `other`.
public func intersection(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formIntersection(other)
return r
}
/// Returns a new option set with the elements contained in this set or in
/// the given set, but not in both.
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in either
/// this set or `other`, but not in both.
public func symmetricDifference(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formSymmetricDifference(other)
return r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `Element == Self`, which is the default.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where Element == Self {
/// Returns a Boolean value that indicates whether a given element is a
/// member of the option set.
///
/// This example uses the `contains(_:)` method to check whether next-day
/// shipping is in the `availableOptions` instance.
///
/// let availableOptions = ShippingOptions.express
/// if availableOptions.contains(.nextDay) {
/// print("Next day shipping available")
/// }
/// // Prints "Next day shipping available"
///
/// - Parameter member: The element to look for in the option set.
/// - Returns: `true` if the option set contains `member`; otherwise,
/// `false`.
public func contains(_ member: Self) -> Bool {
return self.isSuperset(of: member)
}
/// Adds the given element to the option set if it is not already a member.
///
/// In the following example, the `.secondDay` shipping option is added to
/// the `freeOptions` option set if `purchasePrice` is greater than 50.0. For
/// the `ShippingOptions` declaration, see the `OptionSet` protocol
/// discussion.
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = [.standard, .priority]
/// if purchasePrice > 50 {
/// freeOptions.insert(.secondDay)
/// }
/// print(freeOptions.contains(.secondDay))
/// // Prints "true"
///
/// - Parameter newMember: The element to insert.
/// - Returns: `(true, newMember)` if `newMember` was not contained in
/// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is
/// the member of the set equal to `newMember`.
@discardableResult
public mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element) {
let oldMember = self.intersection(newMember)
let shouldInsert = oldMember != newMember
let result = (
inserted: shouldInsert,
memberAfterInsert: shouldInsert ? newMember : oldMember)
if shouldInsert {
self.formUnion(newMember)
}
return result
}
/// Removes the given element and all elements subsumed by it.
///
/// In the following example, the `.priority` shipping option is removed from
/// the `options` option set. Attempting to remove the same shipping option
/// a second time results in `nil`, because `options` no longer contains
/// `.priority` as a member.
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let priorityOption = options.remove(.priority)
/// print(priorityOption == .priority)
/// // Prints "true"
///
/// print(options.remove(.priority))
/// // Prints "nil"
///
/// In the next example, the `.express` element is passed to `remove(_:)`.
/// Although `.express` is not a member of `options`, `.express` subsumes
/// the remaining `.secondDay` element of the option set. Therefore,
/// `options` is emptied and the intersection between `.express` and
/// `options` is returned.
///
/// let expressOption = options.remove(.express)
/// print(expressOption == .express)
/// // Prints "false"
/// print(expressOption == .secondDay)
/// // Prints "true"
///
/// - Parameter member: The element of the set to remove.
/// - Returns: The intersection of `[member]` and the set, if the
/// intersection was nonempty; otherwise, `nil`.
@discardableResult
public mutating func remove(_ member: Element) -> Element? {
let r = isSuperset(of: member) ? Optional(member) : nil
self.subtract(member)
return r
}
/// Inserts the given element into the set.
///
/// If `newMember` is not contained in the set but subsumes current members
/// of the set, the subsumed members are returned.
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let replaced = options.update(with: .express)
/// print(replaced == .secondDay)
/// // Prints "true"
///
/// - Returns: The intersection of `[newMember]` and the set if the
/// intersection was nonempty; otherwise, `nil`.
@discardableResult
public mutating func update(with newMember: Element) -> Element? {
let r = self.intersection(newMember)
self.formUnion(newMember)
return r.isEmpty ? nil : r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `RawValue` conforms to `BitwiseOperations`,
/// which is the usual case. Each distinct bit of an option set's
/// `.rawValue` corresponds to a disjoint value of the `OptionSet`.
///
/// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s
/// - `intersection` is implemented as a bitwise "and" (`&`) of
/// `rawValue`s
/// - `symmetricDifference` is implemented as a bitwise "exclusive or"
/// (`^`) of `rawValue`s
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where RawValue : BitwiseOperations {
/// Creates an empty option set.
///
/// This initializer creates an option set with a raw value of zero.
public init() {
self.init(rawValue: .allZeros)
}
/// Inserts the elements of another set into this option set.
///
/// This method is implemented as a `|` (bitwise OR) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formUnion(_ other: Self) {
self = Self(rawValue: self.rawValue | other.rawValue)
}
/// Removes all elements of this option set that are not
/// also present in the given set.
///
/// This method is implemented as a `&` (bitwise AND) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formIntersection(_ other: Self) {
self = Self(rawValue: self.rawValue & other.rawValue)
}
/// Replaces this set with a new set containing all elements
/// contained in either this set or the given set, but not in both.
///
/// This method is implemented as a `^` (bitwise XOR) operation on the two
/// sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formSymmetricDifference(_ other: Self) {
self = Self(rawValue: self.rawValue ^ other.rawValue)
}
}
@available(*, unavailable, renamed: "OptionSet")
public typealias OptionSetType = OptionSet
| apache-2.0 | ce31d0b1b7239fdafd2986e8d3edb413 | 40.106557 | 80 | 0.665138 | 4.395267 | false | false | false | false |
NitWitStudios/NWSExtensions | Example/NWSExtensionsExample/Controllers/View Controllers/NWSModalViewController.swift | 1 | 1252 | //
// NWSModalViewController.swift
// NWSExtensions
//
// Created by James Hickman on 3/14/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import NWSExtensions
class NWSModalViewController: UIViewController {
var animator: NWSModalAnimator!
@IBOutlet weak var containerView: UIView!
// MARK: - UIViewController
override func awakeFromNib() {
super.awakeFromNib()
self.modalPresentationStyle = .overFullScreen
self.animator = NWSModalAnimator()
self.transitioningDelegate = self.animator
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.clear
containerView.roundCornersWithRadius(4.0)
}
// MARK: - NWSModalViewController
class func viewControllerFromStoryboardInstance() -> NWSModalViewController {
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: NWSModalViewControllerIdentifier) as! NWSModalViewController
return viewController
}
@IBAction func doneBarButtonItemPressed(_ sender: UIBarButtonItem) {
self.dismiss(animated: true, completion: nil)
}
}
| mit | 2397a130761c1bb7ffb872865d92ef80 | 27.431818 | 171 | 0.691447 | 5.127049 | false | false | false | false |
renesto/SkypeExportSwift | SkypeExport/AppDelegate.swift | 1 | 12357 | //
// AppDelegate.swift
// SkypeExport
//
// Created by Aleksandar Kovacevic on 2/11/15.
// Copyright (c) 2015 Aleksandar Kovacevic. All rights reserved.
//
import Cocoa
import Foundation
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
//@IBOutlet weak var skypeUserName: NSComboBox!
// @IBOutlet weak var dialogPartner: NSTextField!
//@IBOutlet weak var skypeContacts: NSComboBox!
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var ExportContactsView: NSView!
@IBOutlet weak var mainView: NSView!
@IBOutlet weak var configView: NSView!
@IBOutlet weak var exportMsgsView: NSView!
@IBOutlet weak var dialogPartner: NSComboBox!
@IBOutlet weak var skypeUserName: NSComboBox!
var config:SkypeConfig=SkypeConfig()
var skypeDB:SkypeDB?
var messages:[(from:String, dialog_partner:String, timestamp:String, message:String)]?
var contacts:[Contact]?
@IBOutlet weak var userNameComboBox: NSComboBox!
@IBAction func applySkypeUserName(sender: AnyObject) {
skypeDB=SkypeDB(skypeUser: userNameComboBox.stringValue, isBusyHandler: isBusyHandler, errorHandler: errorHandler, debugPath: "")
showMsg("Info",message: "Successfully configured and connected to local Skype DB.")
}
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
mainView.hidden=false
configView.hidden=true
ExportContactsView.hidden=true
exportMsgsView.hidden=true
// Insert code here to initialize your application
let users=config.getLocalSkypeUsers()
for user in users {
skypeUserName.addItemWithObjectValue(user)
}
}
@IBAction func goBackToMainView(sender: AnyObject) {
mainView.hidden=false
configView.hidden=true
ExportContactsView.hidden=true
exportMsgsView.hidden=true
}
@IBAction func goToExportMsgView(sender: AnyObject) {
mainView.hidden=true
configView.hidden=true
ExportContactsView.hidden=true
exportMsgsView.hidden=false
if let dB=skypeDB {
for skypeContact in dB.getSkypeContacts() {
dialogPartner.addItemWithObjectValue("\(skypeContact)")
}
}
}
@IBAction func goToConfigView(sender: AnyObject) {
mainView.hidden=true
configView.hidden=false
ExportContactsView.hidden=true
exportMsgsView.hidden=true
}
@IBAction func goToExportContsView(sender: AnyObject) {
mainView.hidden=true
configView.hidden=true
ExportContactsView.hidden=false
exportMsgsView.hidden=true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
@IBAction func applyConfigSettings(sender: AnyObject) {
}
func isBusyHandler(Check: Int) -> Bool {
let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Skype Database is Locked"
myPopup.informativeText = "You need to quit skype before using Skype Exporter."
myPopup.runModal()
return true
}
@IBAction func loadContacts(sender: AnyObject) {
if let db=skypeDB{
contacts=db.getAllContactDetails()
showMsg("Info",message: "Successfully loaded contacts.")
} else {
showMsg("Error",message: "Could not connect to Skype DB. Please go to configuration and set the config beforehand.")
}
}
/*
@IBAction func loadContactOptionsDialog(sender: AnyObject) {
}
@IBAction func showSkypeContacts(sender: AnyObject) {
let dbPath="\(getAppSupportDir()!)/Skype/\(skypeUserName.stringValue)/main.db"
let skypeDB=SkypeDB(skypeUser: skypeUserName.stringValue, isBusyHandler: isBusyHandler,errorHandler: errorHandler,debugPath: "")
let messagesManager:MessagesManager=MessagesManager(skypedb: skypeDB)
let users=messagesManager.getSkypeContacts()
for user in users {
skypeContacts.addItemWithObjectValue("\(user)")
}
}
@IBAction func loadSkypeMessages(sender: AnyObject) {
let skypeDB=SkypeDB(skypeUser: skypeUserName.stringValue, isBusyHandler: isBusyHandler,errorHandler: errorHandler,debugPath: "");
/* let messages=skypeDB.getMessagesForSkypeContact(dialogPartner: skypeContacts.stringValue)
var result:String="";
for message in messages {
result.extend("from: \(message.from), timestamp: \(message.timestamp), message: \(message.message)")
// id: 1, name: Optional("Alice"), email: [email protected]
}
let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Messages are displayed on consoel output.";
myPopup.informativeText = "not here"
myPopup.runModal()
println("\(skypeContacts.stringValue)")
println("\(result)")*/
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
func isMacUserName(text: String, isDir:Bool) -> Bool {
return isDir && !text.hasPrefix(".") && text != "Shared" && text != "Guest"
}
// Tuple result
// Get contents of directory at specified path, returning (filenames, nil) or (nil, error)
*/
/* if let filenames = filenamesOpt {
let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Modal NSAlert Popup";
myPopup.informativeText = "Echo that variable:"// \(filenames)"
myPopup.runModal()
// [".localized", "kris", ...]
}
let (filenamesOpt2, errorOpt2) = contentsOfDirectoryAtPath("/NoSuchDirectory")
if let err = errorOpt2 {
err.description // "Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. ... "
}
*/
func showMsg(title:String, message:String) {
let myPopup:NSAlert = NSAlert()
myPopup.messageText = title
myPopup.informativeText = message
myPopup.runModal()
}
func errorHandler(error: SkypeDB.ERRORS) -> Void {
let myPopup:NSAlert = NSAlert()
myPopup.messageText = "Error"
switch error {
case SkypeDB.ERRORS.DB_FILE_NOT_FOUND:
myPopup.informativeText = "Database File Not Found"
case SkypeDB.ERRORS.DATABASE_NOT_LOADED:
myPopup.informativeText = "Database could not be loaded"
default:
myPopup.informativeText = "Unknown Error Occurred"
}
myPopup.runModal()
}
@IBAction func exportContactsAsCSV(sender: AnyObject) {
var myFiledialog: NSSavePanel = NSSavePanel()
myFiledialog.prompt = "Export"
myFiledialog.worksWhenModal = true
myFiledialog.title = "Choose Path"
myFiledialog.message = "Please choose a path"
myFiledialog.runModal()
var chosenfile = myFiledialog.URL
if (chosenfile != nil) {
var TheFile = chosenfile?.path!
if let contactList=contacts {
let exporter = SkypeExporterOutput()
let contactData=exporter.prepareContactsForExport(contactList)
let result = exporter.saveToCSV(usingSelectedPath:"\(TheFile!)", data: contactData, type: "contacts")
if (result) {
showMsg("Export Result",message:"Export to CSV is successful\nExported to \(TheFile!)")
} else {
showMsg("Export Result", message: "Export to CSV failed")
}
} else {
showMsg("Export Result", message: "No contacts loaded. Load contacts first")
}
} else {
showMsg("Export Result", message: "No File Chosen")
}
}
@IBAction func exportContactsAsHTML(sender: AnyObject) {
var myFiledialog: NSSavePanel = NSSavePanel()
myFiledialog.prompt = "Export"
myFiledialog.worksWhenModal = true
myFiledialog.title = "Choose Path"
myFiledialog.message = "Please choose a path"
myFiledialog.runModal()
var chosenfile = myFiledialog.URL
if (chosenfile != nil) {
var TheFile = chosenfile?.path!
if let contactList=contacts {
let exporter = SkypeExporterOutput()
let contactData=exporter.prepareContactsForExport(contactList)
let result = exporter.saveToHTML(usingSelectedPath:"\(TheFile!)", data: contactData, type: "contacts")
if (result) {
showMsg("Export Result", message: "Export to HTML is successful\nExported to \(TheFile!)")
} else {
showMsg("Export Result", message: "Export to HTML failed")
}
} else {
showMsg("Export Result", message: "No contacts loaded. Load contacts first")
}
} else {
showMsg("Export Result", message: "No file chosen")
}
}
@IBAction func loadMsgsForSingleContact(sender: AnyObject) {
if let dbase=skypeDB {
messages = dbase.getMessagesForSkypeContact(dialogPartner:"\(dialogPartner.stringValue)")
showMsg("Info",message: "Successfully loaded messages.")
} else {
showMsg("Message Extractor",message:"Not connected to local Skype DB. Please go to configuration before extracting messages or contacts.")
}
}
@IBAction func exportMessagesAsHTML(sender: AnyObject) {
var myFiledialog: NSSavePanel = NSSavePanel()
myFiledialog.prompt = "Export"
myFiledialog.worksWhenModal = true
myFiledialog.title = "Choose Path"
myFiledialog.message = "Please choose a path"
myFiledialog.runModal()
var chosenfile = myFiledialog.URL
if (chosenfile != nil) {
var TheFile = chosenfile?.path!
if let messageList=messages {
let exporter = SkypeExporterOutput()
let messageData=exporter.prepareMessagesForExport(messageList)
let result = exporter.saveToHTML(usingSelectedPath:"\(TheFile!)", data: messageData, type: "messages")
if (result) {
showMsg("Export Result", message: "Export to HTML is successful\nExported to \(TheFile!)")
} else {
showMsg("Export Result", message: "Export to HTML failed")
}
} else {
showMsg("Export Result", message: "No messages loaded. Load messages first")
}
} else {
showMsg("Export Result", message: "No file chosen")
}
}
@IBAction func exportMessagesAsCSV(sender: AnyObject) {
var myFiledialog: NSSavePanel = NSSavePanel()
myFiledialog.prompt = "Export"
myFiledialog.worksWhenModal = true
myFiledialog.title = "Choose Path"
myFiledialog.message = "Please choose a path"
myFiledialog.runModal()
var chosenfile = myFiledialog.URL
if (chosenfile != nil) {
var TheFile = chosenfile?.path!
if let messageList=messages {
let exporter = SkypeExporterOutput()
let messageData=exporter.prepareMessagesForExport(messageList)
let result = exporter.saveToCSV(usingSelectedPath:"\(TheFile!)", data: messageData, type: "contacts")
if (result) {
showMsg("Export Result",message:"Export to CSV is successful\nExported to \(TheFile!)")
} else {
showMsg("Export Result", message: "Export to CSV failed")
}
} else {
showMsg("Export Result", message: "No contacts loaded. Load contacts first")
}
} else {
showMsg("Export Result", message: "No File Chosen")
}
}
}
| apache-2.0 | 12640fa4a22b6d8e7f25348ec989547e | 34.915698 | 150 | 0.610603 | 4.862259 | false | false | false | false |
danghoa/GGModules | GGModules/AppDelegate/AppDelegate.swift | 1 | 2994 | //
// AppDelegate.swift
// GGModuleLogin
//
// Created by Đăng Hoà on 1/11/17.
// Copyright © 2017 Green Global. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.makeKeyAndVisible()
let signIn = GGMSignInVC(social: GGMSignInVC.Social.facebook, mainColor: UIColor.magenta, name: "Jonas Brothers")
signIn.setting(backgroundColor: nil, backgroundImage: nil, imageFacebook: nil, imageGoogle: nil)
signIn.settingAPI(path: "http://api-swivel-dev.greenglobal.vn:8100/auth/login")
signIn.response { (type, detail, value) in
if type == GGMSignInVC.Response.successfully {
} else if type == GGMSignInVC.Response.failed {
} else if type == GGMSignInVC.Response.forgot {
} else if type == GGMSignInVC.Response.signUp {
} else {
}
//print(type, detail, value)
}
window?.rootViewController = signIn
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 6beb06a231ad554598bdddc8478c467f | 39.405405 | 281 | 0.731773 | 4.950331 | false | false | false | false |
zaneswafford/ProjectEulerSwift | ProjectEulerTests/ZSMathTests.swift | 1 | 2154 | //
// ZSMathTests.swift
// ProjectEuler
//
// Created by Zane Swafford on 6/17/15.
// Copyright (c) 2015 Zane Swafford. All rights reserved.
//
import Cocoa
import XCTest
class ZSMathTests: XCTestCase {
func testFibonacci() {
// Test the first couple values
var actualFibonacci = [0, 1, 1, 2, 3, 5]
var testDidPass = true
for var i = 0; i <= 5; i++ {
if actualFibonacci[i] != ZSMath.fibonacci(i) {
testDidPass = false
}
}
XCTAssert(testDidPass, "Pass")
}
func testFibonacciSequence() {
var actualFibonacci = [0, 1, 1, 2, 3, 5]
var testDidPass = true
ZSMath.fibbonacciSequence(UpToValue: 5)
XCTAssert(testDidPass, "Pass")
}
func testPrimeFactors() {
var testValues = [123, 456, 789]
var testSolutions = [[3, 41],
[3, 19, 114, 228, 456],
[3, 263]]
var testDidPass = true
for var i = 0; i < 3; i++ {
if testSolutions[i] != ZSMath.primeFactors(ofNumber: testValues[i]) {
testDidPass = false
}
}
XCTAssert(testDidPass, "Pass")
}
func testGeneratePrimes() {
let actualPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
let testPrimes = ZSMath.generatePrimes(upToNumber: 30)
XCTAssert(actualPrimes == testPrimes, "Pass")
}
func testGenerateNPrimes() {
let actualPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
let testPrimes = ZSMath.generateNPrimes(10)
XCTAssert(actualPrimes == testPrimes, "Pass")
}
func testFactorial() {
let actualFactorial5:Double = (5 * 4 * 3 * 2 * 1)
let testFactorial5:Double = ZSMath.factorial(5)
let actualFactorial10:Double = (10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1)
let testFactorial10:Double = ZSMath.factorial(10)
XCTAssert(actualFactorial5 == testFactorial5 && actualFactorial10 == testFactorial10, "Pass")
}
} | bsd-2-clause | 973b8e276c945b2a875b1934737794f3 | 26.628205 | 101 | 0.527855 | 3.888087 | false | true | false | false |
kgn/KGNThread | Source/Thread.swift | 1 | 3413 | //
// Thread.swift
// KGNThread
//
// Created by David Keegan on 1/24/15.
// Copyright (c) 2014 David Keegan. All rights reserved.
//
import Foundation
private let diskQueue = dispatch_queue_create("kgn.thread.disk", DISPATCH_QUEUE_SERIAL)
public struct Thread {
private static func Dispatch(delay delay: NSTimeInterval?, queue: dispatch_queue_t, _ block: dispatch_block_t) {
if delay != nil {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay! * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, queue, block)
} else {
dispatch_async(queue, block)
}
}
/// Global threads
public struct Global {
/**
Dispatch on the high priority global queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func High(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), block)
}
/**
Dispatch on the low priority global queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func Low(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), block)
}
/**
Dispatch on the default priority global queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func Default(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), block)
}
/**
Dispatch on the background priority global queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func Background(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), block)
}
}
/**
Dispatch on a serial queue reserved for disk access.
If you use this thread for all disk access in your application it will
ensure that all disk access happens on the same background serial queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func Disk(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: diskQueue, block)
}
/**
Dispatch on the main thread queue.
- Parameter delay: Optional delay in seconds to wait before dispatching.
- Parameter block: The method to execute on the queue.
*/
public static func Main(delay delay: NSTimeInterval? = nil, block: dispatch_block_t) {
Thread.Dispatch(delay: delay, queue: dispatch_get_main_queue(), block)
}
}
| mit | e3f63dd46df85974618a6ed66122efff | 36.097826 | 121 | 0.652798 | 4.438231 | false | false | false | false |
GraphQLSwift/GraphQL | Sources/GraphQL/Map/Map.swift | 1 | 24693 | import Foundation
import OrderedCollections
// MARK: MapError
public enum MapError: Error {
case incompatibleType
case outOfBounds
case valueNotFound
}
// MARK: Map
public enum Map {
case undefined
case null
case bool(Bool)
case number(Number)
case string(String)
case array([Map])
case dictionary(OrderedDictionary<String, Map>)
public static func int(_ value: Int) -> Map {
return .number(Number(value))
}
public static func double(_ value: Double) -> Map {
return .number(Number(value))
}
}
// MARK: Initializers
public extension Map {
static let encoder = MapEncoder()
init<T: Encodable>(_ encodable: T, encoder: MapEncoder = Map.encoder) throws {
self = try encoder.encode(encodable)
}
init(_ number: Number) {
self = .number(number)
}
init(_ bool: Bool) {
self = .bool(bool)
}
init(_ int: Int) {
self.init(Number(int))
}
init(_ double: Double) {
self.init(Number(double))
}
init(_ string: String) {
self = .string(string)
}
init(_ array: [Map]) {
self = .array(array)
}
init(_ dictionary: OrderedDictionary<String, Map>) {
self = .dictionary(dictionary)
}
init(_ number: Number?) {
self = number.map { Map($0) } ?? .null
}
init(_ bool: Bool?) {
self.init(bool.map { Number($0) })
}
init(_ int: Int?) {
self.init(int.map { Number($0) })
}
init(_ double: Double?) {
self.init(double.map { Number($0) })
}
init(_ string: String?) {
self = string.map { Map($0) } ?? .null
}
init(_ array: [Map]?) {
self = array.map { Map($0) } ?? .null
}
init(_ dictionary: OrderedDictionary<String, Map>?) {
self = dictionary.map { Map($0) } ?? .null
}
}
// MARK: Any
public func map(from value: Any?) throws -> Map {
guard let value = value else {
return .null
}
if let map = value as? Map {
return map
}
if let map = try? Map(any: value) {
return map
}
if
let value = value as? OrderedDictionary<String, Any>,
let dictionary: OrderedDictionary<String, Map> = try? value
.reduce(into: [:], { result, pair in
result[pair.key] = try map(from: pair.value)
})
{
return .dictionary(dictionary)
}
if
let value = value as? [Any],
let array: [Map] = try? value.map({ value in
try map(from: value)
})
{
return .array(array)
}
if
let value = value as? Encodable,
let map = try? Map(AnyEncodable(value))
{
return map
}
throw MapError.incompatibleType
}
public extension Map {
init(any: Any?) throws {
switch any {
case .none:
self = .null
case let number as Number:
self = .number(number)
case let bool as Bool:
self = .bool(bool)
case let double as Double:
self = .number(Number(double))
case let int as Int:
self = .number(Number(int))
case let string as String:
self = .string(string)
case let array as [Map]:
self = .array(array)
case let dictionary as OrderedDictionary<String, Map>:
self = .dictionary(dictionary)
default:
throw MapError.incompatibleType
}
}
}
// MARK: is<Type>
public extension Map {
var isUndefined: Bool {
if case .undefined = self {
return true
}
return false
}
var isNull: Bool {
if case .null = self {
return true
}
return false
}
var isNumber: Bool {
if case .number = self {
return true
}
return false
}
var isString: Bool {
if case .string = self {
return true
}
return false
}
var isArray: Bool {
if case .array = self {
return true
}
return false
}
var isDictionary: Bool {
if case .dictionary = self {
return true
}
return false
}
}
// MARK: is<Type>
public extension Map {
var typeDescription: String {
switch self {
case .undefined:
return "undefined"
case .null:
return "null"
case .bool:
return "bool"
case .number:
return "number"
case .string:
return "string"
case .array:
return "array"
case .dictionary:
return "dictionary"
}
}
}
// MARK: as<type>?
public extension Map {
var bool: Bool? {
return try? boolValue()
}
var int: Int? {
return try? intValue()
}
var double: Double? {
return try? doubleValue()
}
var string: String? {
return try? stringValue()
}
var array: [Map]? {
return try? arrayValue()
}
var dictionary: OrderedDictionary<String, Map>? {
return try? dictionaryValue()
}
}
// MARK: try as<type>()
public extension Map {
func boolValue(converting: Bool = false) throws -> Bool {
guard converting else {
return try get()
}
switch self {
case .undefined:
return false
case .null:
return false
case let .bool(value):
return value
case let .number(number):
return number.boolValue
case let .string(value):
switch value.lowercased() {
case "true": return true
case "false": return false
default: throw MapError.incompatibleType
}
case let .array(value):
return !value.isEmpty
case let .dictionary(value):
return !value.isEmpty
}
}
func intValue(converting: Bool = false) throws -> Int {
guard converting else {
return try (get() as Number).intValue
}
switch self {
case .null:
return 0
case let .number(number):
return number.intValue
case let .string(value):
guard let value = Int(value) else {
throw MapError.incompatibleType
}
return value
default:
throw MapError.incompatibleType
}
}
func doubleValue(converting: Bool = false) throws -> Double {
guard converting else {
return try (get() as Number).doubleValue
}
switch self {
case .null:
return 0
case let .number(number):
return number.doubleValue
case let .string(value):
guard let value = Double(value) else {
throw MapError.incompatibleType
}
return value
default:
throw MapError.incompatibleType
}
}
func stringValue(converting: Bool = false) throws -> String {
guard converting else {
return try get()
}
switch self {
case .undefined:
return "undefined"
case .null:
return "null"
case let .bool(value):
return "\(value)"
case let .number(number):
return number.stringValue
case let .string(value):
return value
case .array:
throw MapError.incompatibleType
case .dictionary:
throw MapError.incompatibleType
}
}
func arrayValue(converting: Bool = false) throws -> [Map] {
guard converting else {
return try get()
}
switch self {
case let .array(value):
return value
case .null:
return []
default:
throw MapError.incompatibleType
}
}
func dictionaryValue(converting: Bool = false) throws -> OrderedDictionary<String, Map> {
guard converting else {
return try get()
}
switch self {
case let .dictionary(value):
return value
case .null:
return [:]
default:
throw MapError.incompatibleType
}
}
}
// MARK: Get
public extension Map {
func get<T>(_ indexPath: IndexPathElement...) throws -> T {
if indexPath.isEmpty {
switch self {
case let .number(value as T):
return value
case let .bool(value as T):
return value
case let .string(value as T):
return value
case let .array(value as T):
return value
case let .dictionary(value as T):
return value
default:
throw MapError.incompatibleType
}
}
return try get(IndexPath(indexPath)).get()
}
func get(_ indexPath: IndexPathElement...) throws -> Map {
return try get(IndexPath(indexPath))
}
func get(_ indexPath: IndexPath) throws -> Map {
var value: Map = self
for element in indexPath.elements {
switch element {
case let .index(index):
let array = try value.arrayValue()
if array.indices.contains(index) {
value = array[index]
} else {
throw MapError.outOfBounds
}
case let .key(key):
let dictionary = try value.dictionaryValue()
if let newValue = dictionary[key] {
value = newValue
} else {
throw MapError.valueNotFound
}
}
}
return value
}
}
// MARK: Set
public extension Map {
mutating func set(_ value: Map, for indexPath: IndexPathElement...) throws {
try set(value, for: indexPath)
}
mutating func set(_ value: Map, for indexPath: [IndexPathElement]) throws {
try set(value, for: IndexPath(indexPath), merging: true)
}
fileprivate mutating func set(_ value: Map, for indexPath: IndexPath, merging: Bool) throws {
var elements = indexPath.elements
guard let first = elements.first else {
return self = value
}
elements.removeFirst()
if elements.isEmpty {
switch first {
case let .index(index):
if case var .array(array) = self {
if !array.indices.contains(index) {
throw MapError.outOfBounds
}
array[index] = value
self = .array(array)
} else {
throw MapError.incompatibleType
}
case let .key(key):
if case var .dictionary(dictionary) = self {
let newValue = value
if
let existingDictionary = dictionary[key]?.dictionary,
let newDictionary = newValue.dictionary,
merging
{
var combinedDictionary: OrderedDictionary<String, Map> = [:]
for (key, value) in existingDictionary {
combinedDictionary[key] = value
}
for (key, value) in newDictionary {
combinedDictionary[key] = value
}
dictionary[key] = .dictionary(combinedDictionary)
} else {
dictionary[key] = newValue
}
self = .dictionary(dictionary)
} else {
throw MapError.incompatibleType
}
}
} else {
var next = (try? get(first)) ?? first.constructEmptyContainer
try next.set(value, for: indexPath, merging: true)
try set(next, for: [first])
}
}
}
// MARK: Remove
public extension Map {
mutating func remove(_ indexPath: IndexPathElement...) throws {
try remove(indexPath)
}
mutating func remove(_ indexPath: [IndexPathElement]) throws {
var indexPath = indexPath
guard let first = indexPath.first else {
return self = .null
}
indexPath.removeFirst()
if indexPath.isEmpty {
guard
case var .dictionary(dictionary) = self,
case let .key(key) = first.indexPathValue
else {
throw MapError.incompatibleType
}
dictionary[key] = nil
self = .dictionary(dictionary)
} else {
guard var next = try? get(first) else {
throw MapError.valueNotFound
}
try next.remove(indexPath)
try set(next, for: [first], merging: false)
}
}
}
// MARK: Subscripts
public extension Map {
subscript(indexPath: IndexPathElement...) -> Map {
get {
return self[IndexPath(indexPath)]
}
set(value) {
self[IndexPath(indexPath)] = value
}
}
subscript(indexPath: IndexPath) -> Map {
get {
return (try? get(indexPath)) ?? nil
}
set(value) {
do {
try set(value, for: indexPath, merging: true)
} catch {
fatalError(String(describing: error))
}
}
}
}
extension String: CodingKey {
public var stringValue: String {
return self
}
public init?(stringValue: String) {
self = stringValue
}
public var intValue: Int? {
return nil
}
public init?(intValue _: Int) {
return nil
}
}
extension Map: Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if container.decodeNil() {
self = .null
} else if let bool = try? container.decode(Bool.self) {
self = .bool(bool)
} else if let double = try? container.decode(Double.self) {
self = .number(Number(double))
} else if let string = try? container.decode(String.self) {
self = .string(string)
} else if let array = try? container.decode([Map].self) {
self = .array(array)
} else if let _ = try? container.decode([String: Map].self) {
// Override OrderedDictionary default (unkeyed alternating key-value)
// Instead decode as a keyed container (like normal Dictionary) but use the order of the input
let container = try decoder.container(keyedBy: _DictionaryCodingKey.self)
var orderedDictionary: OrderedDictionary<String, Map> = [:]
for key in container.allKeys {
let value = try container.decode(Map.self, forKey: key)
orderedDictionary[key.stringValue] = value
}
self = .dictionary(orderedDictionary)
} else if let dictionary = try? container.decode(OrderedDictionary<String, Map>.self) {
self = .dictionary(dictionary)
} else {
throw DecodingError.dataCorruptedError(
in: container,
debugDescription: "Corrupted data"
)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
switch self {
case .undefined:
throw EncodingError.invalidValue(
self,
EncodingError.Context(
codingPath: [],
debugDescription: "undefined values should have been excluded from encoding"
)
)
case .null:
try container.encodeNil()
case let .bool(value):
try container.encode(value)
case let .number(number):
try container.encode(number.doubleValue)
case let .string(string):
try container.encode(string)
case let .array(array):
try container.encode(array)
case let .dictionary(dictionary):
// Override OrderedDictionary default (unkeyed alternating key-value)
// Instead decode as a keyed container (like normal Dictionary) in the order of our OrderedDictionary
// Note that `JSONEncoder` will ignore this because it uses `Dictionary` underneath. Instead, use `GraphQLJSONEncoder`.
var container = encoder.container(keyedBy: _DictionaryCodingKey.self)
for (key, value) in dictionary {
if !value.isUndefined {
guard let codingKey = _DictionaryCodingKey(stringValue: key) else {
throw EncodingError.invalidValue(
self,
EncodingError.Context(
codingPath: [],
debugDescription: "codingKey not found for dictionary key: \(key)"
)
)
}
try container.encode(value, forKey: codingKey)
}
}
}
}
/// A wrapper for dictionary keys which are Strings or Ints.
/// This is copied from Swift core: https://github.com/apple/swift/blob/256a9c5ad96378daa03fa2d5197b4201bf16db27/stdlib/public/core/Codable.swift#L5508
internal struct _DictionaryCodingKey: CodingKey {
internal let stringValue: String
internal let intValue: Int?
internal init?(stringValue: String) {
self.stringValue = stringValue
intValue = Int(stringValue)
}
internal init?(intValue: Int) {
stringValue = "\(intValue)"
self.intValue = intValue
}
}
}
// MARK: Equatable
extension Map: Equatable {}
public func == (lhs: Map, rhs: Map) -> Bool {
switch (lhs, rhs) {
case (.undefined, .undefined):
return true
case (.null, .null):
return true
case let (.bool(l), .bool(r)) where l == r:
return true
case let (.number(l), .number(r)) where l == r:
return true
case let (.string(l), .string(r)) where l == r:
return true
case let (.array(l), .array(r)) where l == r:
return true
case let (.dictionary(l), .dictionary(r)) where l == r:
return true
default:
return false
}
}
// MARK: Hashable
extension Map: Hashable {
public func hash(into hasher: inout Hasher) {
switch self {
case .undefined:
hasher.combine(0)
case .null:
hasher.combine(0)
case let .bool(value):
hasher.combine(value)
case let .number(number):
hasher.combine(number)
case let .string(string):
hasher.combine(string)
case let .array(array):
hasher.combine(array)
case let .dictionary(dictionary):
hasher.combine(dictionary)
}
}
}
// MARK: Literal Convertibles
extension Map: ExpressibleByNilLiteral {
public init(nilLiteral _: Void) {
self = .null
}
}
extension Map: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self = .bool(value)
}
}
extension Map: ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self = .number(Number(value))
}
}
extension Map: ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self = .number(Number(value))
}
}
extension Map: ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self = .string(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = .string(value)
}
public init(stringLiteral value: StringLiteralType) {
self = .string(value)
}
}
extension Map: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Map...) {
self = .array(elements)
}
}
extension Map: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Map)...) {
var dictionary = OrderedDictionary<String, Map>(minimumCapacity: elements.count)
for (key, value) in elements {
dictionary[key] = value
}
self = .dictionary(dictionary)
}
}
// MARK: CustomStringConvertible
extension Map: CustomStringConvertible {
public var description: String {
return self.description(debug: false)
}
}
// MARK: CustomDebugStringConvertible
extension Map: CustomDebugStringConvertible {
public var debugDescription: String {
return description(debug: true)
}
}
// MARK: Generic Description
public extension Map {
func description(debug: Bool) -> String {
var indentLevel = 0
let escapeMapping: [Character: String] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
"\r\n": "\\r\\n",
]
func escape(_ source: String) -> String {
var string = "\""
for character in source {
if let escapedSymbol = escapeMapping[character] {
string.append(escapedSymbol)
} else {
string.append(character)
}
}
string.append("\"")
return string
}
func serialize(map: Map) -> String {
switch map {
case .undefined:
return "undefined"
case .null:
return "null"
case let .bool(value):
return value.description
case let .number(number):
return number.description
case let .string(string):
return escape(string)
case let .array(array):
return serialize(array: array)
case let .dictionary(dictionary):
return serialize(dictionary: dictionary)
}
}
func serialize(array: [Map]) -> String {
var string = "["
if debug {
indentLevel += 1
}
for index in 0 ..< array.count {
if debug {
string += "\n"
string += indent()
}
string += serialize(map: array[index])
if index != array.count - 1 {
if debug {
string += ", "
} else {
string += ","
}
}
}
if debug {
indentLevel -= 1
return string + "\n" + indent() + "]"
} else {
return string + "]"
}
}
func serialize(dictionary: OrderedDictionary<String, Map>) -> String {
var string = "{"
var index = 0
if debug {
indentLevel += 1
}
let filtered = dictionary.filter { item in
!item.value.isUndefined
}
for (key, value) in filtered.sorted(by: { $0.0 < $1.0 }) {
if debug {
string += "\n"
string += indent()
string += escape(key) + ": " + serialize(map: value)
} else {
string += escape(key) + ":" + serialize(map: value)
}
if index != filtered.count - 1 {
if debug {
string += ", "
} else {
string += ","
}
}
index += 1
}
if debug {
indentLevel -= 1
return string + "\n" + indent() + "}"
} else {
return string + "}"
}
}
func indent() -> String {
return String(repeating: " ", count: indentLevel)
}
return serialize(map: self)
}
}
| mit | 641266b5642d45e53ebf866b8a0b4862 | 24.456701 | 155 | 0.507674 | 4.919904 | false | false | false | false |
benlangmuir/swift | test/Concurrency/unavailable_from_async.swift | 5 | 6493 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path %t/UnavailableFunction.swiftmodule -module-name UnavailableFunction -warn-concurrency %S/Inputs/UnavailableFunction.swift
// RUN: %target-swift-frontend -typecheck -verify -I %t %s
// REQUIRES: concurrency
import UnavailableFunction
@available(SwiftStdlib 5.1, *)
func okay() {}
// expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}}
@_unavailableFromAsync
@available(SwiftStdlib 5.1, *)
struct Foo { }
// expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}}
@_unavailableFromAsync
@available(SwiftStdlib 5.1, *)
extension Foo { }
// expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}}
@_unavailableFromAsync
@available(SwiftStdlib 5.1, *)
class Bar {
// expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}}
@_unavailableFromAsync
deinit { }
}
// expected-error@+1{{'@_unavailableFromAsync' attribute cannot be applied to this declaration}}
@_unavailableFromAsync
@available(SwiftStdlib 5.1, *)
actor Baz { }
@available(SwiftStdlib 5.1, *)
struct Bop {
@_unavailableFromAsync(message: "Use Bop(a: Int) instead")
init() {} // expected-note 4 {{'init()' declared here}}
init(a: Int) { }
}
@available(SwiftStdlib 5.1, *)
extension Bop {
@_unavailableFromAsync
func foo() {} // expected-note 4 {{'foo()' declared here}}
@_unavailableFromAsync
mutating func muppet() { } // expected-note 4 {{'muppet()' declared here}}
}
@_unavailableFromAsync
@available(SwiftStdlib 5.1, *)
func foo() {} // expected-note 4 {{'foo()' declared here}}
@available(SwiftStdlib 5.1, *)
func makeAsyncClosuresSynchronously(bop: inout Bop) -> (() async -> Void) {
return { () async -> Void in
// Unavailable methods
_ = Bop() // expected-warning@:9{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}}
_ = Bop(a: 32)
bop.foo() // expected-warning@:9{{'foo' is unavailable from asynchronous contexts}}
bop.muppet() // expected-warning@:9{{'muppet' is unavailable from asynchronous contexts}}
unavailableFunction() // expected-warning@:5{{'unavailableFunction' is unavailable from asynchronous contexts}}
noasyncFunction() // expected-warning@:5{{'noasyncFunction' is unavailable from asynchronous contexts}}
// Can use them from synchronous closures
_ = { Bop() }()
_ = { bop.foo() }()
_ = { bop.muppet() }()
_ = { noasyncFunction() }()
// Unavailable global function
foo() // expected-warning{{'foo' is unavailable from asynchronous contexts}}
// Okay function
okay()
}
}
@available(SwiftStdlib 5.1, *)
@_unavailableFromAsync
func asyncFunc() async { // expected-error{{asynchronous global function 'asyncFunc()' must be available from asynchronous contexts}}
var bop = Bop(a: 32)
_ = Bop() // expected-warning@:7{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}}
bop.foo() // expected-warning@:7{{'foo' is unavailable from asynchronous contexts}}
bop.muppet() // expected-warning@:7{{'muppet' is unavailable from asynchronous contexts}}
unavailableFunction() // expected-warning@:3{{'unavailableFunction' is unavailable from asynchronous contexts}}
noasyncFunction() // expected-warning@:3{{'noasyncFunction' is unavailable from asynchronous contexts}}
// Unavailable global function
foo() // expected-warning{{'foo' is unavailable from asynchronous contexts}}
// Available function
okay()
_ = { () -> Void in
// Check unavailable things inside of a nested synchronous closure
_ = Bop()
foo()
bop.foo()
bop.muppet()
unavailableFunction()
noasyncFunction()
_ = { () async -> Void in
// Check Unavailable things inside of a nested async closure
foo() // expected-warning@:7{{'foo' is unavailable from asynchronous contexts}}
bop.foo() // expected-warning@:11{{'foo' is unavailable from asynchronous contexts}}
bop.muppet() // expected-warning@:11{{'muppet' is unavailable from asynchronous contexts}}
_ = Bop() // expected-warning@:11{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}}
unavailableFunction() // expected-warning@:7{{'unavailableFunction' is unavailable from asynchronous contexts}}
noasyncFunction() // expected-warning@:7{{'noasyncFunction' is unavailable from asynchronous contexts}}
}
}
_ = { () async -> Void in
_ = Bop() // expected-warning@:9{{'init' is unavailable from asynchronous contexts; Use Bop(a: Int) instead}}
foo() // expected-warning@:5{{'foo' is unavailable from asynchronous contexts}}
bop.foo() // expected-warning@:9{{'foo' is unavailable from asynchronous contexts}}
bop.muppet() // expected-warning@:9{{'muppet' is unavailable from asynchronous contexts}}
unavailableFunction() // expected-warning@:5{{'unavailableFunction' is unavailable from asynchronous contexts}}
noasyncFunction() // expected-warning@:5{{'noasyncFunction' is unavailable from asynchronous contexts}}
_ = {
foo()
bop.foo()
_ = Bop()
unavailableFunction()
}
}
}
// Parsing tests
// expected-error@+2 {{expected declaration}}
// expected-error@+1:24{{unknown option 'nope' for attribute '_unavailableFromAsync'}}
@_unavailableFromAsync(nope: "almost right, but not quite")
func blarp1() {}
// expected-error@+2 {{expected declaration}}
// expected-error@+1 {{expected ':' after label 'message'}}
@_unavailableFromAsync(message; "almost right, but not quite")
func blarp2() {}
// expected-error@+1:31 {{'=' has been replaced with ':' in attribute arguments}}{{31-32=: }}
@_unavailableFromAsync(message="almost right, but not quite")
func blarp3() {}
// expected-error@+2 {{expected declaration}}
// expected-error@+1 {{expected string literal in '_unavailableFromAsync' attribute}}
@_unavailableFromAsync(message: 32)
func blarp4() {}
// expected-error@+2 {{expected declaration}}
// expected-error@+1 {{message cannot be an interpolated string}}
@_unavailableFromAsync(message: "blarppy blarp \(31 + 10)")
func blarp5() {}
// expected-error@+1:48 {{expected ')' in '_unavailableFromAsync' attribute}}{{48-48=)}}
@_unavailableFromAsync(message: "blarppy blarp"
func blarp6() {}
| apache-2.0 | 2d906eec4e4ff064bc29a1205070daa4 | 38.114458 | 183 | 0.684583 | 3.988329 | false | false | false | false |
whitepixelstudios/Material | Sources/iOS/Icon.swift | 4 | 7043 | /*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
public struct Icon {
/// An internal reference to the icons bundle.
private static var internalBundle: Bundle?
/**
A public reference to the icons bundle, that aims to detect
the correct bundle to use.
*/
public static var bundle: Bundle {
if nil == Icon.internalBundle {
Icon.internalBundle = Bundle(for: View.self)
let url = Icon.internalBundle!.resourceURL!
let b = Bundle(url: url.appendingPathComponent("com.cosmicmind.material.icons.bundle"))
if let v = b {
Icon.internalBundle = v
}
}
return Icon.internalBundle!
}
/// Get the icon by the file name.
public static func icon(_ name: String) -> UIImage? {
return UIImage(named: name, in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysTemplate)
}
/// Google icons.
public static let add = Icon.icon("ic_add_white")
public static let addCircle = Icon.icon("ic_add_circle_white")
public static let addCircleOutline = Icon.icon("ic_add_circle_outline_white")
public static let arrowBack = Icon.icon("ic_arrow_back_white")
public static let arrowDownward = Icon.icon("ic_arrow_downward_white")
public static let audio = Icon.icon("ic_audiotrack_white")
public static let bell = Icon.icon("cm_bell_white")
public static let cameraFront = Icon.icon("ic_camera_front_white")
public static let cameraRear = Icon.icon("ic_camera_rear_white")
public static let check = Icon.icon("ic_check_white")
public static let clear = Icon.icon("ic_close_white")
public static let close = Icon.icon("ic_close_white")
public static let edit = Icon.icon("ic_edit_white")
public static let email = Icon.icon("ic_email_white")
public static let favorite = Icon.icon("ic_favorite_white")
public static let favoriteBorder = Icon.icon("ic_favorite_border_white")
public static let flashAuto = Icon.icon("ic_flash_auto_white")
public static let flashOff = Icon.icon("ic_flash_off_white")
public static let flashOn = Icon.icon("ic_flash_on_white")
public static let history = Icon.icon("ic_history_white")
public static let home = Icon.icon("ic_home_white")
public static let image = Icon.icon("ic_image_white")
public static let menu = Icon.icon("ic_menu_white")
public static let moreHorizontal = Icon.icon("ic_more_horiz_white")
public static let moreVertical = Icon.icon("ic_more_vert_white")
public static let movie = Icon.icon("ic_movie_white")
public static let pen = Icon.icon("ic_edit_white")
public static let place = Icon.icon("ic_place_white")
public static let phone = Icon.icon("ic_phone_white")
public static let photoCamera = Icon.icon("ic_photo_camera_white")
public static let photoLibrary = Icon.icon("ic_photo_library_white")
public static let search = Icon.icon("ic_search_white")
public static let settings = Icon.icon("ic_settings_white")
public static let share = Icon.icon("ic_share_white")
public static let star = Icon.icon("ic_star_white")
public static let starBorder = Icon.icon("ic_star_border_white")
public static let starHalf = Icon.icon("ic_star_half_white")
public static let videocam = Icon.icon("ic_videocam_white")
public static let visibility = Icon.icon("ic_visibility_white")
public static let work = Icon.icon("ic_work_white")
/// CosmicMind icons.
public struct cm {
public static let add = Icon.icon("cm_add_white")
public static let arrowBack = Icon.icon("cm_arrow_back_white")
public static let arrowDownward = Icon.icon("cm_arrow_downward_white")
public static let audio = Icon.icon("cm_audio_white")
public static let audioLibrary = Icon.icon("cm_audio_library_white")
public static let bell = Icon.icon("cm_bell_white")
public static let check = Icon.icon("cm_check_white")
public static let clear = Icon.icon("cm_close_white")
public static let close = Icon.icon("cm_close_white")
public static let edit = Icon.icon("cm_pen_white")
public static let image = Icon.icon("cm_image_white")
public static let menu = Icon.icon("cm_menu_white")
public static let microphone = Icon.icon("cm_microphone_white")
public static let moreHorizontal = Icon.icon("cm_more_horiz_white")
public static let moreVertical = Icon.icon("cm_more_vert_white")
public static let movie = Icon.icon("cm_movie_white")
public static let pause = Icon.icon("cm_pause_white")
public static let pen = Icon.icon("cm_pen_white")
public static let photoCamera = Icon.icon("cm_photo_camera_white")
public static let photoLibrary = Icon.icon("cm_photo_library_white")
public static let play = Icon.icon("cm_play_white")
public static let search = Icon.icon("cm_search_white")
public static let settings = Icon.icon("cm_settings_white")
public static let share = Icon.icon("cm_share_white")
public static let shuffle = Icon.icon("cm_shuffle_white")
public static let skipBackward = Icon.icon("cm_skip_backward_white")
public static let skipForward = Icon.icon("cm_skip_forward_white")
public static let star = Icon.icon("cm_star_white")
public static let videocam = Icon.icon("cm_videocam_white")
public static let volumeHigh = Icon.icon("cm_volume_high_white")
public static let volumeMedium = Icon.icon("cm_volume_medium_white")
public static let volumeOff = Icon.icon("cm_volume_off_white")
}
}
| bsd-3-clause | 26b1acc94e5caed81d514eaaaa8d0d7f | 51.17037 | 104 | 0.717592 | 3.825638 | false | false | false | false |
Den-Ree/InstagramAPI | src/InstagramAPI/Pods/ObjectMapper/Sources/MapError.swift | 2 | 2426 | //
// MapError.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2016-09-26.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Hearst
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public struct MapError: Error {
public var key: String?
public var currentValue: Any?
public var reason: String?
public var file: StaticString?
public var function: StaticString?
public var line: UInt?
public init(key: String?, currentValue: Any?, reason: String?, file: StaticString? = nil, function: StaticString? = nil, line: UInt? = nil) {
self.key = key
self.currentValue = currentValue
self.reason = reason
self.file = file
self.function = function
self.line = line
}
}
extension MapError: CustomStringConvertible {
private var location: String? {
guard let file = file, let function = function, let line = line else { return nil }
let fileName = ((String(describing: file).components(separatedBy: "/").last ?? "").components(separatedBy: ".").first ?? "")
return "\(fileName).\(function):\(line)"
}
public var description: String {
let info: [(String, Any?)] = [
("- reason", reason),
("- location", location),
("- key", key),
("- currentValue", currentValue)
]
let infoString = info.map { "\($0): \($1 ?? "nil")" }.joined(separator: "\n")
return "Got an error while mapping.\n\(infoString)"
}
}
| mit | 8996f14de08f96b49ee32055093144b0 | 34.676471 | 142 | 0.704452 | 3.925566 | false | false | false | false |
tamanyan/SwiftPageMenu | PageMenuExample/Sources/AppDelegate.swift | 1 | 3550 | //
// AppDelegate.swift
// PageMenuExample
//
// Created by Tamanyan on 3/7/17.
// Copyright © 2017 Tamanyan. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
UINavigationBar.appearance().tintColor = .white
UINavigationBar.appearance().barTintColor = Theme.mainColor
UINavigationBar.appearance().backgroundColor = Theme.mainColor
UINavigationBar.appearance().titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary([NSAttributedString.Key.foregroundColor.rawValue: UIColor.white])
UINavigationBar.appearance().isTranslucent = false
UINavigationBar.appearance().shadowImage = UIImage()
self.window = UIWindow(frame: UIScreen.main.bounds)
let navController = UINavigationController(rootViewController: RootViewController())
if #available(iOS 11.0, *) {
navController.navigationBar.prefersLargeTitles = true
navController.navigationBar.largeTitleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary([NSAttributedString.Key.foregroundColor.rawValue: UIColor.white])
}
self.window?.rootViewController = navController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| mit | 82ff4ef3c124dc15bd82bb4d493adbf6 | 51.970149 | 285 | 0.754297 | 5.78956 | false | false | false | false |
fleurdeswift/code-editor | CodeEditorView/CodeEditorView+Draw.swift | 1 | 3185 | //
// CodeEditorView+Draw.swift
// CodeEditorView
//
// Copyright © 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public extension CodeEditorView {
private func drawLines() {
let drawContext = self.drawContext;
let context = drawContext.contextRef!;
var lineNumber = 0;
var firstLineDrawn = NSNotFound;
let frame = drawContext.frame;
var lineRect = CGRect(x: 0, y: 0, width: frame.size.width, height: 0);
var lineDrawn = 0;
for line in lines {
lineNumber++;
lineRect.origin.y += lineRect.size.height;
lineRect.size.height = line.size.height;
if !frame.intersects(lineRect) {
if firstLineDrawn != NSNotFound {
break;
}
continue;
}
else if firstLineDrawn == NSNotFound {
firstLineDrawn = lineNumber;
CGContextTranslateCTM(context, drawContext.leftSideBarWidth, lineRect.origin.y);
}
line.draw(drawContext);
CGContextTranslateCTM(context, 0, lineRect.size.height);
lineDrawn++;
}
}
private func drawLeftSideBar() {
var rect = self.bounds;
rect.size.width = drawContext.leftSideBarWidth - drawContext.lineHeightD3;
let context = drawContext.contextRef!;
CGContextSetFillColorWithColor(context, theme.leftSidebarBackgroundColor);
CGContextFillRect(context, rect);
var points = [CGPoint]();
points.reserveCapacity(2);
points.append(CGPoint(x: rect.size.width, y: 0));
points.append(CGPoint(x: rect.size.width, y: rect.size.height));
CGContextSetLineWidth(context, 1.0);
CGContextSetStrokeColorWithColor(context, theme.leftSidebarBorderColor);
CGContextStrokeLineSegments(context, points, 2);
CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1, -1));
var lineNumber: Int = 0;
for line in lines {
++lineNumber;
line.drawLeftBar(drawContext, lineNumber: lineNumber);
CGContextTranslateCTM(context, 0, line.size.height);
}
}
@objc
public override func drawRect(dirtyRect: NSRect) {
let contextRef = NSGraphicsContext.currentContext()!.CGContext;
CGContextClipToRect(contextRef, dirtyRect);
if theme.backgroundDraw {
CGContextSetFillColorWithColor(contextRef, theme.backgroundColor);
CGContextFillRect(contextRef, self.bounds);
}
drawContext.contextRef = contextRef;
dispatch_sync(document.queue) {
CGContextSaveGState(contextRef);
self.drawLines();
CGContextRestoreGState(contextRef);
CGContextSaveGState(contextRef);
self.drawLeftSideBar();
CGContextRestoreGState(contextRef);
}
drawContext.contextRef = nil;
}
}
| mit | 1d6e2eef0172dc1e70756d98cb824047 | 31.489796 | 96 | 0.580088 | 5.211129 | false | false | false | false |
CryptoKitten/CryptoEssentials | Sources/CFB.swift | 1 | 2326 | // Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]>
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
final public class CFB: BlockMode {
public static let options: BlockModeOptions = [.initializationVectorRequired]
public static let blockType = InputBlockType.encrypt
public static func makeEncryptionIterator(iv: [UInt8], cipherOperation: @escaping CipherBlockOperation, inputGenerator: AnyIterator<[UInt8]>) -> AnyIterator<[UInt8]> {
var prevCipherText: [UInt8]? = nil
return AnyIterator {
guard let plaintext = inputGenerator.next(),
let ciphertext = cipherOperation(prevCipherText ?? iv)
else {
return nil
}
prevCipherText = xor(plaintext, ciphertext)
return prevCipherText
}
}
public static func makeDecryptionIterator(iv: [UInt8], cipherOperation: @escaping CipherBlockOperation, inputGenerator: AnyIterator<[UInt8]>) -> AnyIterator<[UInt8]> {
var prevCipherText: [UInt8]? = nil
return AnyIterator {
guard let ciphertext = inputGenerator.next(),
let decrypted = cipherOperation(prevCipherText ?? iv)
else {
return nil
}
let result = xor(decrypted, ciphertext)
prevCipherText = ciphertext
return result
}
}
}
| mit | 00ee400d2bdd6411bdadc4615ddec0ce | 48.446809 | 216 | 0.672547 | 5.269841 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.