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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stripe/stripe-ios | IntegrationTester/IntegrationTester/Models/PaymentsModels.swift | 1 | 2033 | //
// PaymentsModels.swift
// IntegrationTester
//
// Created by David Estes on 2/18/21.
//
import Foundation
import Stripe
class MySIModel : ObservableObject {
@Published var paymentStatus: STPPaymentHandlerActionStatus?
@Published var intentParams: STPSetupIntentConfirmParams?
@Published var lastPaymentError: NSError?
var integrationMethod: IntegrationMethod = .cardSetupIntents
func prepareSetupIntent() {
BackendModel.shared.fetchSetupIntent { sip in
sip?.returnURL = BackendModel.returnURL
self.intentParams = sip
}
}
func onCompletion(status: STPPaymentHandlerActionStatus, si: STPSetupIntent?, error: NSError?) {
self.paymentStatus = status
self.lastPaymentError = error
}
}
class MyPIModel : ObservableObject {
@Published var paymentStatus: STPPaymentHandlerActionStatus?
@Published var paymentIntentParams: STPPaymentIntentParams?
@Published var lastPaymentError: NSError?
var integrationMethod: IntegrationMethod = .card
func preparePaymentIntent() {
// Enable this flag to test app-to-app redirects.
if self.integrationMethod == .weChatPay || self.integrationMethod == .alipay {
STPPaymentHandler.shared().simulateAppToAppRedirect = true
} else {
STPPaymentHandler.shared().simulateAppToAppRedirect = false
}
BackendModel.shared.fetchPaymentIntent(integrationMethod: integrationMethod) { pip in
pip?.paymentMethodParams = self.integrationMethod.defaultPaymentMethodParams
pip?.paymentMethodOptions = self.integrationMethod.defaultPaymentMethodOptions
// WeChat Pay is the only supported Payment Method that doesn't allow a returnURL.
if self.integrationMethod != .weChatPay {
pip?.returnURL = BackendModel.returnURL
}
self.paymentIntentParams = pip
}
}
func onCompletion(status: STPPaymentHandlerActionStatus, pi: STPPaymentIntent?, error: NSError?)
{
self.paymentStatus = status
self.lastPaymentError = error
}
}
| mit | c2879ac200ccdc3a8eacbe029a93b85d | 31.790323 | 98 | 0.734383 | 4.852029 | false | false | false | false |
papsti7/MealDiary | MealDiary/TitleViewController.swift | 1 | 1371 | //
// TitleViewController.swift
// MealDiary
//
// Created by admin on 01/09/16.
// Copyright © 2016 Stefan Papst. All rights reserved.
//
import UIKit
class TitleViewController: UIViewController {
@IBOutlet weak var title_textfield: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
title_textfield.text = NewItemContent.title
title_textfield.addTarget(self, action: #selector(self.textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldDidChange(_ textField: UITextField) {
NewItemContent.title = title_textfield.text
}
// 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.
if(segue.identifier == "add_title")
{
let title = title_textfield.text
NewItemContent.title = title
}
}
}
| mit | f00a01999103f798abd56c601910aa9e | 28.148936 | 124 | 0.659854 | 4.910394 | false | false | false | false |
Minitour/WWDC-Collaborators | Macintosh.playground/Sources/Interface/OSApplicationWindow.swift | 1 | 9215 | import UIKit
public protocol OSApplicationWindowDelegate{
/// Delegate function called when window is about to be dragged.
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - container: The application's view.
func applicationWindow(_ applicationWindow: OSApplicationWindow, willStartDraggingContainer container: UIView)
/// Delegate function called when window has finished dragging
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - container: The application's view.
func applicationWindow(_ applicationWindow: OSApplicationWindow, didFinishDraggingContainer container: UIView)
/// Delegate function, called when users taps the panel of the OSApplicationWindow.
///
/// - Parameters:
/// - applicationWindow: The current application window.
/// - panel: The window panel view instance that was tapped.
/// - point: The location of the tap.
func applicationWindow(_ applicationWindow: OSApplicationWindow, didTapWindowPanel panel: WindowPanel,atPoint point: CGPoint)
/// Delegate function, called when user clicks the "close" button in the panel.
///
/// - Parameters:
/// - application: The current application window.
/// - panel: The window panel view instance which holds the button that was clicked.
func applicationWindow(_ application: OSApplicationWindow, didCloseWindowWithPanel panel: WindowPanel)
/// Delegate function, called after user has finished dragging. note that `point` parameter is an `inout`. This is to allow the class which conforms to this delegate the option to modify the point incase the point that was given isn't good.
///
/// - Parameters:
/// - application: The current application window.
/// - point: The panel which the user dragged with.
/// - Returns: return true to allow the movment of the window to the point, and false to ignore the movment.
func applicationWindow(_ application: OSApplicationWindow, canMoveToPoint point: inout CGPoint)->Bool
}
public class OSApplicationWindow: UIView{
fileprivate var lastLocation = CGPoint(x: 0, y: 0)
open var windowOrigin: MacAppDesktopView?
open var delegate: OSApplicationWindowDelegate?
open var dataSource: MacApp?{
didSet{
tabBar?.contentStyle = dataSource?.contentMode
tabBar?.requestContentStyleUpdate()
windowTitle = dataSource?.windowTitle
backgroundColor = dataSource?.contentMode ?? .default == .default ? .white : .black
}
}
open var container: UIView?
open var windowTitle: String?{
set{
tabBar?.title = newValue
}get{
return tabBar?.title
}
}
open var containerSize: CGSize?{
return dataSource?.sizeForWindow()
}
fileprivate (set) open var tabBar: WindowPanel?{
didSet{
let gestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handlePan(sender:)))
tabBar?.addGestureRecognizer(gestureRecognizer)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(sender:)))
tabBar?.addGestureRecognizer(tapGesture)
}
}
fileprivate var transitionWindowFrame: MovingWindow?
public convenience init(delegate: OSApplicationWindowDelegate,dataSource: MacApp){
self.init()
self.delegate = delegate
self.dataSource = dataSource
tabBar?.contentStyle = self.dataSource?.contentMode
tabBar?.requestContentStyleUpdate()
windowTitle = self.dataSource?.windowTitle
backgroundColor = self.dataSource?.contentMode ?? .default == .default ? .white : .black
}
public convenience init(){
self.init(frame: CGRect.zero)
}
override public init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleTap(sender: UITapGestureRecognizer){
delegate?.applicationWindow(self, didTapWindowPanel: tabBar!, atPoint: sender.location(in: tabBar))
}
func handlePan(sender: UIPanGestureRecognizer){
if dataSource?.shouldDragApplication == false{
return
}
let translation = sender.translation(in: self.superview!)
switch sender.state{
case .began:
transitionWindowFrame?.isHidden = false
transitionWindowFrame?.frame = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size)
transitionWindowFrame?.lastLocation = (self.transitionWindowFrame?.center)!
delegate?.applicationWindow(self, willStartDraggingContainer: container!)
dataSource?.macApp(self, willStartDraggingContainer: container!)
break
case .ended:
transitionWindowFrame?.isHidden = true
var point = convert(transitionWindowFrame!.center, to: superview!)
if delegate?.applicationWindow(self, canMoveToPoint: &point) ?? true{
self.center = point
}
delegate?.applicationWindow(self, didFinishDraggingContainer: container!)
dataSource?.macApp(self, didFinishDraggingContainer: container!)
return
default:
break
}
let point = CGPoint(x: (transitionWindowFrame?.lastLocation.x)! + translation.x , y: (transitionWindowFrame?.lastLocation.y)! + translation.y)
transitionWindowFrame?.layer.shadowOpacity = 0
transitionWindowFrame?.center = point
}
func setup(){
backgroundColor = .white
tabBar = WindowPanel()
tabBar?.backgroundColor = .clear
tabBar?.delegate = self
addSubview(tabBar!)
container = UIView()
container?.backgroundColor = .clear
addSubview(container!)
transitionWindowFrame = MovingWindow()
transitionWindowFrame?.isHidden = true
transitionWindowFrame?.backgroundColor = .clear
addSubview(transitionWindowFrame!)
}
override public func layoutSubviews() {
super.layoutSubviews()
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOpacity = 1
self.layer.shadowOffset = CGSize.zero
self.layer.shadowRadius = 5
self.layer.cornerRadius = 2
transitionWindowFrame?.bounds = CGRect(origin: CGPoint(x: 0 , y: 0), size: bounds.size)
frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0) + CGFloat(20))
tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20)
container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0)
}
public override func didMoveToSuperview() {
tabBar?.frame = CGRect(x: 0, y: 0, width: containerSize?.width ?? 0, height: 20)
tabBar?.setNeedsDisplay()
container?.frame = CGRect(x: 0, y: tabBar?.bounds.size.height ?? 20, width: containerSize?.width ?? 0, height: containerSize?.height ?? 0)
frame.size = CGSize(width: containerSize?.width ?? 0, height: (containerSize?.height ?? 0 ) + CGFloat(20))
if let view = dataSource?.container{
view.frame = container!.bounds
container!.addSubview(view)
view.translatesAutoresizingMaskIntoConstraints = false
view.topAnchor.constraint(equalTo: container!.topAnchor).isActive = true
view.bottomAnchor.constraint(equalTo: container!.bottomAnchor).isActive = true
view.leftAnchor.constraint(equalTo: container!.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: container!.rightAnchor).isActive = true
}
}
override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
lastLocation = self.center
super.touchesBegan(touches, with: event)
}
open func close(){
self.dataSource?.willTerminateApplication()
self.delegate?.applicationWindow(self, didCloseWindowWithPanel: tabBar!)
self.removeFromSuperview()
}
}
public class MovingWindow: UIView{
var lastLocation = CGPoint(x: 0, y: 0)
open var borderColor: UIColor = .gray
override public func draw(_ rect: CGRect) {
borderColor.setStroke()
let path = UIBezierPath(rect: rect)
path.lineWidth = 4
path.stroke()
}
}
extension OSApplicationWindow: WindowPanelDelegate{
public func didSelectCloseMenu(_ windowPanel: WindowPanel, panelButton button: PanelButton) {
self.dataSource?.willTerminateApplication()
self.delegate?.applicationWindow(self, didCloseWindowWithPanel: windowPanel)
self.removeFromSuperview()
}
}
| mit | a2bdc2f685102b25bc98454776fb0ffe | 37.236515 | 244 | 0.648508 | 5.116602 | false | false | false | false |
open-telemetry/opentelemetry-swift | Sources/OpenTelemetryApi/Trace/Propagation/B3Propagator.swift | 1 | 5482 | /*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/
import Foundation
/**
* Implementation of the B3 propagation protocol. See
* https://github.com/openzipkin/b3-propagation
*/
public class B3Propagator: TextMapPropagator {
static let traceIdHeader = "X-B3-TraceId"
static let spanIdHeader = "X-B3-SpanId"
static let sampledHeader = "X-B3-Sampled"
static let trueInt = "1"
static let falseInt = "0"
static let combinedHeader = "b3"
static let combinedHeaderDelimiter = "-"
public let fields: Set<String> = [traceIdHeader, spanIdHeader, sampledHeader]
private static let maxTraceIdLength = 2 * TraceId.size
private static let maxSpanIdLength = 2 * SpanId.size
private static let sampledFlags = TraceFlags().settingIsSampled(true)
private static let notSampledFlags = TraceFlags().settingIsSampled(false)
private var singleHeaderInjection: Bool
/// Creates a new instance of B3Propagator. Default to use multiple headers.
public init() {
self.singleHeaderInjection = false
}
/// Creates a new instance of B3Propagator
/// - Parameters:
/// - singleHeader: whether to use single or multiple headers
public init(_ singleHeaderInjection: Bool) {
self.singleHeaderInjection = singleHeaderInjection
}
public func inject<S>(spanContext: SpanContext, carrier: inout [String: String], setter: S) where S: Setter {
let sampled = spanContext.traceFlags.sampled ? B3Propagator.trueInt : B3Propagator.falseInt
if singleHeaderInjection {
setter.set(carrier: &carrier, key: B3Propagator.combinedHeader, value: "\(spanContext.traceId.hexString)\(B3Propagator.combinedHeaderDelimiter)\(spanContext.spanId.hexString)\(B3Propagator.combinedHeaderDelimiter)\(sampled)")
} else {
setter.set(carrier: &carrier, key: B3Propagator.traceIdHeader, value: spanContext.traceId.hexString)
setter.set(carrier: &carrier, key: B3Propagator.spanIdHeader, value: spanContext.spanId.hexString)
setter.set(carrier: &carrier, key: B3Propagator.sampledHeader, value: sampled)
}
}
public func extract<G>(carrier: [String: String], getter: G) -> SpanContext? where G: Getter {
var spanContext: SpanContext?
spanContext = getSpanContextFromSingleHeader(carrier: carrier, getter: getter)
if spanContext == nil {
spanContext = getSpanContextFromMultipleHeaders(carrier: carrier, getter: getter)
}
if spanContext == nil {
print("Invalid SpanId in B3 header. Returning no span context.")
}
return spanContext
}
private func getSpanContextFromSingleHeader<G>(carrier: [String: String], getter: G) -> SpanContext? where G: Getter {
guard let value = getter.get(carrier: carrier, key: B3Propagator.combinedHeader), value.count >= 1 else {
return nil
}
let parts: [String] = value[0].split(separator: "-").map { String($0) }
// must have between 2 and 4 hyphen delimited parts:
// traceId-spanId-sampled-parentSpanId (last two are optional)
if parts.count < 2 || parts.count > 4 {
return nil
}
let traceId = parts[0]
if !isTraceIdValid(traceId) {
return nil
}
let spanId = parts[1]
if !isSpanIdValid(spanId) {
return nil
}
let sampled: String? = parts.count >= 3 ? parts[2] : nil
return buildSpanContext(traceId: traceId, spanId: spanId, sampled: sampled)
}
private func getSpanContextFromMultipleHeaders<G>(carrier: [String: String], getter: G) -> SpanContext? where G: Getter {
guard let traceIdCollection = getter.get(carrier: carrier, key: B3Propagator.traceIdHeader), traceIdCollection.count >= 1, isTraceIdValid(traceIdCollection[0]) else {
return nil
}
let traceId = traceIdCollection[0]
guard let spanIdCollection = getter.get(carrier: carrier, key: B3Propagator.spanIdHeader), spanIdCollection.count >= 0, isSpanIdValid(spanIdCollection[0]) else {
return nil
}
let spanId = spanIdCollection[0]
guard let sampledCollection = getter.get(carrier: carrier, key: B3Propagator.sampledHeader), sampledCollection.count >= 1 else {
return buildSpanContext(traceId: traceId, spanId: spanId, sampled: nil)
}
return buildSpanContext(traceId: traceId, spanId: spanId, sampled: sampledCollection.first)
}
private func buildSpanContext(traceId: String, spanId: String, sampled: String?) -> SpanContext? {
if let sampled = sampled {
let traceFlags = (sampled == B3Propagator.trueInt || sampled == "true") ? B3Propagator.sampledFlags : B3Propagator.notSampledFlags
let returnContext = SpanContext.createFromRemoteParent(traceId: TraceId(fromHexString: traceId), spanId: SpanId(fromHexString: spanId), traceFlags: traceFlags, traceState: TraceState())
return returnContext.isValid ? returnContext : nil
} else {
return nil
}
}
private func isTraceIdValid(_ traceId: String) -> Bool {
return !(traceId.isEmpty || traceId.count > B3Propagator.maxTraceIdLength)
}
private func isSpanIdValid(_ spanId: String) -> Bool {
return !(spanId.isEmpty || spanId.count > B3Propagator.maxSpanIdLength)
}
}
| apache-2.0 | 6a70a8e7108c904461bab62db3932cbf | 40.530303 | 237 | 0.674206 | 4.239753 | false | false | false | false |
albinekcom/BitBay-Ticker-iOS | Codebase/Adder/AdderViewModel.swift | 1 | 1280 | import Combine
final class AdderViewModel: ObservableObject {
@Published private(set) var tickerRowViewModels: [TickerRowViewModel]?
@Published var searchString = ""
private let dataRepository: DataRepository
init(dataRepository: DataRepository) {
self.dataRepository = dataRepository
Publishers
.CombineLatest3(dataRepository.$tickers, dataRepository.$userTickerIds, $searchString)
.compactMap { $0.0.tickerRowViewModels(userTickerIds: $0.1, searchString: $0.2) }
.assign(to: &$tickerRowViewModels)
}
func appendUserTickerId(_ tickerId: String) {
dataRepository.userTickerIds.append(tickerId)
AnalyticsService.shared.trackUserTickerAppended(tickerId: tickerId)
}
}
private extension Array where Element == Ticker {
func tickerRowViewModels(userTickerIds: [String], searchString: String) -> [TickerRowViewModel] {
filter { userTickerIds.contains($0.id) == false }
.map { TickerRowViewModel(ticker: $0) }
.filter {
(searchString.isEmpty || $0.tags.joined(separator: " ").contains(searchString.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()))
}
}
}
| mit | 23759a21d433cedb40f3e883a1f499f0 | 33.594595 | 156 | 0.659375 | 4.55516 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Mapper/DataIncludeMapper/DataIncludeMapper.swift | 1 | 3420 | //
// DataIncludeMapper.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import ObjectMapper
public protocol DataIncludeMapperParser {
func dataIncludeMapper(sender: DataIncludeMapper, mapperFor json: [String: Any], typeString: String) -> Mappable?
func dataIncludeMapper(sender: DataIncludeMapper, objectFor mapper: Mappable, metadata: Metadata?, shouldMap2ndLevelRelationships: Bool) -> Identifiable?
}
public class DataIncludeMapper {
private let metadata: Metadata?
private let includeResponse: Array<Dictionary<String, AnyObject>>
private lazy var mappers: Dictionary<String, Mappable> = self.parseMappers()
private let parser: DataIncludeMapperParser
public init(includeResponse: Array<Dictionary<String, AnyObject>>, metadata: Metadata?, parser: DataIncludeMapperParser = DataIncludeMapperDefaultParser()) {
self.metadata = metadata
self.includeResponse = includeResponse
self.parser = parser
}
fileprivate func parseMappers() -> Dictionary<String, Mappable> {
var mappers = Dictionary<String, Mappable>()
for object in includeResponse {
if let mappedObject = mapperForObject(object) {
mappers[mappedObject.identifier] = mappedObject.mapper
}
}
return mappers
}
func objectWithIdentifier<T: Identifiable>(_ identifier: String, type: T.Type, shouldMap2ndLevelRelationships: Bool = true) -> T? {
guard let mapper = mappers[identifier]
else { return nil }
return parser.dataIncludeMapper(sender: self, objectFor: mapper, metadata: metadata, shouldMap2ndLevelRelationships: shouldMap2ndLevelRelationships) as? T
}
// MARK: - Included response parse
fileprivate func mapperForObject(_ obj: Dictionary<String, AnyObject>) -> (identifier: String, mapper: Mappable)? {
guard let typeString = obj["type"] as? String,
let identifierString = obj["id"] as? String
else { return nil }
let mapper = parser.dataIncludeMapper(sender: self, mapperFor: obj, typeString: typeString)
if (mapper == nil) { Logger.log(.warning, "Unknown typeString: \(typeString)") }
return mapper == nil ? nil : (identifierString, mapper!)
}
}
| mit | 919911b7d9587c1151139e4257a8e592 | 44.6 | 162 | 0.71462 | 4.572193 | false | false | false | false |
christophhagen/Signal-iOS | Signal/src/call/SignalCall.swift | 1 | 6629 | //
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import SignalServiceKit
enum CallState: String {
case idle
case dialing
case answering
case remoteRinging
case localRinging
case connected
case localFailure // terminal
case localHangup // terminal
case remoteHangup // terminal
case remoteBusy // terminal
}
enum CallDirection {
case outgoing, incoming
}
// All Observer methods will be invoked from the main thread.
protocol CallObserver: class {
func stateDidChange(call: SignalCall, state: CallState)
func hasLocalVideoDidChange(call: SignalCall, hasLocalVideo: Bool)
func muteDidChange(call: SignalCall, isMuted: Bool)
func holdDidChange(call: SignalCall, isOnHold: Bool)
func audioSourceDidChange(call: SignalCall, audioSource: AudioSource?)
}
/**
* Data model for a WebRTC backed voice/video call.
*
* This class' state should only be accessed on the main queue.
*/
@objc class SignalCall: NSObject {
let TAG = "[SignalCall]"
var observers = [Weak<CallObserver>]()
let remotePhoneNumber: String
// Signal Service identifier for this Call. Used to coordinate the call across remote clients.
let signalingId: UInt64
let direction: CallDirection
// Distinguishes between calls locally, e.g. in CallKit
let localId: UUID
let thread: TSContactThread
var callRecord: TSCall? {
didSet {
AssertIsOnMainThread()
assert(oldValue == nil)
updateCallRecordType()
}
}
var hasLocalVideo = false {
didSet {
AssertIsOnMainThread()
for observer in observers {
observer.value?.hasLocalVideoDidChange(call: self, hasLocalVideo: hasLocalVideo)
}
}
}
var state: CallState {
didSet {
AssertIsOnMainThread()
Logger.debug("\(TAG) state changed: \(oldValue) -> \(self.state) for call: \(self.identifiersForLogs)")
// Update connectedDate
if self.state == .connected {
if connectedDate == nil {
connectedDate = NSDate()
}
} else {
connectedDate = nil
}
updateCallRecordType()
for observer in observers {
observer.value?.stateDidChange(call: self, state: state)
}
}
}
var isMuted = false {
didSet {
AssertIsOnMainThread()
Logger.debug("\(TAG) muted changed: \(oldValue) -> \(self.isMuted)")
for observer in observers {
observer.value?.muteDidChange(call: self, isMuted: isMuted)
}
}
}
var audioSource: AudioSource? = nil {
didSet {
AssertIsOnMainThread()
Logger.debug("\(TAG) audioSource changed: \(String(describing:oldValue)) -> \(String(describing: audioSource))")
for observer in observers {
observer.value?.audioSourceDidChange(call: self, audioSource: audioSource)
}
}
}
var isSpeakerphoneEnabled: Bool {
guard let audioSource = self.audioSource else {
return false
}
return audioSource.isBuiltInSpeaker
}
var isOnHold = false {
didSet {
AssertIsOnMainThread()
Logger.debug("\(TAG) isOnHold changed: \(oldValue) -> \(self.isOnHold)")
for observer in observers {
observer.value?.holdDidChange(call: self, isOnHold: isOnHold)
}
}
}
var connectedDate: NSDate?
var error: CallError?
// MARK: Initializers and Factory Methods
init(direction: CallDirection, localId: UUID, signalingId: UInt64, state: CallState, remotePhoneNumber: String) {
self.direction = direction
self.localId = localId
self.signalingId = signalingId
self.state = state
self.remotePhoneNumber = remotePhoneNumber
self.thread = TSContactThread.getOrCreateThread(contactId: remotePhoneNumber)
}
// A string containing the three identifiers for this call.
var identifiersForLogs: String {
return "{\(remotePhoneNumber), \(localId), \(signalingId)}"
}
class func outgoingCall(localId: UUID, remotePhoneNumber: String) -> SignalCall {
return SignalCall(direction: .outgoing, localId: localId, signalingId: newCallSignalingId(), state: .dialing, remotePhoneNumber: remotePhoneNumber)
}
class func incomingCall(localId: UUID, remotePhoneNumber: String, signalingId: UInt64) -> SignalCall {
return SignalCall(direction: .incoming, localId: localId, signalingId: signalingId, state: .answering, remotePhoneNumber: remotePhoneNumber)
}
// -
func addObserverAndSyncState(observer: CallObserver) {
AssertIsOnMainThread()
observers.append(Weak(value: observer))
// Synchronize observer with current call state
observer.stateDidChange(call: self, state: state)
}
func removeObserver(_ observer: CallObserver) {
AssertIsOnMainThread()
while let index = observers.index(where: { $0.value === observer }) {
observers.remove(at: index)
}
}
func removeAllObservers() {
AssertIsOnMainThread()
observers = []
}
private func updateCallRecordType() {
AssertIsOnMainThread()
guard let callRecord = self.callRecord else {
return
}
// Mark incomplete calls as completed if call has connected.
if state == .connected &&
callRecord.callType == RPRecentCallTypeOutgoingIncomplete {
callRecord.updateCallType(RPRecentCallTypeOutgoing)
}
if state == .connected &&
callRecord.callType == RPRecentCallTypeIncomingIncomplete {
callRecord.updateCallType(RPRecentCallTypeIncoming)
}
}
// MARK: Equatable
static func == (lhs: SignalCall, rhs: SignalCall) -> Bool {
return lhs.localId == rhs.localId
}
static func newCallSignalingId() -> UInt64 {
return UInt64.ows_random()
}
// This method should only be called when the call state is "connected".
func connectionDuration() -> TimeInterval {
return -connectedDate!.timeIntervalSinceNow
}
}
fileprivate extension UInt64 {
static func ows_random() -> UInt64 {
var random: UInt64 = 0
arc4random_buf(&random, MemoryLayout.size(ofValue: random))
return random
}
}
| gpl-3.0 | f8af79d6f2ae89b242c4ec6b42dad347 | 27.450644 | 155 | 0.627093 | 5.075804 | false | false | false | false |
apple/swift | stdlib/public/Concurrency/CheckedContinuation.swift | 2 | 11779 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
@_silgen_name("swift_continuation_logFailedCheck")
internal func logFailedCheck(_ message: UnsafeRawPointer)
/// Implementation class that holds the `UnsafeContinuation` instance for
/// a `CheckedContinuation`.
@available(SwiftStdlib 5.1, *)
internal final class CheckedContinuationCanary: @unchecked Sendable {
// The instance state is stored in tail-allocated raw memory, so that
// we can atomically check the continuation state.
private init() { fatalError("must use create") }
private static func _create(continuation: UnsafeRawPointer, function: String)
-> Self {
let instance = Builtin.allocWithTailElems_1(self,
1._builtinWordValue,
(UnsafeRawPointer?, String).self)
instance._continuationPtr.initialize(to: continuation)
instance._functionPtr.initialize(to: function)
return instance
}
private var _continuationPtr: UnsafeMutablePointer<UnsafeRawPointer?> {
return UnsafeMutablePointer<UnsafeRawPointer?>(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
}
private var _functionPtr: UnsafeMutablePointer<String> {
let tailPtr = UnsafeMutableRawPointer(
Builtin.projectTailElems(self, (UnsafeRawPointer?, String).self))
let functionPtr = tailPtr
+ MemoryLayout<(UnsafeRawPointer?, String)>.offset(of: \(UnsafeRawPointer?, String).1)!
return functionPtr.assumingMemoryBound(to: String.self)
}
internal static func create<T, E>(continuation: UnsafeContinuation<T, E>,
function: String) -> Self {
return _create(
continuation: unsafeBitCast(continuation, to: UnsafeRawPointer.self),
function: function)
}
internal var function: String {
return _functionPtr.pointee
}
// Take the continuation away from the container, or return nil if it's
// already been taken.
internal func takeContinuation<T, E>() -> UnsafeContinuation<T, E>? {
// Atomically exchange the current continuation value with a null pointer.
let rawContinuationPtr = unsafeBitCast(_continuationPtr,
to: Builtin.RawPointer.self)
let rawOld = Builtin.atomicrmw_xchg_seqcst_Word(rawContinuationPtr,
0._builtinWordValue)
return unsafeBitCast(rawOld, to: UnsafeContinuation<T, E>?.self)
}
deinit {
_functionPtr.deinitialize(count: 1)
// Log if the continuation was never consumed before the instance was
// destructed.
if _continuationPtr.pointee != nil {
logFailedCheck("SWIFT TASK CONTINUATION MISUSE: \(function) leaked its continuation!\n")
}
}
}
/// A mechanism to interface
/// between synchronous and asynchronous code,
/// logging correctness violations.
///
/// A *continuation* is an opaque representation of program state.
/// To create a continuation in asynchronous code,
/// call the `withUnsafeContinuation(function:_:)` or
/// `withUnsafeThrowingContinuation(function:_:)` function.
/// To resume the asynchronous task,
/// call the `resume(returning:)`,
/// `resume(throwing:)`,
/// `resume(with:)`,
/// or `resume()` method.
///
/// - Important: You must call a resume method exactly once
/// on every execution path throughout the program.
///
/// Resuming from a continuation more than once is undefined behavior.
/// Never resuming leaves the task in a suspended state indefinitely,
/// and leaks any associated resources.
/// `CheckedContinuation` logs a message
/// if either of these invariants is violated.
///
/// `CheckedContinuation` performs runtime checks
/// for missing or multiple resume operations.
/// `UnsafeContinuation` avoids enforcing these invariants at runtime
/// because it aims to be a low-overhead mechanism
/// for interfacing Swift tasks with
/// event loops, delegate methods, callbacks,
/// and other non-`async` scheduling mechanisms.
/// However, during development, the ability to verify that the
/// invariants are being upheld in testing is important.
/// Because both types have the same interface,
/// you can replace one with the other in most circumstances,
/// without making other changes.
@available(SwiftStdlib 5.1, *)
public struct CheckedContinuation<T, E: Error>: Sendable {
private let canary: CheckedContinuationCanary
/// Creates a checked continuation from an unsafe continuation.
///
/// Instead of calling this initializer,
/// most code calls the `withCheckedContinuation(function:_:)` or
/// `withCheckedThrowingContinuation(function:_:)` function instead.
/// You only need to initialize
/// your own `CheckedContinuation<T, E>` if you already have an
/// `UnsafeContinuation` you want to impose checking on.
///
/// - Parameters:
/// - continuation: An instance of `UnsafeContinuation`
/// that hasn't yet been resumed.
/// After passing the unsafe continuation to this initializer,
/// don't use it outside of this object.
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
public init(continuation: UnsafeContinuation<T, E>, function: String = #function) {
canary = CheckedContinuationCanary.create(
continuation: continuation,
function: function)
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// - Parameter value: The value to return from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
public func resume(returning value: __owned T) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(returning: value)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, returning \(value)!\n")
}
}
/// Resume the task awaiting the continuation by having it throw an error
/// from its suspension point.
///
/// - Parameter error: The error to throw from the continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
public func resume(throwing error: __owned E) {
if let c: UnsafeContinuation<T, E> = canary.takeContinuation() {
c.resume(throwing: error)
} else {
fatalError("SWIFT TASK CONTINUATION MISUSE: \(canary.function) tried to resume its continuation more than once, throwing \(error)!\n")
}
}
}
@available(SwiftStdlib 5.1, *)
extension CheckedContinuation {
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume<Er: Error>(with result: Result<T, Er>) where E == Error {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it either
/// return normally or throw an error based on the state of the given
/// `Result` value.
///
/// - Parameter result: A value to either return or throw from the
/// continuation.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume(with result: Result<T, E>) {
switch result {
case .success(let val):
self.resume(returning: val)
case .failure(let err):
self.resume(throwing: err)
}
}
/// Resume the task awaiting the continuation by having it return normally
/// from its suspension point.
///
/// A continuation must be resumed exactly once. If the continuation has
/// already been resumed through this object, then the attempt to resume
/// the continuation will trap.
///
/// After `resume` enqueues the task, control immediately returns to
/// the caller. The task continues executing when its executor is
/// able to reschedule it.
@_alwaysEmitIntoClient
public func resume() where T == Void {
self.resume(returning: ())
}
}
/// Suspends the current task,
/// then calls the given closure with a checked continuation for the current task.
///
/// - Parameters:
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
/// - body: A closure that takes a `CheckedContinuation` parameter.
/// You must resume the continuation exactly once.
@available(SwiftStdlib 5.1, *)
@_unsafeInheritExecutor // ABI compatibility with Swift 5.1
@inlinable
public func withCheckedContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Never>) -> Void
) async -> T {
return await withUnsafeContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
/// Suspends the current task,
/// then calls the given closure with a checked throwing continuation for the current task.
///
/// - Parameters:
/// - function: A string identifying the declaration that is the notional
/// source for the continuation, used to identify the continuation in
/// runtime diagnostics related to misuse of this continuation.
/// - body: A closure that takes a `CheckedContinuation` parameter.
/// You must resume the continuation exactly once.
///
/// If `resume(throwing:)` is called on the continuation,
/// this function throws that error.
@available(SwiftStdlib 5.1, *)
@_unsafeInheritExecutor // ABI compatibility with Swift 5.1
@inlinable
public func withCheckedThrowingContinuation<T>(
function: String = #function,
_ body: (CheckedContinuation<T, Error>) -> Void
) async throws -> T {
return try await withUnsafeThrowingContinuation {
body(CheckedContinuation(continuation: $0, function: function))
}
}
| apache-2.0 | 219f5acf0a89833632d3fc9d34077428 | 38.394649 | 141 | 0.701842 | 4.770757 | false | false | false | false |
Zewo/TCPIP | Sources/TCPIP/IP.swift | 1 | 2407 | // IP.swift
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Zewo
//
// 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 CTide
public enum IPMode {
case IPV4
case IPV6
case IPV4Prefered
case IPV6Prefered
}
extension IPMode {
var code: Int32 {
switch self {
case .IPV4: return 1
case .IPV6: return 2
case .IPV4Prefered: return 3
case .IPV6Prefered: return 4
}
}
}
public struct IP {
let address: ipaddr
public init(port: Int, mode: IPMode = .IPV4) throws {
self.address = iplocal(nil, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
public init(networkInterface: String, port: Int, mode: IPMode = .IPV4) throws {
self.address = iplocal(networkInterface, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
public init(address: String, port: Int, mode: IPMode = .IPV4) throws {
self.address = ipremote(address, Int32(port), mode.code)
if errno != 0 {
let description = IPError.lastSystemErrorDescription
throw IPError(description: description)
}
}
}
| mit | caf9e02c5191e2fb9faf3b7651b1a22a | 31.527027 | 83 | 0.677192 | 4.329137 | false | false | false | false |
CanBeMyQueen/DouYuZB | DouYu/DouYu/Classes/Home/View/AmuseMenuView.swift | 1 | 2347 | //
// AmuseMenuView.swift
// DouYu
//
// Created by 张萌 on 2018/1/23.
// Copyright © 2018年 JiaYin. All rights reserved.
//
import UIKit
private let AmuseMenuCellID = "AmuseMenuCellID"
class AmuseMenuView: UIView {
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var pageControl: UIPageControl!
var anchorGroups : [AnchorGroupModel]? {
didSet {
collectionView.reloadData()
}
}
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "AmuseMenuCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: AmuseMenuCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = collectionView.bounds.size
}
}
extension AmuseMenuView {
class func amuseMenuView() -> AmuseMenuView {
return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
}
}
extension AmuseMenuView : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if anchorGroups == nil { return 0 }
let pageNum = (anchorGroups?.count)! / 8
pageControl.numberOfPages = pageNum
return pageNum
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AmuseMenuCellID, for: indexPath) as! AmuseMenuCollectionViewCell
setupCellValue(cell: cell, indexPath: indexPath)
return cell
}
private func setupCellValue(cell : AmuseMenuCollectionViewCell, indexPath: IndexPath) {
let startIndex = indexPath.row * 8
var endIndex = (indexPath.row + 1) * 8 - 1
if endIndex > (anchorGroups?.count)! - 1 {
endIndex = (anchorGroups?.count)! - 1
}
cell.groups = Array(anchorGroups![startIndex...endIndex])
}
}
extension AmuseMenuView : UICollectionViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
pageControl.currentPage = Int(collectionView.contentOffset.x / collectionView.bounds.size.width)
}
}
| mit | e0c8c0d8db41a2780ab647a4fd4b9290 | 31.957746 | 139 | 0.697009 | 5.165563 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/Pods/Kingfisher/Sources/Filter.swift | 28 | 5475 | //
// Filter.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/31.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import CoreImage
import Accelerate
// Reuse the same CI Context for all CI drawing.
private let ciContext = CIContext(options: nil)
/// Transformer method which will be used in to provide a `Filter`.
public typealias Transformer = (CIImage) -> CIImage?
/// Supply a filter to create an `ImageProcessor`.
public protocol CIImageProcessor: ImageProcessor {
var filter: Filter { get }
}
extension CIImageProcessor {
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.apply(filter)
case .data(_):
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Wrapper for a `Transformer` of CIImage filters.
public struct Filter {
let transform: Transformer
public init(tranform: @escaping Transformer) {
self.transform = tranform
}
/// Tint filter which will apply a tint color to images.
public static var tint: (Color) -> Filter = {
color in
Filter { input in
let colorFilter = CIFilter(name: "CIConstantColorGenerator")!
colorFilter.setValue(CIColor(color: color), forKey: kCIInputColorKey)
let colorImage = colorFilter.outputImage
let filter = CIFilter(name: "CISourceOverCompositing")!
filter.setValue(colorImage, forKey: kCIInputImageKey)
filter.setValue(input, forKey: kCIInputBackgroundImageKey)
return filter.outputImage?.cropping(to: input.extent)
}
}
public typealias ColorElement = (CGFloat, CGFloat, CGFloat, CGFloat)
/// Color control filter which will apply color control change to images.
public static var colorControl: (ColorElement) -> Filter = {
brightness, contrast, saturation, inputEV in
Filter { input in
let paramsColor = [kCIInputBrightnessKey: brightness,
kCIInputContrastKey: contrast,
kCIInputSaturationKey: saturation]
let blackAndWhite = input.applyingFilter("CIColorControls", withInputParameters: paramsColor)
let paramsExposure = [kCIInputEVKey: inputEV]
return blackAndWhite.applyingFilter("CIExposureAdjust", withInputParameters: paramsExposure)
}
}
}
extension Kingfisher where Base: Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
public func apply(_ filter: Filter) -> Image {
guard let cgImage = cgImage else {
assertionFailure("[Kingfisher] Tint image only works for CG-based image.")
return base
}
let inputImage = CIImage(cgImage: cgImage)
guard let outputImage = filter.transform(inputImage) else {
return base
}
guard let result = ciContext.createCGImage(outputImage, from: outputImage.extent) else {
assertionFailure("[Kingfisher] Can not make an tint image within context.")
return base
}
#if os(macOS)
return fixedForRetinaPixel(cgImage: result, to: size)
#else
return Image(cgImage: result, scale: base.scale, orientation: base.imageOrientation)
#endif
}
}
public extension Image {
/// Apply a `Filter` containing `CIImage` transformer to `self`.
///
/// - parameter filter: The filter used to transform `self`.
///
/// - returns: A transformed image by input `Filter`.
///
/// - Note: Only CG-based images are supported. If any error happens during transforming, `self` will be returned.
@available(*, deprecated,
message: "Extensions directly on Image are deprecated. Use `kf.apply` instead.",
renamed: "kf.apply")
public func kf_apply(_ filter: Filter) -> Image {
return kf.apply(filter)
}
}
| apache-2.0 | fae662cad2b34b0939fb3ff34ea4f007 | 36.758621 | 118 | 0.658995 | 4.785839 | false | false | false | false |
tkremenek/swift | test/Serialization/function.swift | 30 | 5452 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/def_func.swift
// RUN: llvm-bcanalyzer %t/def_func.swiftmodule | %FileCheck %s
// RUN: %target-swift-frontend -module-name function -emit-silgen -I %t %s | %FileCheck %s -check-prefix=SIL
// CHECK-NOT: FALL_BACK_TO_TRANSLATION_UNIT
// CHECK-NOT: UnknownCode
import def_func
func useEq<T: EqualOperator>(_ x: T, y: T) -> Bool {
return x == y
}
// SIL: sil [ossa] @main
// SIL: [[RAW:%.+]] = global_addr @$s8function3rawSivp : $*Int
// SIL: [[ZERO:%.+]] = function_ref @$s8def_func7getZeroSiyF : $@convention(thin) () -> Int
// SIL: [[RESULT:%.+]] = apply [[ZERO]]() : $@convention(thin) () -> Int
// SIL: store [[RESULT]] to [trivial] [[RAW]] : $*Int
var raw = getZero()
// Check that 'raw' is an Int
var cooked : Int = raw
// SIL: [[GET_INPUT:%.+]] = function_ref @$s8def_func8getInput1xS2i_tF : $@convention(thin) (Int) -> Int
// SIL: {{%.+}} = apply [[GET_INPUT]]({{%.+}}) : $@convention(thin) (Int) -> Int
var raw2 = getInput(x: raw)
// SIL: [[GET_SECOND:%.+]] = function_ref @$s8def_func9getSecond_1yS2i_SitF : $@convention(thin) (Int, Int) -> Int
// SIL: {{%.+}} = apply [[GET_SECOND]]({{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int) -> Int
var raw3 = getSecond(raw, y: raw2)
// SIL: [[USE_NESTED:%.+]] = function_ref @$s8def_func9useNested_1nySi1x_Si1yt_SitF : $@convention(thin) (Int, Int, Int) -> ()
// SIL: {{%.+}} = apply [[USE_NESTED]]({{%.+}}, {{%.+}}, {{%.+}}) : $@convention(thin) (Int, Int, Int) -> ()
useNested((raw, raw2), n: raw3)
// SIL: [[VA_SIZE:%.+]] = integer_literal $Builtin.Word, 2
// SIL: {{%.+}} = apply {{%.*}}<Int>([[VA_SIZE]])
// SIL: [[VARIADIC:%.+]] = function_ref @$s8def_func8variadic1x_ySd_SidtF : $@convention(thin) (Double, @guaranteed Array<Int>) -> ()
// SIL: {{%.+}} = apply [[VARIADIC]]({{%.+}}, {{%.+}}) : $@convention(thin) (Double, @guaranteed Array<Int>) -> ()
variadic(x: 2.5, 4, 5)
// SIL: [[VARIADIC:%.+]] = function_ref @$s8def_func9variadic2_1xySid_SdtF : $@convention(thin) (@guaranteed Array<Int>, Double) -> ()
variadic2(1, 2, 3, x: 5.0)
// SIL: [[SLICE_SIZE:%.+]] = integer_literal $Builtin.Word, 3
// SIL: {{%.+}} = apply {{%.*}}<Int>([[SLICE_SIZE]])
// SIL: [[SLICE:%.+]] = function_ref @$s8def_func5slice1xySaySiG_tF : $@convention(thin) (@guaranteed Array<Int>) -> ()
// SIL: {{%.+}} = apply [[SLICE]]({{%.+}}) : $@convention(thin) (@guaranteed Array<Int>) -> ()
slice(x: [2, 4, 5])
optional(x: .some(23))
optional(x: .none)
// SIL: [[MAKE_PAIR:%.+]] = function_ref @$s8def_func8makePair{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0, τ_0_1> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> (@out τ_0_0, @out τ_0_1)
// SIL: {{%.+}} = apply [[MAKE_PAIR]]<Int, Double>({{%.+}}, {{%.+}})
var pair : (Int, Double) = makePair(a: 1, b: 2.5)
// SIL: [[DIFFERENT_A:%.+]] = function_ref @$s8def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// SIL: [[DIFFERENT_B:%.+]] = function_ref @$s8def_func9different{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
_ = different(a: 1, b: 2)
_ = different(a: false, b: false)
// SIL: [[DIFFERENT2_A:%.+]] = function_ref @$s8def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// SIL: [[DIFFERENT2_B:%.+]] = function_ref @$s8def_func10different2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0 where τ_0_0 : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
_ = different2(a: 1, b: 2)
_ = different2(a: false, b: false)
struct IntWrapper1 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 1 }
}
struct IntWrapper2 : Wrapped {
typealias Value = Int
func getValue() -> Int { return 2 }
}
// SIL: [[DIFFERENT_WRAPPED:%.+]] = function_ref @$s8def_func16differentWrapped1a1bSbx_q_tAA0D0RzAaER_5ValueQy_AFRtzr0_lF : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Wrapped, τ_0_1 : Wrapped, τ_0_0.Value == τ_0_1.Value> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_1) -> Bool
_ = differentWrapped(a: IntWrapper1(), b: IntWrapper2())
// SIL: {{%.+}} = function_ref @$s8def_func10overloaded1xySi_tF : $@convention(thin) (Int) -> ()
// SIL: {{%.+}} = function_ref @$s8def_func10overloaded1xySb_tF : $@convention(thin) (Bool) -> ()
overloaded(x: 1)
overloaded(x: false)
// SIL: {{%.+}} = function_ref @primitive : $@convention(thin) () -> ()
primitive()
if raw == 5 {
testNoReturnAttr()
testNoReturnAttrPoly(x: 5)
}
// SIL: {{%.+}} = function_ref @$s8def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: {{%.+}} = function_ref @$s8def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> Never
// SIL: sil @$s8def_func16testNoReturnAttrs5NeverOyF : $@convention(thin) () -> Never
// SIL: sil @$s8def_func20testNoReturnAttrPoly{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> Never
do {
try throws1()
_ = try throws2(1)
} catch _ {}
// SIL: sil @$s8def_func7throws1yyKF : $@convention(thin) () -> @error Error
// SIL: sil @$s8def_func7throws2{{[_0-9a-zA-Z]*}}F : $@convention(thin) <τ_0_0> (@in_guaranteed τ_0_0) -> (@out τ_0_0, @error Error)
// LLVM: }
| apache-2.0 | b2f1021eab0c2c16fabb40d6aa670ae0 | 44.125 | 279 | 0.593167 | 2.789799 | false | false | false | false |
dcharbonnier/HanekeSwift | HanekeTests/UIImageView+HanekeTests.swift | 2 | 21238 | //
// UIImageView+HanekeTests.swift
// Haneke
//
// Created by Hermes Pique on 9/17/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import UIKit
import XCTest
import OHHTTPStubs
@testable import Haneke
class UIImageView_HanekeTests: DiskTestCase {
var sut : UIImageView!
override func setUp() {
super.setUp()
sut = UIImageView(frame: CGRectMake(0, 0, 10, 10))
}
override func tearDown() {
OHHTTPStubs.removeAllStubs()
let cache = Shared.imageCache
cache.removeAll()
super.tearDown()
}
func testScaleMode_ScaleToFill() {
sut.contentMode = .ScaleToFill
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.Fill)
}
func testScaleMode_ScaleAspectFit() {
sut.contentMode = .ScaleAspectFit
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.AspectFit)
}
func testScaleMode_ScaleAspectFill() {
sut.contentMode = .ScaleAspectFill
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.AspectFill)
}
func testScaleMode_Redraw() {
sut.contentMode = .Redraw
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_Center() {
sut.contentMode = .Center
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_Top() {
sut.contentMode = .Top
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_Bottom() {
sut.contentMode = .Bottom
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_Left() {
sut.contentMode = .Left
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_Right() {
sut.contentMode = .Right
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_TopLeft() {
sut.contentMode = .TopLeft
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_TopRight() {
sut.contentMode = .TopRight
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_BottomLeft() {
sut.contentMode = .BottomLeft
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testScaleMode_BottomRight() {
sut.contentMode = .BottomRight
XCTAssertEqual(sut.hnk_scaleMode, ImageResizer.ScaleMode.None)
}
func testFormatWithSize() {
let size = CGSizeMake(10, 20)
let scaleMode = ImageResizer.ScaleMode.Fill
let image = UIImage.imageWithColor(UIColor.redColor())
let resizer = ImageResizer(size: size, scaleMode: scaleMode, allowUpscaling: true, compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
let format = HanekeGlobals.UIKit.formatWithSize(size, scaleMode: scaleMode)
XCTAssertEqual(format.diskCapacity, HanekeGlobals.UIKit.DefaultFormat.DiskCapacity)
let result = format.apply(image)
let expected = resizer.resizeImage(image)
XCTAssertTrue(result.isEqualPixelByPixel(expected))
}
func testFormat_Default() {
let cache = Shared.imageCache
let resizer = ImageResizer(size: sut.bounds.size, scaleMode: sut.hnk_scaleMode, allowUpscaling: true, compressionQuality: HanekeGlobals.UIKit.DefaultFormat.CompressionQuality)
let image = UIImage.imageWithColor(UIColor.greenColor())
let format = sut.hnk_format
XCTAssertEqual(format.diskCapacity, HanekeGlobals.UIKit.DefaultFormat.DiskCapacity)
XCTAssertTrue(cache.formats[format.name] != nil) // Can't use XCTAssertNotNil because it expects AnyObject
let result = format.apply(image)
let expected = resizer.resizeImage(image)
XCTAssertTrue(result.isEqualPixelByPixel(expected))
}
// MARK: setImage
func testSetImage_MemoryMiss() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
sut.hnk_setImage(image, key: key)
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, key)
}
func testSetImage_MemoryHit() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let expectedImage = setImage(image, key: key)
sut.hnk_setImage(image, key: key)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImage_ImageSet_MemoryMiss() {
let previousImage = UIImage.imageWithColor(UIColor.redColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
sut.image = previousImage
sut.hnk_setImage(image, key: key)
XCTAssertEqual(sut.image!, previousImage)
XCTAssertEqual(sut.hnk_fetcher.key, key)
}
func testSetImage_UsingPlaceholder_MemoryMiss() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
sut.hnk_setImage(image, key: key, placeholder: placeholder)
XCTAssertEqual(sut.image!, placeholder)
XCTAssertEqual(sut.hnk_fetcher.key, key)
}
func testSetImage_UsingPlaceholder_MemoryHit() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let expectedImage = setImage(image, key: key)
sut.hnk_setImage(image, key: key, placeholder: placeholder)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImage_Success() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
sut.contentMode = .Center // No resizing
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImage(image, key: key, success:{resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(image))
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, key)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImage_UsingFormat() {
let image = UIImage.imageWithColor(UIColor.redColor())
let expectedImage = UIImage.imageWithColor(UIColor.greenColor())
let format = Format<UIImage>(name: self.name, diskCapacity: 0) { _ in return expectedImage }
let key = self.name
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImage(image, key: key, format: format, success:{resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(expectedImage))
expectation.fulfill()
})
self.waitForExpectationsWithTimeout(1, handler: nil)
}
// MARK: setImageFromFetcher
func testSetImageFromFetcher_MemoryMiss() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
sut.hnk_setImageFromFetcher(fetcher)
XCTAssertNil(sut.image)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
}
func testSetImageFromFetcher_MemoryHit() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
let expectedImage = setImage(image, key: key)
sut.hnk_setImageFromFetcher(fetcher)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImageFromFetcher_Hit_Animated() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = AsyncFetcher<UIImage>(key: key, value: image)
let expectedImage = sut.hnk_format.apply(image)
sut.hnk_setImageFromFetcher(fetcher)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
XCTAssertNil(sut.image)
self.wait(1) {
return self.sut.image != nil
}
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertNil(sut.hnk_fetcher)
}
func testSetImageFromFetcher_ImageSet_MemoryMiss() {
let previousImage = UIImage.imageWithColor(UIColor.redColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
sut.image = previousImage
sut.hnk_setImageFromFetcher(fetcher)
XCTAssertEqual(sut.image!, previousImage)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
}
func testSetImageFromFetcher_UsingPlaceholder_MemoryMiss() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
sut.hnk_setImageFromFetcher(fetcher, placeholder:placeholder)
XCTAssertEqual(sut.image!, placeholder)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
}
func testSetImageFromFetcher_UsingPlaceholder_MemoryHit() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
let expectedImage = setImage(image, key: key)
sut.hnk_setImageFromFetcher(fetcher, placeholder:placeholder)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImageFromFetcher_Success() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
sut.contentMode = .Center // No resizing
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromFetcher(fetcher, success: { resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(image))
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImageFromFetcher_Failure() {
let key = self.name
let fetcher = MockFetcher<UIImage>(key:key)
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromFetcher(fetcher, failure: {error in
XCTAssertEqual(error!.domain, HanekeGlobals.Domain)
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertTrue(sut.hnk_fetcher === fetcher)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImageFromFetcher_UsingFormat() {
let image = UIImage.imageWithColor(UIColor.redColor())
let expectedImage = UIImage.imageWithColor(UIColor.greenColor())
let format = Format<UIImage>(name: self.name, diskCapacity: 0) { _ in return expectedImage }
let key = self.name
let fetcher = SimpleFetcher<UIImage>(key: key, value: image)
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromFetcher(fetcher, format: format, success: { resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(expectedImage))
expectation.fulfill()
})
self.waitForExpectationsWithTimeout(1, handler: nil)
}
// MARK: setImageFromFile
func testSetImageFromFile_MemoryMiss() {
let fetcher = DiskFetcher<UIImage>(path: self.uniquePath())
sut.hnk_setImageFromFile(fetcher.key)
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
}
func testSetImageFromFile_MemoryHit() {
let image = UIImage.imageWithColor(UIColor.orangeColor())
let fetcher = DiskFetcher<UIImage>(path: self.uniquePath())
let expectedImage = setImage(image, key: fetcher.key)
sut.hnk_setImageFromFile(fetcher.key)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImageFromFileSuccessFailure_MemoryHit() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let fetcher = DiskFetcher<UIImage>(path: self.uniquePath())
let expectedImage = setImage(image, key: fetcher.key)
sut.hnk_setImageFromFile(fetcher.key, failure: {error in
XCTFail("")
}) { result in
XCTAssertTrue(result.isEqualPixelByPixel(expectedImage))
}
}
// MARK: setImageFromURL
func testSetImageFromURL_MemoryMiss() {
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
sut.hnk_setImageFromURL(URL)
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
}
func testSetImageFromURL_MemoryHit() {
let image = UIImage.imageWithColor(UIColor.greenColor())
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
let expectedImage = setImage(image, key: fetcher.key)
sut.hnk_setImageFromURL(URL)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImageFromURL_ImageSet_MemoryMiss() {
let previousImage = UIImage.imageWithColor(UIColor.redColor())
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
sut.image = previousImage
sut.hnk_setImageFromURL(URL)
XCTAssertEqual(sut.image!, previousImage)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
}
func testSetImageFromURL_UsingPlaceholder_MemoryMiss() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
sut.hnk_setImageFromURL(URL, placeholder: placeholder)
XCTAssertEqual(sut.image!, placeholder)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
}
func testSetImageFromURL_UsingPlaceholder_MemoryHit() {
let placeholder = UIImage.imageWithColor(UIColor.yellowColor())
let image = UIImage.imageWithColor(UIColor.greenColor())
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
let expectedImage = setImage(image, key: fetcher.key)
sut.hnk_setImageFromURL(URL, placeholder: placeholder)
XCTAssertTrue(sut.image?.isEqualPixelByPixel(expectedImage) == true)
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testSetImageFromURL_Success() {
let image = UIImage.imageWithColor(UIColor.greenColor())
OHHTTPStubs.stubRequestsPassingTest({ _ in
return true
}, withStubResponse: { _ in
let data = UIImagePNGRepresentation(image)
return OHHTTPStubsResponse(data: data!, statusCode: 200, headers:nil)
})
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
sut.contentMode = .Center // No resizing
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromURL(URL, success:{resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(image))
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImageFromURL_WhenPreviousSetImageFromURL() {
let image = UIImage.imageWithColor(UIColor.greenColor())
OHHTTPStubs.stubRequestsPassingTest({ _ in
return true
}, withStubResponse: { _ in
let data = UIImagePNGRepresentation(image)
return OHHTTPStubsResponse(data: data!, statusCode: 200, headers:nil).responseTime(0.1)
})
let URL1 = NSURL(string: "http://haneke.io/1.png")!
sut.contentMode = .Center // No resizing
sut.hnk_setImageFromURL(URL1, success:{_ in
XCTFail("unexpected success")
}, failure:{_ in
XCTFail("unexpected failure")
})
let URL2 = NSURL(string: "http://haneke.io/2.png")!
let fetcher2 = NetworkFetcher<UIImage>(URL: URL2)
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromURL(URL2, success:{resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(image))
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher2.key)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImageFromURL_Failure() {
OHHTTPStubs.stubRequestsPassingTest({ _ in
return true
}, withStubResponse: { _ in
let data = NSData.dataWithLength(100)
return OHHTTPStubsResponse(data: data, statusCode: 404, headers:nil)
})
let URL = NSURL(string: "http://haneke.io")!
let fetcher = NetworkFetcher<UIImage>(URL: URL)
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromURL(URL, failure:{error in
XCTAssertEqual(error!.domain, HanekeGlobals.Domain)
expectation.fulfill()
})
XCTAssertNil(sut.image)
XCTAssertEqual(sut.hnk_fetcher.key, fetcher.key)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
func testSetImageFromURL_UsingFormat() {
let image = UIImage.imageWithColor(UIColor.redColor())
let expectedImage = UIImage.imageWithColor(UIColor.greenColor())
let format = Format<UIImage>(name: self.name, diskCapacity: 0) { _ in return expectedImage }
OHHTTPStubs.stubRequestsPassingTest({ _ in
return true
}, withStubResponse: { _ in
let data = UIImagePNGRepresentation(image)
return OHHTTPStubsResponse(data: data!, statusCode: 200, headers:nil)
})
let URL = NSURL(string: "http://haneke.io")!
let expectation = self.expectationWithDescription(self.name)
sut.hnk_setImageFromURL(URL, format: format, success:{resultImage in
XCTAssertTrue(resultImage.isEqualPixelByPixel(expectedImage))
expectation.fulfill()
})
self.waitForExpectationsWithTimeout(1, handler: nil)
}
// MARK: cancelSetImage
func testCancelSetImage() {
sut.hnk_cancelSetImage()
XCTAssertTrue(sut.hnk_fetcher == nil)
}
func testCancelSetImage_AfterSetImage() {
let URL = NSURL(string: "http://imgs.xkcd.com/comics/election.png")!
sut.hnk_setImageFromURL(URL, success: { _ in
XCTFail("unexpected success")
}, failure: { _ in
XCTFail("unexpected failure")
})
sut.hnk_cancelSetImage()
XCTAssertTrue(sut.hnk_fetcher == nil)
self.waitFor(0.1)
}
// MARK: Helpers
func setImage(image : UIImage, key: String) -> UIImage {
let format = sut.hnk_format
let expectedImage = format.apply(image)
let cache = Shared.imageCache
cache.addFormat(format)
let expectation = self.expectationWithDescription("set")
cache.set(value: image, key: key, formatName: format.name) { _ in
expectation.fulfill()
}
self.waitForExpectationsWithTimeout(1, handler: nil)
return expectedImage
}
}
class MockFetcher<T : DataConvertible> : Fetcher<T> {
override init(key: String) {
super.init(key: key)
}
override func fetch(failure fail : ((NSError?) -> ()), success succeed : (T.Result) -> ()) {
let error = errorWithCode(0, description: "test")
fail(error)
}
override func cancelFetch() {}
}
| apache-2.0 | 60afe9d14727a68629c31931674b4c0e | 35.491409 | 183 | 0.639279 | 4.885668 | false | true | false | false |
MuYangZhe/Swift30Projects | Project 12 - Tumblr/Tumblr/AppDelegate.swift | 1 | 4578 | //
// AppDelegate.swift
// Tumblr
//
// Created by 牧易 on 17/7/26.
// Copyright © 2017年 MuYi. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "Tumblr")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| mit | 53c98ff2650b874586298c48c7b61019 | 48.150538 | 285 | 0.684752 | 5.830357 | false | false | false | false |
phr85/Shopy | Pods/Sync/Source/Sync/Sync+DATAStack.swift | 1 | 9107 | import DATAStack
public extension Sync {
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter dataStack: The DATAStack instance.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, dataStack: DATAStack, completion: ((_ error: NSError?) -> Void)?) {
self.changes(changes, inEntityNamed: entityName, predicate: nil, dataStack: dataStack, operations: .All, completion: completion)
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter dataStack: The DATAStack instance.
- parameter operations: The type of operations to be applied to the data, Insert, Update, Delete or any possible combination.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, dataStack: DATAStack, operations: Sync.OperationOptions, completion: ((_ error: NSError?) -> Void)?) {
self.changes(changes, inEntityNamed: entityName, predicate: nil, dataStack: dataStack, operations: operations, completion: completion)
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter dataStack: The DATAStack instance.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, dataStack: DATAStack, completion: ((_ error: NSError?) -> Void)?) {
dataStack.performInNewBackgroundContext { backgroundContext in
self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: nil, parentRelationship: nil, inContext: backgroundContext, operations: .All, completion: completion)
}
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter dataStack: The DATAStack instance.
- parameter operations: The type of operations to be applied to the data, Insert, Update, Delete or any possible combination.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, dataStack: DATAStack, operations: Sync.OperationOptions, completion: ((_ error: NSError?) -> Void)?) {
dataStack.performInNewBackgroundContext { backgroundContext in
self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: nil, parentRelationship: nil, inContext: backgroundContext, operations: operations, completion: completion)
}
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter parent: The parent of the synced items, useful if you are syncing the childs of an object, for example
an Album has many photos, if this photos don't incldue the album's JSON object, syncing the photos JSON requires
you to send the parent album to do the proper mapping.
- parameter dataStack: The DATAStack instance.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, parent: NSManagedObject, dataStack: DATAStack, completion: ((_ error: NSError?) -> Void)?) {
dataStack.performInNewBackgroundContext { backgroundContext in
let safeParent = parent.sync_copyInContext(backgroundContext)
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: backgroundContext) else { fatalError("Couldn't find entity named: \(entityName)") }
let relationships = entity.relationships(forDestination: parent.entity)
var predicate: NSPredicate?
let firstRelationship = relationships.first
if let firstRelationship = firstRelationship {
predicate = NSPredicate(format: "%K = %@", firstRelationship.name, safeParent)
}
self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: safeParent, parentRelationship: firstRelationship?.inverseRelationship, inContext: backgroundContext, operations: .All, completion: completion)
}
}
/**
Syncs the entity using the received array of dictionaries, maps one-to-many, many-to-many and one-to-one relationships.
It also syncs relationships where only the id is present, for example if your model is: Company -> Employee,
and your employee has a company_id, it will try to sync using that ID instead of requiring you to provide the
entire company object inside the employees dictionary.
- parameter changes: The array of dictionaries used in the sync process.
- parameter entityName: The name of the entity to be synced.
- parameter predicate: The predicate used to filter out changes, if you want to exclude some local items to be taken in
account in the Sync process, you just need to provide this predicate.
- parameter parent: The parent of the synced items, useful if you are syncing the childs of an object, for example
an Album has many photos, if this photos don't incldue the album's JSON object, syncing the photos JSON requires
- parameter context: The context where the items will be created, in general this should be a background context.
- parameter completion: The completion block, it returns an error if something in the Sync process goes wrong.
*/
public class func changes(_ changes: [[String: Any]], inEntityNamed entityName: String, predicate: NSPredicate?, parent: NSManagedObject?, inContext context: NSManagedObjectContext, completion: ((_ error: NSError?) -> Void)?) {
self.changes(changes, inEntityNamed: entityName, predicate: predicate, parent: parent, parentRelationship: nil, inContext: context, operations: .All, completion: completion)
}
}
| mit | 50bf03fd672897f78bb5453432e530d8 | 78.191304 | 234 | 0.7346 | 5.020397 | false | false | false | false |
andrebocchini/SwiftChattyOSX | Pods/SwiftChatty/SwiftChatty/Requests/Posts/GetPostRequest.swift | 1 | 785 | //
// GetPostRequest.swift
// SwiftChatty
//
// Created by Andre Bocchini on 1/17/16.
// Copyright © 2016 Andre Bocchini. All rights reserved.
//
/// - SeeAlso: http://winchatty.com/v2/readme#_Toc421451671
public struct GetPostRequest: Request {
public let endpoint: ApiEndpoint = .GetPost
public var parameters: [String : AnyObject] = [:]
public init(withPostIds ids: [Int]) {
if ids.count > 0 {
var concatenatedIds: String = ""
for i in 0...(ids.count - 1) {
if i == 0 {
concatenatedIds += String(ids[i])
} else {
concatenatedIds += ("," + String(ids[i]))
}
}
self.parameters["id"] = concatenatedIds
}
}
}
| mit | c08126397d4fedd95f7caa52da97d210 | 26.034483 | 61 | 0.528061 | 4.062176 | false | false | false | false |
coderQuanjun/PigTV | GYJTV/GYJTV/Classes/Main/TQJPageView/TQJPageView.swift | 1 | 2556 | //
// TQJPageView.swift
// GYJTV
//
// Created by 田全军 on 2017/5/15.
// Copyright © 2017年 Quanjun. All rights reserved.
//
import UIKit
class TQJPageView: UIView {
// MARK: 定义属性
fileprivate var titles : [String]!
fileprivate var style : TQJTitleStyle!
fileprivate var childVcs : [UIViewController]!
fileprivate weak var parentVc : UIViewController!
fileprivate var titleView : TQJTitleView!
fileprivate var contentView : TQJContentView!
// MARK: 自定义构造函数
init(frame: CGRect, titles : [String], style : TQJTitleStyle, childVcs : [UIViewController], parentVc : UIViewController) {
super.init(frame: frame)
assert(titles.count == childVcs.count, "标题&控制器个数不同,请检测!!!")
self.style = style
self.titles = titles
self.childVcs = childVcs
self.parentVc = parentVc
parentVc.automaticallyAdjustsScrollViewInsets = false
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置界面内容
extension TQJPageView {
fileprivate func setupUI() {
let titleH : CGFloat = 44
let titleFrame = CGRect(x: 0, y: 0, width: frame.width, height: titleH)
titleView = TQJTitleView(frame: titleFrame, titles: titles, style : style)
titleView.backgroundColor = style.titleBackGroundColor
titleView.delegate = self
addSubview(titleView)
let contentFrame = CGRect(x: 0, y: titleH, width: frame.width, height: frame.height - titleH)
contentView = TQJContentView(frame: contentFrame, childVcs: childVcs, parentViewController: parentVc)
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
contentView.delegate = self
addSubview(contentView)
}
}
// MARK:- 设置TQJContentView的代理
extension TQJPageView : TQJContentViewDelegate {
func contentView(_ contentView: TQJContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
titleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
func contentViewEndScroll(_ contentView: TQJContentView) {
titleView.contentViewDidEndScroll()
}
}
// MARK:- 设置TQJTitleView的代理
extension TQJPageView : TQJTitleViewDelegate {
func titleView(_ titleView: TQJTitleView, selectedIndex index: Int) {
contentView.setCurrentIndex(index)
}
}
| mit | af0865e2a7274d89119be3780bcfa80c | 30.653846 | 127 | 0.677197 | 4.448649 | false | false | false | false |
dps923/winter2017 | notes/week_13/SplitView fixed quirks/splitview/TableViewController.swift | 2 | 854 | import UIKit
class TableViewController: UITableViewController {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
cell.textLabel?.text = "My row number is \(indexPath.row)"
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let nav = segue.destination as! UINavigationController
let vc = nav.viewControllers.first as! ViewController
vc.rowNumber = tableView.indexPathForSelectedRow?.row
}
}
| mit | b57b15ce657845f72d82b136698d70c5 | 36.130435 | 109 | 0.703747 | 5.43949 | false | false | false | false |
muhamed-hafez/twitter-feed | Twitter Feed/Twitter Feed/Model/TFTweet.swift | 1 | 1327 | //
// TFTweet.swift
// Twitter Feed
//
// Created by Muhamed Hafez on 12/16/16.
// Copyright © 2016 Muhamed Hafez. All rights reserved.
//
import Foundation
class TFTweet: TFBaseModel {
var ID: String!
var createdAt: Date!
var user: TFUser!
var text: String!
var hashtags: [TFHashTag]?
var userMentions: [TFUserMention]?
var retweetCount = 0
var favoriteCount = 0
required init(withDictionary dictionary: NSDictionary) {
super.init(withDictionary: dictionary)
// parse the remaining fields
ID = dictionary["id_str"] as! String
user = TFUser(withDictionary: dictionary["user"] as! NSDictionary)
text = dictionary["text"] as? String ?? ""
if let retweetStatus = dictionary["retweeted_status"] as? NSDictionary {
retweetCount = retweetStatus["retweet_count"] as? Int ?? 0
favoriteCount = retweetStatus["favorite_count"] as? Int ?? 0
}
guard let entities = dictionary["entities"] as? NSDictionary else { return }
hashtags = TFHashTag.instancesFromArray(array: entities["hashtags"] as? Array<NSDictionary>) as? [TFHashTag]
userMentions = TFUserMention.instancesFromArray(array: entities["user_mentions"] as? Array<NSDictionary>) as? [TFUserMention]
}
}
| mit | b06133c980712c18d2a65c3f61fef5ef | 33.894737 | 133 | 0.652338 | 4.130841 | false | false | false | false |
programersun/HiChongSwift | HiChongSwift/FindSearchViewController.swift | 1 | 8621 | //
// FindSearchViewController.swift
// HiChongSwift
//
// Created by eagle on 14/12/17.
// Copyright (c) 2014年 多思科技. All rights reserved.
//
import UIKit
class FindSearchViewController: UITableViewController {
private var child: LCYPetSubTypeChildStyle?
private var age: (Int, Int)? {
didSet {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
private var breeding: FindChooseSingleResult = FindChooseSingleResult.Unselected {
didSet {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
private var adopt: FindChooseSingleResult = FindChooseSingleResult.Unselected{
didSet {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 3, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
private var foster: FindChooseSingleResult = FindChooseSingleResult.Unselected{
didSet {
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 4, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
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()
self.title = "搜索"
self.addRightButton("确定", action: "rightButtonPressed:")
self.tableView.hideExtraSeprator()
self.tableView.backgroundColor = UIColor.LCYThemeColor()
let placeHolder = UIView(frame: CGRect(origin: CGPointZero, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 14.0)))
self.tableView.tableHeaderView = placeHolder
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
func rightButtonPressed(sender: AnyObject) {
var parameter = [String: String]()
if let myChild = child {
parameter.extend(["cate_id":myChild.catId])
}
if let myAge = age {
parameter.extend([
"start_age": "\(myAge.0)",
"end_age" : "\(myAge.1)"
])
}
switch breeding {
case .Yes:
parameter.extend(["f_hybridization": "1"])
case .No:
parameter.extend(["f_hybridization": "0"])
case .Unselected:
break
}
switch adopt {
case .Yes:
parameter.extend(["f_adopt": "1"])
case .No:
parameter.extend(["f_adopt": "0"])
case .Unselected:
break
}
switch foster {
case .Yes:
parameter.extend(["is_entrust": "1"])
case .No:
parameter.extend(["is_entrust": "0"])
case .Unselected:
break
}
self.performSegueWithIdentifier("showSearchResult", sender: parameter)
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return 5
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as! UITableViewCell
switch indexPath.row % 2 {
case 0:
cell.backgroundColor = UIColor.LCYTableLightGray()
case 1:
cell.backgroundColor = UIColor.LCYTableLightBlue()
default:
break
}
var imageName = indexPath.row == 0 ? "findSearch_0\(indexPath.row)" : "findSearch_0\(indexPath.row + 1)"
cell.imageView?.image = UIImage(named: imageName)
cell.textLabel?.textColor = UIColor.LCYThemeDarkText()
cell.detailTextLabel?.text = "不限制"
switch indexPath.row {
case 0:
if let myChild = child {
cell.detailTextLabel?.text = myChild.name
}
cell.textLabel?.text = "宠物种类"
// case 1:
// cell.textLabel?.text = "距离"
case 1:
if let age = age {
cell.detailTextLabel?.text = "\(age.0.toAge())~\(age.1.toAge())"
}
cell.textLabel?.text = "宠物年龄"
case 2:
switch breeding {
case .Unselected:
cell.detailTextLabel?.text = "不限制"
case .Yes:
cell.detailTextLabel?.text = "是"
case .No:
cell.detailTextLabel?.text = "否"
}
cell.textLabel?.text = "找配种"
case 3:
switch adopt {
case .Unselected:
cell.detailTextLabel?.text = "不限制"
case .Yes:
cell.detailTextLabel?.text = "是"
case .No:
cell.detailTextLabel?.text = "否"
}
cell.textLabel?.text = "求领养"
case 4:
switch foster {
case .Unselected:
cell.detailTextLabel?.text = "不限制"
case .Yes:
cell.detailTextLabel?.text = "是"
case .No:
cell.detailTextLabel?.text = "否"
}
cell.textLabel?.text = "被寄养"
default:
break
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0:
// 宠物种类
let storyBoard = UIStoryboard(name: "PetCateFilter", bundle: nil)
let destination = storyBoard.instantiateInitialViewController() as! PetCateFilterViewController
destination.delegate = self
destination.root = self
navigationController?.pushViewController(destination, animated: true)
case 1:
performSegueWithIdentifier("chooseAge", sender: nil)
case 2, 3, 4:
performSegueWithIdentifier("showSingle", sender: nil)
default:
break
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "chooseAge":
let destination = segue.destinationViewController as! FindChooseAgeViewController
destination.delegate = self
case "showSingle":
let destination = segue.destinationViewController as! FindChooseSingleSelectionViewController
destination.indexPath = tableView.indexPathForSelectedRow()
destination.delegate = self
case "showSearchResult":
let destination = segue.destinationViewController as! FindSearchResultViewController
let parameter = sender as? [String: String]
destination.parameter = parameter
default:
break
}
}
}
}
extension FindSearchViewController: PetCateFilterDelegate {
func didSelectCategory(childCategory: LCYPetSubTypeChildStyle) {
child = childCategory
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
}
}
extension FindSearchViewController: FindChooseAgeDelegate {
func chooseAgeDone(#from: Int, to: Int) {
age = (from, to)
}
}
extension FindSearchViewController: FindChooseSingleDelegate {
func findChooseSingleDone(indexPath: NSIndexPath, result: FindChooseSingleResult) {
switch indexPath.row {
case 2:
breeding = result
case 3:
adopt = result
case 4:
foster = result
default:
break
}
}
}
| apache-2.0 | 412d56cd85dd856c3bba59e9822f0610 | 34.065844 | 139 | 0.586668 | 5.179939 | false | false | false | false |
kidla/Swift | Code Practice/Basic_II.playground/section-1.swift | 1 | 691 | // Playground - noun: a place where people can play
import UIKit
// Optionals
var str : String? = "Hello Swift by Tutorials"
println(str)
if let upwrappedStr = str {
println("upwrappedStr ! \(upwrappedStr.uppercaseString)")
} else {
println(str)
}
//Forced unwrapping
println("Force unwrapped! \(str!.uppercaseString)")
//Implicit unwrapping
var unwrappaingStr : String!
if unwrappaingStr != nil {
unwrappaingStr = unwrappaingStr.uppercaseString
println(unwrappaingStr)
} else {
println("a \(unwrappaingStr) ")
}
//Optional chaining
var maybeString : String? = "Haello optional chaining Swift"
let upperCase = maybeString?.uppercaseString
println(upperCase) | apache-2.0 | 102019f276be044042dc5239f1a19b34 | 18.771429 | 61 | 0.727931 | 3.420792 | false | false | false | false |
gperdomor/MoyaModelMapper | Tests/MoyaModelMapperTests/MoyaModelMapperSpec.swift | 1 | 9694 | //
// MoyaModelMapperSpec.swift
// MoyaModelMapper
//
// Created by Gustavo Perdomo on 2/19/17.
// Copyright (c) 2017 Gustavo Perdomo. Licensed under the MIT license, as follows:
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Quick
import Nimble
import Moya
import MoyaModelMapper
class MoyaModelMapperSpec: QuickSpec {
override func spec() {
describe("MoyaModelMapper") {
var provider: MoyaProvider<GitHub>!
beforeEach {
provider = MoyaProvider<GitHub>(stubClosure: MoyaProvider.immediatelyStub)
}
describe("Map to Object") {
var repo: Repository?
var _error: MoyaError?
beforeEach {
repo = nil
_error = nil
}
it("Can map response to object") {
waitUntil { done in
provider.request(GitHub.repo(fullName: "gperdomor/sygnaler", keyPath: false)) { (result) in
if case .success(let response) = result {
do {
repo = try response.map(to: Repository.self)
} catch {}
}
done()
}
}
expect(repo).toNot(beNil())
expect(repo?.identifier).to(equal(1))
expect(repo?.name).to(equal("sygnaler"))
expect(repo?.fullName).to(equal("gperdomor/sygnaler"))
expect(repo?.language).to(equal("Swift"))
}
it("Can map response to object from a key path") {
waitUntil { done in
provider.request(GitHub.repo(fullName: "gperdomor/sygnaler", keyPath: true)) { (result) in
if case .success(let response) = result {
do {
repo = try response.map(to: Repository.self, fromKey: "data")
} catch {}
}
done()
}
}
expect(repo).toNot(beNil())
expect(repo?.identifier).to(equal(1))
expect(repo?.name).to(equal("sygnaler"))
expect(repo?.fullName).to(equal("gperdomor/sygnaler"))
expect(repo?.language).to(equal("Swift"))
}
context("Mapping Fails") {
it("Can throws error if mapping fails") {
waitUntil { done in
provider.request(GitHub.repo(fullName: "no-existing-repo", keyPath: false)) { (result) in
if case .success(let response) = result {
do {
repo = try response.map(to: Repository.self)
} catch {
_error = error as? MoyaError
}
}
done()
}
}
expect(repo).to(beNil())
expect(_error).toNot(beNil())
expect(_error).to(beAnInstanceOf(MoyaError.self))
}
it("Can throws error if mapping fails using key path") {
waitUntil { done in
provider.request(GitHub.repo(fullName: "gperdomor/sygnaler", keyPath: true)) { (result) in
if case .success(let response) = result {
do {
repo = try response.map(to: Repository.self, fromKey: "no-existing-key")
} catch {
_error = error as? MoyaError
}
}
done()
}
}
expect(repo).to(beNil())
expect(_error).toNot(beNil())
expect(_error).to(beAnInstanceOf(MoyaError.self))
}
}
}
describe("Map to Array") {
var repos: [Repository]?
var _error: MoyaError?
beforeEach {
repos = nil
_error = nil
}
it("can mapped to array of objects") {
waitUntil { done in
provider.request(GitHub.repos(username: "gperdomor", keyPath: false)) { (result) in
if case .success(let response) = result {
do {
repos = try response.map(to: [Repository.self])
} catch {}
}
done()
}
}
expect(repos).toNot(beNil())
expect(repos?.count).to(equal(1))
expect(repos?[0].identifier).to(equal(1))
expect(repos?[0].name).to(equal("sygnaler"))
expect(repos?[0].fullName).to(equal("gperdomor/sygnaler"))
expect(repos?[0].language).to(equal("Swift"))
}
it("can mapped to array of objects from a key path") {
waitUntil { done in
provider.request(GitHub.repos(username: "gperdomor", keyPath: true)) { (result) in
if case .success(let response) = result {
do {
repos = try response.map(to: [Repository.self], fromKey: "data")
} catch {}
}
done()
}
}
expect(repos).toNot(beNil())
expect(repos?.count).to(equal(1))
expect(repos?[0].identifier).to(equal(1))
expect(repos?[0].name).to(equal("sygnaler"))
expect(repos?[0].fullName).to(equal("gperdomor/sygnaler"))
expect(repos?[0].language).to(equal("Swift"))
}
context("Mapping Fails") {
it("Can throws error if mapping fails") {
waitUntil { done in
provider.request(GitHub.repos(username: "no-existing-user", keyPath: false)) { (result) in
if case .success(let response) = result {
do {
repos = try response.map(to: [Repository.self])
} catch {
_error = error as? MoyaError
}
}
done()
}
}
expect(repos).to(beNil())
expect(_error).toNot(beNil())
expect(_error).to(beAnInstanceOf(MoyaError.self))
}
it("Can throws error if mapping fails using key path") {
waitUntil { done in
provider.request(GitHub.repos(username: "gperdomor", keyPath: true)) { (result) in
if case .success(let response) = result {
do {
repos = try response.map(to: [Repository.self], fromKey: "no-existing-key")
} catch {
_error = error as? MoyaError
}
}
done()
}
}
expect(repos).to(beNil())
expect(_error).toNot(beNil())
expect(_error).to(beAnInstanceOf(MoyaError.self))
}
}
}
}
}
}
| mit | 2cb4faa65f373a1b0dc8cde12fb773ac | 42.666667 | 118 | 0.417165 | 5.695652 | false | false | false | false |
starrpatty28/MJMusicApp | MJMusicApp/MJMusicApp/LoginVC.swift | 1 | 1802 | //
// ViewController.swift
// MJMusicApp
//
// Created by Noi-Ariella Baht Israel on 3/22/17.
// Copyright © 2017 Plant A Seed of Code. All rights reserved.
//
import UIKit
class LoginVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var gifView: UIImageView!
@IBOutlet weak var userNameTxtFld: UITextField!
@IBOutlet weak var passWordTxtFld: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
gifView.loadGif(name: "200w_d")
userNameTxtFld.delegate = self
userNameTxtFld.tag = 0
passWordTxtFld.delegate = self
passWordTxtFld.tag = 0
}
func textFieldShouldReturn(_ userNameTxtField: UITextField) -> Bool
{
// Try to find next responder
if let nextField = userNameTxtField.superview?.viewWithTag(userNameTxtField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
userNameTxtField.resignFirstResponder()
}
// Do not add a line break
return false
}
@nonobjc func passWordFieldShouldReturn(_ passWordTxtField: UITextField) -> Bool
{
// Try to find next responder
if let nextField = passWordTxtField.superview?.viewWithTag(passWordTxtField.tag + 1) as? UITextField {
nextField.becomeFirstResponder()
} else {
// Not found, so remove keyboard.
passWordTxtField.resignFirstResponder()
}
// Do not add a line break
return false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 7b86d597bc5ce0116e6a0afd34c48dfe | 25.101449 | 110 | 0.61688 | 5.002778 | false | false | false | false |
jiecao-fm/SwiftTheme | Source/UIKit+Theme.swift | 2 | 13858 | //
// UIKit+Theme.swift
// SwiftTheme
//
// Created by Gesen on 16/1/22.
// Copyright © 2016年 Gesen. All rights reserved.
//
import UIKit
@objc public extension UIView
{
var theme_alpha: ThemeCGFloatPicker? {
get { return getThemePicker(self, "setAlpha:") as? ThemeCGFloatPicker }
set { setThemePicker(self, "setAlpha:", newValue) }
}
var theme_backgroundColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBackgroundColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBackgroundColor:", newValue) }
}
var theme_tintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTintColor:", newValue) }
}
}
@objc public extension UIApplication
{
#if os(iOS)
func theme_setStatusBarStyle(_ picker: ThemeStatusBarStylePicker, animated: Bool) {
picker.animated = animated
setThemePicker(self, "setStatusBarStyle:animated:", picker)
}
#endif
}
@objc public extension UIBarItem
{
func theme_setTitleTextAttributes(_ picker: ThemeDictionaryPicker?, forState state: UIControl.State) {
let statePicker = makeStatePicker(self, "setTitleTextAttributes:forState:", picker, state)
setThemePicker(self, "setTitleTextAttributes:forState:", statePicker)
}
}
@objc public extension UIBarButtonItem
{
var theme_tintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTintColor:", newValue) }
}
}
@objc public extension UILabel
{
var theme_font: ThemeFontPicker? {
get { return getThemePicker(self, "setFont:") as? ThemeFontPicker }
set { setThemePicker(self, "setFont:", newValue) }
}
var theme_textColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTextColor:", newValue) }
}
var theme_highlightedTextColor: ThemeColorPicker? {
get { return getThemePicker(self, "setHighlightedTextColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setHighlightedTextColor:", newValue) }
}
var theme_shadowColor: ThemeColorPicker? {
get { return getThemePicker(self, "setShadowColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setShadowColor:", newValue) }
}
}
@objc public extension UINavigationBar
{
#if os(iOS)
var theme_barStyle: ThemeBarStylePicker? {
get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker }
set { setThemePicker(self, "setBarStyle:", newValue) }
}
#endif
var theme_barTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBarTintColor:", newValue) }
}
var theme_titleTextAttributes: ThemeDictionaryPicker? {
get { return getThemePicker(self, "setTitleTextAttributes:") as? ThemeDictionaryPicker }
set { setThemePicker(self, "setTitleTextAttributes:", newValue) }
}
var theme_largeTitleTextAttributes: ThemeDictionaryPicker? {
get { return getThemePicker(self, "setLargeTitleTextAttributes:") as? ThemeDictionaryPicker }
set { setThemePicker(self, "setLargeTitleTextAttributes:", newValue) }
}
}
@objc public extension UITabBar
{
#if os(iOS)
var theme_barStyle: ThemeBarStylePicker? {
get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker }
set { setThemePicker(self, "setBarStyle:", newValue) }
}
#endif
var theme_barTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBarTintColor:", newValue) }
}
}
@objc public extension UITableView
{
var theme_separatorColor: ThemeColorPicker? {
get { return getThemePicker(self, "setSeparatorColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setSeparatorColor:", newValue) }
}
var theme_sectionIndexColor: ThemeColorPicker? {
get { return getThemePicker(self, "setSectionIndexColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setSectionIndexColor:", newValue) }
}
var theme_sectionIndexBackgroundColor: ThemeColorPicker? {
get { return getThemePicker(self, "setSectionIndexBackgroundColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setSectionIndexBackgroundColor:", newValue) }
}
}
@objc public extension UITextField
{
var theme_font: ThemeFontPicker? {
get { return getThemePicker(self, "setFont:") as? ThemeFontPicker }
set { setThemePicker(self, "setFont:", newValue) }
}
var theme_keyboardAppearance: ThemeKeyboardAppearancePicker? {
get { return getThemePicker(self, "setKeyboardAppearance:") as? ThemeKeyboardAppearancePicker }
set { setThemePicker(self, "setKeyboardAppearance:", newValue) }
}
var theme_textColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTextColor:", newValue) }
}
var theme_placeholderAttributes: ThemeDictionaryPicker? {
get { return getThemePicker(self, "updatePlaceholderAttributes:") as? ThemeDictionaryPicker }
set { setThemePicker(self, "updatePlaceholderAttributes:", newValue) }
}
}
@objc public extension UITextView
{
var theme_font: ThemeFontPicker? {
get { return getThemePicker(self, "setFont:") as? ThemeFontPicker }
set { setThemePicker(self, "setFont:", newValue) }
}
var theme_keyboardAppearance: ThemeKeyboardAppearancePicker? {
get { return getThemePicker(self, "setKeyboardAppearance:") as? ThemeKeyboardAppearancePicker }
set { setThemePicker(self, "setKeyboardAppearance:", newValue) }
}
var theme_textColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTextColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTextColor:", newValue) }
}
}
@objc public extension UISearchBar
{
#if os(iOS)
var theme_barStyle: ThemeBarStylePicker? {
get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker }
set { setThemePicker(self, "setBarStyle:", newValue) }
}
#endif
var theme_keyboardAppearance: ThemeKeyboardAppearancePicker? {
get { return getThemePicker(self, "setKeyboardAppearance:") as? ThemeKeyboardAppearancePicker }
set { setThemePicker(self, "setKeyboardAppearance:", newValue) }
}
var theme_barTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBarTintColor:", newValue) }
}
}
@objc public extension UIProgressView
{
var theme_progressTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setProgressTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setProgressTintColor:", newValue) }
}
var theme_trackTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setTrackTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setTrackTintColor:", newValue) }
}
}
@objc public extension UIPageControl
{
var theme_pageIndicatorTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setPageIndicatorTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setPageIndicatorTintColor:", newValue) }
}
var theme_currentPageIndicatorTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setCurrentPageIndicatorTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setCurrentPageIndicatorTintColor:", newValue) }
}
}
@objc public extension UIImageView
{
var theme_image: ThemeImagePicker? {
get { return getThemePicker(self, "setImage:") as? ThemeImagePicker }
set { setThemePicker(self, "setImage:", newValue) }
}
}
@objc public extension UIActivityIndicatorView
{
var theme_activityIndicatorViewStyle: ThemeActivityIndicatorViewStylePicker? {
get { return getThemePicker(self, "setActivityIndicatorViewStyle:") as? ThemeActivityIndicatorViewStylePicker }
set { setThemePicker(self, "setActivityIndicatorViewStyle:", newValue) }
}
}
@objc public extension UIScrollView
{
var theme_indicatorStyle: ThemeScrollViewIndicatorStylePicker? {
get { return getThemePicker(self, "setIndicatorStyle:") as? ThemeScrollViewIndicatorStylePicker }
set { setThemePicker(self, "setIndicatorStyle:", newValue) }
}
}
@objc public extension UIButton
{
func theme_setImage(_ picker: ThemeImagePicker?, forState state: UIControl.State) {
let statePicker = makeStatePicker(self, "setImage:forState:", picker, state)
setThemePicker(self, "setImage:forState:", statePicker)
}
func theme_setBackgroundImage(_ picker: ThemeImagePicker?, forState state: UIControl.State) {
let statePicker = makeStatePicker(self, "setBackgroundImage:forState:", picker, state)
setThemePicker(self, "setBackgroundImage:forState:", statePicker)
}
func theme_setTitleColor(_ picker: ThemeColorPicker?, forState state: UIControl.State) {
let statePicker = makeStatePicker(self, "setTitleColor:forState:", picker, state)
setThemePicker(self, "setTitleColor:forState:", statePicker)
}
}
@objc public extension CALayer
{
var theme_backgroundColor: ThemeCGColorPicker? {
get { return getThemePicker(self, "setBackgroundColor:") as? ThemeCGColorPicker}
set { setThemePicker(self, "setBackgroundColor:", newValue) }
}
var theme_borderWidth: ThemeCGFloatPicker? {
get { return getThemePicker(self, "setBorderWidth:") as? ThemeCGFloatPicker }
set { setThemePicker(self, "setBorderWidth:", newValue) }
}
var theme_borderColor: ThemeCGColorPicker? {
get { return getThemePicker(self, "setBorderColor:") as? ThemeCGColorPicker }
set { setThemePicker(self, "setBorderColor:", newValue) }
}
var theme_shadowColor: ThemeCGColorPicker? {
get { return getThemePicker(self, "setShadowColor:") as? ThemeCGColorPicker }
set { setThemePicker(self, "setShadowColor:", newValue) }
}
var theme_strokeColor: ThemeCGColorPicker? {
get { return getThemePicker(self, "setStrokeColor:") as? ThemeCGColorPicker }
set { setThemePicker(self, "setStrokeColor:", newValue) }
}
var theme_fillColor: ThemeCGColorPicker?{
get { return getThemePicker(self, "setFillColor:") as? ThemeCGColorPicker }
set { setThemePicker(self, "setFillColor:", newValue) }
}
}
#if os(iOS)
@objc public extension UIToolbar
{
var theme_barStyle: ThemeBarStylePicker? {
get { return getThemePicker(self, "setBarStyle:") as? ThemeBarStylePicker }
set { setThemePicker(self, "setBarStyle:", newValue) }
}
var theme_barTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBarTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBarTintColor:", newValue) }
}
}
@objc public extension UISwitch
{
var theme_onTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setOnTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setOnTintColor:", newValue) }
}
var theme_thumbTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setThumbTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setThumbTintColor:", newValue) }
}
}
@objc public extension UISlider
{
var theme_thumbTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setThumbTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setThumbTintColor:", newValue) }
}
var theme_minimumTrackTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setMinimumTrackTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setMinimumTrackTintColor:", newValue) }
}
var theme_maximumTrackTintColor: ThemeColorPicker? {
get { return getThemePicker(self, "setMaximumTrackTintColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setMaximumTrackTintColor:", newValue) }
}
}
@objc public extension UIPopoverPresentationController
{
var theme_backgroundColor: ThemeColorPicker? {
get { return getThemePicker(self, "setBackgroundColor:") as? ThemeColorPicker }
set { setThemePicker(self, "setBackgroundColor:", newValue) }
}
}
@objc public extension UIRefreshControl
{
var theme_titleAttributes: ThemeDictionaryPicker? {
get { return getThemePicker(self, "updateTitleAttributes:") as? ThemeDictionaryPicker }
set { setThemePicker(self, "updateTitleAttributes:", newValue) }
}
}
#endif
private func getThemePicker(
_ object : NSObject,
_ selector : String
) -> ThemePicker? {
return object.themePickers[selector]
}
private func setThemePicker(
_ object : NSObject,
_ selector : String,
_ picker : ThemePicker?
) {
object.themePickers[selector] = picker
object.performThemePicker(selector: selector, picker: picker)
}
private func makeStatePicker(
_ object : NSObject,
_ selector : String,
_ picker : ThemePicker?,
_ state : UIControl.State
) -> ThemePicker? {
var picker = picker
if let statePicker = object.themePickers[selector] as? ThemeStatePicker {
picker = statePicker.setPicker(picker, forState: state)
} else {
picker = ThemeStatePicker(picker: picker, withState: state)
}
return picker
}
| mit | 9af18f1e29a6a38e0f192e6a0180b006 | 39.870206 | 119 | 0.698593 | 4.598407 | false | false | false | false |
InLefter/Wea | Wea/SwiftyJSON.swift | 2 | 36661 | // SwiftyJSON.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
// MARK: - Error
///Error domain
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
public let ErrorUnsupportedType: Int = 999
public let ErrorIndexOutOfBounds: Int = 900
public let ErrorWrongType: Int = 901
public let ErrorNotExist: Int = 500
public let ErrorInvalidJSON: Int = 490
// MARK: - JSON Type
/**
JSON's type definitions.
See http://www.json.org
*/
public enum Type :Int{
case Number
case String
case Bool
case Array
case Dictionary
case Null
case Unknown
}
// MARK: - JSON Base
public struct JSON {
/**
Creates a JSON using the data.
- parameter data: The NSData used to convert to json.Top level object in data is an NSArray or NSDictionary
- parameter opt: The JSON serialization reading options. `.AllowFragments` by default.
- parameter error: error The NSErrorPointer used to return the error. `nil` by default.
- returns: The created JSON
*/
public init(data:NSData, options opt: NSJSONReadingOptions = .AllowFragments, error: NSErrorPointer = nil) {
do {
let object: AnyObject = try NSJSONSerialization.JSONObjectWithData(data, options: opt)
self.init(object)
} catch let aError as NSError {
if error != nil {
error.memory = aError
}
self.init(NSNull())
}
}
/**
Create a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
public static func parse(string:String) -> JSON {
return string.dataUsingEncoding(NSUTF8StringEncoding)
.flatMap({JSON(data: $0)}) ?? JSON(NSNull())
}
/**
Creates a JSON using the object.
- parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity.
- returns: The created JSON
*/
public init(_ object: AnyObject) {
self.object = object
}
/**
Creates a JSON from a [JSON]
- parameter jsonArray: A Swift array of JSON objects
- returns: The created JSON
*/
public init(_ jsonArray:[JSON]) {
self.init(jsonArray.map { $0.object })
}
/**
Creates a JSON from a [String: JSON]
- parameter jsonDictionary: A Swift dictionary of JSON objects
- returns: The created JSON
*/
public init(_ jsonDictionary:[String: JSON]) {
var dictionary = [String: AnyObject]()
for (key, json) in jsonDictionary {
dictionary[key] = json.object
}
self.init(dictionary)
}
/// Private object
private var rawArray: [AnyObject] = []
private var rawDictionary: [String : AnyObject] = [:]
private var rawString: String = ""
private var rawNumber: NSNumber = 0
private var rawNull: NSNull = NSNull()
/// Private type
private var _type: Type = .Null
/// prviate error
private var _error: NSError? = nil
/// Object in JSON
public var object: AnyObject {
get {
switch self.type {
case .Array:
return self.rawArray
case .Dictionary:
return self.rawDictionary
case .String:
return self.rawString
case .Number:
return self.rawNumber
case .Bool:
return self.rawNumber
default:
return self.rawNull
}
}
set {
_error = nil
switch newValue {
case let number as NSNumber:
if number.isBool {
_type = .Bool
} else {
_type = .Number
}
self.rawNumber = number
case let string as String:
_type = .String
self.rawString = string
case _ as NSNull:
_type = .Null
case let array as [AnyObject]:
_type = .Array
self.rawArray = array
case let dictionary as [String : AnyObject]:
_type = .Dictionary
self.rawDictionary = dictionary
default:
_type = .Unknown
_error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"])
}
}
}
/// json type
public var type: Type { get { return _type } }
/// Error in JSON
public var error: NSError? { get { return self._error } }
/// The static null json
@available(*, unavailable, renamed="null")
public static var nullJSON: JSON { get { return null } }
public static var null: JSON { get { return JSON(NSNull()) } }
}
// MARK: - CollectionType, SequenceType, Indexable
extension JSON : Swift.CollectionType, Swift.SequenceType, Swift.Indexable {
public typealias Generator = JSONGenerator
public typealias Index = JSONIndex
public var startIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.startIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex)
default:
return JSONIndex()
}
}
public var endIndex: JSON.Index {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.rawArray.endIndex)
case .Dictionary:
return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex)
default:
return JSONIndex()
}
}
public subscript (position: JSON.Index) -> JSON.Generator.Element {
switch self.type {
case .Array:
return (String(position.arrayIndex), JSON(self.rawArray[position.arrayIndex!]))
case .Dictionary:
let (key, value) = self.rawDictionary[position.dictionaryIndex!]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.empty` or `dictonary.empty` otherwise return `true`.
public var isEmpty: Bool {
get {
switch self.type {
case .Array:
return self.rawArray.isEmpty
case .Dictionary:
return self.rawDictionary.isEmpty
default:
return true
}
}
}
/// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`.
public var count: Int {
switch self.type {
case .Array:
return self.rawArray.count
case .Dictionary:
return self.rawDictionary.count
default:
return 0
}
}
public func underestimateCount() -> Int {
switch self.type {
case .Array:
return self.rawArray.underestimateCount()
case .Dictionary:
return self.rawDictionary.underestimateCount()
default:
return 0
}
}
/**
If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty.
- returns: Return a *generator* over the elements of JSON.
*/
public func generate() -> JSON.Generator {
return JSON.Generator(self)
}
}
public struct JSONIndex: ForwardIndexType, _Incrementable, Equatable, Comparable {
let arrayIndex: Int?
let dictionaryIndex: DictionaryIndex<String, AnyObject>?
let type: Type
init(){
self.arrayIndex = nil
self.dictionaryIndex = nil
self.type = .Unknown
}
init(arrayIndex: Int) {
self.arrayIndex = arrayIndex
self.dictionaryIndex = nil
self.type = .Array
}
init(dictionaryIndex: DictionaryIndex<String, AnyObject>) {
self.arrayIndex = nil
self.dictionaryIndex = dictionaryIndex
self.type = .Dictionary
}
public func successor() -> JSONIndex {
switch self.type {
case .Array:
return JSONIndex(arrayIndex: self.arrayIndex!.successor())
case .Dictionary:
return JSONIndex(dictionaryIndex: self.dictionaryIndex!.successor())
default:
return JSONIndex()
}
}
}
public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex == rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex == rhs.dictionaryIndex
default:
return false
}
}
public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex < rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex < rhs.dictionaryIndex
default:
return false
}
}
public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex <= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex <= rhs.dictionaryIndex
default:
return false
}
}
public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex >= rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex >= rhs.dictionaryIndex
default:
return false
}
}
public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool {
switch (lhs.type, rhs.type) {
case (.Array, .Array):
return lhs.arrayIndex > rhs.arrayIndex
case (.Dictionary, .Dictionary):
return lhs.dictionaryIndex > rhs.dictionaryIndex
default:
return false
}
}
public struct JSONGenerator : GeneratorType {
public typealias Element = (String, JSON)
private let type: Type
private var dictionayGenerate: DictionaryGenerator<String, AnyObject>?
private var arrayGenerate: IndexingGenerator<[AnyObject]>?
private var arrayIndex: Int = 0
init(_ json: JSON) {
self.type = json.type
if type == .Array {
self.arrayGenerate = json.rawArray.generate()
}else {
self.dictionayGenerate = json.rawDictionary.generate()
}
}
public mutating func next() -> JSONGenerator.Element? {
switch self.type {
case .Array:
if let o = self.arrayGenerate?.next() {
return (String(self.arrayIndex += 1), JSON(o))
} else {
return nil
}
case .Dictionary:
if let (k, v): (String, AnyObject) = self.dictionayGenerate?.next() {
return (k, JSON(v))
} else {
return nil
}
default:
return nil
}
}
}
// MARK: - Subscript
/**
* To mark both String and Int can be used in subscript.
*/
public enum JSONKey {
case Index(Int)
case Key(String)
}
public protocol JSONSubscriptType {
var jsonKey:JSONKey { get }
}
extension Int: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.Index(self)
}
}
extension String: JSONSubscriptType {
public var jsonKey:JSONKey {
return JSONKey.Key(self)
}
}
extension JSON {
/// If `type` is `.Array`, return json which's object is `array[index]`, otherwise return null json with error.
private subscript(index index: Int) -> JSON {
get {
if self.type != .Array {
var r = JSON.null
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array"])
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds , userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds"])
return r
}
}
set {
if self.type == .Array {
if self.rawArray.count > index && newValue.error == nil {
self.rawArray[index] = newValue.object
}
}
}
}
/// If `type` is `.Dictionary`, return json which's object is `dictionary[key]` , otherwise return null json with error.
private subscript(key key: String) -> JSON {
get {
var r = JSON.null
if self.type == .Dictionary {
if let o = self.rawDictionary[key] {
r = JSON(o)
} else {
r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist"])
}
} else {
r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary"])
}
return r
}
set {
if self.type == .Dictionary && newValue.error == nil {
self.rawDictionary[key] = newValue.object
}
}
}
/// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`.
private subscript(sub sub: JSONSubscriptType) -> JSON {
get {
switch sub.jsonKey {
case .Index(let index): return self[index: index]
case .Key(let key): return self[key: key]
}
}
set {
switch sub.jsonKey {
case .Index(let index): self[index: index] = newValue
case .Key(let key): self[key: key] = newValue
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let json = JSON[data]
let path = [9,"list","person","name"]
let name = json[path]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: [JSONSubscriptType]) -> JSON {
get {
return path.reduce(self) { $0[sub: $1] }
}
set {
switch path.count {
case 0:
return
case 1:
self[sub:path[0]].object = newValue.object
default:
var aPath = path; aPath.removeAtIndex(0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structuresby using the Int/String's array.
- parameter path: The target json's path. Example:
let name = json[9,"list","person","name"]
The same as: let name = json[9]["list"]["person"]["name"]
- returns: Return a json found by the path or a null json with error
*/
public subscript(path: JSONSubscriptType...) -> JSON {
get {
return self[path]
}
set {
self[path] = newValue
}
}
}
// MARK: - LiteralConvertible
extension JSON: Swift.StringLiteralConvertible {
public init(stringLiteral value: StringLiteralType) {
self.init(value)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value)
}
}
extension JSON: Swift.IntegerLiteralConvertible {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value)
}
}
extension JSON: Swift.BooleanLiteralConvertible {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value)
}
}
extension JSON: Swift.FloatLiteralConvertible {
public init(floatLiteral value: FloatLiteralType) {
self.init(value)
}
}
extension JSON: Swift.DictionaryLiteralConvertible {
public init(dictionaryLiteral elements: (String, AnyObject)...) {
self.init(elements.reduce([String : AnyObject]()){(dictionary: [String : AnyObject], element:(String, AnyObject)) -> [String : AnyObject] in
var d = dictionary
d[element.0] = element.1
return d
})
}
}
extension JSON: Swift.ArrayLiteralConvertible {
public init(arrayLiteral elements: AnyObject...) {
self.init(elements)
}
}
extension JSON: Swift.NilLiteralConvertible {
public init(nilLiteral: ()) {
self.init(NSNull())
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: AnyObject) {
if JSON(rawValue).type == .Unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: AnyObject {
return self.object
}
public func rawData(options opt: NSJSONWritingOptions = NSJSONWritingOptions(rawValue: 0)) throws -> NSData {
guard NSJSONSerialization.isValidJSONObject(self.object) else {
throw NSError(domain: ErrorDomain, code: ErrorInvalidJSON, userInfo: [NSLocalizedDescriptionKey: "JSON is invalid"])
}
return try NSJSONSerialization.dataWithJSONObject(self.object, options: opt)
}
public func rawString(encoding: UInt = NSUTF8StringEncoding, options opt: NSJSONWritingOptions = .PrettyPrinted) -> String? {
switch self.type {
case .Array, .Dictionary:
do {
let data = try self.rawData(options: opt)
return NSString(data: data, encoding: encoding) as? String
} catch _ {
return nil
}
case .String:
return self.rawString
case .Number:
return self.rawNumber.stringValue
case .Bool:
return self.rawNumber.boolValue.description
case .Null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.Printable, Swift.DebugPrintable {
public var description: String {
if let string = self.rawString(options:.PrettyPrinted) {
return string
} else {
return "unknown"
}
}
public var debugDescription: String {
return description
}
}
// MARK: - Array
extension JSON {
//Optional [JSON]
public var array: [JSON]? {
get {
if self.type == .Array {
return self.rawArray.map{ JSON($0) }
} else {
return nil
}
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
get {
return self.array ?? []
}
}
//Optional [AnyObject]
public var arrayObject: [AnyObject]? {
get {
switch self.type {
case .Array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .Dictionary {
return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, AnyObject)) -> [String : JSON] in
var d = dictionary
d[element.0] = JSON(element.1)
return d
}
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : AnyObject]
public var dictionaryObject: [String : AnyObject]? {
get {
switch self.type {
case .Dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON: Swift.BooleanType {
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .Bool:
return self.rawNumber.boolValue
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSNumber(bool: newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .Bool, .Number, .String:
return self.object.boolValue
default:
return false
}
}
set {
self.object = NSNumber(bool: newValue)
}
}
}
// MARK: - String
extension JSON {
//Optional string
public var string: String? {
get {
switch self.type {
case .String:
return self.object as? String
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = NSString(string:newValue)
} else {
self.object = NSNull()
}
}
}
//Non-optional string
public var stringValue: String {
get {
switch self.type {
case .String:
return self.object as? String ?? ""
case .Number:
return self.object.stringValue
case .Bool:
return (self.object as? Bool).map { String($0) } ?? ""
default:
return ""
}
}
set {
self.object = NSString(string:newValue)
}
}
}
// MARK: - Number
extension JSON {
//Optional number
public var number: NSNumber? {
get {
switch self.type {
case .Number, .Bool:
return self.rawNumber
default:
return nil
}
}
set {
self.object = newValue ?? NSNull()
}
}
//Non-optional number
public var numberValue: NSNumber {
get {
switch self.type {
case .String:
let decimal = NSDecimalNumber(string: self.object as? String)
if decimal == NSDecimalNumber.notANumber() { // indicates parse error
return NSDecimalNumber.zero()
}
return decimal
case .Number, .Bool:
return self.object as? NSNumber ?? NSNumber(int: 0)
default:
return NSNumber(double: 0.0)
}
}
set {
self.object = newValue
}
}
}
//MARK: - Null
extension JSON {
public var null: NSNull? {
get {
switch self.type {
case .Null:
return self.rawNull
default:
return nil
}
}
set {
self.object = NSNull()
}
}
public func isExists() -> Bool{
if let errorValue = error where errorValue.code == ErrorNotExist{
return false
}
return true
}
}
//MARK: - URL
extension JSON {
//Optional URL
public var URL: NSURL? {
get {
switch self.type {
case .String:
if let encodedString_ = self.rawString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
return NSURL(string: encodedString_)
} else {
return nil
}
default:
return nil
}
}
set {
self.object = newValue?.absoluteString ?? NSNull()
}
}
}
// MARK: - Int, Double, Float, Int8, Int16, Int32, Int64
extension JSON {
public var double: Double? {
get {
return self.number?.doubleValue
}
set {
if let newValue = newValue {
self.object = NSNumber(double: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(double: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(float: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(float: newValue)
}
}
public var int: Int? {
get {
return self.number?.longValue
}
set {
if let newValue = newValue {
self.object = NSNumber(integer: newValue)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.integerValue
}
set {
self.object = NSNumber(integer: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.unsignedLongValue
}
set {
if let newValue = newValue {
self.object = NSNumber(unsignedLong: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.unsignedLongValue
}
set {
self.object = NSNumber(unsignedLong: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.charValue
}
set {
if let newValue = newValue {
self.object = NSNumber(char: newValue)
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.charValue
}
set {
self.object = NSNumber(char: newValue)
}
}
public var uInt8: UInt8? {
get {
return self.number?.unsignedCharValue
}
set {
if let newValue = newValue {
self.object = NSNumber(unsignedChar: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.unsignedCharValue
}
set {
self.object = NSNumber(unsignedChar: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.shortValue
}
set {
if let newValue = newValue {
self.object = NSNumber(short: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.shortValue
}
set {
self.object = NSNumber(short: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.unsignedShortValue
}
set {
if let newValue = newValue {
self.object = NSNumber(unsignedShort: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.unsignedShortValue
}
set {
self.object = NSNumber(unsignedShort: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.intValue
}
set {
if let newValue = newValue {
self.object = NSNumber(int: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(int: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.unsignedIntValue
}
set {
if let newValue = newValue {
self.object = NSNumber(unsignedInt: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.unsignedIntValue
}
set {
self.object = NSNumber(unsignedInt: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.longLongValue
}
set {
if let newValue = newValue {
self.object = NSNumber(longLong: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.longLongValue
}
set {
self.object = NSNumber(longLong: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.unsignedLongLongValue
}
set {
if let newValue = newValue {
self.object = NSNumber(unsignedLongLong: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.unsignedLongLongValue
}
set {
self.object = NSNumber(unsignedLongLong: newValue)
}
}
}
//MARK: - Comparable
extension JSON : Swift.Comparable {}
public func ==(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber == rhs.rawNumber
case (.String, .String):
return lhs.rawString == rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func <=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber <= rhs.rawNumber
case (.String, .String):
return lhs.rawString <= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >=(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber >= rhs.rawNumber
case (.String, .String):
return lhs.rawString >= rhs.rawString
case (.Bool, .Bool):
return lhs.rawNumber.boolValue == rhs.rawNumber.boolValue
case (.Array, .Array):
return lhs.rawArray as NSArray == rhs.rawArray as NSArray
case (.Dictionary, .Dictionary):
return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary
case (.Null, .Null):
return true
default:
return false
}
}
public func >(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber > rhs.rawNumber
case (.String, .String):
return lhs.rawString > rhs.rawString
default:
return false
}
}
public func <(lhs: JSON, rhs: JSON) -> Bool {
switch (lhs.type, rhs.type) {
case (.Number, .Number):
return lhs.rawNumber < rhs.rawNumber
case (.String, .String):
return lhs.rawString < rhs.rawString
default:
return false
}
}
private let trueNumber = NSNumber(bool: true)
private let falseNumber = NSNumber(bool: false)
private let trueObjCType = String.fromCString(trueNumber.objCType)
private let falseObjCType = String.fromCString(falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool:Bool {
get {
let objCType = String.fromCString(self.objCType)
if (self.compare(trueNumber) == NSComparisonResult.OrderedSame && objCType == trueObjCType)
|| (self.compare(falseNumber) == NSComparisonResult.OrderedSame && objCType == falseObjCType){
return true
} else {
return false
}
}
}
}
func ==(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedSame
}
}
func !=(lhs: NSNumber, rhs: NSNumber) -> Bool {
return !(lhs == rhs)
}
func <(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedAscending
}
}
func >(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) == NSComparisonResult.OrderedDescending
}
}
func <=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedDescending
}
}
func >=(lhs: NSNumber, rhs: NSNumber) -> Bool {
switch (lhs.isBool, rhs.isBool) {
case (false, true):
return false
case (true, false):
return false
default:
return lhs.compare(rhs) != NSComparisonResult.OrderedAscending
}
}
| mit | b98e35e2153613a2904fa2db4bf28e6c | 25.643169 | 264 | 0.547366 | 4.740851 | false | false | false | false |
gpancio/iOS-Prototypes | EdmundsAPI/EdmundsAPI/Classes/VehicleColor.swift | 1 | 2233 | //
// VehicleColor.swift
// EdmundsAPI
//
// Created by Graham Pancio on 2016-04-27.
// Copyright © 2016 Graham Pancio. All rights reserved.
//
import Foundation
import ObjectMapper
/**
Represents a single vehicle color.
A vehicle color has a name, and optionally:
- A primaryColorChip, which is a hex color value
- R, G, B values: integer values describing the RGB components of the color.
Note: the primaryColorChip and RGB values might not be available, for example, for older vehicles.
*/
public class VehicleColor: Mappable {
/**
The Edmunds ID. Not useful except, perhaps, for a color lookup later on.
*/
public var id: String?
/**
The name of the color.
*/
public var name: String?
/**
A hex string describing the color.
*/
public var primaryColorChip: String?
/**
The red component of the color, in decimal.
*/
public var r: Int? {
didSet {
r = boundedColorComponent(r)
}
}
/**
The green component of the color, in decimal.
*/
public var g: Int? {
didSet {
g = boundedColorComponent(g)
}
}
/**
The blue component of the color, in decimal.
*/
public var b: Int? {
didSet {
b = boundedColorComponent(b)
}
}
public init() {}
required public init?(_ map: Map) {
}
private func boundedColorComponent(component: Int?) -> Int? {
if component == nil {
return nil
}
if component > 255 {
return 255
}
if component < 0 {
return 0
}
return component
}
public func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
primaryColorChip <- map["colorChips.primary.hex"]
r <- map["colorChips.primary.r"]
g <- map["colorChips.primary.g"]
b <- map["colorChips.primary.b"]
}
/**
Tests whether RGB are non-nil before you dereference them.
*/
public var hasRGB: Bool {
get {
return r != nil && g != nil && b != nil
}
}
}
| mit | 20b86b839cb5d51b50d1c4f20a4cf811 | 20.461538 | 99 | 0.536738 | 4.359375 | false | false | false | false |
jterhorst/TacoDemoiOS | TacoDemoIOS/DetailViewController.swift | 1 | 2395 | //
// DetailViewController.swift
// TacoDemoIOS
//
// Created by Jason Terhorst on 3/22/16.
// Copyright © 2016 Jason Terhorst. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var caloriesValueLabel: UILabel!
@IBOutlet weak var detailsValueLabel: UILabel!
@IBOutlet weak var hasCheeseValueLabel: UILabel!
@IBOutlet weak var hasLettuceValueLabel: UILabel!
@IBOutlet weak var layersValueLabel: UILabel!
@IBOutlet weak var meatValueLabel: UILabel!
var detailItem: Taco? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let caloriesLabel = self.caloriesValueLabel {
caloriesLabel.text = detail.calories?.stringValue
}
if let detailsLabel = self.detailsValueLabel {
detailsLabel.text = detail.details
}
if let hasCheeseLabel = self.hasCheeseValueLabel {
if detail.hasCheese?.boolValue == true {
hasCheeseLabel.text = "Yes"
} else {
hasCheeseLabel.text = "No"
}
}
if let hasLettuceLabel = self.hasLettuceValueLabel {
if detail.hasLettuce?.boolValue == true {
hasLettuceLabel.text = "Yes"
} else {
hasLettuceLabel.text = "No"
}
}
if let layersLabel = self.layersValueLabel {
layersLabel.text = detail.layers?.stringValue
}
if let meatLabel = self.meatValueLabel {
meatLabel.text = detail.meat
}
self.title = detail.value(forKey: "name") as? String;
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showEditor" {
if let detail = self.detailItem {
let controller = (segue.destination as! UINavigationController).topViewController as! EditingViewController
controller.detailItem = detail
}
}
}
}
| mit | 3f8139da14b17c5153583ea86c3d67f7 | 27.843373 | 123 | 0.649958 | 4.26738 | false | false | false | false |
tkausch/swiftalgorithms | CodePuzzles/StringExtension.playground/Contents.swift | 1 | 2769 | //: Playground - noun: a place where people can play
import UIKit
extension String {
var count: Int {
get {
return self.characters.count
}
}
func reversed() -> String {
return String(self.characters.reversed())
}
func contains(s: String) -> Bool {
return self.range(of: s) == nil ? true: false
}
func replace(target: String, withString: String) -> String {
return self.replacingOccurrences(of: target, with: withString)
}
subscript (i: Int) -> Character {
get {
let index = self.index(self.startIndex, offsetBy: i)
return self[index]
}
}
subscript (r: Range<Int>) -> String {
get {
let start: String.Index = self.index(self.startIndex, offsetBy: r.lowerBound)
let end: String.Index = self.index(self.startIndex, offsetBy: r.upperBound)
return self.substring(with: start..<end)
}
}
func indexOf(target: String, fromIndex: Int = 0) -> Int {
let start = self.index(self.startIndex, offsetBy: fromIndex)
if let range = self.range(of: target, range: start..<self.endIndex, locale: nil) {
return self.distance(from: self.startIndex, to: range.lowerBound)
} else {
return -1
}
}
func lastIndexOf(target: String, fromIndex: Int = 0) -> Int {
let start = self.index(self.startIndex, offsetBy: fromIndex)
if let range = self.range(of: target, options: .backwards, range: start..<self.endIndex, locale: nil) {
return self.distance(from: self.startIndex, to: range.lowerBound)
} else {
return -1
}
}
}
"Awsome".count == 6
"Awesome".contains("me") == true
"Awesome".contains("Aw") == true
"Awesome".contains("so") == true
"Awesome".contains("Dude") == false
"ReplaceMeMe".replace(target: "Me", withString: "You") == "ReplaceYouYou"
"MeReplace".replace(target: "Me", withString: "You") == "YouReplace"
"ReplaceMeNow".replace(target: "Me", withString: "You") == "ReplaceYouNow"
"0123456789"[0] == "0"
"0123456789"[5] == "5"
"0123456789"[9] == "9"
"0123456789"[0] == "0"
"0123456789"[5] == "5"
"0123456789"[9] == "9"
"0123456789"[5..<6] == "5"
"0123456789"[0..<1] == "0"
"0123456789"[8..<9] == "8"
"0123456789"[1..<5] == "1234"
"0123456789"[0..<10] == "0123456789"
"Awesome".indexOf(target:"nothin") == -1
"Awesome".indexOf(target:"Awe") == 0
"Awesome".indexOf(target:"some") == 3
"Awesome".indexOf(target:"e", fromIndex: 3) == 6
"BananaBanana".lastIndexOf(target: "na") == 10
"BananaBanana".lastIndexOf(target: "Banana", fromIndex: 6) == 6
"BananaBanana".lastIndexOf(target: "Banana", fromIndex: 7) == -1
| gpl-3.0 | 4e2155f685ee935c3a5b906647b8baba | 27.84375 | 111 | 0.590466 | 3.572903 | false | false | false | false |
Authman2/Pix | Pods/Hero/Sources/HeroDefaultAnimations.swift | 1 | 7860 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
public enum HeroDefaultAnimationType {
public enum Direction {
case left, right, up, down
}
case auto
case push(direction: Direction)
case pull(direction: Direction)
case cover(direction: Direction)
case uncover(direction: Direction)
case slide(direction: Direction)
case zoomSlide(direction: Direction)
case pageIn(direction: Direction)
case pageOut(direction: Direction)
case fade
case zoom
case zoomOut
indirect case selectBy(presenting:HeroDefaultAnimationType, dismissing:HeroDefaultAnimationType)
case none
public var label: String? {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
let valuesMirror = Mirror(reflecting: associated.value)
if !valuesMirror.children.isEmpty {
let parameters = valuesMirror.children.map { ".\($0.value)" }.joined(separator: ",")
return ".\(associated.label ?? "")(\(parameters))"
}
return ".\(associated.label ?? "")(.\(associated.value))"
}
return ".\(self)"
}
}
internal extension Hero {
func shift(direction: HeroDefaultAnimationType.Direction, appearing: Bool, size: CGSize? = nil, transpose: Bool = false) -> CGPoint {
let size = size ?? container.bounds.size
let rtn: CGPoint
switch direction {
case .left, .right:
rtn = CGPoint(x: (direction == .right) == appearing ? -size.width : size.width, y: 0)
case .up, .down:
rtn = CGPoint(x: 0, y: (direction == .down) == appearing ? -size.height : size.height)
}
if transpose {
return CGPoint(x: rtn.y, y: rtn.x)
}
return rtn
}
func prepareDefaultAnimation() {
if case .selectBy(let presentAnim, let dismissAnim) = defaultAnimation {
defaultAnimation = presenting ? presentAnim : dismissAnim
}
if case .auto = defaultAnimation {
if inNavigationController {
defaultAnimation = presenting ? .push(direction:.left) : .pull(direction:.right)
} else if inTabBarController {
defaultAnimation = presenting ? .slide(direction:.left) : .slide(direction:.right)
} else if animators.contains(where: { $0.canAnimate(view: toView, appearing: true) || $0.canAnimate(view: fromView, appearing: false) }) {
defaultAnimation = .none
} else {
defaultAnimation = .fade
}
}
if case .none = defaultAnimation {
return
}
context[fromView] = [.timingFunction(.standard), .duration(0.375)]
context[toView] = [.timingFunction(.standard), .duration(0.375)]
let shadowState: [HeroModifier] = [.shadowOpacity(0.5),
.shadowColor(.black),
.shadowRadius(5),
.shadowOffset(.zero),
.masksToBounds(false)]
switch defaultAnimation {
case .push(let direction):
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false) / 3),
.overlay(color: .black, opacity: 0.3)])
case .pull(let direction):
insertToViewFirst = true
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true) / 3),
.overlay(color: .black, opacity: 0.3)])
case .slide(let direction):
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false))])
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true))])
case .zoomSlide(let direction):
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)), .scale(0.8)])
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)), .scale(0.8)])
case .cover(let direction):
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[fromView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.3)])
case .uncover(let direction):
insertToViewFirst = true
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[toView]!.append(contentsOf: [.overlay(color: .black, opacity: 0.3)])
case .pageIn(let direction):
context[toView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: true)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[fromView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.3)])
case .pageOut(let direction):
insertToViewFirst = true
context[fromView]!.append(contentsOf: [.translate(shift(direction: direction, appearing: false)),
.shadowOpacity(0),
.beginWith(modifiers: shadowState)])
context[toView]!.append(contentsOf: [.scale(0.7), .overlay(color: .black, opacity: 0.3)])
case .fade:
// TODO: clean up this. overFullScreen logic shouldn't be here
if !(fromOverFullScreen && !presenting) {
context[toView] = [.fade]
}
if (!presenting && toOverFullScreen) || !fromView.isOpaque || (fromView.backgroundColor?.alphaComponent ?? 1) < 1 {
context[fromView] = [.fade]
}
context[toView]!.append(.durationMatchLongest)
context[fromView]!.append(.durationMatchLongest)
case .zoom:
insertToViewFirst = true
context[fromView]!.append(contentsOf: [.scale(1.3), .fade])
context[toView]!.append(contentsOf: [.scale(0.7)])
case .zoomOut:
context[toView]!.append(contentsOf: [.scale(1.3), .fade])
context[fromView]!.append(contentsOf: [.scale(0.7)])
default:
fatalError("Not implemented")
}
}
}
| gpl-3.0 | e123c577307100d2f49afff1704ac30e | 45.508876 | 144 | 0.624427 | 4.612676 | false | false | false | false |
pristap/SwiftRSS | SwiftRSS/RSSParser.swift | 1 | 6000 | //
// RSSParser.swift
// SwiftRSS_Example
//
// Created by Thibaut LE LEVIER on 05/09/2014.
// Copyright (c) 2014 Thibaut LE LEVIER. All rights reserved.
//
import UIKit
class RSSParser: NSObject, NSXMLParserDelegate {
class func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
let rssParser: RSSParser = RSSParser()
rssParser.parseFeedForRequest(request, callback: callback)
}
var callbackClosure: ((feed: RSSFeed?, error: NSError?) -> Void)?
var currentElement: String = ""
var currentItem: RSSItem?
var feed: RSSFeed = RSSFeed()
// node names
let node_item: String = "item"
let node_title: String = "title"
let node_link: String = "link"
let node_guid: String = "guid"
let node_publicationDate: String = "pubDate"
let node_description: String = "description"
let node_content: String = "content:encoded"
let node_language: String = "language"
let node_lastBuildDate = "lastBuildDate"
let node_generator = "generator"
let node_copyright = "copyright"
// wordpress specifics
let node_commentsLink = "comments"
let node_commentsCount = "slash:comments"
let node_commentRSSLink = "wfw:commentRss"
let node_author = "dc:creator"
let node_category = "category"
func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if ((error) != nil)
{
callback(feed: nil, error: error)
}
else
{
self.callbackClosure = callback
let parser : NSXMLParser = NSXMLParser(data: data!)
parser.delegate = self
parser.shouldResolveExternalEntities = false
parser.parse()
}
}
}
// MARK: NSXMLParserDelegate
func parserDidStartDocument(parser: NSXMLParser)
{
}
func parserDidEndDocument(parser: NSXMLParser)
{
if let closure = self.callbackClosure
{
closure(feed: self.feed, error: nil)
}
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
if elementName == node_item
{
self.currentItem = RSSItem()
}
self.currentElement = ""
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
if elementName == node_item
{
if let item = self.currentItem
{
self.feed.items.append(item)
}
self.currentItem = nil
return
}
if let item = self.currentItem
{
if elementName == node_title
{
item.title = self.currentElement
}
if elementName == node_link
{
item.setLink1(self.currentElement)
}
if elementName == node_guid
{
item.guid = self.currentElement
}
if elementName == node_publicationDate
{
item.setPubDate1(self.currentElement)
}
if elementName == node_description
{
item.itemDescription = self.currentElement
}
if elementName == node_content
{
item.content = self.currentElement
}
if elementName == node_commentsLink
{
item.setCommentsLink1(self.currentElement)
}
if elementName == node_commentsCount
{
item.commentsCount = Int(self.currentElement)
}
if elementName == node_commentRSSLink
{
item.setCommentRSSLink1(self.currentElement)
}
if elementName == node_author
{
item.author = self.currentElement
}
if elementName == node_category
{
item.categories.append(self.currentElement)
}
}
else
{
if elementName == node_title
{
feed.title = self.currentElement
}
if elementName == node_link
{
feed.setLink1(self.currentElement)
}
if elementName == node_description
{
feed.feedDescription = self.currentElement
}
if elementName == node_language
{
feed.language = self.currentElement
}
if elementName == node_lastBuildDate
{
feed.setlastBuildDate(self.currentElement)
}
if elementName == node_generator
{
feed.generator = self.currentElement
}
if elementName == node_copyright
{
feed.copyright = self.currentElement
}
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
self.currentElement += string
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError) {
if let closure = self.callbackClosure
{
closure(feed: nil, error: parseError)
}
}
} | mit | 9b66466e6c6836742a350890103d7dda | 27.440758 | 173 | 0.514 | 5.420054 | false | false | false | false |
netguru/inbbbox-ios | Inbbbox/Source Files/ViewModels/ProfileProjectsViewModel.swift | 1 | 4108 | //
// ProfileProjectsViewModel.swift
// Inbbbox
//
// Copyright © 2017 Netguru Sp. z o.o. All rights reserved.
//
import Foundation
import PromiseKit
class ProfileProjectsViewModel: ProfileProjectsOrBucketsViewModel {
weak var delegate: BaseCollectionViewViewModelDelegate?
var projects = [ProjectType]()
var projectsIndexedShots = [Int: [ShotType]]()
fileprivate let projectsProvider = ProjectsProvider()
fileprivate let shotsProvider = ShotsProvider()
fileprivate var user: UserType
var itemsCount: Int {
return projects.count
}
init(user: UserType) {
self.user = user
}
func downloadInitialItems() {
firstly {
projectsProvider.provideProjects(forUser: user)
}.then { projects -> Void in
var projectsShouldBeReloaded = true
if let projects = projects {
if projects == self.projects && projects.count != 0 {
projectsShouldBeReloaded = false
}
self.projects = projects
self.downloadShots(forProjects: projects)
}
if projectsShouldBeReloaded {
self.delegate?.viewModelDidLoadInitialItems()
}
}.catch { error in
self.delegate?.viewModelDidFailToLoadInitialItems(error)
}
}
func downloadItemsForNextPage() {
guard UserStorage.isUserSignedIn else {
return
}
firstly {
projectsProvider.nextPage()
}.then { projects -> Void in
if let projects = projects, projects.count > 0 {
let indexes = projects.enumerated().map {
index, _ in
return index + self.projects.count
}
self.projects.append(contentsOf: projects)
let indexPaths = indexes.map {
IndexPath(row: ($0), section: 0)
}
self.delegate?.viewModel(self, didLoadItemsAtIndexPaths: indexPaths)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
func downloadItem(at index: Int) { /* empty */ }
func downloadShots(forProjects projects: [ProjectType]) {
for project in projects {
firstly {
shotsProvider.provideShotsForProject(project)
}.then { shots -> Void in
var projectsShotsShouldBeReloaded = true
guard let index = self.projects.index(where: { $0.identifier == project.identifier }) else { return }
if let oldShots = self.projectsIndexedShots[index], let newShots = shots {
projectsShotsShouldBeReloaded = oldShots != newShots
}
self.projectsIndexedShots[index] = shots ?? [ShotType]()
if projectsShotsShouldBeReloaded {
let indexPath = IndexPath(row: index, section: 0)
self.delegate?.viewModel(self, didLoadShotsForItemAtIndexPath: indexPath)
}
}.catch { error in
self.notifyDelegateAboutFailure(error)
}
}
}
func projectTableViewCellViewData(_ indexPath: IndexPath) -> ProfileProjectTableViewCellViewData {
return ProfileProjectTableViewCellViewData(project: projects[indexPath.row], shots: projectsIndexedShots[indexPath.row])
}
func clearViewModelIfNeeded() {
projects = []
delegate?.viewModelDidLoadInitialItems()
}
}
extension ProfileProjectsViewModel {
struct ProfileProjectTableViewCellViewData {
let name: String
let numberOfShots: String
let shots: [ShotType]?
init(project: ProjectType, shots: [ShotType]?) {
self.name = project.name ?? ""
self.numberOfShots = String(format: "%d", project.shotsCount)
if let shots = shots, shots.count > 0 {
self.shots = shots
} else {
self.shots = nil
}
}
}
}
| gpl-3.0 | 54c12af071f987182a31b406a71efbc4 | 32.663934 | 128 | 0.581203 | 5.245211 | false | false | false | false |
imex94/NetworkKit | NetworkKit/NKHTTPRequest.swift | 1 | 10300 | //
// NKHTTPRequest.swift
// NetworkKit
//
// The MIT License (MIT)
//
// Copyright (c) 2016 Alex Telek
//
// 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
/// HTTP Request error that can occur during network fetching or
/// parsing the data
/// Two main types exist:
/// WARNING: Not serious error, just a warning that somethong went wrong
/// ERROR: Serious error, might cause the app to crash
public enum NKHTTPRequestError: Error {
case invalidURL(String)
case dataTaskError(String)
case noDataReturned(String)
case serializationException(String)
case noInternetConnection(String)
}
/// An extension for the custom error type to return the error message
extension NKHTTPRequestError {
public var message: String {
switch self {
case .invalidURL(let x): return x
case .dataTaskError(let x): return x
case .noDataReturned(let x): return x
case .serializationException(let x): return x
case .noInternetConnection(let x): return x
}
}
}
/// Successful HTTP Request Closure
public typealias NKHTTPRequestSuccessClosure = (Any) -> Void
/// Failure HTTP Request Closure
public typealias NKHTTPRequestFailureClosure = (NKHTTPRequestError) -> Void
/// Create an HTTP Request
open class NKHTTPRequest: NSObject {
/**
A simple HTTP GET method to get request from a url.
- Parameters:
- urlString: The string representing the url.
- params: The parameters you need to pass with the GET method. Everything after '?'.
- success: Successful closure in case the request was successful.
- failure: Failure Closure which notifies if any error has occured during the request.
*/
open class func GET(_ urlString: String, params: [String: String]?, success: @escaping NKHTTPRequestSuccessClosure, failure: @escaping NKHTTPRequestFailureClosure) -> URLSessionDataTask? {
#if !os(watchOS)
guard NKReachability.isNetworkAvailable() else {
failure(.noInternetConnection("The Internet connection appears to be offline. Try to connect again."))
return nil
}
#endif
var urlS = urlString
if let params = params {
urlS += "?"
var counter = 0
for (key, value) in params {
if counter == 0 { urlS += "\(key)=\(value)" }
else {
urlS += "&\(key)=\(value)"
}
counter += 1
}
}
guard let url = URL(string: urlS) else {
failure(.invalidURL("ERROR: \(urlS) is an invalid URL for the HTTP Request."))
return nil
}
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
return dataTaskWithRequest(request, success: success, failure: failure)
}
/**
A simple HTTP POST method to post a resource to the url.
- Parameters:
- urlString: The string representing the url.
- params: The body you need to pass with the POST method. Resources you want to pass.
- success: Successful closure in case the request was successful.
- failure: Failure Closure which notifies if any error has occured during the request.
*/
open class func POST(_ urlString: String, params: [AnyHashable: Any]?, success: @escaping NKHTTPRequestSuccessClosure, failure: @escaping NKHTTPRequestFailureClosure) -> URLSessionDataTask? {
#if !os(watchOS)
guard NKReachability.isNetworkAvailable() else {
failure(.noInternetConnection("The Internet connection appears to be offline. Try to connect again."))
return nil
}
#endif
guard let url = URL(string: urlString) else {
failure(.invalidURL("ERROR: \(urlString) is an invalid URL for the HTTP Request."))
return nil
}
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
if params != nil { request.httpBody = try? JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted) }
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
return dataTaskWithRequest(request, success: success, failure: failure)
}
/**
A simple HTTP POST method to post a resource to the url.
- Parameters:
- urlString: The string representing the url.
- params: The body you need to pass with the POST method. Resources you want to pass.
- success: Successful closure in case the request was successful.
- failure: Failure Closure which notifies if any error has occured during the request.
*/
open class func POST(_ urlString: String, headers: [String: String], params: [AnyHashable: Any]?, success: @escaping NKHTTPRequestSuccessClosure, failure: @escaping NKHTTPRequestFailureClosure) -> URLSessionDataTask? {
#if !os(watchOS)
guard NKReachability.isNetworkAvailable() else {
failure(.noInternetConnection("The Internet connection appears to be offline. Try to connect again."))
return nil
}
#endif
guard let url = URL(string: urlString) else {
failure(.invalidURL("ERROR: \(urlString) is an invalid URL for the HTTP Request."))
return nil
}
let request = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
for (key, value) in headers {
request.setValue(value, forHTTPHeaderField: key)
}
if params != nil { request.httpBody = try? JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted) }
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
return dataTaskWithRequest(request, success: success, failure: failure)
}
/**
A simple HTTP DELETE method to delete a resource from the server.
- Parameters:
- urlString: The string representing the url.
- headers: Header key and value pairs
- params: The body you need to pass with the DELETE method. Resources you want to delete.
- success: Successful closure in case the request was successful.
- failure: Failure Closure which notifies if any error has occured during the request.
*/
open class func DELETE(_ urlString: String, params: [AnyHashable: Any]?, success: @escaping NKHTTPRequestSuccessClosure, failure: @escaping NKHTTPRequestFailureClosure) -> URLSessionDataTask? {
#if !os(watchOS)
guard NKReachability.isNetworkAvailable() else {
failure(.noInternetConnection("The Internet connection appears to be offline. Try to connect again."))
return nil
}
#endif
guard let url = URL(string: urlString) else {
failure(.invalidURL("ERROR: \(urlString) is an invalid URL for the HTTP Request."))
return nil
}
let request = NSMutableURLRequest(url: url)
request.httpMethod = "DELETE"
if params != nil { request.httpBody = try? JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions.prettyPrinted) }
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
return dataTaskWithRequest(request, success: success, failure: failure)
}
fileprivate class func dataTaskWithRequest(_ request: NSMutableURLRequest, success: @escaping NKHTTPRequestSuccessClosure, failure: @escaping NKHTTPRequestFailureClosure) -> URLSessionDataTask {
let dataTask = URLSession.shared.dataTask(with: request as URLRequest) { (d, r, e) in
guard (e == nil) else {
failure(.invalidURL("WARNING: \(e!.localizedDescription)"))
return
}
guard let data = d else {
failure(.invalidURL("WARNING: There was no data returned for this request."))
return
}
DispatchQueue.main.async(execute: { () -> Void in
var responseDict: Any?
do {
responseDict = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
} catch {
failure(.serializationException("ERROR: There was an error parsing the data from the response."))
}
guard let json = responseDict else {
failure(.serializationException("WARNING: There was no data parsed from the response. It's empty. "))
return
}
success(json)
})
}
dataTask.resume()
return dataTask
}
}
| mit | 4a05c701e27443dee39e73fd604ee1ec | 40.532258 | 222 | 0.630291 | 5.225774 | false | false | false | false |
benlangmuir/swift | test/Generics/sr8945.swift | 2 | 638 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module %S/Inputs/sr8945-other.swift -emit-module-path %t/other.swiftmodule -module-name other
// RUN: %target-swift-frontend -emit-silgen %s -I%t -debug-generic-signatures 2>&1 | %FileCheck %s
// https://github.com/apple/swift/issues/51450
import other
public class C : P {
public typealias T = Int
}
public func takesInt(_: Int) {}
// CHECK-LABEL: .foo@
// CHECK-NEXT: Generic signature: <T, S where T : C, S : Sequence, S.[Sequence]Element == Int>
public func foo<T : C, S : Sequence>(_: T, _ xs: S) where S.Element == T.T {
for x in xs {
takesInt(x)
}
}
| apache-2.0 | 3dc8c86393f244c5504cd27b77f4527a | 29.380952 | 130 | 0.661442 | 2.926606 | false | false | false | false |
itsaboutcode/WordPress-iOS | WordPress/Classes/ViewRelated/What's New/Views/AnnouncementCell.swift | 1 | 4268 |
class AnnouncementCell: UITableViewCell {
// MARK: - View elements
private lazy var headingLabel: UILabel = {
return makeLabel(font: Appearance.headingFont)
}()
private lazy var subHeadingLabel: UILabel = {
return makeLabel(font: Appearance.subHeadingFont, color: .textSubtle)
}()
private lazy var descriptionStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [headingLabel, subHeadingLabel])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
return stackView
}()
private lazy var announcementImageView: UIImageView = {
return UIImageView()
}()
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [announcementImageView, descriptionStackView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.setCustomSpacing(Appearance.imageTextSpacing, after: announcementImageView)
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(mainStackView)
contentView.pinSubviewToSafeArea(mainStackView, insets: Appearance.mainStackViewInsets)
NSLayoutConstraint.activate([
announcementImageView.heightAnchor.constraint(equalToConstant: Appearance.announcementImageSize),
announcementImageView.widthAnchor.constraint(equalToConstant: Appearance.announcementImageSize)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Configures the labels and image views using the data from a `WordPressKit.Feature` object.
/// - Parameter feature: The `feature` containing the information to fill the cell with.
func configure(feature: WordPressKit.Feature) {
if let iconBase64Components = feature.iconBase64,
!iconBase64Components.isEmpty,
let base64Image = iconBase64Components.components(separatedBy: ";base64,")[safe: 1],
let imageData = Data(base64Encoded: base64Image, options: .ignoreUnknownCharacters),
let icon = UIImage(data: imageData) {
announcementImageView.image = icon
}
else if let url = URL(string: feature.iconUrl) {
announcementImageView.af_setImage(withURL: url)
}
headingLabel.text = feature.title
subHeadingLabel.text = feature.subtitle
}
/// Configures the labels and image views using the data passed as parameters.
/// - Parameters:
/// - title: The title string to use for the heading.
/// - description: The description string to use for the sub heading.
/// - image: The image to use for the image view.
func configure(title: String, description: String, image: UIImage?) {
headingLabel.text = title
subHeadingLabel.text = description
announcementImageView.image = image
announcementImageView.isHidden = image == nil
}
}
// MARK: Helpers
private extension AnnouncementCell {
func makeLabel(font: UIFont, color: UIColor? = nil) -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.font = font
if let color = color {
label.textColor = color
}
return label
}
}
// MARK: - Appearance
private extension AnnouncementCell {
enum Appearance {
// heading
static let headingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline), size: 17)
// sub-heading
static let subHeadingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .subheadline), size: 15)
// announcement image
static let announcementImageSize: CGFloat = 48
// main stack view
static let imageTextSpacing: CGFloat = 16
static let mainStackViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 0)
}
}
| gpl-2.0 | 376fdc468de91237592ea02412d2e223 | 35.793103 | 135 | 0.683458 | 5.423126 | false | false | false | false |
chungng/workoutbuddy | Workout Buddy/RootViewController.swift | 1 | 7084 | //
// RootViewController.swift
// Workout Buddy
//
// Created by Chung Ng on 12/12/14.
// Copyright (c) 2014 Chung Ng. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
var currentViewControllerIndex: Int = 0
var pendingViewControllerIndex: Int = 0
@IBOutlet weak var pageControl: UIPageControl!
// Pops up an alert and adds an entry to the current exercise
@IBAction func addEntry(sender: AnyObject) {
let exercise = self.modelController.exerciseNames[self.currentViewControllerIndex].name
var alert = UIAlertController(title: exercise,
message: "Add a new entry",
preferredStyle: .Alert)
//BUGBUG: Need to validate weight field is populated before activating the save button
let saveAction = UIAlertAction(title: "Save",
style: .Default) { (action: UIAlertAction!) -> Void in
let weight = ((alert.textFields![0] as UITextField).text as NSString).doubleValue
let reps = ((alert.textFields?[1] as UITextField).text as NSString).integerValue
self.modelController.addEntry(exercise, weight: weight, reps: reps)
//self.tableView.reloadData()
let dataViewController = self.pageViewController!.viewControllers[0] as DataViewController
dataViewController.dataObject = self.modelController.getDataObject(self.currentViewControllerIndex)
let tableView:UITableView = self.pageViewController!.viewControllers[0].tableView
tableView.reloadData()
}
let cancelAction = UIAlertAction(title: "Cancel",
style: .Default) { (action: UIAlertAction!) -> Void in
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
textField.placeholder = "Weight"
textField.keyboardType = UIKeyboardType.DecimalPad
}
alert.addTextFieldWithConfigurationHandler {
(textField: UITextField!) -> Void in
textField.placeholder = "Repetitions"
textField.keyboardType = UIKeyboardType.DecimalPad
}
alert.addAction(saveAction)
alert.addAction(cancelAction)
presentViewController(alert,
animated: true,
completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers: NSArray = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
// Make the navigation bar show
self.navigationController?.navigationBar.translucent = false
// Update page control
pageControl.numberOfPages = self.modelController.exerciseNames.count
pageControl.currentPage = self.modelController.indexOfViewController(self.pageViewController!.viewControllers[0] as DataViewController)
// BUGBUG: Need to hook up UIPageControl's call backs to handle navigation via the pageControl. Disable for now.
pageControl.enabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
// Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers[0] as UIViewController
let viewControllers: NSArray = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
// BUGBUG: There is a bug here. Probably a race condition where playing around with the page transitions in the UI can cause us to fire events out of sequence (theory) and the currentViewController index will be WRONG, thus getting the wrong dot. However, this self corrects after the next transition.
func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [AnyObject]) {
self.pendingViewControllerIndex = self.modelController.indexOfViewController(pendingViewControllers[0] as DataViewController)
}
func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [AnyObject], transitionCompleted completed: Bool) {
self.currentViewControllerIndex = self.pendingViewControllerIndex
// Update page control
self.pageControl.numberOfPages = self.modelController.exerciseNames.count
self.pageControl.currentPage = self.currentViewControllerIndex
}
}
| mit | f8687005f8bee9e2e11132a43e3ff496 | 46.864865 | 305 | 0.705251 | 5.854545 | false | false | false | false |
AnRanScheme/MagiRefresh | Example/MagiRefresh/MagiRefresh/UI/Header/MagiArrowHeader.swift | 1 | 3600 | //
// MagiArrowHeader.swift
// MagiRefresh
//
// Created by anran on 2018/9/5.
// Copyright © 2018年 anran. All rights reserved.
//
import UIKit
public class MagiArrowHeader: MagiRefreshHeaderConrol {
public var pullingText: String = MagiRefreshDefaults.shared.headPullingText
public var readyText: String = MagiRefreshDefaults.shared.readyText
public var refreshingText: String = MagiRefreshDefaults.shared.refreshingText
fileprivate lazy var arrowImgV: UIImageView = {
let arrowImgV = UIImageView()
let bundle = Bundle(for: MagiArrowHeader.classForCoder())
let path = bundle.path(forResource: "Image", ofType: "bundle", inDirectory: nil) ?? ""
let urlString = (path as NSString).appendingPathComponent("arrow.png")
let image = UIImage(contentsOfFile: urlString)
arrowImgV.image = image
arrowImgV.layer.anchorPoint = CGPoint(x: 0.5, y: 0.5)
return arrowImgV
}()
fileprivate lazy var promptlabel: UILabel = {
let promptlabel = UILabel()
promptlabel.textAlignment = .center
promptlabel.textColor = UIColor.lightGray
promptlabel.sizeToFit()
if #available(iOS 8.2, *) {
promptlabel.font = UIFont.systemFont(ofSize: 11,
weight: UIFont.Weight.thin)
}
else {
promptlabel.font = UIFont.systemFont(ofSize: 11)
}
return promptlabel
}()
lazy var indicator: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(
style: .gray)
indicator.hidesWhenStopped = true
return indicator
}()
override public func setupProperties() {
super.setupProperties()
addSubview(arrowImgV)
addSubview(promptlabel)
addSubview(indicator)
}
override public func layoutSubviews() {
super.layoutSubviews()
promptlabel.sizeToFit()
promptlabel.center = CGPoint(x: magi_width/2, y: magi_height/2)
arrowImgV.frame = CGRect(x: 0, y: 0, width: 12, height: 12)
arrowImgV.magi_right = promptlabel.magi_left-20.0
arrowImgV.magi_centerY = promptlabel.magi_centerY
indicator.center = arrowImgV.center
}
override public func magiDidScrollWithProgress(progress: CGFloat, max: CGFloat) {
super.magiDidScrollWithProgress(progress: progress, max: max)
}
override public func magiRefreshStateDidChange(_ status: MagiRefreshStatus) {
super.magiRefreshStateDidChange(status)
switch status {
case .none:
arrowImgV.isHidden = false
indicator.stopAnimating()
UIView.animate(withDuration: 0.3) {
self.arrowImgV.transform = CGAffineTransform.identity
}
case .scrolling:
promptlabel.text = pullingText
promptlabel.sizeToFit()
UIView.animate(withDuration: 0.3) {
self.arrowImgV.transform = CGAffineTransform.identity
}
case .ready:
indicator.stopAnimating()
promptlabel.text = readyText
UIView.animate(withDuration: 0.3) {
self.arrowImgV.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
}
case .refreshing:
promptlabel.text = refreshingText
arrowImgV.isHidden = true
indicator.startAnimating()
case .willEndRefresh:
indicator.stopAnimating()
}
}
}
| mit | 90fb422adab203b66c7c9a55ba25d329 | 32.933962 | 94 | 0.618293 | 4.821716 | false | false | false | false |
Amefuri/ZSwiftKit | ZSwiftKit/Classes/Helper+Image.swift | 1 | 3263 | //
// Helper+UIImageView.swift
// common
//
// Created by peerapat atawatana on 7/5/2559 BE.
// Copyright © 2559 DaydreamClover. All rights reserved.
//
import UIKit
public extension Helper {
struct Image {
public static func configCircularImage(_ imageView:UIImageView) {
imageView.layer.cornerRadius = imageView.frame.size.height / 2;
imageView.layer.masksToBounds = true;
}
/*
-(void)setRoundedView:(UIImageView *)roundedView toDiameter:(float)newSize;
{
CGPoint saveCenter = roundedView.center;
CGRect newFrame = CGRectMake(roundedView.frame.origin.x, roundedView.frame.origin.y, newSize, newSize);
roundedView.frame = newFrame;
roundedView.layer.cornerRadius = newSize / 2.0;
roundedView.center = saveCenter;
}
*/
public static func ResizeImage(_ image: UIImage, targetSize: CGSize) -> UIImage {
// This is the rect that we've calculated out and this is what is actually used below
let rect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)
// Actually do the resizing to the rect using the ImageContext stuff
UIGraphicsBeginImageContextWithOptions(targetSize, false, 1.0)
image.draw(in: rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
public static func getDataBase64(_ data:Foundation.Data) -> String {
return data.base64EncodedString(options: .lineLength64Characters)
}
public static func getImageBase64WithCompression(_ image:UIImage, compression:CGFloat) -> String? {
if let photoData = image.jpegData(compressionQuality: compression) {
return photoData.base64EncodedString(options: .lineLength64Characters)
}
return nil
}
public static func getImageDataWithCompression(_ image:UIImage, compression:CGFloat) -> Foundation.Data? {
return image.jpegData(compressionQuality: compression)
}
public static func decodeImageBase4ToNSData(_ strBase64:String) -> Foundation.Data? {
return Foundation.Data(base64Encoded: strBase64, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)
}
public static func sizeForImageResizeByKeepAspectRatio(_ maxSize:CGFloat, width:CGFloat, height:CGFloat)-> CGSize? {
let maxWidth = width > height ? width : height
if maxWidth > maxSize {
let scaleRatio = maxSize/maxWidth
let newWidth = width * scaleRatio
let newHeight = height * scaleRatio
let newSize = CGSize(width: newWidth, height: newHeight)
return newSize
}
return nil
}
public static func resizeImageInTableViewCell(_ imageView:UIImageView, width:CGFloat, height:CGFloat) {
let itemSize = CGSize(width: width, height: height);
UIGraphicsBeginImageContextWithOptions(itemSize, false, UIScreen.main.scale);
let imageRect = CGRect(x: 0.0, y: 0.0, width: itemSize.width, height: itemSize.height);
imageView.image!.draw(in: imageRect)
imageView.image! = UIGraphicsGetImageFromCurrentImageContext()!;
UIGraphicsEndImageContext();
}
}
}
| mit | 143b2f8f8a89b635ef988799c9664cf8 | 36.930233 | 120 | 0.687002 | 4.713873 | false | false | false | false |
badoo/Chatto | Chatto/sources/Keyboard/KeyboardTracker.swift | 1 | 4233 | //
// Copyright (c) Badoo Trading Limited, 2010-present. All rights reserved.
//
import Foundation
import UIKit
@frozen
public enum KeyboardState {
case hiding
case hidden
case showing
case shown
}
public struct KeyboardStatus {
public let frame: CGRect
public let state: KeyboardState
public init(frame: CGRect,
state: KeyboardState) {
self.frame = frame
self.state = state
}
}
public protocol KeyboardTrackerDelegate: AnyObject {
func didUpdate(keyboardStatus: KeyboardStatus)
}
public protocol KeyboardTrackerProtocol: AnyObject {
var keyboardStatus: KeyboardStatus { get }
var delegate: KeyboardTrackerDelegate? { get set }
}
public final class KeyboardTracker: KeyboardTrackerProtocol {
private let notificationCenter: NotificationCenter
public weak var delegate: KeyboardTrackerDelegate?
public private(set) var keyboardStatus: KeyboardStatus = .init(frame: .zero, state: .hidden) {
didSet {
self.delegate?.didUpdate(keyboardStatus: self.keyboardStatus)
}
}
public init(notificationCenter: NotificationCenter) {
self.notificationCenter = notificationCenter
self.setupNotifications()
}
private func setupNotifications() {
self.notificationCenter.addObserver(
self,
selector: #selector(KeyboardTracker.keyboardWillShow(_:)),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
self.notificationCenter.addObserver(
self,
selector: #selector(KeyboardTracker.keyboardDidShow(_:)),
name: UIResponder.keyboardDidShowNotification,
object: nil
)
self.notificationCenter.addObserver(
self,
selector: #selector(KeyboardTracker.keyboardWillHide(_:)),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
self.notificationCenter.addObserver(
self,
selector: #selector(KeyboardTracker.keyboardDidHide(_:)),
name: UIResponder.keyboardDidHideNotification,
object: nil
)
self.notificationCenter.addObserver(
self,
selector: #selector(KeyboardTracker.keyboardWillChangeFrame(_:)),
name: UIResponder.keyboardWillChangeFrameNotification,
object: nil
)
}
@objc
private func keyboardWillShow(_ notification: Notification) {
let keyboardFrame = self.keyboardFrame(from: notification)
guard keyboardFrame.height > 0 else { return } // Some keyboards may report initial willShow/DidShow notifications with invalid positions
self.keyboardStatus = .init(frame: keyboardFrame, state: .showing)
}
@objc
private func keyboardDidShow(_ notification: Notification) {
let keyboardFrame = self.keyboardFrame(from: notification)
guard keyboardFrame.height > 0 else { return } // Some keyboards may report initial willShow/DidShow notifications with invalid positions
self.keyboardStatus = .init(frame: keyboardFrame, state: .shown)
}
@objc
private func keyboardWillChangeFrame(_ notification: Notification) {
let keyboardFrame = self.keyboardFrame(from: notification)
guard keyboardFrame.height == 0 else { return }
self.keyboardStatus = .init(frame: keyboardFrame, state: .hiding)
}
@objc
private func keyboardWillHide(_ notification: Notification) {
let keyboardFrame = self.keyboardFrame(from: notification)
self.keyboardStatus = .init(frame: keyboardFrame, state: .hiding)
}
@objc
private func keyboardDidHide(_ notification: Notification) {
let keyboardFrame = self.keyboardFrame(from: notification)
self.keyboardStatus = .init(frame: keyboardFrame, state: .hidden)
}
private func keyboardFrame(from notification: Notification) -> CGRect {
let userInfo = (notification as NSNotification).userInfo
let keyboardFrameEndUserInfo = userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue
return keyboardFrameEndUserInfo?.cgRectValue ?? .zero
}
}
| mit | 91686b1fa3842f4b718fdd0a900e1752 | 32.595238 | 146 | 0.678479 | 5.518905 | false | false | false | false |
lorentey/swift | test/decl/var/properties.swift | 3 | 36188 | // RUN: %target-typecheck-verify-swift
func markUsed<T>(_ t: T) {}
struct X { }
var _x: X
class SomeClass {}
func takeTrailingClosure(_ fn: () -> ()) -> Int {}
func takeIntTrailingClosure(_ fn: () -> Int) -> Int {}
//===---
// Stored properties
//===---
var stored_prop_1: Int = 0
var stored_prop_2: Int = takeTrailingClosure {}
//===---
// Computed properties -- basic parsing
//===---
var a1: X {
get {
return _x
}
}
var a2: X {
get {
return _x
}
set {
_x = newValue
}
}
var a3: X {
get {
return _x
}
set(newValue) {
_x = newValue
}
}
var a4: X {
set {
_x = newValue
}
get {
return _x
}
}
var a5: X {
set(newValue) {
_x = newValue
}
get {
return _x
}
}
// Reading/writing properties
func accept_x(_ x: X) { }
func accept_x_inout(_ x: inout X) { }
func test_global_properties(_ x: X) {
accept_x(a1)
accept_x(a2)
accept_x(a3)
accept_x(a4)
accept_x(a5)
a1 = x // expected-error {{cannot assign to value: 'a1' is a get-only property}}
a2 = x
a3 = x
a4 = x
a5 = x
accept_x_inout(&a1) // expected-error {{cannot pass immutable value as inout argument: 'a1' is a get-only property}}
accept_x_inout(&a2)
accept_x_inout(&a3)
accept_x_inout(&a4)
accept_x_inout(&a5)
}
//===--- Implicit 'get'.
var implicitGet1: X {
return _x
}
var implicitGet2: Int {
var zzz = 0
// expected-warning@-1 {{initialization of variable 'zzz' was never used; consider replacing with assignment to '_' or removing it}}
// For the purpose of this test, any other function attribute work as well.
@inline(__always)
func foo() {}
return 0
}
var implicitGet3: Int {
@inline(__always)
func foo() {}
return 0
}
// Here we used apply weak to the getter itself, not to the variable.
var x15: Int {
// For the purpose of this test we need to use an attribute that cannot be
// applied to the getter.
weak
var foo: SomeClass? = SomeClass() // expected-warning {{variable 'foo' was written to, but never read}}
// expected-warning@-1 {{instance will be immediately deallocated because variable 'foo' is 'weak'}}
// expected-note@-2 {{a strong reference is required to prevent the instance from being deallocated}}
// expected-note@-3 {{'foo' declared here}}
return 0
}
// Disambiguated as stored property with a trailing closure in the initializer.
//
var disambiguateGetSet1a: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}}
get {}
}
var disambiguateGetSet1b: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}}
get {
return 42
}
}
var disambiguateGetSet1c: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}}
set {} // expected-error {{variable with a setter must also have a getter}}
}
var disambiguateGetSet1d: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}}
set(newValue) {} // expected-error {{variable with a setter must also have a getter}}
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet2() {
func get(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
get {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet2Attr() {
func get(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
get {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet3() {
func set(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
set {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet3Attr() {
func set(_ fn: () -> ()) {}
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
set {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
func disambiguateGetSet4() {
func set(_ x: Int, fn: () -> ()) {}
let newValue: Int = 0
var a: Int = takeTrailingClosure {
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
func disambiguateGetSet4Attr() {
func set(_ x: Int, fn: () -> ()) {}
var newValue: Int = 0
// expected-warning@-1 {{variable 'newValue' was never mutated; consider changing to 'let' constant}}
var a: Int = takeTrailingClosure {
@inline(__always)
func foo() {}
set(newValue) {}
}
// Check that the property is read-write.
a = a + 42
}
// Disambiguated as stored property with a trailing closure in the initializer.
var disambiguateImplicitGet1: Int = 0 { // expected-error {{variable with getter/setter cannot have an initial value}}
return 42
}
var disambiguateImplicitGet2: Int = takeIntTrailingClosure {
return 42
}
//===---
// Observed properties
//===---
class C {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
}
protocol TrivialInit {
init()
}
class CT<T : TrivialInit> {
var prop1 = 42 {
didSet { }
}
var prop2 = false {
willSet { }
}
var prop3: Int? = nil {
didSet { }
}
var prop4: Bool? = nil {
willSet { }
}
var prop5: T? = nil {
didSet { }
}
var prop6: T? = nil {
willSet { }
}
var prop7 = T() {
didSet { }
}
var prop8 = T() {
willSet { }
}
}
//===---
// Parsing problems
//===---
var computed_prop_with_init_1: X {
get {}
} = X() // expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{2-2=;}}
var x2 { // expected-error{{computed property must have an explicit type}} {{7-7=: <# Type #>}} expected-error{{type annotation missing in pattern}}
get {
return _x
}
}
var (x3): X { // expected-error{{getter/setter can only be defined for a single variable}}
get {
return _x
}
}
var duplicateAccessors1: X {
get { // expected-note {{previous definition of getter here}}
return _x
}
set { // expected-note {{previous definition of setter here}}
_x = newValue
}
get { // expected-error {{variable already has a getter}}
return _x
}
set(v) { // expected-error {{variable already has a setter}}
_x = v
}
}
var duplicateAccessors2: Int = 0 {
willSet { // expected-note {{previous definition of 'willSet' here}}
}
didSet { // expected-note {{previous definition of 'didSet' here}}
}
willSet { // expected-error {{variable already has 'willSet'}}
}
didSet { // expected-error {{variable already has 'didSet'}}
}
}
var extraTokensInAccessorBlock1: X {
get {}
a // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
}
var extraTokensInAccessorBlock2: X {
get {}
weak // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
a
}
var extraTokensInAccessorBlock3: X {
get {}
a = b // expected-error {{expected 'get', 'set', 'willSet', or 'didSet' keyword to start an accessor definition}}
set {}
get {}
}
var extraTokensInAccessorBlock4: X {
get blah wibble // expected-error{{expected '{' to start getter definition}}
}
var extraTokensInAccessorBlock5: X {
set blah wibble // expected-error{{expected '{' to start setter definition}}
}
var extraTokensInAccessorBlock6: X { // expected-error{{non-member observing properties require an initializer}}
willSet blah wibble // expected-error{{expected '{' to start 'willSet' definition}}
}
var extraTokensInAccessorBlock7: X { // expected-error{{non-member observing properties require an initializer}}
didSet blah wibble // expected-error{{expected '{' to start 'didSet' definition}}
}
var extraTokensInAccessorBlock8: X {
foo // expected-error {{use of unresolved identifier 'foo'}}
get {} // expected-error{{use of unresolved identifier 'get'}}
set {} // expected-error{{use of unresolved identifier 'set'}}
}
var extraTokensInAccessorBlock9: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
struct extraTokensInAccessorBlock10 {
var x: Int {
get // expected-error {{expected '{' to start getter definition}}
var a = b
}
init() {}
}
var x9: X {
get ( ) { // expected-error{{expected '{' to start getter definition}}
}
}
var x10: X {
set ( : ) { // expected-error{{expected setter parameter name}}
}
get {}
}
var x11 : X {
set { // expected-error{{variable with a setter must also have a getter}}
}
}
var x12: X {
set(newValue %) { // expected-error {{expected ')' after setter parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start setter definition}}
}
}
var x13: X {} // expected-error {{computed property must have accessors specified}}
// Type checking problems
struct Y { }
var y: Y
var x20: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set {
y = newValue // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x21: X {
get {
return y // expected-error{{cannot convert return expression of type 'Y' to return type 'X'}}
}
set(v) {
y = v // expected-error{{cannot assign value of type 'X' to type 'Y'}}
}
}
var x23: Int, x24: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}
var x25: Int { // expected-error{{'var' declarations with multiple variables cannot have explicit getters/setters}}
return 42
}, x26: Int // expected-warning{{variable 'x26' was never used; consider replacing with '_' or removing it}}
// Properties of struct/enum/extensions
struct S {
var _backed_x: X, _backed_x2: X
var x: X {
get {
return _backed_x
}
mutating
set(v) {
_backed_x = v
}
}
}
extension S {
var x2: X {
get {
return self._backed_x2
}
mutating
set {
_backed_x2 = newValue
}
}
var x3: X {
get {
return self._backed_x2
}
}
}
struct StructWithExtension1 {
var foo: Int
static var fooStatic = 4
}
extension StructWithExtension1 {
var fooExt: Int // expected-error {{extensions must not contain stored properties}}
static var fooExtStatic = 4
}
class ClassWithExtension1 {
var foo: Int = 0
class var fooStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
extension ClassWithExtension1 {
var fooExt: Int // expected-error {{extensions must not contain stored properties}}
class var fooExtStatic = 4 // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
enum EnumWithExtension1 {
var foo: Int // expected-error {{enums must not contain stored properties}}
static var fooStatic = 4
}
extension EnumWithExtension1 {
var fooExt: Int // expected-error {{extensions must not contain stored properties}}
static var fooExtStatic = 4
}
protocol ProtocolWithExtension1 {
var foo: Int { get }
static var fooStatic : Int { get }
}
extension ProtocolWithExtension1 {
var fooExt: Int // expected-error{{extensions must not contain stored properties}}
static var fooExtStatic = 4 // expected-error{{static stored properties not supported in protocol extensions}}
}
protocol ProtocolWithExtension2 {
var bar: String { get }
}
struct StructureImplementingProtocolWithExtension2: ProtocolWithExtension2 {
let bar: String
}
extension ProtocolWithExtension2 {
static let baz: ProtocolWithExtension2 = StructureImplementingProtocolWithExtension2(bar: "baz") // expected-error{{static stored properties not supported in protocol extensions}}
}
func getS() -> S { // expected-note 2{{did you mean 'getS'?}}
let s: S
return s
}
func test_extension_properties(_ s: inout S, x: inout X) {
accept_x(s.x)
accept_x(s.x2)
accept_x(s.x3)
accept_x(getS().x)
accept_x(getS().x2)
accept_x(getS().x3)
s.x = x
s.x2 = x
s.x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
getS().x = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x2 = x // expected-error{{cannot assign to property: 'getS' returns immutable value}}
getS().x3 = x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
accept_x_inout(&getS().x) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x2) // expected-error{{cannot pass immutable value as inout argument: 'getS' returns immutable value}}
accept_x_inout(&getS().x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
x = getS().x
x = getS().x2
x = getS().x3
accept_x_inout(&s.x)
accept_x_inout(&s.x2)
accept_x_inout(&s.x3) // expected-error{{cannot pass immutable value as inout argument: 'x3' is a get-only property}}
}
extension S {
mutating
func test(other_x: inout X) {
x = other_x
x2 = other_x
x3 = other_x // expected-error{{cannot assign to property: 'x3' is a get-only property}}
other_x = x
other_x = x2
other_x = x3
}
}
// Accessor on non-settable type
struct Aleph {
var b: Beth {
get {
return Beth(c: 1)
}
}
}
struct Beth { // expected-note 2{{did you mean 'Beth'?}}
var c: Int
}
func accept_int_inout(_ c: inout Int) { }
func accept_int(_ c: Int) { }
func test_settable_of_nonsettable(_ a: Aleph) {
a.b.c = 1 // expected-error{{cannot assign}}
let x:Int = a.b.c
_ = x
accept_int(a.b.c)
accept_int_inout(&a.b.c) // expected-error {{cannot pass immutable value as inout argument: 'b' is a get-only property}}
}
// TODO: Static properties are only implemented for nongeneric structs yet.
struct MonoStruct {
static var foo: Int = 0
static var (bar, bas): (String, UnicodeScalar) = ("zero", "0")
static var zim: UInt8 {
return 0
}
static var zang = UnicodeScalar("\0")
static var zung: UInt16 {
get {
return 0
}
set {}
}
var a: Double
var b: Double
}
struct MonoStructOneProperty {
static var foo: Int = 22
}
enum MonoEnum {
static var foo: Int = 0
static var zim: UInt8 {
return 0
}
}
struct GenStruct<T> {
static var foo: Int = 0 // expected-error{{static stored properties not supported in generic types}}
}
class MonoClass {
class var foo: Int = 0 // expected-error{{class stored properties not supported in classes; did you mean 'static'?}}
}
protocol Proto {
static var foo: Int { get }
}
func staticPropRefs() -> (Int, Int, String, UnicodeScalar, UInt8) {
return (MonoStruct.foo, MonoEnum.foo, MonoStruct.bar, MonoStruct.bas,
MonoStruct.zim)
}
func staticPropRefThroughInstance(_ foo: MonoStruct) -> Int {
return foo.foo //expected-error{{static member 'foo' cannot be used on instance of type 'MonoStruct'}}
}
func memberwiseInitOnlyTakesInstanceVars() -> MonoStruct {
return MonoStruct(a: 1.2, b: 3.4)
}
func getSetStaticProperties() -> (UInt8, UInt16) {
MonoStruct.zim = 12 // expected-error{{cannot assign}}
MonoStruct.zung = 34
return (MonoStruct.zim, MonoStruct.zung)
}
var selfRefTopLevel: Int {
return selfRefTopLevel // expected-warning {{attempting to access 'selfRefTopLevel' within its own getter}}
}
var selfRefTopLevelSetter: Int {
get {
return 42
}
set {
markUsed(selfRefTopLevelSetter) // no-warning
selfRefTopLevelSetter = newValue // expected-warning {{attempting to modify 'selfRefTopLevelSetter' within its own setter}}
}
}
var selfRefTopLevelSilenced: Int {
get {
return properties.selfRefTopLevelSilenced // no-warning
}
set {
properties.selfRefTopLevelSilenced = newValue // no-warning
}
}
class SelfRefProperties {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{12-12=self.}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
var unused = setter + setter // expected-warning {{initialization of variable 'unused' was never used; consider replacing with assignment to '_' or removing it}} {{7-17=_}}
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
// expected-note@-1 {{access 'self' explicitly to silence this warning}} {{7-7=self.}}
}
}
var silenced: Int {
get {
return self.silenced // no-warning
}
set {
self.silenced = newValue // no-warning
}
}
var someOtherInstance: SelfRefProperties = SelfRefProperties()
var delegatingVar: Int {
// This particular example causes infinite access, but it's easily possible
// for the delegating instance to do something else.
return someOtherInstance.delegatingVar // no-warning
}
}
func selfRefLocal() {
var getter: Int {
return getter // expected-warning {{attempting to access 'getter' within its own getter}}
}
var setter: Int {
get {
return 42
}
set {
markUsed(setter) // no-warning
setter = newValue // expected-warning {{attempting to modify 'setter' within its own setter}}
}
}
}
struct WillSetDidSetProperties {
var a: Int {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var b: Int {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var c: Int {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
var d: Int {
didSet { // expected-error {{'didSet' cannot be provided together with a getter}}
markUsed("woot")
}
get {
return 4
}
}
var e: Int {
willSet { // expected-error {{'willSet' cannot be provided together with a setter}}
markUsed("woot")
}
set { // expected-error {{variable with a setter must also have a getter}}
return 4 // expected-error {{unexpected non-void return value in void function}}
}
}
var f: Int {
willSet(5) {} // expected-error {{expected willSet parameter name}}
didSet(^) {} // expected-error {{expected didSet parameter name}}
}
var g: Int {
willSet(newValue 5) {} // expected-error {{expected ')' after willSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start 'willSet' definition}}
}
var h: Int {
didSet(oldValue ^) {} // expected-error {{expected ')' after didSet parameter name}} expected-note {{to match this opening '('}}
// expected-error@-1 {{expected '{' to start 'didSet' definition}}
}
// didSet/willSet with initializers.
// Disambiguate trailing closures.
var disambiguate1: Int = 42 { // simple initializer, simple label
didSet {
markUsed("eek")
}
}
var disambiguate2: Int = 42 { // simple initializer, complex label
willSet(v) {
markUsed("eek")
}
}
var disambiguate3: Int = takeTrailingClosure {} { // Trailing closure case.
willSet(v) {
markUsed("eek")
}
}
var disambiguate4: Int = 42 {
willSet {}
}
var disambiguate5: Int = 42 {
didSet {}
}
var disambiguate6: Int = takeTrailingClosure {
@inline(__always)
func f() {}
return ()
}
var inferred1 = 42 {
willSet {
markUsed("almost")
}
didSet {
markUsed("here")
}
}
var inferred2 = 40 {
willSet {
markUsed(b)
markUsed(newValue)
}
}
var inferred3 = 50 {
willSet(newC) {
markUsed(c)
markUsed(newC)
}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate1 {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}}
}
}
struct WillSetDidSetDisambiguate1Attr {
var willSet: Int
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet = 42 // expected-error {{expected '{' to start 'willSet' definition}}
}
}
// Disambiguated as accessor.
struct WillSetDidSetDisambiguate2 {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
struct WillSetDidSetDisambiguate2Attr {
func willSet(_: () -> Int) {}
var x: (() -> ()) -> Int = takeTrailingClosure {
willSet {}
}
}
// No need to disambiguate -- this is clearly a function call.
func willSet(_: () -> Int) {}
struct WillSetDidSetDisambiguate3 {
var x: Int = takeTrailingClosure({
willSet { 42 }
})
}
protocol ProtocolGetSet1 {
var a: Int // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{13-13= { get <#set#> \}}}
}
protocol ProtocolGetSet2 {
var a: Int {} // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-16={ get <#set#> \}}}
}
protocol ProtocolGetSet3 {
var a: Int { get }
}
protocol ProtocolGetSet4 {
var a: Int { set } // expected-error {{variable with a setter must also have a getter}}
}
protocol ProtocolGetSet5 {
var a: Int { get set }
}
protocol ProtocolGetSet6 {
var a: Int { set get }
}
protocol ProtocolWillSetDidSet1 {
var a: Int { willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-25={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet2 {
var a: Int { didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-24={ get <#set#> \}}} expected-error {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet3 {
var a: Int { willSet didSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet4 {
var a: Int { didSet willSet } // expected-error {{property in protocol must have explicit { get } or { get set } specifier}} {{14-32={ get <#set#> \}}} expected-error 2 {{expected get or set in a protocol property}}
}
protocol ProtocolWillSetDidSet5 {
let a: Int { didSet willSet } // expected-error {{immutable property requirement must be declared as 'var' with a '{ get }' specifier}} {{3-6=var}} {{13-13= { get \}}} {{none}} expected-error 2 {{expected get or set in a protocol property}} expected-error {{'let' declarations cannot be computed properties}} {{3-6=var}}
}
var globalDidsetWillSet: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
var globalDidsetWillSet2 : Int = 42 {
didSet {}
}
class Box {
var num: Int
init(num: Int) {
self.num = num
}
}
func double(_ val: inout Int) {
val *= 2
}
class ObservingPropertiesNotMutableInWillSet {
var anotherObj : ObservingPropertiesNotMutableInWillSet
init() {}
var property: Int = 42 {
willSet {
// <rdar://problem/16826319> willSet immutability behavior is incorrect
anotherObj.property = 19 // ok
property = 19 // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&property) // expected-warning {{attempting to store to property 'property' within its own willSet}}
double(&self.property) // no-warning
}
}
// <rdar://problem/21392221> - call to getter through BindOptionalExpr was not viewed as a load
var _oldBox : Int
weak var weakProperty: Box? {
willSet {
_oldBox = weakProperty?.num ?? -1
}
}
func localCase() {
var localProperty: Int = 42 {
willSet {
localProperty = 19 // expected-warning {{attempting to store to property 'localProperty' within its own willSet}}
}
}
}
}
func doLater(_ fn : () -> ()) {}
// rdar://<rdar://problem/16264989> property not mutable in closure inside of its willSet
class MutableInWillSetInClosureClass {
var bounds: Int = 0 {
willSet {
let oldBounds = bounds
doLater { self.bounds = oldBounds }
}
}
}
// <rdar://problem/16191398> add an 'oldValue' to didSet so you can implement "didChange" properties
var didSetPropertyTakingOldValue : Int = 0 {
didSet(oldValue) {
markUsed(oldValue)
markUsed(didSetPropertyTakingOldValue)
}
}
// rdar://16280138 - synthesized getter is defined in terms of archetypes, not interface types
protocol AbstractPropertyProtocol {
associatedtype Index
var a : Index { get }
}
struct AbstractPropertyStruct<T> : AbstractPropertyProtocol {
typealias Index = T
var a : T
}
// Allow _silgen_name accessors without bodies.
var _silgen_nameGet1: Int {
@_silgen_name("get1") get
set { }
}
var _silgen_nameGet2: Int {
set { }
@_silgen_name("get2") get
}
var _silgen_nameGet3: Int {
@_silgen_name("get3") get
}
var _silgen_nameGetSet: Int {
@_silgen_name("get4") get
@_silgen_name("set4") set
}
// <rdar://problem/16375910> reject observing properties overriding readonly properties
class Base16375910 {
var x : Int { // expected-note {{attempt to override property here}}
return 42
}
var y : Int { // expected-note {{attempt to override property here}}
get { return 4 }
set {}
}
}
class Derived16375910 : Base16375910 {
override init() {}
override var x : Int { // expected-error {{cannot observe read-only property 'x'; it can't change}}
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16382967> Observing properties have no storage, so shouldn't prevent initializer synth
class Derived16382967 : Base16375910 {
override var y : Int {
willSet {
markUsed(newValue)
}
}
}
// <rdar://problem/16659058> Read-write properties can be made read-only in a property override
class Derived16659058 : Base16375910 {
override var y : Int { // expected-error {{cannot override mutable property with read-only property 'y'}}
get { return 42 }
}
}
// <rdar://problem/16406886> Observing properties don't work with ownership types
struct PropertiesWithOwnershipTypes {
unowned var p1 : SomeClass {
didSet {
}
}
init(res: SomeClass) {
p1 = res
}
}
// <rdar://problem/16608609> Assert (and incorrect error message) when defining a constant stored property with observers
class Test16608609 {
let constantStored: Int = 0 { // expected-error {{'let' declarations cannot be observing properties}} {{4-7=var}}
willSet {
}
didSet {
}
}
}
// <rdar://problem/16941124> Overriding property observers warn about using the property value "within its own getter"
class rdar16941124Base {
var x = 0
}
class rdar16941124Derived : rdar16941124Base {
var y = 0
override var x: Int {
didSet {
y = x + 1 // no warning.
}
}
}
// Overrides of properties with custom ownership.
class OwnershipBase {
class var defaultObject: AnyObject { fatalError("") }
var strongVar: AnyObject? // expected-note{{overridden declaration is here}}
weak var weakVar: AnyObject? // expected-note{{overridden declaration is here}}
// FIXME: These should be optional to properly test overriding.
unowned var unownedVar: AnyObject = defaultObject
unowned var optUnownedVar: AnyObject? = defaultObject
unowned(unsafe) var unownedUnsafeVar: AnyObject = defaultObject // expected-note{{overridden declaration is here}}
unowned(unsafe) var optUnownedUnsafeVar: AnyObject? = defaultObject
}
class OwnershipExplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned var optUnownedVar: AnyObject? {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? {
didSet {}
}
}
class OwnershipImplicitSub : OwnershipBase {
override var strongVar: AnyObject? {
didSet {}
}
override weak var weakVar: AnyObject? {
didSet {}
}
override unowned var unownedVar: AnyObject {
didSet {}
}
override unowned var optUnownedVar: AnyObject? {
didSet {}
}
override unowned(unsafe) var unownedUnsafeVar: AnyObject {
didSet {}
}
override unowned(unsafe) var optUnownedUnsafeVar: AnyObject? {
didSet {}
}
}
class OwnershipBadSub : OwnershipBase {
override weak var strongVar: AnyObject? { // expected-error {{cannot override 'strong' property with 'weak' property}}
didSet {}
}
override unowned var weakVar: AnyObject? { // expected-error {{cannot override 'weak' property with 'unowned' property}}
didSet {}
}
override weak var unownedVar: AnyObject { // expected-error {{'weak' variable should have optional type 'AnyObject?'}}
didSet {}
}
override unowned var unownedUnsafeVar: AnyObject { // expected-error {{cannot override 'unowned(unsafe)' property with 'unowned' property}}
didSet {}
}
}
// <rdar://problem/17391625> Swift Compiler Crashes when Declaring a Variable and didSet in an Extension
class rdar17391625 {
var prop = 42 // expected-note {{overri}}
}
extension rdar17391625 {
var someStoredVar: Int // expected-error {{extensions must not contain stored properties}}
var someObservedVar: Int { // expected-error {{extensions must not contain stored properties}}
didSet {
}
}
}
class rdar17391625derived : rdar17391625 {
}
extension rdar17391625derived {
// Not a stored property, computed because it is an override.
override var prop: Int { // expected-error {{overri}}
didSet {
}
}
}
// <rdar://problem/27671033> Crash when defining property inside an invalid extension
// (This extension is no longer invalid.)
public protocol rdar27671033P {}
struct rdar27671033S<Key, Value> {}
extension rdar27671033S : rdar27671033P where Key == String {
let d = rdar27671033S<Int, Int>() // expected-error {{extensions must not contain stored properties}}
}
// <rdar://problem/19874152> struct memberwise initializer violates new sanctity of previously set `let` property
struct r19874152S1 {
let number : Int = 42
}
_ = r19874152S1(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S1() // Ok
struct r19874152S2 {
var number : Int = 42
}
_ = r19874152S2(number:64) // Ok, property is a var.
_ = r19874152S2() // Ok
struct r19874152S3 { // expected-note {{'init(flavor:)' declared here}}
let number : Int = 42
let flavor : Int
}
_ = r19874152S3(number:64) // expected-error {{incorrect argument label in call (have 'number:', expected 'flavor:')}} {{17-23=flavor}}
_ = r19874152S3(number:64, flavor: 17) // expected-error {{extra argument 'number' in call}}
_ = r19874152S3(flavor: 17) // ok
_ = r19874152S3() // expected-error {{missing argument for parameter 'flavor' in call}}
struct r19874152S4 {
let number : Int? = nil
}
_ = r19874152S4(number:64) // expected-error {{argument passed to call that takes no arguments}}
_ = r19874152S4() // Ok
struct r19874152S5 {
}
_ = r19874152S5() // ok
struct r19874152S6 {
let (a,b) = (1,2) // Cannot handle implicit synth of this yet.
}
_ = r19874152S5() // ok
// <rdar://problem/24314506> QoI: Fix-it for dictionary initializer on required class var suggests [] instead of [:]
class r24314506 { // expected-error {{class 'r24314506' has no initializers}}
var myDict: [String: AnyObject] // expected-note {{stored property 'myDict' without initial value prevents synthesized initializers}} {{34-34= = [:]}}
}
// https://bugs.swift.org/browse/SR-3893
// Generic type is not inferenced from its initial value for properties with
// will/didSet
struct SR3893Box<Foo> {
let value: Foo
}
struct SR3893 {
// Each of these "bad" properties used to produce errors.
var bad: SR3893Box = SR3893Box(value: 0) {
willSet {
print(newValue.value)
}
}
var bad2: SR3893Box = SR3893Box(value: 0) {
willSet(new) {
print(new.value)
}
}
var bad3: SR3893Box = SR3893Box(value: 0) {
didSet {
print(oldValue.value)
}
}
var good: SR3893Box<Int> = SR3893Box(value: 0) {
didSet {
print(oldValue.value)
}
}
var plain: SR3893Box = SR3893Box(value: 0)
}
protocol WFI_P1 : class {}
protocol WFI_P2 : class {}
class WeakFixItTest {
init() {}
// expected-error @+1 {{'weak' variable should have optional type 'WeakFixItTest?'}} {{31-31=?}}
weak var foo : WeakFixItTest
// expected-error @+1 {{'weak' variable should have optional type '(WFI_P1 & WFI_P2)?'}} {{18-18=(}} {{33-33=)?}}
weak var bar : WFI_P1 & WFI_P2
}
// SR-8811 (Warning)
let sr8811a = fatalError() // expected-warning {{constant 'sr8811a' inferred to have type 'Never', which is an enum with no cases}} expected-note {{add an explicit type annotation to silence this warning}} {{12-12=: Never}}
let sr8811b: Never = fatalError() // Ok
let sr8811c = (16, fatalError()) // expected-warning {{constant 'sr8811c' inferred to have type '(Int, Never)', which contains an enum with no cases}} expected-note {{add an explicit type annotation to silence this warning}} {{12-12=: (Int, Never)}}
let sr8811d: (Int, Never) = (16, fatalError()) // Ok
// SR-10995
class SR_10995 {
func makeDoubleOptionalNever() -> Never?? {
return nil
}
func makeSingleOptionalNever() -> Never? {
return nil
}
func sr_10995_foo() {
let doubleOptionalNever = makeDoubleOptionalNever() // expected-warning {{constant 'doubleOptionalNever' inferred to have type 'Never??', which may be unexpected}}
// expected-note@-1 {{add an explicit type annotation to silence this warning}} {{28-28=: Never??}}
// expected-warning@-2 {{initialization of immutable value 'doubleOptionalNever' was never used; consider replacing with assignment to '_' or removing it}}
let singleOptionalNever = makeSingleOptionalNever() // expected-warning {{constant 'singleOptionalNever' inferred to have type 'Never?', which may be unexpected}}
// expected-note@-1 {{add an explicit type annotation to silence this warning}} {{28-28=: Never?}}
// expected-warning@-2 {{initialization of immutable value 'singleOptionalNever' was never used; consider replacing with assignment to '_' or removing it}}
}
}
// SR-9267
class SR_9267 {}
extension SR_9267 {
var foo: String = { // expected-error {{extensions must not contain stored properties}} // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'foo' a computed property}}{{19-21=}}
return "Hello"
}
}
enum SR_9267_E {
var SR_9267_prop: String = { // expected-error {{enums must not contain stored properties}} // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop' a computed property}}{{28-30=}}
return "Hello"
}
}
var SR_9267_prop_1: Int = { // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_1' a computed property}}{{25-27=}}
return 0
}
class SR_9267_C {
var SR_9267_prop_2: String = { // expected-error {{function produces expected type 'String'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_2' a computed property}}{{30-32=}}
return "Hello"
}
}
class SR_9267_C2 {
let SR_9267_prop_3: Int = { return 0 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} // expected-note {{Remove '=' to make 'SR_9267_prop_3' a computed property}}{{3-6=var}}{{27-29=}}
}
class LazyPropInClass {
lazy var foo: Int = { return 0 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}}
// expected-note@-1 {{Remove '=' to make 'foo' a computed property}}{{21-23=}}{{3-8=}}
}
| apache-2.0 | bc5148f8890304ce3672e46ea52eb4de | 26.086826 | 323 | 0.660164 | 3.744619 | false | false | false | false |
fs/Social-iOS | @Test/Test/MasterViewController.swift | 1 | 3588 | //
// MasterViewController.swift
// Test
//
// Created by Vladimir Goncharov on 04.04.16.
// Copyright © 2016 FlatStack. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var detailViewController: DetailViewController? = nil
var objects = [AnyObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
}
override func viewWillAppear(animated: Bool) {
self.clearsSelectionOnViewWillAppear = self.splitViewController!.collapsed
super.viewWillAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func insertNewObject(sender: AnyObject) {
objects.insert(NSDate(), atIndex: 0)
let indexPath = NSIndexPath(forRow: 0, inSection: 0)
self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let object = objects[indexPath.row] as! NSDate
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
controller.detailItem = object
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return objects.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let object = objects[indexPath.row] as! NSDate
cell.textLabel!.text = object.description
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
objects.removeAtIndex(indexPath.row)
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.
}
}
}
| mit | 22f6b1b3a316f94e183e1730274cb167 | 36.364583 | 157 | 0.69027 | 5.776167 | false | false | false | false |
ggu/2D-RPG-Template | Borba/UI/SKButtonContents.swift | 2 | 1130 | //
// SKButton.swift
// Borba
//
// Created by Gabriel Uribe on 6/5/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
import SpriteKit
class SKButtonContents : SKSpriteNode {
private enum Margin {
static let left: CGFloat = 20
static let right: CGFloat = 20
static let top: CGFloat = 10
static let bottom: CGFloat = 10
}
private var label: SKLabelNode
init(color: UIColor, text: String) {
self.label = SKLabelNode(text: text);
self.label.fontName = "Copperplate"
let buttonWidth = self.label.frame.width + Margin.left + Margin.right
let buttonHeight = self.label.frame.height + Margin.top + Margin.bottom
let size = CGSize(width: buttonWidth, height: buttonHeight)
super.init(texture: nil, color: color, size: size)
setup()
}
private func setup() {
label.position = CGPoint(x: 0, y: -Margin.top)
addChild(label)
}
func setMargins(horizontal: Int, vertical: Int) {}
func changeText(text: String) {}
required init?(coder aDecoder: NSCoder) {
self.label = SKLabelNode(text: "")
super.init(coder: aDecoder)
}
}
| mit | 67730882a6a8bde2b48780663276ba09 | 24.681818 | 75 | 0.665487 | 3.766667 | false | false | false | false |
qiuncheng/CuteAttribute | CuteAttribute/CuteAttributeKeys.swift | 1 | 615 | //
// CuteAttributeKeys.swift
// Cute
//
// Created by vsccw on 2017/8/9.
// Copyright © 2017年 https://vsccw.com. All rights reserved.
//
import UIKit
internal struct CuteAttributeKey {
static let rangesKey = UnsafeRawPointer(bitPattern: "rangesKey".hashValue)!
static let fromKey = UnsafeRawPointer(bitPattern: "fromKey".hashValue)!
static let tapRangesKey = UnsafeRawPointer(bitPattern: "tapRangesKey".hashValue)!
static let viewCuteKey = UnsafeRawPointer(bitPattern: "labelCuteKey".hashValue)!
static let highlightKey = UnsafeRawPointer(bitPattern: "highlightKey".hashValue)!
}
| mit | 4e66af5da2ff0dbd108ea8f5ae69b442 | 26.818182 | 85 | 0.745098 | 4.05298 | false | false | false | false |
apple/swift-corelibs-foundation | Tests/Foundation/Tests/TestNSSortDescriptor.swift | 2 | 11157 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 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
//
#if !DARWIN_COMPATIBILITY_TESTS
struct IntSortable {
var value: Int
}
struct StringSortable {
var value: String
}
struct PlayerRecordSortable: Hashable {
var name: String
var victories: Int
var tiebreakerPoints: Int
}
class TestNSSortDescriptor: XCTestCase {
// Conceptually, requires a < firstCopyOfB, firstCopyOfB == secondCopyOfB, firstCopyOfB !== secondCopyOfB (if reference types)
private func assertObjectsPass<Root, Value: Comparable>(_ a: Root, _ firstCopyOfB: Root, _ secondCopyOfB: Root, keyPath: KeyPath<Root, Value>) {
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: true)
XCTAssertEqual(sort.compare(a, to: firstCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfB), .orderedSame)
}
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: false)
XCTAssertEqual(sort.compare(a, to: firstCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfB), .orderedSame)
}
}
func assertObjectsPass<Root, BridgedRoot, BaseType, Value: Comparable>(_ a: Root, _ firstCopyOfB: Root, _ secondCopyOfB: Root, _ bridgedA: BridgedRoot, _ firstCopyOfBridgedB: BridgedRoot, _ secondCopyOfBridgedB: BridgedRoot, keyPath: KeyPath<BaseType, Value>) {
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: true)
XCTAssertEqual(sort.compare(bridgedA, to: firstCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(a, to: firstCopyOfBridgedB), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfBridgedB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: bridgedA), .orderedDescending)
XCTAssertEqual(sort.compare(bridgedA, to: secondCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfBridgedB), .orderedAscending)
XCTAssertEqual(sort.compare(secondCopyOfBridgedB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: bridgedA), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfBridgedB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfBridgedB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfBridgedB, to: firstCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfBridgedB), .orderedSame)
}
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: false)
XCTAssertEqual(sort.compare(bridgedA, to: firstCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(a, to: firstCopyOfBridgedB), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfBridgedB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: bridgedA), .orderedAscending)
XCTAssertEqual(sort.compare(bridgedA, to: secondCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfBridgedB), .orderedDescending)
XCTAssertEqual(sort.compare(secondCopyOfBridgedB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: bridgedA), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfBridgedB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfBridgedB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfBridgedB, to: firstCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfBridgedB), .orderedSame)
}
}
private func assertObjectsPass<Root, Value>(_ a: Root, _ firstCopyOfB: Root, _ secondCopyOfB: Root, keyPath: KeyPath<Root, Value>, comparator: @escaping Comparator) {
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: true, comparator: comparator)
XCTAssertEqual(sort.compare(a, to: firstCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfB), .orderedAscending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: a), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfB), .orderedSame)
}
do {
let sort = NSSortDescriptor(keyPath: keyPath, ascending: false, comparator: comparator)
XCTAssertEqual(sort.compare(a, to: firstCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(a, to: secondCopyOfB), .orderedDescending)
XCTAssertEqual(sort.compare(secondCopyOfB, to: a), .orderedAscending)
XCTAssertEqual(sort.compare(firstCopyOfB, to: secondCopyOfB), .orderedSame)
XCTAssertEqual(sort.compare(secondCopyOfB, to: firstCopyOfB), .orderedSame)
}
}
func testComparable() {
let a = IntSortable(value: 42)
let b = IntSortable(value: 108)
let bAgain = IntSortable(value: 108)
assertObjectsPass(a, b, bAgain, keyPath: \IntSortable.value)
}
func testBuiltinComparableObject() {
let a = NSString(string: "A")
let b = NSString(string: "B")
let bAgain = NSString(string: "B")
assertObjectsPass(a, b, bAgain, keyPath: \NSString.self)
}
func testBuiltinComparableBridgeable() {
let a = NSString(string: "A")
let b = NSString(string: "B")
let bAgain = NSString(string: "B")
let aString = "A"
let bString = "B"
let bStringAgain = "B"
assertObjectsPass(a, b, bAgain, aString, bString, bStringAgain, keyPath: \NSString.self)
assertObjectsPass(a, b, bAgain, aString, bString, bStringAgain, keyPath: \String.self)
}
func testComparatorSorting() {
let canonicalOrder = [ "Velma", "Daphne", "Scooby" ]
let a = StringSortable(value: "Velma")
let b = StringSortable(value: "Daphne")
let bAgain = StringSortable(value: "Daphne")
assertObjectsPass(a, b, bAgain, keyPath: \StringSortable.value) { (lhs, rhs) -> ComparisonResult in
let lhsIndex = canonicalOrder.firstIndex(of: lhs as! String)!
let rhsIndex = canonicalOrder.firstIndex(of: rhs as! String)!
if lhsIndex < rhsIndex {
return .orderedAscending
} else if lhsIndex > rhsIndex {
return .orderedDescending
} else {
return .orderedSame
}
}
}
private let runOnlySinglePermutation = false // Useful for debugging. Always keep set to false when committing.
func permute<T>(_ array: [T]) -> [[T]] {
guard !runOnlySinglePermutation else {
return [array]
}
guard !array.isEmpty else { return [[]] }
var rest = array
let head = rest.popLast()!
let subpermutations = permute(rest)
var result: [[T]] = []
for permutation in subpermutations {
for i in 0 ..< array.count {
var edited = permutation
edited.insert(head, at: i)
result.append(edited)
}
}
return result
}
func testSortingContainers() {
let a = PlayerRecordSortable(name: "A", victories: 3, tiebreakerPoints: 0)
let b = PlayerRecordSortable(name: "B", victories: 1, tiebreakerPoints: 10)
let c = PlayerRecordSortable(name: "C", victories: 1, tiebreakerPoints: 10)
let d = PlayerRecordSortable(name: "D", victories: 1, tiebreakerPoints: 15)
func check(_ result: [Any]) {
let actualResult = result as! [PlayerRecordSortable]
XCTAssertEqual(actualResult[0].name, "A")
XCTAssertEqual(actualResult[1].name, "D")
if actualResult[2].name == "B" {
XCTAssertEqual(actualResult[2].name, "B")
XCTAssertEqual(actualResult[3].name, "C")
} else {
XCTAssertEqual(actualResult[2].name, "C")
XCTAssertEqual(actualResult[3].name, "B")
}
}
let descriptors = [
NSSortDescriptor(keyPath: \PlayerRecordSortable.victories, ascending: false),
NSSortDescriptor(keyPath: \PlayerRecordSortable.tiebreakerPoints, ascending: false),
]
let permutations = permute([a, b, c, d])
for permutation in permutations {
check(NSArray(array: permutation).sortedArray(using: descriptors))
let mutable = NSMutableArray(array: permutation)
mutable.sort(using: descriptors)
check(mutable as! [PlayerRecordSortable])
let set = NSSet(array: permutation)
check(set.sortedArray(using: descriptors))
let orderedSet = NSOrderedSet(array: permutation)
check(orderedSet.sortedArray(using: descriptors))
let mutableOrderedSet = orderedSet.mutableCopy() as! NSMutableOrderedSet
mutableOrderedSet.sort(using: descriptors)
check(mutableOrderedSet.array)
}
}
static var allTests: [(String, (TestNSSortDescriptor) -> () throws -> Void)] {
return [
("testComparable", testComparable),
("testBuiltinComparableObject", testBuiltinComparableObject),
("testBuiltinComparableBridgeable", testBuiltinComparableBridgeable),
("testComparatorSorting", testComparatorSorting),
("testSortingContainers", testSortingContainers),
]
}
}
#endif
| apache-2.0 | 14958b8e2726b799d298e17277c7f6c1 | 46.075949 | 265 | 0.641481 | 4.539056 | false | true | false | false |
Acidburn0zzz/firefox-ios | Client/Frontend/AuthenticationManager/AuthenticationSettingsViewController.swift | 1 | 13726 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import SwiftKeychainWrapper
import LocalAuthentication
private let logger = Logger.browserLogger
private func presentNavAsFormSheet(_ presented: UINavigationController, presenter: UINavigationController?, settings: AuthenticationSettingsViewController?) {
presented.modalPresentationStyle = .formSheet
presenter?.present(presented, animated: true) {
if let selectedRow = settings?.tableView.indexPathForSelectedRow {
settings?.tableView.deselectRow(at: selectedRow, animated: false)
}
}
}
class TurnPasscodeOnSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
override var accessibilityIdentifier: String? {
return "TurnOnPasscode"
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.settings = settings as? AuthenticationSettingsViewController
super.init(title: NSAttributedString.tableRowTitle(.AuthenticationTurnOnPasscode, enabled: true),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: SetupPasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class TurnPasscodeOffSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
override var accessibilityIdentifier: String? {
return "TurnOffPasscode"
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil) {
self.settings = settings as? AuthenticationSettingsViewController
super.init(title: NSAttributedString.tableRowTitle(.AuthenticationTurnOffPasscode, enabled: true),
delegate: delegate)
}
override func onClick(_ navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: RemovePasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class ChangePasscodeSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
override var accessibilityIdentifier: String? {
return "ChangePasscode"
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool) {
self.settings = settings as? AuthenticationSettingsViewController
let attributedTitle = NSAttributedString.tableRowTitle(.AuthenticationChangePasscode, enabled: enabled)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
override func onClick(_ navigationController: UINavigationController?) {
presentNavAsFormSheet(UINavigationController(rootViewController: ChangePasscodeViewController()),
presenter: navigationController,
settings: settings)
}
}
class RequirePasscodeSetting: Setting {
weak var settings: AuthenticationSettingsViewController?
fileprivate weak var navigationController: UINavigationController?
override var accessibilityIdentifier: String? {
return "PasscodeInterval"
}
override var accessoryType: UITableViewCell.AccessoryType { return .disclosureIndicator }
override var style: UITableViewCell.CellStyle { return .value1 }
override var status: NSAttributedString {
// Only show the interval if we are enabled and have an interval set.
let authenticationInterval = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
if let interval = authenticationInterval?.requiredPasscodeInterval, enabled {
return NSAttributedString.tableRowTitle(interval.settingTitle, enabled: false)
}
return NSAttributedString(string: "")
}
init(settings: SettingsTableViewController, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self.navigationController = settings.navigationController
self.settings = settings as? AuthenticationSettingsViewController
let title: String = .AuthenticationRequirePasscode
let attributedTitle = NSAttributedString.tableRowTitle(title, enabled: enabled ?? true)
super.init(title: attributedTitle,
delegate: delegate,
enabled: enabled)
}
func deselectRow () {
if let selectedRow = self.settings?.tableView.indexPathForSelectedRow {
self.settings?.tableView.deselectRow(at: selectedRow, animated: true)
}
}
override func onClick(_: UINavigationController?) {
deselectRow()
guard let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() else {
navigateToRequireInterval()
return
}
if authInfo.requiresValidation() {
AppAuthenticator.presentAuthenticationUsingInfo(authInfo, touchIDReason: .AuthenticationRequirePasscodeTouchReason, success: {
self.navigateToRequireInterval()
}, cancel: nil, fallback: {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isOk in
guard isOk else { return }
self.navigationController?.dismiss(animated: true) {
self.navigateToRequireInterval()
}
}
})
} else {
self.navigateToRequireInterval()
}
}
fileprivate func navigateToRequireInterval() {
navigationController?.pushViewController(RequirePasscodeIntervalViewController(), animated: true)
}
}
class TouchIDSetting: Setting {
fileprivate let authInfo: AuthenticationKeychainInfo?
fileprivate weak var navigationController: UINavigationController?
fileprivate weak var switchControl: UISwitch?
fileprivate var touchIDSuccess: (() -> Void)?
fileprivate var touchIDFallback: (() -> Void)?
init(
title: NSAttributedString?,
navigationController: UINavigationController? = nil,
delegate: SettingsDelegate? = nil,
enabled: Bool? = nil,
touchIDSuccess: (() -> Void)? = nil,
touchIDFallback: (() -> Void)? = nil) {
self.touchIDSuccess = touchIDSuccess
self.touchIDFallback = touchIDFallback
self.navigationController = navigationController
self.authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo()
super.init(title: title, delegate: delegate, enabled: enabled)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.selectionStyle = .none
// In order for us to recognize a tap gesture without toggling the switch,
// the switch is wrapped in a UIView which has a tap gesture recognizer. This way
// we can disable interaction of the switch and still handle tap events.
let control = UISwitchThemed()
control.onTintColor = UIColor.theme.tableView.controlTint
control.isOn = authInfo?.useTouchID ?? false
control.isUserInteractionEnabled = false
switchControl = control
let accessoryContainer = UIView(frame: control.frame)
accessoryContainer.addSubview(control)
let gesture = UITapGestureRecognizer(target: self, action: #selector(switchTapped))
accessoryContainer.addGestureRecognizer(gesture)
cell.accessoryView = accessoryContainer
}
@objc fileprivate func switchTapped() {
guard let authInfo = authInfo else {
logger.error("Authentication info should always be present when modifying Touch ID preference.")
return
}
if authInfo.useTouchID {
AppAuthenticator.presentAuthenticationUsingInfo(
authInfo,
touchIDReason: .AuthenticationDisableTouchReason,
success: self.touchIDSuccess,
cancel: nil,
fallback: self.touchIDFallback
)
} else {
toggleTouchID(true)
}
}
func toggleTouchID(_ enabled: Bool) {
authInfo?.useTouchID = enabled
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo)
switchControl?.setOn(enabled, animated: true)
}
}
class AuthenticationSettingsViewController: SettingsTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
updateTitleForTouchIDState()
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidRemove, object: nil)
notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: .PasscodeDidCreate, object: nil)
notificationCenter.addObserver(self, selector: #selector(refreshSettings), name: UIApplication.didBecomeActiveNotification, object: nil)
tableView.accessibilityIdentifier = "AuthenticationManager.settingsTableView"
}
override func generateSettings() -> [SettingSection] {
if let _ = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() {
return passcodeEnabledSettings()
} else {
return passcodeDisabledSettings()
}
}
fileprivate func updateTitleForTouchIDState() {
let localAuthContext = LAContext()
if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
let title: String
if localAuthContext.biometryType == .faceID {
title = .AuthenticationFaceIDPasscodeSetting
} else {
title = .AuthenticationTouchIDPasscodeSetting
}
navigationItem.title = title
} else {
navigationItem.title = .AuthenticationPasscode
}
}
fileprivate func passcodeEnabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: .AuthenticationPasscode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOffSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: true)
])
var requirePasscodeSectionChildren: [Setting] = [RequirePasscodeSetting(settings: self)]
let localAuthContext = LAContext()
if localAuthContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
let title: String
if localAuthContext.biometryType == .faceID {
title = Strings.UseFaceID
} else {
title = Strings.UseTouchID
}
requirePasscodeSectionChildren.append(
TouchIDSetting(
title: NSAttributedString.tableRowTitle(title, enabled: true),
navigationController: self.navigationController,
delegate: nil,
enabled: true,
touchIDSuccess: { [unowned self] in
self.touchIDAuthenticationSucceeded()
},
touchIDFallback: { [unowned self] in
self.fallbackOnTouchIDFailure()
}
)
)
}
let requirePasscodeSection = SettingSection(title: nil, children: requirePasscodeSectionChildren)
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
fileprivate func passcodeDisabledSettings() -> [SettingSection] {
var settings = [SettingSection]()
let passcodeSectionTitle = NSAttributedString(string: .AuthenticationPasscode)
let passcodeSection = SettingSection(title: passcodeSectionTitle, children: [
TurnPasscodeOnSetting(settings: self),
ChangePasscodeSetting(settings: self, delegate: nil, enabled: false)
])
let requirePasscodeSection = SettingSection(title: nil, children: [
RequirePasscodeSetting(settings: self, delegate: nil, enabled: false),
])
settings += [
passcodeSection,
requirePasscodeSection,
]
return settings
}
}
extension AuthenticationSettingsViewController {
@objc func refreshSettings(_ notification: Notification) {
updateTitleForTouchIDState()
settings = generateSettings()
tableView.reloadData()
}
}
extension AuthenticationSettingsViewController {
fileprivate func getTouchIDSetting() -> TouchIDSetting? {
guard settings.count >= 2 && settings[1].count >= 2 else {
return nil
}
return settings[1][1] as? TouchIDSetting
}
fileprivate func touchIDAuthenticationSucceeded() {
getTouchIDSetting()?.toggleTouchID(false)
}
func fallbackOnTouchIDFailure() {
AppAuthenticator.presentPasscodeAuthentication(self.navigationController).uponQueue(.main) { isPasscodeOk in
guard isPasscodeOk else { return }
self.getTouchIDSetting()?.toggleTouchID(false)
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
}
| mpl-2.0 | 9afd4a99b40492988fb3536eccaa42a0 | 38.105413 | 158 | 0.670042 | 6.133155 | false | false | false | false |
IvanRublev/VRMaskColoredButton | Example/VRMaskColoredButton_ExampleSwift/Jukebox.swift | 1 | 6180 | //
// Jukebox.swift
// VRMaskColoredButton
//
// Created by Ivan Rublev on 1/31/16.
// Copyright © 2016 Ivan Rublev http://ivanrublev.me. All rights reserved.
//
import Foundation
import AVFoundation
protocol JukeboxDelegate: class {
func jukeboxPlayWasStarted()
func jukeboxPlayWasPaused()
func jukeboxSongWasChanged(currentSong: UInt)
func jukeboxVolume(muted: Bool)
}
class Jukebox: NSObject, AVAudioPlayerDelegate {
// MARK: Songs
struct Song {
var title: String
var fileName: String
init(_ newFileName: String, _ newTitle: String) {
fileName = newFileName
title = newTitle
}
}
private let songs = [
Song("Beat to the Bop", "Beat to the Bop"),
Song("bop - hook", "Hook Bop"),
Song("Jiga Bop 7", "Jiga Bop")
]
let songTitles: [String]
override init() {
var titles = [String]()
for aSong in songs {
titles.append(aSong.title)
}
songTitles = titles
super.init()
}
// MARK: State
private var _play = false {
didSet {
if _play == oldValue {
return
}
if _play == true { // start playing
self.playCurrentSong()
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.jukeboxPlayWasStarted()
}
} else { // pause playing
self.pauseCurrentSong()
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.jukeboxPlayWasPaused()
}
}
}
}
private var _currentSong: UInt = 0 {
didSet {
_currentSong = UInt(max(0, min(Int(_currentSong), self.songs.count-1)))
if _currentSong == oldValue {
return
} // change song
pauseCurrentSong()
if _play {
playCurrentSong()
}
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.jukeboxSongWasChanged(self._currentSong)
}
}
}
private var _muted = false
private let playQueue = dispatch_queue_create("play", DISPATCH_QUEUE_CONCURRENT)
// MARK: External interface
weak var delegate: JukeboxDelegate? {
didSet {
dispatch_sync(playQueue) {
let isPlaying = self._play
let songNumber = self._currentSong
let isMuted = self._muted
dispatch_async(dispatch_get_main_queue()) {
if isPlaying {
self.delegate?.jukeboxPlayWasStarted()
} else {
self.delegate?.jukeboxPlayWasPaused()
}
self.delegate?.jukeboxSongWasChanged(songNumber)
self.delegate?.jukeboxVolume(isMuted)
}
}
}
}
var play: Bool {
set {
dispatch_barrier_sync(playQueue) {
self._play = newValue
}
}
get {
var isPlaying = false
dispatch_sync(playQueue) {
isPlaying = self._play
}
return isPlaying
}
}
var currentSong: UInt {
var songNumber: UInt!
dispatch_sync(playQueue) {
songNumber = self._currentSong
}
return songNumber
}
func nextSong() {
dispatch_barrier_sync(playQueue) {
self._currentSong += 1
}
}
func prevSong() {
dispatch_barrier_sync(playQueue) {
self._currentSong -= 1
}
}
var muted: Bool {
set {
dispatch_barrier_sync(playQueue) {
if newValue == self._muted {
return
}
self._muted = newValue
self.setPlayerVolume()
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.jukeboxVolume(newValue)
}
}
}
get {
var isMuted = false
dispatch_sync(playQueue) {
isMuted = self._muted
}
return isMuted
}
}
// MARK: Control AVAudioPlayer
private var player: AVAudioPlayer!
private func playCurrentSong() {
let fileName = songs[Int(_currentSong)].fileName
let currentSongURL = NSBundle.mainBundle().URLForResource(fileName, withExtension: "m4a")!
if let thePlayer = player {
if thePlayer.url! == currentSongURL {
thePlayer.play()
return
} else { // need to make new player for new song
thePlayer.stop()
}
} // no player, make new one
let newPlayer = try! AVAudioPlayer(contentsOfURL: currentSongURL)
newPlayer.delegate = self
newPlayer.numberOfLoops = 1
try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
player = newPlayer
setPlayerVolume()
player.play()
}
private func pauseCurrentSong() {
if let thePlayer = player {
thePlayer.pause()
}
}
private func setPlayerVolume() {
if let thePlayer = player {
thePlayer.volume = (_muted == true ? 0.0 : 1.0)
}
}
// MARK: AVAudioPlayer delegate
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
dispatch_barrier_sync(playQueue) {
if self._currentSong == UInt(self.songs.count-1) { // last song, stop and rewind
self._play = false
self._currentSong = 0
self.player = nil
} else { // play next song
self._currentSong += 1
}
}
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer, error: NSError?) throws {
throw error!
}
} | mit | 8868fa73e429af6670bcc61fc985d470 | 27.611111 | 98 | 0.507202 | 5.077239 | false | false | false | false |
eramdam/WallbaseDirectDownloader | safari/Wallhaven Direct Downloader/Wallhaven Direct Downloader Extension/SafariWebExtensionHandler.swift | 1 | 787 | //
// SafariWebExtensionHandler.swift
// Wallhaven Direct Downloader Extension
//
// Created by Damien Erambert on 2/28/21.
//
import SafariServices
import os.log
let SFExtensionMessageKey = "message"
class SafariWebExtensionHandler: NSObject, NSExtensionRequestHandling {
func beginRequest(with context: NSExtensionContext) {
let item = context.inputItems[0] as! NSExtensionItem
let message = item.userInfo?[SFExtensionMessageKey]
os_log(.default, "Received message from browser.runtime.sendNativeMessage: %@", message as! CVarArg)
let response = NSExtensionItem()
response.userInfo = [ SFExtensionMessageKey: [ "Response to": message ] ]
context.completeRequest(returningItems: [response], completionHandler: nil)
}
}
| gpl-2.0 | 8ee626a2b8e8d7f1fede124ebe737881 | 29.269231 | 108 | 0.726811 | 4.348066 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze-tvOS/ViewModels/VideoPlayerViewModel.swift | 1 | 6825 | //
// VideoPlayerViewModel.swift
// Harekaze
//
// Created by Yasuhiro Hatta on 2016/10/01.
// Copyright © 2016年 Yuki MIZUNO. All rights reserved.
//
import UIKit
//import DynamicTVVLCKit
import RxSwift
import RxCocoa
struct DeinterlaceMode: RawRepresentable {
// https://wiki.videolan.org/Deinterlacing
// http://vlc.sourcearchive.com/documentation/1.1.3-1/group__libvlc__video_gc975a12c1a7c7729ad18eee50c305659.html
var rawValue: String
static let blend = DeinterlaceMode(rawValue: "blend")
static let bob = DeinterlaceMode(rawValue: "bob")
static let discard = DeinterlaceMode(rawValue: "discard")
static let linear = DeinterlaceMode(rawValue: "linear")
static let mean = DeinterlaceMode(rawValue: "mean")
static let x = DeinterlaceMode(rawValue: "x")
static let yadif = DeinterlaceMode(rawValue: "yadif")
static let yadif2x = DeinterlaceMode(rawValue: "yadif2x")
}
extension VLCMediaPlayer {
func setDeinterlaceFilter(mode: DeinterlaceMode) {
setDeinterlaceFilter(mode.rawValue)
}
}
extension VLCTime {
var valueInSeconds: Int {
return value.intValue / 1000
}
}
private class MediaPlayerDelegate: NSObject, VLCMediaPlayerDelegate {
private let program: Program
var initialTime: Int? = nil
init(program: Program) {
self.program = program
}
// MARK: ----- state -------------------------------------------------------
let state = Variable<VLCMediaPlayerState>(.stopped)
/*private*/ func mediaPlayerStateChanged(_ aNotification: Notification!) {
guard let mediaPlayer = aNotification.object as? VLCMediaPlayer else {
return
}
state.value = mediaPlayer.state
// FIXME: DEBUG PRINT
switch mediaPlayer.state {
case .stopped: //< Player has stopped
print("stopped")
case .opening: //< Stream is opening
print("opening")
case .buffering: //< Stream is buffering
//print("buffering")
break
case .ended: //< Stream has ended
print("ended")
case .error: //< Player has generated an error
print("error")
case .playing: //< Stream is playing
print("playing")
case .paused: //< Stream is paused
print("paused")
}
}
// MARK: ----- time --------------------------------------------------------
let time = Variable<Int>(0)
let position = Variable<Float>(0)
/*private*/ func mediaPlayerTimeChanged(_ aNotification: Notification!) {
guard let mediaPlayer = aNotification.object as? VLCMediaPlayer else {
return
}
if let initialTime = initialTime {
let currentTime = initialTime + mediaPlayer.time.valueInSeconds
time.value = currentTime
position.value = Float(currentTime) / Float(program.duration)
} else {
time.value = mediaPlayer.time.valueInSeconds
position.value = mediaPlayer.position
}
// FIXME: DEBUG PRINT
//print("position: \(mediaPlayer.position)")
}
}
class VideoPlayerViewModel {
private let program: Program
private let mediaPlayer: VLCMediaPlayer
private let mediaPlayerDelegate: MediaPlayerDelegate
private let disposeBag = DisposeBag()
init(program: Program) {
self.program = program
self.mediaPlayer = VLCMediaPlayer()
self.mediaPlayerDelegate = MediaPlayerDelegate(program: program)
var lastTime = ChinachuAPI.lastTime(id: program.id)
if lastTime != nil && lastTime! > Int(program.duration) {
lastTime = nil
}
// FIXME: DEBUG PRINT
print("time load: \(lastTime), duration: \(program.duration)")
setupMediaPlayer(initialTime: lastTime)
mediaPlayerDelegate.time.asObservable()
.throttle(15, latest: true, scheduler: MainScheduler.instance)
.subscribe(
onNext: { [unowned program] (time) in
if time > 0 {
ChinachuAPI.setLastTime(id: program.id, time: time)
// FIXME: DEBUG PRINT
print("time saved: \(time)")
}
}
)
.addDisposableTo(disposeBag)
mediaPlayerDelegate.state.asObservable()
.subscribe(
onNext: { [unowned program] (state) in
if state == .ended {
ChinachuAPI.setLastTime(id: program.id, time: nil)
}
}
)
.addDisposableTo(disposeBag)
}
deinit {
mediaPlayer.stop()
mediaPlayer.drawable = nil
}
// MARK: - Media Player Setup
private func setupMediaPlayer(initialTime time: Int?) {
mediaPlayerDelegate.initialTime = time
let request = ChinachuAPI.StreamingMediaRequest(id: program.id, time: time)
let urlRequest = try! request.buildURLRequest()
var compnents = URLComponents(url: urlRequest.url!, resolvingAgainstBaseURL: false)!
compnents.user = ChinachuAPI.username
compnents.password = ChinachuAPI.password
let media = VLCMedia(url: compnents.url!)
media.addOptions(["network-caching": 3333])
mediaPlayer.media = media
mediaPlayer.setDeinterlaceFilter(mode: .linear)
mediaPlayer.delegate = mediaPlayerDelegate
}
func set(drawable: UIView) {
mediaPlayer.drawable = drawable
}
// MARK: - Media Player Event
var positionDriver: Driver<Float> {
return mediaPlayerDelegate.position.asDriver()
}
var stateDriver: Driver<VLCMediaPlayerState> {
return mediaPlayerDelegate.state.asDriver()
}
// MARK: - Media Player Control
func play() {
mediaPlayer.play()
}
func pause() {
mediaPlayer.pause()
}
func toggle() {
if mediaPlayer.isPlaying {
pause()
} else if mediaPlayer.state == .paused {
play()
}
// switch mediaPlayer.state {
// case .opening, .buffering, .playing:
// pause()
// case .paused:
// play()
// case .stopped, .ended, .error:
// break
// }
}
func setProgress(_ progres: Float, autoPlay: Bool) {
let newTime = Int(Float(program.duration) * progres)
mediaPlayer.stop()
setupMediaPlayer(initialTime: newTime)
if autoPlay {
play()
}
}
}
| bsd-3-clause | 6757b32c87c6d96e86d5f5cbdd844642 | 28.153846 | 117 | 0.572559 | 4.744089 | false | false | false | false |
marcorcb/SwiftSimplePhotoPicker | SwiftSimplePhotoPickerExample/SwiftSimplePhotoPickerExample/SwiftSimplePhotoPicker.swift | 1 | 5299 | //
// SwiftSimplePhotoPicker.swift
// SwiftSimplePhotoPickerExample
//
// Created by Marco Braga on 11/08/17.
// Copyright © 2017 Marco Braga. All rights reserved.
//
import UIKit
class SwiftSimpleImagePickerController: UIImagePickerController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
class SwiftSimplePhotoPicker: NSObject {
static let shared = SwiftSimplePhotoPicker()
var imagePickerController: SwiftSimpleImagePickerController
var completionBlock: ((UIImage) -> Void)?
override init() {
self.imagePickerController = SwiftSimpleImagePickerController()
super.init()
self.imagePickerController.navigationBar.isTranslucent = false
self.imagePickerController.delegate = self
self.imagePickerController.allowsEditing = true
}
func showPicker(in viewController: UIViewController, completion: @escaping (UIImage) -> Void) {
self.completionBlock = completion
let actionSheet = UIAlertController(title: "Choose an option", message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Choose Photo", style: .default, handler: { (_) in
self.imagePickerController.sourceType = .photoLibrary
viewController.present(self.imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Take Photo", style: .default, handler: { (_) in
self.imagePickerController.sourceType = .camera
self.imagePickerController.cameraDevice = .front
self.imagePickerController.cameraFlashMode = .off
viewController.present(self.imagePickerController, animated: true, completion: nil)
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
viewController.present(actionSheet, animated: true, completion: nil)
}
func fixOrientation(for image: UIImage) -> UIImage {
if image.imageOrientation == .up {
return image
}
var transform: CGAffineTransform = .identity
switch image.imageOrientation {
case .down, .downMirrored:
transform = CGAffineTransform(translationX: image.size.width, y: image.size.height)
transform = CGAffineTransform(rotationAngle: .pi)
case .left, .leftMirrored:
transform = CGAffineTransform(translationX: image.size.width, y: 0.0)
transform = CGAffineTransform(rotationAngle: .pi / 2)
case .right, .rightMirrored:
transform = CGAffineTransform(translationX: 0, y: image.size.height)
transform = CGAffineTransform(rotationAngle: -(.pi / 2))
case .up, .upMirrored:
break
@unknown default:
break
}
switch image.imageOrientation {
case .upMirrored, .downMirrored:
transform = CGAffineTransform(translationX: image.size.width, y: 0.0)
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
case .leftMirrored, .rightMirrored:
transform = CGAffineTransform(translationX: image.size.height, y: 0.0)
transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
case .up, .down, .left, .right:
break
@unknown default:
break
}
let context: CGContext = CGContext(data: nil, width: Int(image.size.width),
height: Int(image.size.height),
bitsPerComponent: image.cgImage!.bitsPerComponent, bytesPerRow: 0,
space: image.cgImage!.colorSpace!,
bitmapInfo: image.cgImage!.bitmapInfo.rawValue)!
context.concatenate(transform)
switch image.imageOrientation {
case .left, .leftMirrored, .right, .rightMirrored:
context.draw(image.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: image.size.height, height: image.size.width))
default:
context.draw(image.cgImage!, in: CGRect(x: 0.0, y: 0.0, width: image.size.width, height: image.size.height))
}
let cgImage: CGImage = context.makeImage()!
let fixedImage: UIImage = UIImage(cgImage: cgImage)
return fixedImage
}
}
extension UIAlertController {
override open var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
extension SwiftSimplePhotoPicker: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
picker.dismiss(animated: true, completion: nil)
let editedImage: UIImage = fixOrientation(for: info[UIImagePickerController.InfoKey.editedImage]
as? UIImage ?? UIImage())
if let completionBlock = self.completionBlock {
DispatchQueue.main.async {
completionBlock(editedImage)
}
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
}
| mit | 2d1241cd58bdb4c4c6b7b0c90e502fe4 | 40.390625 | 120 | 0.64798 | 5.199215 | false | false | false | false |
mgallagher/sets-and-reps | SetsAndReps/WeightChangerViewController.swift | 1 | 2523 | //
// WeightChangerViewController.swift
// SetsAndReps
//
// Created by Michael Gallagher on 4/19/15.
// Copyright (c) 2015 Michael Gallagher. All rights reserved.
//
import UIKit
protocol WeightUpdatedDelegate {
func userDidUpdateWeight(updatedCell:NSIndexPath, weightAsString:String)
}
class WeightChangerViewController: UIViewController {
var delegate : WeightUpdatedDelegate? = nil
var weightAsString : String? = nil
let weightInterval = 5
var cellIndexToUpdate : NSIndexPath? = nil
@IBOutlet weak var weightTextField : UITextField! = UITextField()
override func viewDidLoad() {
super.viewDidLoad()
if weightAsString != nil {
setWeightText(weightAsString!.toInt()!)
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func incrementWeight(sender: AnyObject) {
let up = weightTextField.text.toInt()! + weightInterval
setWeightText(up)
}
@IBAction func decrementWeight(sender: AnyObject) {
let down = weightTextField.text.toInt()! - weightInterval
setWeightText(down)
}
@IBAction func setWeightAndDismiss(sender: UIButton) {
view.endEditing(true)
if (delegate != nil) {
if (weightTextField.text.isNumeric)
{
delegate!.userDidUpdateWeight(cellIndexToUpdate!, weightAsString: weightTextField.text!)
}
}
// self.dismissViewControllerAnimated(true, completion: nil) // Storyboard unwind isn't working
// Unwinding this vc from storyboard
}
@IBAction func didTapOutside(sender: AnyObject) {
view.endEditing(true)
}
func setWeightText(weightAsInt: Int) {
weightTextField.text = String(weightAsInt)
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// let vc = segue.destinationViewController as! ActiveWorkoutTableViewController
// vc.cellIndexToUpdate = self.cellIndexToUpdate
// let cell = vc.tableView.cellForRowAtIndexPath(cellIndexToUpdate) as! ActiveWorkoutTableViewCell
// cell.weightLiftedLabelButton.setTitle(String(weightTextField.text.toInt()!), forState: .Normal)
// println("setting: \(String(weightTextField.text.toInt()!))")
}
}
| mit | b867996cefbbf88b31fd1ea912aa1694 | 31.346154 | 105 | 0.667063 | 4.814885 | false | false | false | false |
saeta/penguin | Sources/PenguinPipeline/Pipeline/TransformPipelineIterator.swift | 1 | 16022 | // Copyright 2020 Penguin Authors
//
// 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
/// TransformPipelineIterator is used to run arbitrary user-supplied transformations in a pipelined fashion.
///
/// The transform function should return nil to skip the element.
// TODO: Add threading to pipeline the transformation!
// TODO: Add early stopping control flow.
public struct TransformPipelineIterator<Underlying: PipelineIteratorProtocol, Output>:
PipelineIteratorProtocol
{
public typealias Element = Output
public typealias TransformFunction = (Underlying.Element) throws -> Output?
public init(
_ underlying: Underlying, name: String?, threadCount: Int, bufferSize: Int,
transform: @escaping TransformFunction
) {
self.impl = Impl(
underlying, name: name, threadCount: threadCount, bufferSize: bufferSize, transform: transform
)
}
public mutating func next() throws -> Output? {
while let output = impl.buffer.consume() {
switch output {
case let .success(output):
if output == nil {
continue // Get another element, as this one should be filtered out.
}
return output
case let .failure(err):
throw err
}
}
return nil // Iteration is complete.
}
/// The implementation of the TransformPipelineIterator.
///
/// Overall design: _n_ threads race to call `.next()` from the `underlying` iterator, and
/// receive a token. They then each in parallel execute the transform function, and set the output in the
/// corresponding element in the output `buffer`.
///
/// In this design, there are 3 thread categories:
/// - Initializer thread: this is the thread that initalizes the TransformPipelineIterator. Because this is
/// usually the user's main thread, we should do the minimum amount of work before returning, as
/// this is usually on the "critical path". (This thread is not present in "steady-state", and can be the
/// same kernel/physical thread as the consumer thread. We consider it separately as the
/// performance considerations during initialization are distinct.)
/// - Consumer thread: this is the thread that calls `TransformPipelineIterator.next`. The
/// architecture of PiplineIterator's demands that minimal amounts of work be done here.
/// - Worker threads. These threads are internal to the `TransformPipelineIterator` and are
/// used to run the user-supplied transform function.
///
/// This implementation does a relatively small amount of work during initialization. This is important as
/// this is on the critical path to getting the pipeline setup. Here, we copy the configuration, allocate the
/// output buffer, and start the worker threads. The worker threads then immediately start attempting to
/// pull elements from the upstream iterator as quickly as possible in order to fill up the pipeline as
/// quickly as possible.
///
/// When worker threads request new elements from the upstream iterator, they do so while holding the
/// lock `condition`.
///
/// Tuning tips:
/// - Tune threadCount for your machine, target throughput, and your pipeline. Ensure there
/// are approximately equal worker threads (threadCount) as physical cores on your machine,
/// aggregated across all TransformPipelineIterator's.
/// - Increase the ratio bufferSize:threadCount if the transformation function can be highly variable.
/// - Combine multiple `TransformFunction`s into fewer, if possible.
///
/// Invariants:
/// - Worker threads only ever block trying to get an element from the underlying iterator. Every other operation
/// must not block the thread.
/// - `tail` chases `head` around the circular buffer `buffer`.
// TODO: Optimize the case where the filter condition is highly selective.
// TODO: Dynamically size the output buffer capacity and thread count, espceially if
// there is highly variable `TransformFunction` latency.
// TODO: Add tracing annotations.
// TODO: Allow users to customize worker thread NUMA scheduling policies / etc.
final class Impl {
/// Element represents the output of a transformation. If it is .success(nil) it should
/// be filtered out of the output.
// TODO: Mark as a move-only type when available.
typealias Element = Result<Output?, Error>
/// ADT to represent tokens into the buffer.
struct Token {
let index: Int
}
// TODO: optimize away the extra optional overhead of Element.
struct Entry {
init() {
semaphore = DispatchSemaphore(value: 0)
}
// Initialized to 0, incremented to 1 when entry is set,
// and reset to zero when consumed.
var semaphore: DispatchSemaphore
// The entry itself. Semaphore should never be notified when entry is nil.
var entry: Element?
// Note: do not rely on this for synchronization purposes!
var isEmpty: Bool { entry == nil }
}
/// Associated information related to the TransformPipelineIterator.
///
/// Note: we stuff all these things here, instead of inside Impl in order to ensure the WorkerThreads
/// do not hold a reference to Impl. This is because in order to ensure a safe shut-down, the
/// WorkerThreads must not have a reference to Impl right when Impl.deinit is called.
///
/// TODO: refactor all of this once Swift has move-only structs!
struct BufferHeader {
// Head points to the next element to be allocated to be executed
// on a worker thread.
//
// Read & written by worker threads; must hold `condition` lock.
var head: Int = 0
// Tail points to the next element to be consumed by the consumer.
// tail is only updated only by the consumer thread. It can be
// safely read by the consumer thread without the lock, but must
// be always written to while holding the `condition` lock, and
// all worker thread reads must also hold the `condition` lock.
var tail: Int = 0
// Synchronization primitive.
var condition = NSCondition()
// The upstream iterator this transform pulls elements to transform from.
// It is set to nil when execution should be cancelled or when it reaches the
// end of the sequence in order to eagerly free up resources.
//
// It should only be manipulated while holding the `condition` lock.
var underlying: Underlying?
// The name of the operation.
let name: String?
}
class Buffer: ManagedBuffer<BufferHeader, Entry> {
func initialize() {
withUnsafeMutablePointerToElements { base in
for i in 0..<capacity {
let ptr = base.advanced(by: i)
ptr.initialize(to: Entry())
}
}
}
deinit {
withUnsafeMutablePointerToElements { base in
_ = base.deinitialize(count: capacity)
}
}
// MARK: -Worker methods
/// Gets the next element to work on. If nil, worker thread should exit.
///
/// Called from worker threads.
func next(_ threadName: String?) -> (Result<Underlying.Element, Error>, Token)? {
header.condition.lock()
defer { header.condition.unlock() }
while header.underlying != nil && !hasRoomForNext() {
header.condition.wait()
}
if header.underlying == nil {
return nil
}
let token = Token(index: header.head)
header.head = (header.head + 1) % capacity
let result = Result { () throws -> Underlying.Element? in
assert(header.underlying != nil, "header.underlying was nil.")
return try header.underlying!.next() // Assumed fast.
}
switch result {
case let .success(output):
if let output = output {
return (.success(output), token)
}
// End of upstream iterator.
// Notify the token index just in case the consumer is already waiting.
complete(token: token, .success(nil)) // Pretend it should be filtered.
header.underlying = nil
header.condition.broadcast()
return nil
case let .failure(err):
return (.failure(err), token)
}
}
private func hasRoomForNext() -> Bool {
(header.head + 1) % capacity != header.tail
}
/// Completes the processing of an element, and sets it ready
///
/// Called from worker threads.
func complete(token: Token, _ elem: Element) {
withUnsafeMutablePointerToElements { base in
let ptr = base.advanced(by: token.index)
assert(
ptr.pointee.isEmpty,
"Element at \(token.index) was not empty (Operation: \(header.name ?? "")).")
ptr.pointee.entry = elem
ptr.pointee.semaphore.signal()
}
}
// MARK: -Consumer methods
/// Retrieves the next element the TransformPipelineIterator should produce.
///
/// If it returns nil, the upstream iteration has completed.
///
/// Called from consumer thread.
// TODO: Optimize the case where there are sequences of filtered out elements (i.e.
// where we return `Optional(.success(nil))`.)
func consume() -> Element? {
header.condition.lock()
let endOfIteration = header.underlying == nil && header.head == header.tail
let tail = header.tail
header.condition.unlock()
if endOfIteration {
return nil
}
let output = waitFor(tail)
header.condition.lock()
header.tail = (header.tail + 1) % capacity // Advance tail.
header.condition.signal() // Wake up a waiting worker thread.
header.condition.unlock()
return output
}
func waitFor(_ index: Int) -> Element {
withUnsafeMutablePointerToElements { base in
let ptr = base.advanced(by: index)
ptr.pointee.semaphore.wait()
guard let output = ptr.pointee.entry else {
fatalError("Output at \(index) was nil.")
}
ptr.pointee.entry = nil
return output
}
}
}
final class WorkerThread: PipelineWorkerThread {
init(name: String, transform: @escaping TransformFunction) {
self.transform = transform
super.init(name: name)
}
override func body() {
// Infinitely loop.
while let (res, token) = buffer.next(name) {
switch res {
case let .success(input):
let output = Result { try transform(input) }
buffer.complete(token: token, output)
case let .failure(err):
buffer.complete(token: token, .failure(err))
}
}
buffer = nil // Set to nil to avoid any nonsense.
}
let transform: TransformFunction
unowned var buffer: Buffer!
}
init(
_ underlying: Underlying, name: String?, threadCount: Int, bufferSize: Int,
transform: @escaping TransformFunction
) {
self.buffer =
Buffer.create(minimumCapacity: bufferSize) { _ in
BufferHeader(underlying: underlying, name: name)
} as! Buffer
self.transform = transform
self.name = name
self.buffer.initialize()
self.threads = [WorkerThread]()
self.threads.reserveCapacity(threadCount)
// Must be fully initialized before starting threads.
for i in 0..<threadCount {
let thread = WorkerThread(
name: "\(name ?? "")_worker_thread_\(i)",
transform: transform)
thread.buffer = buffer
thread.start()
self.threads.append(thread)
}
}
deinit {
buffer.header.condition.lock()
buffer.header.underlying = nil // Signal to workers that they should terminate.
buffer.header.condition.broadcast()
buffer.header.condition.unlock()
// Cancel and join with all the worker threads to ensure they have all shut down successfully.
self.threads.forEach {
$0.waitUntilStarted() // Guarantee that the worker thread has at least started.
$0.cancel()
}
self.threads.forEach {
$0.join()
$0.buffer = nil // Set to nil to ensure the Thread's deinit doesn't try and do anything.
}
}
// The buffer containing the transformed outputs.
let buffer: Buffer
// The transform function
let transform: TransformFunction
// The worker threads.
var threads: [WorkerThread]
let name: String?
}
var impl: Impl
}
public struct TransformPipelineSequence<Underlying: PipelineSequence, Output>: PipelineSequence {
public typealias Element = Output
public typealias TransformFunction = (Underlying.Element) throws -> Output?
public init(
_ underlying: Underlying, name: String?, threadCount: Int, bufferSize: Int,
transform: @escaping TransformFunction
) {
self.underlying = underlying
self.name = name
self.threadCount = threadCount
self.bufferSize = bufferSize
self.transform = transform
}
public func makeIterator() -> TransformPipelineIterator<Underlying.Iterator, Output> {
TransformPipelineIterator(
underlying.makeIterator(), name: name, threadCount: threadCount, bufferSize: bufferSize,
transform: transform)
}
let underlying: Underlying
let name: String?
let threadCount: Int
let bufferSize: Int
let transform: TransformFunction
}
extension PipelineSequence {
/// Transforms the iterator from returning elements of type `Element` into returning elements of type `T`.
///
/// The map function `f` is run on potentially many threads in a data-parallel manner.
public func map<T>(name: String? = nil, f: @escaping (Element) throws -> T)
-> TransformPipelineSequence<Self, T>
{
TransformPipelineSequence(self, name: name, threadCount: 5, bufferSize: 15, transform: f)
}
/// Filter removes elements where `f(elem)` returns `false`, but passes through elements that
/// return `true`.
public func filter(name: String? = nil, f: @escaping (Element) throws -> Bool)
-> TransformPipelineSequence<Self, Element>
{
TransformPipelineSequence(self, name: name, threadCount: 5, bufferSize: 15) {
if try f($0) { return $0 } else { return nil }
}
}
/// Compact map removes `nil`s, but passes through transformed elements of type `T`.
public func compactMap<T>(name: String? = nil, f: @escaping (Element) throws -> T?)
-> TransformPipelineSequence<Self, T>
{
TransformPipelineSequence(self, name: name, threadCount: 5, bufferSize: 15, transform: f)
}
}
extension PipelineIteratorProtocol {
public func map<T>(name: String? = nil, f: @escaping (Element) throws -> T)
-> TransformPipelineIterator<Self, T>
{
TransformPipelineIterator(self, name: name, threadCount: 5, bufferSize: 15, transform: f)
}
public func filter(name: String? = nil, f: @escaping (Element) throws -> Bool)
-> TransformPipelineIterator<Self, Element>
{
TransformPipelineIterator(self, name: name, threadCount: 5, bufferSize: 15) {
if try f($0) { return $0 } else { return nil }
}
}
public func compactMap<T>(name: String? = nil, f: @escaping (Element) throws -> T?)
-> TransformPipelineIterator<Self, T>
{
TransformPipelineIterator(self, name: name, threadCount: 5, bufferSize: 15, transform: f)
}
}
| apache-2.0 | 5fef56238c95a6ebc592688637df43f0 | 37.422062 | 116 | 0.657221 | 4.590831 | false | false | false | false |
nebiros/ola-k-ase | OlaKAse/Classes/Controllers/FriendsQueryTableViewController.swift | 1 | 4306 | //
// MainViewController.swift
// OlaKAse
//
// Created by Juan Felipe Alvarez Saldarriaga on 6/18/15.
// Copyright © 2015 Juan Felipe Alvarez Saldarriaga. All rights reserved.
//
import UIKit
import Parse
import ParseUI
import FBSDKShareKit
class FriendsQueryTableViewController: PFQueryTableViewController {
@IBOutlet weak var addBarButton: UIBarButtonItem!
@IBOutlet weak var loginBarButton: UIBarButtonItem!
@IBOutlet weak var inviteBarButton: UIBarButtonItem!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
func commonInit() {
parseClassName = Friend.parseClassName()
pullToRefreshEnabled = true
paginationEnabled = true
objectsPerPage = 25;
loadingViewEnabled = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupLoginBarButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated);
guard let currentUser = User.currentUser() else {
return presentLogInVC()
}
let currentInstalation = PFInstallation()
currentInstalation.setObject(currentUser, forKey: "user")
}
// MARK: - PFQueryTableViewController
override func queryForTable() -> PFQuery {
let query = PFQuery(className: parseClassName!)
if pullToRefreshEnabled {
query.cachePolicy = .NetworkOnly
}
if objects?.count == 0 {
query.cachePolicy = .CacheElseNetwork
}
return query
}
}
// MARK: - UI
extension FriendsQueryTableViewController {
func presentLogInVC() {
let loginVC = PFLogInViewController()
loginVC.delegate = self
loginVC.fields = [.Default, .Facebook]
loginVC.facebookPermissions = ["public_profile", "email", "user_friends"]
presentViewController(loginVC, animated: true, completion: nil)
}
@IBAction func addBarButtonTapped(sender: UIBarButtonItem) {
}
func setupLoginBarButtonItem() {
guard let _ = User.currentUser() else {
loginBarButton.title = NSLocalizedString("Login", comment: "")
return
}
loginBarButton.title = NSLocalizedString("Logout", comment: "")
}
@IBAction func loginBarButtonTapped(sender: UIBarButtonItem) {
guard let _ = User.currentUser() else {
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
return presentLogInVC()
}
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
User.logOutInBackground()
}
@IBAction func inviteBarButtonTapped(sender: UIBarButtonItem) {
presentFacebookAppInviteDialog()
}
}
// MARK: - FBSDKAppInviteDialogDelegate
extension FriendsQueryTableViewController: FBSDKAppInviteDialogDelegate {
func presentFacebookAppInviteDialog() {
let content = FBSDKAppInviteContent()
content.appLinkURL = NSURL(string: "https://fb.me/1601337420135347")
FBSDKAppInviteDialog.showWithContent(content, delegate: self)
}
func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didCompleteWithResults results: [NSObject : AnyObject]!) {
}
func appInviteDialog(appInviteDialog: FBSDKAppInviteDialog!, didFailWithError error: NSError!) {
}
}
// MARK: - PFLogInViewControllerDelegate
extension FriendsQueryTableViewController: PFLogInViewControllerDelegate {
func logInViewController(logInController: PFLogInViewController, didLogInUser user: PFUser) {
NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("setupLoginBarButtonItem"), userInfo: nil, repeats: false)
logInController.dismissViewControllerAnimated(true, completion: nil)
}
}
| mpl-2.0 | a1edf97364d812542bec69c5c4ec5e58 | 28.895833 | 147 | 0.660859 | 5.275735 | false | false | false | false |
Donny8028/Swift-TinyFeatures | PhotoPicker/PhotoPicker/ImagePickerSheetController/ImagePickerAction.swift | 1 | 3103 | //
// ImagePickerAction.swift
// ImagePickerSheet
//
// Created by Laurin Brandner on 24/05/15.
// Copyright (c) 2015 Laurin Brandner. All rights reserved.
//
import Foundation
public enum ImagePickerActionStyle {
case Default
case Cancel
}
public class ImagePickerAction {
public typealias Title = Int -> String
public typealias Handler = (ImagePickerAction) -> ()
public typealias SecondaryHandler = (ImagePickerAction, Int) -> ()
/// The title of the action's button.
public let title: String
/// The title of the action's button when more than one image is selected.
public let secondaryTitle: Title
/// The style of the action. This is used to call a cancel handler when dismissing the controller by tapping the background.
public let style: ImagePickerActionStyle
private let handler: Handler?
private let secondaryHandler: SecondaryHandler?
/// Initializes a new cancel ImagePickerAction
public init(cancelTitle: String) {
self.title = cancelTitle
self.secondaryTitle = { _ in cancelTitle }
self.style = .Cancel
self.handler = nil
self.secondaryHandler = nil
}
/// Initializes a new ImagePickerAction. The secondary title and handler are used when at least 1 image has been selected.
/// Secondary title defaults to title if not specified.
/// Secondary handler defaults to handler if not specified.
public convenience init(title: String, secondaryTitle: String? = nil, style: ImagePickerActionStyle = .Default, handler: Handler, secondaryHandler: SecondaryHandler? = nil) {
self.init(title: title, secondaryTitle: secondaryTitle.map { string in { _ in string }}, style: style, handler: handler, secondaryHandler: secondaryHandler)
}
/// Initializes a new ImagePickerAction. The secondary title and handler are used when at least 1 image has been selected.
/// Secondary title defaults to title if not specified. Use the closure to format a title according to the selection.
/// Secondary handler defaults to handler if not specified
public init(title: String, secondaryTitle: Title?, style: ImagePickerActionStyle = .Default, handler: Handler, secondaryHandler secondaryHandlerOrNil: SecondaryHandler? = nil) {
var secondaryHandler = secondaryHandlerOrNil
if secondaryHandler == nil {
secondaryHandler = { action, _ in
handler(action)
}
}
self.title = title
self.secondaryTitle = secondaryTitle ?? { _ in title }
self.style = style
self.handler = handler
self.secondaryHandler = secondaryHandler
}
func handle(numberOfImages: Int = 0) {
if numberOfImages > 0 {
secondaryHandler?(self, numberOfImages)
}
else {
handler?(self)
}
}
}
func ?? (left: ImagePickerAction.Title?, right: ImagePickerAction.Title) -> ImagePickerAction.Title {
if let left = left {
return left
}
return right
}
| mit | 947e0297df67af5737d672af362a89bb | 35.505882 | 181 | 0.671286 | 4.894322 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Insurance | PerchReadyApp/apps/Perch/iphone/native/Perch/Controllers/PinViewController.swift | 1 | 24170 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
import Foundation
/**
* Entering a pin screen. Mainly responsible for all the animations associated with the screen.
*/
class PinViewController: PerchViewController {
// MARK: IBOutlets
/** Outlets from storyboard. A lot of these are constraint outlets for animating view position changes for things like when the keyboard pops up. */
@IBOutlet weak var pinContainerView: UIView!
@IBOutlet weak var stayConnectedLabel: UILabel!
@IBOutlet weak var stayConnectedBottomSpace: NSLayoutConstraint!
@IBOutlet weak var stayConnectedHeight: NSLayoutConstraint!
@IBOutlet weak var perchLogoHeight: NSLayoutConstraint!
@IBOutlet weak var perchTextImageView: UIImageView!
@IBOutlet weak var fillOrangeViewHeight: NSLayoutConstraint!
@IBOutlet weak var perchLogoImageView: UIImageView!
@IBOutlet weak var syncingWithSensorsLabel: UILabel!
@IBOutlet weak var middleLineBottomSpace: NSLayoutConstraint!
@IBOutlet weak var syncButtonBottomSpace: NSLayoutConstraint!
// MARK: Animation Related Instance Variables
/** Setup variables/constants for the timers that will drive the bird flying loading animation */
let flyInImageCount = 75
let flyInAnimationTime = 2.5
var flyInTimer: NSTimer!
let circleImageCount = 15
let circleAnimationTime = 0.5
var circleTimer: NSTimer!
let flyOutImageCount = 30
let flyOutAnimationTime = 1.0
var flyOutTimer: NSTimer!
let flyOutNoShrinkImageCount = 14
let flyOutNoShrinkAnimationTime = 0.466
var flyOutNoShrinkTimer: NSTimer!
var loadingFinished = false
var animationActive = false
var pendingTransition = false
var pendingError = false
/** We don't really want to include the first 25 frames of flyIn animation xcasset, because they don't actually start to show the bird flying in yet */
var flyInCurrentImageNum = 26
var circleCurrentImageNum = 0
var flyOutCurrentImageNum = 0
var flyOutNoShrinkCurrentImageNum = 0
/** End animation setup variables */
// MARK: Instance Variables
/** Constant for determining if "perch" text should be shown below logo when keyboard animated up. Screens with less than this height don't have quite enough room to show the logo and text with keyboard up. */
let maximumScreenHeightForKeepingPerchLogo: CGFloat = 600
// Used to start the query for asset data
var assetDataMgr: AssetOverviewDataManager? = AssetOverviewDataManager.sharedInstance
weak var enterPinVC: EnterPinViewController?
/** Made class var so can quickly access from test without needing to instantiate this view controller */
class var requiredPinLength: Int { return 4 }
/** Used for determining how much to animate view changes up/down for things like keyboard popping up */
let screenHeight: CGFloat = UIScreen.mainScreen().bounds.height
let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.size.height
/** This needs to be accessed from flyOut animation ending so not local to syncButtonTapped */
var currentErrorMessage = ""
var loginCallback: (()->())!
var loginVC: LoginViewController?
// MARK: View Controller Overrides
override func viewDidLoad() {
super.viewDidLoad()
/** Set up initial state for perch logo UI */
self.setInitialPerchLogoState()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
/** Register for keyboard notifications */
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil)
/** Reset these alphas and image when coming back to screen from another screen.
They are changed to a different state when leaving the screen, so make sure to set the back to initial state here. */
self.perchTextImageView.alpha = 1
self.stayConnectedLabel.alpha = 1
self.perchLogoImageView.image = UIImage(named: "perch_logo")
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
/** If we are coming back to this screen after a successful pin registration (which animates an orange view taking over the screen), hide the orange view that overtook the screen */
if self.fillOrangeViewHeight.constant > 0 {
self.hideOrange()
}
/** Allow sales rep to quickly show off simple version of app by entering demo mode */
if !CurrentUser.sharedInstance.hasBeenAskedToEnterDemoMode {
CurrentUser.sharedInstance.hasBeenAskedToEnterDemoMode = true
let demoAlert = UIAlertController(title: NSLocalizedString("Would you like to use \"Perch\" in demo mode?", comment: ""), message: "", preferredStyle: UIAlertControllerStyle.Alert)
let actionNo = UIAlertAction(title: NSLocalizedString("No", comment: ""), style: UIAlertActionStyle.Default, handler: nil)
let actionYes = UIAlertAction(title: NSLocalizedString("Yes", comment: ""), style: UIAlertActionStyle.Default, handler: { (action: UIAlertAction) -> Void in
CurrentUser.sharedInstance.demoMode = true
self.enterPinVC!.pinTextField.text = "0000"
self.enterPinVC!.fakePinSync()
})
demoAlert.addAction(actionNo)
demoAlert.addAction(actionYes)
self.presentViewController(demoAlert, animated: true, completion: nil)
}
}
/** Remove keyboard notification observer in viewWillDisappear */
override func viewWillDisappear(animated: Bool) {
super.viewDidDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EmbedPinSegue" {
if let destVC = segue.destinationViewController as? EnterPinViewController {
enterPinVC = destVC
enterPinVC!.delegate = self
}
}
}
/** Make sure status bar text black */
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.Default
}
// MARK: UI Related
/** Animation time of the orange view taking over the screen on successful sync */
let coverAnimationTime = 0.4
/** Animate the orange view taking over the screen on successful sync */
func coverOrange() {
self.view.endEditing(true)
/** Make the height of the orange view twice the screen height to ensure the view fills the entire screen no matter where it originates from. */
self.fillOrangeViewHeight.constant = screenHeight
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
/** Once screen covered in orange segue to asset overview */
UIView.animateWithDuration(NSTimeInterval(coverAnimationTime), animations: { () -> Void in
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
}) { (finished) -> Void in
if finished {
// When finished, call the callback so that the login view controller can be presented by the Challenge Handler
self.loginCallback()
}
}
}
/** Animate the orange view down to invisible again */
func hideOrange() {
self.fillOrangeViewHeight.constant = 0
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(NSTimeInterval(coverAnimationTime), animations: { () -> Void in
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
})
}
/** Start the sequence of timers that are responsible for swapping out the image view to show the bird flying for loading */
func showLoading() {
/** Set the time each frame should appear. This is the division of the desired total animation time by the total image count for the animation. */
let flyInEachImageTime = flyInAnimationTime / Double(flyInImageCount)
/** Start a timer that will call a selector for updating the image view image with each fire of the timer */
flyInTimer = NSTimer.scheduledTimerWithTimeInterval(flyInEachImageTime, target: self, selector: Selector("flyIn"), userInfo: nil, repeats: true)
/** Don't want other buttons causing other animation changes during our loading animation so disable other buttons */
enterPinVC?.buttonsEnabled(false)
/** Other changes in the UI happen other than just loading animation, so make those changes */
self.prepareScreenUIForLoading()
}
/** These are the UI changes that need to take place when loading starts.
Design wants birdhouse logo to become centered vertically and other things on UI to disappear.
Also wanted to display text to user telling them what was happening. */
func prepareScreenUIForLoading() {
/** Design wanted keyboard dismissed on loading starting */
self.view.endEditing(true)
/** Center the birdhouse logo vertically */
self.middleLineBottomSpace.constant = (screenHeight + pinContainerView.height - self.perchLogoHeight.constant) / 2
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(0.5, animations: { () -> Void in
self.perchTextImageView.alpha = 0
self.stayConnectedLabel.alpha = 0
self.syncingWithSensorsLabel.alpha = 1
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
})
}
/** These are the UI changes that need to take place when loading is finished. Basically undoing things done in prepareScreenUIForLoading() */
func prepareScreenUIForLoadingFinished() {
self.setInitialPerchLogoState()
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
UIView.animateWithDuration(0.5, animations: { () -> Void in
/** Only animate views back in if we aren't about to transition to other screen.
Design thought this looked better. */
if !self.pendingTransition {
self.perchTextImageView.alpha = 1
self.stayConnectedLabel.alpha = 1
}
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
})
}
/** Helper method for restoring perch logo to its initial state when view controller loaded */
func setInitialPerchLogoState() {
self.syncingWithSensorsLabel.alpha = 0
self.middleLineBottomSpace.constant = (screenHeight + self.stayConnectedBottomSpace.constant + stayConnectedHeight.constant - statusBarHeight - (self.perchLogoHeight.constant/2)) / 2
}
// MARK: Keyboard Notifications
/** Call the update ui method when receiving a keyboard notification */
func keyboardWillShow(notification: NSNotification) {
self.moveViewWithKeyboard(notification)
}
/** Call the update ui method when receiving a keyboard notification */
func keyboardWillHide(notification: NSNotification) {
self.moveViewWithKeyboard(notification)
}
/** Helper method for determining which direction the keyboard is animating */
func keyboardAnimatingDown(keyboardFrameEnd: CGRect) -> Bool {
return screenHeight == keyboardFrameEnd.origin.y
}
/** Update the UI when the keyboard appears or disappears */
func moveViewWithKeyboard(notification: NSNotification) {
if let info = notification.userInfo {
/** Get information about the keyboard that is popping up or minimizing */
let keyboardFrameEnd: CGRect = (info[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
let keyboardAnimationDuration = info[UIKeyboardAnimationDurationUserInfoKey] as! NSNumber
let keyboardHeight = screenHeight - keyboardFrameEnd.origin.y
/** If the keyboard is animating down (dismissing), then reset the perch logo position */
if self.keyboardAnimatingDown(keyboardFrameEnd) {
self.setInitialPerchLogoState()
} else {
/** Since we keep perch text if on screen big enough to keep it. This means the centering of perch logo shifts a little to center better with text below. */
if self.screenHeight >= self.maximumScreenHeightForKeepingPerchLogo {
/** Set up the constraint to be centered based on the view available (factor in all things on screen like keyboard, bottom enter button). Divide by 2 because you want it centered on screen. Add things below the middle line, subtract things above the middle line. Subtracting moves the line down, adding moves the line up. The subtraction of the perch logo divided by 2 is to account for the logo being taller than the text label below it. */
self.middleLineBottomSpace.constant = (screenHeight + pinContainerView.height + keyboardHeight - (self.perchLogoHeight.constant/2)) / 2
} else {
self.middleLineBottomSpace.constant = (screenHeight + pinContainerView.height + keyboardHeight - self.perchLogoHeight.constant) / 2
}
}
/** Animate the moving of the sync button to be on top of keyboard if keyboard present, otherwise put it on bottom of screen. */
self.syncButtonBottomSpace.constant = keyboardHeight
/** Update any other constraints associated with the constraint(s) just updated */
self.view.setNeedsUpdateConstraints()
/** Show and hide UI elements based on keyboard animating or dismissing */
UIView.animateWithDuration(keyboardAnimationDuration.doubleValue, animations: {
/** Animate the constraint changes (make sure they don't happen immediately) */
self.view.layoutIfNeeded()
if self.keyboardAnimatingDown(keyboardFrameEnd) {
self.stayConnectedLabel.alpha = 1
self.perchTextImageView.alpha = 1
} else {
self.stayConnectedLabel.alpha = 0
/** Hide perch text if not on screen big enough to keep it */
if self.screenHeight < self.maximumScreenHeightForKeepingPerchLogo {
self.perchTextImageView.alpha = 0
}
}
})
}
}
// MARK: ASSET DATA METHODS
/**
Starts the query for asset data. This occurs after subscribing to the pin channel finishes.
*/
func startAssetDataQuery() {
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
let assetOverviewDataManager = AssetOverviewDataManager.sharedInstance
assetOverviewDataManager.getAllAssetData({[unowned self] in self.assetQueryFinished($0)})
}
}
/**
This is called by the Challenge Handler if authentication is required. This will stop the loading animation, and start the cover orange animation
*/
func authRequired(callback: (()->())!) {
loadingFinished = true
loginCallback = callback
if !self.animationActive {
self.coverOrange()
} else {
self.pendingTransition = true
}
}
// This is called when the query for asset data finishes. Once finished and succesful, tells the login view that it was succesful.
func assetQueryFinished(success: Bool) {
if let loginVC = self.presentedViewController as? LoginViewController {
self.loginVC = loginVC
}
if success {
self.loginVC?.syncSensorsFinished()
} else {
loadingFinished = true
pendingError = true
self.loginVC?.dismissViewControllerAnimated(true, completion: nil)
enterPinVC?.shakeAndShowError("Failed to sync with sensors. Try again or enter a new pin.")
}
}
}
// MARK: Pin Entry Delegate
extension PinViewController: PinEntryDelegate {
// Once a pin has been entered, show the loading animation
func didEnterPin() {
self.showLoading()
}
/**
Once the pin syn finishs, either stop the animation becaues of an error, or start the asset data query
*/
func pinSyncFinished(error: Bool, errorMessage: String?) {
if error {
loadingFinished = true
self.pendingError = true
} else {
self.startAssetDataQuery()
}
}
/**
If doing a fake sync, start the asset data query
*/
func fakePinSyncFinished() {
self.showLoading()
self.animationActive = true
self.startAssetDataQuery()
}
}
// MARK: Bird flying loading animation
extension PinViewController {
/** This is the method that is called for each time the flyInTimer fires. It is responsible for updating the logo image view every x seconds
so it appears as though a bird is flying in from the edge of the screen. */
func flyIn() {
/** As soon as we start the animation, let all other areas of the view controller know by setting this variable */
animationActive = true
enterPinVC?.animationActive = true
/** This statement entered for last frame of the animation. Used to kick off the next animaiton and stop this one. */
if flyInCurrentImageNum == flyInImageCount {
/** Reset the current image to the initial one so if need to start the animation again later, it will start at correct location. */
flyInCurrentImageNum = 26
/** Stop the timer that is responsible for doing the fly in animaiton */
flyInTimer.invalidate()
/** If networking call has already finished by the time the fly in animation is done, go ahead and start the fly out animation to wrap up the loading animation */
if loadingFinished {
/** Reset loadingFinished, so next time animation is run it won't immediately finish */
loadingFinished = false
/** Decide which fly out animation to do based on if there was an error with the networking call */
self.doFlyOutAnimationBasedOnErrorState()
} else {
/** If loading still going on when fly in finishes, start the flying around circles animation */
let circleEachImageTime = circleAnimationTime / Double(circleImageCount)
circleTimer = NSTimer.scheduledTimerWithTimeInterval(circleEachImageTime, target: self, selector: Selector("circle"), userInfo: nil, repeats: true)
}
} else {
/** This is what normall happens each time the timer is fired - the image view's image is updated with the next image of the bird flying. */
self.perchLogoImageView.image = UIImage(named: "pech_fly_in\(flyInCurrentImageNum)")
}
/** Update the current image so the next pass through of the timer firing will update to the next image */
flyInCurrentImageNum++
}
/** Selector method called each time the circle timer is fired. Animates the bird flying around in a circle aroung logo.
See flyIn() method comments for more detailed high level overview of how it works. */
func circle() {
if circleCurrentImageNum == circleImageCount {
circleCurrentImageNum = 0
if loadingFinished {
loadingFinished = false
circleTimer.invalidate()
self.doFlyOutAnimationBasedOnErrorState()
}
} else {
self.perchLogoImageView.image = UIImage(named: "perch_circle\(circleCurrentImageNum)")
}
circleCurrentImageNum++
}
/** Selector method called each time the fly out timer is fired. Animates the bird flying into the logo.
See flyIn() method comments for more detailed high level overview of how it works. */
func flyOut() {
if flyOutCurrentImageNum == flyOutImageCount {
flyOutCurrentImageNum = 0
flyOutTimer.invalidate()
/** The buttons were disabled at beginning of loading starting to show, so enable them back here */
enterPinVC?.buttonsEnabled(true)
/** Reset UI to before loading */
self.prepareScreenUIForLoadingFinished()
/** Let everyone else in this view controller know the animation is not active anymore */
animationActive = false
enterPinVC?.animationActive = false
/** Make sure transition pending (returned success from sync) before doning transition */
if pendingTransition {
pendingTransition = false
self.coverOrange()
}
} else {
self.perchLogoImageView.image = UIImage(named: "perch_fly_out\(flyOutCurrentImageNum)")
}
flyOutCurrentImageNum++
}
/** Selector method called each time the fly out (no shrink) timer is fired. Animates the bird flying into the logo.
See flyIn() or flyOut() method comments for more detailed high level overview of how it works. */
func flyOutNoShrink() {
if flyOutNoShrinkCurrentImageNum == flyOutNoShrinkImageCount {
flyOutNoShrinkCurrentImageNum = 0
flyOutNoShrinkTimer.invalidate()
enterPinVC?.buttonsEnabled(true)
self.prepareScreenUIForLoadingFinished()
animationActive = false
enterPinVC?.animationActive = false
} else {
self.perchLogoImageView.image = UIImage(named: "perch_fly_out_noshrink\(flyOutNoShrinkCurrentImageNum)")
}
flyOutNoShrinkCurrentImageNum++
}
/** Helper method for determining which fly out animation to do based on error state.
If there is an error, then we are not transitioning to next screen so we don't want to
animate the birdhouse logo shrinking down. */
func doFlyOutAnimationBasedOnErrorState() {
if self.pendingError {
self.pendingError = false
let flyOutNoShrinkEachImageTime = flyOutNoShrinkAnimationTime / Double(flyOutNoShrinkImageCount)
flyOutNoShrinkTimer = NSTimer.scheduledTimerWithTimeInterval(flyOutNoShrinkEachImageTime, target: self, selector: "flyOutNoShrink", userInfo: nil, repeats: true)
} else {
let flyOutEachImageTime = flyOutAnimationTime / Double(flyOutImageCount)
flyOutTimer = NSTimer.scheduledTimerWithTimeInterval(flyOutEachImageTime, target: self, selector: "flyOut", userInfo: nil, repeats: true)
}
}
}
| epl-1.0 | 0970acdea416288e5770964ab525798c | 46.764822 | 461 | 0.65824 | 5.277074 | false | false | false | false |
jessesquires/JSQCoreDataKit | Sources/CoreDataStack.swift | 1 | 9532 | //
// Created by Jesse Squires
// https://www.jessesquires.com
//
//
// Documentation
// https://jessesquires.github.io/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015-present Jesse Squires
// Released under an MIT license: https://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/**
An instance of `CoreDataStack` encapsulates the entire Core Data stack.
It manages the managed object model, the persistent store coordinator, and managed object contexts.
It is composed of a main context and a background context.
These two contexts operate on the main queue and a private background queue, respectively.
Both are connected to the persistent store coordinator and data between them is perpetually kept in sync.
Changes to a child context are propagated to its parent context and eventually the persistent store when saving.
- warning: **You cannot create a `CoreDataStack` instance directly. Instead, use a `CoreDataStackProvider` for initialization.**
*/
public final class CoreDataStack {
// MARK: Typealiases
/// Describes the result type for creating a `CoreDataStack`.
public typealias StackResult = Result<CoreDataStack, Error>
// MARK: Properties
/// The model for the stack.
public let model: CoreDataModel
/**
The main managed object context for the stack, which operates on the main queue.
This context is a root level context that is connected to the `storeCoordinator`.
It is kept in sync with `backgroundContext`.
*/
public let mainContext: NSManagedObjectContext
/**
The background managed object context for the stack, which operates on a background queue.
This context is a root level context that is connected to the `storeCoordinator`.
It is kept in sync with `mainContext`.
*/
public let backgroundContext: NSManagedObjectContext
/**
The persistent store coordinator for the stack. Both contexts are connected to this coordinator.
*/
public let storeCoordinator: NSPersistentStoreCoordinator
// MARK: Initialization
init(model: CoreDataModel,
mainContext: NSManagedObjectContext,
backgroundContext: NSManagedObjectContext,
storeCoordinator: NSPersistentStoreCoordinator) {
self.model = model
self.mainContext = mainContext
self.backgroundContext = backgroundContext
self.storeCoordinator = storeCoordinator
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self,
selector: #selector(self._didReceiveMainContextDidSave(notification:)),
name: .NSManagedObjectContextDidSave,
object: mainContext)
notificationCenter.addObserver(self,
selector: #selector(self._didReceiveBackgroundContextDidSave(notification:)),
name: .NSManagedObjectContextDidSave,
object: backgroundContext)
}
// MARK: Child contexts
/**
Creates a new child context with the specified `concurrencyType` and `mergePolicyType`.
The parent context is either `mainContext` or `backgroundContext` dependending on the specified `concurrencyType`:
* `.PrivateQueueConcurrencyType` will set `backgroundContext` as the parent.
* `.MainQueueConcurrencyType` will set `mainContext` as the parent.
Saving the returned context will propagate changes through the parent context and then to the persistent store.
- parameter concurrencyType: The concurrency pattern to use. The default is `.MainQueueConcurrencyType`.
- parameter mergePolicyType: The merge policy to use. The default is `.MergeByPropertyObjectTrumpMergePolicyType`.
- returns: A new child managed object context.
*/
public func childContext(concurrencyType: NSManagedObjectContextConcurrencyType = .mainQueueConcurrencyType,
mergePolicyType: NSMergePolicyType = .mergeByPropertyObjectTrumpMergePolicyType) -> NSManagedObjectContext.ChildContext {
let childContext = NSManagedObjectContext(concurrencyType: concurrencyType)
childContext.mergePolicy = NSMergePolicy(merge: mergePolicyType)
switch concurrencyType {
case .mainQueueConcurrencyType:
childContext.parent = self.mainContext
case .privateQueueConcurrencyType:
childContext.parent = self.backgroundContext
case .confinementConcurrencyType:
fatalError("*** Error: ConfinementConcurrencyType is not supported because it is deprecated.")
@unknown default:
fatalError("*** Error: unsupported, unknown concurrency type \(concurrencyType).")
}
if let name = childContext.parent?.name {
childContext.name = name + ".child"
}
NotificationCenter.default.addObserver(self,
selector: #selector(self._didReceiveChildContextDidSave(notification:)),
name: .NSManagedObjectContextDidSave,
object: childContext)
return childContext
}
/**
Resets the managed object contexts in the stack on their respective threads.
Then, if the coordinator is connected to a persistent store, the store will be deleted and recreated on a background thread.
The completion closure is executed on the main thread.
- note: Removing and re-adding the persistent store is performed on a background queue.
For binary and SQLite stores, this will also remove the store from disk.
- parameter queue: A background queue on which to reset the stack.
The default is a background queue with a "user initiated" quality of service class.
- parameter completion: The closure to be called once resetting is complete. This is called on the main queue.
*/
public func reset(onQueue queue: DispatchQueue = .global(qos: .userInitiated),
completion: @escaping (StackResult) -> Void) {
self.mainContext.performAndWait { self.mainContext.reset() }
self.backgroundContext.performAndWait { self.backgroundContext.reset() }
guard let store = self.storeCoordinator.persistentStores.first else {
DispatchQueue.main.async {
completion(.success(self))
}
return
}
queue.async {
precondition(!Thread.isMainThread, "*** Error: cannot reset a stack on the main queue")
let storeCoordinator = self.storeCoordinator
let options = store.options
let model = self.model
storeCoordinator.performAndWait {
do {
if let modelURL = model.storeURL {
try storeCoordinator.destroyPersistentStore(at: modelURL,
ofType: model.storeType.type,
options: options)
}
try storeCoordinator.addPersistentStore(ofType: model.storeType.type,
configurationName: nil,
at: model.storeURL,
options: options)
} catch {
DispatchQueue.main.async {
completion(.failure(error as NSError))
}
return
}
DispatchQueue.main.async {
completion(.success(self))
}
}
}
}
// MARK: Private
@objc
private func _didReceiveChildContextDidSave(notification: Notification) {
guard let context = notification.object as? NSManagedObjectContext else {
assertionFailure("*** Error: \(notification.name) posted from object of type "
+ String(describing: notification.object.self)
+ ". Expected \(NSManagedObjectContext.self) instead.")
return
}
guard let parentContext = context.parent else {
// have reached the root context, nothing to do
return
}
parentContext.saveAsync(completion: nil)
}
@objc
private func _didReceiveBackgroundContextDidSave(notification: Notification) {
self.mainContext.perform {
self.mainContext.mergeChanges(fromContextDidSave: notification)
}
}
@objc
private func _didReceiveMainContextDidSave(notification: Notification) {
self.backgroundContext.perform {
self.backgroundContext.mergeChanges(fromContextDidSave: notification)
}
}
}
extension CoreDataStack: Equatable {
/// :nodoc:
public static func == (lhs: CoreDataStack, rhs: CoreDataStack) -> Bool {
lhs.model == rhs.model
}
}
extension CoreDataStack: CustomStringConvertible {
/// :nodoc:
public var description: String {
"\(CoreDataStack.self)(model=\(self.model.name); mainContext=\(self.mainContext); backgroundContext=\(self.backgroundContext))"
}
}
| mit | 42a2359fd241c07627e95fc7118261b8 | 39.21519 | 150 | 0.634771 | 6.028463 | false | false | false | false |
binarylevel/Tinylog-iOS | Tinylog/Extensions/UIColor+TinylogiOSAdditions.swift | 1 | 3229 | //
// UIColor+TinylogiOSAdditions.swift
// Tinylog
//
// Created by Spiros Gerokostas on 17/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
extension UIColor {
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
if hex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("invalid rgb string, length should be 7 or 9")
}
} else {
print("scan hex error")
}
} else {
print("invalid rgb string, missing '#' as prefix")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
class func tinylogNavigationBarColor() -> UIColor {
return UIColor(hue: 0.0, saturation: 0.0, brightness: 0.98, alpha: 1.00)
}
class func tinylogBackgroundColor() -> UIColor {
return UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
}
class func tinylogTableViewLineColor() -> UIColor {
return UIColor(red: 224.0 / 255.0, green: 224.0 / 255.0, blue: 224.0 / 255.0, alpha: 1.0)
}
class func tinylogTextColor() -> UIColor {
return UIColor(red: 77.0 / 255.0, green: 77.0 / 255.0, blue: 77.0 / 255.0, alpha: 1.0)
}
class func tinylogItemColor() -> UIColor {
return UIColor(red: 250.0 / 255.0, green: 250.0 / 255.0, blue: 250.0 / 255.0, alpha: 1.0)
}
class func tinylogMainColor() -> UIColor {
return UIColor(red: 43.0 / 255.0, green: 174.0 / 255.0, blue: 230.0 / 255.0, alpha: 1.0)
}
class func tinylogNumbersColor() -> UIColor {
return UIColor(red:76.0 / 255.0, green:90.0 / 255.0, blue:100.0 / 255.0 ,alpha:1.0)
}
class func tinylogNavigationBarLineColor()->UIColor {
return UIColor(red: 205.0 / 255.0, green: 205.0 / 255.0, blue: 205.0 / 255.0, alpha: 1.0)
}
class func tinylogNavigationBarDarkColor()->UIColor {
return UIColor(red: 20.0 / 255.0, green: 21.0 / 255.0, blue: 24.0 / 255.0, alpha: 1.0)
}
class func tinylogNavigationBarDayColor()->UIColor {
return UIColor(red: 243.0 / 255.0, green: 243.0 / 255.0, blue: 243.0 / 255.0, alpha: 1.0)
}
}
| mit | 23a7b06f452e42fd1bec2a2f314e0e6c | 36.534884 | 97 | 0.545539 | 3.566851 | false | false | false | false |
sag333ar/GoogleBooksAPIResearch | GoogleBooksApp/GoogleBooksUI/UserInterfaceModules/BookDetails/View/BookDetailsView+Setup.swift | 1 | 2872 | //
// BookDetailsView+Setup.swift
// GoogleBooksApp
//
// Created by Kothari, Sagar on 9/9/17.
// Copyright © 2017 Sagar Kothari. All rights reserved.
//
import UIKit
extension BookDetailsView {
func loadUIData() {
setTitleAndAuthor()
setSubtitleText()
prepareBookThumb()
setTitleForNavigationBar()
}
func setTitleAndAuthor() {
if let data = book?.volumeInfo?.title {
bookTitleLabel.text = data
} else {
bookTitleLabel.text = "Title not available"
}
if let data = book?.volumeInfo?.authors {
bookAuthorLabel.text = data.joined(separator: ", ")
} else {
bookAuthorLabel.text = "Author not available"
}
}
func setSubtitleText() {
if let data = book?.volumeInfo?.subtitle {
bookSubtitleLabel.text = data
} else {
bookSubtitleLabel.text = "Subtitle not available."
}
if let data = book?.volumeInfo?.pageCount {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nThere are \(data) pages."
} else {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nNumber of pages info not available."
}
if let data = book?.accessInfo?.pdf?.isAvailable {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nPDF \(data == true ? "available." : "not available.")"
} else {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nPDF info is not available."
}
if let data = book?.volumeInfo?.printType {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nPrint type is \(data)"
} else {
bookSubtitleLabel.text = bookSubtitleLabel.text!
+ "\n\nPrint type info is not available."
}
}
func setTitleForNavigationBar() {
if let title = book?.volumeInfo?.title {
self.title = title
} else {
self.title = "Anonymos Book"
}
}
func prepareBookThumb() {
bookThumbImageView.image = nil
bookThumbImageView.sd_setShowActivityIndicatorView(true)
bookThumbImageView.sd_setIndicatorStyle(.gray)
if let data = book?.volumeInfo?.imageLinks?.smallThumbnail, let url = URL(string: data) {
self.bookThumbImageView.sd_setImage(with: url,
completed: nil)
}
bookThumbImageView.layer.borderColor = UIColor.black.cgColor
bookThumbImageView.layer.borderWidth = 1
bookThumbImageView.layer.shadowOffset = CGSize(width: 3, height: 3)
bookThumbImageView.layer.shadowRadius = 2
bookThumbImageView.layer.shadowOpacity = 10
bookThumbImageView.layer.shadowColor = UIColor.black.cgColor
}
}
extension BookDetailsView {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
scrollView.contentSize = CGSize(width: view.frame.size.width, height: stackView.frame.size.height + 30)
}
}
| apache-2.0 | b675f2c161f3c589a3991b6c16a15c5d | 28 | 107 | 0.653431 | 4.16087 | false | false | false | false |
darren90/Gankoo_Swift | Gankoo/Gankoo/Classes/Home/RMDataModel.swift | 1 | 2986 | //
// RMDataModel.swift
// Gankoo
//
// Created by Fengtf on 2017/2/9.
// Copyright © 2017年 ftf. All rights reserved.
//
import UIKit
import RealmSwift
class RMDataModel: Object {
dynamic var _id = ""
dynamic var desc = ""
dynamic var type = ""
dynamic var iconUrl = ""
dynamic var url = ""
dynamic var who = ""
dynamic var date = Date()
}
class RMDBTools: NSObject {
static let shareInstance:RMDBTools = RMDBTools()
override init() {
super.init()
}
var realm = { () -> Realm in
let docPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first
let dbPath = docPath?.appending("/Gankoo.realm")
let dbUrl = URL(fileURLWithPath: dbPath!)
let rm = try! Realm(fileURL: dbUrl)
return rm
}()
func getAllDatas() -> [DataModel]{//
let arrs = realm.objects(RMDataModel.self).sorted(byKeyPath: "date")
var models = [DataModel]()
for res in arrs {
let m = getModel(res)
models.append(m)
}
return models
}
func addData(_ model:DataModel?){
guard let model = model else {
return
}
//已经存过了
if isDataExist(model) == true {
return
}
realm.beginWrite()
let m = getDbModel(model)
realm.add(m)
try! realm.commitWrite()
}
func deleData(_ model:DataModel?){
guard let model = model else {
return
}
let predicate = NSPredicate(format: "_id = '\(model._id ?? "")'")
guard let rsm = realm.objects(RMDataModel.self).filter(predicate).first else {
return
}
realm.beginWrite()
// let m = getDbModel(model)
realm.delete(rsm)
try! realm.commitWrite()
}
func isDataExist(_ model:DataModel?) -> Bool{
guard let model = model else {
return false
}
let predicate = NSPredicate(format: "_id = '\(model._id ?? "")'")
let rsm = realm.objects(RMDataModel.self).filter(predicate).first
if rsm == nil {
return false
}
return true
}
func getDbModel(_ model:DataModel) -> RMDataModel{
let m = RMDataModel()
m._id = model._id ?? ""
m.desc = model.desc ?? ""
m.type = model.type ?? "未知"
m.iconUrl = model.images?.first ?? ""
m.who = model.who ?? "未知"
m.date = Date()
m.url = model.url ?? "https://github.com/darren90"
return m
}
func getModel(_ model:RMDataModel) -> DataModel{
let m = DataModel()
m._id = model._id
m.desc = model.desc
m.type = model.type
m.who = model.who
m.images = [model.iconUrl]
if model.iconUrl.characters.count == 0 {
m.images = nil
}
m.url = model.url
return m
}
}
| apache-2.0 | bf48873257746c2b960467a040af9e7b | 20.962963 | 106 | 0.533221 | 4.050546 | false | false | false | false |
malaonline/iOS | mala-ios/View/TeacherDetail/TeacherDetailsCertificateCell.swift | 1 | 2710 | //
// TeacherDetailsCertificateCell.swift
// mala-ios
//
// Created by Elors on 1/5/16.
// Copyright © 2016 Mala Online. All rights reserved.
//
import UIKit
import SKPhotoBrowser
class TeacherDetailsCertificateCell: MalaBaseCell {
// MARK: - Property
var models: [AchievementModel?] = [] {
didSet {
guard models.count != oldValue.count else { return }
/// 解析数据
for model in models {
self.labels.append(" "+(model?.title ?? "默认证书"))
let photo = SKPhoto.photoWithImageURL(model?.img?.absoluteString ?? "")
photo.caption = model?.title ?? "默认证书"
images.append(photo)
}
tagsView.labels = self.labels
}
}
var labels: [String] = []
var images: [SKPhoto] = []
// MARK: - Components
/// 标签容器
lazy var tagsView: TagListView = {
let tagsView = TagListView(frame: CGRect(x: 0, y: 0, width: MalaLayout_CardCellWidth, height: 0))
tagsView.labelBackgroundColor = UIColor(named: .CertificateBack)
tagsView.textColor = UIColor(named: .CertificateLabel)
tagsView.iconName = "image_icon"
tagsView.commonTarget = self
tagsView.commonAction = #selector(TeacherDetailsCertificateCell.tagDidTap(_:))
return tagsView
}()
// MARK: - Constructed
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
configure()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func configure() {
content.addSubview(tagsView)
content.snp.updateConstraints { (maker) -> Void in
maker.bottom.equalTo(contentView).offset(-10)
}
tagsView.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(content)
maker.left.equalTo(content)
maker.width.equalTo(MalaLayout_CardCellWidth)
maker.bottom.equalTo(content)
}
}
// MARK: - Delegate
/// 标签点击事件
func tagDidTap(_ sender: UITapGestureRecognizer) {
/// 图片浏览器
if let index = sender.view?.tag {
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(index)
browser.navigationController?.isNavigationBarHidden = true
NotificationCenter.default.post(name: MalaNotification_PushPhotoBrowser, object: browser)
}
}
}
| mit | 43b2abd42aceaac0d40de7eec7323795 | 29.872093 | 105 | 0.59435 | 4.617391 | false | false | false | false |
satoshin21/Anima | Example/SizeAnimationViewController.swift | 1 | 1644 | //
// SizeAnimationViewController.swift
// AnimaExample
//
// Created by Satoshi Nagasaka on 2017/03/22.
// Copyright © 2017年 satoshin21. All rights reserved.
//
import UIKit
import Anima
class SizeAnimationViewController: UIViewController {
@IBOutlet weak var animaView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let animations: [AnimaType] = [.scaleBy(1.5),
.rotateByZDegree(360)]
animaView.layer.anima.then(group: animations, options: [
.autoreverse,
.timingFunction(.easeInOut),
.repeat(count: .infinity)])
.fire()
}
let anchors: [AnimaAnchorPoint] = [.topLeft,
.topRight,
.bottomLeft,
.bottomRight,
.center]
var currentAnchor:AnimaAnchorPoint = .center
@IBAction func changeAnchor(_ sender: UIButton) {
let nextAnchor: AnimaAnchorPoint = {
switch currentAnchor {
case .center:
return .topLeft
case .topLeft:
return .topRight
case .topRight:
return .bottomLeft
case .bottomLeft:
return .bottomRight
case .bottomRight:
return .center
default:
fatalError()
}
}()
animaView.layer.anima.then(.moveAnchor(nextAnchor)).fire()
currentAnchor = nextAnchor
}
}
| mit | 506a982b5fcffc20d5a49a6fa5360eeb | 26.813559 | 66 | 0.500914 | 5.31068 | false | false | false | false |
raphaelhanneken/apple-juice | AppleJuice/BatteryState.swift | 1 | 2012 | //
// BatteryState.swift
// Apple Juice
// https://github.com/raphaelhanneken/apple-juice
//
import Foundation
/// Define the precision, with wich the icon can display the current charging level
public let drawingPrecision = 5.4
/// Defines the state the battery is currently in.
///
/// - chargedAndPlugged: The battery is plugged into a power supply and charged.
/// - charging: The battery is plugged into a power supply and
/// charging. Takes the current percentage as argument.
/// - discharging: The battery is currently discharging. Accepts the
/// current percentage as argument.
enum BatteryState: Equatable {
case chargedAndPlugged
case charging(percentage: Percentage)
case discharging(percentage: Percentage)
// MARK: Internal
/// The current percentage.
var percentage: Percentage {
switch self {
case .chargedAndPlugged:
return Percentage(numeric: 100)
case .charging(let percentage):
return percentage
case .discharging(let percentage):
return percentage
}
}
}
/// Compares two BatteryStatusTypes for equality.
///
/// - parameter lhs: A BatteryStatusType.
/// - parameter rhs: Another BatteryStatusType.
/// - returns: True if the supplied BatteryStatusType's are equal. Otherwise false.
func == (lhs: BatteryState, rhs: BatteryState) -> Bool {
switch (lhs, rhs) {
case (.chargedAndPlugged, .chargedAndPlugged),
(.charging, .charging):
return true
case (.discharging(let lhsPercentage), .discharging(let rhsPercentage)):
guard let lhs = lhsPercentage.numeric, let rhs = rhsPercentage.numeric else {
return false
}
// Divide the percentages by the defined drawing precision; So that the battery image
// only gets redrawn, when it actually differs.
return round(Double(lhs) / drawingPrecision) == round(Double(rhs ) / drawingPrecision)
default:
return false
}
}
| mit | e4768f66108d03e671edb041bf5057e8 | 33.101695 | 94 | 0.674453 | 4.461197 | false | false | false | false |
fredfoc/OpenWit | Example/OpenWit/Examples/Models/CustomConverseModels.swift | 1 | 1415 | //
// CustomConverseModels.swift
// OpenWit
//
// Created by fauquette fred on 7/01/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import OpenWit
import ObjectMapper
/// a custom enity defined as an answer
struct AddShopItemAnswerModel: Mappable {
var shopListAlone: String?
var shopItemAlone: String?
var missingAll: Bool?
var allOk: String?
public init?(map: Map) {}
mutating public func mapping(map: Map) {
shopListAlone <- map["shopListAlone"]
shopItemAlone <- map["shopItemAlone"]
missingAll <- map["missingAll"]
allOk <- map["allOk"]
}
init(allOk: String?, shopListAlone: String?, shopItemAlone: String?, missingAll: Bool?) {
self.allOk = allOk
self.shopListAlone = shopListAlone
self.shopItemAlone = shopItemAlone
self.missingAll = missingAll
}
}
struct CreateListAnswerModel: Mappable {
var listName: String?
var missingListName: String?
public init?(map: Map) {}
mutating public func mapping(map: Map) {
missingListName <- map["missingListName"]
listName <- map["listName"]
}
init(listName: String?, missingListName: String?) {
self.listName = listName
self.missingListName = missingListName
}
}
| mit | 92b136a042197d1ab3c43ee857b1183b | 25.185185 | 93 | 0.608911 | 4.195846 | false | false | false | false |
azadibogolubov/InterestDestroyer | iOS Version/Interest Destroyer/Charts/Classes/Utils/ChartViewPortHandler.swift | 15 | 12203 | //
// ChartViewPortHandler.swift
// Charts
//
// Created by Daniel Cohen Gindi on 27/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
public class ChartViewPortHandler: NSObject
{
/// matrix used for touch events
private var _touchMatrix = CGAffineTransformIdentity
/// this rectangle defines the area in which graph values can be drawn
private var _contentRect = CGRect()
private var _chartWidth = CGFloat(0.0)
private var _chartHeight = CGFloat(0.0)
/// minimum scale value on the y-axis
private var _minScaleY = CGFloat(1.0)
/// maximum scale value on the y-axis
private var _maxScaleY = CGFloat.max
/// minimum scale value on the x-axis
private var _minScaleX = CGFloat(1.0)
/// maximum scale value on the x-axis
private var _maxScaleX = CGFloat.max
/// contains the current scale factor of the x-axis
private var _scaleX = CGFloat(1.0)
/// contains the current scale factor of the y-axis
private var _scaleY = CGFloat(1.0)
private var _transX = CGFloat(0.0)
private var _transY = CGFloat(0.0)
/// offset that allows the chart to be dragged over its bounds on the x-axis
private var _transOffsetX = CGFloat(0.0)
/// offset that allows the chart to be dragged over its bounds on the x-axis
private var _transOffsetY = CGFloat(0.0)
public override init()
{
}
public init(width: CGFloat, height: CGFloat)
{
super.init()
setChartDimens(width: width, height: height)
}
public func setChartDimens(width width: CGFloat, height: CGFloat)
{
let offsetLeft = self.offsetLeft
let offsetTop = self.offsetTop
let offsetRight = self.offsetRight
let offsetBottom = self.offsetBottom
_chartHeight = height
_chartWidth = width
restrainViewPort(offsetLeft: offsetLeft, offsetTop: offsetTop, offsetRight: offsetRight, offsetBottom: offsetBottom)
}
public var hasChartDimens: Bool
{
if (_chartHeight > 0.0 && _chartWidth > 0.0)
{
return true
}
else
{
return false
}
}
public func restrainViewPort(offsetLeft offsetLeft: CGFloat, offsetTop: CGFloat, offsetRight: CGFloat, offsetBottom: CGFloat)
{
_contentRect.origin.x = offsetLeft
_contentRect.origin.y = offsetTop
_contentRect.size.width = _chartWidth - offsetLeft - offsetRight
_contentRect.size.height = _chartHeight - offsetBottom - offsetTop
}
public var offsetLeft: CGFloat
{
return _contentRect.origin.x
}
public var offsetRight: CGFloat
{
return _chartWidth - _contentRect.size.width - _contentRect.origin.x
}
public var offsetTop: CGFloat
{
return _contentRect.origin.y
}
public var offsetBottom: CGFloat
{
return _chartHeight - _contentRect.size.height - _contentRect.origin.y
}
public var contentTop: CGFloat
{
return _contentRect.origin.y
}
public var contentLeft: CGFloat
{
return _contentRect.origin.x
}
public var contentRight: CGFloat
{
return _contentRect.origin.x + _contentRect.size.width
}
public var contentBottom: CGFloat
{
return _contentRect.origin.y + _contentRect.size.height
}
public var contentWidth: CGFloat
{
return _contentRect.size.width
}
public var contentHeight: CGFloat
{
return _contentRect.size.height
}
public var contentRect: CGRect { return _contentRect; }
public var contentCenter: CGPoint
{
return CGPoint(x: _contentRect.origin.x + _contentRect.size.width / 2.0, y: _contentRect.origin.y + _contentRect.size.height / 2.0)
}
public var chartHeight: CGFloat { return _chartHeight; }
public var chartWidth: CGFloat { return _chartWidth; }
// MARK: - Scaling/Panning etc.
/// Zooms around the specified center
public func zoom(scaleX scaleX: CGFloat, scaleY: CGFloat, x: CGFloat, y: CGFloat) -> CGAffineTransform
{
var matrix = CGAffineTransformTranslate(_touchMatrix, x, y)
matrix = CGAffineTransformScale(matrix, scaleX, scaleY)
matrix = CGAffineTransformTranslate(matrix, -x, -y)
return matrix
}
/// Zooms in by 1.4, x and y are the coordinates (in pixels) of the zoom center.
public func zoomIn(x x: CGFloat, y: CGFloat) -> CGAffineTransform
{
return zoom(scaleX: 1.4, scaleY: 1.4, x: x, y: y)
}
/// Zooms out by 0.7, x and y are the coordinates (in pixels) of the zoom center.
public func zoomOut(x x: CGFloat, y: CGFloat) -> CGAffineTransform
{
return zoom(scaleX: 0.7, scaleY: 0.7, x: x, y: y)
}
/// Resets all zooming and dragging and makes the chart fit exactly it's bounds.
public func fitScreen() -> CGAffineTransform
{
_minScaleX = 1.0
_minScaleY = 1.0
return CGAffineTransformIdentity
}
/// Centers the viewport around the specified position (x-index and y-value) in the chart.
public func centerViewPort(pt pt: CGPoint, chart: ChartViewBase)
{
let translateX = pt.x - offsetLeft
let translateY = pt.y - offsetTop
let matrix = CGAffineTransformConcat(_touchMatrix, CGAffineTransformMakeTranslation(-translateX, -translateY))
refresh(newMatrix: matrix, chart: chart, invalidate: true)
}
/// call this method to refresh the graph with a given matrix
public func refresh(newMatrix newMatrix: CGAffineTransform, chart: ChartViewBase, invalidate: Bool) -> CGAffineTransform
{
_touchMatrix = newMatrix
// make sure scale and translation are within their bounds
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
chart.setNeedsDisplay()
return _touchMatrix
}
/// limits the maximum scale and X translation of the given matrix
private func limitTransAndScale(inout matrix matrix: CGAffineTransform, content: CGRect?)
{
// min scale-x is 1, max is the max CGFloat
_scaleX = min(max(_minScaleX, matrix.a), _maxScaleX)
// min scale-y is 1
_scaleY = min(max(_minScaleY, matrix.d), _maxScaleY)
var width: CGFloat = 0.0
var height: CGFloat = 0.0
if (content != nil)
{
width = content!.width
height = content!.height
}
let maxTransX = -width * (_scaleX - 1.0)
let newTransX = min(max(matrix.tx, maxTransX - _transOffsetX), _transOffsetX)
_transX = newTransX;
let maxTransY = height * (_scaleY - 1.0)
let newTransY = max(min(matrix.ty, maxTransY + _transOffsetY), -_transOffsetY)
_transY = newTransY;
matrix.tx = _transX
matrix.a = _scaleX
matrix.ty = _transY
matrix.d = _scaleY
}
public func setMinimumScaleX(xScale: CGFloat)
{
var newValue = xScale
if (newValue < 1.0)
{
newValue = 1.0
}
_minScaleX = newValue
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
}
public func setMaximumScaleX(xScale: CGFloat)
{
_maxScaleX = xScale
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
}
public func setMinMaxScaleX(minScaleX minScaleX: CGFloat, maxScaleX: CGFloat)
{
var newMin = minScaleX
if (newMin < 1.0)
{
newMin = 1.0
}
_minScaleX = newMin
_maxScaleX = maxScaleX
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
}
public func setMaximumScaleY(yScale: CGFloat)
{
_maxScaleY = yScale;
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
}
public func setMinimumScaleY(yScale: CGFloat)
{
var newValue = yScale
if (newValue < 1.0)
{
newValue = 1.0
}
_minScaleY = newValue
limitTransAndScale(matrix: &_touchMatrix, content: _contentRect)
}
public var touchMatrix: CGAffineTransform
{
return _touchMatrix
}
// MARK: - Boundaries Check
public func isInBoundsX(x: CGFloat) -> Bool
{
if (isInBoundsLeft(x) && isInBoundsRight(x))
{
return true
}
else
{
return false
}
}
public func isInBoundsY(y: CGFloat) -> Bool
{
if (isInBoundsTop(y) && isInBoundsBottom(y))
{
return true
}
else
{
return false
}
}
public func isInBounds(x x: CGFloat, y: CGFloat) -> Bool
{
if (isInBoundsX(x) && isInBoundsY(y))
{
return true
}
else
{
return false
}
}
public func isInBoundsLeft(x: CGFloat) -> Bool
{
return _contentRect.origin.x <= x ? true : false
}
public func isInBoundsRight(x: CGFloat) -> Bool
{
let normalizedX = CGFloat(Int(x * 100.0)) / 100.0
return (_contentRect.origin.x + _contentRect.size.width) >= normalizedX ? true : false
}
public func isInBoundsTop(y: CGFloat) -> Bool
{
return _contentRect.origin.y <= y ? true : false
}
public func isInBoundsBottom(y: CGFloat) -> Bool
{
let normalizedY = CGFloat(Int(y * 100.0)) / 100.0
return (_contentRect.origin.y + _contentRect.size.height) >= normalizedY ? true : false
}
/// - returns: the current x-scale factor
public var scaleX: CGFloat
{
return _scaleX
}
/// - returns: the current y-scale factor
public var scaleY: CGFloat
{
return _scaleY
}
public var transX: CGFloat
{
return _transX
}
public var transY: CGFloat
{
return _transY
}
/// if the chart is fully zoomed out, return true
public var isFullyZoomedOut: Bool
{
if (isFullyZoomedOutX && isFullyZoomedOutY)
{
return true
}
else
{
return false
}
}
/// - returns: true if the chart is fully zoomed out on it's y-axis (vertical).
public var isFullyZoomedOutY: Bool
{
if (_scaleY > _minScaleY || _minScaleY > 1.0)
{
return false
}
else
{
return true
}
}
/// - returns: true if the chart is fully zoomed out on it's x-axis (horizontal).
public var isFullyZoomedOutX: Bool
{
if (_scaleX > _minScaleX || _minScaleX > 1.0)
{
return false
}
else
{
return true
}
}
/// Set an offset in pixels that allows the user to drag the chart over it's bounds on the x-axis.
public func setDragOffsetX(offset: CGFloat)
{
_transOffsetX = offset
}
/// Set an offset in pixels that allows the user to drag the chart over it's bounds on the y-axis.
public func setDragOffsetY(offset: CGFloat)
{
_transOffsetY = offset
}
/// - returns: true if both drag offsets (x and y) are zero or smaller.
public var hasNoDragOffset: Bool
{
return _transOffsetX <= 0.0 && _transOffsetY <= 0.0 ? true : false
}
public var canZoomOutMoreX: Bool
{
return (_scaleX > _minScaleX)
}
public var canZoomInMoreX: Bool
{
return (_scaleX < _maxScaleX)
}
} | apache-2.0 | ff1c9deccfa1709f573ec6fe191d17bb | 25.530435 | 139 | 0.581414 | 4.526335 | false | false | false | false |
tamanyan/SwiftPageMenu | Sources/TabMenu/TabMenuView.swift | 1 | 19566 | //
// TabMenuView.swift
// SwiftPageMenu
//
// Created by Tamanyan on 3/9/17.
// Copyright © 2017 Tamanyan. All rights reserved.
//
import UIKit
class TabMenuView: UIView {
/// This callback function is called when tab menu item is selected
var pageItemPressedBlock: ((_ index: Int, _ direction: EMPageViewControllerNavigationDirection) -> Void)?
/// tab menu titles
var pageTabItems: [String] = [] {
didSet {
self.pageTabItemsCount = self.pageTabItems.count
self.beforeIndex = self.pageTabItems.count
self.collectionView.reloadData()
self.cursorView.isHidden = self.pageTabItems.isEmpty
}
}
/// Get whether infinite mode or not
var isInfinite: Bool {
return self.options.isInfinite
}
var layouted: Bool = false
fileprivate var options: PageMenuOptions
fileprivate var beforeIndex: Int = 0
fileprivate var currentIndex: Int = 0
fileprivate var pageTabItemsCount: Int = 0
fileprivate var shouldScrollToItem: Bool = false
fileprivate var pageTabItemsWidth: CGFloat = 0.0
fileprivate var collectionViewContentOffsetX: CGFloat?
fileprivate var currentBarViewWidth: CGFloat = 0.0
fileprivate var cellForSize: TabMenuItemCell!
fileprivate var distance: CGFloat = 0
fileprivate var contentView: UIView = {
let contentView = UIView()
contentView.backgroundColor = .clear
return contentView
}()
fileprivate lazy var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = 10
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.backgroundColor = .clear
collectionView.showsHorizontalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.contentInset = self.options.tabMenuContentInset
return collectionView
}()
fileprivate var cursorView: TabMenuItemCursor!
init(options: PageMenuOptions) {
self.options = options
super.init(frame: CGRect.zero)
self.backgroundColor = options.tabMenuBackgroundColor
// content view
addSubview(self.contentView)
self.contentView.translatesAutoresizingMaskIntoConstraints = false
self.contentView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.contentView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
self.contentView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
self.contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
// collection view
self.contentView.addSubview(self.collectionView)
self.collectionView.register(TabMenuItemCell.self, forCellWithReuseIdentifier: TabMenuItemCell.cellIdentifier)
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.collectionView.topAnchor.constraint(equalTo: self.contentView.topAnchor).isActive = true
self.collectionView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor).isActive = true
self.collectionView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor).isActive = true
self.cellForSize = TabMenuItemCell()
self.collectionView.scrollsToTop = false
self.collectionView.reloadData()
switch self.options.menuCursor {
case let .underline(barColor, _):
let underlineView = UnderlineCursorView(frame: .zero)
if self.isInfinite {
underlineView.setup(parent: self.contentView, isInfinite: true, options: self.options)
} else {
underlineView.setup(parent: self.collectionView, isInfinite: false, options: self.options)
}
underlineView.backgroundColor = barColor
self.cursorView = underlineView
case let .roundRect(rectColor, cornerRadius, _, borderWidth, borderColor):
let rectView = RoundRectCursorView(frame: .zero)
if self.isInfinite {
rectView.setup(parent: self.contentView, isInfinite: true, options: self.options)
} else {
rectView.setup(parent: self.collectionView, isInfinite: false, options: self.options)
}
rectView.backgroundColor = rectColor
rectView.layer.cornerRadius = cornerRadius
if let borderWidth = borderWidth, let borderColor = borderColor {
rectView.layer.borderWidth = borderWidth
rectView.layer.borderColor = borderColor.cgColor
}
self.cursorView = rectView
}
self.cursorView.isHidden = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: - View
extension TabMenuView {
/**
Called when you swipe in isInfinityTabPageViewController, moves the contentOffset of collectionView
- parameter index: Next Index
- parameter contentOffsetX: contentOffset.x of scrollView of isInfinityTabPageViewController
*/
func scrollCurrentBarView(_ index: Int, contentOffsetX: CGFloat, progress: CGFloat) {
var nextIndex = isInfinite ? index + self.pageTabItemsCount : index
if self.isInfinite && index == 0 && (self.beforeIndex - self.pageTabItemsCount) == self.pageTabItemsCount - 1 {
// Calculate the index at the time of transition to the first item from the last item of pageTabItems
nextIndex = pageTabItemsCount * 2
} else if self.isInfinite && (index == self.pageTabItemsCount - 1) && (self.beforeIndex - self.pageTabItemsCount) == 0 {
// Calculate the index at the time of transition from the first item of pageTabItems to the last item
nextIndex = self.pageTabItemsCount - 1
}
let currentIndexPath = IndexPath(item: self.currentIndex, section: 0)
let nextIndexPath = IndexPath(item: nextIndex, section: 0)
self.cursorView.isHidden = false
if let currentCell = collectionView.cellForItem(at: currentIndexPath) as? TabMenuItemCell, let nextCell = collectionView.cellForItem(at: nextIndexPath) as? TabMenuItemCell {
// stop scroll forcedly
self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
// hidden visible decorations
self.hiddenVisibleDecorations()
if self.collectionViewContentOffsetX == nil {
self.collectionViewContentOffsetX = self.collectionView.contentOffset.x
}
if currentBarViewWidth == 0.0 {
currentBarViewWidth = currentCell.frame.width
}
if distance == 0 {
var distance = self.distance(from: currentCell, to: nextCell)
if self.collectionView.near(edge: .left, clearance: -distance) && distance < 0 {
distance = -(self.collectionView.contentOffset.x + self.collectionView.contentInset.left)
} else if self.collectionView.near(edge: .right, clearance: distance) && distance > 0 {
distance = self.collectionView.contentSize.width - (self.collectionView.contentOffset.x + self.collectionView.bounds.width - self.collectionView.contentInset.right)
}
self.distance = distance
}
if progress > 0 {
nextCell.highlightTitle(progress: progress)
currentCell.unHighlightTitle(progress: progress)
} else {
nextCell.highlightTitle(progress: -1 * progress)
currentCell.unHighlightTitle(progress: -1 * progress)
}
let width = abs(progress) * (nextCell.frame.width - currentCell.frame.width)
let scroll = abs(progress) * self.distance
if self.isInfinite {
self.collectionView.contentOffset.x = (collectionViewContentOffsetX ?? 0) + scroll
} else {
let overflow = self.collectionView.frame.width < self.collectionView.contentSize.width
if progress >= 0 && progress < 1 {
self.cursorView.updatePosition(x: currentCell.frame.minX + progress * currentCell.frame.width)
if overflow {
self.collectionView.contentOffset.x = (collectionViewContentOffsetX ?? 0) + scroll
}
} else if progress > -1 && progress < 0 {
self.cursorView.updatePosition(x: currentCell.frame.minX + nextCell.frame.width * progress)
if overflow {
self.collectionView.contentOffset.x = (collectionViewContentOffsetX ?? 0) + scroll
}
}
}
self.cursorView.updateWidth(width: self.currentBarViewWidth + width)
} else {
// hidden visible decorations
self.hiddenVisibleDecorations()
if let _ = self.collectionView.cellForItem(at: currentIndexPath) {
// scoll to center of current cell
self.collectionView.scrollToItem(at: currentIndexPath, at: .centeredHorizontally, animated: false)
}
}
}
/**
Helper function that calculates distance between "from cell" and "to cell"
- parameter from: base cell that you would like to calculate distance
- parameter to: end cell that you would like to calculate distance
*/
fileprivate func distance(from: UICollectionViewCell, to: UICollectionViewCell) -> CGFloat {
let distanceToCenter = collectionView.bounds.midX - from.frame.midX
let distanceBetweenCells = to.frame.midX - from.frame.midX
return distanceBetweenCells - distanceToCenter
}
/**
Center the current cell after page swipe
*/
func scrollToHorizontalCenter() {
let indexPath = IndexPath(item: self.currentIndex, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
self.collectionViewContentOffsetX = self.collectionView.contentOffset.x
}
/**
Called in after the transition is complete pages in isInfinityTabPageViewController in the process of updating the current
- parameter index: Next Index
*/
func updateCurrentIndex(_ index: Int, shouldScroll: Bool, animated: Bool = false) {
deselectVisibleCells()
self.currentIndex = self.isInfinite ? index + self.pageTabItemsCount : index
let indexPath = IndexPath(item: self.currentIndex, section: 0)
moveCurrentBarView(indexPath, animated: animated, shouldScroll: shouldScroll)
}
/**
Make the tapped cell the current if isInfinite is true
- parameter index: Next IndexPath√
*/
fileprivate func updateCurrentIndexForTap(_ index: Int) {
deselectVisibleCells()
if self.isInfinite && (index < self.pageTabItemsCount) || (index >= self.pageTabItemsCount * 2) {
self.currentIndex = (index < self.pageTabItemsCount) ? index + self.pageTabItemsCount : index - self.pageTabItemsCount
self.shouldScrollToItem = true
} else {
self.currentIndex = index
}
let indexPath = IndexPath(item: index, section: 0)
moveCurrentBarView(indexPath, animated: true, shouldScroll: true)
}
/**
Move the collectionView to IndexPath of Current
- parameter indexPath: Next IndexPath
- parameter animated: true when you tap to move the isInfinityTabMenuItemCell
- parameter shouldScroll:
*/
fileprivate func moveCurrentBarView(_ indexPath: IndexPath, animated: Bool, shouldScroll: Bool) {
var targetIndexPath = indexPath
self.distance = 0
if shouldScroll {
if self.isInfinite {
targetIndexPath = IndexPath(item: indexPath.item % self.pageTabItemsCount + self.pageTabItemsCount, section: 0)
self.collectionView.scrollToItem(
at: targetIndexPath,
at: .centeredHorizontally,
animated: animated)
} else {
targetIndexPath = indexPath
self.collectionView.scrollToItem(
at: indexPath,
at: .centeredHorizontally,
animated: animated)
}
self.layoutIfNeeded()
self.collectionViewContentOffsetX = nil
self.currentBarViewWidth = 0.0
}
if let cell = collectionView.cellForItem(at: targetIndexPath) as? TabMenuItemCell {
if animated && shouldScroll {
cell.highlightTitle()
cell.isDecorationHidden = false
}
self.cursorView.updateWidth(width: cell.frame.width)
if !isInfinite {
self.cursorView.updatePosition(x: cell.frame.origin.x)
}
if !animated && shouldScroll {
cell.highlightTitle()
cell.isDecorationHidden = false
}
}
self.beforeIndex = self.currentIndex
}
/**
Touch event control of collectionView
- parameter userInteractionEnabled: UserInteractionEnabled
*/
func updateCollectionViewUserInteractionEnabled(_ userInteractionEnabled: Bool) {
collectionView.isUserInteractionEnabled = userInteractionEnabled
}
/**
Update all of the cells in the display to the unselected state
*/
fileprivate func deselectVisibleCells() {
self.collectionView
.visibleCells
.compactMap { $0 as? TabMenuItemCell }
.forEach {
$0.unHighlightTitle()
$0.isDecorationHidden = true
}
}
/**
Update all of the cells in the display to the unselected state
*/
fileprivate func hiddenVisibleDecorations() {
self.collectionView
.visibleCells
.compactMap { $0 as? TabMenuItemCell }
.forEach { $0.isDecorationHidden = true }
}
}
// MARK: - UICollectionViewDataSource
extension TabMenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.isInfinite ? self.pageTabItemsCount * 3 : self.pageTabItemsCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TabMenuItemCell.cellIdentifier, for: indexPath) as! TabMenuItemCell
self.configureCell(cell, indexPath: indexPath)
return cell
}
func configureCell(_ cell: TabMenuItemCell, indexPath: IndexPath) {
let fixedIndex = self.isInfinite ? indexPath.item % self.pageTabItemsCount : indexPath.item
cell.configure(title: self.pageTabItems[fixedIndex], options: self.options)
if fixedIndex == (self.currentIndex % self.pageTabItemsCount) {
cell.highlightTitle()
cell.isDecorationHidden = false
} else {
cell.unHighlightTitle()
cell.isDecorationHidden = true
}
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
// FIXME: Tabs are not displayed when processing is performed during introduction display
if let cell = cell as? TabMenuItemCell, self.layouted {
let fixedIndex = self.isInfinite ? indexPath.item % self.pageTabItemsCount : indexPath.item
if fixedIndex == (self.currentIndex % self.pageTabItemsCount) {
cell.isDecorationHidden = false
cell.highlightTitle()
} else {
cell.isDecorationHidden = true
cell.unHighlightTitle()
}
}
}
}
// MARK: - UIScrollViewDelegate
extension TabMenuView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let fixedIndex = self.isInfinite ? indexPath.item % self.pageTabItemsCount : indexPath.item
var direction: EMPageViewControllerNavigationDirection = .forward
if self.isInfinite == true {
if (indexPath.item < self.pageTabItemsCount) || (indexPath.item < self.currentIndex) {
direction = .reverse
}
} else {
if indexPath.item < self.currentIndex {
direction = .reverse
}
}
self.updateCollectionViewUserInteractionEnabled(false)
self.pageItemPressedBlock?(fixedIndex, direction)
self.updateCurrentIndexForTap(indexPath.item)
}
internal func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isDragging && self.isInfinite {
self.cursorView.isHidden = true
let indexPath = IndexPath(item: currentIndex, section: 0)
if let cell = collectionView.cellForItem(at: indexPath) as? TabMenuItemCell {
cell.isDecorationHidden = false
}
}
guard self.isInfinite else {
return
}
if self.pageTabItemsWidth == 0.0 {
self.pageTabItemsWidth = floor(scrollView.contentSize.width / 3.0)
}
if (scrollView.contentOffset.x <= 0.0) || (scrollView.contentOffset.x > self.pageTabItemsWidth * 2.0) {
scrollView.contentOffset.x = self.pageTabItemsWidth
}
}
internal func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
// Accept the touch event because animation is complete
self.updateCollectionViewUserInteractionEnabled(true)
guard self.isInfinite else {
return
}
let indexPath = IndexPath(item: currentIndex, section: 0)
if self.shouldScrollToItem {
// After the moved so as not to sense of incongruity, to adjust the contentOffset at the currentIndex
self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: false)
self.shouldScrollToItem = false
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension TabMenuView: UICollectionViewDelegateFlowLayout {
internal func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
self.configureCell(self.cellForSize, indexPath: indexPath)
let size = cellForSize.sizeThatFits(CGSize(width: collectionView.bounds.width, height: self.options.menuItemSize.height))
return size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
}
| mit | 5c867153bad08cffd1e482c277d18c49 | 37.892644 | 184 | 0.654756 | 5.355324 | false | false | false | false |
hadibadjian/GAlileo | reminders/Reminders/Sources/ReminderViewController.swift | 1 | 1579 | // Copyright © 2016 HB. All rights reserved.
class ReminderViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tasksTableView: UITableView!
@IBOutlet weak var titleTextField: UITextField!
let taskTableViewCellIdentifier = "TaskTableViewCell"
let addTaskTableViewCellIdentifier = "AddTaskTableViewCell"
var numberOfRows = 0
// MARK: ViewController Lifecycle
override func viewDidAppear(animated: Bool) {
tasksTableView.delegate = self
tasksTableView.dataSource = self
tasksTableView.reloadData()
}
// Mark: TableView Delegate and DataSource
func tableView(
tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return numberOfRows + 1
}
func tableView(
tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell?
switch indexPath.row {
case 0 where numberOfRows == 0, numberOfRows:
cell = tableView.dequeueReusableCellWithIdentifier(addTaskTableViewCellIdentifier)
default:
cell = tableView.dequeueReusableCellWithIdentifier(taskTableViewCellIdentifier)
}
return cell!
}
func tableView(
tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
case 0 where numberOfRows == 0, numberOfRows:
numberOfRows += 1
tableView.reloadData()
default:
break
}
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
}
import UIKit
| mit | 405b8b58faae3c44beaad285eff68745 | 24.868852 | 92 | 0.7218 | 5.696751 | false | false | false | false |
mltbnz/pixelsynth | pixelsynth/ImageFactory.swift | 1 | 1527 | //
// ImageUtil.swift
// pixelsynth
//
// Created by Malte Bünz on 22.04.17.
// Copyright © 2017 Malte Bünz. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
import MetalKit
struct ImageFactory {
// Connection to the openCV wrapper class
private let openCVWrapper: OpenCVWrapper = OpenCVWrapper()
// TODO: Observable
private var greyScaleMode: Bool = true
/**
Converts a sampleBuffer into an UIImage
- parameter sampleBuffer:The input samplebuffer
*/
public func image(from sampleBuffer: CMSampleBuffer) -> UIImage? {
guard let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return nil }
let ciImage = CIImage(cvPixelBuffer: imageBuffer)
let context = CIContext()
guard let cgImage = context.createCGImage(ciImage, from: ciImage.extent) else { return nil }
let image = UIImage(cgImage: cgImage)
guard greyScaleMode == false else {
let greyScaleImage = OpenCVWrapper.convert2GreyscaleImage(image)
return greyScaleImage
}
return image
}
/**
Returns an array holding the brightness values of a line at the center of the screen in 1D array
- parameter image: The input image
*/
public func imageBrightnessValues(from image: UIImage) -> Array<UInt8>? {
// convert uiimage to cv::Mat
let values = OpenCVWrapper.getPixelLineBrightntessValues(image)
return values as? Array<UInt8>
}
}
| mit | e83cf9c9c5672f35587fdd67c56d6529 | 30.75 | 101 | 0.676509 | 4.674847 | false | false | false | false |
Lclmyname/BookReader_Swift | BookStore/Model/Category.swift | 1 | 1197 | //
// Category.swift
// BookStore
//
// Created by apple on 16/9/28.
// Copyright © 2016年 刘朝龙. All rights reserved.
//
import Foundation
let cgArray : Array<String> = ["玄幻魔法", "武侠修真", "都市言情", "历史军事", "网游动漫", "科幻小说", "恐怖灵异", "其他类型", "排行榜", "最近阅读"]
let cgnArray: Array<Int> = [1,2,3,4,6,7,8,10,11,12]
enum BookCategory : Int {
case Fantasy_Magic = 1 /*玄幻魔法*/
case Martial_Arts_Comprehension /*武侠修真*/
case Sentimental_City /*都市言情*/
case Historical_Crossing /*历史军事*/
case Online_Animation = 6 /*网游动漫*/
case High_Fidelity /*科幻小说*/
case Supernatural_Horror /*恐怖灵异*/
case Other = 10 /*其他类型*/
case Charts /*排行榜*/
case Read /*最近阅读*/
func getString() -> String {
let index = cgnArray.index(of: self.rawValue)
return cgArray[index!]
}
}
| mit | e6ff7ab2b38b702a0c1dac1a5a7d91a0 | 33.4 | 109 | 0.472868 | 3.127273 | false | false | false | false |
masahikot/CRToastSwift | CRToastSwift/Dismisser.swift | 2 | 2519 | //
// Dismisser.swift
// CRToastSwift
//
// Copyright (c) 2015 Masahiko Tsujita <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import CRToast
/// Related to a notification presentation, and had ability to dismiss the notification.
public struct Dismisser<Notification: NotificationType> {
/// Initializes a dismisser with a presentation.
init(presentation: Presentation<Notification>) {
self.presentation = presentation
}
/// The related notification presentation.
weak var presentation: Presentation<Notification>?
/**
Dismisses the related notification.
- parameter animated: The boolean value that determines whether animate the dismissal or not. Default is true.
- parameter handler: A handler called when the notification is dismissed.
*/
public func dismiss(animated animated: Bool = true, handler: (Notification -> Void)? = nil) {
guard let presentation = self.presentation else {
debugPrint("CRToastSwift: Dismisser.dismiss() was called after presentation object had been deallocated.\nDismissal by this call will not be performed and given handler will not be invoked.")
return
}
if let handler = handler {
presentation.onDismissal(handler)
}
CRToastManager.dismissAllNotificationsWithIdentifier(presentation.identifier, animated: animated)
}
}
| mit | 456e39b510ec02e8f31f6ddb6590268f | 43.192982 | 203 | 0.726082 | 4.798095 | false | false | false | false |
OscarSwanros/swift | test/SILGen/unmanaged_ownership.swift | 2 | 3055 | // RUN: %target-swift-frontend -enable-sil-ownership -parse-stdlib -module-name Swift -emit-silgen %s | %FileCheck %s
class C {}
enum Optional<T> {
case none
case some(T)
}
precedencegroup AssignmentPrecedence {
assignment: true
associativity: right
}
struct Holder {
unowned(unsafe) var value: C
}
_ = Holder(value: C())
// CHECK-LABEL:sil hidden @_T0s6HolderV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned C, @thin Holder.Type) -> Holder
// CHECK: bb0([[T0:%.*]] : @owned $C,
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[T0]] : $C to $@sil_unmanaged C
// CHECK-NEXT: destroy_value [[T0]] : $C
// CHECK-NEXT: [[T2:%.*]] = struct $Holder ([[T1]] : $@sil_unmanaged C)
// CHECK-NEXT: return [[T2]] : $Holder
// CHECK-NEXT: } // end sil function '_T0s6HolderVABs1CC5value_tcfC'
func set(holder holder: inout Holder) {
holder.value = C()
}
// CHECK-LABEL: sil hidden @_T0s3setys6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> () {
// CHECK: bb0([[ADDR:%.*]] : @trivial $*Holder):
// CHECK: [[T0:%.*]] = function_ref @_T0s1CC{{[_0-9a-zA-Z]*}}fC
// CHECK: [[C:%.*]] = apply [[T0]](
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[WRITE]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = ref_to_unmanaged [[C]]
// CHECK-NEXT: assign [[T1]] to [[T0]]
// CHECK-NEXT: destroy_value [[C]]
// CHECK-NEXT: end_access [[WRITE]] : $*Holder
// CHECK: } // end sil function '_T0s3setys6HolderVz6holder_tF'
func get(holder holder: inout Holder) -> C {
return holder.value
}
// CHECK-LABEL: sil hidden @_T0s3gets1CCs6HolderVz6holder_tF : $@convention(thin) (@inout Holder) -> @owned C {
// CHECK: bb0([[ADDR:%.*]] : @trivial $*Holder):
// CHECK-NEXT: debug_value_addr %0 : $*Holder, var, name "holder", argno 1
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*Holder
// CHECK-NEXT: [[T0:%.*]] = struct_element_addr [[READ]] : $*Holder, #Holder.value
// CHECK-NEXT: [[T1:%.*]] = load [trivial] [[T0]] : $*@sil_unmanaged C
// CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]]
// CHECK-NEXT: [[T2_COPY:%.*]] = copy_value [[T2]]
// CHECK-NEXT: end_access [[READ]] : $*Holder
// CHECK-NEXT: return [[T2_COPY]]
func project(fn fn: () -> Holder) -> C {
return fn().value
}
// CHECK-LABEL: sil hidden @_T0s7projects1CCs6HolderVyc2fn_tF : $@convention(thin) (@owned @noescape @callee_owned () -> Holder) -> @owned C {
// CHECK: bb0([[FN:%.*]] : @owned $@noescape @callee_owned () -> Holder):
// CHECK: [[BORROWED_FN:%.*]] = begin_borrow [[FN]]
// CHECK-NEXT: [[BORROWED_FN_COPY:%.*]] = copy_value [[BORROWED_FN]]
// CHECK-NEXT: [[T0:%.*]] = apply [[BORROWED_FN_COPY]]()
// CHECK-NEXT: [[T1:%.*]] = struct_extract [[T0]] : $Holder, #Holder.value
// CHECK-NEXT: [[T2:%.*]] = unmanaged_to_ref [[T1]]
// CHECK-NEXT: [[COPIED_T2:%.*]] = copy_value [[T2]]
// CHECK-NEXT: end_borrow [[BORROWED_FN]] from [[FN]]
// CHECK-NEXT: destroy_value [[FN]]
// CHECK-NEXT: return [[COPIED_T2]]
| apache-2.0 | 6fb41e1bcf348e702e213a1e4ef5fe95 | 42.642857 | 142 | 0.596727 | 2.917861 | false | false | false | false |
LoopKit/LoopKit | LoopKit/Extensions/OutputStream.swift | 1 | 1050 | //
// OutputStream.swift
// LoopKit
//
// Created by Darin Krauss on 8/28/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import Foundation
extension OutputStream {
func write(_ string: String) throws {
if let streamError = streamError {
throw streamError
}
let bytes = [UInt8](string.utf8)
write(bytes, maxLength: bytes.count)
if let streamError = streamError {
throw streamError
}
}
func write(_ data: Data) throws {
if let streamError = streamError {
throw streamError
}
if data.isEmpty {
return
}
_ = data.withUnsafeBytes { (unsafeRawBuffer: UnsafeRawBufferPointer) -> UInt8 in
if let unsafe = unsafeRawBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self) {
write(unsafe, maxLength: unsafeRawBuffer.count)
}
return 0
}
if let streamError = streamError {
throw streamError
}
}
}
| mit | 2ef9f61d68fded60441492fcda4dcf57 | 25.225 | 94 | 0.57388 | 4.746606 | false | false | false | false |
Egibide-DAM/swift | 02_ejemplos/07_ciclo_vida/01_inicializacion/12_ejemplo_inicializadores.playground/Contents.swift | 1 | 1242 | class Food {
var name: String
init(name: String) {
self.name = name
}
convenience init() {
self.init(name: "[Unnamed]")
}
}
let namedMeat = Food(name: "Bacon")
// namedMeat's name is "Bacon"
let mysteryMeat = Food()
// mysteryMeat's name is "[Unnamed]"
class RecipeIngredient: Food {
var quantity: Int
init(name: String, quantity: Int) {
self.quantity = quantity
super.init(name: name)
}
override convenience init(name: String) {
self.init(name: name, quantity: 1)
}
}
let oneMysteryItem = RecipeIngredient()
let oneBacon = RecipeIngredient(name: "Bacon")
let sixEggs = RecipeIngredient(name: "Eggs", quantity: 6)
class ShoppingListItem: RecipeIngredient {
var purchased = false
var description: String {
var output = "\(quantity) x \(name)"
output += purchased ? " ✔" : " ✘"
return output
}
}
var breakfastList = [
ShoppingListItem(),
ShoppingListItem(name: "Bacon"),
ShoppingListItem(name: "Eggs", quantity: 6),
]
breakfastList[0].name = "Orange juice"
breakfastList[0].purchased = true
for item in breakfastList {
print(item.description)
}
// 1 x Orange juice ✔
// 1 x Bacon ✘
// 6 x Eggs ✘
| apache-2.0 | 0cf8820592f0295581f3b6c3c37df3e7 | 22.245283 | 57 | 0.632305 | 3.688623 | false | false | false | false |
ztyjr888/WeChat | WeChat/Contact/Others/Add Friends/ContactAddFriendsTableViewController.swift | 1 | 5622 | //
// ContactAddFriendsTableViewController.swift
// WeChat
//
// Created by Smile on 16/2/6.
// Copyright © 2016年 [email protected]. All rights reserved.
//
import UIKit
//添加朋友页面
class ContactAddFriendsTableViewController: WeChatTableViewNormalController,WeChatSearchBarDelegate {
@IBOutlet weak var searchView: UIView!
@IBOutlet weak var myWeChatNumLabel: UILabel!
@IBOutlet weak var twoDimeImageView: UIImageView!
var twoDimeView:UIView?
override func viewDidLoad() {
super.viewDidLoad()
initFrame()
}
override func viewWillAppear(animated: Bool) {
self.navigationController?.navigationBar.hidden = false
}
func initFrame(){
createFooterForTableView()
tableView.separatorStyle = .None
//设置第二个tableView Cell背景色和tableView一样
let indexPath = NSIndexPath(forRow: 1, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.backgroundColor = getBackgroundColor()
self.navigationItem.title = "添加朋友"
tableView.backgroundColor = getBackgroundColor()
//画分割线
drawLastLine()
searchView.addGestureRecognizer(WeChatUITapGestureRecognizer(target:self,action: "searchViewTap:"))
twoDimeImageView.addGestureRecognizer(WeChatUITapGestureRecognizer(target:self,action: "twoDimeImageViewTap:"))
createSkyView()
}
//MAKRS: 创建skyView
func createSkyView(){
if skyView == nil {
skyView = ContactSkyView(frame: self.view.frame)
skyView?.exitBtn.addTarget(self, action: "exitSky", forControlEvents: .TouchUpInside)
}
}
//MARKS: 创建显示图片
func createTwoDimeView(){
if twoDimeView != nil {
self.parentViewController?.parentViewController!.view.addSubview(twoDimeView!)
return
}
twoDimeView = MyTwoDime(frame: self.view.frame, bgColor: nil)
twoDimeView!.addGestureRecognizer(WeChatUITapGestureRecognizer(target:self,action: "twoDimeViewTap:"))
self.parentViewController?.parentViewController!.view.addSubview(twoDimeView!)
}
//MARKS: 二维码点击事件
func twoDimeImageViewTap(view:WeChatUITapGestureRecognizer){
createTwoDimeView()
}
//MARKS: 弹出二维码点击事件
func twoDimeViewTap(view:WeChatUITapGestureRecognizer){
if twoDimeView != nil {
twoDimeView?.removeFromSuperview()
}
}
//MARKS:画分割线
func drawLastLine(){
for(var j = 0;j < tableView.numberOfRowsInSection(0);j++){
if j == 1 {
continue
}
let indexPath = NSIndexPath(forRow: j, inSection: 0)
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.selectionStyle = .None
if cell == nil {
continue
}
if j == 0 || j == 2 {
cell!.layer.addSublayer(WeChatDrawView().drawLineAtLast(0,height: 0))
if j == 0 {
cell!.layer.addSublayer(WeChatDrawView().drawLineAtLast(0,height: cell!.frame.height))
} else {
cell!.layer.addSublayer(WeChatDrawView().drawLineAtLast(20,height: cell!.frame.height))
}
} else {
if j == (tableView.numberOfRowsInSection(0) - 1) {
cell!.layer.addSublayer(WeChatDrawView().drawLineAtLast(0,height: cell!.frame.height))
}else {
cell!.layer.addSublayer(WeChatDrawView().drawLineAtLast(20,height: cell!.frame.height))
}
}
}
}
//MARKS:searchView点击事件
func searchViewTap(view:WeChatUITapGestureRecognizer){
let customView = ContactCustomSearchView()
customView.index = 1
customView.sessions = ContactModel().contactSesion
customView.delegate = self
customView.iscreateThreeArc = false
customView.isCreateSpeakImage = false
self.navigationController?.pushViewController(customView, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
//MARKS: 设置背景色,用于tableviewfooter一致
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//let _section = tableView.headerViewForSection(section)
let view = UIView()
view.backgroundColor = getBackgroundColor()
return view
}
//MARKS: 去掉tableview底部空白
func createFooterForTableView(){
let view = UIView()
view.backgroundColor = getBackgroundColor()
tableView.tableFooterView = view
}
//MARKS:雷达退出事件
func exitSky(){
if skyView != nil {
skyView?.removeFromSuperview()
}
}
var skyView:ContactSkyView?
//MARKS: tableView cell选中事件
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == 2 {
if self.skyView == nil {
createSkyView()
}
self.parentViewController?.parentViewController!.view.addSubview(self.skyView!)
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: false)//取消选中
}
}
| apache-2.0 | 0d18d2425a63fa8d24660c738c7fde67 | 31.616766 | 119 | 0.615385 | 4.951818 | false | false | false | false |
bartoszj/Mallet | LLDB Test Application/LLDB iOS App Swift Tests/CoreGraphicsSwiftTests.swift | 1 | 1777 | //
// CoreGraphicsSwiftTests.swift
// LLDB Test Application
//
// Created by Bartosz Janda on 01.02.2015.
// Copyright (c) 2015 Bartosz Janda. All rights reserved.
//
import UIKit
import XCTest
class CoreGraphicsSwiftTests: SharedSwiftTestCase {
// MAKR: - Setup
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testTrue() {
XCTAssertTrue(true)
}
// MARK: - CGPoint
// func testCGPoint() {
// let point = CGPoint(x: 1, y: 2)
// self.compareVariable(point, type: "CGPoint", summary: "(x = 1, y = 2)")
// }
// MARK: - CGSize
// func testCGSize() {
// let size = CGSize(width: 3, height: 4)
// self.compareVariable(size, type: "CGSize", summary: "(width = 3, height = 4)")
// }
// MARK: - CGRect
// func testCGRect() {
// let rect = CGRect(x: 6, y: 7, width: 8, height: 9)
// self.compareVariable(rect, type: "CGRect", summary: "(origin = (x = 6, y = 7), size = (width = 8, height = 9))")
// }
// MARK: - CGVector
// func testCGVector() {
// let vector = CGVector(dx: 3, dy: 5)
// self.compareVariable(vector, type: "CGVector", summary: "(dx = 3, dy = 5)")
// }
// MARK: - CGAffineTransform
// func testCGAffineTransform() {
// let transofrm = CGAffineTransform(a: 2, b: 3, c: 4, d: 5, tx: 6, ty: 7)
// self.compareVariable(transofrm, type: "CGAffineTransform", summary: "([2, 3], [4, 5], [6, 7])")
// }
}
| mit | 59b7f63a9b0e3568afdcdd2cdf13b4a6 | 29.637931 | 122 | 0.570625 | 3.525794 | false | true | false | false |
anthonyliao/sudoku-solver-ios | sudoku-solver-ios/sudoku-solver-ios/Classes/Models/SolverBeta.swift | 1 | 9832 | //
// Solver.swift - given a size of puzzle, will solve puzzle
// sudoku-solver-ios
//
// Created by ANTHONY on 10/30/14.
// Copyright (c) 2014 ANTHONY. All rights reserved.
//
import Foundation
class SolverBeta: Printable {
//How many squares across in the grid
let gridSize: Int
//How many squares across for a section
let sectionSize: Int
//A 2x2 representation of the grid and possible values
//Given a 2x2 grid:
// | 123456789 123456789 |
// | 3 6 |
//Can be represented as [[123456789], [123456789], [3], [6]]
var squares: [[Int]]
//For a given square, list of squares (indices in squares array) that are in the row, col, or box
var peers: [[Int]]
var numSolutions: Int = 0
convenience init(str: String) {
var array: [Int] = [Int]()
for (i,j) in enumerate(str) {
array.append(String(j).toInt()!)
}
self.init(initialIntArray: array)
}
init(initialIntArray: [Int]) {
self.gridSize = Int(sqrt(Float(initialIntArray.count)))
self.sectionSize = Int(sqrt(Float(gridSize)))
self.squares = [[Int]]()
for var i = 0; i < initialIntArray.count; i++ {
if initialIntArray[i] == 0 {
var solutions = [Int]()
solutions += 1...self.gridSize
squares.insert(solutions, atIndex: i)
} else {
squares.insert([initialIntArray[i]], atIndex: i)
}
}
LOG.info("squares - \(self.squares)")
self.peers = [[Int]]()
for var i = 0; i < initialIntArray.count; i++ {
var peersForI: [Int] = []
//row peers
for var j = 0; j < self.gridSize; j++ {
var peer = ((i / self.gridSize) * self.gridSize) + (j)
//dont add self
if i != peer && !contains(peersForI, peer) {
peersForI.append(peer)
}
}
//col peers
for var j = 0; j < self.gridSize; j++ {
var peer = (i % self.gridSize) + (self.gridSize * j)
if i != peer && !contains(peersForI, peer) {
peersForI.append(peer)
}
}
//box peers
for var j = 0; j < self.gridSize * self.gridSize; j++ {
var iRow: Int = i / self.gridSize
var iCol: Int = i % self.gridSize
var jRow: Int = j / self.gridSize
var jCol: Int = j % self.gridSize
var iBoxRow: Int = iRow / self.sectionSize
var iBoxCol: Int = iCol / self.sectionSize
var jBoxRow: Int = jRow / self.sectionSize
var jBoxCol: Int = jCol / self.sectionSize
if i != j && !contains(peersForI, j) && iBoxRow == jBoxRow && iBoxCol == jBoxCol {
peersForI.append(j)
}
}
self.peers.append(peersForI)
}
LOG.info("peers - \(self.peers)")
LOG.info("\(self.description)")
}
init(initial2DArray: [[Int]], peers: [[Int]]) {
var start = NSDate()
self.gridSize = Int(sqrt(Float(initial2DArray.count)))
self.sectionSize = Int(sqrt(Float(gridSize)))
self.squares = initial2DArray
self.peers = peers
var end = NSDate().timeIntervalSinceDate(start)
LOG.info("init duration - \(end)\n\(self.description)")
}
//Return the current grid in a pretty format
var description: String {
get {
var str: String = "\n"
var maxSquareSize = 1
for square in squares {
maxSquareSize = max(maxSquareSize, square.count)
}
var sectionSeparator = " | "
var numberSeparator = " "
var newLine = "\n"
var dash = "-"
var padding = " "
var horizontalSectionSeparatorSize = maxSquareSize*self.gridSize + self.gridSize*2*countElements(numberSeparator) + (self.sectionSize+1)*countElements(sectionSeparator)
for var i = 0; i < squares.count; i++ {
//Add section separator after each section
if i != 0 && i % self.sectionSize == 0 {
str += sectionSeparator
}
//New line at end of grid
if i != 0 && i % self.gridSize == 0 {
str += newLine
//Horizontal section not upcoming
if i % (self.sectionSize * self.gridSize) != 0 {
str += sectionSeparator
}
}
//Add horizontal section separator after each section
if i % (self.sectionSize * self.gridSize) == 0 {
for var j = 0; j < horizontalSectionSeparatorSize; j++ {
str += dash
}
str += newLine + sectionSeparator
}
str += numberSeparator
//Add possible values
for var j = 0; j < squares[i].count; j++ {
str += String(squares[i][j])
}
//Pad if short
for var j = squares[i].count; j < maxSquareSize; j++ {
str += padding
}
str += numberSeparator
}
//Final section separator
str += sectionSeparator
str += newLine
for var j = 0; j < horizontalSectionSeparatorSize; j++ {
str += dash
}
str += newLine
return str
}
}
func getCopy() -> [[Int]] {
var start = NSDate()
var squaresCopy = [[Int]]()
for var i = 0; i < self.squares.count; i++ {
squaresCopy.insert([], atIndex: i)
for var j = 0; j < self.squares[i].count; j++ {
squaresCopy[i].append(self.squares[i][j])
}
}
var end = NSDate().timeIntervalSinceDate(start)
LOG.info("duration - \(end)")
return squaresCopy
}
func solve() -> ([[Int]])! {
//look at solved entries in original puzzle, invalidate these values from peers
var original = self.getCopy()
var start = NSDate()
for var i = 0; i < original.count; i++ {
var values = original[i]
if values.count == 1 {
self.invalidatePeers(i, value: values[0])
}
}
var end = NSDate().timeIntervalSinceDate(start)
LOG.info("cover in \(end) - \(self.description)")
var start3 = NSDate()
var idx = self.findSquareWithSmallestPossibleValues()
var end3 = NSDate().timeIntervalSinceDate(start3)
LOG.info("smallest possible value find took \(end3)")
if idx != -1 {
for var i = 0; i < self.squares[idx].count; i++ {
var copy = self.getCopy()
var start4 = NSDate()
var value = [copy[idx][i]]
copy[idx] = value
var end4 = NSDate().timeIntervalSinceDate(start4)
LOG.info("picked \(idx) to be \(value) in \(end4)")
var solver = SolverBeta(initial2DArray: copy, peers: peers)
var solution = solver.solve()
numSolutions += solver.numSolutions
if solution != nil {
self.squares = solution
break
} else {
LOG.info("picked \(idx) to be \(value), invalid - \(self.numSolutions)")
}
}
}
if numSolutions == 0 {
numSolutions++
}
var start2 = NSDate()
if isValidSolution() {
LOG.info("solution - \(self.description)")
return self.getCopy()
}
var end2 = NSDate().timeIntervalSinceDate(start2)
LOG.info("validating took \(end2)")
return nil
}
func invalidatePeers(square: Int, value: Int) {
//remove value from square's peers list of possible values
var peersForSquare = self.peers[square]
for peer in peersForSquare {
var numPossibleValuesBefore = self.squares[peer].count
self.squares[peer] = self.squares[peer].filter({ (possibleValue: Int) -> Bool in
return possibleValue != value
})
var numPossibleValuesAfter = self.squares[peer].count
//invalid solution
if numPossibleValuesAfter == 0 {
break
}
//if a peer narrowed possible values down to 1 value, invalidate that value from peer's peer
if numPossibleValuesBefore > 1 && numPossibleValuesAfter == 1 {
self.invalidatePeers(peer, value: self.squares[peer][0])
}
}
}
func findSquareWithSmallestPossibleValues() -> Int {
var minSize = self.gridSize
var minIndex = -1
for (i, j) in enumerate(self.squares) {
if j.count != 1 && j.count < minSize {
minIndex = i
minSize = j.count
}
}
return minIndex
}
func isValidSolution() -> Bool {
for square in self.squares {
if square.count != 1 {
return false
}
}
return true
}
} | mit | ea75572251030cdb8db085bbbb77d618 | 34.243728 | 180 | 0.481387 | 4.547641 | false | false | false | false |
cardstream/iOS-SDK | cardstream-ios-sdk/CryptoSwift-0.7.2/Sources/CryptoSwift/MD5.swift | 7 | 6363 | //
// MD5.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 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.
//
public final class MD5: DigestType {
static let blockSize: Int = 64
static let digestLength: Int = 16 // 128 / 8
fileprivate static let hashInitialValue: Array<UInt32> = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476]
fileprivate var accumulated = Array<UInt8>()
fileprivate var processedBytesTotalCount: Int = 0
fileprivate var accumulatedHash: Array<UInt32> = MD5.hashInitialValue
/** specifies the per-round shift amounts */
private let s: Array<UInt32> = [
7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22,
5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23,
6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
]
/** binary integer part of the sines of integers (Radians) */
private let k: Array<UInt32> = [
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee,
0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501,
0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821,
0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa,
0xd62f105d, 0x2441453, 0xd8a1e681, 0xe7d3fbc8,
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed,
0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a,
0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70,
0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x4881d05,
0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039,
0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1,
0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391,
]
public init() {
}
public func calculate(for bytes: Array<UInt8>) -> Array<UInt8> {
do {
return try update(withBytes: bytes.slice, isLast: true)
} catch {
fatalError()
}
}
// mutating currentHash in place is way faster than returning new result
fileprivate func process(block chunk: ArraySlice<UInt8>, currentHash: inout Array<UInt32>) {
assert(chunk.count == 16 * 4)
// Initialize hash value for this chunk:
var A: UInt32 = currentHash[0]
var B: UInt32 = currentHash[1]
var C: UInt32 = currentHash[2]
var D: UInt32 = currentHash[3]
var dTemp: UInt32 = 0
// Main loop
for j in 0..<k.count {
var g = 0
var F: UInt32 = 0
switch j {
case 0...15:
F = (B & C) | ((~B) & D)
g = j
break
case 16...31:
F = (D & B) | (~D & C)
g = (5 * j + 1) % 16
break
case 32...47:
F = B ^ C ^ D
g = (3 * j + 5) % 16
break
case 48...63:
F = C ^ (B | (~D))
g = (7 * j) % 16
break
default:
break
}
dTemp = D
D = C
C = B
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15 and get M[g] value
let gAdvanced = g << 2
var Mg = UInt32(chunk[chunk.startIndex &+ gAdvanced])
Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 1]) << 8
Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 2]) << 16
Mg |= UInt32(chunk[chunk.startIndex &+ gAdvanced &+ 3]) << 24
B = B &+ rotateLeft(A &+ F &+ k[j] &+ Mg, by: s[j])
A = dTemp
}
currentHash[0] = currentHash[0] &+ A
currentHash[1] = currentHash[1] &+ B
currentHash[2] = currentHash[2] &+ C
currentHash[3] = currentHash[3] &+ D
}
}
extension MD5: Updatable {
public func update(withBytes bytes: ArraySlice<UInt8>, isLast: Bool = false) throws -> Array<UInt8> {
accumulated += bytes
if isLast {
let lengthInBits = (processedBytesTotalCount + accumulated.count) * 8
let lengthBytes = lengthInBits.bytes(totalBytes: 64 / 8) // A 64-bit representation of b
// Step 1. Append padding
bitPadding(to: &accumulated, blockSize: MD5.blockSize, allowance: 64 / 8)
// Step 2. Append Length a 64-bit representation of lengthInBits
accumulated += lengthBytes.reversed()
}
var processedBytes = 0
for chunk in accumulated.batched(by: MD5.blockSize) {
if isLast || (accumulated.count - processedBytes) >= MD5.blockSize {
process(block: chunk, currentHash: &accumulatedHash)
processedBytes += chunk.count
}
}
accumulated.removeFirst(processedBytes)
processedBytesTotalCount += processedBytes
// output current hash
var result = Array<UInt8>()
result.reserveCapacity(MD5.digestLength)
for hElement in accumulatedHash {
let hLE = hElement.littleEndian
result += Array<UInt8>(arrayLiteral: UInt8(hLE & 0xff), UInt8((hLE >> 8) & 0xff), UInt8((hLE >> 16) & 0xff), UInt8((hLE >> 24) & 0xff))
}
// reset hash value for instance
if isLast {
accumulatedHash = MD5.hashInitialValue
}
return result
}
}
| gpl-3.0 | 355f4b8d902e0934c9394e8d27b2f102 | 37.071856 | 217 | 0.586033 | 3.52439 | false | false | false | false |
taikhoanthunghiemcuatoi/mac | swift1/CollectionViewDemo1/CollectionViewDemo1/FlickrPhotosCollectionViewController.swift | 1 | 8014 | //
// FlickrPhotosCollectionViewController.swift
// CollectionViewDemo1
//
// Created by MTV on 12/26/15.
// Copyright (c) 2015 MTV. All rights reserved.
//
import UIKit
class FlickrPhotosCollectionViewController: UICollectionViewController, UITextFieldDelegate, UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "Cell"
private let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0);
private var searches = [FlickrSearchResults]();
private let flickr = Flickr();
override func viewDidLoad() {
print("calling viewDidLoad");
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Register cell classes
//self.collectionView!.registerClass(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// 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: UICollectionViewDataSource
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
//#warning Incomplete method implementation -- Return the number of sections
print("calling numberOfSectionsInCollectionView");
return searches.count;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//#warning Incomplete method implementation -- Return the number of items in the section
print("calling numberOfItemsInSection");
return searches[section].searchResults.count;
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
print("calling cellForItemAtIndexPath");
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! FlickrPhotoViewCell
// Configure the cell
let flickrPhoto = photoForIndexPath(indexPath);
cell.backgroundColor = UIColor.blackColor();
cell.imageView.image = flickrPhoto.thumbnail;
return cell
}
// MARK: UICollectionViewDelegate
/*
// Uncomment this method to specify if the specified item should be highlighted during tracking
override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
*/
var largePhotoIndexPath : NSIndexPath?{
didSet{
var indexPaths = [NSIndexPath]();
if (largePhotoIndexPath != nil){
indexPaths.append(largePhotoIndexPath!);
}
collectionView?.performBatchUpdates({self.collectionView?.reloadItemsAtIndexPaths(indexPaths)
return
}){
completed in
if (self.largePhotoIndexPath != nil){
print("calling scrollToItemAtIndexPath");
self.collectionView?.scrollToItemAtIndexPath(self.largePhotoIndexPath!, atScrollPosition: .CenteredHorizontally, animated: true);
}
}
}
}
// Uncomment this method to specify if the specified item should be selected
override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
print("calling shouldSelectItemAtIndexPath");
print("selected item at index path \(indexPath)");
if (largePhotoIndexPath == indexPath){
largePhotoIndexPath = nil;
}else{
largePhotoIndexPath = indexPath;
}
return false;
}
/*
// Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
return false
}
override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
}
*/
func photoForIndexPath(indexPath : NSIndexPath) -> FlickrPhoto{
return searches[indexPath.section].searchResults[indexPath.row];
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// 1
let activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
textField.addSubview(activityIndicator)
activityIndicator.frame = textField.bounds
activityIndicator.startAnimating()
flickr.searchFlickrForTerm(textField.text!) {
results, error in
//2
activityIndicator.removeFromSuperview()
if error != nil {
print("Error searching : \(error)")
}
if results != nil {
//3
print("Found \(results!.searchResults.count) matching \(results!.searchTerm)")
self.searches.insert(results!, atIndex: 0)
//4
self.collectionView?.reloadData()
}
}
textField.text = nil
textField.resignFirstResponder()
return true
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
print("calling sizeForItemAtIndexPath");
let flickrPhoto = photoForIndexPath(indexPath)
// New code
if indexPath == largePhotoIndexPath {
var size = collectionView.bounds.size
size.height -= topLayoutGuide.length
size.height -= (sectionInsets.top + sectionInsets.right)
size.width -= (sectionInsets.left + sectionInsets.right)
return flickrPhoto.sizeToFillWidthOfSize(size)
}
// Previous code
if var size = flickrPhoto.thumbnail?.size {
size.width += 10
size.height += 10
return size
}
return CGSize(width: 100, height: 100)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return sectionInsets
}
override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
print("calling viewForSupplementaryElementOfKind");
//1
switch kind {
//2
case UICollectionElementKindSectionHeader:
//3
let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind,withReuseIdentifier: "FlickrPhotoHeaderView",forIndexPath: indexPath) as! FlickrPhotoHeaderView
headerView.label.text = searches[indexPath.section].searchTerm
return headerView
default:
//4
assert(false, "Unexpected element kind")
}
}
}
| apache-2.0 | 1a01e25adb5184867455ddbe4e48406f | 38.477833 | 185 | 0.666209 | 6.380573 | false | false | false | false |
Ferrari-lee/firefox-ios | Client/Application/AppDelegate.swift | 8 | 12079 | /* 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 Shared
import Storage
import AVFoundation
import XCGLogger
import Breakpad
private let log = Logger.browserLogger
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var browserViewController: BrowserViewController!
var rootViewController: UINavigationController!
weak var profile: BrowserProfile?
var tabManager: TabManager!
let appVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Set the Firefox UA for browsing.
setUserAgent()
// Start the keyboard helper to monitor and cache keyboard state.
KeyboardHelper.defaultHelper.startObserving()
// Create a new sync log file on cold app launch
Logger.syncLogger.newLogWithDate(NSDate())
let profile = getProfile(application)
// Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented.
setUpWebServer(profile)
do {
// for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
} catch _ {
log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar")
}
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
let defaultRequest = NSURLRequest(URL: UIConstants.AboutHomeURL)
self.tabManager = TabManager(defaultNewTabRequest: defaultRequest, profile: profile)
browserViewController = BrowserViewController(profile: profile, tabManager: self.tabManager)
// Add restoration class, the factory that will return the ViewController we
// will restore with.
browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self)
browserViewController.restorationClass = AppDelegate.self
browserViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController = UINavigationController(rootViewController: browserViewController)
rootViewController.automaticallyAdjustsScrollViewInsets = false
rootViewController.delegate = self
rootViewController.navigationBarHidden = true
self.window!.rootViewController = rootViewController
self.window!.backgroundColor = UIConstants.AppBackgroundColor
activeCrashReporter = BreakpadCrashReporter(breakpadInstance: BreakpadController.sharedInstance())
configureActiveCrashReporter(profile.prefs.boolForKey("crashreports.send.always"))
NSNotificationCenter.defaultCenter().addObserverForName(FSReadingListAddReadingListItemNotification, object: nil, queue: nil) { (notification) -> Void in
if let userInfo = notification.userInfo, url = userInfo["URL"] as? NSURL {
let title = (userInfo["Title"] as? String) ?? ""
profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.currentDevice().name)
}
}
// check to see if we started 'cos someone tapped on a notification.
if let localNotification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as? UILocalNotification {
viewURLInNewTab(localNotification)
}
return true
}
/**
* We maintain a weak reference to the profile so that we can pause timed
* syncs when we're backgrounded.
*
* The long-lasting ref to the profile lives in BrowserViewController,
* which we set in application:willFinishLaunchingWithOptions:.
*
* If that ever disappears, we won't be able to grab the profile to stop
* syncing... but in that case the profile's deinit will take care of things.
*/
func getProfile(application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let p = BrowserProfile(localName: "profile", app: application)
self.profile = p
return p
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
self.window!.makeKeyAndVisible()
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
if let components = NSURLComponents(URL: url, resolvingAgainstBaseURL: false) {
if components.scheme != "firefox" && components.scheme != "firefox-x-callback" {
return false
}
var url: String?
for item in (components.queryItems ?? []) as [NSURLQueryItem] {
switch item.name {
case "url":
url = item.value
default: ()
}
}
if let url = url,
newURL = NSURL(string: url.unescape()) {
self.browserViewController.openURLInNewTab(newURL)
return true
}
}
return false
}
// We sync in the foreground only, to avoid the possibility of runaway resource usage.
// Eventually we'll sync in response to notifications.
func applicationDidBecomeActive(application: UIApplication) {
self.profile?.syncManager.beginTimedSyncs()
// We could load these here, but then we have to futz with the tab counter
// and making NSURLRequests.
self.browserViewController.loadQueuedTabs()
}
func applicationDidEnterBackground(application: UIApplication) {
self.profile?.syncManager.endTimedSyncs()
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTaskWithExpirationHandler { _ in
log.warning("Running out of background time, but we have a profile shutdown pending.")
application.endBackgroundTask(taskId)
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.profile?.shutdown()
application.endBackgroundTask(taskId)
}
}
private func setUpWebServer(profile: Profile) {
let server = WebServer.sharedInstance
ReaderModeHandlers.register(server, profile: profile)
ErrorPageHelper.register(server)
AboutHomeHandler.register(server)
AboutLicenseHandler.register(server)
SessionRestoreHandler.register(server)
server.start()
}
private func setUserAgent() {
// Note that we use defaults here that are readable from extensions, so they
// can just used the cached identifier.
let defaults = NSUserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
let firefoxUA = UserAgent.defaultUserAgent(defaults)
// Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader.
// This only needs to be done once per runtime.
defaults.registerDefaults(["UserAgent": firefoxUA])
FaviconFetcher.userAgent = firefoxUA
SDWebImageDownloader.sharedDownloader().setValue(firefoxUA, forHTTPHeaderField: "User-Agent")
// Record the user agent for use by search suggestion clients.
SearchViewController.userAgent = firefoxUA
}
func application(application: UIApplication, handleActionWithIdentifier identifier: String?, forLocalNotification notification: UILocalNotification, completionHandler: () -> Void) {
if let actionId = identifier {
if let action = SentTabAction(rawValue: actionId) {
viewURLInNewTab(notification)
switch(action) {
case .Bookmark:
addBookmark(notification)
break
case .ReadingList:
addToReadingList(notification)
break
default:
break
}
} else {
print("ERROR: Unknown notification action received")
}
} else {
print("ERROR: Unknown notification received")
}
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
viewURLInNewTab(notification)
}
private func viewURLInNewTab(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
browserViewController.openURLInNewTab(urlToOpen)
}
}
}
private func addBookmark(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
browserViewController.addBookmark(alertURL, title: title)
}
}
private func addToReadingList(notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
if let urlToOpen = NSURL(string: alertURL) {
NSNotificationCenter.defaultCenter().postNotificationName(FSReadingListAddReadingListItemNotification, object: self, userInfo: ["URL": urlToOpen, "Title": title])
}
}
}
}
// MARK: - Root View Controller Animations
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(navigationController: UINavigationController,
animationControllerForOperation operation: UINavigationControllerOperation,
fromViewController fromVC: UIViewController,
toViewController toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.Push {
return BrowserToTrayAnimator()
} else if operation == UINavigationControllerOperation.Pop {
return TrayToBrowserAnimator()
} else {
return nil
}
}
}
var activeCrashReporter: CrashReporter?
func configureActiveCrashReporter(optedIn: Bool?) {
if let reporter = activeCrashReporter {
configureCrashReporter(reporter, optedIn: optedIn)
}
}
public func configureCrashReporter(reporter: CrashReporter, optedIn: Bool?) {
let configureReporter: () -> () = {
let addUploadParameterForKey: String -> Void = { key in
if let value = NSBundle.mainBundle().objectForInfoDictionaryKey(key) as? String {
reporter.addUploadParameter(value, forKey: key)
}
}
addUploadParameterForKey("AppID")
addUploadParameterForKey("BuildID")
addUploadParameterForKey("ReleaseChannel")
addUploadParameterForKey("Vendor")
}
if let optedIn = optedIn {
// User has explicitly opted-in for sending crash reports. If this is not true, then the user has
// explicitly opted-out of crash reporting so don't bother starting breakpad or stop if it was running
if optedIn {
reporter.start(true)
configureReporter()
reporter.setUploadingEnabled(true)
} else {
reporter.stop()
}
}
// We haven't asked the user for their crash reporting preference yet. Log crashes anyways but don't send them.
else {
reporter.start(true)
configureReporter()
}
}
| mpl-2.0 | 23d159cc706e069fe8f1a838b572af25 | 41.382456 | 185 | 0.671413 | 5.838086 | false | false | false | false |
shenyuan000/TextField-InputView | TextField+InputView/ListTVC.swift | 1 | 1991 | //
// ListTVC.swift
// TextField+InputView
//
// Created by 成林 on 15/8/24.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import UIKit
class ListTVC: UITableViewController {
let rid = "rid"
let dataList = ["单列+原始值","单列+模型值","模型多选","更多功能请期待"]
}
extension ListTVC{
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = (tableView.dequeueReusableCellWithIdentifier(rid) as? UITableViewCell) ?? UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: rid)
cell.textLabel?.text = dataList[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.row == self.dataList.count - 1 {return}
var vc: UIViewController = UIViewController()
if indexPath.row == 0{
vc = OneStringVC(nibName:"OneStringVC",bundle:nil)
}else if indexPath.row == 1 {
vc = OneModelVC(nibName:"OneModelVC",bundle:nil)
}else if indexPath.row == 2{
vc = MulSelVC(nibName:"MulSelVC",bundle:nil)
}
vc.title = dataList[indexPath.row]
self.navigationController?.pushViewController(vc, animated: true)
}
}
| mit | e1056e5ab4f19d96590b85275e4e9e62 | 25.175676 | 167 | 0.610738 | 4.966667 | false | false | false | false |
1yvT0s/Goldengate | Goldengate/NSTimer.swift | 2 | 1364 | import Foundation
typealias Block = () -> ()
class NSTimerActor {
var block: Block
init(block: Block) {
self.block = block
}
dynamic func fire() {
block()
}
}
// FIXME: `make` class functions are a workaround for a crasher when using convenience initializers with Swift 1.1
extension NSTimer {
class func make(intervalFromNow: NSTimeInterval, _ block: Block) -> NSTimer {
let actor = NSTimerActor(block: block)
return self.init(timeInterval: intervalFromNow, target: actor, selector: "fire", userInfo: nil, repeats: false)
}
class func make(every interval: NSTimeInterval, _ block: Block) -> NSTimer {
let actor = NSTimerActor(block: block)
return self.init(timeInterval: interval, target: actor, selector: "fire", userInfo: nil, repeats: true)
}
class func schedule(intervalFromNow: NSTimeInterval, _ block: Block) -> NSTimer {
let timer = NSTimer.make(intervalFromNow, block)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
return timer
}
class func schedule(every interval: NSTimeInterval, _ block: Block) -> NSTimer {
let timer = NSTimer.make(every: interval, block)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSDefaultRunLoopMode)
return timer
}
} | mit | 08c1a09bd6a1d6d7083d9b07d77854ce | 32.292683 | 119 | 0.66349 | 4.577181 | false | false | false | false |
harenbrs/swix | swix/swix/swix/matrix/m-operators.swift | 2 | 6144 | //
// twoD-operators.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
func make_operator(lhs: matrix, operation: String, rhs: matrix)->matrix{
assert(lhs.shape.0 == rhs.shape.0, "Sizes must match!")
assert(lhs.shape.1 == rhs.shape.1, "Sizes must match!")
var result = zeros_like(lhs) // real result
let lhsM = lhs.flat
let rhsM = rhs.flat
var resM:ndarray = zeros_like(lhsM) // flat ndarray
if operation=="+" {resM = lhsM + rhsM}
else if operation=="-" {resM = lhsM - rhsM}
else if operation=="*" {resM = lhsM * rhsM}
else if operation=="/" {resM = lhsM / rhsM}
else if operation=="<" {resM = lhsM < rhsM}
else if operation==">" {resM = lhsM > rhsM}
else if operation==">=" {resM = lhsM >= rhsM}
else if operation=="<=" {resM = lhsM <= rhsM}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: matrix, operation: String, rhs: Double)->matrix{
var result = zeros_like(lhs) // real result
// var lhsM = asmatrix(lhs.grid) // flat
let lhsM = lhs.flat
var resM:ndarray = zeros_like(lhsM) // flat matrix
if operation=="+" {resM = lhsM + rhs}
else if operation=="-" {resM = lhsM - rhs}
else if operation=="*" {resM = lhsM * rhs}
else if operation=="/" {resM = lhsM / rhs}
else if operation=="<" {resM = lhsM < rhs}
else if operation==">" {resM = lhsM > rhs}
else if operation==">=" {resM = lhsM >= rhs}
else if operation=="<=" {resM = lhsM <= rhs}
result.flat.grid = resM.grid
return result
}
func make_operator(lhs: Double, operation: String, rhs: matrix)->matrix{
var result = zeros_like(rhs) // real result
// var rhsM = asmatrix(rhs.grid) // flat
let rhsM = rhs.flat
var resM:ndarray = zeros_like(rhsM) // flat matrix
if operation=="+" {resM = lhs + rhsM}
else if operation=="-" {resM = lhs - rhsM}
else if operation=="*" {resM = lhs * rhsM}
else if operation=="/" {resM = lhs / rhsM}
else if operation=="<" {resM = lhs < rhsM}
else if operation==">" {resM = lhs > rhsM}
else if operation==">=" {resM = lhs >= rhsM}
else if operation=="<=" {resM = lhs <= rhsM}
result.flat.grid = resM.grid
return result
}
// DOUBLE ASSIGNMENT
func <- (inout lhs:matrix, rhs:Double){
let assign = ones((lhs.shape)) * rhs
lhs = assign
}
// DOT PRODUCT
infix operator *! {associativity none precedence 140}
func *! (lhs: matrix, rhs: matrix) -> matrix{
return dot(lhs, y: rhs)}
// SOLVE
infix operator !/ {associativity none precedence 140}
func !/ (lhs: matrix, rhs: ndarray) -> ndarray{
return solve(lhs, b: rhs)}
// EQUALITY
func ~== (lhs: matrix, rhs: matrix) -> Bool{
return (rhs.flat ~== lhs.flat)}
infix operator == {associativity none precedence 140}
func == (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat == rhs.flat).reshape(lhs.shape)
}
infix operator !== {associativity none precedence 140}
func !== (lhs: matrix, rhs: matrix)->matrix{
return (lhs.flat !== rhs.flat).reshape(lhs.shape)
}
/// ELEMENT WISE OPERATORS
// PLUS
infix operator + {associativity none precedence 140}
func + (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
func + (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "+", rhs: rhs)}
// MINUS
infix operator - {associativity none precedence 140}
func - (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
func - (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "-", rhs: rhs)}
// TIMES
infix operator * {associativity none precedence 140}
func * (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
func * (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "*", rhs: rhs)}
// DIVIDE
infix operator / {associativity none precedence 140}
func / (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)
}
func / (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
func / (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "/", rhs: rhs)}
// LESS THAN
infix operator < {associativity none precedence 140}
func < (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
func < (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "<", rhs: rhs)}
// GREATER THAN
infix operator > {associativity none precedence 140}
func > (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
func > (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: ">", rhs: rhs)}
// GREATER THAN OR EQUAL
infix operator >= {associativity none precedence 140}
func >= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)}
func >= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)}
func >= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)}
// LESS THAN OR EQUAL
infix operator <= {associativity none precedence 140}
func <= (lhs: matrix, rhs: Double) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)}
func <= (lhs: matrix, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)}
func <= (lhs: Double, rhs: matrix) -> matrix{
return make_operator(lhs, operation: "=>", rhs: rhs)} | mit | be0445033ee9e5ea1896b55645bff879 | 38.391026 | 72 | 0.635254 | 3.348229 | false | false | false | false |
ShamylZakariya/Squizit | Squizit/Models/DrawingInputController.swift | 1 | 5714 | //
// DrawingInputController.swift
// Squizit
//
// Created by Shamyl Zakariya on 8/15/14.
// Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import Foundation
import UIKit
class DrawingInputController {
private var _points = [CGPoint](count: 5, repeatedValue: CGPoint.zero)
private var _pointsTop = 0
private var _isFirstPoint = false
private var _lastSegment = LineSegment()
// MARK: Public Ivars
var drawing:Drawing? {
didSet {
view?.setNeedsDisplay()
}
}
// the viewport into the drawing - this is what will be rendered on screen
var viewport:CGRect = CGRect.zero {
didSet {
view?.setNeedsDisplay()
}
}
weak var view:UIView? {
didSet {
view?.setNeedsDisplay()
}
}
var fill:Fill = Fill.Pencil;
// MARK: Public
init(){}
func undo() {
if let drawing = drawing {
if let dirtyRect = drawing.popStroke() {
self.view?.setNeedsDisplayInRect( drawingToScreen(dirtyRect) )
} else {
view?.setNeedsDisplay()
}
}
}
func drawUsingImmediatePipeline( dirtyRect:CGRect, context:CGContextRef) {
if let drawing = drawing {
drawing.draw(dirtyRect, context: context)
}
}
func drawUsingBitmapPipeline( context:CGContextRef ) {
if let drawing = drawing {
let image = drawing.render( viewport ).image
image.drawAtPoint( viewport.origin, blendMode: CGBlendMode.Multiply, alpha: 1)
}
}
func touchBegan( locationInView:CGPoint ) {
if let drawing = drawing {
let locationInDrawing = screenToDrawing( locationInView )
_pointsTop = 0
_points[_pointsTop] = locationInDrawing
_isFirstPoint = true
_activeStroke = Stroke( fill: self.fill )
drawing.addStroke(_activeStroke!)
}
}
func touchMoved( locationInView:CGPoint ) {
if let drawing = drawing {
let locationInDrawing = screenToDrawing( locationInView )
_pointsTop += 1
_points[_pointsTop] = locationInDrawing;
if _pointsTop == 4 {
appendToStroke()
drawing.render( viewport ) {
[unowned self]
(image:UIImage, dirtyRect:CGRect ) in
if !dirtyRect.isNull {
self.view?.setNeedsDisplayInRect( self.drawingToScreen(dirtyRect) )
} else {
self.view?.setNeedsDisplay()
}
return
}
}
}
}
func touchEnded() {
if let drawing = drawing {
drawing.updateBoundingRect()
}
_activeStroke = nil
view?.setNeedsDisplay()
}
// MARK: Private
private func screenToDrawing( location:CGPoint ) -> CGPoint {
return location
}
private func drawingToScreen( rect:CGRect ) -> CGRect {
return rect
}
private var _activeStroke:Stroke?
private func appendToStroke() {
_points[3] = CGPoint(x: (_points[2].x + _points[4].x)/2, y: (_points[2].y + _points[4].y)/2)
var pointsBuffer:[CGPoint] = []
for i in 0 ..< 4 {
pointsBuffer.append(_points[i]);
}
_points[0] = _points[3]
_points[1] = _points[4]
_pointsTop = 1
let fillSize = self.fill.size
let SCALE:CGFloat = 1.0
let RANGE:CGFloat = 100
let MIN:CGFloat = fillSize.0
let MAX:CGFloat = fillSize.1
var ls = [LineSegment](count:4,repeatedValue:LineSegment())
for i in 0.stride(to: pointsBuffer.count, by: 4) {
if ( _isFirstPoint ) {
ls[0] = LineSegment(firstPoint: pointsBuffer[0], secondPoint: pointsBuffer[0])
_isFirstPoint = false
}
else {
ls[0] = _lastSegment
}
//
// Dropping distanceSquared is the key - use distance and I can return to the tuple-based min/max sizing
// and I'll no longer have the weird lumpy shapes which are resultant of the squaring curve
//
let frac1 = SCALE * (MIN + (clamp( distance(pointsBuffer[i+0], b: pointsBuffer[i+1]), lowerBound: 0.0, upperBound: RANGE )/RANGE) * (MAX-MIN))
let frac2 = SCALE * (MIN + (clamp( distance(pointsBuffer[i+1], b: pointsBuffer[i+2]), lowerBound: 0.0, upperBound: RANGE )/RANGE) * (MAX-MIN))
let frac3 = SCALE * (MIN + (clamp( distance(pointsBuffer[i+2], b: pointsBuffer[i+3]), lowerBound: 0.0, upperBound: RANGE )/RANGE) * (MAX-MIN))
ls[1] = LineSegment(firstPoint: pointsBuffer[i+0], secondPoint: pointsBuffer[i+1]).perpendicular(absoluteLength: frac1)
ls[2] = LineSegment(firstPoint: pointsBuffer[i+1], secondPoint: pointsBuffer[i+2]).perpendicular(absoluteLength: frac2)
ls[3] = LineSegment(firstPoint: pointsBuffer[i+2], secondPoint: pointsBuffer[i+3]).perpendicular(absoluteLength: frac3)
let a = ControlPoint(position: ls[0].firstPoint, control: ls[1].firstPoint)
let b = ControlPoint(position: ls[0].secondPoint, control: ls[1].secondPoint)
let c = ControlPoint(position: ls[3].firstPoint, control: ls[2].firstPoint)
let d = ControlPoint(position: ls[3].secondPoint, control: ls[2].secondPoint)
let chunk = Stroke.Chunk(
start: Stroke.Chunk.Spar(a: a, b: b),
end: Stroke.Chunk.Spar(a: c, b: d)
)
_activeStroke!.chunks.append(chunk)
_lastSegment = ls[3]
}
}
}
// MARK: -
/**
Adapter to simplify forwarding UIView touch events to a DrawingInputController
*/
extension DrawingInputController {
func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent, offset:CGPoint = CGPoint.zero) {
if touches.count > 1 {
return
}
let touch = touches.first as! UITouch
let location = touch.locationInView(view!)
touchBegan(location.subtract(offset))
}
func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent, offset:CGPoint = CGPoint.zero) {
if touches.count > 1 {
return
}
let touch = touches.first as! UITouch
let location = touch.locationInView(view!)
touchMoved(location.subtract(offset))
}
func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
touchEnded()
}
func touchesCancelled(touches: Set<NSObject>, withEvent event: UIEvent) {
touchEnded()
}
} | mit | b5ec05470ec5b5a9c05b725e0a3446cf | 24.176211 | 145 | 0.684284 | 3.3048 | false | false | false | false |
banxi1988/Staff | Pods/BXiOSUtils/Pod/Classes/UIKitGlobals.swift | 1 | 661 | //
// UIKitGlobals.swift
// Pods
//
// Created by Haizhen Lee on 15/12/6.
//
//
import UIKit
public let screenScale = UIScreen.mainScreen().scale
public let screenWidth = UIScreen.mainScreen().bounds.width
public let screenHeight = UIScreen.mainScreen().bounds.height
public var designBaseWidth:CGFloat = 375 // // Design Pointer to Devices Pointer
public func dp2dp(dp:CGFloat) -> CGFloat{
let coefficent = screenWidth / designBaseWidth
return ceil(dp * coefficent)
}
// 比 375 小的设备对应缩小,大的不变
public func sdp2dp(dp:CGFloat) -> CGFloat{
if screenWidth >= designBaseWidth{
return dp
}else{
return dp2dp(dp)
}
} | mit | d356535f9538b6f02ff1330dc6b49f0c | 21.642857 | 81 | 0.721959 | 3.55618 | false | false | false | false |
velvetroom/columbus | Source/Model/Create/MCreatePlan+Geocode.swift | 1 | 1262 | import Foundation
import CoreLocation
extension MCreatePlan
{
//MARK: private
private func startGeocoder()
{
guard
self.geocoder == nil
else
{
return
}
let geocoder:CLGeocoder = CLGeocoder()
self.geocoder = geocoder
}
private func geocodeLocation(
placemarks:[CLPlacemark]?,
error:Error?,
completion:((String?) -> ()))
{
guard
error == nil,
let placemark:CLPlacemark = placemarks?.first,
let name:String = placemark.name
else
{
completion(nil)
return
}
completion(name)
}
//MARK: internal
func geocodeLocation(
location:CLLocation,
completion:@escaping((String?) -> ()))
{
startGeocoder()
geocoder?.reverseGeocodeLocation(location)
{ [weak self] (
placemarks:[CLPlacemark]?,
error:Error?) in
self?.geocodeLocation(
placemarks:placemarks,
error:error,
completion:completion)
}
}
}
| mit | 91ae260f43403ee6ef6d5c9c49c808bc | 19.031746 | 58 | 0.468304 | 5.95283 | false | false | false | false |
ben-ng/swift | test/SILGen/generic_witness.swift | 1 | 2433 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3foo{{.*}} : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_TF15generic_witness3bar{{.*}} : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box $<τ_0_0> { var τ_0_0 } <Runcible>
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWuRx15generic_witness3Inkwx5PaintS_3PenrGVS_6Canvasx_S_6MediumS_FS4_4drawuRd__S_6Pencilwd__6StrokezWx7TextureS1__rfT5paintWxS7_S1__6pencilqd___T_ : $@convention(witness_method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> ()
// CHECK: [[FN:%.*]] = function_ref @_TFV15generic_witness6Canvas4drawuRd__S_6Pencilwx5Paintzwd__6StrokerfT5paintwxS2_6pencilqd___T_ : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| apache-2.0 | 86b3167a34de89136c42f6547dc917e4 | 41.803571 | 377 | 0.623696 | 2.708475 | false | false | false | false |
nixzhu/WorkerBee | WorkerBee/TextSize.swift | 1 | 3139 | //
// TextSize.swift
// WorkerBee
//
// Created by nixzhu on 2017/5/26.
// Copyright © 2017年 nixWork. All rights reserved.
//
import UIKit
public struct TextSize {
private struct FixedWidthCacheEntry: Hashable {
let text: String
let font: UIFont
let width: CGFloat
let insets: UIEdgeInsets
var hashValue: Int {
return text.hashValue ^ font.hashValue ^ Int(width) ^ Int(insets.top) ^ Int(insets.left) ^ Int(insets.bottom) ^ Int(insets.right)
}
static func ==(lhs: FixedWidthCacheEntry, rhs: FixedWidthCacheEntry) -> Bool {
return lhs.width == rhs.width && lhs.insets == rhs.insets && lhs.text == rhs.text && lhs.font == rhs.font
}
}
private struct FixedHeightCacheEntry: Hashable {
let text: String
let font: UIFont
let insets: UIEdgeInsets
var hashValue: Int {
return text.hashValue ^ font.hashValue ^ Int(insets.top) ^ Int(insets.left) ^ Int(insets.bottom) ^ Int(insets.right)
}
static func ==(lhs: FixedHeightCacheEntry, rhs: FixedHeightCacheEntry) -> Bool {
return lhs.insets == rhs.insets && lhs.text == rhs.text && lhs.font == rhs.font
}
}
private static var fixedWidthCache = [FixedWidthCacheEntry: CGFloat]() {
didSet {
assert(Thread.isMainThread)
}
}
private static var fixedHeightCache = [FixedHeightCacheEntry: CGFloat]() {
didSet {
assert(Thread.isMainThread)
}
}
public static func height(text: String, font: UIFont, width: CGFloat, insets: UIEdgeInsets = .zero) -> CGFloat {
let key = FixedWidthCacheEntry(text: text, font: font, width: width, insets: insets)
if let hit = fixedWidthCache[key] {
return hit
}
let constrainedSize = CGSize(width: width - insets.left - insets.right, height: CGFloat.greatestFiniteMagnitude)
let attributes = [NSAttributedStringKey.font: font]
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let bounds = (text as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil)
let height = ceil(bounds.height + insets.top + insets.bottom)
fixedWidthCache[key] = height
return height
}
public static func width(text: String, font: UIFont, insets: UIEdgeInsets = .zero) -> CGFloat {
let key = FixedHeightCacheEntry(text: text, font: font, insets: insets)
if let hit = fixedHeightCache[key] {
return hit
}
let constrainedSize = CGSize(width: CGFloat.greatestFiniteMagnitude, height: 0)
let attributes = [NSAttributedStringKey.font: font]
let options: NSStringDrawingOptions = [.usesFontLeading, .usesLineFragmentOrigin]
let bounds = (text as NSString).boundingRect(with: constrainedSize, options: options, attributes: attributes, context: nil)
let width = ceil(bounds.width + insets.left + insets.right)
fixedHeightCache[key] = width
return width
}
}
| mit | 8d72b9586a15a4a62f01a3015eb5afd0 | 37.716049 | 141 | 0.642857 | 4.499283 | false | false | false | false |
RLovelett/VHS | VHS/Types/Body.swift | 1 | 1005 | //
// Body.swift
// VHS
//
// Created by Lovelett, Ryan A. on 1/10/19.
// Copyright © 2019 Ryan Lovelett. All rights reserved.
//
public struct Body: Decodable {
enum Keys: String, CodingKey {
case type
case data
}
private let raw: BodyDataDecodable?
public let data: Data?
init(_ data: Data?) {
self.raw = nil
self.data = data
}
init<T: BodyDataDecodable>(_ raw: T) {
self.raw = raw
self.data = self.raw?.data
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Keys.self)
let type = try? container.decode(String.self, forKey: .type)
if Text.handle(type) {
self.init(try container.decode(Text.self, forKey: .data))
} else if JSON.handle(type) {
self.init(try container.decode(JSON.self, forKey: .data))
} else {
self.init(try container.decode(Base64.self, forKey: .data))
}
}
}
| mit | 32bdd6a521fb41e3837712b37889d07c | 22.904762 | 71 | 0.579681 | 3.691176 | false | false | false | false |
mac-cain13/R.swift | Sources/RswiftCore/Generators/SegueGenerator.swift | 2 | 6438 | //
// SegueStructGenerator.swift
// R.swift
//
// Created by Mathijs Kadijk on 10-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
private struct SegueWithInfo {
let segue: Storyboard.Segue
let sourceType: Type
let destinationType: Type
var groupKey: String {
return "\(segue.identifier)|\(segue.type)|\(sourceType)|\(destinationType)"
}
}
struct SegueStructGenerator: ExternalOnlyStructGenerator {
private let storyboards: [Storyboard]
init(storyboards: [Storyboard]) {
self.storyboards = storyboards
}
func generatedStruct(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct {
let structName: SwiftIdentifier = "segue"
let qualifiedName = prefix + structName
let seguesWithInfo = storyboards.flatMap { storyboard in
storyboard.viewControllers.flatMap { viewController in
viewController.segues.compactMap { segue -> SegueWithInfo? in
guard let destinationType = resolveDestinationTypeForSegue(
segue,
inViewController: viewController,
inStoryboard: storyboard,
allStoryboards: storyboards)
else
{
warn("Destination view controller with id \(segue.destination) for segue \(segue.identifier) in \(viewController.type) not found in storyboard \(storyboard.name). Is this storyboard corrupt?")
return nil
}
guard !segue.identifier.isEmpty else {
return nil
}
return SegueWithInfo(segue: segue, sourceType: viewController.type, destinationType: destinationType)
}
}
}
let deduplicatedSeguesWithInfo = seguesWithInfo
.grouped { $0.groupKey }
.values
.compactMap { $0.first }
var structs: [Struct] = []
for (sourceType, seguesBySourceType) in deduplicatedSeguesWithInfo.grouped(by: { $0.sourceType }) {
let groupedSeguesWithInfo = seguesBySourceType.grouped(bySwiftIdentifier: { $0.segue.identifier })
groupedSeguesWithInfo.printWarningsForDuplicatesAndEmpties(source: "segue", container: "for '\(sourceType)'", result: "segue")
let sts = groupedSeguesWithInfo
.uniques
.grouped { $0.sourceType }
.values
.compactMap { self.seguesWithInfoForSourceTypeToStruct($0, at: externalAccessLevel) }
structs = structs + sts
}
return Struct(
availables: [],
comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(structs.count) view controllers."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: [],
functions: [],
structs: structs,
classes: [],
os: ["iOS", "tvOS"]
)
}
private func resolveDestinationTypeForSegue(_ segue: Storyboard.Segue, inViewController: Storyboard.ViewController, inStoryboard storyboard: Storyboard, allStoryboards storyboards: [Storyboard]) -> Type? {
if segue.kind == "unwind" {
return Type._UIViewController
}
let destinationViewControllerType = storyboard.viewControllers
.filter { $0.id == segue.destination }
.first?
.type
let destinationViewControllerPlaceholderType = storyboard.viewControllerPlaceholders
.filter { $0.id == segue.destination }
.first
.flatMap { storyboard -> Type? in
switch storyboard.resolveWithStoryboards(storyboards) {
case .customBundle:
return Type._UIViewController // Not supported, fallback to UIViewController
case let .resolved(vc):
return vc?.type
}
}
return destinationViewControllerType ?? destinationViewControllerPlaceholderType
}
private func seguesWithInfoForSourceTypeToStruct(_ seguesWithInfoForSourceType: [SegueWithInfo], at externalAccessLevel: AccessLevel) -> Struct? {
guard let sourceType = seguesWithInfoForSourceType.first?.sourceType else { return nil }
let properties = seguesWithInfoForSourceType.map { segueWithInfo -> Let in
let type = Type(
module: "Rswift",
name: "StoryboardSegueIdentifier",
genericArgs: [segueWithInfo.segue.type, segueWithInfo.sourceType, segueWithInfo.destinationType],
optional: false
)
return Let(
comments: ["Segue identifier `\(segueWithInfo.segue.identifier)`."],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: segueWithInfo.segue.identifier),
typeDefinition: .specified(type),
value: "Rswift.StoryboardSegueIdentifier(identifier: \"\(segueWithInfo.segue.identifier)\")"
)
}
let functions = seguesWithInfoForSourceType.map { segueWithInfo -> Function in
Function(
availables: [],
comments: [
"Optionally returns a typed version of segue `\(segueWithInfo.segue.identifier)`.",
"Returns nil if either the segue identifier, the source, destination, or segue types don't match.",
"For use inside `prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)`."
],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: segueWithInfo.segue.identifier),
generics: nil,
parameters: [
Function.Parameter.init(name: "segue", type: Type._UIStoryboardSegue)
],
doesThrow: false,
returnType: Type.TypedStoryboardSegueInfo
.asOptional()
.withGenericArgs([segueWithInfo.segue.type, segueWithInfo.sourceType, segueWithInfo.destinationType]),
body: "return Rswift.TypedStoryboardSegueInfo(segueIdentifier: R.segue.\(SwiftIdentifier(name: sourceType.description)).\(SwiftIdentifier(name: segueWithInfo.segue.identifier)), segue: segue)",
os: ["iOS", "tvOS"]
)
}
let typeName = SwiftIdentifier(name: sourceType.description)
return Struct(
availables: [],
comments: ["This struct is generated for `\(sourceType.name)`, and contains static references to \(properties.count) segues."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: typeName),
implements: [],
typealiasses: [],
properties: properties,
functions: functions,
structs: [],
classes: [],
os: []
)
}
}
| mit | acd0de50d78657de54e96638d095036d | 35.168539 | 207 | 0.671948 | 4.95612 | false | false | false | false |
khizkhiz/swift | test/Sema/object_literals_osx.swift | 8 | 1414 | // RUN: %target-parse-verify-swift
// REQUIRES: OS=macosx
struct S: _ColorLiteralConvertible {
init(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float) {}
}
let y: S = [#Color(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)#]
let y2 = [#Color(colorLiteralRed: 1, green: 0, blue: 0, alpha: 1)#] // expected-error{{could not infer type of color literal}} expected-note{{import AppKit to use 'NSColor' as the default color literal type}}
let y3 = [#Color(colorLiteralRed: 1, bleen: 0, grue: 0, alpha: 1)#] // expected-error{{cannot convert value of type '(colorLiteralRed: Int, bleen: Int, grue: Int, alpha: Int)' to expected argument type '(colorLiteralRed: Float, green: Float, blue: Float, alpha: Float)'}}
struct I: _ImageLiteralConvertible {
init(imageLiteral: String) {}
}
let z: I = [#Image(imageLiteral: "hello.png")#]
let z2 = [#Image(imageLiteral: "hello.png")#] // expected-error{{could not infer type of image literal}} expected-note{{import AppKit to use 'NSImage' as the default image literal type}}
struct Path: _FileReferenceLiteralConvertible {
init(fileReferenceLiteral: String) {}
}
let p1: Path = [#FileReference(fileReferenceLiteral: "what.txt")#]
let p2 = [#FileReference(fileReferenceLiteral: "what.txt")#] // expected-error{{could not infer type of file reference literal}} expected-note{{import Foundation to use 'NSURL' as the default file reference literal type}}
| apache-2.0 | fa1d71dd2d926f2532073a08aa91cb97 | 57.916667 | 271 | 0.722065 | 3.770667 | false | false | false | false |
machasamurai/KeyboardStateObserver | CPKeyboardStateObserver/ViewController.swift | 1 | 11478 | //
// ViewController.swift
// CPKeyboardStateObserver
//
// Created by Ramon Beckmann on 2016/02/02.
// Copyright © 2016 Corepilots. All rights reserved.
//
import UIKit
class ViewController: UIViewController, CPKeyboardObserverDelegate {
// textView used to trigger the keyboard events
@IBOutlet weak var textView: UITextView!
// label that displays the current keyboards state and the callback method
@IBOutlet weak var stateLabel: UILabel!
// // button to pause the observer
@IBOutlet weak var pauseButton: UIButton!
// button to change the callback methos (delegate or closure (block))
@IBOutlet weak var functionButton: UIButton!
// constraint used to animate the label
@IBOutlet weak var stateLabelBottomConstraint: NSLayoutConstraint!
// blocks used to demonstrate the observer using closures
var blockForStateHide: BlockForState!
var blockForStateShow: BlockForState!
var blockForStateUndockEvent: BlockForState!
var blockForStateDockEvent: BlockForState!
var blockForStateWillMove: BlockForState!
var blockForStateDidMove: BlockForState!
// the current observation mode
var mode: ObservationMode!
var observationModeStringArray = ["delegate", "block"]
/**
The observation modes.
- Block: use the observer using blocks/closures as callback method.
- Delegate: use the observer using the CPKeyboardObserverDelegate
*/
enum ObservationMode: Int {
case Block
case Delegate
}
override func viewDidLoad() {
super.viewDidLoad()
// we start with using blocks
self.mode = .Block
self.initData()
// init the views
self.initViews()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// start the observer using blocks/closures
CPKeyboardStateObserver.sharedObserver.startObserving(self.view, blockForStateHide: self.blockForStateHide, blockForStateShow: self.blockForStateShow, blockForStateUndock: self.blockForStateUndockEvent, blockForStateDock: self.blockForStateDockEvent, blockForStateWillMove: self.blockForStateWillMove, blockForStateDidMove: self.blockForStateDidMove)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
// stop observing since the viewController will disappear
CPKeyboardStateObserver.sharedObserver.stopObserving()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/**
Initialize the blocks for the observer.
For the demo purpose we just change the text of the state label to the corresponding event and move the state label along with the keyboard frame for all events except the 'willMove' event.
*/
private func initData() {
self.blockForStateHide = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockDidHide"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
self.blockForStateShow = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockDidShow"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
self.blockForStateUndockEvent = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockDidUndock"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
self.blockForStateDockEvent = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockDidDock"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
self.blockForStateWillMove = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockWillMove"
self.hideLabel()
}
self.blockForStateDidMove = { (keyboardInfo: [NSObject : AnyObject]) -> Void in
self.stateLabel.text = "blockDidMove"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
}
/**
Initialize the views.
For the demo purposes we only set the button titles.
*/
private func initViews() {
self.functionButton.setTitle(self.observationModeStringArray[self.mode.rawValue], forState: .Normal)
self.pauseButton.setTitle("pause", forState: .Normal)
}
/**
Toggle the observation mode.
Toggle between delegate mode and block/closure mode.
- Parameter sender: the function button.
*/
@IBAction func toggleMode(sender: UIButton) {
let sharedObserver = CPKeyboardStateObserver.sharedObserver
// stop observing before changing the observing mode
sharedObserver.stopObserving()
// if currently using blocks/closures switch to using the delegate
if self.mode == .Block {
sharedObserver.startObserving(self.view, delegate: self)
self.mode = .Delegate
sender.setTitle("block", forState: .Normal)
}
// if currently using the delegate switch to using blocks/closures
else {
CPKeyboardStateObserver.sharedObserver.startObserving(self.view, blockForStateHide: self.blockForStateHide, blockForStateShow: self.blockForStateShow, blockForStateUndock: self.blockForStateUndockEvent, blockForStateDock: self.blockForStateDockEvent, blockForStateWillMove: self.blockForStateWillMove, blockForStateDidMove: self.blockForStateDidMove)
self.mode = .Block
sender.setTitle("delegate", forState:.Normal)
}
}
/**
Move the label with the information from the new keyboard frame dictionary.
- Parameter userInfo: the dictionary with the information about the keyboard frame.
- Parameter shouldFollowKeyboard: boolean that indicates if the label should follow the keyboard.
true = follow
false = don't follow
*/
private func moveLabel(userInfo: [NSObject : AnyObject], shouldFollowKeyboard: Bool) {
let keyboardFrame = (userInfo[KeyboardFrameDictionaryKey.CPKeyboardStateObserverNewFrameKey] as! NSValue).CGRectValue()
if shouldFollowKeyboard {
self.stateLabelBottomConstraint.constant = (UIScreen.mainScreen().bounds.size.height - keyboardFrame.origin.y) + self.stateLabel.frame.size.height
}
else {
self.stateLabelBottomConstraint.constant = UIScreen.mainScreen().bounds.size.height
}
// since we are using the storyboard and constraints we use 'layoutIfNeeded' to animate the tranlation
UIView.animateWithDuration(0.3, animations: { () -> Void in
self.view.layoutIfNeeded()
}, completion: { (Bool) -> Void in
// show the label if hidden
self.showLabel()
})
}
/**
Pause and restart the observer.
- Parameter sender: the action button.
*/
@IBAction func toggleAction(sender: UIButton) {
let keyboardObserver = CPKeyboardStateObserver.sharedObserver
// if is observing pause the observer
if keyboardObserver.isObserving {
keyboardObserver.pauseObserver()
sender.setTitle("play", forState: .Normal)
self.stateLabel.text = "pause"
}
// if obsevrer is paused restart it
else {
keyboardObserver.restartObserver()
sender.setTitle("pause", forState: .Normal)
self.stateLabel.text = "play"
}
}
/**
Shows the label with an alpha animation.
*/
private func showLabel() {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.stateLabel.alpha = 1
}, completion: nil)
}
/**
Hides the label with an alpha animation.
*/
private func hideLabel() {
UIView.animateWithDuration(0.25, animations: { () -> Void in
self.stateLabel.alpha = 0
}, completion: nil)
}
// MARK: CPKeyboardStateObserverDelegate methods
/**
The keyboard didMove event.
We change the label text and label position.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardDidMove(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateDidMove"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
/**
The keyboard willDock event.
We change the label text and label position.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardWillDock(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateDidDock"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
/**
The keyboard willHide event.
We change the label text and label position.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardWillHide(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateDidHide"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
/**
The keyboard willMove event.
We change the label text and hide the label.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardWillMove(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateWillMove"
self.hideLabel()
}
/**
The keyboard willShow event.
We change the label text and label position.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardWillShow(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateDidShow"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
/**
The keyboard willUndock event.
We change the label text and label position.
- Parameter keyboardStateObserver: the observer instance.
- Parameter keyboardInfo: the dictionary with the information about the keyboard frame.
*/
func keyboardWillUndock(keyboardStateObserver: CPKeyboardStateObserver, keyboardInfo: [NSObject : AnyObject]) {
self.stateLabel.text = "delegateDidUndock"
self.moveLabel(keyboardInfo, shouldFollowKeyboard: true)
}
} | mit | 29edcc7fa8b8872ff8f77d9f62d0ff7a | 36.756579 | 362 | 0.666028 | 5.135123 | false | false | false | false |
joerocca/GitHawk | Playgrounds/Github API.playground/Contents.swift | 2 | 1316 | //: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
func curl(request: NSURLRequest) {
print(request)
let task = URLSession.shared.dataTask(with: request as URLRequest, completionHandler: { (data, response, err) in
print(response)
if let data = data {
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
} else {
print(err ?? "error failure")
}
})
task.resume()
}
let basic = "Basic " + "USERNAME:PASSWORD".data(using: .ascii)!.base64EncodedString()
let request = NSMutableURLRequest(url: URL(string: "https://api.github.com/authorizations")!)
request.httpMethod = "POST"
request.setValue(basic, forHTTPHeaderField: "Authorization")
request.setValue("123456", forHTTPHeaderField: "X-GitHub-OTP")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let json: [String: Any] = [
"scopes": ["repo"],
"note": "gitter app development",
"client_id": "CLIENT_ID",
"client_secret": "CLIENT_SECRET",
]
request.httpBody = try! JSONSerialization.data(withJSONObject: json, options: [])
curl(request: request)
| mit | 662083e5db864120543c8aa7065d5b91 | 32.74359 | 116 | 0.690729 | 4.074303 | false | false | false | false |
qualaroo/QualarooSDKiOS | Qualaroo/Survey/Body/Question/List/AnswerListInteractor.swift | 1 | 1766 | //
// AnswerListInteractor.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
class AnswerListInteractor {
private let responseBuilder: AnswerListResponseBuilder
private let validator: AnswerListValidator
private weak var buttonHandler: SurveyButtonHandler?
private weak var answerHandler: SurveyAnswerHandler?
private let question: Question
init(responseBuilder: AnswerListResponseBuilder,
validator: AnswerListValidator,
buttonHandler: SurveyButtonHandler,
answerHandler: SurveyAnswerHandler,
question: Question) {
self.responseBuilder = responseBuilder
self.validator = validator
self.buttonHandler = buttonHandler
self.answerHandler = answerHandler
self.question = question
validateAnswer([])
}
@discardableResult private func validateAnswer(_ idsAndTexts: [(Int, String?)]) -> Bool {
let isValid = validator.isValid(idsAndTexts: idsAndTexts)
if isValid {
buttonHandler?.enableButton()
} else {
buttonHandler?.disableButton()
}
return isValid
}
func setAnswer(_ answers: [(Int, String?)]) {
let isValid = validateAnswer(answers)
if !isValid {
return
}
passAnswer(answers)
conductTransitionIfNeeded()
}
private func passAnswer(_ answers: [(Int, String?)]) {
guard let response = responseBuilder.response(idsAndTexts: answers) else { return }
answerHandler?.answerChanged(response)
}
private func conductTransitionIfNeeded() {
if question.shouldShowButton == false {
answerHandler?.goToNextNode()
}
}
}
| mit | 814c1b3a3262fc2b166a295531aac776 | 27.95082 | 91 | 0.716874 | 4.493639 | false | false | false | false |
Electrode-iOS/ELRouter | ELRouter/NSURL+DeepLink.swift | 2 | 1655 | //
// NSURL+DeepLink.swift
// ELRouter
//
// Created by Brandon Sneed on 10/20/15.
// Copyright © 2015 Walmart. All rights reserved.
//
import Foundation
public extension URL {
public var deepLinkComponents: [String]? {
// a deep link doesn't have the notion of a host, construct it as such
var components = [String]()
// if we have a host, it's considered a component.
if let host = host {
components.append(host)
}
// now add the path components, leaving the encoded parts intact
if let urlComponents = URLComponents(url: self, resolvingAgainstBaseURL: false) {
let percentEncodedPath = urlComponents.percentEncodedPath
// Note that the percentEncodedPath property of NSURLComponents does not add any encoding, it just returns any
// encoding that is already in the path. Unencoded slashes will remain unencoded but escaped slashes will remain
// escaped, which is what we want here.
let pathComponents = percentEncodedPath.components(separatedBy: "/")
// remove any empty strings, such as the one in the first element that results from the initial slash
let pathComponentsAfterSlash = pathComponents.filter() { !$0.isEmpty }
// append to our components
components += pathComponentsAfterSlash
}
return components
}
/*public var queryAsPairsif : [String : String]? {
if let query = query {
let components = query.componentsSeparatedByString("&")
}
return nil
}*/
}
| mit | 3dafea4e955632f5d2519d4e769e6091 | 35.755556 | 124 | 0.631802 | 5.234177 | false | false | false | false |
Bouke/HAP | Sources/HAP/Base/Predefined/Characteristics/Characteristic.MetricsBufferFullState.swift | 1 | 2099 | import Foundation
public extension AnyCharacteristic {
static func metricsBufferFullState(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Metrics Buffer Full State",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> AnyCharacteristic {
AnyCharacteristic(
PredefinedCharacteristic.metricsBufferFullState(
value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange) as Characteristic)
}
}
public extension PredefinedCharacteristic {
static func metricsBufferFullState(
_ value: Bool = false,
permissions: [CharacteristicPermission] = [.read, .events],
description: String? = "Metrics Buffer Full State",
format: CharacteristicFormat? = .bool,
unit: CharacteristicUnit? = nil,
maxLength: Int? = nil,
maxValue: Double? = nil,
minValue: Double? = nil,
minStep: Double? = nil,
validValues: [Double] = [],
validValuesRange: Range<Double>? = nil
) -> GenericCharacteristic<Bool> {
GenericCharacteristic<Bool>(
type: .metricsBufferFullState,
value: value,
permissions: permissions,
description: description,
format: format,
unit: unit,
maxLength: maxLength,
maxValue: maxValue,
minValue: minValue,
minStep: minStep,
validValues: validValues,
validValuesRange: validValuesRange)
}
}
| mit | 64844ecdd89843915ce35c432969267a | 33.409836 | 67 | 0.586946 | 5.437824 | false | false | false | false |
xivol/MCS-V3-Mobile | examples/graphics/Draw 2.0/Draw 2.0/DrawView.swift | 1 | 2274 | //
// DrawView.swift
// Draw 2.0
//
// Created by Илья Лошкарёв on 04.10.17.
// Copyright © 2017 Илья Лошкарёв. All rights reserved.
//
import UIKit
import Foundation
class DrawView: UIImageView {
var strokeWidth: CGFloat = 10.0
var strokeColor = UIColor.blue
var lastPoint = CGPoint.zero
weak var palette: Palette?
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
if let touch = touches.first {
lastPoint = touch.location(in: self)
drawLine(from: lastPoint, to: lastPoint)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if let touch = touches.first {
let currentPoint = touch.location(in: self)
drawLine(from: lastPoint, to: currentPoint)
lastPoint = currentPoint
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
}
func drawLine(from fromPoint: CGPoint, to toPoint:CGPoint) {
UIGraphicsBeginImageContext(self.bounds.size)
let context = UIGraphicsGetCurrentContext()
context?.setAllowsAntialiasing(true)
self.image?.draw(in: self.bounds)
let linePath = UIBezierPath()
linePath.move(to: fromPoint)
linePath.addLine(to: toPoint)
let dist = hypot(fromPoint.x - toPoint.x, fromPoint.y - toPoint.y)
linePath.lineWidth = 1 + strokeWidth * exp(-min(dist, 20)/20)
linePath.lineCapStyle = .round
linePath.lineJoinStyle = .round
strokeColor.setStroke()
linePath.stroke()
self.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
func clear() {
UIGraphicsBeginImageContext(self.bounds.size)
let rect = UIBezierPath(rect: self.bounds)
UIColor.white.setFill()
rect.fill()
self.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
}
| mit | 9b33f5527ecb4495dbafa1d87f03a32b | 28.592105 | 79 | 0.616719 | 4.921225 | false | false | false | false |
LesCoureurs/Courir | Courir/Courir/SettingsViewController.swift | 1 | 2486 | //
// SettingsViewController.swift
// Courir
//
// Created by Karen on 6/4/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController {
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: Display Form
/// Display form for setting new player name
@IBAction func handleSetName(sender: AnyObject) {
presentViewController(generateFormFor("New Name", withSaveKey: SettingsManager.nameKey, andPlaceholder: SettingsManager._instance.get(SettingsManager.nameKey) as! String), animated: true, completion: nil)
}
private func generateFormFor(title: String, withSaveKey key: String, andPlaceholder placeholder: String = "") -> UIAlertController {
let alertController = UIAlertController(title: title, message: "", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
alertController.dismissViewControllerAnimated(true, completion: nil)
}
alertController.addAction(cancelAction)
let saveAction = UIAlertAction(title: "Save", style: .Default) { _ in
if let value = alertController.textFields?.first?.text {
SettingsManager._instance.put(key, value: value)
}
}
alertController.addAction(saveAction)
alertController.addTextFieldWithConfigurationHandler { textField in
textField.placeholder = placeholder
textField.addTarget(self, action: #selector(SettingsViewController.textFieldDidChange(_:)), forControlEvents: .EditingChanged)
}
return alertController
}
/// Allow the user to save the field only if it contains at least 1 non-whitespace character
func textFieldDidChange(sender: UIControl) {
if let field = sender as? UITextField, text = field.text, controller = self.presentedViewController as? UIAlertController, save = controller.actions.last {
save.enabled = !text.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).isEmpty
}
}
// MARK: - Navigation
@IBAction func handleBackAction(sender: AnyObject) {
if let parentVC = parentViewController as? MainViewController {
parentVC.transitionOut()
}
}
}
| mit | dea8dc7679b51ff9dd6cdcf3e594732b | 35.014493 | 212 | 0.688531 | 5.367171 | false | false | false | false |
EZ-NET/CodePiece | ESTwitter/API/PostOptions.swift | 1 | 1295 | //
// PostOptions.swift
// ESTwitter
//
// Created by Tomohiro Kumagai on 2020/01/27.
// Copyright © 2020 Tomohiro Kumagai. All rights reserved.
//
import Foundation
extension API {
public struct PostOption {
public var inReplyTo: StatusId?
public var mediaIDs: [MediaId]
public var attachmentUrl: URL?
public var coordinate: CoordinatesElement?
public var autoPopulateReplyMetadata: Bool?
public var excludeReplyUserIds: Bool?
public var placeId: Double?
public var displayCoordinates: Bool?
public var trimUser: Bool?
public var tweetMode: TweetMode
public init(inReplyTo: StatusId? = nil, mediaIDs: [MediaId] = [], attachmentUrl: URL? = nil, coordinate: CoordinatesElement? = nil, autoPopulateReplyMetadata: Bool? = nil, excludeReplyUserIds: Bool? = nil, placeId: Double? = nil, displayCoordinates: Bool? = nil, trimUser: Bool? = nil, tweetMode: TweetMode = .default) {
self.inReplyTo = inReplyTo
self.mediaIDs = mediaIDs
self.attachmentUrl = attachmentUrl
self.coordinate = coordinate
self.autoPopulateReplyMetadata = autoPopulateReplyMetadata
self.excludeReplyUserIds = excludeReplyUserIds
self.placeId = placeId
self.displayCoordinates = displayCoordinates
self.trimUser = trimUser
self.tweetMode = tweetMode
}
}
}
| gpl-3.0 | 631c5715c8b16ff1e771051e70bf040a | 31.35 | 322 | 0.744204 | 3.718391 | false | false | false | false |
evertoncunha/EPCSpinnerView | Example/EPCSpinnerView/ViewController.swift | 1 | 1851 | //
// ViewController.swift
// EPCSpinnerView
//
// Created by evertoncunha on 09/13/2017.
// Copyright (c) 2017 evertoncunha. All rights reserved.
//
import UIKit
import EPCSpinnerView
class ViewController: UIViewController {
let spinner = EPCSpinnerView()
let buildWithAutolayout = false
override func viewDidLoad() {
super.viewDidLoad()
if buildWithAutolayout {
buildViewWithAutolayout()
}
else {
spinner.frame = CGRect(x: 30, y: 30, width: 180, height: 180)
view.addSubview(spinner)
}
var fra = CGRect.zero
fra.size = EPCDrawnIconLock.suggestedSize
let icon = EPCDrawnIconLock(frame: fra)
spinner.addIcon(icon)
spinner.startAnimating()
}
func buildViewWithAutolayout() {
spinner.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(spinner)
let views = ["s":spinner]
NSLayoutConstraint.activate([
NSLayoutConstraint.constraints(withVisualFormat: "H:|-30-[s(180)]", options: [], metrics: nil, views: views),
NSLayoutConstraint.constraints(withVisualFormat: "V:|-30-[s(180)]", options: [], metrics: nil, views: views)
].flatMap {return $0})
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func tappedError() {
spinner.state = .error
}
@IBAction func tappedSuccess() {
spinner.state = .success
}
@IBAction func tappedLoading() {
spinner.state = .loading
}
@IBAction func tappedStepper(_ stepper: UIStepper) {
let val: CGFloat = 180 + CGFloat(stepper.value)
var fra = spinner.frame
fra.size = CGSize(width: val, height: val)
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(3)
spinner.frame = fra
UIView.commitAnimations()
}
}
| mit | 933fc13259483be516ba157df7d17af1 | 22.43038 | 115 | 0.660724 | 4.197279 | false | false | false | false |
kevintavog/PeachMetadata | source/PeachMetadata/ImageBrowser.swift | 1 | 11716 | //
// PeachMetadata
//
import Foundation
import Quartz
import Async
import RangicCore
extension PeachWindowController
{
static fileprivate let missingAttrs = [
NSAttributedStringKey.foregroundColor : NSColor(deviceRed: 0.0, green: 0.7, blue: 0.7, alpha: 1.0),
NSAttributedStringKey.font : NSFont.labelFont(ofSize: 14)
]
static fileprivate let badDataAttrs = [
NSAttributedStringKey.foregroundColor : NSColor.orange,
NSAttributedStringKey.font : NSFont.labelFont(ofSize: 14)
]
@IBAction func updateThumbnailsize(_ sender: AnyObject)
{
Preferences.thumbnailZoom = thumbSizeSlider.floatValue
imageBrowserView.setZoomValue(thumbSizeSlider.floatValue)
}
func populateImageView(_ folder: String)
{
mediaProvider.clear()
mediaProvider.addFolder(folder)
// for (_, m) in mediaProvider.enumerated() {
// if let rotation = m.rotation {
// if rotation != 0 {
// Logger.error("\(m.name!) is rotated \(rotation)")
// }
// }
// }
loadThumbnails()
}
func reloadExistingMedia()
{
mediaProvider.refresh()
loadThumbnails()
}
func loadThumbnails()
{
thumbnailItems = [ThumbnailViewItem]()
for (_, m) in mediaProvider.enumerated() {
thumbnailItems.append(ThumbnailViewItem(mediaData: m))
}
filterItems()
setFolderStatus()
}
func isFilterActive() -> Bool
{
return statusLocationLabel.state != .off || statusDateLabel.state != .off || statusKeywordLabel.state != .off
}
func filterItems()
{
if isFilterActive() == false {
filteredThumbnailItems = thumbnailItems
} else {
filteredThumbnailItems.removeAll()
for thumb in thumbnailItems {
if statusLocationLabel.state != .off {
if let location = thumb.mediaData.location {
if SensitiveLocations.sharedInstance.isSensitive(location) {
filteredThumbnailItems.append(thumb)
continue
}
} else {
filteredThumbnailItems.append(thumb)
continue
}
}
if statusDateLabel.state != .off {
if thumb.mediaData.doFileAndExifTimestampsMatch() == false {
filteredThumbnailItems.append(thumb)
continue
}
}
if statusKeywordLabel.state != .off {
if thumb.mediaData.keywords == nil || thumb.mediaData.keywords?.count == 0 {
filteredThumbnailItems.append(thumb)
}
}
}
}
imageBrowserView.reloadData()
}
// MARK: imageBrowserView data provider
override func numberOfItems(inImageBrowser browser: IKImageBrowserView!) -> Int
{
return filteredThumbnailItems.count
}
override func imageBrowser(_ browser: IKImageBrowserView!, itemAt index: Int) -> Any!
{
return filteredThumbnailItems[index]
}
func selectedMediaItems() -> [MediaData]
{
var mediaItems = [MediaData]()
for index in imageBrowserView.selectionIndexes() {
mediaItems.append(mediaProvider.getMedia(index)!)
}
return mediaItems
}
// MARK: imageBrowserView Delegate
override func imageBrowserSelectionDidChange(_ browser: IKImageBrowserView!)
{
let selectedItems = selectedMediaItems()
switch imageBrowserView.selectionIndexes().count {
case 0:
setFolderStatus()
postNoSelection()
case 1:
setSingleItemStatus(selectedItems.first!)
postSelectedItem(selectedItems.first!)
default:
setMultiItemStatus(selectedItems, filesMessage: "files selected")
postSelectedItem(selectedItems.first!)
}
do {
if try selectedKeywords.save() {
imageBrowserView.reloadData()
}
} catch let error {
Logger.error("Failed saving keywords: \(error)")
PeachWindowController.showWarning("Failed saving keywords: \(error)")
}
selectedKeywords = FilesAndKeywords(mediaItems: selectedItems)
mediaKeywordsController.selectionChanged(selectedKeywords)
allKeywordsController.selectionChanged(selectedKeywords)
}
func postSelectedItem(_ mediaData: MediaData)
{
let userInfo: [String: MediaData] = ["MediaData": mediaData]
Notifications.postNotification(Notifications.Selection.MediaData, object: self, userInfo: userInfo)
}
func postNoSelection()
{
Notifications.postNotification(Notifications.Selection.MediaData, object: self, userInfo: nil)
}
func setStatus(_ message: String)
{
Logger.info("Status message changed: '\(message)'")
statusLabel.stringValue = message
}
func setStatusMediaNumber(_ fileNumber: Int)
{
statusFileLabel.stringValue = String(fileNumber)
}
func setStatusLocationInfo(_ count: Int, status: LocationStatus)
{
let message = String(count)
var imageName = "location"
if status == .sensitiveLocation {
statusLocationLabel.attributedTitle = NSMutableAttributedString(string: message, attributes: PeachWindowController.badDataAttrs)
imageName = "locationBad"
} else if status == .missingLocation {
statusLocationLabel.attributedTitle = NSMutableAttributedString(string: message, attributes: PeachWindowController.missingAttrs)
imageName = "locationMissing"
} else {
statusLocationLabel.title = message
}
statusLocationLabel.image = NSImage(imageLiteralResourceName: imageName)
}
func setStatusDateInfo(_ count: Int, status: DateStatus)
{
let message = String(count)
var imageName = "timestamp"
if status == .mismatchedDate {
statusDateLabel.attributedTitle = NSMutableAttributedString(string: message, attributes: PeachWindowController.badDataAttrs)
imageName = "timestampBad"
} else {
statusDateLabel.title = message
}
statusDateLabel.image = NSImage(imageLiteralResourceName: imageName)
}
func setStatusKeywordInfo(_ count: Int, status: KeywordStatus)
{
let message = String(count)
var imageName = "keyword"
if status == .noKeyword {
statusKeywordLabel.attributedTitle = NSMutableAttributedString(string: message, attributes: PeachWindowController.missingAttrs)
imageName = "keywordMissing"
} else {
statusKeywordLabel.title = message
}
statusKeywordLabel.image = NSImage(imageLiteralResourceName: imageName)
}
func setSingleItemStatus(_ media: MediaData)
{
var locationString = media.locationString()
var keywordsString = media.keywordsString()
if media.keywords == nil || media.keywords.count == 0 {
keywordsString = "< no keywords >"
} else {
keywordsString = media.keywords.joined(separator: ", ")
}
if media.location != nil && media.location.hasPlacename() {
locationString = media.location.placenameAsString(Preferences.placenameFilter)
}
setStatus(String("\(media.name!); \(locationString); \(keywordsString)"))
if let location = media.location {
if !location.hasPlacename() {
// There's a location, but the placename hasn't been resolved yet
Async.background {
let placename = media.location.placenameAsString(Preferences.placenameFilter)
Async.main {
self.setStatus("\(media.name!); \(placename); \(keywordsString)")
}
}
}
}
}
func setMultiItemStatus(_ mediaItems: [MediaData], filesMessage: String)
{
var folderKeywords = Set<String>()
for media in mediaItems {
if let mediaKeywords = media.keywords {
for k in mediaKeywords {
folderKeywords.insert(k)
}
}
}
let keywordsString = folderKeywords.joined(separator: ", ")
setStatus("keywords: \(keywordsString)")
}
func setFolderStatus()
{
var mediaFiles = [MediaData]()
for (_, m) in mediaProvider.enumerated() {
mediaFiles.append(m)
}
setMultiItemStatus(mediaFiles, filesMessage: "files")
setStatusMediaInfo()
}
func setStatusMediaInfo()
{
var numberMissingLocation = 0
var numberWithSensitiveLocation = 0
var numberWithMismatchedDate = 0
var numberMissingKeyword = 0
for (_, media) in mediaProvider.enumerated() {
if let location = media.location {
if SensitiveLocations.sharedInstance.isSensitive(location) {
numberWithSensitiveLocation += 1
}
} else {
numberMissingLocation += 1
}
if media.keywords == nil {
numberMissingKeyword += 1
}
if media.doFileAndExifTimestampsMatch() == false {
numberWithMismatchedDate += 1
}
}
let mediaCount = mediaProvider.mediaCount
setStatusMediaNumber(mediaCount)
if numberWithSensitiveLocation > 0 {
setStatusLocationInfo(numberWithSensitiveLocation, status: .sensitiveLocation)
}
else if numberMissingLocation > 0 {
setStatusLocationInfo(numberMissingLocation, status: .missingLocation)
} else {
setStatusLocationInfo(mediaCount, status: .goodLocation)
}
if numberWithMismatchedDate > 0 {
setStatusDateInfo(numberWithMismatchedDate, status: .mismatchedDate)
} else {
setStatusDateInfo(mediaCount, status: .goodDate)
}
if numberMissingKeyword > 0 {
setStatusKeywordInfo(numberMissingKeyword, status: .noKeyword)
} else {
setStatusKeywordInfo(mediaCount, status: .hasKeyword)
}
}
}
open class ThumbnailViewItem : NSObject
{
public let mediaData: MediaData
init(mediaData: MediaData) {
self.mediaData = mediaData
}
open override func imageUID() -> String! {
return mediaData.url.path
}
open override func imageRepresentationType() -> String! {
switch mediaData.type! {
case .image:
return IKImageBrowserNSURLRepresentationType
case .video:
return IKImageBrowserQTMoviePathRepresentationType
default:
return IKImageBrowserNSURLRepresentationType
}
}
open override func imageRepresentation() -> Any! {
switch mediaData.type! {
case .image:
return mediaData.url
case .video:
return mediaData.url
default:
return mediaData.url
}
}
}
public enum LocationStatus
{
case missingLocation
case sensitiveLocation
case goodLocation
}
public enum DateStatus
{
case goodDate
case mismatchedDate
}
public enum KeywordStatus
{
case noKeyword
case hasKeyword
}
| mit | 22879ac06a17c825dcd34754374ec058 | 29.510417 | 140 | 0.599693 | 5.15669 | false | false | false | false |
thinkaboutiter/SimpleLogger | Sources/SimpleLogger/Writers/MultipleFilesLogWriter.swift | 1 | 3206 | //
// MultipleFilesLogWriter.swift
// SimpleLogger
//
// The MIT License (MIT)
//
// Copyright (c) 2020 thinkaboutiter ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
struct MultipleFilesLogWriter {
// MARK: - Properties
private static var logsDirectoryPath: String = ""
static func setLogsDirectoryPath(_ newValue: String) {
MultipleFilesLogWriter.logsDirectoryPath = newValue
guard MultipleFilesLogWriter.logsDirectoryPath.count > 0 else {
return
}
MultipleFilesLogWriter.createLogsDirectory(at: self.logsDirectoryPath)
}
/// We should have only one logs directory.
private static var didCreateLogsDirectory: Bool = false
// MARK: - Initialization
private init() {}
// MARK: - Utils
static func write(_ candidate: String,
toFile fileName: String) throws
{
guard MultipleFilesLogWriter.didCreateLogsDirectory else {
let message: String = "Logs directory not available"
print(message)
throw Error.writeToFile(reason: message)
}
let path_candidate: String = "\(MultipleFilesLogWriter.logsDirectoryPath)/\(fileName)\(Constants.logFileExtension)"
guard let valid_absolutePath: String = WriterUtils.absoulutePathString(from: path_candidate) else {
let message: String = "Invalid log file path!"
print(message)
throw Error.writeToFile(reason: message)
}
try WriterUtils.write(candidate, toFileAtPath: valid_absolutePath)
}
private static func createLogsDirectory(at path: String) {
guard !MultipleFilesLogWriter.didCreateLogsDirectory else {
return
}
self.didCreateLogsDirectory = WriterUtils.createDirectory(at: path)
}
}
// MARK: - Constants
extension MultipleFilesLogWriter {
private enum Constants {
static let logFileExtension: String = ".log"
}
}
// MARK: - Error
extension MultipleFilesLogWriter {
enum Error: Swift.Error {
case writeToFile(reason: String)
}
}
| mit | 7849e5f988f550f69c2fbc5ec17a8a97 | 35.431818 | 123 | 0.691828 | 4.626263 | false | false | false | false |
zdima/ZDComboBox | ZDComboBox/ZDComboBoxTreeContent.swift | 1 | 4147 | //
// ZDComboBoxTreeContent.swift
// combobox
//
// Created by Dmitriy Zakharkin on 8/9/15.
// Copyright (c) 2015 ZDima. All rights reserved.
//
import Cocoa
class ZDComboBoxTree: ZDPopupContent, NSOutlineViewDelegate {
var disableSelectionNotification: Bool = false
@IBOutlet var itemController: NSTreeController!
@IBOutlet var tree: NSOutlineView!
let recordSortDescriptors = [
NSSortDescriptor(key: "title", ascending: true)
]
@IBAction func performClick(sender: AnyObject) {
// hide popup when user select item by click
ZDPopupWindowManager.popupManager.hidePopup()
}
override func invalidateFilter() {
if !filter.isEmpty {
var filteredContent: [ZDComboBoxItem] = []
for item in items {
if let filtered = item.selfOrHasChildWithKey( filter.lowercaseString ) {
filteredContent.append(filtered)
}
}
itemController.content = filteredContent
} else {
itemController.content = items
}
tree.expandItem(nil, expandChildren: true)
}
override func viewWillAppear() {
invalidateFilter()
tree.expandItem( nil, expandChildren: true)
super.viewWillAppear()
}
func makeSelectionVisible() {
var selRect: NSRect = tree!.rectOfRow( tree!.selectedRow )
tree.scrollRectToVisible( selRect )
}
override func moveSelectionUp(up: Bool) {
var i: Int = tree!.selectedRow
if up {
i = i-1
} else {
i = i+1
}
if i < 0 {
return
}
tree.selectRowIndexes( NSIndexSet(index: i), byExtendingSelection: false)
makeSelectionVisible()
}
func outlineViewSelectionDidChange(notification: NSNotification) {
if disableSelectionNotification == false {
let sa: NSArray = itemController.selectedObjects
delegate!.selectionDidChange( sa, fromUpDown: true)
}
}
func outlineView(outlineView: NSOutlineView,
shouldShowOutlineCellForItem item: AnyObject) -> Bool {
return true
}
func outlineView(outlineView: NSOutlineView,
shouldShowCellExpansionForTableColumn tableColumn: NSTableColumn?, item: AnyObject) -> Bool {
return false
}
func childByName(name: String, children: [AnyObject],
indexes: NSMutableArray) -> Bool {
var i: Int = 0
var ret: Bool = false
let maxCount: Int = children.count
let stringLength: Int = count(name) as Int
let stringRange: NSRange = NSRange(location: 0, length:stringLength)
for object in children {
if let item: ZDComboBoxItem = object as? ZDComboBoxItem {
indexes.addObject(NSNumber(integer: i))
if item.title.lowercaseString.hasPrefix(name.lowercaseString) {
ret = true
break
} else {
ret = childByName(name,
children: (item.childs as NSArray).sortedArrayUsingDescriptors(recordSortDescriptors),
indexes: indexes)
if ret == true {
break
}
indexes.removeLastObject()
}
}
i = i+1
}
return ret
}
override func moveSelectionTo(string: String?, filtered: Bool) -> NSString? {
disableSelectionNotification = true
var indexes: NSMutableArray = NSMutableArray()
if filtered {
if string != nil {
filter = string!
} else {
filter = ""
}
} else {
filter = ""
}
if let children = itemController.content as? NSArray {
let sortedchildren = children.sortedArrayUsingDescriptors(recordSortDescriptors)
if childByName(string!, children:sortedchildren, indexes:indexes) {
var selection: NSIndexPath? = nil;
for n in indexes {
if let num: NSNumber = n as? NSNumber {
if selection != nil {
selection = selection!.indexPathByAddingIndex(num.integerValue)
} else {
selection = NSIndexPath(index: num.integerValue )
}
}
}
itemController.setSelectionIndexPath( selection )
var sa: NSArray = itemController.selectedObjects;
if let c: ZDComboBoxItem = sa.firstObject as? ZDComboBoxItem {
var s: String = c.title
disableSelectionNotification = false
return s;
}
}
}
disableSelectionNotification = false
makeSelectionVisible()
return nil;//i != self.tree.selectedRow;
}
override func convertUserObjectToItems() {
super.convertUserObjectToItems()
itemController.content = items
}
}
| mit | bc46b6f3fdac5ce0b56fe857e82c250e | 24.441718 | 95 | 0.699783 | 3.736036 | false | false | false | false |
abeschneider/stem | Sources/Op/MulOp.swift | 1 | 2691 | //
// mul.swift
// stem
//
// Created by Schneider, Abraham R. on 11/12/16.
// Copyright © 2016 none. All rights reserved.
//
import Foundation
import Tensor
open class MulOp<S:Storage>: Op<S> where S.ElementType:FloatNumericType {
open var _input:[Tensor<S>] {
let _in:[Source<S>] = inputs[0]
return _in.map { $0.output }
}
public init(_ ops:Op<S>...) {
super.init(inputs: ["input"], outputs: ["output"])
connect(from: ops, "output", to: self, "input")
outputs["output"] = [Tensor<S>](repeating: zeros(_input[0].shape), count: _input.count)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
open override func apply() {
if output.shape != _input[0].shape {
output.resize(_input[0].shape)
}
copy(from: _input[0], to: output)
for o in _input[1..<_input.count] {
imul(output, o)
}
}
}
open class MulOpGrad<S:Storage>: Op<S>, Gradient where S.ElementType:FloatNumericType {
open var _op:Tensor<S> { return inputs[0].output }
open var _input:[Tensor<S>] {
let _in:[Source<S>] = inputs[1]
return _in.map { $0.output }
}
open var _gradOutput:Tensor<S> { return inputs[2].output }
public required init(op:MulOp<S>) {
super.init(inputs: ["op", "input", "gradOutput"], outputs: ["output"])
let opInputs:[Source<S>] = op.inputs[0]
connect(from: op, "output", to: self, "op")
connect(from: opInputs.map { $0.op! }, "output", to: self, "input")
outputs["output"] = [Tensor<S>](repeating: Tensor<S>(_input[0].shape), count: _input.count)
}
required public init(op: Op<S>, shared: Bool) {
fatalError("init(op:shared:) has not been implemented")
}
open override func apply() {
if outputs["output"]!.count != _input.count {
outputs["output"] = [Tensor<S>](repeating: Tensor<S>(_input[0].shape), count: _input.count)
}
// TODO: there is a more efficient way to implement this
for (i, out) in outputs[0].enumerated() {
copy(from: _gradOutput, to: out)
for (j, output) in _input.enumerated() {
if i != j {
imul(out, output)
}
}
}
}
open override func reset() {
for out in outputs["output"]! {
fill(out, value: 0)
}
}
}
extension MulOp: Differentiable {
public func gradient() -> GradientType {
return MulOpGrad<S>(op: self)
}
}
| mit | 990488d03239c42dea51e00f209dcc7c | 29.224719 | 103 | 0.540892 | 3.625337 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.