repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cotkjaer/Silverback
|
Silverback/Dropbox.swift
|
1
|
6961
|
//
// Dropbox.swift
// Silverback
//
// Created by Christian Otkjær on 15/01/16.
// Copyright © 2016 Christian Otkjær. All rights reserved.
//
import Foundation
import UIKit
import ContactsUI
public class ConnectionEndpoint
{
public enum Type
{
case None, InnerEllipse //, OuterEllipse, Frame, Border
func pathForFrame(frame: CGRect?) -> UIBezierPath
{
if let f = frame
{
switch self
{
case .None:
return UIBezierPath()
case .InnerEllipse:
return UIBezierPath(ovalInRect: f)
}
}
return UIBezierPath()
}
}
required public init() { }
public var type : Type = .None
func pathForFrame(frame:CGRect?) -> UIBezierPath
{
return type.pathForFrame(frame)
}
func pointOnRimAtAngle(theta: CGFloat?, forFrame frame:CGRect?) -> CGPoint?
{
if let f = frame, let a = theta
{
switch type
{
case .None:
return f.center
case .InnerEllipse:
return CGPoint(x: cos(a) * f.width / 2, y: sin(a) * f.height / 2) + f.center
}
}
return nil
}
}
public class Connection: CAShapeLayer
{
var location = CGPointZero
private let fromEndpoint = ConnectionEndpoint()
private let toEndpoint = ConnectionEndpoint()
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
setup()
}
override public init()
{
super.init()
setup()
}
func setup()
{
fillColor = nil
fillRule = kCAFillRuleNonZero
lineCap = kCALineCapRound
lineDashPattern = nil
lineDashPhase = 0.0
lineJoin = kCALineJoinRound
lineWidth = 0.66
miterLimit = lineWidth * 2
strokeColor = UIColor.grayColor().CGColor
fromEndpoint.type = .InnerEllipse
toEndpoint.type = .InnerEllipse
}
public enum ConnectionAnchor
{
case
Right,
Left,
Up,
Down,
None
var opposite : ConnectionAnchor
{
switch self
{
case .Up:
return .Down
case .Down:
return .Up
case .Left:
return .Right
case .Right:
return .Left
case .None:
return .None
}
}
var angle : CGFloat?
{
switch self
{
case .Up:
return 3 * π / 2
case .Down:
return π / 2
case .Left:
return π
case .Right:
return 0
case .None:
return nil
}
}
}
public var fromFrame: CGRect?
{ didSet { if oldValue != fromFrame { updateConnection() } } }
public var toFrame: CGRect?
{ didSet { if oldValue != toFrame { updateConnection() } } }
public var fromAnchor : ConnectionAnchor = .None
{ didSet { if oldValue != fromAnchor { updateConnection() } } }
public var toAnchor : ConnectionAnchor = .None
{ didSet { if oldValue != toAnchor { updateConnection() } } }
public func updateConnection()
{
let bezierPath = fromEndpoint.pathForFrame(fromFrame)
if let fromFrame = self.fromFrame, let toFrame = self.toFrame
{
var controlPoint1 = CGPoint()
var controlPoint2 = CGPoint()
var fromPoint = CGPoint()
var toPoint = CGPoint()
if let point = fromEndpoint.pointOnRimAtAngle(fromAnchor.angle, forFrame:fromFrame)
{
fromPoint = point
bezierPath.moveToPoint(fromPoint)
}
if let point = toEndpoint.pointOnRimAtAngle(toAnchor.angle, forFrame:toFrame)
{
toPoint = point
}
bezierPath.moveToPoint(fromPoint)
switch toAnchor
{
case .Up:
toPoint = toFrame.topCenter
controlPoint2 = toPoint.with(y: (fromPoint.y + toPoint.y) / 2)
case .Down:
toPoint = toFrame.bottomCenter
controlPoint2 = toPoint.with(y: (fromPoint.y + toPoint.y) / 2)
case .Left:
toPoint = toFrame.centerLeft
controlPoint2 = toPoint.with(x: (fromPoint.x + toPoint.x) / 2)
case .Right:
toPoint = toFrame.centerRight
controlPoint2 = toPoint.with(x: (fromPoint.x + toPoint.x) / 2)
case .None:
bezierPath.removeAllPoints()
path = nil
return
}
switch fromAnchor
{
case .Up:
controlPoint1 = fromPoint.with(y: (fromPoint.y + toPoint.y) / 2)
case .Down:
controlPoint1 = fromPoint.with(y: (fromPoint.y + toPoint.y) / 2)
case .Left:
controlPoint1 = fromPoint.with(x: (fromPoint.x + toPoint.x) / 2)
case .Right:
controlPoint1 = fromPoint.with(x: (fromPoint.x + toPoint.x) / 2)
case .None:
bezierPath.removeAllPoints()
path = nil
return
}
bezierPath.addCurveToPoint(toPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2)
bezierPath.appendPath(toEndpoint.pathForFrame(toFrame))
}
path = bezierPath.CGPath
}
//MARK: - Animation
public var animatePath : Bool = false
override public func actionForKey(event: String) -> CAAction?
{
if event == "path" && animatePath
{
let animation = CABasicAnimation(keyPath: event)
animation.duration = CATransaction.animationDuration()
animation.timingFunction = CATransaction.animationTimingFunction()
return animation
}
return super.actionForKey(event)
}
}
// MARK: - CNContactPickerViewController
@available(iOS 9.0, *)
extension CNContactPickerViewController
{
@available(iOS 9.0, *)
public convenience init(delegate: CNContactPickerDelegate)
{
self.init()
self.delegate = delegate
}
}
|
mit
|
e778ae58beb7f391b3fe8b4a757a6291
| 25.344697 | 107 | 0.488857 | 5.329502 | false | false | false | false |
EaglesoftZJ/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleVoiceCell.swift
|
1
|
19905
|
//
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
import VBFPopFlatButton
import YYImage
open class AABubbleVoiceCell: AABubbleBaseFileCell,AAModernConversationAudioPlayerDelegate,AAModernViewInlineMediaContextDelegate {
// Views
fileprivate let progress = AAProgressView(size: CGSize(width: 44, height: 44))
fileprivate let timeLabel = AttributedLabel()
fileprivate let voiceTimeLabel = AttributedLabel()
fileprivate let playPauseButton = UIButton()
fileprivate let soundProgressSlider = UISlider()
fileprivate let statusView = UIImageView()
fileprivate let durationLabel = AttributedLabel()
fileprivate let titleLabel = AttributedLabel()
// Binded data
var bindedLayout: VoiceMessageCellLayout!
var thumbLoaded = false
var contentLoaded = false
// Constructors
public init(frame: CGRect) {
super.init(frame: frame, isFullSize: false)
////////////////////////////////////////////////////
timeLabel.font = UIFont.italicSystemFont(ofSize: 11)
timeLabel.textColor = appStyle.chatTextDateOutColor
////////////////////////////////////////////////////
statusView.contentMode = UIViewContentMode.center
////////////////////////////////////////////////////
soundProgressSlider.tintColor = appStyle.chatStatusSending
soundProgressSlider.isUserInteractionEnabled = false
//soundProgressSlider.addTarget(self, action: "seekToNewAudioValue", forControlEvents: UIControlEvents.ValueChanged)
let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
let trackLeftImage = UIImage.tinted("aa_voiceplaybackground", color: UIColor(red: 0.0, green: 0.761, blue: 0.9964, alpha: 1.0 ))
let trackLeftResizable = trackLeftImage.resizableImage(withCapInsets: insets)
soundProgressSlider.setMinimumTrackImage(trackLeftResizable, for: UIControlState())
let trackRightImage = UIImage.tinted("aa_voiceplaybackground", color: UIColor(red: 0.0, green: 0.5856, blue: 0.9985, alpha: 1.0 ))
let trackRightResizable = trackRightImage.resizableImage(withCapInsets: insets)
soundProgressSlider.setMaximumTrackImage(trackRightResizable, for: UIControlState())
let thumbImageNormal = UIImage.bundled("aa_thumbvoiceslider")
soundProgressSlider.setThumbImage(thumbImageNormal, for: UIControlState())
////////////////////////////////////////////////////
voiceTimeLabel.font = UIFont.italicSystemFont(ofSize: 11)
voiceTimeLabel.textColor = appStyle.chatTextDateOutColor
////////////////////////////////////////////////////
durationLabel.font = UIFont.systemFont(ofSize: 11.0)
durationLabel.textColor = appStyle.chatTextDateOutColor
durationLabel.text = " "
durationLabel.sizeToFit()
////////////////////////////////////////////////////
durationLabel.layer.drawsAsynchronously = true
progress.layer.drawsAsynchronously = true
playPauseButton.layer.drawsAsynchronously = true
soundProgressSlider.layer.drawsAsynchronously = true
voiceTimeLabel.layer.drawsAsynchronously = true
timeLabel.layer.drawsAsynchronously = true
statusView.layer.drawsAsynchronously = true
////////////////////////////////////////////////////
contentView.addSubview(durationLabel)
contentView.addSubview(progress)
contentView.addSubview(playPauseButton)
contentView.addSubview(soundProgressSlider)
contentView.addSubview(voiceTimeLabel)
contentView.addSubview(timeLabel)
contentView.addSubview(statusView)
////////////////////////////////////////////////////
playPauseButton.setImage(UIImage.bundled("aa_playrecordbutton"), for: UIControlState())
playPauseButton.addTarget(self, action: #selector(AABubbleVoiceCell.mediaDidTap), for: UIControlEvents.touchUpInside)
contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1)
let longPressTap = UILongPressGestureRecognizer(target:self,action:#selector(AABubbleCell.longTap(tap:)))
self.contentView.isUserInteractionEnabled = true
self.contentView.addGestureRecognizer(longPressTap)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Binding
open override func bind(_ message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) {
self.bindedLayout = cellLayout as! VoiceMessageCellLayout
let document = message.content as! ACVoiceContent
bubbleInsets = UIEdgeInsets(
top: setting.clenchTop ? AABubbleCell.bubbleTopCompact : AABubbleCell.bubbleTop,
left: 10 + (AADevice.isiPad ? 16 : 0),
bottom: setting.clenchBottom ? AABubbleCell.bubbleBottomCompact : AABubbleCell.bubbleBottom,
right: 10 + (AADevice.isiPad ? 16 : 0))
if (!reuse) {
// Bind bubble
if (self.isOut) {
bindBubbleType(BubbleType.mediaOut, isCompact: false)
} else {
bindBubbleType(BubbleType.mediaIn, isCompact: false)
}
titleLabel.text = AALocalized("ChatVoiceMessage")
durationLabel.text = bindedLayout.voiceDuration
// Reset progress
self.progress.hideButton()
UIView.animate(withDuration: 0, animations: { () -> Void in
self.progress.isHidden = true
})
// Bind file
let autoDownload: Bool
if self.peer.isGroup {
autoDownload = ActorSDK.sharedActor().isAudioAutoDownloadGroup
} else if self.peer.isPrivate {
autoDownload = ActorSDK.sharedActor().isAudioAutoDownloadPrivate
} else {
autoDownload = false
}
fileBind(message, autoDownload: autoDownload)
}
dispatchOnUi { () -> Void in
//let content = bindedMessage!.content as! ACDocumentContent
let content = self.bindedMessage!.content as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
let fileID = fileSource.getFileReference().getFileId()
if self.controller.currentAudioFileId != fileID {
self.soundProgressSlider.value = 0.0
self.playPauseButton.setImage(UIImage.bundled("aa_playrecordbutton"), for: UIControlState())
self.controller.voiceContext?.removeDelegate(self)
} else {
self.controller.voiceContext?.delegate = self
self.controller.voicePlayer?.delegate = self
if self.controller.voicePlayer?.isPaused() == false {
self.playPauseButton.setImage(UIImage.bundled("aa_pauserecordbutton"), for: UIControlState())
} else {
self.playPauseButton.setImage(UIImage.bundled("aa_playrecordbutton"), for: UIControlState())
}
}
if let progressVoice = self.controller.voicesCache[fileID] {
if progressVoice > 0.0 {
self.soundProgressSlider.value = progressVoice
}
}
}
}
// Update time
timeLabel.text = cellLayout.date
// Update status
if (isOut) {
statusView.isHidden = false
switch(message.messageState.toNSEnum()) {
case .SENT:
if message.sortDate <= readDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusRead
} else if message.sortDate <= receiveDate {
self.statusView.image = appStyle.chatIconCheck2
self.statusView.tintColor = appStyle.chatStatusReceived
} else {
self.statusView.image = appStyle.chatIconCheck1
self.statusView.tintColor = appStyle.chatStatusSent
}
case .ERROR:
self.statusView.image = appStyle.chatIconError
self.statusView.tintColor = appStyle.chatStatusError
break
default:
self.statusView.image = appStyle.chatIconClock
self.statusView.tintColor = appStyle.chatStatusSending
break
}
} else {
statusView.isHidden = true
}
}
//MARK: - File state binding
open override func fileStateChanged(_ reference: String?, progress: Int?, isPaused: Bool, isUploading: Bool, selfGeneration: Int) {
runOnUiThread(selfGeneration) { () -> () in
if isUploading {
if isPaused {
self.playPauseButton.hideView()
self.progress.showView()
self.progress.setButtonType(FlatButtonType.buttonUpBasicType, animated: true)
self.progress.hideProgress()
} else {
self.playPauseButton.hideView()
self.progress.showView()
self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true)
self.progress.setProgress(Double(progress!)/100.0)
}
} else {
if (reference != nil) {
self.playPauseButton.showView()
self.progress.setProgress(1)
self.progress.hideView()
} else if isPaused {
self.playPauseButton.hideView()
self.progress.showView()
self.progress.setButtonType(FlatButtonType.buttonDownloadType, animated: true)
self.progress.hideProgress()
} else {
self.playPauseButton.hideView()
self.progress.showView()
self.progress.setButtonType(FlatButtonType.buttonPausedType, animated: true)
self.progress.setProgress(Double(progress!)/100.0)
}
}
}
}
//MARK: - Media Action
open func mediaDidTap() {
let content = bindedMessage!.content as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
Actor.requestState(withFileId: fileSource.getFileReference().getFileId(), with: AAFileCallback(
notDownloaded: { () -> () in
Actor.startDownloading(with: fileSource.getFileReference())
}, onDownloading: { (progress) -> () in
Actor.cancelDownloading(withFileId: fileSource.getFileReference().getFileId())
}, onDownloaded: { (reference) -> () in
dispatchOnUi({ () -> Void in
let path = CocoaFiles.pathFromDescriptor(reference)
let fileID = fileSource.getFileReference().getFileId()
self.controller.playVoiceFromPath(path,fileId: fileID,position:self.soundProgressSlider.value)
self.playPauseButton.setImage(UIImage.bundled("aa_pauserecordbutton"), for: UIControlState())
self.controller.voicePlayer.delegate = self
self.controller.voiceContext.delegate = self
})
}))
} else if let fileSource = content.getSource() as? ACFileLocalSource {
let rid = bindedMessage!.rid
Actor.requestUploadState(withRid: rid, with: AAUploadFileCallback(
notUploaded: { () -> () in
Actor.resumeUpload(withRid: rid)
}, onUploading: { (progress) -> () in
Actor.pauseUpload(withRid: rid)
}, onUploadedClosure: { () -> () in
dispatchOnUi({ () -> Void in
let path = CocoaFiles.pathFromDescriptor(fileSource.getFileDescriptor())
let content = self.bindedMessage!.content as! ACDocumentContent
if let fileSource = content.getSource() as? ACFileRemoteSource {
let fileID = fileSource.getFileReference().getFileId()
self.controller.playVoiceFromPath(path,fileId: fileID,position:self.soundProgressSlider.value)
self.playPauseButton.setImage(UIImage.bundled("aa_pauserecordbutton"), for: UIControlState())
self.controller.voicePlayer.delegate = self
self.controller.voiceContext.delegate = self
}
})
}))
}
}
open func seekToNewAudioValue() {
}
open func audioPlayerDidFinish() {
dispatchOnUi { () -> Void in
self.playPauseButton.setImage(UIImage.bundled("aa_playrecordbutton"), for: UIControlState())
self.soundProgressSlider.value = 0.0
self.controller.voicesCache[self.controller.currentAudioFileId] = 0.0
}
}
open func inlineMediaPlaybackStateUpdated(_ isPaused: Bool, playbackPosition: Float, timestamp: TimeInterval, preciseDuration: TimeInterval) {
dispatchOnUi({ () -> Void in
self.soundProgressSlider.value = playbackPosition
if (isPaused == true) {
self.playPauseButton.setImage(UIImage.bundled("aa_playrecordbutton"), for: UIControlState())
}
self.controller.voicesCache[self.controller.currentAudioFileId] = playbackPosition
})
}
//MARK: - Layouting
open override func layoutContent(_ maxWidth: CGFloat, offsetX: CGFloat) {
let insets = fullContentInsets
let contentWidth = self.contentView.frame.width
layoutBubble(200, contentHeight: 55)
let contentLeft = self.isOut ? contentWidth - 200 - insets.right - contentInsets.left : insets.left
let top = insets.top - 2
// Progress state
let progressRect = CGRect(x: contentLeft + 7.5, y: 7.5 + top, width: 44, height: 44)
self.progress.frame = progressRect
self.playPauseButton.frame = progressRect
timeLabel.frame = CGRect(x: 0, y: 0, width: 1000, height: 1000)
timeLabel.sizeToFit()
// Content
self.soundProgressSlider.frame = CGRect(x: contentLeft + 62, y: 16 + top, width: 200 - 70, height: 22)
self.durationLabel.frame = CGRect(x: contentLeft + 62, y: 10 + 25 + top, width: 200 - 64, height: 22)
// Message state
if (self.isOut) {
self.timeLabel.frame = CGRect(x: self.bubble.frame.maxX - 55 - self.bubblePadding, y: self.bubble.frame.maxY - 24, width: 46, height: 26)
self.statusView.frame = CGRect(x: self.bubble.frame.maxX - 24 - self.bubblePadding, y: self.bubble.frame.maxY - 24, width: 20, height: 26)
self.statusView.isHidden = false
} else {
self.timeLabel.frame = CGRect(x: self.bubble.frame.maxX - 47 - self.bubblePadding, y: self.bubble.frame.maxY - 24, width: 46, height: 26)
self.statusView.isHidden = true
}
}
}
/**
Voice cell layout
*/
open class VoiceMessageCellLayout: AACellLayout {
open let contentSize: CGSize
open let screenSize: CGSize
open let autoDownload: Bool
open let fileName: String
open let fileExt: String
open let fileSize: String
open var voiceDuration: String!
/**
Creting layout for media bubble
*/
public init(fileName: String, fileExt: String, fileSize: Int,id: Int64, date: Int64, autoDownload: Bool,duration:jint, layouter: AABubbleLayouter) {
// Saving content size
self.contentSize = CGSize(width: 200, height: 55)
// Saving autodownload flag
self.autoDownload = autoDownload
// Calculating bubble screen size
self.screenSize = CGSize(width: 200, height: 55)
self.fileName = fileName
self.fileExt = fileExt.lowercased()
self.fileSize = Actor.getFormatter().formatFileSize(jint(fileSize))
// Creating layout
super.init(height: self.screenSize.height + 2, date: date, key: "voice", layouter: layouter)
self.voiceDuration = getTimeString(Int(duration))
}
func getTimeString(_ totalSeconds:Int) -> String {
let seconds = Int(totalSeconds % 60)
let minutes = Int((totalSeconds / 60) % 60)
if minutes < 10 {
if seconds < 10 {
return "0\(minutes):0\(seconds)"
} else {
return "0\(minutes):\(seconds)"
}
} else {
if seconds < 10 {
return "\(minutes):0\(seconds)"
} else {
return "\(minutes):\(seconds)"
}
}
}
/**
Creating layout for voice content
*/
public convenience init(id: Int64, voiceContent: ACVoiceContent, date: Int64, layouter: AABubbleLayouter) {
self.init(fileName: voiceContent.getName(), fileExt: voiceContent.getExt(), fileSize: Int(voiceContent.getSource().getSize()),id: id, date: date, autoDownload: true,duration:jint(voiceContent.getDuration()/1000), layouter: layouter)
}
/**
Creating layout for message
*/
public convenience init(message: ACMessage, layouter: AABubbleLayouter) {
if let content = message.content as? ACVoiceContent {
self.init(id: Int64(message.rid), voiceContent: content, date: Int64(message.date), layouter: layouter)
} else {
fatalError("Unsupported content for media cell")
}
}
}
/**
Layouter for voice bubbles
*/
open class AABubbleVoiceCellLayouter: AABubbleLayouter {
open func isSuitable(_ message: ACMessage) -> Bool {
if message.content is ACVoiceContent {
return true
}
return false
}
open func buildLayout(_ peer: ACPeer, message: ACMessage) -> AACellLayout {
return VoiceMessageCellLayout(message: message, layouter: self)
}
open func cellClass() -> AnyClass {
return AABubbleVoiceCell.self
}
}
|
agpl-3.0
|
e1859225dde5bb2b0a275e7cb66e441e
| 38.651394 | 240 | 0.55574 | 5.391387 | false | false | false | false |
datomnurdin/iOS-CircleProgressView
|
CircleProgressView/ViewController.swift
|
2
|
1933
|
//
// ViewController.swift
// CircleProgressView
//
// Created by Eric Rolf on 8/11/14.
// Copyright (c) 2014 Eric Rolf, Cardinal Solutions Group. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var circleProgressView: CircleProgressView!
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var progressSlider: UISlider!
@IBOutlet weak var clockwiseSwitch: UISwitch!
let nf = NSNumberFormatter()
override func viewDidLoad() {
super.viewDidLoad()
nf.numberStyle = NSNumberFormatterStyle.DecimalStyle
nf.maximumFractionDigits = 2
self.clockwiseSwitch.setOn(self.circleProgressView.clockwise, animated: false)
self.progressSlider.value = Float(self.circleProgressView.progress)
self.progressLabel.text = "Progress: " + nf.stringFromNumber(NSNumber(double: self.circleProgressView.progress))!
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - IBActions
@IBAction func sliderDidChangeValue(sender: AnyObject) {
let slider:UISlider = sender as! UISlider
self.circleProgressView.progress = Double(slider.value)
self.progressLabel.text = "Progress: " + nf.stringFromNumber(NSNumber(double: self.circleProgressView.progress))!
}
@IBAction func switchDidChangeValue(sender: AnyObject) {
let mySwitch:UISwitch = sender as! UISwitch
self.circleProgressView.clockwise = mySwitch.on
self.circleProgressView.progress = self.circleProgressView.progress
}
// MARK: - Helpers
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
|
mit
|
8d017a582e4a1eaaece5e5b1ce177af2
| 31.762712 | 121 | 0.665287 | 4.844612 | false | false | false | false |
apple/swift-async-algorithms
|
Sources/AsyncAlgorithms/AsyncThrowingExclusiveReductionsSequence.swift
|
1
|
4766
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
extension AsyncSequence {
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given error-throwing closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as an asynchronous sequence.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence and returns
/// the result. If the closure throws an error, the sequence throws.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
public func reductions<Result>(_ initial: Result, _ transform: @Sendable @escaping (Result, Element) async throws -> Result) -> AsyncThrowingExclusiveReductionsSequence<Self, Result> {
reductions(into: initial) { result, element in
result = try await transform(result, element)
}
}
/// Returns an asynchronous sequence containing the accumulated results of combining the
/// elements of the asynchronous sequence using the given error-throwing closure.
///
/// This can be seen as applying the reduce function to each element and
/// providing the initial value followed by these results as an asynchronous sequence.
///
/// - Parameters:
/// - initial: The value to use as the initial value.
/// - transform: A closure that combines the previously reduced result and
/// the next element in the receiving asynchronous sequence, mutating the
/// previous result instead of returning a value. If the closure throws an
/// error, the sequence throws.
/// - Returns: An asynchronous sequence of the initial value followed by the reduced
/// elements.
@inlinable
public func reductions<Result>(into initial: Result, _ transform: @Sendable @escaping (inout Result, Element) async throws -> Void) -> AsyncThrowingExclusiveReductionsSequence<Self, Result> {
AsyncThrowingExclusiveReductionsSequence(self, initial: initial, transform: transform)
}
}
/// An asynchronous sequence of applying an error-throwing transform to the element of
/// an asynchronous sequence and the previously transformed result.
@frozen
public struct AsyncThrowingExclusiveReductionsSequence<Base: AsyncSequence, Element> {
@usableFromInline
let base: Base
@usableFromInline
let initial: Element
@usableFromInline
let transform: @Sendable (inout Element, Base.Element) async throws -> Void
@inlinable
init(_ base: Base, initial: Element, transform: @Sendable @escaping (inout Element, Base.Element) async throws -> Void) {
self.base = base
self.initial = initial
self.transform = transform
}
}
extension AsyncThrowingExclusiveReductionsSequence: AsyncSequence {
/// The iterator for an `AsyncThrowingExclusiveReductionsSequence` instance.
@frozen
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var iterator: Base.AsyncIterator
@usableFromInline
var current: Element?
@usableFromInline
let transform: @Sendable (inout Element, Base.Element) async throws -> Void
@inlinable
init(_ iterator: Base.AsyncIterator, initial: Element, transform: @Sendable @escaping (inout Element, Base.Element) async throws -> Void) {
self.iterator = iterator
self.current = initial
self.transform = transform
}
@inlinable
public mutating func next() async throws -> Element? {
guard let result = current else { return nil }
let value = try await iterator.next()
if let value = value {
var result = result
do {
try await transform(&result, value)
current = result
return result
} catch {
current = nil
throw error
}
} else {
current = nil
return nil
}
}
}
@inlinable
public func makeAsyncIterator() -> Iterator {
Iterator(base.makeAsyncIterator(), initial: initial, transform: transform)
}
}
extension AsyncThrowingExclusiveReductionsSequence: Sendable where Base: Sendable, Element: Sendable { }
|
apache-2.0
|
a3b9498be31c6051a662f4afbf5f05c6
| 38.38843 | 193 | 0.684222 | 5.070213 | false | false | false | false |
hironytic/Moltonf-iOS
|
Moltonf/Model/ImageCache/ImageLoader.swift
|
1
|
5088
|
//
// ImageLoader.swift
// Moltonf
//
// Copyright (c) 2016 Hironori Ichimiya <[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
import RxSwift
fileprivate typealias R = Resource
public enum ImageLoaderError: Error {
case invalidURL
case invalidData
}
public class ImageLoader {
public static let shared = ImageLoader()
private init() { }
private let _disposeBag = DisposeBag()
private let _syncQueue = DispatchQueue(label: "ImageLoader.sync")
private var _observables: [URL: Observable<UIImage>] = [:]
public func load(fromURL url: URL, altImage: UIImage? = nil) -> Observable<UIImage> {
// print("request for url: \(url)")
var observable: Observable<UIImage>!
_syncQueue.sync {
if let existing = _observables[url] {
observable = existing
} else {
// print("not existing: \(url.absoluteString)")
let obs = Observable<UIImage>
.create { observer in
// search from cache first
if let data = ImageCacheDB.shared.imageData(forURL: url) {
if let image = UIImage(data: data) {
observer.onNext(image)
} else {
observer.onError(ImageLoaderError.invalidData)
}
return Disposables.create()
}
// load from network
return ImageLoader.loadNetworkImageData(fromURL: url, altImage: altImage)
.subscribe(observer)
}
.replay(1)
obs.connect().addDisposableTo(_disposeBag)
_observables[url] = obs
observable = obs
}
}
return observable
}
private static func loadNetworkImageData(fromURL url: URL, altImage: UIImage?) -> Observable<UIImage> {
var result: Observable<UIImage> = URLSession.shared
.rx.data(request: URLRequest(url: url))
// .do(onNext: { _ in print("loaded: \(url.absoluteString)") })
// .delay(5, scheduler: MainScheduler.instance)
.map { data in
try ImageCacheDB.shared.putImageData(forURL: url, data: data)
if let image = UIImage(data: data) {
return image;
} else {
throw ImageLoaderError.invalidData
}
}
if let altImage = altImage {
result = result
.startWith(altImage)
.catchErrorJustReturn(altImage)
}
return result
}
}
public extension Avatar {
public var faceIconImageLine: Observable<UIImage> {
get {
guard let story = story else { return Observable.error(ImageLoaderError.invalidURL) }
guard let faceIconURI = faceIconURI else { return Observable.error(ImageLoaderError.invalidURL) }
guard let baseURL = URL(string: story.baseURI) else { return Observable.error(ImageLoaderError.invalidURL) }
guard let fullURL = URL(string: faceIconURI, relativeTo: baseURL) else { return Observable.error(ImageLoaderError.invalidURL) }
return Observable.deferred { ImageLoader.shared.load(fromURL: fullURL, altImage: R.Image.face_unknown) }
}
}
}
public extension Story {
public var graveIconImageLine: Observable<UIImage> {
get {
guard let baseURL = URL(string: baseURI) else { return Observable.error(ImageLoaderError.invalidURL) }
guard let fullURL = URL(string: graveIconURI, relativeTo: baseURL) else { return Observable.error(ImageLoaderError.invalidURL) }
return Observable.deferred { ImageLoader.shared.load(fromURL: fullURL, altImage: R.Image.face_unknown) }
}
}
}
|
mit
|
9f39610c682e3725c40f2bca198806c9
| 40.704918 | 140 | 0.605542 | 4.944606 | false | false | false | false |
OHeroJ/twicebook
|
Sources/App/Controllers/CommentController.swift
|
1
|
2723
|
//
// CommentController.swift
// App
//
// Created by laijihua on 29/09/2017.
//
import Foundation
import Vapor
final class CommentController: ControllerRoutable {
init(builder: RouteBuilder) {
builder.get("book",Int.parameter, handler: bookComments)
builder.get("user", Int.parameter, handler: userComments)
builder.post("book", Int.parameter, handler: addComment)
builder.post("report", Int.parameter, handler: reportComment)
}
func addComment(request: Request) throws -> ResponseRepresentable {
let bookId = try request.parameters.next(Int.self)
guard let userId = request.data[Comment.Key.userId]?.int else {
return try ApiRes.error(code: 1, msg: "miss user_id")
}
guard let user = try User.find(userId) else {
return try ApiRes.error(code: 3,msg: "miss user")
}
guard let content = request.data[Comment.Key.content]?.string else {
return try ApiRes.error(code: 2, msg: "miss content")
}
guard let book = try Book.find(bookId) else {
return try ApiRes.error(code: 4, msg: "miss book ")
}
let createTime = Date().toString
let comment = Comment(bookId: Identifier(bookId), userId: Identifier(userId), content: content, createTime: createTime, userName: user.name, userAvator: user.avator)
try comment.save()
book.commentCount += 1
try book.save()
return try ApiRes.success(data:["success": true])
}
func reportComment(request: Request) throws -> ResponseRepresentable {
let commentId = try request.parameters.next(Int.self)
guard let comment = try Comment.find(commentId) else {
return try ApiRes.error(code: 1, msg: "not find comment")
}
comment.reportCount += 1
if comment.reportCount > 10 {
if let book = try Book.find(comment.bookId) {
book.commentCount -= 1
try book.save()
}
try comment.delete()
}
try comment.save()
return try ApiRes.success(data:["success": true])
}
func bookComments(request: Request) throws -> ResponseRepresentable {
let bookId = try request.parameters.next(Int.self)
let query = try Comment.makeQuery().filter(Comment.Key.bookId, bookId)
return try Comment.page(request: request, query: query)
}
func userComments(request: Request) throws -> ResponseRepresentable {
let userId = try request.parameters.next(Int.self)
let query = try Comment.makeQuery().filter(Comment.Key.userId, userId)
return try Comment.page(request: request, query: query)
}
}
|
mit
|
ef6d69bedccf577b94b48dd9227ed866
| 36.819444 | 173 | 0.632391 | 4.268025 | false | false | false | false |
andrea-prearo/SwiftExamples
|
RegionMonitor/RegionMonitor/RegionNotification.swift
|
1
|
2636
|
//
// RegionNotification.swift
// RegionMonitor
//
// Created by Andrea Prearo on 5/24/15.
// Copyright (c) 2015 Andrea Prearo. All rights reserved.
//
import Foundation
import UIKit
let RegionNotificationEventKey = "RegionNotificationEvent"
let RegionNotificationTimestampKey = "RegionNotificationTimestamp"
let RegionNotificationMessageKey = "RegionNotificationMessage"
let RegionNotificationAppStatusKey = "RegionNotificationAppStatus"
class RegionNotification: NSObject, NSCoding {
let timestamp: Date
let event: RegionAnnotationEvent
let message: String
let appStatus: UIApplication.State
init(timestamp: Date, event: RegionAnnotationEvent, message: String, appStatus: UIApplication.State) {
self.timestamp = timestamp
self.event = event
self.message = message
self.appStatus = appStatus
}
override var description: String {
return "Timestamp=\(displayTimestamp()), Event=\(displayEvent()), Message=\(message), App Status=\(displayAppStatus())"
}
// MARK: NSCoding
required init?(coder decoder: NSCoder) {
timestamp = decoder.decodeObject(forKey: RegionNotificationTimestampKey) as! Date
event = RegionAnnotationEvent(rawValue: decoder.decodeInteger(forKey: RegionNotificationEventKey))!
message = decoder.decodeObject(forKey: RegionNotificationMessageKey) as! String
appStatus = UIApplication.State(rawValue: decoder.decodeInteger(forKey: RegionNotificationAppStatusKey))!
}
func encode(with coder: NSCoder) {
coder.encode(timestamp, forKey: RegionNotificationTimestampKey)
coder.encode(event.rawValue, forKey: RegionNotificationEventKey)
coder.encode(message, forKey: RegionNotificationMessageKey)
coder.encode(appStatus.rawValue, forKey: RegionNotificationAppStatusKey)
}
// MARK: Utility Methods
func displayTimestamp() -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.short
dateFormatter.timeStyle = DateFormatter.Style.short
return dateFormatter.string(from: timestamp)
}
func displayEvent() -> String {
switch event {
case .entry:
return "Entry"
case .exit:
return "Exit"
}
}
func displayAppStatus() -> String {
switch appStatus {
case .active:
return "Active"
case .inactive:
return "Inactive"
case .background:
return "Background"
@unknown default:
fatalError("Unknown app state")
}
}
}
|
mit
|
7cb800b3c6db7dceab58e7c894e7a26e
| 31.146341 | 127 | 0.685888 | 4.93633 | false | false | false | false |
ifLab/WeCenterMobile-iOS
|
WeCenterMobile/View/Search/TopicSearchResultCell.swift
|
3
|
1563
|
//
// TopicSearchResultCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/6/14.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class TopicSearchResultCell: UITableViewCell {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var badgeLabel: UILabel!
@IBOutlet weak var topicImageView: UIImageView!
@IBOutlet weak var topicTitleLabel: UILabel!
@IBOutlet weak var topicDescriptionLabel: UILabel!
@IBOutlet weak var topicButton: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
let theme = SettingsManager.defaultManager.currentTheme
for v in [containerView, badgeLabel] {
v.msr_borderColor = theme.borderColorA
}
containerView.backgroundColor = theme.backgroundColorB
badgeLabel.backgroundColor = theme.backgroundColorA
topicTitleLabel.textColor = theme.titleTextColor
topicDescriptionLabel.textColor = theme.subtitleTextColor
badgeLabel.textColor = theme.footnoteTextColor
topicButton.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted)
}
func update(dataObject dataObject: DataObject) {
let topic = dataObject as! Topic
topicTitleLabel.text = topic.title
topicDescriptionLabel.text = topic.introduction ?? ""
topicImageView.wc_updateWithTopic(topic)
topicButton.msr_userInfo = topic
setNeedsLayout()
layoutIfNeeded()
}
}
|
gpl-2.0
|
a19cb5027fd0dda62b1f41f99208c0b0
| 33.688889 | 99 | 0.70788 | 5.327645 | false | false | false | false |
andreaperizzato/CoreStore
|
CoreStoreDemo/CoreStoreDemo/Fetching and Querying Demo/FetchingAndQueryingDemoViewController.swift
|
3
|
9360
|
//
// FetchingAndQueryingDemoViewController.swift
// CoreStoreDemo
//
// Created by John Rommel Estropia on 2015/06/12.
// Copyright (c) 2015 John Rommel Estropia. All rights reserved.
//
import UIKit
import CoreStore
private struct Static {
static let timeZonesStack: DataStack = {
let dataStack = DataStack()
try! dataStack.addSQLiteStoreAndWait(
fileName: "TimeZoneDemo.sqlite",
configuration: "FetchingAndQueryingDemo",
resetStoreOnModelMismatch: true
)
dataStack.beginSynchronous { (transaction) -> Void in
transaction.deleteAll(From(TimeZone))
for name in NSTimeZone.knownTimeZoneNames() {
let rawTimeZone = NSTimeZone(name: name)!
let cachedTimeZone = transaction.create(Into(TimeZone))
cachedTimeZone.name = rawTimeZone.name
cachedTimeZone.abbreviation = rawTimeZone.abbreviation ?? ""
cachedTimeZone.secondsFromGMT = Int32(rawTimeZone.secondsFromGMT)
cachedTimeZone.hasDaylightSavingTime = rawTimeZone.daylightSavingTime
cachedTimeZone.daylightSavingTimeOffset = rawTimeZone.daylightSavingTimeOffset
}
transaction.commit()
}
return dataStack
}()
}
// MARK: - FetchingAndQueryingDemoViewController
class FetchingAndQueryingDemoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// MARK: UIViewController
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if self.didAppearOnce {
return
}
self.didAppearOnce = true
let alert = UIAlertController(
title: "Fetch and Query Demo",
message: "This demo shows how to execute fetches and queries.\n\nEach menu item executes and displays a preconfigured fetch/query.",
preferredStyle: .Alert
)
alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
super.prepareForSegue(segue, sender: sender)
if let indexPath = sender as? NSIndexPath {
switch segue.destinationViewController {
case let controller as FetchingResultsViewController:
let item = self.fetchingItems[indexPath.row]
controller.setTimeZones(item.fetch(), title: item.title)
case let controller as QueryingResultsViewController:
let item = self.queryingItems[indexPath.row]
controller.setValue(item.query(), title: item.title)
default:
break
}
}
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch self.segmentedControl?.selectedSegmentIndex {
case .Some(Section.Fetching.rawValue):
return self.fetchingItems.count
case .Some(Section.Querying.rawValue):
return self.queryingItems.count
default:
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UITableViewCell")!
switch self.segmentedControl?.selectedSegmentIndex {
case .Some(Section.Fetching.rawValue):
cell.textLabel?.text = self.fetchingItems[indexPath.row].title
case .Some(Section.Querying.rawValue):
cell.textLabel?.text = self.queryingItems[indexPath.row].title
default:
cell.textLabel?.text = nil
}
return cell
}
// MARK: UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch self.segmentedControl?.selectedSegmentIndex {
case .Some(Section.Fetching.rawValue):
self.performSegueWithIdentifier("FetchingResultsViewController", sender: indexPath)
case .Some(Section.Querying.rawValue):
self.performSegueWithIdentifier("QueryingResultsViewController", sender: indexPath)
default:
break
}
}
// MARK: Private
private enum Section: Int {
case Fetching
case Querying
}
private let fetchingItems = [
(
title: "All Time Zones",
fetch: { () -> [TimeZone] in
return Static.timeZonesStack.fetchAll(
From(TimeZone),
OrderBy(.Ascending("name"))
)!
}
),
(
title: "Time Zones in Asia",
fetch: { () -> [TimeZone] in
return Static.timeZonesStack.fetchAll(
From(TimeZone),
Where("%K BEGINSWITH[c] %@", "name", "Asia"),
OrderBy(.Ascending("secondsFromGMT"))
)!
}
),
(
title: "Time Zones in America and Europe",
fetch: { () -> [TimeZone] in
return Static.timeZonesStack.fetchAll(
From(TimeZone),
Where("%K BEGINSWITH[c] %@", "name", "America")
|| Where("%K BEGINSWITH[c] %@", "name", "Europe"),
OrderBy(.Ascending("secondsFromGMT"))
)!
}
),
(
title: "All Time Zones Except America",
fetch: { () -> [TimeZone] in
return Static.timeZonesStack.fetchAll(
From(TimeZone),
!Where("%K BEGINSWITH[c] %@", "name", "America"),
OrderBy(.Ascending("secondsFromGMT"))
)!
}
),
(
title: "Time Zones with Summer Time",
fetch: { () -> [TimeZone] in
return Static.timeZonesStack.fetchAll(
From(TimeZone),
Where("hasDaylightSavingTime", isEqualTo: true),
OrderBy(.Ascending("name"))
)!
}
)
]
private let queryingItems = [
(
title: "Number of Time Zones",
query: { () -> AnyObject in
return Static.timeZonesStack.queryValue(
From(TimeZone),
Select<NSNumber>(.Count("name"))
)!
}
),
(
title: "Abbreviation For Tokyo's Time Zone",
query: { () -> AnyObject in
return Static.timeZonesStack.queryValue(
From(TimeZone),
Select<String>("abbreviation"),
Where("%K ENDSWITH[c] %@", "name", "Tokyo")
)!
}
),
(
title: "All Abbreviations",
query: { () -> AnyObject in
return Static.timeZonesStack.queryAttributes(
From(TimeZone),
Select<NSDictionary>("name", "abbreviation"),
OrderBy(.Ascending("name"))
)!
}
),
(
title: "Number of Countries per Time Zone",
query: { () -> AnyObject in
return Static.timeZonesStack.queryAttributes(
From(TimeZone),
Select<NSDictionary>(.Count("abbreviation"), "abbreviation"),
GroupBy("abbreviation"),
OrderBy(.Ascending("secondsFromGMT"), .Ascending("name"))
)!
}
),
(
title: "Number of Countries with Summer Time",
query: { () -> AnyObject in
return Static.timeZonesStack.queryAttributes(
From(TimeZone),
Select<NSDictionary>(
.Count("hasDaylightSavingTime", As: "numberOfCountries"),
"hasDaylightSavingTime"
),
GroupBy("hasDaylightSavingTime"),
OrderBy(.Descending("hasDaylightSavingTime"))
)!
}
)
]
var didAppearOnce = false
@IBOutlet dynamic weak var segmentedControl: UISegmentedControl?
@IBOutlet dynamic weak var tableView: UITableView?
@IBAction dynamic func segmentedControlValueChanged(sender: AnyObject?) {
self.tableView?.reloadData()
}
}
|
mit
|
799dc9d41cef8822a29c0849756fccde
| 31.275862 | 144 | 0.51453 | 6.019293 | false | false | false | false |
igroomgrim/ta-da
|
TADA/TADA/TaskFormViewController.swift
|
1
|
2710
|
//
// TaskFormViewController.swift
// TADA
//
// Created by Anak Mirasing on 10/18/2558 BE.
// Copyright © 2558 iGROOMGRiM. All rights reserved.
//
import UIKit
import RealmSwift
class TaskFormViewController: UIViewController {
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var statusSwitch: UISwitch!
var task: TDTask?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let task = task {
titleTextField.text = task.title
descriptionTextView.text = task.taskDescription
if task.done {
statusSwitch.setOn(true, animated: false)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Action
@IBAction func cancelButtonTapped(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion:nil)
}
@IBAction func saveButtonTapped(sender: AnyObject) {
if let task = task {
updateTask(task)
}else{
createNewTask()
}
}
// MARK: - Create Task
func createNewTask() {
let task = TDTask()
if (titleTextField.text!.isEmpty || descriptionTextView.text.isEmpty) {
print("notification : isEmpty")
}else{
task.title = titleTextField.text!
task.taskDescription = descriptionTextView.text
task.created = NSDate.timeIntervalSinceReferenceDate()
if statusSwitch.on {
task.done = true
}else{
task.done = false
}
print("\(task.title)")
print("\(task.taskDescription)")
print("\(task.done)")
print("\(task.created)")
let realm = try! Realm()
realm.beginWrite()
realm.add(task)
try! realm.commitWrite()
self.dismissViewControllerAnimated(true, completion:nil)
}
}
// MARK: - Update Task
func updateTask(task: TDTask) {
let realm = try! Realm()
realm.beginWrite()
task.title = titleTextField.text!
task.taskDescription = descriptionTextView.text
if statusSwitch.on {
task.done = true
}else{
task.done = false
}
try! realm.commitWrite()
self.dismissViewControllerAnimated(true, completion:nil)
}
}
|
mit
|
df42cfcc678f3f5dacd817194def3448
| 25.821782 | 79 | 0.562938 | 5.22973 | false | false | false | false |
Piwigo/Piwigo-Mobile
|
piwigo/Settings/Privacy/LockOptionsViewController.swift
|
1
|
11355
|
//
// LockOptionsViewController.swift
// piwigo
//
// Created by Eddy Lelièvre-Berna on 28/03/2022.
// Copyright © 2022 Piwigo.org. All rights reserved.
//
import LocalAuthentication
import UIKit
import piwigoKit
protocol LockOptionsDelegate: NSObjectProtocol {
func didSetAppLock(toState isLocked: Bool)
}
class LockOptionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
weak var delegate: LockOptionsDelegate?
var context = LAContext()
var contextErrorMsg = ""
@IBOutlet var lockOptionsTableView: UITableView!
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Set title
title = NSLocalizedString("settingsHeader_privacy", comment: "Privacy")
// Evaluate biometrics policy
var error: NSError?
let _ = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error)
contextErrorMsg = error?.localizedDescription ?? ""
}
@objc func applyColorPalette() {
// Background color of the view
view.backgroundColor = .piwigoColorBackground()
// Navigation bar
let attributes = [
NSAttributedString.Key.foregroundColor: UIColor.piwigoColorWhiteCream(),
NSAttributedString.Key.font: UIFont.piwigoFontNormal()
]
navigationController?.navigationBar.titleTextAttributes = attributes as [NSAttributedString.Key : Any]
if #available(iOS 11.0, *) {
navigationController?.navigationBar.prefersLargeTitles = false
}
navigationController?.navigationBar.barStyle = AppVars.shared.isDarkPaletteActive ? .black : .default
navigationController?.navigationBar.tintColor = .piwigoColorOrange()
navigationController?.navigationBar.barTintColor = .piwigoColorBackground()
navigationController?.navigationBar.backgroundColor = .piwigoColorBackground()
if #available(iOS 15.0, *) {
/// In iOS 15, UIKit has extended the usage of the scrollEdgeAppearance,
/// which by default produces a transparent background, to all navigation bars.
let barAppearance = UINavigationBarAppearance()
barAppearance.configureWithOpaqueBackground()
barAppearance.backgroundColor = .piwigoColorBackground()
navigationController?.navigationBar.standardAppearance = barAppearance
navigationController?.navigationBar.scrollEdgeAppearance = navigationController?.navigationBar.standardAppearance
}
// Table view
lockOptionsTableView.separatorColor = .piwigoColorSeparator()
lockOptionsTableView.indicatorStyle = AppVars.shared.isDarkPaletteActive ? .white : .black
lockOptionsTableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Set colors, fonts, etc.
applyColorPalette()
// Register palette changes
NotificationCenter.default.addObserver(self, selector: #selector(applyColorPalette),
name: .pwgPaletteChanged, object: nil)
}
deinit {
// Unregister palette changes
NotificationCenter.default.removeObserver(self, name: .pwgPaletteChanged, object: nil)
}
// MARK: - UITableView - Header
private func getContentOfHeader(inSection section: Int) -> String {
var title = ""
switch section {
default:
title = " "
}
return title
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let title = getContentOfHeader(inSection: section)
return TableViewUtilities.shared.heightOfHeader(withTitle: title,
width: tableView.frame.size.width)
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let title = getContentOfHeader(inSection: section)
return TableViewUtilities.shared.viewOfHeader(withTitle: title)
}
// MARK: - UITableView - Rows
func numberOfSections(in tableView: UITableView) -> Int {
var nberOfSection = 2
if #available(iOS 11.0, *) {
nberOfSection += context.biometryType == .none ? 0 : 1
}
return nberOfSection
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0...2:
return 1
default:
return 0
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 44.0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var tableViewCell = UITableViewCell()
switch indexPath.section {
case 0: // Auto-Upload On/Off
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
let title = NSLocalizedString("settings_appLock", comment: "App Lock")
cell.configure(with: title)
cell.cellSwitch.setOn(AppVars.shared.isAppLockActive, animated: true)
cell.cellSwitchBlock = { switchState in
// Check if a password exists
if switchState, AppVars.shared.appLockKey.isEmpty {
let appLockSB = UIStoryboard(name: "AppLockViewController", bundle: nil)
guard let appLockVC = appLockSB.instantiateViewController(withIdentifier: "AppLockViewController") as? AppLockViewController else { return }
appLockVC.config(forAction: .enterPasscode)
self.navigationController?.pushViewController(appLockVC, animated: true)
} else {
// Enable/disable app-lock option
AppVars.shared.isAppLockActive = switchState
self.delegate?.didSetAppLock(toState: switchState)
}
}
tableViewCell = cell
case 1: // Change Password
guard let cell = tableView.dequeueReusableCell(withIdentifier: "ButtonTableViewCell", for: indexPath) as? ButtonTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a ButtonTableViewCell!")
return ButtonTableViewCell()
}
if AppVars.shared.appLockKey.isEmpty {
cell.configure(with: NSLocalizedString("settings_appLockEnter", comment: "Enter Passcode"))
} else {
cell.configure(with: NSLocalizedString("settings_appLockModify", comment: "Modify Passcode"))
}
cell.accessibilityIdentifier = "passcode"
tableViewCell = cell
case 2: // TouchID / FaceID On/Off
guard let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchTableViewCell", for: indexPath) as? SwitchTableViewCell else {
print("Error: tableView.dequeueReusableCell does not return a SwitchTableViewCell!")
return SwitchTableViewCell()
}
var title = ""
if #available(iOS 11.0, *) {
switch context.biometryType {
case .touchID:
title = NSLocalizedString("settings_biometricsTouchID", comment: "Touch ID")
case .faceID:
title = NSLocalizedString("settings_biometricsFaceID", comment: "Face ID")
default:
title = "—?—"
}
}
cell.configure(with: title)
if contextErrorMsg.isEmpty == false {
cell.switchName.textColor = .piwigoColorRightLabel()
cell.cellSwitch.onTintColor = .piwigoColorRightLabel()
cell.isUserInteractionEnabled = false
}
cell.cellSwitch.setOn(AppVars.shared.isBiometricsEnabled, animated: true)
cell.cellSwitchBlock = { switchState in
AppVars.shared.isBiometricsEnabled = switchState
}
tableViewCell = cell
default:
break
}
tableViewCell.backgroundColor = .piwigoColorCellBackground()
tableViewCell.tintColor = .piwigoColorOrange()
return tableViewCell
}
// MARK: - UITableView - Footer
private func getContentOfFooter(inSection section: Int) -> String {
var footer = ""
switch section {
case 0: // App-Lock On/Off
footer = NSLocalizedString("settings_appLockInfo", comment: "With App Lock, ...")
case 1: // Change Passcode
footer = NSLocalizedString("settings_passcodeInfo", comment: "The passcode is separate…")
case 2: // Touch ID / Face ID On/Off
if contextErrorMsg.isEmpty {
if #available(iOS 11.0, *) {
switch context.biometryType {
case .none:
footer = ""
case .touchID:
footer = NSLocalizedString("settings_biometricsTouchIDinfo", comment: "Use Touch ID…")
case .faceID:
footer = NSLocalizedString("settings_biometricsFaceIDinfo", comment:"Use Face ID…")
@unknown default:
footer = ""
}
}
} else {
footer = contextErrorMsg
}
default:
footer = " "
}
return footer
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let text = getContentOfFooter(inSection: section)
return TableViewUtilities.shared.heightOfFooter(withText: text,
width: tableView.frame.size.width)
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let text = getContentOfFooter(inSection: section)
return TableViewUtilities.shared.viewOfFooter(withText: text)
}
// MARK: - UITableViewDelegate Methods
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
// Change password?
if indexPath.section == 1 {
// Display numpad for setting up a passcode
let appLockSB = UIStoryboard(name: "AppLockViewController", bundle: nil)
guard let appLockVC = appLockSB.instantiateViewController(withIdentifier: "AppLockViewController") as? AppLockViewController else { return }
if AppVars.shared.appLockKey.isEmpty {
appLockVC.config(forAction: .enterPasscode)
} else {
appLockVC.config(forAction: .modifyPasscode)
}
navigationController?.pushViewController(appLockVC, animated: true)
}
}
}
|
mit
|
f4138987d5b8191e07eb32aded6d08c9
| 40.39781 | 160 | 0.617121 | 5.743291 | false | false | false | false |
MyAppConverter/HTMLtoPDF-Demo-Swift
|
HTMLtoPDF-Demo/HTMLtoPDF-Demo/NDViewController.swift
|
1
|
2823
|
import UIKit
//
// NDViewController.m
// HTMLtoPDF-Demo
//
// Created by Clément Wehrung on 12/11/12.
// Copyright (c) 2012 Nurves. All rights reserved.
//
// *******************************************************************************************
// * *
// **This code has been automaticaly ported to Swift language 1.2 using MyAppConverter.com **
// * 11/06/2015 *
// *******************************************************************************************
class NDViewController :UIViewController, NDHTMLtoPDFDelegate
{
@IBOutlet weak var resultLabel:UILabel?
var PDFCreator:NDHTMLtoPDF?
override func viewDidLoad(){
super.viewDidLoad()
}
@IBAction func generatePDFUsingDelegate( sender:AnyObject ){
self.resultLabel?.text = "loading..."
var tt:NSString = "~/Documents/delegateDemo.pdf".stringByExpandingTildeInPath
self.PDFCreator = NDHTMLtoPDF.createPDFWithURL(NSURL(string:"http://edition.cnn.com/2012/11/12/business/china-consumer-economy/index.html?hpt=hp_c1")!, pathForPDF:tt, delegate: self, pageSize: CGSizeMake(595.2,841.8), margins:UIEdgeInsetsMake(10, 5, 10, 5)) as? NDHTMLtoPDF;
}
@IBAction func generatePDFUsingBlocks( sender:AnyObject ){
self.resultLabel?.text = "loading..."
self.PDFCreator = NDHTMLtoPDF.createPDFWithURL(NSURL(string:"http://edition.cnn.com/2013/09/19/opinion/rushkoff-apple-ios-baby-steps/index.html")! , pathForPDF:"~/Documents/blocksDemo.pdf".stringByExpandingTildeInPath, pageSize:CGSizeMake(595.2,841.8), margins:UIEdgeInsetsMake(10, 5, 10, 5), successBlock: {( htmlToPDF:NDHTMLtoPDF) in
var result:NSString = NSString(format:"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath!);
NSLog("%@",result);
self.resultLabel!.text = result as String;
} , errorBlock:{(htmlToPDF:NDHTMLtoPDF) in
var result:NSString = NSString(format:"HTMLtoPDF did fail (%@)", htmlToPDF);
NSLog("%@",result);
self.resultLabel!.text = result as String;
}) as? NDHTMLtoPDF;
}
func HTMLtoPDFDidSucceed( htmlToPDF:NDHTMLtoPDF ){
var result:NSString? = NSString(format:"HTMLtoPDF did succeed (%@ / %@)", htmlToPDF, htmlToPDF.PDFpath!);
NSLog("%@" , result! )
self.resultLabel?.text = result as? String
}
func HTMLtoPDFDidFail( htmlToPDF:NDHTMLtoPDF ){
var result:NSString = NSString(format:"HTMLtoPDF did fail (%@)" , htmlToPDF )
NSLog("%@" , result )
self.resultLabel?.text = result as String
}
}
|
mit
|
de331987d2dbbfb7ba7b8e74853eb8ce
| 45.278689 | 343 | 0.568391 | 4.742857 | false | false | false | false |
SlayterDev/DeafShark
|
DeafShark/DSAST.swift
|
1
|
9628
|
//
// DSAST.swift
// DeafShark
//
// Created by Bradley Slayter on 6/16/15.
// Copyright © 2015 Flipped Bit. All rights reserved.
//
import Cocoa
@objc open class DSAST: NSObject {
var children: [DSAST] = []
override init() {
}
init(lineContext: LineContext?) {
super.init()
self.lineContext = lineContext
}
fileprivate var explicitLineContext: LineContext?
var lineContext: LineContext? {
get {
return explicitLineContext ?? children.first?.lineContext
}
set (explicitLineContext) {
self.explicitLineContext = explicitLineContext
}
}
override open var description: String {
return ("DeafSharkAST" + self.childDescriptions)
}
open var childDescriptions: String {
let indentedDescriptions = self.children.map({ (child: DSAST) -> String in
child.description.components(separatedBy: "\n").reduce("") {
return $0 + "\n\t" + $1
}
})
return indentedDescriptions.reduce("", +)
}
}
// Program Body
open class DSBody: DSAST {
func codeGen() {
Codegen.topLevel_Codegen(self)
}
}
open class DSExpr: DSAST {
let isAssignable: Bool
init(assignable: Bool = false, lineContext: LineContext?) {
self.isAssignable = assignable
super.init(lineContext: lineContext)
}
}
@objc open class DSType: DSAST {
var identifier: String
var itemCount: Int?
override init() {
self.identifier = ""
super.init()
}
init(identifier: String, itemCount: Int?, lineContext: LineContext?) {
self.identifier = identifier
self.itemCount = itemCount
super.init(lineContext: lineContext)
}
override open var description: String {
return "DeafSharkType - type:\(identifier)"
}
func getItemCount() -> Int {
return itemCount!
}
}
open class DSAssignment: DSAST {
var storage: DSExpr
var expression: DSExpr
init(storage: DSExpr, expression: DSExpr) {
self.storage = storage
self.expression = expression
super.init(lineContext: nil)
self.children = [self.storage, self.expression]
}
override open var description: String {
return "DeafSharkAssignment " + self.childDescriptions
}
}
open class DSDeclaration: DSAST {
var identifier: String
var isConstant: Bool
var type: DSType?
var assignment: DSExpr? {
didSet {
self.children.append(assignment!)
}
}
init(id: String, type: DSType?, lineContext: LineContext?) {
identifier = id
isConstant = true
self.type = type
super.init(lineContext: lineContext)
if let type = type {
self.children.append(type)
}
}
convenience init(id: String, lineContext: LineContext?) {
self.init(id: id, type: nil, lineContext: lineContext)
}
override open var description: String {
return "DeafSharkDeclaration - identifier:\(identifier), isConstant:\(isConstant)" + self.childDescriptions
}
}
open class DSBinaryExpression: DSExpr {
let op: String
let lhs: DSExpr
let rhs: DSExpr
init(op: String, lhs: DSExpr, rhs: DSExpr) {
self.op = op
self.lhs = lhs
self.rhs = rhs
super.init(assignable: false, lineContext: nil)
switch lhs {
case let l as DSBinaryExpression:
self.children.append(contentsOf: l.children)
default:
self.children.append(lhs)
}
switch rhs {
case let r as DSBinaryExpression:
self.children.append(contentsOf: r.children)
default:
self.children.append(rhs)
}
}
override open var description: String {
return "DeafSharkBinaryOperation - op:\(op)" + "\n RH\(op): " + self.lhs.description + "\n LH\(op): " + self.rhs.description
}
}
open class DSFunctionType: DSType {
var parameterType: DSType
var returnType: DSType
init(parameterType: DSType, returnType: DSType, lineContext: LineContext? = nil) {
self.parameterType = parameterType
self.returnType = returnType
super.init(identifier: "func", itemCount: nil, lineContext: lineContext)
}
override open var description: String {
var description = "("
description += parameterType.description
description += " -> "
description += returnType.description
description += ")"
return description
}
}
open class DSFunctionParameter: DSDeclaration {}
open class DSFunctionBody: DSBody {
init(_ body: DSBody, lineContext: LineContext?) {
super.init(lineContext: lineContext)
self.children = body.children
self.lineContext = body.lineContext
}
override open var description: String {
return "DeafSharkFunctionBody" + self.childDescriptions
}
}
open class DSFunctionDeclaration: DSAST {
var prototype: DSFunctionPrototype
var body: DSFunctionBody?
init(id: String, parameters: [DSDeclaration], returnType: DSType, body: DSFunctionBody?, lineContext: LineContext?) {
self.prototype = DSFunctionPrototype(id: id, parameters: parameters, returnType: returnType, lineContext: lineContext)
self.body = body
super.init(lineContext: lineContext)
self.children.append(self.prototype)
if let body = self.body {
self.children.append(body)
}
}
override open var description: String {
return "DeafSharkFunctionDeclaration - \(self.prototype.identifier) -> \(self.prototype.type!.identifier)" + self.childDescriptions
}
}
open class DSFunctionPrototype: DSDeclaration {
var parameters: [DSDeclaration]
init(id: String, parameters: [DSDeclaration], returnType: DSType, lineContext: LineContext?) {
self.parameters = parameters
super.init(id: id, type: returnType, lineContext: lineContext)
}
override open var description: String {
var description = "DeafSharkFunctionPrototype - \(self.identifier)( "
for param in self.parameters {
description += param.identifier + " "
}
description += ") -> \(self.type!.identifier)" + self.childDescriptions
return description
}
}
open class DSCall: DSExpr {
let identifier: DSIdentifierString
init(identifier: DSIdentifierString, arguments: [DSExpr]) {
self.identifier = identifier
super.init(lineContext: nil)
let args = arguments as [DSAST]
self.children.append(contentsOf: args)
}
override open var description: String {
return "DeafSharkFunctionCall - identifier:\(identifier.name)" + self.childDescriptions
}
}
open class DSConditionalStatement: DSAST {
let cond: DSExpr
let body: DSBody
init(condition: DSExpr, body: DSBody, lineContext: LineContext?) {
self.cond = condition
self.body = body
super.init(lineContext: lineContext)
self.lineContext = lineContext
}
}
open class DSIfStatement: DSConditionalStatement {
var elseBody: DSBody?
var alternates: [DSIfStatement]?
override init(condition: DSExpr, body: DSBody, lineContext: LineContext?) {
self.elseBody = nil
self.alternates = [DSIfStatement]()
super.init(condition: condition, body: body, lineContext: lineContext)
}
override open var description: String {
var desc = "DeafSharkIfStatement - condition:\(self.cond.description)"
for alt in alternates! {
desc += " " + alt.description
}
return desc
}
}
open class DSWhileStatement: DSConditionalStatement {
override open var description: String {
return "DeafSharkWhileStatement - condition:\(self.cond.description)" + self.body.description
}
}
open class DSForStatement: DSConditionalStatement {
let initial: DSAST
let increment: DSExpr
init(initial: DSAST, condition: DSExpr, increment: DSExpr, body: DSBody, lineContext: LineContext?) {
self.initial = initial
self.increment = increment
super.init(condition: condition, body: body, lineContext: lineContext)
}
override open var description: String {
return "DeafSharkForStatement - condition:\(self.cond.description)" + self.body.description
}
}
open class DSReturnStatement: DSExpr {
let statement: DSExpr
init (statement: DSExpr, lineContext: LineContext?) {
self.statement = statement
super.init(assignable: false, lineContext: lineContext)
}
}
open class DSBreakStatement: DSExpr {
init (lineContext: LineContext?) {
super.init(assignable: false, lineContext: lineContext)
}
override open var description: String {
return "DeafSharkBreakStatement - break"
}
}
open class DSIdentifierString: DSExpr {
var name: String
var arrayAccess: DSExpr?
init(name: String, lineContext: LineContext) {
self.name = name
super.init(assignable: true, lineContext: lineContext)
}
override open var description: String {
return "DeafSharkIdentifier - name:\(name) " + ((self.arrayAccess == nil) ? "" : "[" + self.arrayAccess!.description + "]")
}
}
open class DSStringLiteral: DSExpr {
let val: String
init (val: String, lineContext: LineContext?) {
self.val = val
super.init(lineContext: lineContext)
}
override open var description: String {
return "DeafSharkStringLiteral - val:\"\(val)\""
}
}
open class DSSignedIntegerLiteral: DSExpr {
let val: Int
init(val: Int, lineContext: LineContext?) {
self.val = val
super.init(lineContext: lineContext)
}
override open var description: String {
return "DeafSharkSignedIntegerLiteral - val:\(val)"
}
}
open class DSFloatLiteral: DSExpr {
let val: Float
init(val: Float, lineContext: LineContext?) {
self.val = val
super.init(lineContext: lineContext)
}
override open var description: String {
return "DeafSharkFloatLiteral - val:\(val)"
}
}
open class DSBooleanLiteral: DSExpr {
let val: Bool
init(val: Bool, lineContext: LineContext?) {
self.val = val
super.init(lineContext: lineContext)
}
override open var description: String {
return "DeafSharkBooleanLiteral - val:\(val)"
}
}
open class DSArrayLiteral: DSExpr {
init(elements: [DSExpr], lineContext: LineContext?) {
super.init(lineContext: lineContext)
self.children = elements
}
override open var description: String {
return "DeafSharkArrayLiteral" + self.childDescriptions
}
}
|
mit
|
0b1ae93e09dfca5fe137d3c76959e14e
| 23.43401 | 133 | 0.722032 | 3.522503 | false | false | false | false |
fitpay/fitpay-ios-sdk
|
FitpaySDKTests/Rtm/RtmMessagingTests.swift
|
1
|
3132
|
import XCTest
import Nimble
@testable import FitpaySDK
class RtmMessagingTests: XCTestCase {
var rtmMessaging: RtmMessaging!
let wvConfigStorage = WvConfigStorage()
override func setUp() {
super.setUp()
rtmMessaging = RtmMessaging(wvConfigStorage: wvConfigStorage)
}
func testSuccessVersionNegotiating() {
let handler = MockRtmMessageHandler(wvConfigStorage: wvConfigStorage)
rtmMessaging.handlersMapping = [WvConfig.RtmProtocolVersion.ver3: handler]
waitUntil { done in
handler.completion = { (_) in
done()
}
self.rtmMessaging.received(message: ["type": "version", "callBackId": 0, "data": ["version": 3]]) { (success) in
expect(success).to(beTrue())
}
self.rtmMessaging.received(message: ["type": "ping", "callBackId": 1])
}
}
func testUnknownVersionReceived() {
let handler = MockRtmMessageHandler(wvConfigStorage: wvConfigStorage)
rtmMessaging.handlersMapping = [WvConfig.RtmProtocolVersion.ver3: handler]
waitUntil { done in
self.rtmMessaging.received(message: ["type": "version", "callBackId": 0, "data": ["version": 99]]) { (success) in
expect(success).to(beFalse())
}
self.rtmMessaging.received(message: ["type": "ping", "callBackId": 1]) { (success) in
expect(success).to(beFalse())
done()
}
}
}
func testLowerVersionReceived() {
let handler = MockRtmMessageHandler(wvConfigStorage: wvConfigStorage)
rtmMessaging.handlersMapping = [WvConfig.RtmProtocolVersion.ver2: handler,
WvConfig.RtmProtocolVersion.ver3: MockRtmMessageHandler(wvConfigStorage: wvConfigStorage)]
waitUntil { done in
handler.completion = { (_) in
done()
}
self.rtmMessaging.received(message: ["type": "version", "callBackId": 0, "data": ["version": 2]]) {
expect($0).to(beTrue())
}
self.rtmMessaging.received(message: ["type": "ping", "callBackId": 1]) {
expect($0).to(beTrue())
}
}
}
func testUnknownMessageTypeNegotiating() {
let handler = MockRtmMessageHandler(wvConfigStorage: wvConfigStorage)
rtmMessaging.handlersMapping = [WvConfig.RtmProtocolVersion.ver2: handler]
waitUntil { done in
handler.completion = { (_) in
done()
}
self.rtmMessaging.received(message: ["type": "UnknownType", "callBackId": 21, "data": ["string parameter": "Some Details", "number parameter": 99]])
self.rtmMessaging.received(message: ["type": "version", "callBackId": 0, "data": ["version": 2]]) { (success) in
expect(success).to(beTrue())
}
}
}
}
|
mit
|
e6fddf3ff67ea6c55e9b4d4061e29cd6
| 34.191011 | 160 | 0.552363 | 4.552326 | false | true | false | false |
nataliq/TripCheckins
|
TripCheckins/Common/Observable.swift
|
1
|
1259
|
//
// Observable.swift
// TripCheckins
//
// Created by Nataliya on 9/12/17.
// Copyright © 2017 Nataliya Patsovska. All rights reserved.
//
import Foundation
typealias ObserverObject = AnyObject & Observer
protocol Observable {
mutating func addObserver(_ observer: ObserverObject)
mutating func removeObserver(_ observer: ObserverObject)
func notifyObservers()
}
protocol Observer: class {
func didUpdateObservableObject(_ observable: Observable)
}
protocol ObserversContainer {
var observers: [WeakObserverReference] { set get }
}
class WeakObserverReference {
private(set) weak var observer: ObserverObject?
init(observer: ObserverObject?) {
self.observer = observer
}
}
extension Observable where Self: ObserversContainer {
mutating func addObserver(_ observer: ObserverObject) {
observers.append(WeakObserverReference(observer: observer))
}
mutating func removeObserver(_ observer: AnyObject & Observer) {
if let observerIndex = observers.index(where: { $0 === observer }) {
observers.remove(at: observerIndex)
}
}
func notifyObservers() {
self.observers.forEach { $0.observer?.didUpdateObservableObject(self) }
}
}
|
mit
|
a03d477fd552c73f58b7f5006142f074
| 24.16 | 79 | 0.697138 | 4.492857 | false | false | false | false |
sinsoku/PlayingCard
|
Sources/PlayingCard/Game/Poker.swift
|
1
|
4609
|
class Poker {
struct PokerComparing: CardComparable {
static let suitLevel: Array<Suit> = [.Club, .Diamond, .Heart, .Spade]
static let rankLevel: Array<Rank> = [.Two, .Three, .Four, .Five, .Six, .Seven, .Eight,
.Nine, .Ten, .Jack, .Queen, .King, .Ace]
static func eq<T>(_ lhs: Card<T>, _ rhs: Card<T>) -> Bool {
return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}
static func lt<T>(_ lhs: Card<T>, _ rhs: Card<T>) -> Bool {
return lhs != rhs &&
(rankLevel.index(of: lhs.rank) < rankLevel.index(of: rhs.rank) ||
suitLevel.index(of: lhs.suit) < suitLevel.index(of: rhs.suit))
}
}
enum Hand: Int {
case OnePair
case TwoPair
case ThreeOfAKind
case Straight
case Flush
case FullHouse
case FourOfAKind
case StraightFlush
case RoyalStraightFlush
case HighCard
static func judge<T>(_ cards: Set<Card<T>>) -> Hand {
if isRoyalStraightFlush(cards) {
return .RoyalStraightFlush
} else if isStraightFlush(cards) {
return .StraightFlush
} else if isFourOfAKind(cards) {
return .FourOfAKind
} else if isFullHouse(cards) {
return .FullHouse
} else if isFlush(cards) {
return .Flush
} else if isStraight(cards) {
return .Straight
} else if isThreeOfAKind(cards) {
return .ThreeOfAKind
} else if isTwoPair(cards) {
return .TwoPair
} else if isOnePair(cards) {
return .OnePair
} else {
return .HighCard
}
}
private static func isRoyalStraightFlush<T>(_ cards: Set<Card<T>>) -> Bool {
return [
Util.factory("10S", "11S", "12S", "13S", "1S"),
Util.factory("10H", "11H", "12H", "13H", "1H"),
Util.factory("10C", "11C", "12C", "13C", "1C"),
Util.factory("10D", "11D", "12D", "13D", "1D")
].contains(cards)
}
private static func isStraightFlush<T>(_ cards: Set<Card<T>>) -> Bool {
return isFlush(cards) && isStraight(cards)
}
private static func isFourOfAKind<T>(_ cards: Set<Card<T>>) -> Bool {
var result: Dictionary<Rank, Int> = [:]
cards.forEach {
if let value = result[$0.rank] {
result[$0.rank] = value + 1
} else {
result[$0.rank] = 1
}
}
return result.values.contains(4)
}
private static func isFullHouse<T>(_ cards: Set<Card<T>>) -> Bool {
var result: Dictionary<Rank, Int> = [:]
cards.forEach {
if let value = result[$0.rank] {
result[$0.rank] = value + 1
} else {
result[$0.rank] = 1
}
}
return result.values.contains(3) && result.values.contains(2)
}
private static func isFlush<T>(_ cards: Set<Card<T>>) -> Bool {
return Set(cards.map { $0.suit }).count == 1
}
private static func isStraight<T>(_ cards: Set<Card<T>>) -> Bool {
let ranks = cards.map { $0.rank.rawValue }.sorted()
if ranks == [1, 10, 11, 12, 13] {
return true
} else {
return ranks[4] - ranks[0] == 4
}
}
private static func isThreeOfAKind<T>(_ cards: Set<Card<T>>) -> Bool {
var result: Dictionary<Rank, Int> = [:]
cards.forEach {
if let value = result[$0.rank] {
result[$0.rank] = value + 1
} else {
result[$0.rank] = 1
}
}
return result.values.contains(3)
}
private static func isTwoPair<T>(_ cards: Set<Card<T>>) -> Bool {
var result: Dictionary<Rank, Int> = [:]
cards.forEach {
if let value = result[$0.rank] {
result[$0.rank] = value + 1
} else {
result[$0.rank] = 1
}
}
return result.filter { $1 == 2 }.count == 2
}
private static func isOnePair<T>(_ cards: Set<Card<T>>) -> Bool {
var result: Dictionary<Rank, Int> = [:]
cards.forEach {
if let value = result[$0.rank] {
result[$0.rank] = value + 1
} else {
result[$0.rank] = 1
}
}
return result.filter { $1 == 2 }.count == 1
}
}
}
|
mit
|
e054e734446ba12033b0132319612fbe
| 31.687943 | 92 | 0.482317 | 3.828073 | false | false | false | false |
jovito-royeca/Decktracker
|
ios/Pods/Eureka/Source/Rows/SliderRow.swift
|
4
|
5201
|
// SliderRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// The cell of the SliderRow
public class SliderCell: Cell<Float>, CellType {
public required init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .Value1, reuseIdentifier: reuseIdentifier)
}
public var titleLabel: UILabel! {
textLabel?.translatesAutoresizingMaskIntoConstraints = false
textLabel?.setContentHuggingPriority(500, forAxis: .Horizontal)
return textLabel
}
public var valueLabel: UILabel! {
detailTextLabel?.translatesAutoresizingMaskIntoConstraints = false
detailTextLabel?.setContentHuggingPriority(500, forAxis: .Horizontal)
return detailTextLabel
}
lazy public var slider: UISlider = {
let result = UISlider()
result.translatesAutoresizingMaskIntoConstraints = false
result.setContentHuggingPriority(500, forAxis: .Horizontal)
return result
}()
public var formatter: NSNumberFormatter?
public override func setup() {
super.setup()
selectionStyle = .None
slider.minimumValue = sliderRow.minimumValue
slider.maximumValue = sliderRow.maximumValue
slider.addTarget(self, action: #selector(SliderCell.valueChanged), forControlEvents: .ValueChanged)
if shouldShowTitle() {
contentView.addSubview(titleLabel)
contentView.addSubview(valueLabel!)
}
contentView.addSubview(slider)
let views = ["titleLabel" : titleLabel, "valueLabel" : valueLabel, "slider" : slider]
let metrics = ["hPadding" : 16.0, "vPadding" : 12.0, "spacing" : 12.0]
if shouldShowTitle() {
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-hPadding-[titleLabel]-[valueLabel]-hPadding-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: metrics, views: views))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-vPadding-[titleLabel]-spacing-[slider]-vPadding-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: metrics, views: views))
} else {
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-vPadding-[slider]-vPadding-|", options: NSLayoutFormatOptions.AlignAllLeft, metrics: metrics, views: views))
}
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-hPadding-[slider]-hPadding-|", options: NSLayoutFormatOptions.AlignAllBaseline, metrics: metrics, views: views))
}
public override func update() {
super.update()
if !shouldShowTitle() {
textLabel?.text = nil
detailTextLabel?.text = nil
}
slider.value = row.value ?? 0.0
}
func valueChanged() {
let roundedValue: Float
let steps = Float(sliderRow.steps)
if steps > 0 {
let stepValue = round((slider.value - slider.minimumValue) / (slider.maximumValue - slider.minimumValue) * steps)
let stepAmount = (slider.maximumValue - slider.minimumValue) / steps
roundedValue = stepValue * stepAmount + self.slider.minimumValue
}
else {
roundedValue = slider.value
}
row.value = roundedValue
if shouldShowTitle() {
valueLabel.text = "\(row.value!)"
}
}
private func shouldShowTitle() -> Bool {
return row.title?.isEmpty == false
}
private var sliderRow: SliderRow {
return row as! SliderRow
}
}
/// A row that displays a UISlider. If there is a title set then the title and value will appear above the UISlider.
public final class SliderRow: Row<Float, SliderCell>, RowType {
public var minimumValue: Float = 0.0
public var maximumValue: Float = 10.0
public var steps: UInt = 20
required public init(tag: String?) {
super.init(tag: tag)
}
}
|
apache-2.0
|
740106bae31e57860ec9386e2adca79e
| 40.943548 | 220 | 0.681023 | 5.16998 | false | false | false | false |
KelvinJin/NextGrowingTextView
|
Pod/Classes/NextGrowingInternalTextView.swift
|
1
|
3322
|
// NextGrowingInternalTextView.swift
//
// Copyright (c) 2015 muukii
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: - NextGrowingInternalTextView: UITextView
internal class NextGrowingInternalTextView: UITextView {
// MARK: - Internal
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NotificationCenter.default.addObserver(self, selector: #selector(NextGrowingInternalTextView.textDidChangeNotification(_ :)), name: NSNotification.Name.UITextViewTextDidChange, object: self)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override var text: String! {
didSet {
self.updatePlaceholder()
}
}
var placeholderAttributedText: NSAttributedString? {
didSet {
self.setNeedsDisplay()
}
}
override func layoutSubviews() {
super.layoutSubviews()
self.setNeedsDisplay()
}
override func draw(_ rect: CGRect) {
super.draw(rect)
guard self.displayPlaceholder == true else {
return
}
let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = self.textAlignment
let targetRect = CGRect(x: 5, y: 8 + self.contentInset.top, width: self.frame.size.width - self.contentInset.left, height: self.frame.size.height - self.contentInset.top)
let attributedString = self.placeholderAttributedText
attributedString?.draw(in: targetRect)
}
// MARK: Private
fileprivate var displayPlaceholder: Bool = true {
didSet {
if oldValue != self.displayPlaceholder {
self.setNeedsDisplay()
}
}
}
fileprivate dynamic func textDidChangeNotification(_ notification: Notification) {
self.updatePlaceholder()
}
fileprivate func updatePlaceholder() {
self.displayPlaceholder = self.text.characters.count == 0
}
}
|
mit
|
89182d62169fa777f618835f176b2aaa
| 32.897959 | 198 | 0.674594 | 5.142415 | false | false | false | false |
ZulwiyozaPutra/Alien-Adventure-Tutorial
|
Alien Adventure/OldestItemFromPlanet.swift
|
1
|
1458
|
//
// OldestItemFromPlanet.swift
// Alien Adventure
//
// Created by Jarrod Parkes on 10/3/15.
// Copyright © 2015 Udacity. All rights reserved.
//
extension Hero {
func oldestItemFromPlanet(inventory: [UDItem], planet: String) -> UDItem? {
var oldestPlanet: UDItem?
var oldestPlanetAge: Int?
for item in inventory {
let histocicalDataItem = item.historicalData
if let planetItem = histocicalDataItem["PlanetOfOrigin"] as? String {
if planetItem == planet {
print("\(item.name) item matched which is \(planet)")
if let planetAge = histocicalDataItem["CarbonAge"] as? Int {
if oldestPlanet == nil {
oldestPlanet = item
oldestPlanetAge = planetAge
} else if oldestPlanetAge! <= planetAge {
oldestPlanet = item
oldestPlanetAge = planetAge
}
}
}
}
}
return oldestPlanet
}
}
// If you have completed this function and it is working correctly, feel free to skip this part of the adventure by opening the "Under the Hood" folder, and making the following change in Settings.swift: "static var RequestsToSkip = 2"
|
mit
|
d22036f976b8eee42f906f8023f3d38a
| 32.883721 | 235 | 0.520933 | 5.278986 | false | false | false | false |
Antondomashnev/Sourcery
|
SourceryTests/Parsing/AnnotationsParserSpec.swift
|
1
|
4312
|
//
// Created by Krzysztof Zablocki on 31/12/2016.
// Copyright (c) 2016 Pixle. All rights reserved.
//
import Quick
import Nimble
import PathKit
import SourceKittenFramework
@testable import Sourcery
@testable import SourceryRuntime
class AnnotationsParserSpec: QuickSpec {
override func spec() {
describe("AnnotationsParser") {
describe("parse(line:)") {
func parse(_ content: String) -> Annotations {
return AnnotationsParser.parse(line: content)
}
it("extracts single annotation") {
let annotations = ["skipEquality": NSNumber(value: true)]
expect(parse("skipEquality")).to(equal(annotations))
}
it("extracts repeated annotations into array") {
let parsedAnnotations = parse("implements = \"Service1\", implements = \"Service2\"")
expect(parsedAnnotations["implements"] as? [String]).to(equal(["Service1", "Service2"]))
}
it("extracts multiple annotations on the same line") {
let annotations = ["skipEquality": NSNumber(value: true),
"jsonKey": "json_key" as NSString]
expect(parse("skipEquality, jsonKey = \"json_key\"")).to(equal(annotations))
}
}
describe("parse(content:)") {
func parse(_ content: String) -> Annotations {
return AnnotationsParser(contents: content).all
}
it("extracts inline annotations") {
let result = parse("//sourcery: skipDescription\n/* sourcery: skipEquality */var name: Int { return 2 }")
expect(result).to(equal([
"skipDescription": NSNumber(value: true),
"skipEquality": NSNumber(value: true)
]))
}
it("extracts multi-line annotations, including numbers") {
let annotations = ["skipEquality": NSNumber(value: true),
"placeholder": "geo:37.332112,-122.0329753?q=1 Infinite Loop" as NSString,
"jsonKey": "[\"json_key\": key, \"json_value\": value]" as NSString,
"thirdProperty": NSNumber(value: -3)]
let result = parse("// sourcery: skipEquality, jsonKey = [\"json_key\": key, \"json_value\": value]\n" +
"// sourcery: thirdProperty = -3\n" +
"// sourcery: placeholder = \"geo:37.332112,-122.0329753?q=1 Infinite Loop\"\n" +
"var name: Int { return 2 }")
expect(result).to(equal(annotations))
}
it("extracts repeated annotations into array") {
let parsedAnnotations = parse("// sourcery: implements = \"Service1\"\n// sourcery: implements = \"Service2\"")
expect(parsedAnnotations["implements"] as? [String]).to(equal(["Service1", "Service2"]))
}
it("extracts annotations interleaved with comments") {
let annotations = ["isSet": NSNumber(value: true),
"numberOfIterations": NSNumber(value: 2)]
let result = parse("// sourcery: isSet\n" +
"/// isSet is used for something useful\n" +
"// sourcery: numberOfIterations = 2\n" +
"var name: Int { return 2 }")
expect(result).to(equal(annotations))
}
it("extracts file annotations") {
let annotations = ["isSet": NSNumber(value: true)]
let result = parse("// sourcery:file: isSet\n" +
"/// isSet is used for something useful\n" +
"var name: Int { return 2 }")
expect(result).to(equal(annotations))
}
}
}
}
}
|
mit
|
302f22b302df00433951e07cf85a982a
| 45.869565 | 131 | 0.478432 | 5.451327 | false | false | false | false |
AgaKhanFoundation/WCF-iOS
|
Steps4Impact/Networking/Service.swift
|
1
|
4488
|
/**
* Copyright © 2019 Aga Khan Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
import Dispatch
import Foundation
enum HTTPMethod: String {
case get = "GET"
case delete = "DELETE"
case patch = "PATCH"
case post = "POST"
case put = "PUT"
}
enum ServiceRequestResult {
internal typealias HTTPStatusCode = Int
internal typealias Response = JSON?
case success(statusCode: HTTPStatusCode, response: Response)
case failed(_ error: Error?)
var response: Response {
switch self {
case .success(statusCode: _, response: let response):
return response
case .failed:
return nil
}
}
var isSuccess: Bool {
switch self {
case .success: return true
case .failed: return false
}
}
}
class Service {
typealias ServiceRequestCompletion = (ServiceRequestResult) -> Void
private let server: URLComponents
private let session: URLSession
internal init(server: URLComponents, session: URLSession) {
self.server = server
self.session = session
}
internal func request(_ method: HTTPMethod, url: URL, parameters: JSON? = nil,
completion: ServiceRequestCompletion?) {
var request: URLRequest = URLRequest(url: url)
request.httpBody = parameters?.serialise()
request.httpMethod = method.rawValue
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = session.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
print("<- [\(method.rawValue.uppercased())] \(request) [\(String(data: request.httpBody, encoding: .utf8) ?? "")]") // swiftlint:disable:this line_length
guard error == nil else {
self.callback(completion, result: .failed(error))
return
}
guard let http = response as? HTTPURLResponse else {
self.callback(completion, result: .failed(nil))
return
}
guard let data = data else {
self.callback(completion, result: .failed(nil))
return
}
print("-> [\(http.statusCode)] \(String(data: data, encoding: .utf8) ?? "Not decodable")")
switch JSON.deserialise(data) {
case .some(let response):
self.callback(completion, result: .success(statusCode: http.statusCode, response: response))
default:
self.callback(completion, result: .failed(nil))
}
}
task.resume()
}
internal func callback(_ completion: ServiceRequestCompletion?,
result: ServiceRequestResult) {
guard let completion = completion else { return }
DispatchQueue.main.async {
completion(result)
}
}
internal func buildURL(_ endpoint: String, _ query: JSON? = nil) -> URL? {
var url: URLComponents = server
url.path.append(endpoint)
if let dictionary = query?.dictionaryValue {
var parameters: [String] = []
for (key, value) in dictionary {
parameters.append("\(key)=\(value)")
}
url.query = parameters.joined(separator: "&")
}
return url.url
}
}
|
bsd-3-clause
|
d142c08f627e8f4026d6b349e12bfe78
| 32.485075 | 161 | 0.677067 | 4.55533 | false | false | false | false |
shyn/cs193p
|
Psychologist/Psychologist/FaceView.swift
|
2
|
3848
|
//
// FaceView.swift
// Happiness
//
// Created by deepwind on 4/29/17.
// Copyright © 2017 deepwind. All rights reserved.
//
import UIKit
protocol FaceViewDataSource: class {
// var happiness: Int { get set}
func smilinessForFaceView(sender: FaceView) -> Double?
}
@IBDesignable
class FaceView: UIView
{
@IBInspectable
var lineWidth: CGFloat = 3 { didSet { setNeedsDisplay() } }
@IBInspectable
var scale:CGFloat = 0.9 { didSet { setNeedsDisplay() } }
@IBInspectable
var color:UIColor = UIColor.blue { didSet { setNeedsDisplay() } }
var faceCenter: CGPoint {
return convert(center, from: superview)
}
var faceRadius: CGFloat {
return min(bounds.height, bounds.width)/2 * scale
}
// do not keep this pointer in memory to avoid cycle reference
// but weak can not decorate protocol.. so we make our protocol a 'class':)
weak var dataSource: FaceViewDataSource?
func pinch(_ gesture: UIPinchGestureRecognizer) {
if gesture.state == .changed {
scale *= gesture.scale
gesture.scale = 1
}
}
override func draw(_ rect: CGRect) {
let facePath = UIBezierPath(arcCenter: faceCenter, radius: faceRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
facePath.lineWidth = lineWidth
color.set()
facePath.stroke()
let smiliness = dataSource?.smilinessForFaceView(sender: self) ?? 0.5
bezierPathForEye(whichEye: .Left).stroke()
bezierPathForEye(whichEye: .Right).stroke()
bezierPathForSmile(fractionOfMaxSmile: smiliness).stroke()
}
private struct Scaling {
static let FaceRadiusToEyeRadiusRatio: CGFloat = 10
static let FaceRadiusToEyeOffsetRatio: CGFloat = 3
static let FaceRadiusToEyeSeparationRatio: CGFloat = 1.5
static let FaceRadiusToMouthWidthRatio: CGFloat = 1
static let FaceRadiusToMouthHeightRatio: CGFloat = 3
static let FaceRadiusToMouthOffsetRatio: CGFloat = 3
}
private enum Eye { case Left, Right }
private func bezierPathForSmile(fractionOfMaxSmile: Double) -> UIBezierPath
{
let mouthWidth = faceRadius / Scaling.FaceRadiusToMouthWidthRatio
let mouthHeight = faceRadius / Scaling.FaceRadiusToMouthHeightRatio
let mouthVerticleOffset = faceRadius / Scaling.FaceRadiusToMouthOffsetRatio
let smileHeight = CGFloat(max(min(fractionOfMaxSmile, 1), -1)) * mouthHeight
let start = CGPoint(x: faceCenter.x - mouthWidth/2, y: faceCenter.y + mouthVerticleOffset)
let end = CGPoint(x: start.x + mouthWidth, y: start.y)
let cp1 = CGPoint(x: start.x + mouthWidth/3, y: start.y + smileHeight)
let cp2 = CGPoint(x: end.x - mouthWidth/3, y: cp1.y)
let path = UIBezierPath()
path.move(to: start)
path.addCurve(to: end, controlPoint1: cp1, controlPoint2: cp2)
path.lineWidth = lineWidth
return path
}
private func bezierPathForEye(whichEye: Eye) -> UIBezierPath
{
let eyeRadius = faceRadius / Scaling.FaceRadiusToEyeRadiusRatio
let eyeVerticalOffset = faceRadius / Scaling.FaceRadiusToEyeOffsetRatio
let eyeHorizontalSeparation = faceRadius / Scaling.FaceRadiusToEyeSeparationRatio
var eyeCenter = faceCenter
eyeCenter.y -= eyeVerticalOffset
switch whichEye {
case .Left:
eyeCenter.x -= eyeHorizontalSeparation / 2
case .Right:
eyeCenter.x += eyeHorizontalSeparation / 2
}
let path = UIBezierPath(arcCenter: eyeCenter, radius: eyeRadius, startAngle: 0, endAngle: CGFloat(2*Double.pi), clockwise: true)
path.lineWidth = lineWidth
return path
}
}
|
mit
|
0195fc43877e16befc84d5186e1792bf
| 35.638095 | 142 | 0.656875 | 4.772953 | false | false | false | false |
Eonil/SQLite3
|
Sources/HighLevel/Schema.swift
|
2
|
2505
|
//
// Schema.swift
// EonilSQLite3
//
// Created by Hoon H. on 9/18/14.
//
//
import Foundation
/// Provides simple and convenient methods
public struct Schema {
unowned let owner:Database
init(owner:Database) {
self.owner = owner
}
}
public extension Schema {
public var database:Database {
get {
return owner
}
}
public func namesOfAllTables() -> [String] {
let x = database.connection.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").execute()
let d = x.allDictionaries()
return d.map {$0["name"]!.text!}
}
public func table(of name:String) -> Schema.Table {
let p = Query.Language.Syntax.Pragma(database: nil, name: "table_info", argument: Query.Language.Syntax.Pragma.Argument.Call(value: name))
let c = p.description
let d = database.connection.prepare(c).execute().allDictionaries()
Debug.log(d)
return Schema.Table(name: "?", key: [], columns: [])
}
// public func create(table q:Query.Schema.Table.Create) {
// database.apply { self.database.connection.run(q) }
// }
public func create(#tableName:String, keyColumnNames:[String], dataColumnNames:[String]) {
let kcs = keyColumnNames.map {Schema.Column(name: $0, nullable: false, type: Schema.Column.TypeCode.None, unique: true, index: nil)}
let dcs = dataColumnNames.map {Schema.Column(name: $0, nullable: true, type: Schema.Column.TypeCode.None, unique: false, index: nil)}
let def = Schema.Table(name: tableName, key: keyColumnNames, columns: kcs+dcs)
let cmd = Query.Schema.Table.Create(temporary: false, definition: def)
database.apply { self.database.connection.run(cmd) }
}
public func create(#tableName:String, keyColumnName:String, dataColumnNames:[String]) {
create(tableName: tableName, keyColumnNames: [keyColumnName], dataColumnNames: dataColumnNames)
}
public func create(#tableName:String, dataColumnNames:[String]) {
create(tableName: tableName, keyColumnNames: [], dataColumnNames: dataColumnNames)
}
// public func drop(table q:Query.Schema.Table.Drop) {
// func tx() {
// database.connection.run(q.express())
// }
// database.apply(tx)
// }
public func drop(table tname:String) {
let cmd = Query.Schema.Table.Drop(name: Query.Identifier(tname), ifExists: false)
database.apply { self.database.connection.run(cmd) }
}
func allRowsOfRawMasterTable() -> [[String:Value]] {
return database.apply { self.database.connection.run("SELECT * FROM sqlite_master") }
}
}
|
mit
|
7dde7f1bff55dad4e8d3bd5e085f3397
| 22.411215 | 140 | 0.697405 | 3.10794 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/RxGesture/Pod/Classes/SharedTypes.swift
|
1
|
3375
|
// Copyright (c) RxSwiftCommunity
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
#if os(iOS)
import UIKit
public typealias Touch = UITouch
public typealias GestureRecognizer = UIGestureRecognizer
#if swift(>=4.2)
public typealias GestureRecognizerState = UIGestureRecognizer.State
#else
public typealias GestureRecognizerState = UIGestureRecognizerState
#endif
public typealias GestureRecognizerDelegate = UIGestureRecognizerDelegate
public typealias View = UIView
public typealias Point = CGPoint
#elseif os(OSX)
import AppKit
public typealias Touch = NSTouch
public typealias GestureRecognizer = NSGestureRecognizer
public typealias GestureRecognizerState = NSGestureRecognizer.State
public typealias GestureRecognizerDelegate = NSGestureRecognizerDelegate
public typealias View = NSView
public typealias Point = NSPoint
#endif
public enum TargetView {
/// The target view will be the gestureRecognizer's view
case view
/// The target view will be the gestureRecognizer's view's superview
case superview
/// The target view will be the gestureRecognizer's view's window
case window
/// The target view will be the given view
case this(View)
public func targetView(for gestureRecognizer: GestureRecognizer) -> View? {
switch self {
case .view:
return gestureRecognizer.view
case .superview:
return gestureRecognizer.view?.superview
case .window:
#if os(iOS)
return gestureRecognizer.view?.window
#elseif os(OSX)
return gestureRecognizer.view?.window?.contentView
#endif
case .this(let view):
return view
}
}
}
extension GestureRecognizerState: CustomStringConvertible {
public var description: String {
return String(describing: type(of: self)) + {
switch self {
case .possible: return ".possible"
case .began: return ".began"
case .changed: return ".changed"
case .ended: return ".ended"
case .cancelled: return ".cancelled"
case .failed: return ".failed"
@unknown default: return ".failed"
}
}()
}
}
|
apache-2.0
|
bb5edcd87d60efc4955cf80aeb0aa6be
| 36.5 | 80 | 0.69037 | 5.28169 | false | false | false | false |
esttorhe/RxSwift
|
RxSwift/RxSwift/Observables/Observable+Single.swift
|
1
|
4370
|
//
// Observable+Single.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
// as observable
public func asObservable<E>
(source: Observable<E>) -> Observable<E> {
if let asObservable = source as? AsObservable<E> {
return asObservable.omega()
}
else {
return AsObservable(source: source)
}
}
// distinct until changed
public func distinctUntilChangedOrDie<E: Equatable>(source: Observable<E>)
-> Observable<E> {
return distinctUntilChangedOrDie({ success($0) }, { success($0 == $1) })(source)
}
public func distinctUntilChangedOrDie<E, K: Equatable>
(keySelector: (E) -> RxResult<K>)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChangedOrDie(keySelector, { success($0 == $1) })(source)
}
}
public func distinctUntilChangedOrDie<E>
(comparer: (lhs: E, rhs: E) -> RxResult<Bool>)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChangedOrDie({ success($0) }, comparer)(source)
}
}
public func distinctUntilChangedOrDie<E, K>
(keySelector: (E) -> RxResult<K>, _ comparer: (lhs: K, rhs: K) -> RxResult<Bool>)
-> (Observable<E> -> Observable<E>) {
return { source in
return DistinctUntilChanged(source: source, selector: keySelector, comparer: comparer)
}
}
public func distinctUntilChanged<E: Equatable>(source: Observable<E>)
-> Observable<E> {
return distinctUntilChanged({ $0 }, { ($0 == $1) })(source)
}
public func distinctUntilChanged<E, K: Equatable>
(keySelector: (E) -> K)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChanged(keySelector, { ($0 == $1) })(source)
}
}
public func distinctUntilChanged<E>
(comparer: (lhs: E, rhs: E) -> Bool)
-> (Observable<E> -> Observable<E>) {
return { source in
return distinctUntilChanged({ ($0) }, comparer)(source)
}
}
public func distinctUntilChanged<E, K>
(keySelector: (E) -> K, _ comparer: (lhs: K, rhs: K) -> Bool)
-> (Observable<E> -> Observable<E>) {
return { source in
return DistinctUntilChanged(source: source, selector: {success(keySelector($0)) }, comparer: { success(comparer(lhs: $0, rhs: $1))})
}
}
// do
public func doOrDie<E>
(eventHandler: (Event<E>) -> RxResult<Void>)
-> (Observable<E> -> Observable<E>) {
return { source in
return Do(source: source, eventHandler: eventHandler)
}
}
public func `do`<E>
(eventHandler: (Event<E>) -> Void)
-> (Observable<E> -> Observable<E>) {
return { source in
return Do(source: source, eventHandler: { success(eventHandler($0)) })
}
}
// doOnNext
public func doOnNext<E>
(actionOnNext: E -> Void)
-> (Observable<E> -> Observable<E>) {
return { source in
return source >- `do` { event in
switch event {
case .Next(let value):
actionOnNext(value)
default:
break
}
}
}
}
// startWith
// Prefixes observable sequence with `firstElement` element.
// The same functionality could be achieved using `concat([returnElement(prefix), source])`,
// but this is significantly more efficient implementation.
public func startWith<E>
(firstElement: E)
-> (Observable<E> -> Observable<E>) {
return { source in
return StartWith(source: source, element: firstElement)
}
}
// retry
public func retry<E>
(source: Observable<E>)
-> Observable<E> {
return AnySequence(InifiniteSequence(repeatedValue: source)) >- onError
}
public func retry<E>
(retryCount: Int)
-> Observable<E> -> Observable<E> {
return { source in
return AnySequence(Repeat(count: retryCount, repeatedValue: source)) >- onError
}
}
// scan
public func scan<E, A>
(seed: A, accumulator: (A, E) -> A)
-> Observable<E> -> Observable<A> {
return { source in
return Scan(source: source, seed: seed, accumulator: { success(accumulator($0, $1)) })
}
}
public func scanOrDie<E, A>
(seed: A, accumulator: (A, E) -> RxResult<A>)
-> Observable<E> -> Observable<A> {
return { source in
return Scan(source: source, seed: seed, accumulator: accumulator)
}
}
|
mit
|
ad4ae2ff08e55592f712795f703007bd
| 25.652439 | 140 | 0.618535 | 3.780277 | false | false | false | false |
jaksatomovic/Snapgram
|
Snapgram/homeVC.swift
|
1
|
10939
|
//
// homeVC.swift
// Snapgram
//
// Created by Jaksa Tomovic on 28/11/16.
// Copyright © 2016 Jaksa Tomovic. All rights reserved.
//
import UIKit
import Parse
class homeVC: UICollectionViewController {
// refresher variable
var refresher : UIRefreshControl!
// size of page
var page : Int = 12
// arrays to hold server information
var uuidArray = [String]()
var picArray = [PFFile]()
// default func
override func viewDidLoad() {
super.viewDidLoad()
// always vertical scroll
self.collectionView?.alwaysBounceVertical = true
// background color
collectionView?.backgroundColor = .white
// title at the top
self.navigationItem.title = PFUser.current()?.username?.uppercased()
// pull to refresh
refresher = UIRefreshControl()
refresher.addTarget(self, action: #selector(homeVC.refresh), for: UIControlEvents.valueChanged)
collectionView?.addSubview(refresher)
// receive notification from editVC
NotificationCenter.default.addObserver(self, selector: #selector(homeVC.reload(_:)), name: NSNotification.Name(rawValue: "reload"), object: nil)
// load posts func
loadPosts()
}
// refreshing func
func refresh() {
// reload posts
loadPosts()
// stop refresher animating
refresher.endRefreshing()
}
// reloading func after received notification
func reload(_ notification:Notification) {
collectionView?.reloadData()
}
// load posts func
func loadPosts() {
// request infomration from server
let query = PFQuery(className: "posts")
query.whereKey("username", equalTo: PFUser.current()!.username!)
query.limit = page
query.findObjectsInBackground (block: { (objects, error) -> Void in
if error == nil {
// clean up
self.uuidArray.removeAll(keepingCapacity: false)
self.picArray.removeAll(keepingCapacity: false)
// find objects related to our request
for object in objects! {
// add found data to arrays (holders)
self.uuidArray.append(object.value(forKey: "uuid") as! String)
self.picArray.append(object.value(forKey: "pic") as! PFFile)
}
self.collectionView?.reloadData()
} else {
print(error!.localizedDescription)
}
})
}
// load more while scrolling down
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y >= scrollView.contentSize.height - self.view.frame.size.height {
loadMore()
}
}
// paging
func loadMore() {
// if there is more objects
if page <= picArray.count {
// increase page size
page = page + 12
// load more posts
let query = PFQuery(className: "posts")
query.whereKey("username", equalTo: PFUser.current()!.username!)
query.limit = page
query.findObjectsInBackground(block: { (objects, error) -> Void in
if error == nil {
// clean up
self.uuidArray.removeAll(keepingCapacity: false)
self.picArray.removeAll(keepingCapacity: false)
// find related objects
for object in objects! {
self.uuidArray.append(object.value(forKey: "uuid") as! String)
self.picArray.append(object.value(forKey: "pic") as! PFFile)
}
self.collectionView?.reloadData()
} else {
print(error?.localizedDescription)
}
})
}
}
// cell numb
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picArray.count
}
// cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath) -> CGSize {
let size = CGSize(width: self.view.frame.size.width / 3, height: self.view.frame.size.width / 3)
return size
}
// cell config
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// define cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! pictureCell
// get picture from the picArray
picArray[(indexPath as NSIndexPath).row].getDataInBackground { (data, error) -> Void in
if error == nil {
cell.picImg.image = UIImage(data: data!)
}
}
return cell
}
// header config
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// define header
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Header", for: indexPath) as! headerView
// STEP 1. Get user data
// get users data with connections to collumns of PFuser class
header.fullnameLbl.text = (PFUser.current()?.object(forKey: "fullname") as? String)?.uppercased()
header.webTxt.text = PFUser.current()?.object(forKey: "web") as? String
header.webTxt.sizeToFit()
header.bioLbl.text = PFUser.current()?.object(forKey: "bio") as? String
header.bioLbl.sizeToFit()
let avaQuery = PFUser.current()?.object(forKey: "ava") as! PFFile
avaQuery.getDataInBackground { (data, error) -> Void in
header.avaImg.image = UIImage(data: data!)
}
header.button.setTitle("edit profile", for: UIControlState())
// STEP 2. Count statistics
// count total posts
let posts = PFQuery(className: "posts")
posts.whereKey("username", equalTo: PFUser.current()!.username!)
posts.countObjectsInBackground (block: { (count, error) -> Void in
if error == nil {
header.posts.text = "\(count)"
}
})
// count total followers
let followers = PFQuery(className: "follow")
followers.whereKey("following", equalTo: PFUser.current()!.username!)
followers.countObjectsInBackground (block: { (count, error) -> Void in
if error == nil {
header.followers.text = "\(count)"
}
})
// count total followings
let followings = PFQuery(className: "follow")
followings.whereKey("follower", equalTo: PFUser.current()!.username!)
followings.countObjectsInBackground (block: { (count, error) -> Void in
if error == nil {
header.followings.text = "\(count)"
}
})
// STEP 3. Implement tap gestures
// tap posts
let postsTap = UITapGestureRecognizer(target: self, action: #selector(homeVC.postsTap))
postsTap.numberOfTapsRequired = 1
header.posts.isUserInteractionEnabled = true
header.posts.addGestureRecognizer(postsTap)
// tap followers
let followersTap = UITapGestureRecognizer(target: self, action: #selector(homeVC.followersTap))
followersTap.numberOfTapsRequired = 1
header.followers.isUserInteractionEnabled = true
header.followers.addGestureRecognizer(followersTap)
// tap followings
let followingsTap = UITapGestureRecognizer(target: self, action: #selector(homeVC.followingsTap))
followingsTap.numberOfTapsRequired = 1
header.followings.isUserInteractionEnabled = true
header.followings.addGestureRecognizer(followingsTap)
return header
}
// taped posts label
func postsTap() {
if !picArray.isEmpty {
let index = IndexPath(item: 0, section: 0)
self.collectionView?.scrollToItem(at: index, at: UICollectionViewScrollPosition.top, animated: true)
}
}
// tapped followers label
func followersTap() {
user = PFUser.current()!.username!
showDetails = "followers"
// make references to followersVC
let followers = self.storyboard?.instantiateViewController(withIdentifier: "followersVC") as! followersVC
// present
self.navigationController?.pushViewController(followers, animated: true)
}
// tapped followings label
func followingsTap() {
user = PFUser.current()!.username!
showDetails = "followings"
// make reference to followersVC
let followings = self.storyboard?.instantiateViewController(withIdentifier: "followersVC") as! followersVC
// present
self.navigationController?.pushViewController(followings, animated: true)
}
// clicked log out
@IBAction func logout(_ sender: AnyObject) {
// implement log out
PFUser.logOutInBackground { (error) -> Void in
if error == nil {
// remove logged in user from App memory
UserDefaults.standard.removeObject(forKey: "username")
UserDefaults.standard.synchronize()
let signin = self.storyboard?.instantiateViewController(withIdentifier: "signInVC") as! signInVC
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = signin
}
}
}
// go post
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// send post uuid to "postuuid" variable
postuuid.append(uuidArray[(indexPath as NSIndexPath).row])
// navigate to post view controller
let post = self.storyboard?.instantiateViewController(withIdentifier: "postVC") as! postVC
self.navigationController?.pushViewController(post, animated: true)
}
}
|
mit
|
4fb9b73dbcceba7ce696e92a5d30ca1c
| 33.504732 | 176 | 0.582739 | 5.560752 | false | false | false | false |
chelseafarley/SwiftTextFields
|
SwiftTextFields/SwiftTextFields/UIValidationTextField.swift
|
1
|
1100
|
//
// UIValidationTextField.swift
// SwiftTextFieldsSample
//
// Created by Chelsea Farley on 9/06/15.
// Copyright (c) 2015 Trip Wire. All rights reserved.
//
import UIKit
@IBDesignable public class UIValidationTextField: UITextField {
var overlayView : UIView!
var isValid = true
public func validateInput() -> Bool {
return isValid
}
public func showOrHideOverlay() {
if (isValid && rightView != nil) {
rightView = nil
rightViewMode = UITextFieldViewMode.Never
} else if (!isValid && rightView == nil) {
rightView = overlayView
rightViewMode = UITextFieldViewMode.Always
}
}
@IBInspectable public var messageColor : UIColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1) {
didSet {
(overlayView as! UIOverlayLabel).textColor = messageColor
}
}
@IBInspectable public var messageFont : UIFont = UIFont.systemFontOfSize(10) {
didSet {
(overlayView as! UIOverlayLabel).font = messageFont
}
}
}
|
cc0-1.0
|
3e4277b82305fc0cec266fe3ac32a4b8
| 26.525 | 107 | 0.612727 | 4.803493 | false | false | false | false |
couchbits/iOSToolbox
|
Sources/Extensions/UIKit/Controls/UISegmentedControlExtensions.swift
|
1
|
1267
|
//
// UISegmentedControlExtensions.swift
// iOSToolbox
//
// Created by Dominik Gauggel on 16.11.17.
//
import Foundation
private var ValuecChangedBlockHandlerKey: UInt8 = 0
public extension UISegmentedControl {
convenience init(valueChanged: ((UISegmentedControl) -> Void)? = nil) {
self.init()
initializeHandler(valueChanged)
}
var valueChanged: ((UISegmentedControl) -> Void)? {
get {
return blockHandler?.blockHandler
}
set {
initializeHandler(newValue)
}
}
internal var blockHandler: GenericBlockHandler<UISegmentedControl>? {
get { return getAssociated(associativeKey: &ValuecChangedBlockHandlerKey) }
set { setAssociated(value: newValue, associativeKey: &ValuecChangedBlockHandlerKey) }
}
internal func initializeHandler(_ handler: ((UISegmentedControl) -> Void)?) {
if let handler = blockHandler {
removeTarget(handler, action: GenericBlockHandlerAction, for: .valueChanged)
}
if let handler = handler {
blockHandler = GenericBlockHandler(object: self, blockHandler: handler)
addTarget(blockHandler, action: GenericBlockHandlerAction, for: .valueChanged)
}
}
}
|
mit
|
277356b3f2e8fa2f3c8737bffe2d20d1
| 29.166667 | 93 | 0.664562 | 4.968627 | false | false | false | false |
codestergit/swift
|
test/IRGen/objc_methods.swift
|
4
|
5377
|
// RUN: rm -rf %t && mkdir -p %t
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -primary-file %s -emit-ir | %FileCheck --check-prefix=CHECK --check-prefix=CHECK-%target-os %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import Foundation
// Protocol methods require extended method type encodings to capture block
// signatures and parameter object types.
@objc protocol Fooable {
func block(_: (Int) -> Int)
func block2(_: (Int,Int) -> Int)
func takesString(_: String) -> String
func takesArray(_: [AnyObject]) -> [AnyObject]
func takesDict(_: [NSObject: AnyObject]) -> [NSObject: AnyObject]
func takesSet(_: Set<NSObject>) -> Set<NSObject>
}
class Foo: Fooable {
func bar() {}
@objc func baz() {}
@IBAction func garply(_: AnyObject?) {}
@objc func block(_: (Int) -> Int) {}
@objc func block2(_: (Int,Int) -> Int) {}
@objc func takesString(_ x: String) -> String { return x }
@objc func takesArray(_ x: [AnyObject]) -> [AnyObject] { return x }
@objc func takesDict(_ x: [NSObject: AnyObject]) -> [NSObject: AnyObject] { return x }
@objc func takesSet(_ x: Set<NSObject>) -> Set<NSObject> { return x }
@objc func fail() throws {}
}
// CHECK: [[BAZ_SIGNATURE:@.*]] = private unnamed_addr constant [8 x i8] c"v16@0:8\00"
// CHECK: [[GARPLY_SIGNATURE:@.*]] = private unnamed_addr constant [11 x i8] c"v24@0:8@16\00"
// CHECK: [[BLOCK_SIGNATURE_TRAD:@.*]] = private unnamed_addr constant [12 x i8] c"v24@0:8@?16\00"
// CHECK-macosx: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"c24@0:8^@16\00"
// CHECK-ios: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK-tvos: [[FAIL_SIGNATURE:@.*]] = private unnamed_addr constant [12 x i8] c"B24@0:8^@16\00"
// CHECK: @_INSTANCE_METHODS__TtC12objc_methods3Foo = private constant { {{.*}}] } {
// CHECK: i32 24,
// CHECK: i32 9,
// CHECK: [9 x { i8*, i8*, i8* }] [{
// CHECK: i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\01L_selector_data(baz)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* [[BAZ_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*)* @_T012objc_methods3FooC3bazyyFTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(garply:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([11 x i8], [11 x i8]* [[GARPLY_SIGNATURE]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i8*)* @_T012objc_methods3FooC6garplyys9AnyObject_pSgFTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([7 x i8], [7 x i8]* @"\01L_selector_data(block:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64)*)* @_T012objc_methods3FooC5blockyS2icFTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([8 x i8], [8 x i8]* @"\01L_selector_data(block2:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[BLOCK_SIGNATURE_TRAD]], i64 0, i64 0),
// CHECK: i8* bitcast (void (i8*, i8*, i64 (i64, i64)*)* @_T012objc_methods3FooC6block2yS2i_SitcFTo to i8*)
// CHECK: }, {
// CHECK: i8* getelementptr inbounds ([20 x i8], [20 x i8]* @"\01L_selector_data(failAndReturnError:)", i64 0, i64 0),
// CHECK: i8* getelementptr inbounds ([12 x i8], [12 x i8]* [[FAIL_SIGNATURE]], i64 0, i64 0),
// CHECK-macosx: i8* bitcast (i8 (i8*, i8*, %4**)* @_T012objc_methods3FooC4failyyKFTo to i8*)
// CHECK-ios: i8* bitcast (i1 (i8*, i8*, %4**)* @_T012objc_methods3FooC4failyyKFTo to i8*)
// CHECK: }]
// CHECK: }, section "__DATA, __objc_const", align 8
// CHECK: [[BLOCK_SIGNATURE_EXT_1:@.*]] = private unnamed_addr constant [18 x i8] c"v24@0:8@?<q@?q>16\00"
// CHECK: [[BLOCK_SIGNATURE_EXT_2:@.*]] = private unnamed_addr constant [19 x i8] c"v24@0:8@?<q@?qq>16\00"
// CHECK: [[STRING_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [31 x i8] c"@\22NSString\2224@0:8@\22NSString\2216\00"
// CHECK: [[ARRAY_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [29 x i8] c"@\22NSArray\2224@0:8@\22NSArray\2216\00"
// CHECK: [[DICT_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [39 x i8] c"@\22NSDictionary\2224@0:8@\22NSDictionary\2216\00"
// CHECK: [[SET_SIGNATURE_EXT:@.*]] = private unnamed_addr constant [25 x i8] c"@\22NSSet\2224@0:8@\22NSSet\2216\00"
// CHECK: @_PROTOCOL_METHOD_TYPES__TtP12objc_methods7Fooable_ = private constant [6 x i8*] [
// CHECK: i8* getelementptr inbounds ([18 x i8], [18 x i8]* [[BLOCK_SIGNATURE_EXT_1]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([19 x i8], [19 x i8]* [[BLOCK_SIGNATURE_EXT_2]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([31 x i8], [31 x i8]* [[STRING_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([29 x i8], [29 x i8]* [[ARRAY_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([39 x i8], [39 x i8]* [[DICT_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: i8* getelementptr inbounds ([25 x i8], [25 x i8]* [[SET_SIGNATURE_EXT]], i64 0, i64 0)
// CHECK: ]
// rdar://16006333 - observing properties don't work in @objc classes
@objc
class ObservingAccessorTest : NSObject {
var bounds: Int = 0 {
willSet {}
didSet {}
}
}
|
apache-2.0
|
42b98794022ec6122eb1e6f6418064cc
| 57.445652 | 157 | 0.628231 | 2.854034 | false | false | false | false |
ziligy/JGSettingsManager
|
JGSettingsManager/SwitchTableCell.swift
|
1
|
1819
|
//
// SwitchTableCell.swift
// JGSettingsManager
//
// Created by Jeff on 12/13/15.
// Copyright © 2015 Jeff Greenberg. All rights reserved.
//
import UIKit
public class SwitchTableCell: UITableViewCell {
// MARK: Data
private var data: JGUserDefault<Bool>!
// MARK: UI
private let boolSwitch = UISwitch()
private let label = UILabel()
// MARK: Init
public convenience init (switchData: JGUserDefault<Bool>, label: String) {
self.init()
self.data = switchData
self.setupViews()
self.initializeUI(label)
}
private func setupViews() {
addSubview(label)
addSubview(boolSwitch)
boolSwitch.addTarget(self, action: Selector("save:"), forControlEvents: .ValueChanged)
boolSwitch.translatesAutoresizingMaskIntoConstraints = false
label.translatesAutoresizingMaskIntoConstraints = false
}
private func initializeUI(title: String) {
label.text = title
boolSwitch.setOn(data.value(), animated: false)
}
// MARK: Save
public func save(sender: UISwitch) {
data.save(sender.on)
}
// MARK: Constraints
override public func layoutSubviews() {
updateConstraints()
}
override public func updateConstraints() {
label.leadingAnchor.constraintEqualToAnchor(leadingAnchor, constant: 10).active = true
label.centerYAnchor.constraintEqualToAnchor(centerYAnchor, constant: 0).active = true
boolSwitch.trailingAnchor.constraintEqualToAnchor(trailingAnchor, constant: -10).active = true
boolSwitch.centerYAnchor.constraintEqualToAnchor(centerYAnchor, constant: 0).active = true
super.updateConstraints()
}
}
|
mit
|
de1923328eeaf0ed0a53cb4bac64018f
| 24.971429 | 102 | 0.644664 | 5.106742 | false | false | false | false |
gewill/Feeyue
|
Feeyue/Main/Lists/Lists/ListsViewModel.swift
|
1
|
1735
|
//
// ListsViewModel.swift
// Feeyue
//
// Created by Will on 2018/7/15.
// Copyright © 2018 Will. All rights reserved.
//
import Foundation
import RealmSwift
import SwiftyJSON
import Moya
import RxSwift
import Moya_SwiftyJSONMapper
import SwifterSwift
class ListsViewModel {
var lists: Results<TwitterList>!
private var token: NotificationToken?
private var realm: Realm!
var userId: String!
var user: TwitterUser?
// MARK: - life cycle
init(userId: String, realm: Realm = RealmProvider.twitter.realm) {
self.userId = userId
self.realm = realm
lists = realm.objects(TwitterList.self)
.sorted(byKeyPath: TwitterList.Property.createdAt.rawValue, ascending: false)
}
deinit {
token?.invalidate()
}
var didUpdate: VoidClosure? = nil {
didSet {
guard let didUpdate = didUpdate,
let lists = lists else {
token?.invalidate()
return
}
token = lists.observe({ changes in
switch changes {
case .initial:
didUpdate()
case .update:
didUpdate()
case .error:
break
}
})
}
}
// MARK: - load data
func reloadData() -> Observable<[TwitterList]> {
return twitterProvider.rx.request(.list(userId))
//.debug()
.map(to: [TwitterList.self])
.asObservable()
.do(onNext: { response in
try! self.realm.write {
self.realm.add(response, update: true)
}
})
}
}
|
mit
|
a21a487a4e5a9387e597e100440d2c4b
| 22.432432 | 89 | 0.527682 | 4.830084 | false | false | false | false |
steelwheels/Coconut
|
CoconutData/Source/CommandLine/CNReadline.swift
|
1
|
7778
|
/*
* @file CNReadline.swift
* @brief Define CNReadline class
* @par Copyright
* Copyright (C) 2019-2021 Steel Wheels Project
*/
import Foundation
import Darwin
open class CNReadline
{
public enum Result {
case none
case string(String, Int) // string, index
case error(NSError)
}
private enum ReadMode {
case input
case popupLines(PopupLines)
}
private struct PopupLines {
var cursorDiff: Int
var addedLines: Int
public init(cursorDiff diff: Int, addedLines lines: Int){
cursorDiff = diff
addedLines = lines
}
}
private var mReadMode: ReadMode
private var mHistory: CNCommandHistory
private var mLine: String
private var mCurrentIndex: String.Index
private var mCodeQueue: CNQueue<CNEscapeCode>
private var mComplemeter: CNCommandComplemeter
private var mHistoryCommandExpression: NSRegularExpression
public init(terminalInfo terminfo: CNTerminalInfo, environment env: CNEnvironment) {
mReadMode = .input
mHistory = CNCommandHistory()
mLine = ""
mCurrentIndex = mLine.startIndex
mCodeQueue = CNQueue()
let cmdtable = CNCommandTable()
mComplemeter = CNCommandComplemeter(terminalInfo: terminfo, commandTable: cmdtable)
mHistoryCommandExpression = try! NSRegularExpression(pattern: #"^\s*!([0-9]+)\s*$"#, options: [])
cmdtable.read(from: env)
}
public var history: Array<String> {
get { return mHistory.commandHistory }
}
open func readLine(console cons: CNFileConsole) -> Result {
switch cons.inputFile.gets() {
case .str(let str):
/* Erace popuped lines if it exist */
switch mReadMode {
case .input:
break // Do nothing
case .popupLines(let plines):
popLines(popupLines: plines, console: cons)
mReadMode = .input
}
switch CNEscapeCode.decode(string: str) {
case .ok(let codes):
for code in codes {
mCodeQueue.push(code)
}
case .error(let err):
return .error(err)
}
case .endOfFile:
break
case .null:
break
}
if let code = mCodeQueue.pop() {
return readLine(escapeCode: code, console: cons)
} else {
return .none
}
}
private func readLine(escapeCode code: CNEscapeCode, console cons: CNConsole) -> Result {
let result: Result
switch code {
case .string(let str):
result = readLine(string: str, console: cons)
case .newline:
result = determineLine(console: cons)
case .tab:
result = complement(console: cons)
case .backspace:
if mLine.startIndex < mCurrentIndex {
mCurrentIndex = mLine.index(before: mCurrentIndex)
cons.print(string: code.encode())
}
result = .none
case .delete:
if mLine.startIndex < mCurrentIndex {
let newidx = mLine.index(before: mCurrentIndex)
mLine.remove(at: newidx)
mCurrentIndex = newidx
cons.print(string: code.encode())
}
result = .none
case .cursorUp(let num), .cursorPreviousLine(let num):
result = selectHistory(delta: -num, console: cons)
case .cursorDown(let num), .cursorNextLine(let num):
result = selectHistory(delta: +num, console: cons)
case .cursorForward(let delta):
for _ in 0..<delta {
if mCurrentIndex < mLine.endIndex {
mCurrentIndex = mLine.index(after: mCurrentIndex)
cons.print(string: code.encode())
} else {
break
}
}
result = .none
case .cursorBackward(let delta):
for _ in 0..<delta {
if mLine.startIndex < mCurrentIndex {
mCurrentIndex = mLine.index(before: mCurrentIndex)
cons.print(string: code.encode())
} else {
break
}
}
result = .none
default:
/* Not supported */
result = .none
}
return result
}
private func readLine(string str: String, console cons: CNConsole) -> Result {
/* Update the current line */
mLine.insert(contentsOf: str, at: mCurrentIndex)
/* Get the substring after current index */
let pstr = mLine.suffix(from: mCurrentIndex)
cons.print(string: String(pstr))
/* Forward index for inserted string */
mCurrentIndex = mLine.index(mCurrentIndex, offsetBy: str.count)
/* Rollback cursor for substring */
let len = pstr.count - str.count
if len > 0 {
cons.print(string: CNEscapeCode.cursorBackward(len).encode())
}
return .none
}
private func determineLine(console cons: CNConsole) -> Result {
/* Move cursor to the end */
moveCursorToEnd(console: cons)
let result: Result
if let repcmd = convertToHistoryCommand(string: mLine) {
result = replaceLine(newLine: repcmd, console: cons)
} else {
/* Normal command */
let dist = mLine.distance(from: mLine.startIndex, to: mCurrentIndex)
result = .string(mLine, dist)
mHistory.append(command: mLine)
mLine = ""
mCurrentIndex = mLine.startIndex
}
return result
}
private func convertToHistoryCommand(string str: String) -> String? {// History ID
let matches = mHistoryCommandExpression.matches(in: str, options: [], range: NSRange(location: 0, length: str.count))
if matches.count > 0 {
let match = matches[0]
if match.numberOfRanges > 1 {
let range = match.range(at: 1)
let start = str.index(str.startIndex, offsetBy: range.location)
let end = str.index(start, offsetBy: range.length)
let pat = String(str[start..<end])
if let val = Int(pat) {
return mHistory.command(at: val)
}
}
}
return nil
}
private func replaceLine(newLine newline: String, console cons: CNConsole) -> Result {
/* Set return value */
let result: Result = .string(newline, newline.count)
/* Reset newline */
mLine = ""
mCurrentIndex = mLine.startIndex
return result
}
private func complement(console cons: CNConsole) -> Result {
switch mComplemeter.complement(string: mLine, index: mCurrentIndex) {
case .none:
break
case .matched(let newline):
replaceCurrentLine(newLine: newline, console: cons)
case .candidates(let lines):
let popup = pushLines(lines: lines, console: cons)
mReadMode = .popupLines(popup)
}
return .none
}
private func selectHistory(delta val: Int, console cons: CNConsole) -> Result {
if let cmd = mHistory.select(delta: val, latest: mLine) {
moveCursorToEnd(console: cons)
replaceCurrentLine(newLine: cmd, console: cons)
}
return .none
}
private func moveCursorToEnd(console cons: CNConsole) {
var mvcount = 0
while mCurrentIndex < mLine.endIndex {
mCurrentIndex = mLine.index(after: mCurrentIndex)
mvcount += 1
}
if mvcount > 0 {
cons.print(string: CNEscapeCode.cursorForward(mvcount).encode())
}
}
private func replaceCurrentLine(newLine str: String, console cons: CNConsole) {
/* Delete current line */
var delcode: String = ""
for _ in 0..<mLine.count {
delcode += CNEscapeCode.delete.encode()
}
cons.print(string: delcode)
/* Put newline */
cons.print(string: str)
/* Reset newline */
mLine = str
mCurrentIndex = mLine.endIndex
}
private func pushLines(lines srclines: Array<String>, console cons: CNConsole) -> PopupLines {
/* Move to end of line */
let mvcnt = mLine.distance(from: mCurrentIndex, to: mLine.endIndex)
var ecode = CNEscapeCode.cursorForward(mvcnt).encode()
mCurrentIndex = mLine.endIndex
/* Append lines */
for line in srclines {
ecode += CNEscapeCode.string("\n" + line).encode()
}
/* Execute the code */
cons.print(string: ecode)
return PopupLines(cursorDiff: mvcnt, addedLines: srclines.count)
}
private func popLines(popupLines plines: PopupLines, console cons: CNConsole){
/* Remove lines */
var ecode: String = ""
for _ in 0..<plines.addedLines {
ecode += CNEscapeCode.eraceEntireLine.encode()
}
/* Restore line position */
ecode += CNEscapeCode.cursorBackward(plines.cursorDiff).encode()
mCurrentIndex = mLine.index(mCurrentIndex, offsetBy: -plines.cursorDiff)
/* Execute the code */
cons.print(string: ecode)
}
}
|
lgpl-2.1
|
96d9f47f2bb6ad73570bceff415262dc
| 26.878136 | 119 | 0.690023 | 3.235441 | false | false | false | false |
WestlakeAPC/game-off-2016
|
external/Fiber2D/Fiber2D/PhysicsBody.swift
|
1
|
11304
|
//
// PhysicsBody.swift
// Fiber2D
//
// Created by Andrey Volodin on 18.09.16.
// Copyright © 2016 s1ddok. All rights reserved.
//
import SwiftMath
/**
* A body affect by physics.
*
* It can attach one or more shapes.
* If you create body with createXXX, it will automatically compute mass and moment with density your specified(which is PHYSICSBODY_MATERIAL_DEFAULT by default, and the density value is 0.1f), and it based on the formula: mass = density * area.
* If you create body with createEdgeXXX, the mass and moment will be inifinity by default. And it's a static body.
* You can change mass and moment with `mass` and `moment`. And you can change the body to be dynamic or static by use `dynamic`.
*/
public class PhysicsBody: ComponentBase, Behaviour, FixedUpdatable, Pausable {
// MARK: State
/** Whether the body is at rest. */
public var isResting: Bool {
get {
return cpBodyIsSleeping(chipmunkBody) == 0
}
set {
let isResting = self.isResting
if newValue && !isResting {
cpBodySleep(chipmunkBody)
} else if !newValue && isResting {
cpBodyActivate(chipmunkBody)
}
}
}
/**
* @brief Test the body is dynamic or not.
*
* A dynamic body will effect with gravity.
*/
public var isDynamic = true {
didSet {
guard isDynamic != oldValue else {
return
}
if isDynamic {
cpBodySetType(chipmunkBody, CP_BODY_TYPE_DYNAMIC)
internalBodySetMass(chipmunkBody, cpFloat(_mass))
cpBodySetMoment(chipmunkBody, cpFloat(_moment))
} else {
cpBodySetType(chipmunkBody, CP_BODY_TYPE_KINEMATIC);
}
}
}
/** if the body is affected by the physics world's gravitational force or not. */
public var isGravityEnabled = false
/** Whether the body can be rotated. */
public var isRotationEnabled = true {
didSet {
if isRotationEnabled != oldValue {
cpBodySetMoment(chipmunkBody, isRotationEnabled ? cpFloat(_moment) : cpFloat.infinity)
}
}
}
// MARK: Properties
/** set body rotation offset, it's the rotation witch relative to node */
public var rotationOffset: Angle {
get { return _rotationOffset }
set {
if abs((_rotationOffset - newValue).degrees) > 0.5 {
let rot = rotation
_rotationOffset = newValue
rotation = rot
}
}
}
/** get the body rotation. */
public var rotation: Angle {
get {
let cpAngle = Angle(radians: Float(cpBodyGetAngle(chipmunkBody)))
if cpAngle != _recordedAngle {
_recordedAngle = cpAngle
_recordedRotation = -_recordedAngle - rotationOffset
}
return _recordedRotation
}
set {
_recordedRotation = newValue
_recordedAngle = -rotation - rotationOffset
cpBodySetAngle(chipmunkBody, cpFloat(_recordedAngle.radians))
}
}
/** get the body position. */
public var position: Point {
get {
let tt = cpBodyGetPosition(chipmunkBody)
return Point(tt) - positionOffset
}
set {
cpBodySetPosition(chipmunkBody, cpVect(newValue + positionOffset))
}
}
/** set body position offset, it's the position which is relative to the node */
public var positionOffset: Vector2f {
get {
return _positionOffset
}
set {
if _positionOffset != newValue {
let pos = self.position
_positionOffset = newValue
self.position = pos
}
}
}
internal var scale: (x: Float, y: Float) = (x: 1.0, y: 1.0) {
didSet {
for shape in shapes {
_area -= shape.area
if !_massSetByUser {
add(mass: -shape.mass)
}
if !_momentSetByUser {
add(moment: -shape.moment)
}
// shape.scale = scale
_area += shape.area
if !_massSetByUser {
add(mass: shape.mass)
}
if !_momentSetByUser {
add(moment: shape.moment)
}
}
}
}
/**
* The velocity of a body.
*/
public var velocity: Vector2f {
get { return Vector2f(cpBodyGetVelocity(chipmunkBody)) }
set {
guard isDynamic else {
print("physics warning: your can't set velocity for a static body.")
return
}
cpBodySetVelocity(chipmunkBody, cpVect(velocity))
}
}
/** The max of velocity */
public var velocityLimit: Float = Float.infinity
/**
* The angular velocity of a body.
*/
public var angularVelocity: Float {
get {
return Float(cpBodyGetAngularVelocity(chipmunkBody))
}
set {
guard isDynamic else {
print("You can't set angular velocity for a static body.")
return
}
cpBodySetAngularVelocity(chipmunkBody, cpFloat(newValue))
}
}
/** The max of angular velocity */
public var angularVelocityLimit: Float = Float.infinity
/**
* Linear damping.
*
* it is used to simulate fluid or air friction forces on the body.
* @param damping The value is 0.0f to 1.0f.
*/
public var linearDamping: Float = 0.0 {
didSet {
updateDamping()
}
}
/**
* Angular damping.
*
* It is used to simulate fluid or air friction forces on the body.
* @param damping The value is 0.0f to 1.0f.
*/
public var angularDamping: Float = 0.0 {
didSet {
updateDamping()
}
}
private func updateDamping() { _isDamping = linearDamping != 0.0 || angularDamping != 0.0 }
internal(set) public var shapes = [PhysicsShape]()
internal(set) public var joints = [PhysicsJoint]()
/** get the world body added to. */
internal(set) public weak var world: PhysicsWorld? = nil
override init() {
chipmunkBody = cpBodyNew(cpFloat(_mass), cpFloat(_moment))
super.init()
internalBodySetMass(chipmunkBody, cpFloat(_mass))
cpBodySetUserData(chipmunkBody, Unmanaged.passUnretained(self).toOpaque())
cpBodySetVelocityUpdateFunc(chipmunkBody, internalBodyUpdateVelocity)
}
public var paused: Bool = false
public func fixedUpdate(delta: Time) {
// damping compute
if (_isDamping && isDynamic && !isResting) {
chipmunkBody.pointee.v.x *= cpfclamp(1.0 - cpFloat(delta * linearDamping), 0.0, 1.0)
chipmunkBody.pointee.v.y *= cpfclamp(1.0 - cpFloat(delta * linearDamping), 0.0, 1.0)
chipmunkBody.pointee.w *= cpfclamp(1.0 - cpFloat(delta * angularDamping), 0.0, 1.0)
}
}
// MARK: Component stuff
public var enabled: Bool = true {
didSet {
if oldValue != enabled {
if enabled {
world?.addBodyOrDelay(body: self)
paused = false
} else {
world?.removeBodyOrDelay(body: self)
paused = true
}
}
}
}
public override func onAdd(to owner: Node) {
super.onAdd(to: owner)
let contentSize = owner.contentSizeInPoints
ownerCenterOffset = contentSize * 0.5
rotationOffset = owner.rotation
}
// MARK: Internal vars
/** The rigid body of chipmunk. */
internal let chipmunkBody: UnsafeMutablePointer<cpBody>
// offset between owner's center point and down left point
internal var ownerCenterOffset = Vector2f.zero
// it means body's moment is not calculated by shapes
internal var _momentSetByUser = false
internal var _momentDefault = true
internal var _moment: Float = MOMENT_DEFAULT
// it means body's mass is not calculated by shapes
internal var _massSetByUser = false
internal var _massDefault = true
internal var _mass: Float = MASS_DEFAULT
internal var _density: Float = 0.0
internal var _area: Float = 0.0
internal var _recordPos = Point.zero
internal var _offset = Vector2f.zero
internal var _isDamping = false
internal var _recordScaleX: Float = 0.0
internal var _recordScaleY: Float = 0.0
internal var _recordedRotation: Angle = 0°
// MARK: Private vars
private var _rotationOffset: Angle = 0°
private var _recordedAngle: Angle = 0°
private var _positionOffset: Vector2f = Vector2f.zero
}
extension PhysicsBody {
func addToPhysicsWorld() {
if let physicsSystem = owner?.scene?.system(for: PhysicsSystem.self) {
physicsSystem.world.add(body: self)
physicsSystem.dirty = true
}
}
/** remove the body from the world it added to */
func removeFromPhysicsWorld() {
if let physicsSystem = owner?.scene?.system(for: PhysicsSystem.self) {
physicsSystem.world.remove(body: self)
physicsSystem.dirty = true
}
}
}
public extension PhysicsBody {
/**
* Create a body contains a circle.
*
* @param radius A float number, it is the circle's radius.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
* @return An autoreleased PhysicsBody object pointer.
*/
public static func circle(radius: Float, material: PhysicsMaterial = PhysicsMaterial.default, offset: Vector2f = Vector2f.zero) -> PhysicsBody {
let circleShape = PhysicsShapeCircle(radius: radius, material: material, offset: offset)
let body = PhysicsBody()
body.add(shape: circleShape)
return body
}
/**
* Create a body contains a box shape.
*
* @param size Size contains this box's width and height.
* @param material A PhysicsMaterial object, the default value is PHYSICSSHAPE_MATERIAL_DEFAULT.
* @param offset A Vec2 object, it is the offset from the body's center of gravity in body local coordinates.
* @return An autoreleased PhysicsBody object pointer.
*/
public static func box(size: Size, material: PhysicsMaterial = PhysicsMaterial.default, offset: Vector2f = Vector2f.zero) -> PhysicsBody {
let boxShape = PhysicsShapeBox(size: size, material: material, offset: offset)
let body = PhysicsBody()
body.add(shape: boxShape)
return body
}
}
|
apache-2.0
|
fd93433ca5e5387e6f412b9f25efd592
| 31.65896 | 245 | 0.572655 | 4.521809 | false | false | false | false |
bixubot/AcquainTest
|
ChatRoom/ChatRoom/MessageController.swift
|
1
|
9891
|
//
// MessageController.swift
// ChatRoom
//
// Contains all the messages sent/received for current user from other users. Designated to be the root view when app is initiated.
//
// Created by Binwei Xu on 3/16/17.
// Copyright © 2017 Binwei Xu. All rights reserved.
//
import UIKit
import Firebase
class MessageController: UITableViewController {
let cellId = "cellId"
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Logout", style: .plain, target: self, action: #selector(handleLogout))
let newmessageimage = UIImage(named: "new_message_icon")
navigationItem.rightBarButtonItem = UIBarButtonItem(image: newmessageimage, style: .plain, target: self, action: #selector(handleNewMessage))
// self.navigationController?.navigationBar.barTintColor = UIColor.black;
// if user is not logged in, show the login page
checkIfUserIsLoggedIn()
tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
}
// to store all messages and group by users in a dictionary
var messages = [Message]()
var messagesDictionary = [String: Message]()
// acquire messages and present them
func observeUserMessages(){
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
//acquire the list of messages related to the current user
let ref = FIRDatabase.database().reference().child("user-messages").child(uid)
ref.observe(.childAdded, with: { (snapshot) in
let userId = snapshot.key
FIRDatabase.database().reference().child("user-messages").child(uid).child(userId).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key
self.fetchMessageWithMessageId(messageId: messageId)
}, withCancel: nil)
}, withCancel: nil)
}
private func fetchMessageWithMessageId(messageId: String){
let messageReference = FIRDatabase.database().reference().child("messages").child(messageId)
// get the actual message from the list
messageReference.observeSingleEvent(of: .value, with: { (snapshot2) in
if let dictionary = snapshot2.value as? [String: AnyObject]{
let message = Message()
message.setValuesForKeys(dictionary)
if let chatPartnerId = message.chatPartnerId() {
self.messagesDictionary[chatPartnerId] = message
}
self.attemptReloadTable() //so we don't constantly reload data which causes gliches
}
}, withCancel: nil)
}
private func attemptReloadTable() {
self.timer?.invalidate()
self.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(self.handleReloadTable), userInfo: nil, repeats: false)
}
var timer: Timer?
func handleReloadTable() {
self.messages = Array(self.messagesDictionary.values)
self.messages.sort(by: { (m1, m2) -> Bool in
return (m1.timestamp?.intValue)! > (m2.timestamp?.intValue)!
})
//this will crash because of background thread, so lets call this on dispatch_async main thread
//dispatch_async(dispatch_get_main_queue())
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messagesDictionary.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! UserCell
let message = messages[indexPath.row]
cell.message = message
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 66
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let message = messages[indexPath.row]
guard let chatPartnerId = message.chatPartnerId() else {
return // seek a better to catch error or missing data
}
let ref = FIRDatabase.database().reference().child("users").child(chatPartnerId)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dictionary = snapshot.value as? [String: AnyObject] else {
return // seek a better to catch error or missing data
}
let user = User()
user.id = chatPartnerId
user.setValuesForKeys(dictionary)
self.showChatControllerForUser(user: user)
}, withCancel: nil)
}
override func viewWillAppear(_ animated: Bool) {
checkIfUserIsLoggedIn()
}
// allow user to send a new message to another user
func handleNewMessage() {
let newMessageController = NewMessageController()
//this allow user to click another user in the NewMessageController by creating a reference with var messagesController so that it will come back to current MessageController.
newMessageController.messagesController = self
// allows newMessageController to have a navigation bar at the top
let navController = UINavigationController(rootViewController: newMessageController)
present(navController, animated: true, completion: nil)
}
// helper method to check if a user is logged in
func checkIfUserIsLoggedIn(){
if FIRAuth.auth()?.currentUser?.uid == nil{
perform(#selector(handleLogout), with: nil, afterDelay: 0)
} else {
fetchUserAndSetupNavBarTitle()
}
}
// fetch info of current user to setup the nav bar
func fetchUserAndSetupNavBarTitle() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
// for some reason uid = nil
return
}
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: Any] {
let user = User()
user.setValuesForKeys(dictionary)
self.setupNavBarWithUser(user: user)
}
}, withCancel: nil)
}
// setup the layout of components in tab bar and present the view
func setupNavBarWithUser(user: User) {
messages.removeAll()
messagesDictionary.removeAll()
tableView.reloadData()
observeUserMessages()
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: 100, height: 40)
titleView.backgroundColor = UIColor.clear
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
containerView.centerXAnchor.constraint(equalTo: titleView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
if let profileImageUrl = user.profileImageUrl {
profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
}
containerView.addSubview(profileImageView)
//ios 9 constrant anchors: need x,y,width,height anchors
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
let nameLabel = UILabel()
titleView.addSubview(nameLabel)
containerView.addSubview(nameLabel)
nameLabel.text = user.name
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
self.navigationItem.titleView = titleView
}
// present the chat log view
func showChatControllerForUser(user: User){
let chatLogController = ChatLogController(collectionViewLayout: UICollectionViewFlowLayout())
chatLogController.user = user
navigationController?.pushViewController(chatLogController, animated: true)
}
// helper that handle the logout
func handleLogout() {
// when logout bottom is clicked, sign out the current account
do {
try FIRAuth.auth()?.signOut()
} catch let logoutError{
print(logoutError)
}
let loginController = LoginController()
loginController.messagesController = self //allow nav bar title update
present(loginController, animated:true, completion: nil)
}
}
|
mit
|
208f380c6868e7ae21a5d629379bf46f
| 39.532787 | 183 | 0.649949 | 5.366251 | false | false | false | false |
visualitysoftware/swift-sdk
|
CloudBoost/CloudQuery.swift
|
1
|
39824
|
//
// CloudQuery.swift
// CloudBoost
//
// Created by Randhir Singh on 30/03/16.
// Copyright © 2016 Randhir Singh. All rights reserved.
//
import Foundation
public class CloudQuery{
var tableName: String?
private var query = NSMutableDictionary()
private var select = NSMutableDictionary()
private var sort = NSMutableDictionary()
private let body = NSMutableDictionary()
private var include = [String]()
private var includeList = [String]()
private var _include = [String]()
private var _includeList = [String]()
var skip = 0
var limit = 10
public var objectClass: CloudObject.Type? = nil
// constructor
public init(tableName: String,
objectClass: CloudObject.Type? = nil) {
self.tableName = tableName
self.objectClass = objectClass
query["$include"] = _include
query["$includeList"] = _includeList
}
// getter and setters for limit
public func getLimit() -> Int {
return limit
}
public func setLimit(limit: Int) {
self.limit = limit
}
// getter and setters for skip
public func getSkip() -> Int {
return skip
}
public func setSkip(skip: Int) {
self.skip = skip
}
// getter and setters for tableName
public func getTableName() -> String?{
return tableName
}
public func setTableName(tableName: String) {
self.tableName = tableName
}
// Getter and setters for select statements
public func getSelect() -> NSMutableDictionary {
return select
}
public func setSelect(select: NSMutableDictionary){
self.select = select
}
// Getter and setter for includeList and include
public func getIncludeList() -> [String] {
return includeList
}
public func setIncludeList(includeList: [String]){
self.includeList = includeList
}
public func getInclude() -> [String] {
return include
}
public func setInclude(include: [String]){
self.include = include
}
// getter and setter for Sort
public func getSort() -> NSMutableDictionary {
return sort
}
public func setSort(sort: NSMutableDictionary){
self.sort = sort
}
// For $includeList and $include
public func get_includeList() -> [String] {
return _includeList
}
public func set_includeList(_includeList: [String]){
self._includeList = _includeList
}
public func get_include() -> [String] {
return _include
}
public func set_include(_include: [String]){
self._include = _include
}
// getter and setter for query
public func getQuery() -> NSMutableDictionary {
return query
}
public func setQuery(query: NSMutableDictionary){
self.query = query
}
// MARK: query elements
public func selectColumn(column: String){
if self.select.count == 0 {
select["_id"] = 1
select["createdAt"] = 1
select["updatedAt"] = 1
select["ACL"] = 1
select["_type"] = 1
select["_tableName"] = 1
}
select[column] = 1
}
public func doNotSelectColumn(column: String){
select[column] = 0
}
/**
* CloudQuery Search, caseSensitive and diacriticSensitive defaults to false
*
* @param search
* @param language
* @param caseSensitive
* @param diacriticSensitive
*/
public func search(search: String, language: String? = "en", caseSensitive: Bool? = nil, diacriticSensitive: Bool? = nil) {
let textFields = NSMutableDictionary()
textFields["$search"] = search
textFields["$language"] = language
textFields["$caseSensitive"] = caseSensitive
textFields["$diacriticSensitive"] = diacriticSensitive
self.query["$text"] = textFields
}
/**
* CloudQuery Or
*
*
* @param object1
* @param object2
* @throws CLoubBoostError
*/
public func or(object1: CloudQuery, object2: CloudQuery) throws {
guard let tableName1 = object1.getTableName() else{
throw CloudBoostError.InvalidArgument
}
guard let tableName2 = object2.getTableName() else {
throw CloudBoostError.InvalidArgument
}
if(tableName1 != tableName2){
throw CloudBoostError.InvalidArgument
}
var array = [NSDictionary]()
array.append(object1.getQuery())
array.append(object2.getQuery())
self.query["$or"] = array
}
/**
*
* CloudQuery EqualTo
*
*
* @param columnName
* @param obj
* @return CloudQuery good for chaining requests
* @throws CLoubBoostError
*/
public func equalTo(columnName: String, obj: AnyObject?) throws -> CloudQuery {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
var obj = obj
if let ob = obj as? CloudObject {
_columnName = _columnName + "._id"
if let id = ob.getId() {
obj = id
}else{
throw CloudBoostError.InvalidArgument
}
}
if let ob = obj as? CloudRole {
_columnName = _columnName + "._id"
if let id = ob.getId() {
obj = id
}else{
throw CloudBoostError.InvalidArgument
}
}
query[_columnName] = obj
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
return self
}
/**
*
* CloudQuery Not Equal To
*
* @param columnName
* @param obj
* @return CloudQuery
* @throws CLoubBoostError
*/
public func notEqualTo(columnName: String, obj: AnyObject) throws {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
var obj = obj
if let ob = obj as? CloudObject {
_columnName = _columnName + "._id"
if let id = ob.getId() {
obj = id
}else{
throw CloudBoostError.InvalidArgument
}
}
if let ob = obj as? CloudRole {
_columnName = _columnName + "._id"
if let id = ob.getId() {
obj = id
}else{
throw CloudBoostError.InvalidArgument
}
}
query[_columnName] = [ "$ne" : obj ]
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
}
public func lessThan(columnName: String, obj: AnyObject) throws {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$lt":obj]
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
}
public func lessThanEqualTo(columnName: String, obj: AnyObject) throws {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$lte":obj]
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
}
public func greaterThan(columnName: String, obj: AnyObject) throws {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$gt":obj]
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
}
public func greaterThanEqualTo(columnName: String, obj: AnyObject) throws {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$gte":obj]
guard let _ = try query.getJSON() else{
throw CloudBoostError.InvalidArgument
}
}
public func substring(columnName: String, subStr: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$regex": ".*" + subStr + ".*"]
}
public func startsWith(columnName: String, str: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$regex": "^" + str]
}
public func containsAll(columnName: String, obj: [String]) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$all":obj]
}
public func regex(columnName: String, exp: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$regex":exp]
}
/**
*
* CloudQuery ContainedIn
*
* @param columnName
* @param data
* @return CloudQuery
* @throws CloudBoostExcetion
*/
public func containedIn(columnName: String, data: [AnyObject]) throws -> CloudQuery{
var _columnName = columnName
if(columnName == "id" || columnName == "expires"){
_columnName = "_" + columnName
}
var column = NSMutableDictionary()
if let col = self.query[_columnName] as? NSMutableDictionary {
column = col
}
var _in_ = [String]()
var _nin_ = [String]()
if data as? [String] != nil || data as? [CloudObject] != nil || data as? [Int] != nil || data as? [Double] != nil {
var object = [CloudObject]()
query["$include"] = _include
query["$includeList"] = _includeList
if column["$in"] == nil {
column["$in"] = [String]()
}
if column["$nin"] == nil {
column["$nin"] = [String]()
}
_in_ = column["$in"] as! [String]
_nin_ = column["$nin"] as! [String]
if data as? [CloudObject] != nil {
_columnName = _columnName == "_id" ? _columnName : _columnName + "._id"
var dataz = [String]()
for (index, el) in data.enumerate() {
object.insert(el as! CloudObject, atIndex: index)
if let id = object[index].getId() {
dataz.append(id)
}else{
throw CloudBoostError.InvalidArgument
}
}
for (index, dat) in dataz.enumerate() {
if _in_.indexOf(dat) == nil {
_in_.append(dat)
}
if _nin_.indexOf(dat) != nil {
_nin_.removeAtIndex(index)
}
}
} else {
for (index, dat) in data.enumerate() {
if _in_.indexOf(dat.description) == nil {
_in_.append(dat.description)
}
if _nin_.indexOf(dat.description) != nil {
_nin_.removeAtIndex(index)
}
}
}
column["$in"] = _in_
column["$nin"] = _nin_
self.query[_columnName] = column
} else {
throw CloudBoostError.InvalidArgument
}
return self
}
/**
*
* CloudQuery notContainedIn
*
* @param columnName
* @param data
* @return CloudQuery
* @throws CloudBoostExcetion
*/
public func notContainedIn(columnName: String, data: [AnyObject]) throws -> CloudQuery{
var _columnName = columnName
if(columnName == "id" || columnName == "expires"){
_columnName = "_" + columnName
}
var column = NSMutableDictionary()
if let col = self.query[_columnName] as? NSMutableDictionary {
column = col
}
var _in_ = [String]()
var _nin_ = [String]()
if data as? [String] != nil || data as? [CloudObject] != nil || data as? [Int] != nil || data as? [Double] != nil {
var object = [CloudObject]()
query["$include"] = _include
query["$includeList"] = _includeList
if column["$in"] == nil {
column["$in"] = [String]()
}
if column["$nin"] == nil {
column["$nin"] = [String]()
}
_in_ = column["$in"] as! [String]
_nin_ = column["$nin"] as! [String]
if data as? [CloudObject] != nil {
_columnName = _columnName + "._id"
var dataz = [String]()
for (index, el) in data.enumerate() {
object.insert(el as! CloudObject, atIndex: index)
if let id = object[index].getId() {
dataz.append(id)
}else{
throw CloudBoostError.InvalidArgument
}
}
for (index, dat) in dataz.enumerate() {
if _nin_.indexOf(dat) == nil {
_nin_.append(dat)
}
if _in_.indexOf(dat) != nil {
_in_.removeAtIndex(index)
}
}
} else {
for (index, dat) in data.enumerate() {
if _nin_.indexOf(dat.description) == nil {
_nin_.append(dat.description)
}
if _in_.indexOf(dat.description) != nil {
_in_.removeAtIndex(index)
}
}
}
column["$in"] = _in_
column["$nin"] = _nin_
self.query[_columnName] = column
} else {
throw CloudBoostError.InvalidArgument
}
return self
}
public func notContainedIn(columnName: String, obj: [String]) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$nin":obj]
}
/**
*
* CloudQuery Exists
*
* @param columnName
*/
public func exists(columnName: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$exists":true]
}
/**
*
* CloudQuery Does Not Exists
*
* @param columnName
*/
public func doesNotExists(columnName: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
query[_columnName] = ["$exists":false]
}
/**
*
* CloudQuery Include List
*
* @param columnName
*/
public func includeList(columnName: String){
var _columnName = columnName
if columnName == "id" || columnName == "expires" {
_columnName = "_" + columnName
}
self.includeList.append(_columnName)
query["$includeList"] = self.includeList
}
/**
*
* CloudQuery Include
*
* @param columnName
*/
public func include(columnName: String){
var _columnName = columnName
if columnName == "id" || columnName == "expires" {
_columnName = "_" + columnName
}
self.include.append(_columnName)
query["$include"] = self.include
}
public func sortAscendingBy(columnName: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
sort[_columnName] = 1
}
public func sortDescendingBy(columnName: String) {
var _columnName = columnName
if(columnName == "id"){
_columnName = "_id"
}
sort[_columnName] = 1
}
public func near(columnName: String, geoPoint: CloudGeoPoint, maxDistance: Double, minDistance: Double){
query[columnName] = nil
query[columnName] = [ "$near" : [ "$geometry": [ "coordinates" : geoPoint.getCoordinates(), "type" : "Point"],
"$maxDistance" : maxDistance,
"$minDistance" : minDistance
]
]
}
// query GeoPoint within an arrangement of Geo points
public func geoWithin(columnName: String, geoPoints: [CloudGeoPoint]){
query[columnName] = nil
var coordinateList = [[Double]]()
for geoPoint in geoPoints {
coordinateList.append(geoPoint.getCoordinates())
}
coordinateList.append(geoPoints[0].getCoordinates())
query[columnName] = [ "$geoWithin" : [ "$geometry": [ "coordinates" : [coordinateList], "type" : "Polygon"] ] ]
}
// within radius of a geo point
public func geoWithin(columnName: String, geoPoint: CloudGeoPoint, radius: Double) {
query[columnName] = nil
query[columnName] = [ "$geoWithin" : [ "$centerSphere": [ geoPoint.getCoordinates(), radius/3963.2] ] ]
}
public func find(callback: (response: CloudBoostResponse)->Void) {
let params = NSMutableDictionary()
params["query"] = query
params["select"] = select
params["limit"] = limit
params["skip"] = skip
params["sort"] = sort
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + tableName! + "/find"
CloudCommunications._request("POST",
url: NSURL(string: url)!,
params: params, callback: { response in
if response.status == 200 {
if let documents = response.object as? [NSDictionary] {
var objectsArray = [CloudObject]()
for document in documents {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
objectsArray.append(object)
}
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = objectsArray
theResponse.status = response.status
callback(response: theResponse)
} else if let document = response.object as? NSMutableDictionary {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = object
theResponse.status = response.status
callback(response: theResponse)
} else {
callback(response: response)
}
} else {
callback(response: response)
}
})
}
public func findOne(callback: (response: CloudBoostResponse)->Void) throws {
let params = NSMutableDictionary()
params["query"] = query
params["select"] = select
params["skip"] = skip
params["sort"] = sort
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + tableName! + "/findOne"
CloudCommunications._request("POST",
url: NSURL(string: url)!,
params: params, callback: { response in
if response.status == 200 {
if let documents = response.object as? [NSMutableDictionary] {
var objectsArray = [CloudObject]()
for document in documents {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
objectsArray.append(object)
}
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = objectsArray
theResponse.status = response.status
callback(response: theResponse)
} else if let document = response.object as? NSMutableDictionary {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = object
theResponse.status = response.status
callback(response: theResponse)
} else {
callback(response: response)
}
} else {
callback(response: response)
}
})
}
public func findById(id: String, callback: (response: CloudBoostResponse) -> Void ){
print("equatinf \(id)")
try! self.equalTo("id", obj: id)
let params = NSMutableDictionary()
params["query"] = query
params["select"] = select
params["limit"] = 1
params["skip"] = 0
params["sort"] = sort
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + tableName! + "/find"
CloudCommunications._request("POST",
url: NSURL(string: url)!,
params: params, callback: { response in
if response.status == 200 {
if let documents = response.object as? [NSMutableDictionary] {
var objectsArray = [CloudObject]()
for document in documents {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
objectsArray.append(object)
}
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = objectsArray
theResponse.status = response.status
callback(response: theResponse)
} else if let document = response.object as? NSMutableDictionary {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = object
theResponse.status = response.status
callback(response: theResponse)
} else {
callback(response: response)
}
} else {
callback(response: response)
}
})
}
public func distinct(key: String, callback: (response: CloudBoostResponse) -> Void ){
var _key = key
if(key == "id") {
_key = "_id"
}
let params = NSMutableDictionary()
params["onKey"] = _key
params["query"] = query
params["select"] = select
params["limit"] = limit
params["skip"] = 0
params["sort"] = sort
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + tableName! + "/distinct"
CloudCommunications._request("POST",
url: NSURL(string: url)!,
params: params, callback: { response in
if response.status == 200 {
if let documents = response.object as? [NSMutableDictionary] {
var objectsArray = [CloudObject]()
for document in documents {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
objectsArray.append(object)
}
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = objectsArray
theResponse.status = response.status
callback(response: theResponse)
} else if let document = response.object as? NSMutableDictionary {
let object = CloudObject.cloudObjectFromDocumentDictionary(document, documentType: self.objectClass)
let theResponse = CloudBoostResponse()
theResponse.success = response.success
theResponse.object = object
theResponse.status = response.status
callback(response: theResponse)
} else {
callback(response: response)
}
} else {
callback(response: response)
}
})
}
public func count( callbak: (response: CloudBoostResponse) -> Void ){
let params = NSMutableDictionary()
params["query"] = query
params["limit"] = self.limit
params["skip"] = 0
params["key"] = CloudApp.getAppKey()
var url = CloudApp.getApiUrl() + "/data/" + CloudApp.getAppId()!
url = url + "/" + tableName! + "/count"
CloudCommunications._request("POST", url: NSURL(string: url)!, params: params, callback: {
(response: CloudBoostResponse) in
callbak(response: response)
})
}
public func paginate(_pageNo: Int?, _totalItemsInPage: Int?, callback: (objectsList: [NSDictionary]?, count: Int?, totalPages: Int?)->Void) {
var pageNo: Int
var totalItemsInPage: Int
if let pno = _pageNo {
pageNo = pno
}else{
pageNo = 1
}
if let total = _totalItemsInPage {
totalItemsInPage = total
}else{
totalItemsInPage = limit
}
if pageNo > 0 && totalItemsInPage > 0 {
let skip = pageNo*totalItemsInPage - totalItemsInPage
self.setSkip(skip)
self.setLimit(totalItemsInPage)
} else if totalItemsInPage > 0 {
self.setLimit(totalItemsInPage)
}
self.find({
response in
if response.success {
self.setLimit(99999999)
self.setSkip(0)
let list = response.object as? [NSDictionary]
self.count({
response in
if response.success {
if let count = response.object as? Int {
callback(objectsList: list, count: count, totalPages: Int(ceil(Double(count)/Double(self.limit))) )
}
}else {
callback(objectsList: list, count: nil, totalPages: nil)
}
})
} else {
callback(objectsList: nil,count: nil,totalPages: nil)
}
})
}
public static func validateQuery(co: CloudObject, query: NSMutableDictionary) -> Bool {
for (key, value) in query {
if let key = key as? String{
if key == "$include" || key == "$includeList" {
continue
}
if value as? NSMutableDictionary != nil || value as? [NSMutableDictionary] != nil {
// checking OR
if key == "$or" {
if let arr = query[key] as? [NSMutableDictionary] {
var valid = false
if arr.count > 0 {
for (_,val) in arr.enumerate() {
if(CloudQuery.validateQuery(co, query: val)){
valid = true
break
}
}
if valid == false {
return false
}
}
}else{
return false
}
}
// here 'key' will usually contain the column name and value will be query
if let dictValue = value as? [String:AnyObject] {
// iterating over each query, $ne, $eq, etc
for (subKey, subValue) in dictValue {
//not equalTo query
if subKey == "$ne" {
if co.get(key) === subValue {
return false
}
}
//greater than
if subKey == "$gt" {
if (co.get(key)as?Int) <= (subValue as? Int) {
return false
}
}
//less than
if subKey == "$lt" {
if (co.get(key)as?Int) >= (subValue as? Int) {
return false
}
}
//greater than and equalTo.
if subKey == "$gte" {
if (co.get(key)as?Int) < (subValue as? Int) {
return false
}
}
//less than and equalTo.
if subKey == "$lte" {
if (co.get(key)as?Int) > (subValue as? Int) {
return false
}
}
//exists
if subKey == "$exists" {
if let _ = co.get(key) {
// do nothing since the object exists
}else{
return false
}
}
//startsWith.
if subKey == "$regex" {
if let re = subValue as? String {
let reg = Regex(re)
if let toMatch = co.get(key) as? String{
return reg.test(toMatch)
}
}
return false
}
//containedIn
if subKey == "$in" {
if let arr = value[subKey] as? [AnyObject]{
var value: AnyObject?
if key.containsString(".") && co.get(key) == nil {
if co.get(key.componentsSeparatedByString(".")[0]) != nil {
value = co.get(key.componentsSeparatedByString(".")[0])
}
} else if co.get(key) != nil {
value = co.get(key)
}
for el in arr {
// return true on first occurance of 'value'
if value === el {
return true
}
}
}else{
return false
}
return false
}
//notContainedIn
if subKey == "$nin" {
if let arr = value[subKey] as? [AnyObject]{
var value: AnyObject?
if key.containsString(".") && co.get(key) == nil {
if co.get(key.componentsSeparatedByString(".")[0]) != nil {
value = co.get(key.componentsSeparatedByString(".")[0])
}
} else if co.get(key) != nil {
value = co.get(key)
}
for el in arr {
// return true on first occurance of 'value'
if value === el {
return false
}
}
}else{
return true
}
return true
}
if subKey == "$all" {
}
}
}
} else {
// when the query sub-object corresponding to 'key' is not a JSONObect/JSONArray
}
} // else dosent matter, if the key is not in a string format, then discard that query
}
return true
}
}
|
mit
|
01917e331ef6c979b4756e15ba5bd407
| 36.287453 | 152 | 0.402958 | 6.104077 | false | false | false | false |
jingwei-huang1/LayoutKit
|
LayoutKitSampleApp/MenuViewController.swift
|
3
|
2138
|
// Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/// The main menu for the sample app.
class MenuViewController: UITableViewController {
private let reuseIdentifier = " "
private let viewControllers: [UIViewController.Type] = [
BenchmarkViewController.self,
FeedScrollViewController.self,
FeedCollectionViewController.self,
FeedTableViewController.self,
StackViewController.self,
NestedCollectionViewController.self,
ForegroundMiniProfileViewController.self,
BackgroundMiniProfileViewController.self,
BatchUpdatesCollectionViewController.self,
BatchUpdatesTableViewController.self
]
convenience init() {
self.init(style: .grouped)
title = "Menu"
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewControllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = String(describing: viewControllers[indexPath.row])
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewController = viewControllers[indexPath.row].init()
viewController.title = String(describing: viewController)
navigationController?.pushViewController(viewController, animated: true)
}
}
|
apache-2.0
|
3a21357cb2c4235c3269ba3ad7d40121
| 38.592593 | 131 | 0.727315 | 5.426396 | false | false | false | false |
snailjj/iOSDemos
|
SnailSwiftDemos/SnailSwiftDemos/ThirdFrameworks/ViewControllers/MJRefreshViewController.swift
|
2
|
2031
|
//
// MJRefreshViewController.swift
// SnailSwiftDemos
//
// Created by Jian Wu on 2016/12/12.
// Copyright © 2016年 Snail. All rights reserved.
//
import UIKit
class MJRefreshViewController: CustomViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var aTableView: CustomTableView!
var count = 10
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
initTableView()
}
func initTableView() {
leftBtn.isHidden = false
navTitleLabel.text = "MJRefresh"
aTableView.register(UITableViewCell.self, forCellReuseIdentifier: "RefreshCell")
aTableView.isCanPullRefresh = true
aTableView.isCanUpPullRefresh = true
aTableView.pullRefresh = {
self.count = 10
self.aTableView.endPullRefresh = true
}
aTableView.upPullRefresh = {
self.count += 10
self.aTableView.endUpPullRefresh = true
}
}
//MARK: - UITableViewDelegate methods
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RefreshCell", for: indexPath)
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
6fbdd43d3089f176b0d67f099ae7d2c0
| 28.823529 | 106 | 0.651381 | 5.28125 | false | false | false | false |
wfleming/pico-block
|
pblockLib/DebugLog.swift
|
1
|
2661
|
//
// GroupLog.swift
// pblock
//
// Created by Will Fleming on 7/10/15.
// Copyright © 2015 PBlock. All rights reserved.
//
import Foundation
/**
Adapted from https://gist.github.com/Abizern/a81f31a75e1ad98ff80d
Prints the filename, function name, line number and textual representation of `object` and a newline character into
the standard output if the build setting for "Other Swift Flags" defines `-D DEBUG`.
Only the first parameter needs to be passed to this function.
The textual representation is obtained from the `message` using its protocol conformances, in the following
order of preference: `Streamable`, `Printable`, `DebugPrintable`. Do not overload this function for your type.
Instead, adopt one of the protocols mentioned above.
:param: message The object whose textual representation will be printed. If this is an expression, it is lazily evaluated.
:param: file The name of the file, defaults to the current file without the ".swift" extension.
:param: function The name of the function, defaults to the function within which the call is made.
:param: line The line number, defaults to the line number within the file that the call is made.
*/
func dlog<T>(@autoclosure message: () -> T, _ file: NSString = __FILE__, _ function: String = __FUNCTION__, _ line: Int = __LINE__) {
#if DEBUG
let file = (file.lastPathComponent as NSString).stringByDeletingPathExtension
print("\(file).\(function)[\(line)]: \(message())\n")
#endif
}
/**
Log a message to a file shared by the app group.
*/
func logToGroupLogFile(message: String) {
#if DEBUG
let fm = NSFileManager.defaultManager()
let appGroup = AppEnv.sharedInstance.appGroup
let dirURL = fm.containerURLForSecurityApplicationGroupIdentifier(appGroup)
if nil == dirURL {
print("Could not get group directory: cannot log message \"\(message)\"\n")
} else {
let logURL = dirURL!.URLByAppendingPathComponent("events.log")
if !fm.fileExistsAtPath(logURL.path!) {
"".dataUsingEncoding(NSUTF8StringEncoding)?.writeToURL(logURL, atomically: true)
if !fm.fileExistsAtPath(logURL.path!) {
print("Failed to create logfile in group directory\n")
return
}
}
do {
let fh = try NSFileHandle(forWritingToURL: logURL)
defer {
fh.closeFile()
}
fh.seekToEndOfFile()
let logLine = "\(NSDate().description) $\(message)\n"
fh.writeData(logLine.dataUsingEncoding(NSUTF8StringEncoding)!)
} catch {
print("Error encountered trying to write message \"\(message)\"to group log: \(error)\n")
}
}
#endif
}
|
mit
|
0c0907d637a1b4452e6efcc246f517c7
| 38.132353 | 133 | 0.693985 | 4.276527 | false | false | false | false |
kaishin/gifu
|
Sources/Gifu/Helpers/ImageSourceHelpers.swift
|
1
|
3379
|
#if os(iOS) || os(tvOS)
import ImageIO
import MobileCoreServices
import UIKit
typealias GIFProperties = [String: Double]
/// Most GIFs run between 15 and 24 Frames per second.
///
/// If a GIF does not have (frame-)durations stored in its metadata,
/// this default framerate is used to calculate the GIFs duration.
private let defaultFrameRate: Double = 15.0
/// Default Fallback Frame-Duration based on `defaultFrameRate`
private let defaultFrameDuration: Double = 1 / defaultFrameRate
/// Threshold used in `capDuration` for a FrameDuration
private let capDurationThreshold: Double = 0.02 - Double.ulpOfOne
/// Frameduration used, if a frame-duration is below `capDurationThreshold`
private let minFrameDuration: Double = 0.1
/// Retruns the duration of a frame at a specific index using an image source (an `CGImageSource` instance).
///
/// - returns: A frame duration.
func CGImageFrameDuration(with imageSource: CGImageSource, atIndex index: Int) -> TimeInterval {
guard imageSource.isAnimatedGIF else { return 0.0 }
// Return nil, if the properties do not store a FrameDuration or FrameDuration <= 0
guard let GIFProperties = imageSource.properties(at: index),
let duration = frameDuration(with: GIFProperties),
duration > 0 else { return defaultFrameDuration }
return capDuration(with: duration)
}
/// Ensures that a duration is never smaller than a threshold value.
///
/// - returns: A capped frame duration.
func capDuration(with duration: Double) -> Double {
let cappedDuration = duration < capDurationThreshold ? 0.1 : duration
return cappedDuration
}
/// Returns a frame duration from a `GIFProperties` dictionary.
///
/// - returns: A frame duration.
func frameDuration(with properties: GIFProperties) -> Double? {
guard let unclampedDelayTime = properties[String(kCGImagePropertyGIFUnclampedDelayTime)],
let delayTime = properties[String(kCGImagePropertyGIFDelayTime)]
else { return nil }
return duration(withUnclampedTime: unclampedDelayTime, andClampedTime: delayTime)
}
/// Calculates frame duration based on both clamped and unclamped times.
///
/// - returns: A frame duration.
func duration(withUnclampedTime unclampedDelayTime: Double, andClampedTime delayTime: Double) -> Double? {
let delayArray = [unclampedDelayTime, delayTime]
return delayArray.filter({ $0 >= 0 }).first
}
/// An extension of `CGImageSourceRef` that adds GIF introspection and easier property retrieval.
extension CGImageSource {
/// Returns whether the image source contains an animated GIF.
///
/// - returns: A boolean value that is `true` if the image source contains animated GIF data.
var isAnimatedGIF: Bool {
let isTypeGIF = UTTypeConformsTo(CGImageSourceGetType(self) ?? "" as CFString, kUTTypeGIF)
let imageCount = CGImageSourceGetCount(self)
return isTypeGIF != false && imageCount > 1
}
/// Returns the GIF properties at a specific index.
///
/// - parameter index: The index of the GIF properties to retrieve.
/// - returns: A dictionary containing the GIF properties at the passed in index.
func properties(at index: Int) -> GIFProperties? {
guard let imageProperties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as? [String: AnyObject] else { return nil }
return imageProperties[String(kCGImagePropertyGIFDictionary)] as? GIFProperties
}
}
#endif
|
mit
|
7d69c100a0dad96f0c97af1698ef0528
| 38.752941 | 128 | 0.747263 | 4.505333 | false | false | false | false |
gregomni/swift
|
validation-test/compiler_crashers_2_fixed/0173-circular-generic-type-alias-deserialization.swift
|
3
|
662
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -emit-module-path %t/foo.swiftmodule -Xfrontend -debug-generic-signatures -Xfrontend -requirement-machine-protocol-signatures=on %s 2>&1 | %FileCheck %s
public protocol P { }
public struct X<T: P> {
public init() { }
}
// CHECK-LABEL: main.(file).Q@
// CHECK-NEXT: Requirement signature: <Self where Self.[Q]A : P, Self.[Q]C : Collection, Self.[Q]C.[Sequence]Element == X<Self.[Q]A>>
public protocol Q {
associatedtype A: P
associatedtype C: Collection where C.Element == MyX
typealias MyX = X<A>
}
public struct Y: P { }
extension X: Q {
public typealias A = Y
public typealias C = [MyX]
}
|
apache-2.0
|
bf9fc4febf34229147155099311339de
| 32.1 | 180 | 0.682779 | 3.137441 | false | false | false | false |
mshhmzh/firefox-ios
|
Client/Frontend/Accessors/NewTabAccessors.swift
|
4
|
2512
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
/// Accessors to find what a new tab should do when created without a URL.
struct NewTabAccessors {
static let PrefKey = PrefsKeys.KeyNewTab
static let Default = NewTabPage.TopSites
static func getNewTabPage(prefs: Prefs) -> NewTabPage {
guard let raw = prefs.stringForKey(PrefKey) else {
return Default
}
let option = NewTabPage(rawValue: raw) ?? Default
// Check if the user has chosen to open a homepage, but no homepage is set,
// then use the default.
if option == .HomePage && HomePageAccessors.getHomePage(prefs) == nil {
return Default
}
return option
}
static func getNewTabPage(state: AppState) -> NewTabPage {
return getNewTabPage(Accessors.getPrefs(state))
}
}
/// Enum to encode what should happen when the user opens a new tab without a URL.
enum NewTabPage: String {
case BlankPage = "Blank"
case HomePage = "HomePage"
case TopSites = "TopSites"
case Bookmarks = "Bookmarks"
case History = "History"
case ReadingList = "ReadingList"
var settingTitle: String {
switch self {
case .BlankPage:
return Strings.SettingsNewTabBlankPage
case .HomePage:
return Strings.SettingsNewTabHomePage
case .TopSites:
return Strings.SettingsNewTabTopSites
case .Bookmarks:
return Strings.SettingsNewTabBookmarks
case .History:
return Strings.SettingsNewTabHistory
case .ReadingList:
return Strings.SettingsNewTabReadingList
}
}
var homePanelType: HomePanelType? {
switch self {
case .TopSites:
return HomePanelType.TopSites
case .Bookmarks:
return HomePanelType.Bookmarks
case .History:
return HomePanelType.History
case .ReadingList:
return HomePanelType.ReadingList
default:
return nil
}
}
var url: NSURL? {
guard let homePanel = self.homePanelType else {
return nil
}
return homePanel.localhostURL
}
static let allValues = [BlankPage, TopSites, Bookmarks, History, ReadingList, HomePage]
}
|
mpl-2.0
|
f0ada651332006cd79333bcf860c600b
| 30.024691 | 91 | 0.637341 | 4.954635 | false | false | false | false |
seandavidmcgee/HumanKontactBeta
|
src/Pods/LiquidLoader/Pod/Classes/LiquidLoadEffect.swift
|
1
|
2794
|
//
// LiquidLoader.swift
// LiquidLoading
//
// Created by Takuma Yoshida on 2015/08/17.
// Copyright (c) 2015年 yoavlt. All rights reserved.
//
import Foundation
import UIKit
class LiquidLoadEffect : NSObject {
var circleScale: CGFloat = 1.17
var moveScale: CGFloat = 0.80
var color = UIColor.whiteColor()
var engine: SimpleCircleLiquidEngine?
var moveCircle: LiquittableCircle?
var shadowCircle: LiquittableCircle?
weak var loader: LiquidLoader!
var isGrow = false {
didSet {
grow(self.isGrow)
}
}
/* the following properties is initialized when frame is assigned */
var circles: [LiquittableCircle]!
var circleRadius: CGFloat!
var key: CGFloat = 0.0 {
didSet {
updateKeyframe(self.key)
}
}
init(loader: LiquidLoader, color: UIColor) {
self.circleRadius = loader.frame.width * 0.05
self.loader = loader
self.color = color
super.init()
setup()
}
func resize() {
// abstract
}
func setup() {
willSetup()
engine?.color = color
self.circles = setupShape()
for circle in circles {
loader?.addSubview(circle)
}
if moveCircle != nil {
loader?.addSubview(moveCircle!)
}
resize()
_ = NSTimer.scheduledTimerWithTimeInterval(0.02, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func updateKeyframe(key: CGFloat) {
self.engine?.clear()
let movePos = movePosition(key)
// move subviews positions
moveCircle?.center = movePos
shadowCircle?.center = movePos
circles.each { circle in
if self.moveCircle != nil {
self.engine?.push(self.moveCircle!, other: circle)
}
}
resize()
// draw and show grow
if let parent = loader {
self.engine?.draw(parent)
}
if let shadow = shadowCircle {
loader?.bringSubviewToFront(shadow)
}
}
func setupShape() -> [LiquittableCircle] {
return [] // abstract
}
func movePosition(key: CGFloat) -> CGPoint {
return CGPointZero // abstract
}
func update() {
// abstract
}
func willSetup() {
// abstract
}
func grow(isGrow: Bool) {
if isGrow {
shadowCircle = LiquittableCircle(center: self.moveCircle!.center, radius: self.moveCircle!.radius * 1.0, color: self.color)
shadowCircle?.isGrow = isGrow
loader?.addSubview(shadowCircle!)
} else {
shadowCircle?.removeFromSuperview()
}
}
}
|
mit
|
4a6db46e5c9910aba29982159e79f47a
| 22.470588 | 135 | 0.562679 | 4.562092 | false | false | false | false |
PiXeL16/BudgetShare
|
BudgetShareTests/Modules/SignUp/Presenter/SignUpPresenterSpec.swift
|
1
|
2092
|
import Nimble
import Quick
@testable import BudgetShare
class SignUpPresenterProviderSpec: QuickSpec {
override func spec() {
describe("The signup presenter provider") {
var subject: SignUpPresenterProvider!
var view: MockSignUpView!
var interactor: MockSignUpInteractor!
var wireframe: MockSignUpWireframe!
beforeEach {
view = MockSignUpView()
interactor = MockSignUpInteractor()
wireframe = MockSignUpWireframe(root: nil, view: view)
subject = SignUpPresenterProvider()
subject.view = view
subject.interactor = interactor
interactor.output = subject
subject.wireframe = wireframe
}
it("Inits with correct values") {
expect(subject.view).toNot(beNil())
expect(subject.interactor).toNot(beNil())
expect(subject.wireframe).toNot(beNil())
}
it("SignUp succeed") {
interactor.shouldSuccedWhenSigningUp = true
subject.singUp(email: "[email protected]", password: "test", name: "test")
expect(interactor.signUpCalled).to(beTrue())
expect(view.didSignUpSuccesfullyCalled).to(beTrue())
expect(wireframe.pushBudgetDetailCalled).to(beTrue())
}
it("SignUp errors") {
interactor.shouldSuccedWhenSigningUp = false
subject.singUp(email: "[email protected]", password: "test", name: "test")
expect(view.didSignUpSuccesfullyCalled).to(beFalse())
expect(view.didReceiveErrorCalled).to(beTrue())
}
it("Shows errors") {
subject.presentError(message: "Test")
expect(wireframe.showErrorCalled).to(beTrue())
}
}
}
}
|
mit
|
85021959b99ecdebcaf0d9c63857a6f2
| 35.068966 | 86 | 0.521033 | 5.731507 | false | true | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/CaptureSession/CaptureSessionInterruptionObserver.swift
|
1
|
3816
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AVFoundation
class CaptureSessionInterruptionObserver {
enum CameraAvailability {
case available
case blockedByBrightnessSensor
case permissionsDenied
case captureInterrupted
}
// MARK: - Properties
static let shared = CaptureSessionInterruptionObserver()
/// Should be set to true when a capture session interruption notification is received, so that
/// camera use will not be allowed.
///
/// - Note: Because this value depends on receiving AVCaptureSessionWasInterrupted and
/// AVCaptureSessionInterruptionEnded notifications to update current state, it may not be a
/// reliable indicator of multitasking if there is no active AVCaptureSession running when
/// multitasking begins or ends. Further testing is recommended.
var isCaptureSessionInterrupted = false
/// Should be set to true when the brightness sensor is being used, so that camera use will not
/// be allowed.
var isBrightnessSensorInUse = false
/// Can the camera be used? This is disabled if a user chooses a brightness sensor and starts a
/// recording, during which the camera cannot be used.
var isCameraUseAllowed: Bool {
return !isCaptureSessionInterrupted && !isBrightnessSensorInUse &&
CameraAccessHandler.checkForPermission()
}
var cameraAvailability: CameraAvailability {
if isBrightnessSensorInUse {
return .blockedByBrightnessSensor
}
if isCaptureSessionInterrupted {
return .captureInterrupted
}
// Note: this check will request perms if they are not determined,
// so it's not a 1:1 match with permissions denied
if CameraAccessHandler.checkForPermission() {
return .available
} else {
return .permissionsDenied
}
}
// MARK: - Public
// MARK: - Private
/// Use `shared`.
private init() {
// Capture session notifications.
NotificationCenter.default.addObserver(self,
selector: #selector(captureSessionWasInterrupted(_:)),
name: .AVCaptureSessionWasInterrupted,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(captureSessionInterruptionEnded(_:)),
name: .AVCaptureSessionInterruptionEnded,
object: nil)
}
@objc private func captureSessionWasInterrupted(_ notification: Notification) {
guard Thread.isMainThread else {
DispatchQueue.main.async {
self.captureSessionWasInterrupted(notification)
}
return
}
guard AVCaptureSession.InterruptionReason(notificationUserInfo: notification.userInfo) ==
.videoDeviceNotAvailableWithMultipleForegroundApps else { return }
isCaptureSessionInterrupted = true
}
@objc private func captureSessionInterruptionEnded(_ notification: Notification) {
guard Thread.isMainThread else {
DispatchQueue.main.async {
self.captureSessionInterruptionEnded(notification)
}
return
}
isCaptureSessionInterrupted = false
}
}
|
apache-2.0
|
209c0f8808123fe0896910f6c51913eb
| 33.071429 | 100 | 0.686845 | 5.359551 | false | false | false | false |
dpricha89/DrApp
|
Source/TableCells/ImageRow.swift
|
1
|
8773
|
import Foundation
import Eureka
public struct ImageRowSourceTypes : OptionSet {
public let rawValue: Int
public var imagePickerControllerSourceTypeRawValue: Int { return self.rawValue >> 1 }
public init(rawValue: Int) { self.rawValue = rawValue }
init(_ sourceType: UIImagePickerControllerSourceType) { self.init(rawValue: 1 << sourceType.rawValue) }
public static let PhotoLibrary = ImageRowSourceTypes(.photoLibrary)
public static let Camera = ImageRowSourceTypes(.camera)
public static let SavedPhotosAlbum = ImageRowSourceTypes(.savedPhotosAlbum)
public static let All: ImageRowSourceTypes = [Camera, PhotoLibrary, SavedPhotosAlbum]
}
extension ImageRowSourceTypes {
// MARK: Helpers
var localizedString: String {
switch self {
case ImageRowSourceTypes.Camera:
return "Take photo"
case ImageRowSourceTypes.PhotoLibrary:
return "Photo Library"
case ImageRowSourceTypes.SavedPhotosAlbum:
return "Saved Photos"
default:
return ""
}
}
}
public enum ImageClearAction {
case no
case yes(style: UIAlertActionStyle)
}
//MARK: Row
open class _ImageRow<Cell: CellType>: OptionsRow<Cell>, PresenterRowType where Cell: BaseCell, Cell: TypedCellType, Cell.Value == UIImage {
public typealias PresenterRow = ImagePickerController
/// Defines how the view controller will be presented, pushed, etc.
open var presentationMode: PresentationMode<PresenterRow>?
/// Will be called before the presentation occurs.
open var onPresentCallback: ((FormViewController, PresenterRow) -> Void)?
open var sourceTypes: ImageRowSourceTypes
open internal(set) var imageURL: URL?
open var clearAction = ImageClearAction.yes(style: .destructive)
private var _sourceType: UIImagePickerControllerSourceType = .camera
public required init(tag: String?) {
sourceTypes = .All
super.init(tag: tag)
presentationMode = .presentModally(controllerProvider: ControllerProvider.callback { return ImagePickerController() }, onDismiss: { [weak self] vc in
self?.select()
vc.dismiss(animated: true)
})
self.displayValueFor = nil
}
// copy over the existing logic from the SelectorRow
func displayImagePickerController(_ sourceType: UIImagePickerControllerSourceType) {
if let presentationMode = presentationMode, !isDisabled {
if let controller = presentationMode.makeController(){
controller.row = self
controller.sourceType = sourceType
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: cell.formViewController()!)
}
else{
_sourceType = sourceType
presentationMode.present(nil, row: self, presentingController: cell.formViewController()!)
}
}
}
/// Extends `didSelect` method
/// Selecting the Image Row cell will open a popup to choose where to source the photo from,
/// based on the `sourceTypes` configured and the available sources.
open override func customDidSelect() {
guard !isDisabled else {
super.customDidSelect()
return
}
deselect()
var availableSources: ImageRowSourceTypes = []
if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
let _ = availableSources.insert(.PhotoLibrary)
}
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let _ = availableSources.insert(.Camera)
}
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
let _ = availableSources.insert(.SavedPhotosAlbum)
}
sourceTypes.formIntersection(availableSources)
if sourceTypes.isEmpty {
super.customDidSelect()
guard let presentationMode = presentationMode else { return }
if let controller = presentationMode.makeController() {
controller.row = self
controller.title = selectorTitle ?? controller.title
onPresentCallback?(cell.formViewController()!, controller)
presentationMode.present(controller, row: self, presentingController: self.cell.formViewController()!)
} else {
presentationMode.present(nil, row: self, presentingController: self.cell.formViewController()!)
}
return
}
// Now that we know the number of sources aren't empty, let the user select the source
let sourceActionSheet = UIAlertController(title: nil, message: selectorTitle, preferredStyle: .actionSheet)
guard let tableView = cell.formViewController()?.tableView else { fatalError() }
if let popView = sourceActionSheet.popoverPresentationController {
popView.sourceView = tableView
popView.sourceRect = tableView.convert(cell.accessoryView?.frame ?? cell.contentView.frame, from: cell)
}
createOptionsForAlertController(sourceActionSheet)
if case .yes(let style) = clearAction, value != nil {
let clearPhotoOption = UIAlertAction(title: NSLocalizedString("Clear Photo", comment: ""), style: style, handler: { [weak self] _ in
self?.value = nil
self?.imageURL = nil
self?.updateCell()
})
sourceActionSheet.addAction(clearPhotoOption)
}
if sourceActionSheet.actions.count == 1 {
if let imagePickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceTypes.imagePickerControllerSourceTypeRawValue) {
displayImagePickerController(imagePickerSourceType)
}
} else {
let cancelOption = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler:nil)
sourceActionSheet.addAction(cancelOption)
if let presentingViewController = cell.formViewController() {
presentingViewController.present(sourceActionSheet, animated: true)
}
}
}
/**
Prepares the pushed row setting its title and completion callback.
*/
open override func prepare(for segue: UIStoryboardSegue) {
super.prepare(for: segue)
guard let rowVC = segue.destination as? PresenterRow else { return }
rowVC.title = selectorTitle ?? rowVC.title
rowVC.onDismissCallback = presentationMode?.onDismissCallback ?? rowVC.onDismissCallback
onPresentCallback?(cell.formViewController()!, rowVC)
rowVC.row = self
rowVC.sourceType = _sourceType
}
open override func customUpdateCell() {
super.customUpdateCell()
cell.accessoryType = .none
cell.editingAccessoryView = .none
if let image = self.value {
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 44, height: 44))
imageView.contentMode = .scaleAspectFill
imageView.image = image
imageView.clipsToBounds = true
cell.accessoryView = imageView
cell.editingAccessoryView = imageView
} else {
cell.accessoryView = nil
cell.editingAccessoryView = nil
}
}
}
extension _ImageRow {
//MARK: Helpers
func createOptionForAlertController(_ alertController: UIAlertController, sourceType: ImageRowSourceTypes) {
guard let pickerSourceType = UIImagePickerControllerSourceType(rawValue: sourceType.imagePickerControllerSourceTypeRawValue), sourceTypes.contains(sourceType) else { return }
let option = UIAlertAction(title: NSLocalizedString(sourceType.localizedString, comment: ""), style: .default, handler: { [weak self] _ in
self?.displayImagePickerController(pickerSourceType)
})
alertController.addAction(option)
}
func createOptionsForAlertController(_ alertController: UIAlertController) {
createOptionForAlertController(alertController, sourceType: .Camera)
createOptionForAlertController(alertController, sourceType: .PhotoLibrary)
createOptionForAlertController(alertController, sourceType: .SavedPhotosAlbum)
}
}
/// A selector row where the user can pick an image
public final class ImageRow : _ImageRow<PushSelectorCell<UIImage>>, RowType {
public required init(tag: String?) {
super.init(tag: tag)
}
}
|
apache-2.0
|
391bb5b7e0655a7b7cf1d66f2b0a79c7
| 39.995327 | 182 | 0.658384 | 5.891874 | false | false | false | false |
CodeEagle/XcodeScriptsKit
|
format_code.swift
|
1
|
1283
|
#!/usr/bin/env xcrun -sdk macosx swift
import Foundation
extension Bool {
var unsafePointer: UnsafeMutablePointer<ObjCBool> {
let b = UnsafeMutablePointer<ObjCBool>.allocate(capacity: 1)
b.initialize(to: ObjCBool(self))
return b
}
}
func files(inDirectory dir: String) -> [String] {
let fm = FileManager.default
do { return try fm.contentsOfDirectory(atPath: dir) } catch { return [] }
}
private func path(isDirectory path: String) -> Bool {
let isdir = false.unsafePointer
let fm = FileManager.default
if fm.fileExists(atPath: path, isDirectory: isdir) {
return isdir.pointee.boolValue
}
return false
}
func loop(at folder: String) {
var arguments: [String] = CommandLine.arguments
let dir = arguments.removeFirst() as NSString
let formatterPath = dir.deletingLastPathComponent + "/swiftformat"
formatCode(at: folder, exePath: formatterPath)
}
func formatCode(at path: String, exePath: String) {
let task = Process()
task.launchPath = exePath
task.arguments = [path, "--indent", "4", path]
task.launch()
}
func start() {
var arguments: [String] = CommandLine.arguments
arguments.removeFirst()
let targetFolder = arguments.removeFirst()
loop(at: targetFolder)
}
start()
|
mit
|
e9be00f9ba1d3a7792fcb17a478a84c8
| 27.511111 | 77 | 0.68979 | 4.009375 | false | false | false | false |
cinnamon/MPFramework
|
MPFramework/Utils/TextValidator.swift
|
1
|
721
|
//
// TextValidator.swift
// MPFramework
//
// Created by 이인재 on 2016.11.03.
// Copyright © 2016 magentapink. All rights reserved.
//
open class TextValidator {
private init() {}
open func validate(textField: UITextField, title: String?, message: String?, confirmTitle: String) -> String? {
guard let text = textField.text, text.isEmpty == false else {
let alert = UIAlertController(title: title, message: message, confirmTitle: confirmTitle, confirm: { (action) in
textField.becomeFirstResponder()
})
if let topViewController = UIApplication.topViewController() {
topViewController.present(alert, animated: true, completion: nil)
}
return nil
}
return text
}
}
|
apache-2.0
|
68f77a27d593f3dd3df311438e596f83
| 24.5 | 115 | 0.694678 | 3.797872 | false | false | false | false |
danielcwj16/ConnectedAlarmApp
|
Pods/SwiftyJSON/Source/SwiftyJSON.swift
|
3
|
39954
|
// SwiftyJSON.swift
//
// Copyright (c) 2014 - 2017 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
@available(*, deprecated, message: "Use the `SwiftyJSONError.errorDomain` instead")
public let ErrorDomain: String = "SwiftyJSONErrorDomain"
///Error code
@available(*, deprecated, message: "Use the `SwiftyJSONError.unsupportedType` instead")
public let ErrorUnsupportedType: Int = 999
@available(*, deprecated, message: "Use the `SwiftyJSONError.indexOutOfBounds` instead")
public let ErrorIndexOutOfBounds: Int = 900
@available(*, deprecated, message: "Use the `SwiftyJSONError.wrongType` instead")
public let ErrorWrongType: Int = 901
@available(*, deprecated, message: "Use the `SwiftyJSONError.notExist` instead")
public let ErrorNotExist: Int = 500
@available(*, deprecated, message: "Use the `SwiftyJSONError.invalidJSON` instead")
public let ErrorInvalidJSON: Int = 490
public enum SwiftyJSONError: Int, Swift.Error {
case unsupportedType = 999
case indexOutOfBounds = 900
case elementTooDeep = 902
case wrongType = 901
case notExist = 500
case invalidJSON = 490
}
extension SwiftyJSONError: CustomNSError {
public static var errorDomain: String { return "com.swiftyjson.SwiftyJSON" }
public var errorCode: Int { return self.rawValue }
public var errorUserInfo: [String : Any] {
switch self {
case .unsupportedType:
return [NSLocalizedDescriptionKey: "It is a unsupported type."]
case .indexOutOfBounds:
return [NSLocalizedDescriptionKey: "Array Index is out of bounds."]
case .wrongType:
return [NSLocalizedDescriptionKey: "Couldn't merge, because the JSONs differ in type on top level."]
case .notExist:
return [NSLocalizedDescriptionKey: "Dictionary key does not exist."]
case .invalidJSON:
return [NSLocalizedDescriptionKey: "JSON is invalid."]
case .elementTooDeep:
return [NSLocalizedDescriptionKey: "Element too deep. Increase maxObjectDepth and make sure there is no reference loop."]
}
}
}
// 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. `[]` by default.
- returns: The created JSON
*/
public init(data: Data, options opt: JSONSerialization.ReadingOptions = []) throws {
let object: Any = try JSONSerialization.jsonObject(with: data, options: opt)
self.init(jsonObject: object)
}
/**
Creates a JSON object
- parameter object: the object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- returns: the created JSON object
*/
public init(_ object: Any) {
switch object {
case let object as Data:
do {
try self.init(data: object)
} catch {
self.init(jsonObject: NSNull())
}
default:
self.init(jsonObject: object)
}
}
/**
Parses the JSON string into a JSON object
- parameter json: the JSON string
- returns: the created JSON object
*/
public init(parseJSON jsonString: String) {
if let data = jsonString.data(using: .utf8) {
self.init(data)
} else {
self.init(NSNull())
}
}
/**
Creates a JSON from JSON string
- parameter string: Normal json string like '{"a":"b"}'
- returns: The created JSON
*/
@available(*, deprecated, message: "Use instead `init(parseJSON: )`")
public static func parse(_ json: String) -> JSON {
return json.data(using: String.Encoding.utf8)
.flatMap { try? 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
*/
fileprivate init(jsonObject: Any) {
self.object = jsonObject
}
/**
Merges another JSON into this JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONs getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public mutating func merge(with other: JSON) throws {
try self.merge(with: other, typecheck: true)
}
/**
Merges another JSON into this JSON and returns a new JSON, whereas primitive values which are not present in this JSON are getting added,
present values getting overwritten, array values getting appended and nested JSONS getting merged the same way.
- parameter other: The JSON which gets merged into this JSON
- returns: New merged JSON
- throws `ErrorWrongType` if the other JSONs differs in type on the top level.
*/
public func merged(with other: JSON) throws -> JSON {
var merged = self
try merged.merge(with: other, typecheck: true)
return merged
}
// Private woker function which does the actual merging
// Typecheck is set to true for the first recursion level to prevent total override of the source JSON
fileprivate mutating func merge(with other: JSON, typecheck: Bool) throws {
if self.type == other.type {
switch self.type {
case .dictionary:
for (key, _) in other {
try self[key].merge(with: other[key], typecheck: false)
}
case .array:
self = JSON(self.arrayValue + other.arrayValue)
default:
self = other
}
} else {
if typecheck {
throw SwiftyJSONError.wrongType
} else {
self = other
}
}
}
/// Private object
fileprivate var rawArray: [Any] = []
fileprivate var rawDictionary: [String : Any] = [:]
fileprivate var rawString: String = ""
fileprivate var rawNumber: NSNumber = 0
fileprivate var rawNull: NSNull = NSNull()
fileprivate var rawBool: Bool = false
/// Private type
fileprivate var _type: Type = .null
/// Private error
fileprivate var _error: SwiftyJSONError?
/// Object in JSON
public var object: Any {
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.rawBool
default:
return self.rawNull
}
}
set {
_error = nil
switch unwrap(newValue) {
case let number as NSNumber:
if number.isBool {
_type = .bool
self.rawBool = number.boolValue
} else {
_type = .number
self.rawNumber = number
}
case let string as String:
_type = .string
self.rawString = string
case _ as NSNull:
_type = .null
case nil:
_type = .null
case let array as [Any]:
_type = .array
self.rawArray = array
case let dictionary as [String : Any]:
_type = .dictionary
self.rawDictionary = dictionary
default:
_type = .unknown
_error = SwiftyJSONError.unsupportedType
}
}
}
/// JSON type
public var type: Type { return _type }
/// Error in JSON
public var error: SwiftyJSONError? { return _error }
/// The static null JSON
@available(*, unavailable, renamed:"null")
public static var nullJSON: JSON { return null }
public static var null: JSON { return JSON(NSNull()) }
}
// unwrap nested JSON
private func unwrap(_ object: Any) -> Any {
switch object {
case let json as JSON:
return unwrap(json.object)
case let array as [Any]:
return array.map(unwrap)
case let dictionary as [String : Any]:
var unwrappedDic = dictionary
for (k, v) in dictionary {
unwrappedDic[k] = unwrap(v)
}
return unwrappedDic
default:
return object
}
}
public enum Index<T: Any>: Comparable {
case array(Int)
case dictionary(DictionaryIndex<String, T>)
case null
static public func == (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left == right
case (.dictionary(let left), .dictionary(let right)):
return left == right
case (.null, .null): return true
default:
return false
}
}
static public func < (lhs: Index, rhs: Index) -> Bool {
switch (lhs, rhs) {
case (.array(let left), .array(let right)):
return left < right
case (.dictionary(let left), .dictionary(let right)):
return left < right
default:
return false
}
}
}
public typealias JSONIndex = Index<JSON>
public typealias JSONRawIndex = Index<Any>
extension JSON: Swift.Collection {
public typealias Index = JSONRawIndex
public var startIndex: Index {
switch type {
case .array:
return .array(rawArray.startIndex)
case .dictionary:
return .dictionary(rawDictionary.startIndex)
default:
return .null
}
}
public var endIndex: Index {
switch type {
case .array:
return .array(rawArray.endIndex)
case .dictionary:
return .dictionary(rawDictionary.endIndex)
default:
return .null
}
}
public func index(after i: Index) -> Index {
switch i {
case .array(let idx):
return .array(rawArray.index(after: idx))
case .dictionary(let idx):
return .dictionary(rawDictionary.index(after: idx))
default:
return .null
}
}
public subscript (position: Index) -> (String, JSON) {
switch position {
case .array(let idx):
return (String(idx), JSON(self.rawArray[idx]))
case .dictionary(let idx):
let (key, value) = self.rawDictionary[idx]
return (key, JSON(value))
default:
return ("", JSON.null)
}
}
}
// 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 whose object is `array[index]`, otherwise return null json with error.
fileprivate subscript(index index: Int) -> JSON {
get {
if self.type != .array {
var r = JSON.null
r._error = self._error ?? SwiftyJSONError.wrongType
return r
} else if index >= 0 && index < self.rawArray.count {
return JSON(self.rawArray[index])
} else {
var r = JSON.null
r._error = SwiftyJSONError.indexOutOfBounds
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 whose object is `dictionary[key]` , otherwise return null json with error.
fileprivate 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 = SwiftyJSONError.notExist
}
} else {
r._error = self._error ?? SwiftyJSONError.wrongType
}
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:)`.
fileprivate 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 structures by using array of Int and/or String as path.
- 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.remove(at: 0)
var nextJSON = self[sub: path[0]]
nextJSON[aPath] = newValue
self[sub: path[0]] = nextJSON
}
}
}
/**
Find a json in the complex data structures by using array of Int and/or String as path.
- 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.ExpressibleByStringLiteral {
public init(stringLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(extendedGraphemeClusterLiteral value: StringLiteralType) {
self.init(value as Any)
}
public init(unicodeScalarLiteral value: StringLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(value as Any)
}
}
extension JSON: Swift.ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Any)...) {
var dictionary = [String: Any](minimumCapacity: elements.count)
for (k, v) in elements {
dictionary[k] = v
}
self.init(dictionary as Any)
}
}
extension JSON: Swift.ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Any...) {
self.init(elements as Any)
}
}
extension JSON: Swift.ExpressibleByNilLiteral {
@available(*, deprecated, message: "use JSON.null instead. Will be removed in future versions")
public init(nilLiteral: ()) {
self.init(NSNull() as Any)
}
}
// MARK: - Raw
extension JSON: Swift.RawRepresentable {
public init?(rawValue: Any) {
if JSON(rawValue).type == .unknown {
return nil
} else {
self.init(rawValue)
}
}
public var rawValue: Any {
return self.object
}
public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data {
guard JSONSerialization.isValidJSONObject(self.object) else {
throw SwiftyJSONError.invalidJSON
}
return try JSONSerialization.data(withJSONObject: self.object, options: opt)
}
public func rawString(_ encoding: String.Encoding = .utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? {
do {
return try _rawString(encoding, options: [.jsonSerialization: opt])
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
public func rawString(_ options: [writingOptionsKeys: Any]) -> String? {
let encoding = options[.encoding] as? String.Encoding ?? String.Encoding.utf8
let maxObjectDepth = options[.maxObjextDepth] as? Int ?? 10
do {
return try _rawString(encoding, options: options, maxObjectDepth: maxObjectDepth)
} catch {
print("Could not serialize object to JSON because:", error.localizedDescription)
return nil
}
}
fileprivate func _rawString(_ encoding: String.Encoding = .utf8, options: [writingOptionsKeys: Any], maxObjectDepth: Int = 10) throws -> String? {
if maxObjectDepth < 0 {
throw SwiftyJSONError.invalidJSON
}
switch self.type {
case .dictionary:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let dict = self.object as? [String: Any?] else {
return nil
}
let body = try dict.keys.map { key throws -> String in
guard let value = dict[key] else {
return "\"\(key)\": null"
}
guard let unwrappedValue = value else {
return "\"\(key)\": null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.elementTooDeep
}
if nestedValue.type == .string {
return "\"\(key)\": \"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return "\"\(key)\": \(nestedString)"
}
}
return "{\(body.joined(separator: ","))}"
} catch _ {
return nil
}
case .array:
do {
if !(options[.castNilToNSNull] as? Bool ?? false) {
let jsonOption = options[.jsonSerialization] as? JSONSerialization.WritingOptions ?? JSONSerialization.WritingOptions.prettyPrinted
let data = try self.rawData(options: jsonOption)
return String(data: data, encoding: encoding)
}
guard let array = self.object as? [Any?] else {
return nil
}
let body = try array.map { value throws -> String in
guard let unwrappedValue = value else {
return "null"
}
let nestedValue = JSON(unwrappedValue)
guard let nestedString = try nestedValue._rawString(encoding, options: options, maxObjectDepth: maxObjectDepth - 1) else {
throw SwiftyJSONError.invalidJSON
}
if nestedValue.type == .string {
return "\"\(nestedString.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\""))\""
} else {
return nestedString
}
}
return "[\(body.joined(separator: ","))]"
} catch _ {
return nil
}
case .string:
return self.rawString
case .number:
return self.rawNumber.stringValue
case .bool:
return self.rawBool.description
case .null:
return "null"
default:
return nil
}
}
}
// MARK: - Printable, DebugPrintable
extension JSON: Swift.CustomStringConvertible, Swift.CustomDebugStringConvertible {
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]? {
if self.type == .array {
return self.rawArray.map { JSON($0) }
} else {
return nil
}
}
//Non-optional [JSON]
public var arrayValue: [JSON] {
return self.array ?? []
}
//Optional [Any]
public var arrayObject: [Any]? {
get {
switch self.type {
case .array:
return self.rawArray
default:
return nil
}
}
set {
if let array = newValue {
self.object = array as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Dictionary
extension JSON {
//Optional [String : JSON]
public var dictionary: [String : JSON]? {
if self.type == .dictionary {
var d = [String: JSON](minimumCapacity: rawDictionary.count)
for (key, value) in rawDictionary {
d[key] = JSON(value)
}
return d
} else {
return nil
}
}
//Non-optional [String : JSON]
public var dictionaryValue: [String : JSON] {
return self.dictionary ?? [:]
}
//Optional [String : Any]
public var dictionaryObject: [String : Any]? {
get {
switch self.type {
case .dictionary:
return self.rawDictionary
default:
return nil
}
}
set {
if let v = newValue {
self.object = v as Any
} else {
self.object = NSNull()
}
}
}
}
// MARK: - Bool
extension JSON { // : Swift.Bool
//Optional bool
public var bool: Bool? {
get {
switch self.type {
case .bool:
return self.rawBool
default:
return nil
}
}
set {
if let newValue = newValue {
self.object = newValue as Bool
} else {
self.object = NSNull()
}
}
}
//Non-optional bool
public var boolValue: Bool {
get {
switch self.type {
case .bool:
return self.rawBool
case .number:
return self.rawNumber.boolValue
case .string:
return ["true", "y", "t"].contains { (truthyString) in
return self.rawString.caseInsensitiveCompare(truthyString) == .orderedSame
}
default:
return false
}
}
set {
self.object = 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.rawNumber.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:
return self.rawNumber
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
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:
return self.object as? NSNumber ?? NSNumber(value: 0)
case .bool:
return NSNumber(value: self.rawBool ? 1 : 0)
default:
return NSNumber(value: 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 exists() -> Bool {
if let errorValue = error, (400...1000).contains(errorValue.errorCode) {
return false
}
return true
}
}
// MARK: - URL
extension JSON {
//Optional URL
public var url: URL? {
get {
switch self.type {
case .string:
// Check for existing percent escapes first to prevent double-escaping of % character
if self.rawString.range(of: "%[0-9A-Fa-f]{2}", options: .regularExpression, range: nil, locale: nil) != nil {
return Foundation.URL(string: self.rawString)
} else if let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
// We have to use `Foundation.URL` otherwise it conflicts with the variable name.
return Foundation.URL(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(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var doubleValue: Double {
get {
return self.numberValue.doubleValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var float: Float? {
get {
return self.number?.floatValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var floatValue: Float {
get {
return self.numberValue.floatValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int: Int? {
get {
return self.number?.intValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var intValue: Int {
get {
return self.numberValue.intValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt: UInt? {
get {
return self.number?.uintValue
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uIntValue: UInt {
get {
return self.numberValue.uintValue
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int8: Int8? {
get {
return self.number?.int8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: Int(newValue))
} else {
self.object = NSNull()
}
}
}
public var int8Value: Int8 {
get {
return self.numberValue.int8Value
}
set {
self.object = NSNumber(value: Int(newValue))
}
}
public var uInt8: UInt8? {
get {
return self.number?.uint8Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt8Value: UInt8 {
get {
return self.numberValue.uint8Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int16: Int16? {
get {
return self.number?.int16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int16Value: Int16 {
get {
return self.numberValue.int16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt16: UInt16? {
get {
return self.number?.uint16Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt16Value: UInt16 {
get {
return self.numberValue.uint16Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int32: Int32? {
get {
return self.number?.int32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int32Value: Int32 {
get {
return self.numberValue.int32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt32: UInt32? {
get {
return self.number?.uint32Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt32Value: UInt32 {
get {
return self.numberValue.uint32Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var int64: Int64? {
get {
return self.number?.int64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var int64Value: Int64 {
get {
return self.numberValue.int64Value
}
set {
self.object = NSNumber(value: newValue)
}
}
public var uInt64: UInt64? {
get {
return self.number?.uint64Value
}
set {
if let newValue = newValue {
self.object = NSNumber(value: newValue)
} else {
self.object = NSNull()
}
}
}
public var uInt64Value: UInt64 {
get {
return self.numberValue.uint64Value
}
set {
self.object = NSNumber(value: 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.rawBool == rhs.rawBool
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.rawBool == rhs.rawBool
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.rawBool == rhs.rawBool
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(value: true)
private let falseNumber = NSNumber(value: false)
private let trueObjCType = String(cString: trueNumber.objCType)
private let falseObjCType = String(cString: falseNumber.objCType)
// MARK: - NSNumber: Comparable
extension NSNumber {
var isBool: Bool {
let objCType = String(cString: self.objCType)
if (self.compare(trueNumber) == .orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == .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) == .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) == .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) == ComparisonResult.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) != .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) != .orderedAscending
}
}
public enum writingOptionsKeys {
case jsonSerialization
case castNilToNSNull
case maxObjextDepth
case encoding
}
|
mit
|
f7e78a4e9c95754c43ee98fe99786d81
| 26.68815 | 265 | 0.549307 | 4.649057 | false | false | false | false |
lovemo/MVVMFramework-Swift
|
SwiftMVVMKitDemo/SwiftMVVMKitDemo/Classes/Src/firstExample/View/BQCell.swift
|
1
|
1191
|
//
// BQCell.swift
// SwiftMVVMKitDemo
//
// Created by yuantao on 16/3/7.
// Copyright © 2016年 momo. All rights reserved.
//
import UIKit
class BQCell: UITableViewCell {
@IBOutlet weak var lbTitle: UILabel!
@IBOutlet weak var lbHeight: UILabel!
@IBOutlet weak var contentImage: UIImageView!
override func configure(cell: UITableViewCell, customObj obj: AnyObject, indexPath: NSIndexPath) {
let model = obj as! FirstModel
self.lbTitle.text = model.title
let lengthStr = "Swift is a powerful and intuitive programming language for iOS, OS X, tvOS, and watchOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next project — or addition into your current app — because Swift code works side-by-side with Objective-C."
let shortStr = "Swift. A modern programming language that is safe, fast, and interactive."
self.lbHeight.text = ((indexPath.row) % 2 == 0) ? lengthStr : shortStr
self.contentImage.image = ((indexPath.row) % 2 == 0) ? UIImage(named: "phil") : UIImage(named: "dogebread")
}
}
|
mit
|
818f09b21dcfe9d631765fdbaebac00d
| 39.827586 | 355 | 0.684122 | 4.054795 | false | false | false | false |
ryanbaldwin/Restivus
|
Tests/PreEncodedRestablesSpec.swift
|
1
|
1703
|
//
// PreEncodedSpec.swift
// Restivus
//
// Created by Ryan Baldwin on 2017-12-27.
//Copyright © 2017 bunnyhug.me. All rights reserved.
//
import Quick
import Nimble
import Restivus
class PreEncodedRestablesSpec: QuickSpec {
override func spec() {
describe("A PreEncoded Postable") {
let postable = PreEncodedPostable()
itBehavesLike("a PreEncoded Restable"){["restable": AnyRestable<Raw>(postable),
"expectedData": postable.data]}
}
describe("A PreEncoded Puttable") {
let puttable = PreEncodedPuttable()
itBehavesLike("a PreEncoded Restable"){["restable": AnyRestable<Raw>(puttable),
"expectedData": puttable.data]}
}
describe("A PreEncoded Gettable") {
let gettable = PreEncodedGettable()
itBehavesLike("a PreEncoded Restable"){["restable": AnyRestable<Raw>(gettable),
"expectedData": gettable.data]}
}
describe("A PreEncoded Patchable") {
let patchable = PreEncodedPatchable()
itBehavesLike("a PreEncoded Restable"){["restable": AnyRestable<Raw>(patchable),
"expectedData": patchable.data]}
}
describe("A PreEncoded Deletable") {
let deletable = PreEncodedDeletable()
itBehavesLike("a PreEncoded Restable"){["restable": AnyRestable<Raw>(deletable),
"expectedData": deletable.data]}
}
}
}
|
apache-2.0
|
e3ba176e51388e266a4a00865e4d64d7
| 36.822222 | 92 | 0.532902 | 5.065476 | false | false | false | false |
breadwallet/breadwallet-ios
|
breadwallet/src/Views/AccountFooterView.swift
|
1
|
5219
|
//
// AccountFooterView.swift
// breadwallet
//
// Created by Adrian Corscadden on 2016-11-16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import UIKit
class AccountFooterView: UIView, Subscriber, Trackable {
static let height: CGFloat = 67.0
var sendCallback: (() -> Void)?
var receiveCallback: (() -> Void)?
var giftCallback: (() -> Void)?
private var hasSetup = false
private let currency: Currency
private let toolbar = UIToolbar()
private var giftButton: UIButton?
init(currency: Currency) {
self.currency = currency
super.init(frame: .zero)
}
override func layoutSubviews() {
super.layoutSubviews()
guard !hasSetup else { return }
setup()
hasSetup = true
}
private func toRadian(value: Int) -> CGFloat {
return CGFloat(Double(value) / 180.0 * .pi)
}
func jiggle() {
guard let button = giftButton else { return }
let rotation = CAKeyframeAnimation(keyPath: "transform.rotation.z")
rotation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
rotation.values = [-10, 10, -5, 5, -3, 3, -2, 2, 0].map {
self.toRadian(value: $0)
}
let scale = CAKeyframeAnimation(keyPath: "transform.scale")
scale.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
scale.values = [1.4, 1.35, 1.3, 1.25, 1.2, 1.15, 1.1, 1.05, 1.0]
let shakeGroup: CAAnimationGroup = CAAnimationGroup()
shakeGroup.animations = [rotation, scale]
shakeGroup.duration = 0.8
button.imageView?.layer.add(shakeGroup, forKey: "jiggle")
}
private func setup() {
let separator = UIView(color: .separatorGray)
addSubview(toolbar)
addSubview(separator)
backgroundColor = currency.colors.1
toolbar.clipsToBounds = true // to remove separator line
toolbar.isOpaque = true
toolbar.isTranslucent = false
toolbar.barTintColor = backgroundColor
// constraints
toolbar.constrainTopCorners(height: AccountFooterView.height)
separator.constrainTopCorners(height: 0.5)
setupToolbarButtons()
}
private func setupToolbarButtons() {
var buttons = [
(S.Button.send, #selector(AccountFooterView.send)),
(S.Button.receive, #selector(AccountFooterView.receive))
].compactMap { (title, selector) -> UIBarButtonItem in
let button = UIButton.rounded(title: title)
button.tintColor = .white
button.backgroundColor = .transparentWhite
button.addTarget(self, action: selector, for: .touchUpInside)
return UIBarButtonItem(customView: button)
}
if currency.isGiftingEnabled {
let giftButton = UIButton.rounded(image: "Gift")
giftButton.tap = giftCallback
self.giftButton = giftButton
buttons.append(UIBarButtonItem(customView: giftButton))
}
let paddingWidth = C.padding[2]
let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
fixedSpace.width = C.padding[1]
if currency.isGiftingEnabled {
toolbar.items = [
flexibleSpace,
buttons[0],
fixedSpace,
buttons[1],
fixedSpace,
buttons[2],
flexibleSpace
]
} else {
toolbar.items = [
flexibleSpace,
buttons[0],
fixedSpace,
buttons[1],
flexibleSpace
]
}
if currency.isGiftingEnabled {
let giftingButtonWidth: CGFloat = 44.0
let buttonCount = 2
let buttonWidth = (self.bounds.width - (paddingWidth * CGFloat(buttonCount+1))) / CGFloat(buttonCount) - (giftingButtonWidth)/2.0
let buttonHeight = CGFloat(44.0)
for (index, element) in buttons.enumerated() {
if index != 2 {
element.customView?.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight)
} else {
element.customView?.frame = CGRect(x: 0, y: 0, width: giftingButtonWidth, height: buttonHeight)
}
}
} else {
let buttonWidth = (self.bounds.width - (paddingWidth * CGFloat(buttons.count+1))) / CGFloat(buttons.count)
let buttonHeight = CGFloat(44.0)
buttons.forEach {
$0.customView?.frame = CGRect(x: 0, y: 0, width: buttonWidth, height: buttonHeight)
}
}
}
@objc private func send() { sendCallback?() }
@objc private func receive() { receiveCallback?() }
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
}
|
mit
|
d1040344481563ad4d75951d70d1a1f5
| 33.556291 | 141 | 0.582407 | 4.782768 | false | false | false | false |
yankodimitrov/SignalKit
|
SignalKit/Extensions/UIKit/UITableViewExtensions.swift
|
1
|
3686
|
//
// UITableViewExtensions.swift
// SignalKit
//
// Created by Yanko Dimitrov on 3/7/16.
// Copyright © 2016 Yanko Dimitrov. All rights reserved.
//
import UIKit
public extension SignalType where ObservationValue == CollectionEvent {
/// Bind the collection change events to a table view
public func bindTo(tableView: UITableView, rowAnimation: UITableViewRowAnimation = .Automatic) -> Disposable {
let binding = TableViewBinding()
addObserver { [weak binding] in
binding?.handleCollectionEvent($0)
}
binding.tableView = tableView
binding.rowAnimation = rowAnimation
binding.disposableSource = self
return binding
}
}
// MARK: - TableViewBinding
final class TableViewBinding: Disposable {
weak var tableView: UITableView?
var rowAnimation = UITableViewRowAnimation.Automatic
var disposableSource: Disposable?
init() {}
func dispose() {
disposableSource?.dispose()
}
func handleCollectionEvent(event: CollectionEvent) {
guard !event.containsResetOperation else {
tableView?.reloadData()
return
}
tableView?.beginUpdates()
handleOperations(event.operations)
tableView?.endUpdates()
}
func handleOperations(operations: Set<CollectionEvent.Operation>) {
for operation in operations {
handleOperation(operation)
}
}
func handleOperation(operation: CollectionEvent.Operation) {
switch operation {
case let .Insert(element):
handleInsertOperationForElement(element)
case let .Remove(element):
handleRemoveOperationForElement(element)
case let .Update(element):
handleUpdateOperationForElement(element)
default:
return
}
}
func handleInsertOperationForElement(element: CollectionEvent.Element) {
if case .Section(let index) = element {
tableView?.insertSections(NSIndexSet(index: index), withRowAnimation: rowAnimation)
}
if case .Item(let section, let row) = element {
let path = NSIndexPath(forRow: row, inSection: section)
tableView?.insertRowsAtIndexPaths([path], withRowAnimation: rowAnimation)
}
}
func handleRemoveOperationForElement(element: CollectionEvent.Element) {
if case .Section(let index) = element {
tableView?.deleteSections(NSIndexSet(index: index), withRowAnimation: rowAnimation)
}
if case .Item(let section, let row) = element {
let path = NSIndexPath(forRow: row, inSection: section)
tableView?.deleteRowsAtIndexPaths([path], withRowAnimation: rowAnimation)
}
}
func handleUpdateOperationForElement(element: CollectionEvent.Element) {
if case .Section(let index) = element {
tableView?.reloadSections(NSIndexSet(index: index), withRowAnimation: rowAnimation)
}
if case .Item(let section, let row) = element {
let path = NSIndexPath(forRow: row, inSection: section)
tableView?.reloadRowsAtIndexPaths([path], withRowAnimation: rowAnimation)
}
}
}
|
mit
|
c272c4109459cb4536a003411a6c6aca
| 26.095588 | 114 | 0.576119 | 5.943548 | false | false | false | false |
HabitRPG/habitrpg-ios
|
Habitica API Client/Habitica API Client/Models/Group/APIMemberItems.swift
|
1
|
1788
|
//
// APIMemberItems.swift
// Habitica API Client
//
// Created by Phillip Thelen on 18.03.19.
// Copyright © 2019 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
public class APIMemberItems: UserItemsProtocol, Decodable {
public var gear: UserGearProtocol?
public var currentMount: String?
public var currentPet: String?
public var ownedQuests: [OwnedItemProtocol] = []
public var ownedFood: [OwnedItemProtocol] = []
public var ownedHatchingPotions: [OwnedItemProtocol] = []
public var ownedEggs: [OwnedItemProtocol] = []
public var ownedSpecialItems: [OwnedItemProtocol] = []
public var ownedPets: [OwnedPetProtocol]
public var ownedMounts: [OwnedMountProtocol]
enum CodingKeys: String, CodingKey {
case gear
case currentMount
case currentPet
case ownedPets = "pets"
case ownedMounts = "mounts"
}
public required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
gear = try? values.decode(APIMemberGear.self, forKey: .gear)
currentPet = try? values.decode(String.self, forKey: .currentPet)
currentMount = try? values.decode(String.self, forKey: .currentMount)
let petsDict = try?values.decode([String: Int?].self, forKey: .ownedPets)
ownedPets = (petsDict?.map({ (key, trained) -> OwnedPetProtocol in
return APIOwnedPet(key: key, trained: trained ?? 0)
})) ?? []
let mountsDict = try?values.decode([String: Bool?].self, forKey: .ownedMounts)
ownedMounts = (mountsDict?.map({ (key, owned) -> APIOwnedMount in
return APIOwnedMount(key: key, owned: owned ?? false)
})) ?? []
}
}
|
gpl-3.0
|
189b6c738d6f89e7eb8822763f9ef7e8
| 36.229167 | 86 | 0.658646 | 4.03386 | false | false | false | false |
wess/reddift
|
reddiftTests/ParseResponseObjectTest.swift
|
1
|
5408
|
//
// ParseResponseObjectTest.swift
// reddift
//
// Created by sonson on 2015/04/22.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import Nimble
import Quick
class ParseResponseObjectTest: QuickSpec {
override func spec() {
describe("When error json which is not a response from reddit.com is loaded") {
it("output is nil") {
for fileName in ["error.json", "t1.json", "t2.json", "t3.json", "t4.json", "t5.json"] {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName(fileName) {
let object:Any? = Parser.parseJSON(json)
expect(object == nil).to(equal(true))
isSucceeded = true
}
expect(isSucceeded).to(equal(true))
}
}
}
describe("comments.json file") {
it("has 1 Link and 26 Comments") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("comments.json") {
if let objects = Parser.parseJSON(json) as? [JSON] {
expect(objects.count).to(equal(2))
if let links = objects[0] as? Listing {
expect(links.children.count).to(equal(1))
expect(links.children[0] is Link).to(equal(true))
}
if let comments = objects[1] as? Listing {
for comment in comments.children {
expect(comment is Comment).to(equal(true))
}
expect(comments.children.count).to(equal(26))
}
isSucceeded = true
}
}
expect(isSucceeded).to(equal(true))
}
}
describe("links.json file") {
it("has 26 Links") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("links.json") {
if let listing = Parser.parseJSON(json) as? Listing {
expect(listing.children.count).to(equal(26))
for child in listing.children {
expect(child is Link).to(equal(true))
}
isSucceeded = true
}
}
expect(isSucceeded).to(equal(true))
}
}
describe("message.json file") {
it("has 4 entries, Comment, Comment, Comment, Message.") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("message.json") {
if let listing = Parser.parseJSON(json) as? Listing {
isSucceeded = true
expect(listing.children.count).to(equal(4))
expect(listing.children[0] is Comment).to(equal(true))
expect(listing.children[1] is Comment).to(equal(true))
expect(listing.children[2] is Comment).to(equal(true))
expect(listing.children[3] is Message).to(equal(true))
}
}
expect(isSucceeded).to(equal(true))
}
}
describe("subreddit.json file") {
it("has 5 Subreddits.") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("subreddit.json") {
if let listing = Parser.parseJSON(json) as? Listing {
expect(listing.children.count).to(equal(5))
for child in listing.children {
expect(child is Subreddit).to(equal(true))
}
isSucceeded = true
}
}
expect(isSucceeded).to(equal(true))
}
}
describe("Parse JSON that is a response to posting a comment") {
it("To t1 object as Comment") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("api_comment_response.json") {
let result = parseResponseJSONToPostComment(json)
switch result {
case .Success:
isSucceeded = true
case .Failure:
break
}
}
expect(isSucceeded).to(equal(true))
}
}
describe("Parse JSON which contains multi") {
it("Must have 2 Multi objects") {
var isSucceeded = false
if let json:AnyObject = self.jsonFromFileName("multi.json") {
if let array = Parser.parseJSON(json) as? [Any] {
isSucceeded = true
for obj in array {
expect(obj is Multireddit).to(equal(true))
}
}
}
expect(isSucceeded).to(equal(true))
}
}
}
}
|
mit
|
c303a01a93fa5c0271332f07ae87650c
| 39.343284 | 103 | 0.447651 | 5.320866 | false | false | false | false |
adamjthomas/PitchPerfect
|
PitchPerfect/PitchPerfect/ViewController.swift
|
1
|
1246
|
//
// ViewController.swift
// PitchPerfect
//
// Created by Adam Thomas on 5/12/16.
// Copyright © 2016 Adam Thomas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var recordingLabel: UILabel!
@IBOutlet weak var recordButton: UIButton!
@IBOutlet weak var stopRecordingButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
stopRecordingButton.enabled = false
}
@IBAction func recordAudio(sender: AnyObject) {
print("Record button pressed")
recordingLabel.text = "Recording in progress"
stopRecordingButton.enabled = true
recordButton.enabled = false
}
@IBAction func stopRecording(sender: AnyObject) {
print("Stop recording button pressed")
recordButton.enabled = true
stopRecordingButton.enabled = false
recordingLabel.text = "Tap to record"
}
}
|
mit
|
732dcd5e951829360e4b4377a325b91a
| 26.065217 | 80 | 0.665863 | 5.081633 | false | false | false | false |
tjw/swift
|
test/SILGen/coverage_closures.swift
|
1
|
2600
|
// RUN: %target-swift-frontend -Xllvm -sil-full-demangle -profile-generate -profile-coverage-mapping -emit-sorted-sil -emit-sil -module-name coverage_closures %s | %FileCheck %s
// rdar://39200851: Closure in init method covered twice
class C2 {
init() {
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 () -> () in coverage_closures.C2.init()
// CHECK-NEXT: [[@LINE+2]]:13 -> [[@LINE+4]]:6 : 0
// CHECK-NEXT: }
let _ = { () in
print("hello")
}
}
}
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_closures.bar
// CHECK-NEXT: [[@LINE+9]]:35 -> [[@LINE+13]]:2 : 0
// CHECK-NEXT: [[@LINE+9]]:44 -> [[@LINE+11]]:4 : 1
// CHECK-NEXT: [[@LINE+10]]:4 -> [[@LINE+11]]:2 : 0
// CHECK-NEXT: }
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #2 (Swift.Int32) -> Swift.Int32 in coverage_closures.bar
// CHECK-NEXT: [[@LINE+4]]:13 -> [[@LINE+4]]:42 : 0
// CHECK-NEXT: }
func bar(arr: [(Int32) -> Int32]) {
for a in [{ (b : Int32) -> Int32 in b }] {
a(0)
}
}
// CHECK-LABEL: sil_coverage_map {{.*}}// coverage_closures.foo
func foo() {
let c1 = { (i1 : Int32, i2 : Int32) -> Bool in i1 < i2 }
// CHECK-LABEL: sil_coverage_map {{.*}}// f1 #1 ((Swift.Int32, Swift.Int32) -> Swift.Bool) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+5]]:55 -> [[@LINE+7]]:4 : 0
// CHECK-NEXT: }
// CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 : @autoclosure () throws -> Swift.Bool in f1
// CHECK-NEXT: [[@LINE+2]]:29 -> [[@LINE+2]]:42 : 0
func f1(_ closure : (Int32, Int32) -> Bool) -> Bool {
return closure(0, 1) && closure(1, 0)
}
f1(c1)
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #2 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+1]]:6 -> [[@LINE+1]]:27 : 0
f1 { i1, i2 in i1 > i2 }
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #3 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE+5]]:6 -> [[@LINE+5]]:48 : 0
// CHECK-NEXT: }
// CHECK-LABEL: sil_coverage_map {{.*}}// implicit closure #1 : @autoclosure () throws -> {{.*}} in coverage_closures.foo
// CHECK-NEXT: [[@LINE+1]]:36 -> [[@LINE+1]]:46 : 0
f1 { left, right in left == 0 || right == 1 }
}
// CHECK-LABEL: sil_coverage_map {{.*}}// closure #1 (Swift.Int32, Swift.Int32) -> Swift.Bool in coverage_closures.foo()
// CHECK-NEXT: [[@LINE-27]]:12 -> [[@LINE-27]]:59 : 0
// SR-2615: Implicit constructor decl has no body, and shouldn't be mapped
struct C1 {
// CHECK-NOT: sil_coverage_map{{.*}}errors
private var errors = [String]()
}
bar(arr: [{ x in x }])
foo()
let _ = C2()
|
apache-2.0
|
a924dc349dcad12fafa6159da2c7c6b2
| 35.619718 | 177 | 0.581923 | 2.882483 | false | false | false | false |
Appstax/appstax-ios
|
Appstax/Appstax/AXObjectService.swift
|
1
|
11907
|
import Foundation
public class AXObjectService {
private var apiClient: AXApiClient
public init(apiClient: AXApiClient) {
self.apiClient = apiClient
}
public func create(collectionName: String) -> AXObject {
return create(collectionName, properties: [:])
}
public func create(collectionName: String, properties: [String:AnyObject]) -> AXObject {
return create(collectionName, properties: properties, status: .New)
}
public func create(collectionName: String, properties: [String:AnyObject], status:AXObjectStatus) -> AXObject {
if collectionName == "users" {
return AXUser(properties: properties)
} else {
return AXObject(collectionName:collectionName, properties: properties, status: status)
}
}
public func createObjects(collectionName: String, properties: [[String:AnyObject]], status: AXObjectStatus) -> [AXObject] {
return properties.map({
return self.create(collectionName, properties: $0, status: status)
})
}
public func saveObject(object: AXObject, completion: ((AXObject, NSError?) -> ())?) {
if object.hasUnsavedRelations {
let error = "Error saving object. Found unsaved related objects. Save related objects first or consider using saveAll instead."
completion?(object, NSError(domain: "AXObjectError", code: 0, userInfo: [NSLocalizedDescriptionKey:error]))
} else {
object.status = .Saving
let savedProperties = object.allPropertiesForSaving
let afterSave: ((AXObject, NSError?) -> ()) = {
object, error in
if error != nil {
completion?(object, error)
} else {
object.afterSave(savedProperties, completion: { completion?(object, $0) })
}
}
if object.objectID == nil {
if object.hasUnsavedFiles {
saveNewObjectWithFiles(object, completion: afterSave)
} else {
saveNewObjectWithoutFiles(object, completion: afterSave)
}
} else {
updateObject(object, completion: afterSave)
}
}
}
private func updateObject(object: AXObject, completion: ((AXObject, NSError?) -> ())?) {
let url = urlForObject(object)
apiClient.putDictionary(object.allPropertiesForSaving, toUrl: url) {
dictionary, error in
if error == nil {
let fileService = Appstax.defaultContext.fileService
fileService.saveFilesForObject(object) {
error in
object.status = error != nil ? .Modified : .Saved
completion?(object, error)
}
} else {
completion?(object, error)
}
}
}
private func saveNewObjectWithoutFiles(object: AXObject, completion: ((AXObject, NSError?) -> ())?) {
let url = urlForCollection(object.collectionName)
apiClient.postDictionary(object.allPropertiesForSaving, toUrl: url) {
dictionary, error in
object.status = error != nil ? .Modified : .Saved
if error == nil {
if let id = dictionary?["sysObjectId"] as! String? {
object.objectID = id
}
}
completion?(object, error)
}
}
private func saveNewObjectWithFiles(object: AXObject, completion: ((AXObject, NSError?) -> ())?) {
let url = urlForCollection(object.collectionName)
let fileService = Appstax.defaultContext.fileService
var multipart: [String: AnyObject] = [:]
for (key, file) in object.allFileProperties {
file.status = AXFileStatusSaving
let data = fileService.dataForFile(file)
multipart[key] = [
"data": data,
"mimeType": file.mimeType,
"filename": file.filename
]
AXLog.trace("Adding file to body: mimeType=\(file.mimeType), filename=\(file.filename), data=\(data.length) bytes")
}
let objectData = apiClient.serializeDictionary(object.allPropertiesForSaving)
multipart["sysObjectData"] = ["data": objectData]
AXLog.trace("Object data in multipart body: \(NSString(data: objectData, encoding: NSUTF8StringEncoding))")
apiClient.sendMultipartFormData(multipart, toUrl: url, method: "POST") {
dictionary, error in
object.status = error != nil ? .Modified : .Saved
if error == nil {
if let id = dictionary?["sysObjectId"] as! String? {
object.objectID = id
}
for (key, file) in object.allFileProperties {
file.status = AXFileStatusSaved
file.url = fileService.urlForFileName(file.filename, objectID: object.objectID, propertyName: key, collectionName: object.collectionName)
}
}
completion?(object, error)
}
}
public func saveObjects(objects: [AXObject], completion: ((NSError?) -> ())?) {
if objects.count == 0 {
completion?(nil)
}
var completionCount = 0
var firstError: NSError?
for object in objects {
saveObject(object) {
object, error in
completionCount += 1
if firstError == nil && error != nil {
firstError = error
}
if completionCount == objects.count {
completion?(firstError)
}
}
}
}
public func remove(object: AXObject, completion: ((NSError?) -> ())?) {
let url = urlForObject(object)
apiClient.deleteUrl(url, completion: completion)
}
public func findAll(collectionName: String, options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
let url = urlForCollection(collectionName, queryParameters: queryParametersFromQueryOptions(options))
apiClient.dictionaryFromUrl(url) {
dictionary, error in
var objects: [AXObject] = []
if let properties = dictionary?["objects"] as? [[String:AnyObject]] {
objects = self.createObjects(collectionName, properties: properties, status: .Saved)
}
completion?(objects, error)
}
}
public func find(collectionName: String, withId id: String, options: [String:AnyObject]?, completion: ((AXObject?, NSError?) -> ())?) {
let url = urlForObject(collectionName, withId: id, queryParameters: queryParametersFromQueryOptions(options))
apiClient.dictionaryFromUrl(url) {
dictionary, error in
if let properties = dictionary {
completion?(self.create(collectionName, properties: properties, status: .Saved), error)
} else {
completion?(nil, error)
}
}
}
public func find(collectionName: String, with propertyValues:[String:AnyObject], options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
let query = AXQuery()
var keys = Array(propertyValues.keys)
keys.sortInPlace({ $0 < $1 })
for key in keys {
if let stringValue = propertyValues[key] as? String {
query.string(key, equals: stringValue)
}
if let objectValue = propertyValues[key] as? AXObject {
query.relation(key, hasObject: objectValue)
}
}
find(collectionName, queryString:query.queryString, options: options, completion: completion)
}
public func find(collectionName: String, search propertyValues: [String:String], options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
let query = AXQuery()
query.logicalOperator = "or"
for (key, _) in propertyValues {
query.string(key, contains: propertyValues[key])
}
find(collectionName, queryString:query.queryString, options: options, completion: completion)
}
public func find(collectionName: String, search searchString: String, properties:[String], options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
var propertyValues: [String:String] = [:]
for property in properties {
propertyValues[property] = searchString
}
find(collectionName, search:propertyValues, options: options, completion:completion)
}
public func find(collectionName: String, query queryBlock:((AXQuery) -> ()), options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
let query = AXQuery()
queryBlock(query)
find(collectionName, queryString: query.queryString, options: options, completion: completion)
}
public func find(collectionName: String, queryString: String, options: [String:AnyObject]?, completion: (([AXObject]?, NSError?) -> ())?) {
let query = AXQuery(queryString: queryString)
var queryParameters = queryParametersFromQueryOptions(options)
queryParameters["filter"] = query.queryString
let url = apiClient.urlFromTemplate("/objects/:collection", parameters: ["collection": collectionName], queryParameters: queryParameters)!
apiClient.dictionaryFromUrl(url) {
dictionary, error in
var objects: [AXObject] = []
if let properties = dictionary?["objects"] as? [[String:AnyObject]] {
objects = self.createObjects(collectionName, properties: properties, status: .Saved)
}
completion?(objects, error)
}
}
public func urlForObject(object: AXObject, queryParameters: [String:String] = [:]) -> NSURL {
return urlForObject(object.collectionName, withId: object.objectID!, queryParameters: queryParameters)
}
public func urlForObject(collectionName: String, withId id: String, queryParameters: [String:String] = [:]) -> NSURL {
let parameters = ["collection": collectionName, "id": id]
return apiClient.urlFromTemplate("objects/:collection/:id", parameters: parameters, queryParameters: queryParameters)!
}
public func urlForCollection(collectionName: String, queryParameters: [String:String] = [:]) -> NSURL {
return apiClient.urlFromTemplate("objects/:collection", parameters: ["collection":collectionName], queryParameters: queryParameters)!
}
private func queryParametersFromQueryOptions(options: [String:AnyObject]?) -> [String:String] {
var parameters: [String:String] = [:]
if let expand = options?["expand"] as? Int {
parameters["expanddepth"] = "\(expand)"
}
if let order = options?["order"] as? String {
var startPos: Int = 0
var sortorder:String = "asc"
if order.hasPrefix("-") {
sortorder = "desc"
startPos = 1
}
parameters["sortorder"] = sortorder
parameters["sortcolumn"] = order.substringFromIndex(order.startIndex.advancedBy(startPos))
}
if let page = options?["page"] as? Int {
parameters["paging"] = "yes"
parameters["pagenum"] = "\(page)"
}
if let pageSize = options?["pageSize"] as? Int {
parameters["paging"] = "yes"
parameters["pagelimit"] = "\(pageSize)"
}
return parameters
}
}
|
mit
|
330e865db3e1d4cd2f84df6a4bb3a8de
| 42.301818 | 172 | 0.584194 | 5.097175 | false | false | false | false |
wickwirew/FluentLayout
|
FluentLayout/LayoutDefaultControlCreator.swift
|
2
|
1893
|
import Foundation
internal class LayoutDefaultControlCreator: LayoutDefaultControls {
func createLabel() -> UILabel {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15, weight: UIFontWeightLight)
label.numberOfLines = 0
label.lineBreakMode = .byCharWrapping
return label
}
func createTitleLabel() -> UILabel {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightRegular)
return label
}
func createTextField() -> UITextField {
let textField = LayoutTextField()
textField.backgroundColor = UIColor(colorLiteralRed: 0.94, green: 0.94, blue: 0.94, alpha: 1.0)
textField.layer.cornerRadius = 4
return textField
}
func createButton() -> UIButton {
let button = UIButton()
button.backgroundColor = .gray
button.layer.cornerRadius = 4
button.setTitleColor(.white, for: .normal)
return button
}
func createTextView() -> UITextView {
let textView = UITextView()
textView.backgroundColor = UIColor(colorLiteralRed: 0.94, green: 0.94, blue: 0.94, alpha: 1.0)
textView.layer.cornerRadius = 4
return textView
}
func createImage() -> UIImageView {
return UIImageView()
}
}
private class LayoutTextField: UITextField {
let padding = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5);
override func textRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return UIEdgeInsetsInsetRect(bounds, padding)
}
}
|
mit
|
983cafb4b457651223c3fb558642d0e6
| 27.253731 | 103 | 0.635499 | 4.981579 | false | false | false | false |
lorentey/swift
|
test/SILGen/switch_var.swift
|
3
|
27506
|
// RUN: %target-swift-emit-silgen -module-name switch_var %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
a(x: x)
}
// CHECK: function_ref @$s10switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
case var z:
// CHECK: [[NO_CASE2]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2aa1xySi_Sit_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2bb1xySi_Sit_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
case var v:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var2cc1xySi_Sit_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$s10switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_41pyAA1P_p_tF : $@convention(thin) (@in_guaranteed P) -> () {
func test_var_4(p p: P) {
// CHECK: function_ref @$s10switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$s10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$s10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: destroy_addr [[PAIR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK-NEXT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_addr
case (_, var w):
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$s10switch_var1d1xySi_tF
// CHECK: destroy_value [[WADDR]]
// CHECK-NEXT: destroy_addr [[PAIR_0]] : $*P
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @$s10switch_var3fooSiyF
// CHECK: function_ref @$s10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
d()
}
e()
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @$s10switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @$s10switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @$s10switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: function_ref @$s10switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[BORROWED_VAL_COPY]])
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL_2:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[BORROWED_VAL_2]]
// CHECK: function_ref @$s10switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY_2]])
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: [[BORROWED_VAL_3:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[BORROWED_VAL_3]]
// CHECK: function_ref @$s10switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: store_borrow [[BORROWED_VAL_COPY_3]] to [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF
// CHECK-NEXT: apply [[FUNC]](
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
case _:
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: function_ref @$s10switch_var1dyyF
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @$s10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @$s10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[BORROWED_VAL:%.*]] = begin_borrow [[VAL]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[BORROWED_VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: store_borrow [[BORROWED_VAL_COPY]] to [[TMP_VAL_COPY_ADDR:%.*]] :
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[FUNC:%.*]] = function_ref @$s10switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: [[D_FUNC:%.*]] = function_ref @$s10switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$s10switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @$s10switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// CHECK: debug_value [[T1:%.+]] :
// CHECK: debug_value [[T2:%.+]] :
switch (0,0) {
// CHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// CHECK: ([[FIRST:%[0-9]+]], [[SECOND:%[0-9]+]]) = destructure_tuple {{%.+}} : $(Int, Int)
// CHECK: apply {{%.+}}([[SECOND]], [[T1]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[SECOND]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: apply {{%.*}}([[FIRST]], [[T2]], {{%.+}})
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: br [[CASE_BODY]]([[FIRST]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$s10switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]([[C_TUP:%.*]] : $(Int, Int, Double)):
// CHECK: ([[C__:%.*]], [[C_X:%.*]], [[C_N:%.*]]) = destructure_tuple [[C_TUP]]
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @$s10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden [ossa] @$s10switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]([[Y_TUP:%.*]] : $(Foo, Int)):
// CHECK: ([[Y_F:%.*]], [[Y_X:%.*]]) = destructure_tuple [[Y_TUP]]
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]([[A_TUP:%.*]] : $(Int, Double)):
// CHECK: ([[A_X:%.*]], [[A_N:%.*]]) = destructure_tuple [[A_TUP]]
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]([[B_TUP:%.*]] : $(Double, Int)):
// CHECK: ([[B_N:%.*]], [[B_X:%.*]]) = destructure_tuple [[B_TUP]]
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]([[Z_TUP:%.*]] : $(Int, Foo)):
// CHECK: ([[Z_X:%.*]], [[Z_F:%.*]]) = destructure_tuple [[Z_TUP]]
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @$s10switch_var3aaa1xySiz_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden [ossa] @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
|
apache-2.0
|
1e4ba1fb8a0a58ca0dad80ff7ee2c8a1
| 37.362622 | 161 | 0.511307 | 2.858657 | false | false | false | false |
bvic23/VinceRP
|
VinceRP/Common/Core/SpinSet.swift
|
1
|
2670
|
//
// Created by Viktor Belenyesi on 18/04/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
public class SpinSet<T: AnyObject>: AtomicReference<T> {
override init(_ t: T) {
super.init(t)
}
func update(t: T) {
super.value = t
}
override public var value: T {
set {
super.value = newValue
}
get {
return super.value
}
}
final func spinSet(transform: T -> T) {
super.value = transform(self.value)
}
// final func spinSetOpt(transform: T -> T?) -> Bool {
// let oldV = super.value
// let newVOpt = transform(oldV)
// guard let newV = newVOpt else {
// return false
// }
// if compareAndSet(oldV, newV) {
// return true
// }
// return spinSetOpt(transform)
// }
}
public class Incrementing<T>: Hub<T> {
private let updateCount = AtomicLong(0)
public var oldValue: SpinSet<SpinState<T>>?
func state() -> SpinSet<SpinState<T>> {
if let s = oldValue {
return s
}
oldValue = SpinSet(self.makeState())
return oldValue!
}
func setState(newValue: SpinSet<SpinState<T>>) {
oldValue = newValue
}
func getStamp() -> long {
return updateCount.getAndIncrement()
}
func toTry() -> SpinState<T> {
return self.state().value
}
func makeState() -> SpinState<T> {
fatalError(ABSTRACT_METHOD)
}
}
public class Spinlock<T>: Incrementing<T> {
override func ping(incoming: Set<Node>) -> Set<Node> {
var oldValue: SpinState<T>? = nil
if let l = self.oldValue {
oldValue = l.value
}
let newState = makeState()
let s = self.state()
// s.spinSetOpt {
if (newState.timestamp >= s.value.timestamp) {
self.state().value = newState
}
// }
if let ov = oldValue where s.value.checkEquality(ov) {
return Set()
}
return children
}
}
public class SpinState<T> {
let timestamp: long
let value: Try<T>
init(_ timestamp: long, _ value: Try<T>) {
self.timestamp = timestamp
self.value = value
}
func checkEquality(other: SpinState<T>) -> Bool {
let lhs = self.value
let rhs = other.value
switch (lhs, rhs) {
case (.Success(let l), .Success(let r)): return l === r
case (.Failure(let l), .Failure(let r)): return l == r
default: return false
}
}
}
|
mit
|
466d0f46a1b4ef77e9729aa7cd45b9bb
| 21.066116 | 63 | 0.520599 | 3.914956 | false | false | false | false |
haitran2011/Rocket.Chat.iOS
|
Rocket.Chat/Extensions/UIImageExtension.swift
|
2
|
1798
|
//
// UIImageExtension.swift
// Rocket.Chat
//
// Created by Rafael K. Streit on 8/16/16.
// Copyright © 2016 Rocket.Chat. All rights reserved.
//
import UIKit
extension UIImage {
func imageWithTint(_ color: UIColor, alpha: CGFloat = 1.0) -> UIImage {
guard let cgImage = cgImage else { return self }
UIGraphicsBeginImageContextWithOptions(self.size, false, UIScreen.main.scale)
let context = UIGraphicsGetCurrentContext()
color.setFill()
context?.translateBy(x: 0, y: self.size.height)
context?.scaleBy(x: 1.0, y: -1.0)
context?.setBlendMode(CGBlendMode.colorBurn)
let rect = CGRect(x: 0.0, y: 0.0, width: self.size.width, height: self.size.height)
context?.draw(cgImage, in: rect)
context?.setBlendMode(CGBlendMode.sourceIn)
context?.addRect(rect)
context?.drawPath(using: CGPathDrawingMode.fill)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard let image = img else { return self }
return image
}
func resizeWith(width: CGFloat) -> UIImage? {
let height = CGFloat(ceil(width/self.size.width * self.size.height))
let size = CGSize(width: width, height: height)
let imageView = UIImageView(frame: CGRect(origin: .zero, size: size))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
}
|
mit
|
f890f9d3525ef6d06180d8c44e9ff8cb
| 31.089286 | 91 | 0.664997 | 4.503759 | false | false | false | false |
hooman/swift
|
test/ClangImporter/CoreGraphics_test.swift
|
3
|
6531
|
// RUN: %target-swift-frontend -module-name=cgtest -emit-ir -O %s | %FileCheck %s
// Test some imported CG APIs
import CoreGraphics
// REQUIRES: OS=macosx
// REQUIRES: CPU=x86_64
// CHECK: [[SWITCHTABLE:@.*]] = private unnamed_addr constant [8 x i64] [i64 0, i64 12, i64 23, i64 34, i64 45, i64 55, i64 67, i64 71]
// CHECK-LABEL: define swiftcc i64 {{.*}}testEnums{{.*}} {
public func testEnums(_ model: CGColorSpaceModel) -> Int {
switch model {
case .unknown : return 0
case .monochrome : return 12
case .rgb : return 23
case .cmyk : return 34
case .lab : return 45
case .deviceN : return 55
case .indexed : return 67
case .pattern : return 71
default: return -1
}
// CHECK: [[GEP:%.+]] = getelementptr inbounds [8 x i64], [8 x i64]* [[SWITCHTABLE]], i64 0, i64 %{{.*}}
// CHECK: [[LOAD:%.+]] = load i64, i64* [[GEP]], align 8
// CHECK: ret i64 [[LOAD]]
}
// CHECK-LABEL: define swiftcc void {{.*}}rotationAround{{.*}} {
// Get a transform that will rotate around a given offset
public func rotationAround(offset: CGPoint, angle: CGFloat,
transform: CGAffineTransform = .identity) -> CGAffineTransform {
// FIXME: consistent API namings
return transform.translatedBy(x: offset.x, y: offset.y)
.rotated(by: angle)
.translatedBy(x: -offset.x, y: -offset.y)
// CHECK: call void @CGAffineTransformTranslate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}}, {{.*}})
// CHECK: call void @CGAffineTransformRotate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}})
// CHECK: call void @CGAffineTransformTranslate(%{{.*}}.CGAffineTransform* {{.*}}, %{{.*}}.CGAffineTransform* {{.*}},{{.*}}, {{.*}})
//
// CHECK: ret void
}
// CHECK-LABEL: define swiftcc void {{.*}}trace{{.*}} {
public func trace(in context: CGContext, path: CGPath) {
let red = CGColor(red: 1, green: 0, blue: 0, alpha: 1)
context.saveGState()
context.addPath(path)
context.setStrokeColor(red)
context.strokePath()
context.restoreGState()
// CHECK: call %{{.*}}.CGColor* @CGColorCreateGenericRGB(double 1.000000e+00, double 0.000000e+00, double 0.000000e+00, double 1.000000e+00)
// CHECK: call void @CGContextSaveGState(%{{.*}}.CGContext* %{{.*}})
// CHECK: call void @CGContextAddPath(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.CGPath* %{{.*}})
// CHECK: call void @CGContextSetStrokeColorWithColor(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.CGColor* %{{.*}})
// CHECK: call void @CGContextStrokePath(%{{.*}}.CGContext* %{{.*}})
// CHECK: call void @CGContextRestoreGState(%{{.*}}.CGContext* %{{.*}})
//
// CHECK: ret void
}
// CHECK-LABEL: define swiftcc void {{.*}}pdfOperations{{.*}} {
public func pdfOperations(_ context: CGContext) {
context.beginPDFPage(nil)
context.endPDFPage()
context.closePDF()
// CHECK: call void @CGPDFContextBeginPage(%{{.*}}.CGContext* %{{.*}}, %{{.*}}.__CFDictionary* {{.*}})
// CHECK: call void @CGPDFContextEndPage(%{{.*}}.CGContext* %{{.*}})
// CHECK: call void @CGPDFContextClose(%{{.*}}.CGContext* %{{.*}})
//
// CHECK: ret void
}
// Test some more recently renamed APIs
// CHECK-LABEL: define swiftcc void {{.*}}testColorRenames{{.*}} {
@available(macOS 10.11, *)
public func testColorRenames(color: CGColor,
intent: CGColorRenderingIntent) {
let colorSpace = CGColorSpace(name: CGColorSpace.sRGB)!
// CHECK: %{{.*}} = load {{.*}}%struct.__CFString** @kCGColorSpaceSRGB{{.*}}, align 8
// CHECK: %{{.*}} = {{.*}} call %struct.CGColorSpace* @CGColorSpaceCreateWithName(%struct.__CFString* %{{.*}})
let _ = color.converted(to: colorSpace, intent: intent, options: nil)
// CHECK: %{{.*}} = {{.*}} call %struct.CGColor* @CGColorCreateCopyByMatchingToColorSpace(%struct.CGColorSpace* nonnull %{{.*}}, i32 %{{.*}}, %struct.CGColor* %{{.*}}, %struct.__CFDictionary* null)
//
// CHECK: ret void
}
// CHECK-LABEL: define swiftcc void {{.*}}testRenames{{.*}} {
public func testRenames(transform: CGAffineTransform, context: CGContext,
point: CGPoint, size: CGSize, rect: CGRect,
image: CGImage,
edge: CGRectEdge) {
let transform = transform.inverted().concatenating(transform)
// CHECK: call void @CGAffineTransformInvert(%struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}})
// CHECK: call void @CGAffineTransformConcat(%struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}}, %struct.CGAffineTransform* {{.*}})
let _ = point.applying(transform)
var rect = rect.applying(transform)
let _ = size.applying(transform)
// CHECK: %{{.*}} = {{(tail )?}}call { double, double } @CGPointApplyAffineTransform(double %{{.*}}, double %{{.*}}, %struct.CGAffineTransform* {{.*}})
// CHECK: call void @CGRectApplyAffineTransform(%struct.CGRect* {{.*}}, %struct.CGRect* {{.*}}, %struct.CGAffineTransform* {{.*}})
// CHECK: %{{.*}} = {{(tail )?}}call { double, double } @CGSizeApplyAffineTransform(double %{{.*}}, double %{{.*}}, %struct.CGAffineTransform* {{.*}})
context.concatenate(transform)
context.rotate(by: CGFloat.pi)
context.scaleBy(x: 1.0, y: 1.0)
context.translateBy(x: 1.0, y: 1.0)
// CHECK: call void @CGContextConcatCTM(%struct.CGContext* [[CONTEXT:%[0-9]+]], %struct.CGAffineTransform* {{.*}})
// CHECK: call void @CGContextRotateCTM(%struct.CGContext* [[CONTEXT]], double {{.*}})
// CHECK: call void @CGContextScaleCTM(%struct.CGContext* [[CONTEXT]], double {{1\.0+.*}}, double {{1\.0+.*}})
// CHECK: call void @CGContextTranslateCTM(%struct.CGContext* [[CONTEXT]], double {{1\.0+.*}}, double {{1\.0+.*}})
context.clip(to: rect)
context.clip(to: rect, mask: image)
// CHECK: call void @CGContextClipToRect(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}})
// CHECK: call void @CGContextClipToMask(%struct.CGContext* [[CONTEXT]], %struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}}, %struct.CGImage* %{{.*}})
var slice = CGRect.zero
var remainder = CGRect.zero
rect.__divided(slice: &slice, remainder: &remainder, atDistance: CGFloat(2.0),
from: edge)
assert((slice, remainder) == rect.divided(atDistance: CGFloat(2.0),
from: edge))
// CHECK: call void @CGRectDivide(%struct.CGRect* nonnull byval({{.*}}) align 8 %{{.*}}, %struct.CGRect* nonnull %{{.*}}, %struct.CGRect* nonnull %{{.*}}, double {{2\.0+.*}}, i32 %{{.*}})
//
// CHECK: ret void
}
|
apache-2.0
|
98c118878aaebd7b8850608b0fe21fc7
| 48.477273 | 199 | 0.616751 | 4.13093 | false | true | false | false |
leotumwattana/WWC-Animations
|
WWC-Animations/ExamplesViewController.swift
|
1
|
1310
|
//
// ViewController.swift
// WWC-Animations
//
// Created by Leo Tumwattana on 27/5/15.
// Copyright (c) 2015 Innovoso Ltd. All rights reserved.
//
import UIKit
class ExamplesViewController: UIViewController, BeeCircleDelegate {
// ==================
// MARK: - Properties
// ==================
var tap:UITapGestureRecognizer!
// ================
// MARK: - Subviews
// ================
@IBOutlet weak var beeCircle:BeeCircle!
override func viewDidLoad() {
super.viewDidLoad()
tap = UITapGestureRecognizer(target: self, action: "tapped:")
tap.enabled = false
view.addGestureRecognizer(tap)
beeCircle.delegate = self
}
override func prefersStatusBarHidden() -> Bool {
return true
}
// ======================
// MARK: - Event Handlers
// ======================
func tapped(tap:UITapGestureRecognizer) {
let location = tap.locationInView(view)
beeCircle.moveToPoint(location)
beeCircle.scale(to: nil)
}
// =========================
// MARK: - BeeCircleDelegate
// =========================
func beeCircleChangedActivation(bee: BeeCircle) {
tap.enabled = bee.activated
}
}
|
bsd-3-clause
|
2f9e496e747c9fed938f2d4782d3966d
| 21.586207 | 69 | 0.514504 | 4.88806 | false | false | false | false |
lanjing99/RxSwiftDemo
|
10-combining-operators-in-practice/starter/OurPlanet/OurPlanet/Model/EOLocation.swift
|
5
|
2303
|
/*
* Copyright (c) 2016 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import UIKit
import CoreLocation
struct EOLocation {
enum GeometryType {
case position
case point
case polygon
static func fromString(string: String) -> GeometryType? {
switch string {
case "Point": return .point
case "Position": return .position
case "Polygon": return .polygon
default: return nil
}
}
}
let type: GeometryType
let date: Date?
let coordinates: [CLLocationCoordinate2D]
init?(json: [String: Any]) {
guard let typeString = json["type"] as? String,
let geoType = GeometryType.fromString(string: typeString),
let coords = json["coordinates"] as? [Any],
(coords.count % 2) == 0 else {
return nil
}
if let dateString = json["date"] as? String {
date = EONET.ISODateReader.date(from: dateString)
} else {
date = nil
}
type = geoType
coordinates = stride(from: 0, to: coords.count, by: 2).flatMap { index in
guard let lat = coords[index] as? Double,
let long = coords[index + 1] as? Double else {
return nil
}
return CLLocationCoordinate2D(latitude: lat, longitude: long)
}
}
}
|
mit
|
7ccaea08a9d1d76010af33d2027318ec
| 33.373134 | 80 | 0.683022 | 4.353497 | false | false | false | false |
markspanbroek/Shhwift
|
Pods/Mockingjay/Mockingjay/Builders.swift
|
2
|
1689
|
//
// Builders.swift
// Mockingjay
//
// Created by Kyle Fuller on 01/03/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
// Collection of generic builders
/// Generic builder for returning a failure
public func failure(error:NSError) -> (request:NSURLRequest) -> Response {
return { _ in return .Failure(error) }
}
public func http(status:Int = 200, headers:[String:String]? = nil, data:NSData? = nil) -> (request:NSURLRequest) -> Response {
return { (request:NSURLRequest) in
if let response = NSHTTPURLResponse(URL: request.URL!, statusCode: status, HTTPVersion: nil, headerFields: headers) {
return Response.Success(response, data)
}
return .Failure(NSError(domain: NSInternalInconsistencyException, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to construct response for stub."]))
}
}
public func json(body:AnyObject, status:Int = 200, headers:[String:String]? = nil) -> (request:NSURLRequest) -> Response {
return { (request:NSURLRequest) in
do {
let data = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions())
return jsonData(data, status: status, headers: headers)(request: request)
} catch {
return .Failure(error as NSError)
}
}
}
public func jsonData(data: NSData, status: Int = 200, headers: [String:String]? = nil) -> (request:NSURLRequest) -> Response {
return { (request:NSURLRequest) in
var headers = headers ?? [String:String]()
if headers["Content-Type"] == nil {
headers["Content-Type"] = "application/json; charset=utf-8"
}
return http(status, headers: headers, data: data)(request:request)
}
}
|
mit
|
280b5300ce75f2af988f316550ac864b
| 33.469388 | 160 | 0.689757 | 4.00237 | false | false | false | false |
WhisperSystems/Signal-iOS
|
SignalServiceKit/src/Messages/TypingIndicatorMessage.swift
|
1
|
3314
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc(OWSTypingIndicatorAction)
public enum TypingIndicatorAction: Int {
case started
case stopped
}
@objc(OWSTypingIndicatorMessage)
public class TypingIndicatorMessage: TSOutgoingMessage {
private let action: TypingIndicatorAction
// MARK: Initializers
@objc
public init(thread: TSThread,
action: TypingIndicatorAction) {
self.action = action
super.init(outgoingMessageWithTimestamp: NSDate.ows_millisecondTimeStamp(),
in: thread,
messageBody: nil,
attachmentIds: NSMutableArray(),
expiresInSeconds: 0,
expireStartedAt: 0,
isVoiceMessage: false,
groupMetaMessage: .unspecified,
quotedMessage: nil,
contactShare: nil,
linkPreview: nil,
messageSticker: nil,
isViewOnceMessage: false)
}
@objc
public required init!(coder: NSCoder) {
self.action = .started
super.init(coder: coder)
}
@objc
public required init(dictionary dictionaryValue: [String: Any]!) throws {
self.action = .started
try super.init(dictionary: dictionaryValue)
}
@objc
public override func shouldSyncTranscript() -> Bool {
return false
}
@objc
public override var isSilent: Bool {
return true
}
@objc
public override var isOnline: Bool {
return true
}
private func protoAction(forAction action: TypingIndicatorAction) -> SSKProtoTypingMessage.SSKProtoTypingMessageAction {
switch action {
case .started:
return .started
case .stopped:
return .stopped
}
}
@objc
public override func buildPlainTextData(_ recipient: SignalRecipient,
thread: TSThread,
transaction: SDSAnyReadTransaction) -> Data? {
let typingBuilder = SSKProtoTypingMessage.builder(timestamp: self.timestamp)
typingBuilder.setAction(protoAction(forAction: action))
if let groupThread = thread as? TSGroupThread {
typingBuilder.setGroupID(groupThread.groupModel.groupId)
}
let contentBuilder = SSKProtoContent.builder()
do {
contentBuilder.setTypingMessage(try typingBuilder.build())
let data = try contentBuilder.buildSerializedData()
return data
} catch let error {
owsFailDebug("failed to build content: \(error)")
return nil
}
}
// MARK: TSYapDatabaseObject overrides
@objc
public override var shouldBeSaved: Bool {
return false
}
@objc
public override var debugDescription: String {
return "typingIndicatorMessage"
}
// MARK:
@objc(stringForTypingIndicatorAction:)
public class func string(forTypingIndicatorAction action: TypingIndicatorAction) -> String {
switch action {
case .started:
return "started"
case .stopped:
return "stopped"
}
}
}
|
gpl-3.0
|
57dfee8debc55062b616286ee7967b20
| 25.943089 | 124 | 0.595353 | 5.26868 | false | false | false | false |
timgrohmann/vertretungsplan_ios
|
JSONLoader.swift
|
1
|
4376
|
//
// JSONLoader.swift
// Vertretungsplan
//
// Created by Tim Grohmann on 24.04.17.
// Copyright © 2017 Tim Grohmann. All rights reserved.
//
import Foundation
class JSONLoader{
var url: String
init(url: String) {
self.url = url
}
func getChanges(callback: @escaping (ChangedTimeTableData?, JSONLoadError?) -> ()) {
if let nsurl = URL(string: self.url){
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.dataTask(with: nsurl, completionHandler: {
data, response, error in
if error != nil{
callback(nil, JSONLoadError.couldNotLoad)
}
if let r = response as? HTTPURLResponse{
switch r.statusCode{
case 200:
break
default:
callback(nil, JSONLoadError.couldNotLoad)
break
}
}
if let data = data{
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as! [String: Any]{
do{
var lessons: [ChangedLesson] = [ChangedLesson]()
guard let plan = json["plan"] as? [String: Any] else {throw JSONLoadError.invalidJSON}
guard let lRaw = plan["lessons"] as? [[String: Any]] else {throw JSONLoadError.invalidJSON}
guard let dayFor = plan["forDay"] as? String else {throw JSONLoadError.invalidJSON}
let weekday = dayFor.components(separatedBy: ",")[0]
let days = ["Mo":0,"Di":1,"Mi":2,"Do":3,"Fr":4, "Sa": -1, "So": -1]
guard let day = days[weekday] else {throw JSONLoadError.dayNotFormatted}
if day == -1 {
throw JSONLoadError.weekend
}
//let day = 3
for l: [String: Any] in lRaw{
if let subject = l["subject"] as? String, let klasse = l["rawCourse"] as? String, let info = l["info"] as? String, let hour = l["lesson"] as? Int{
let teacher = l["rawTeacher"] as? String ?? ""
let room = l["room"] as? String ?? ""
let newLesson = ChangedLesson(subject: subject, teacher: teacher, room: room, course: klasse, info: info, day: day, hour: hour)
lessons.append(newLesson)
if let rSubject = l["rSubject"] as? String {
newLesson.subject = rSubject
}
newLesson.origTeacher = l["oTeacher"] as? String
newLesson.origSubject = l["oSubject"] as? String
}
}
guard let lastUpdated = plan["lastUpdated"] as? String else {throw JSONLoadError.invalidJSON}
guard let schoolName = plan["school_name"] as? String else {throw JSONLoadError.invalidJSON}
callback(ChangedTimeTableData(changedLessons: lessons, schoolName: schoolName, lastRefreshed: lastUpdated), nil)
}catch let e as JSONLoadError{
callback(nil, e)
}catch{
callback(nil, .unknown)
}
}
}
})
task.resume()
}else{
callback(nil, JSONLoadError.invalidURL)
}
}
}
enum JSONLoadError: Error {
case dayNotFormatted
case invalidJSON
case JSONNotParsable
case invalidURL
case outOfStock
case couldNotLoad
case unknown
case weekend
}
|
apache-2.0
|
7db5d1debfa24da16e3ea0171b4d923c
| 42.75 | 178 | 0.437029 | 5.608974 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
TrustTests/Coordinators/AppCoordinatorTests.swift
|
1
|
2628
|
// Copyright DApps Platform Inc. All rights reserved.
import XCTest
@testable import Trust
class AppCoordinatorTests: XCTestCase {
func testStart() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore()
)
coordinator.start()
XCTAssertTrue(coordinator.navigationController.viewControllers[0] is WelcomeViewController)
}
func testStartWithAccounts() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore(
wallets: [.make()]
)
)
coordinator.start()
XCTAssertEqual(1, coordinator.coordinators.count)
XCTAssertTrue(coordinator.navigationController.viewControllers[0] is UITabBarController)
}
func testReset() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore(
wallets: [.make()]
)
)
coordinator.start()
coordinator.reset()
XCTAssertTrue(coordinator.navigationController.viewControllers[0] is WelcomeViewController)
}
func testStartWelcomeWalletCoordinator() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore(),
navigationController: FakeNavigationController()
)
coordinator.start()
coordinator.showInitialWalletCoordinator(entryPoint: .createInstantWallet)
XCTAssertTrue(coordinator.navigationController.viewControllers[0] is WelcomeViewController)
}
func testImportWalletCoordinator() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore(
wallets: [.make()]
),
navigationController: FakeNavigationController()
)
coordinator.start()
coordinator.showInitialWalletCoordinator(entryPoint: .importWallet)
XCTAssertTrue((coordinator.navigationController.presentedViewController as? NavigationController)?.viewControllers[0] is ImportMainWalletViewController)
}
func testShowTransactions() {
let coordinator = AppCoordinator(
window: UIWindow(),
keystore: FakeKeystore(),
navigationController: FakeNavigationController()
)
coordinator.start()
coordinator.showTransactions(for: .make())
XCTAssertEqual(1, coordinator.coordinators.count)
XCTAssertTrue(coordinator.navigationController.viewControllers[0] is UITabBarController)
}
}
|
gpl-3.0
|
f044964289031ece5eb80c456a22b383
| 29.206897 | 160 | 0.644597 | 6.083333 | false | true | false | false |
xedin/swift
|
test/SILGen/objc_set_bridging.swift
|
12
|
6320
|
// RUN: %empty-directory(%t)
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-emit-silgen(mock-sdk: -sdk %S/Inputs -I %t) -module-name objc_set_bridging %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
@objc class Foo : NSObject {
// Bridging set parameters
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC16bridge_Set_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSSet, Foo) -> ()
@objc func bridge_Set_param(_ s: Set<Foo>) {
// CHECK: bb0([[NSSET:%[0-9]+]] : @unowned $NSSet, [[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$sSh10FoundationE36_unconditionallyBridgeFromObjectiveCyShyxGSo5NSSetCSgFZ
// CHECK: [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
// CHECK: [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
// CHECK: [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
// CHECK: [[BORROWED_SET:%.*]] = begin_borrow [[SET]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$s17objc_set_bridging3FooC16bridge_Set_param{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Set<Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SET]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Set<Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
}
// CHECK: // end sil function '$s17objc_set_bridging3FooC16bridge_Set_param{{[_0-9a-zA-Z]*}}FTo'
// Bridging set results
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC17bridge_Set_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSSet {
@objc func bridge_Set_result() -> Set<Foo> {
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @$s17objc_set_bridging3FooC17bridge_Set_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: [[SET:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$sSh10FoundationE19_bridgeToObjectiveCSo5NSSetCyF
// CHECK: [[BORROWED_SET:%.*]] = begin_borrow [[SET]]
// CHECK: [[NSSET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[BORROWED_SET]]) : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned NSSet
// CHECK: end_borrow [[BORROWED_SET]]
// CHECK: destroy_value [[SET]]
// CHECK: return [[NSSET]] : $NSSet
}
// CHECK: } // end sil function '$s17objc_set_bridging3FooC17bridge_Set_result{{[_0-9a-zA-Z]*}}FTo'
@objc var property: Set<Foo> = Set()
// Property getter
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC8property{{[_0-9a-zA-Z]*}}vgTo : $@convention(objc_method) (Foo) -> @autoreleased NSSet
// CHECK: bb0([[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[SELF_COPY]] = copy_value [[SELF]] : $Foo
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[GETTER:%[0-9]+]] = function_ref @$s17objc_set_bridging3FooC8property{{[_0-9a-zA-Z]*}}vg : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: [[SET:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Set<Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$sSh10FoundationE19_bridgeToObjectiveCSo5NSSetCyF
// CHECK: [[BORROWED_SET:%.*]] = begin_borrow [[SET]]
// CHECK: [[NSSET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[BORROWED_SET]]) : $@convention(method) <τ_0_0 where τ_0_0 : Hashable> (@guaranteed Set<τ_0_0>) -> @owned NSSet
// CHECK: end_borrow [[BORROWED_SET]]
// CHECK: destroy_value [[SET]]
// CHECK: return [[NSSET]] : $NSSet
// CHECK: } // end sil function '$s17objc_set_bridging3FooC8property{{[_0-9a-zA-Z]*}}vgTo'
// Property setter
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC8property{{[_0-9a-zA-Z]*}}vsTo : $@convention(objc_method) (NSSet, Foo) -> () {
// CHECK: bb0([[NSSET:%[0-9]+]] : @unowned $NSSet, [[SELF:%[0-9]+]] : @unowned $Foo):
// CHECK: [[NSSET_COPY:%.*]] = copy_value [[NSSET]] : $NSSet
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]] : $Foo
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @$sSh10FoundationE36_unconditionallyBridgeFromObjectiveCyShyxGSo5NSSetCSgFZ
// CHECK: [[OPT_NSSET:%[0-9]+]] = enum $Optional<NSSet>, #Optional.some!enumelt.1, [[NSSET_COPY]] : $NSSet
// CHECK: [[SET_META:%[0-9]+]] = metatype $@thin Set<Foo>.Type
// CHECK: [[SET:%[0-9]+]] = apply [[CONVERTER]]<Foo>([[OPT_NSSET]], [[SET_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @$s17objc_set_bridging3FooC8property{{[_0-9a-zA-Z]*}}vs : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[SET]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Set<Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]] : $Foo
// CHECK: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vgTo : $@convention(objc_method) (Foo) -> @autoreleased NSSet
// CHECK-LABEL: sil hidden [thunk] [ossa] @$s17objc_set_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}vsTo : $@convention(objc_method) (NSSet, Foo) -> () {
@objc var nonVerbatimProperty: Set<String> = Set()
}
func ==(x: Foo, y: Foo) -> Bool { }
|
apache-2.0
|
8e4977c979c03800cad4f5f4b4fe1dbf
| 67.630435 | 184 | 0.603579 | 3.108813 | false | false | false | false |
hooman96/Audio-App
|
Audio App/playSoundViewController.swift
|
1
|
3082
|
//
// playSoundViewController.swift
// Audio App
//
// Created by hooman mohammadi on 8/31/15.
// Copyright (c) 2015 hooman mohammadi. All rights reserved.
//
import UIKit
import AVFoundation
class playSoundViewController: UIViewController {
var audioPlayer:AVAudioPlayer!
var receivedAudio:RecordedAudio!
var audioEngine:AVAudioEngine!
var audioFile:AVAudioFile!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// if var pathFile = NSBundle.mainBundle().pathForResource("movie_quote", ofType: "mp3")
// {
// var URLPath = NSURL.fileURLWithPath(pathFile)
//
// }
audioPlayer = AVAudioPlayer(contentsOfURL: receivedAudio.filePathURL, error: nil)
audioPlayer.enableRate = true
audioEngine = AVAudioEngine()
audioFile = AVAudioFile(forReading: receivedAudio.filePathURL, error: nil)
}
@IBAction func stopingButton(sender: UIButton) {
audioPlayer.stop()
audioPlayer.currentTime = 0.0
audioPlayer.rate = 0.5
audioPlayer.play()
}
@IBAction func fastButton(sender: UIButton) {
audioPlayer.stop()
audioPlayer.currentTime = 0.0
audioPlayer.rate = 2
audioPlayer.play()
}
@IBAction func newVoiceButton(sender: UIButton) {
// playAudioWithVariablePitch(1000)
audioPlayer.stop()
audioEngine.stop()
audioEngine.reset()
var audioPlayerNode = AVAudioPlayerNode()
audioEngine.attachNode(audioPlayerNode)
var changePitchEffect = AVAudioUnitTimePitch()
changePitchEffect.pitch = 1000
audioEngine.attachNode(changePitchEffect)
audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil)
audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil)
audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil)
audioEngine.startAndReturnError(nil)
audioPlayerNode.play()
}
@IBAction func evilVoiceButton(sender: UIButton) {
audioPlayer.stop()
audioPlayer.currentTime = 0.0
audioPlayer.rate = 1
audioPlayer.play()
}
func playAudioWithVariablePitch(pitch: Float) {
println("error")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func stopAudio(sender: UIButton) {
audioPlayer.stop()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
140ecf66ed8d7244018df939464aeb27
| 27.537037 | 106 | 0.643089 | 5.102649 | false | false | false | false |
honghaoz/CrackingTheCodingInterview
|
Swift/LeetCode/Dynamic Programming/2维DP/85_Maximal Rectangle.swift
|
1
|
2047
|
// 85_Maximal Rectangle
// https://leetcode.com/problems/maximal-rectangle/
//
// Created by Honghao Zhang on 9/20/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing only 1's and return its area.
//
//Example:
//
//Input:
//[
// ["1","0","1","0","0"],
// ["1","0","1","1","1"],
// ["1","1","1","1","1"],
// ["1","0","0","1","0"]
//]
//Output: 6
//
// 求一个matrix中最大的rectangle
import Foundation
class Num85 {
// DP, build a state of the max width for each row ends at a index
// Then for each element, check the size with each possible height
func maximalRectangle(_ matrix: [[Character]]) -> Int {
guard matrix.count > 0 else {
return 0
}
let m = matrix.count // row count
guard matrix[0].count > 0 else {
return 0
}
let n = matrix[0].count // column count
// state:
// maxWidth[i][j] stores the max width ends at [i][j]
var maxWidth: [[Int]] = Array(repeating: Array(repeating: 0, count: n), count: m)
// answer
var maxSize: Int = 0
// initialize:
// maxWidth
for i in 0..<m {
for j in 0..<n {
if j == 0 {
maxWidth[i][j] = (matrix[i][j] == "1") ? 1 : 0
}
else {
if matrix[i][j] == "1" {
maxWidth[i][j] = maxWidth[i][j - 1] + 1
}
}
}
}
// function & answer
for i in 0..<m {
for j in 0..<n {
if matrix[i][j] == "1" {
// the width of the largest rectangle whose bottom right corner is (i, j)
var width = maxWidth[i][j]
// iterate the max width from current row to above to check the size for each possible height
var k = i
while k >= 0, maxWidth[k][j] > 0 {
width = min(width, maxWidth[k][j])
let height = i - k + 1
maxSize = max(maxSize, width * height)
k -= 1
}
}
}
}
return maxSize
}
}
|
mit
|
bc618ccc2015e43c7a65840377260164
| 23.190476 | 120 | 0.521161 | 3.46167 | false | false | false | false |
superk589/DereGuide
|
DereGuide/Unit/Simulation/View/UnitAdvanceCalculationResultView.swift
|
2
|
1837
|
//
// UnitAdvanceCalculationResultView.swift
// DereGuide
//
// Created by zzk on 2017/6/21.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import SnapKit
class UnitAdvanceCalculationResultView: UIView {
let leftLabel = UILabel()
let rightLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(leftLabel)
addSubview(rightLabel)
rightLabel.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.right.equalToSuperview()
make.height.greaterThanOrEqualTo(24)
make.width.equalToSuperview().dividedBy(2).offset(-10)
make.bottom.equalToSuperview()
}
rightLabel.textColor = .cute
rightLabel.textAlignment = .right
rightLabel.font = .systemFont(ofSize: 14)
rightLabel.adjustsFontSizeToFitWidth = true
let line = LineView()
addSubview(line)
line.snp.makeConstraints { (make) in
make.top.equalTo(rightLabel.snp.bottom)
make.left.right.equalTo(rightLabel)
}
leftLabel.numberOfLines = 2
leftLabel.adjustsFontSizeToFitWidth = true
leftLabel.baselineAdjustment = .alignCenters
leftLabel.font = .systemFont(ofSize: 14)
leftLabel.snp.makeConstraints { (make) in
make.centerY.equalTo(rightLabel)
make.left.equalToSuperview()
make.right.lessThanOrEqualTo(rightLabel.snp.left).offset(-5)
}
leftLabel.text = NSLocalizedString("计算结果", comment: "")
}
func setup(result: String) {
rightLabel.text = result
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
45b97d4f9797714fad581058d34bf2a9
| 28.967213 | 72 | 0.619256 | 4.835979 | false | false | false | false |
charliecm/alfred-hyperlink
|
src/CopyHTML.swift
|
1
|
502
|
import Cocoa
let argv = CommandLine.arguments[1].split(separator:" ", maxSplits: 1).map(String.init)
let url = argv.count > 0 ? argv[0] : "about:blank"
let title = argv.count > 1 ? argv[1] : "Untitled"
let pasteboard = NSPasteboard.general
let type = NSPasteboard.PasteboardType.html
pasteboard.declareTypes([type], owner: nil)
pasteboard.setString("<a href='\(url)'>\(title)</a>", forType: type)
pasteboard.setString(title + " — " + url, forType: NSPasteboard.PasteboardType.string)
print(title)
|
mit
|
7c8740198b11b371481e8b7d29d4aec5
| 37.461538 | 87 | 0.722 | 3.546099 | false | false | false | false |
tiagomnh/ProjectEuler
|
ProjectEuler/Generators/FibonacciGenerator.swift
|
1
|
395
|
//
// FibonacciGenerator.swift
// ProjectEuler
//
// Created by Tiago Henriques on 04/05/16.
// Copyright © 2016 Tiago Henriques. All rights reserved.
//
import Foundation
class FibonacciGenerator: GeneratorType {
private var n1 = 1
private var n2 = 0
func next() -> Int? {
let result = n1 + n2
n1 = n2
n2 = result
return result
}
}
|
mit
|
49dc93ee0a275bae62a0c960dee56b08
| 16.130435 | 58 | 0.598985 | 3.716981 | false | false | false | false |
nua-schroers/mvvm-frp
|
30_MVVM-App/MatchGame/MatchGame/ViewModel/MainViewModel.swift
|
1
|
5630
|
//
// MainViewModel.swift
// MatchGame
//
// Created by Dr. Wolfram Schroers on 5/27/16.
// Copyright © 2016 Wolfram Schroers. All rights reserved.
//
import UIKit
/// The view model let's the controller know that something must be done.
protocol MainTakeAction: CanPresentDialog {
/// Transition to "Settings" screen.
func transitionToSettings()
/// Update the labels and button enabled states.
func updateLabelsAndButtonStates()
/// Set a certain number of matches in the match pile view.
func setMatchesInPileView(_ count:Int)
/// Remove a certain number of matches in the match pile view.
func removeMatchesInPileView(_ count:Int)
}
/// View model corresponding to the "Main" game screen.
class MainViewModel: NSObject, ReceiveDataContext {
// MARK: The data model (a new home!)
/// Data model for the game state.
fileprivate var matchModel = MatchModel()
// MARK: State of the view
/// The text shown as game state.
var gameState: String {
get {
return prettyMatchString(self.matchModel.matchCount)
}
}
/// The text shown as move report.
var moveReport = ""
/// The enabled state of the "Take 2" button.
var buttonTwoEnabled: Bool {
get {
return self.matchModel.userLimit() > 1
}
}
/// The enabled state of the "Take 3" button.
var buttonThreeEnabled: Bool {
get {
return self.matchModel.userLimit() > 2
}
}
// MARK: VM talks to Controller
/// Activities are triggered through the delegate.
weak var delegate: MainTakeAction?
// MARK: Controller talks to VM
/// Return an appropriate `MatchDataContext`.
func createContext() -> MatchDataContext {
var context = MatchDataContext()
context.initialMatchCount = self.matchModel.initialCount
context.removeMax = self.matchModel.removeMax
switch self.matchModel.strategy {
case .dumb:
context.strategyIndex = 0
case .wild:
context.strategyIndex = 1
case .smart:
context.strategyIndex = 2
}
return context
}
/// Handle when the view will appear.
func viewWillAppear() {
self.startNewGame()
}
/// Respond to "Info" button.
func userTappedInfo() {
self.delegate?.transitionToSettings()
}
/// Respond to "Take 1", "Take 2" and "Take 3" button.
func userTappedTake(_ count:Int) {
self.userMove(count)
}
// MARK: VM talks to another VM -- CanAcceptSettings
func dataContextChanged(_ context: MatchDataContext) {
self.matchModel.initialCount = context.initialMatchCount
self.matchModel.removeMax = context.removeMax
switch context.strategyIndex {
case 0:
self.matchModel.strategy = .dumb
case 1:
self.matchModel.strategy = .wild
default:
self.matchModel.strategy = .smart
}
}
// MARK: Internal helpers
/// Return a number of matches with proper unit.
fileprivate func prettyMatchString(_ count:Int) -> String {
switch count {
case 1:
return NSLocalizedString("1 match", comment: "")
default:
return String(format: NSLocalizedString("%d matches", comment: ""), count)
}
}
/// Start a new game.
fileprivate func startNewGame() {
// Handle the data model.
self.matchModel.restart()
// Handle the state of the view that shall be shown.
self.moveReport = NSLocalizedString("Please start", comment: "")
// Let the controller update the state.
self.delegate?.setMatchesInPileView(self.matchModel.matchCount)
self.delegate?.updateLabelsAndButtonStates()
}
/// End a single game.
fileprivate func gameOver(_ message:String) {
self.delegate?.presentDialog(NSLocalizedString("The game is over", comment: ""),
message: message,
okButtonText: NSLocalizedString("New game", comment: ""),
action: {
self.startNewGame()
},
hasCancel: false)
}
/// Execute a user move.
fileprivate func userMove(_ count:Int) {
// Update the data model.
self.matchModel.performUserMove(count)
// Update the match pile UI.
self.delegate?.removeMatchesInPileView(count)
// Check if the user lost.
if self.matchModel.isGameOver() {
// The user has lost.
self.gameOver(NSLocalizedString("You have lost", comment: ""))
} else {
// The computer moves.
let computerMove = self.matchModel.performComputerMove()
// Update the match pile UI again.
self.delegate?.removeMatchesInPileView(computerMove)
// Check if the computer lost.
if self.matchModel.isGameOver() {
// The computer lost.
self.gameOver(NSLocalizedString("I have lost", comment: ""))
} else {
// Update the UI again (print the computer move).
self.moveReport = String(format: NSLocalizedString("I remove %@", comment: ""),
self.prettyMatchString(computerMove))
}
}
// Let the controller update the state.
self.delegate?.updateLabelsAndButtonStates()
}
}
|
mit
|
7809c8194f5d56d19a6e80b5a34e3915
| 29.592391 | 95 | 0.590869 | 4.794719 | false | false | false | false |
Alecrim/AlecrimAsyncKit
|
Sources/Task.swift
|
1
|
7662
|
//
// Task.swift
// AlecrimAsyncKit
//
// Created by Vanderlei Martinelli on 09/03/18.
// Copyright © 2018 Alecrim. All rights reserved.
//
import Foundation
// MARK: - Task
public final class Task<V, E: Error> {
// MARK: Result
// Result
private var _result: Swift.Result<V, E>?
private var result: Swift.Result<V, E>? {
get {
self.lock(); defer { self.unlock() }
return self._result
}
set {
self.lock(); defer { self.unlock() }
// We can set the result once
if self._result == nil {
self._result = newValue
}
}
}
// MARK: Work Item
// Work Item
private var workItem: DispatchWorkItem?
// Dispatch Group (needed when used with closures without immediate return and `finish` methods)
private var _dispatchGroup: DispatchGroup?
// Result and Dispatch Group Lock
private var _lock = os_unfair_lock_s()
private func lock() { os_unfair_lock_lock(&self._lock) }
private func unlock() { os_unfair_lock_unlock(&self._lock) }
// MARK: Initializers
internal convenience init() {
self.init(result: nil)
}
internal convenience init(value: V) {
self.init(result: .success(value))
}
fileprivate init(result: Swift.Result<V, E>?) {
self.result = result
}
internal convenience init(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], closure: @escaping (Task<V, E>) -> Void) {
self.init(result: nil)
// will need to leave using a `finish` method
self.enterDispatchGroup()
//
let block: () -> Void = {
Thread.current.cancellableTaskBox = CancellableTaskBox(self as? CancellableTask)
closure(self)
}
//
self.workItem = DispatchWorkItem(qos: qos, flags: flags, block: block)
}
// MARK: Executing
internal func execute(on queue: DispatchQueue) {
if let _ = self.result {
return
}
else if let workItem = self.workItem {
Thread.current.cancellableTaskBox?.value?.cancellation += { [weak self] in
(self as? CancellableTask)?.cancel()
}
queue.async(execute: workItem)
}
else {
fatalError()
}
}
// MARK: Cancelling
fileprivate private(set) lazy var _cancellation = Cancellation()
// MARK: Finishing
public func finish(with value: V) {
self._finish(with: .success(value))
}
fileprivate func _finish(with result: Swift.Result<V, E>) {
self.result = result
self.leaveDispatchGroup()
}
// MARK: Dispatch Group Helpers
private func enterDispatchGroup() {
self.lock(); defer { self.unlock() }
self._dispatchGroup = DispatchGroup()
self._dispatchGroup?.enter()
}
private func leaveDispatchGroup() {
self.lock(); defer { self.unlock() }
if let dispatchGroup = self._dispatchGroup {
self._dispatchGroup = nil
dispatchGroup.leave()
}
}
private func waitDispatchGroup() {
var dispatchGroup: DispatchGroup?
do {
self.lock(); defer { self.unlock() }
dispatchGroup = self._dispatchGroup
}
dispatchGroup?.wait()
}
}
// MARK: - Failable Task
extension Task where E == Swift.Error {
// MARK: Initializers
internal convenience init(error: E) {
self.init(result: .failure(error))
}
internal convenience init(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], closure: @escaping () throws -> V) {
self.init(result: nil)
let block: () -> Void = {
Thread.current.cancellableTaskBox = CancellableTaskBox(self)
self._finish(with: Swift.Result(catching: closure))
}
self.workItem = DispatchWorkItem(qos: qos, flags: flags, block: block)
}
// MARK: Awaiting
internal func await() throws -> V {
if let result = self.result {
return try result.get()
}
else if let workItem = self.workItem {
workItem.wait()
waitDispatchGroup()
guard let result = self.result else {
fatalError("Task may be not properly finished. See `Task.finish(with: _)`.")
}
return try result.get()
}
else {
fatalError()
}
}
// MARK: Cancelling
/// A Boolean value that indicates whether the `Task` has been cancelled.
public var isCancelled: Bool {
guard let result = self.result else {
return false
}
switch result {
case let .failure(error):
return error.isUserCancelled
default:
return false
}
}
public var cancellation: Cancellation {
return self._cancellation
}
//
public func cancel() {
self._finish(with: .failure(NSError.userCancelled))
if let workItem = self.workItem {
self.cancellation.run(after: workItem)
workItem.cancel() // fired by workItem notify, runs on a private concurrent queue
}
else {
self.cancellation.run() // runs immediately on current queue
}
}
// MARK: Finishing
public func finish(with error: E) {
self._finish(with: .failure(error))
}
public func finish(with value: V?, or error: E?) {
precondition(value != nil || error != nil)
if let error = error {
self.finish(with: error)
}
else if let value = value {
self.finish(with: value)
}
else {
fatalError()
}
}
public func finish(with result: Swift.Result<V, E>) {
self._finish(with: result)
}
}
// MARK: - Non Failable Task
extension Task where E == Never {
// MARK: Initializers
internal convenience init(qos: DispatchQoS = .unspecified, flags: DispatchWorkItemFlags = [], closure: @escaping () -> V) {
self.init(result: nil)
let block: () -> Void = {
Thread.current.cancellableTaskBox = nil
self._finish(with: .success(closure()))
}
self.workItem = DispatchWorkItem(qos: qos, flags: flags, block: block)
}
// MARK: Executing
internal func await() -> V {
if let result = self.result {
return try! result.get()
}
else if let workItem = self.workItem {
workItem.wait()
waitDispatchGroup()
guard let result = self.result else {
fatalError()
}
return try! result.get()
}
else {
fatalError()
}
}
}
// MARK: - Void Value Task
extension Task where V == Void {
public func finish() {
self.finish(with: ())
}
}
// MARK: - CancellableTask
fileprivate protocol CancellableTask: AnyObject {
var cancellation: Cancellation { get }
func cancel()
}
extension Task: CancellableTask where E == Error {
}
extension Thread {
fileprivate var cancellableTaskBox: CancellableTaskBox? {
get {
return self.threadDictionary["___AAK_TASK"] as? CancellableTaskBox
}
set {
self.threadDictionary["___AAK_TASK"] = newValue
}
}
}
fileprivate struct CancellableTaskBox {
fileprivate weak var value: CancellableTask?
fileprivate init(_ value: CancellableTask?) {
self.value = value
}
}
|
mit
|
5ed7fd3e8f09659b874e5aba4dd92bd6
| 22.645062 | 140 | 0.565331 | 4.511779 | false | false | false | false |
sarvex/SwiftRecepies
|
HomeKit/Interacting with HomeKit Accessories/Interacting with HomeKit Accessories/ViewController.swift
|
1
|
8206
|
//
// ViewController.swift
// Interacting with HomeKit Accessories
//
// Created by Vandad Nahavandipoor on 7/26/14.
// Copyright (c) 2014 Pixolity Ltd. All rights reserved.
//
// These example codes are written for O'Reilly's iOS 8 Swift Programming Cookbook
// If you use these solutions in your apps, you can give attribution to
// Vandad Nahavandipoor for his work. Feel free to visit my blog
// at http://vandadnp.wordpress.com for daily tips and tricks in Swift
// and Objective-C and various other programming languages.
//
// You can purchase "iOS 8 Swift Programming Cookbook" from
// the following URL:
// http://shop.oreilly.com/product/0636920034254.do
//
// If you have any questions, you can contact me directly
// at [email protected]
// Similarly, if you find an error in these sample codes, simply
// report them to O'Reilly at the following URL:
// http://www.oreilly.com/catalog/errata.csp?isbn=0636920034254
import UIKit
import HomeKit
extension HMCharacteristic{
func containsProperty(paramProperty: String) -> Bool{
if let propeties = self.properties{
for property in properties as! [String]{
if property == paramProperty{
return true
}
}
}
return false
}
func isReadable() -> Bool{
return containsProperty(HMCharacteristicPropertyReadable)
}
func isWritable() -> Bool{
return containsProperty(HMCharacteristicPropertyWritable)
}
}
class ViewController: UIViewController, HMHomeManagerDelegate,
HMAccessoryBrowserDelegate {
var home: HMHome!
var room: HMRoom!
var projectorAccessory: HMAccessory!
/* First time it is read, it will generate a random string.
The next time it is read, it will give you the string that it created
the first time. Works between application runs and persist the
data in user defaults */
var homeName: String = {
let homeNameKey = "HomeName"
let defaults = NSUserDefaults.standardUserDefaults()
/* Can we find the old value? */
if let name = defaults.stringForKey(homeNameKey){
if count(name) > 0 {
return name
}
}
/* Create a new name */
let newName = "Home \(arc4random_uniform(UInt32.max))"
defaults.setValue(newName, forKey: homeNameKey)
return newName
}()
lazy var accessoryBrowser: HMAccessoryBrowser = {
let browser = HMAccessoryBrowser()
browser.delegate = self
return browser
}()
let roomName = "Bedroom"
let accessoryName = "Cinema Room Projector"
var homeManager: HMHomeManager!
func createRoom(){
home.addRoomWithName(roomName, completionHandler: {
[weak self](room: HMRoom!, error: NSError!) in
if error != nil{
println("Failed to create the room")
} else {
println("Successuflly created the room")
let strongSelf = self!
strongSelf.room = room
strongSelf.findCinemaRoomProjectorAccessory()
}
})
}
func createHome(){
homeManager.addHomeWithName(homeName, completionHandler: {
[weak self](home: HMHome!, error: NSError!) in
if error != nil{
println("Failed to create the home")
} else {
println("Successfully created the home")
let strongSelf = self!
strongSelf.home = home
println("Creating the room...")
strongSelf.createRoom()
}
})
}
func homeManagerDidUpdateHomes(manager: HMHomeManager) {
for home in manager.homes as! [HMHome]{
if home.name == homeName{
println("Found the home")
self.home = home
for room in home.rooms as! [HMRoom]{
if room.name == roomName{
println("Found the room")
self.room = room
findCinemaRoomProjectorAccessory()
}
}
if self.room == nil{
/* We have to create the room */
println("The room doesn't exist. Creating it...")
createRoom()
}
}
}
if home == nil{
println("Home doesn't exist. Creating it...")
createHome()
}
}
func accessoryBrowser(browser: HMAccessoryBrowser,
didFindNewAccessory accessory: HMAccessory!) {
println("Found an accessory...")
if accessory.name == accessoryName{
println("Discovered the projector accessory")
println("Adding it to the home")
home.addAccessory(accessory, completionHandler: {
[weak self](error: NSError!) in
if error != nil{
println("Failed to add it to the home")
} else {
println("Successfully added it to home")
println("Assigning the projector to the room...")
let strongSelf = self!
strongSelf.home.assignAccessory(accessory,
toRoom: strongSelf.room,
completionHandler: {(error: NSError!) in
if error != nil{
println("Failed to assign the projector to the room")
} else {
strongSelf.projectorAccessory = accessory
println("Successfully assigned the projector to the room")
strongSelf.lowerBrightnessOfProjector()
}
})
}
})
}
}
func lowerBrightnessOfProjector(){
var brightnessCharacteristic: HMCharacteristic!
println("Finding the brightness characteristic of the projector...")
for service in projectorAccessory.services as! [HMService]{
for characteristic in service.characteristics as! [HMCharacteristic]{
if characteristic.characteristicType == HMCharacteristicTypeBrightness{
println("Found it")
brightnessCharacteristic = characteristic
}
}
}
if brightnessCharacteristic == nil{
println("Could not find it")
} else {
if brightnessCharacteristic.isReadable() == false{
println("Cannot read the value of the brightness characteristic")
return
}
println("Reading the value of the brightness characteristic...")
brightnessCharacteristic.readValueWithCompletionHandler{[weak self]
(error: NSError!) in
if error != nil{
println("Could not read the brightness value")
} else {
println("Read the brightness value. Setting it now...")
if brightnessCharacteristic.isWritable(){
let newValue = (brightnessCharacteristic.value as! Float) - 1.0
brightnessCharacteristic.writeValue(newValue,
completionHandler: {(error: NSError!) in
if error != nil{
println("Failed to set the brightness value")
} else {
println("Successfully set the brightness value")
}
})
} else {
println("The brightness characteristic is not writable")
}
}
}
if brightnessCharacteristic.value is Float{
} else {
println("The value of the brightness is not Float. Cannot set it")
}
}
}
func findCinemaRoomProjectorAccessory(){
if let accessories = room.accessories{
for accessory in accessories as! [HMAccessory]{
if accessory.name == accessoryName{
println("Found the projector accessory in the room")
self.projectorAccessory = accessory
}
}
}
/* Start searching for accessories */
if self.projectorAccessory == nil{
println("Could not find the projector accessory in the room")
println("Starting to search for all available accessories")
accessoryBrowser.startSearchingForNewAccessories()
} else {
lowerBrightnessOfProjector()
}
}
override func viewDidLoad() {
homeManager = HMHomeManager()
homeManager.delegate = self
}
}
|
isc
|
1a2d732867b1b5a4ab062ca19f419759
| 27.199313 | 83 | 0.601511 | 5.125547 | false | false | false | false |
AlamofireProject/Alamofire
|
Alamofire/ResponseSerialization.swift
|
1
|
29958
|
//
// ResponseSerialization.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The type in which all data response serializers must conform to in order to serialize a response.
public protocol DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DataResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DataResponseSerializer<Value>: DataResponseSerializerProtocol {
/// The type of serialized object to be created by this `DataResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, data and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, Data?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: -
/// The type in which all download response serializers must conform to in order to serialize a response.
public protocol DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializerType`.
associatedtype SerializedObject
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<SerializedObject> { get }
}
// MARK: -
/// A generic `DownloadResponseSerializerType` used to serialize a request, response, and data into a serialized object.
public struct DownloadResponseSerializer<Value>: DownloadResponseSerializerProtocol {
/// The type of serialized object to be created by this `DownloadResponseSerializer`.
public typealias SerializedObject = Value
/// A closure used by response handlers that takes a request, response, url and error and returns a result.
public var serializeResponse: (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>
/// Initializes the `ResponseSerializer` instance with the given serialize response closure.
///
/// - parameter serializeResponse: The closure used to serialize the response.
///
/// - returns: The new generic response serializer instance.
public init(serializeResponse: @escaping (URLRequest?, HTTPURLResponse?, URL?, Error?) -> Result<Value>) {
self.serializeResponse = serializeResponse
}
}
// MARK: - Timeline
extension Request {
var timeline: Timeline {
let requestCompletedTime = self.endTime ?? CFAbsoluteTimeGetCurrent()
let initialResponseTime = self.delegate.initialResponseTime ?? requestCompletedTime
return Timeline(
requestStartTime: self.startTime ?? CFAbsoluteTimeGetCurrent(),
initialResponseTime: initialResponseTime,
requestCompletedTime: requestCompletedTime,
serializationCompletedTime: CFAbsoluteTimeGetCurrent()
)
}
}
// MARK: - Default
extension DataRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(queue: DispatchQueue? = nil, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self {
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var dataResponse = DefaultDataResponse(
request: self.request,
response: self.response,
data: self.delegate.data,
error: self.delegate.error,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
completionHandler(dataResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DataResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DataResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.delegate.data,
self.delegate.error
)
var dataResponse = DataResponse<T.SerializedObject>(
request: self.request,
response: self.response,
data: self.delegate.data,
result: result,
timeline: self.timeline
)
dataResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(dataResponse) }
}
return self
}
}
extension DownloadRequest {
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DefaultDownloadResponse) -> Void)
-> Self
{
delegate.queue.addOperation {
(queue ?? DispatchQueue.main).async {
var downloadResponse = DefaultDownloadResponse(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
error: self.downloadDelegate.error,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
completionHandler(downloadResponse)
}
}
return self
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter queue: The queue on which the completion handler is dispatched.
/// - parameter responseSerializer: The response serializer responsible for serializing the request, response,
/// and data contained in the destination url.
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func response<T: DownloadResponseSerializerProtocol>(
queue: DispatchQueue? = nil,
responseSerializer: T,
completionHandler: @escaping (DownloadResponse<T.SerializedObject>) -> Void)
-> Self
{
delegate.queue.addOperation {
let result = responseSerializer.serializeResponse(
self.request,
self.response,
self.downloadDelegate.fileURL,
self.downloadDelegate.error
)
var downloadResponse = DownloadResponse<T.SerializedObject>(
request: self.request,
response: self.response,
temporaryURL: self.downloadDelegate.temporaryURL,
destinationURL: self.downloadDelegate.destinationURL,
resumeData: self.downloadDelegate.resumeData,
result: result,
timeline: self.timeline
)
downloadResponse.add(self.delegate.metrics)
(queue ?? DispatchQueue.main).async { completionHandler(downloadResponse) }
}
return self
}
}
// MARK: - Data
extension Request {
/// Returns a result data type that contains the response data as-is.
///
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseData(response: HTTPURLResponse?, data: Data?, error: Error?) -> Result<Data> {
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(Data()) }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
return .success(validData)
}
}
extension DataRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DataResponseSerializer<Data> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseData(response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DataResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns the associated data as-is.
///
/// - returns: A data response serializer.
public static func dataResponseSerializer() -> DownloadResponseSerializer<Data> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseData(response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter completionHandler: The code to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseData(
queue: DispatchQueue? = nil,
completionHandler: @escaping (DownloadResponse<Data>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.dataResponseSerializer(),
completionHandler: completionHandler
)
}
}
// MARK: - String
extension Request {
/// Returns a result string type initialized from the response data with the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseString(
encoding: String.Encoding?,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<String>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success("") }
guard let validData = data else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNil))
}
var convertedEncoding = encoding
if let encodingName = response?.textEncodingName as CFString!, convertedEncoding == nil {
convertedEncoding = String.Encoding(rawValue: CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding(encodingName))
)
}
let actualEncoding = convertedEncoding ?? String.Encoding.isoLatin1
if let string = String(data: validData, encoding: actualEncoding) {
return .success(string)
} else {
return .failure(AFError.responseSerializationFailed(reason: .stringSerializationFailed(encoding: actualEncoding)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DataResponseSerializer<String> {
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DataResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a result string type initialized from the response data with
/// the specified string encoding.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the server
/// response, falling back to the default HTTP default character set, ISO-8859-1.
///
/// - returns: A string response serializer.
public static func stringResponseSerializer(encoding: String.Encoding? = nil) -> DownloadResponseSerializer<String> {
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseString(encoding: encoding, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter encoding: The string encoding. If `nil`, the string encoding will be determined from the
/// server response, falling back to the default HTTP default character set,
/// ISO-8859-1.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseString(
queue: DispatchQueue? = nil,
encoding: String.Encoding? = nil,
completionHandler: @escaping (DownloadResponse<String>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.stringResponseSerializer(encoding: encoding),
completionHandler: completionHandler
)
}
}
// MARK: - JSON
extension Request {
/// Returns a JSON object contained in a result type constructed from the response data using `JSONSerialization`
/// with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponseJSON(
options: JSONSerialization.ReadingOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
var serializeable : Bool? = nil
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
response?.evaluate({ completed in serializeable = completed})
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
var json = try JSONSerialization.jsonObject(with: validData, options: options)
while (serializeable == nil) {json = try JSONSerialization.jsonObject(with: validData, options: options)}
if (serializeable!) {
return .success(json)
} else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
} catch {
return .failure(AFError.responseSerializationFailed(reason: .jsonSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns a JSON object result type constructed from the response data using
/// `JSONSerialization` with the specified reading options.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
///
/// - returns: A JSON object response serializer.
public static func jsonResponseSerializer(
options: JSONSerialization.ReadingOptions = .allowFragments)
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponseJSON(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The JSON serialization reading options. Defaults to `.allowFragments`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responseJSON(
queue: DispatchQueue? = nil,
options: JSONSerialization.ReadingOptions = .allowFragments,
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.jsonResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
// MARK: - Property List
extension Request {
/// Returns a plist object contained in a result type constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter response: The response from the server.
/// - parameter data: The data returned from the server.
/// - parameter error: The error already encountered if it exists.
///
/// - returns: The result data type.
public static func serializeResponsePropertyList(
options: PropertyListSerialization.ReadOptions,
response: HTTPURLResponse?,
data: Data?,
error: Error?)
-> Result<Any>
{
guard error == nil else { return .failure(error!) }
if let response = response, emptyDataStatusCodes.contains(response.statusCode) { return .success(NSNull()) }
guard let validData = data, validData.count > 0 else {
return .failure(AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength))
}
do {
let plist = try PropertyListSerialization.propertyList(from: validData, options: options, format: nil)
return .success(plist)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .propertyListSerializationFailed(error: error)))
}
}
}
extension DataRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DataResponseSerializer<Any>
{
return DataResponseSerializer { _, response, data, error in
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DataResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DataRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
extension DownloadRequest {
/// Creates a response serializer that returns an object constructed from the response data using
/// `PropertyListSerialization` with the specified reading options.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
///
/// - returns: A property list object response serializer.
public static func propertyListResponseSerializer(
options: PropertyListSerialization.ReadOptions = [])
-> DownloadResponseSerializer<Any>
{
return DownloadResponseSerializer { _, response, fileURL, error in
guard error == nil else { return .failure(error!) }
guard let fileURL = fileURL else {
return .failure(AFError.responseSerializationFailed(reason: .inputFileNil))
}
do {
let data = try Data(contentsOf: fileURL)
return Request.serializeResponsePropertyList(options: options, response: response, data: data, error: error)
} catch {
return .failure(AFError.responseSerializationFailed(reason: .inputFileReadFailed(at: fileURL)))
}
}
}
/// Adds a handler to be called once the request has finished.
///
/// - parameter options: The property list reading options. Defaults to `[]`.
/// - parameter completionHandler: A closure to be executed once the request has finished.
///
/// - returns: The request.
@discardableResult
public func responsePropertyList(
queue: DispatchQueue? = nil,
options: PropertyListSerialization.ReadOptions = [],
completionHandler: @escaping (DownloadResponse<Any>) -> Void)
-> Self
{
return response(
queue: queue,
responseSerializer: DownloadRequest.propertyListResponseSerializer(options: options),
completionHandler: completionHandler
)
}
}
/// A set of HTTP response status code that do not contain response data.
private let emptyDataStatusCodes: Set<Int> = [204, 205]
|
mit
|
577a8b39e0ad7acfecc7728ca92d73ae
| 40.493075 | 126 | 0.639295 | 5.637561 | false | false | false | false |
sublimter/Meijiabang
|
KickYourAss/KickYourAss/ArtistDetailFile/ZXY_ChangeCommentVC.swift
|
3
|
3198
|
//
// ZXY_ChangeCommentVC.swift
// KickYourAss
//
// Created by 宇周 on 15/2/10.
// Copyright (c) 2015年 多思科技. All rights reserved.
//
import UIKit
class ZXY_ChangeCommentVC: UIViewController {
@IBOutlet weak var commentTextF: UITextField!
var albumDes : String?
var albumID : String?
var albumDetail : ZXY_PictureDetailBase?
override func viewDidLoad() {
super.viewDidLoad()
self.setNaviBarLeftImage("backArrow")
self.title = "编辑图集"
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("rightButtonAction"))
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if(self.albumDes != nil)
{
self.commentTextF.text = albumDes!
self.commentTextF.becomeFirstResponder()
}
else
{
self.commentTextF.becomeFirstResponder()
}
}
func rightButtonAction()
{
if(self.albumID == nil)
{
self.navigationController?.popViewControllerAnimated(true)
return
}
else
{
if(self.commentTextF.text.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) == 0)
{
self.showAlertEasy("提示", messageContent: "介绍不能为空")
return
}
var stringURL = ZXY_ALLApi.ZXY_MainAPI + ZXY_ALLApi.ZXY_ModifyAlbumAPI
var parameter : Dictionary<String , AnyObject> = ["album_id": albumID! , "description": self.commentTextF.text]
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
ZXY_NetHelperOperate().startGetDataPost(stringURL, parameter: parameter, successBlock: {[weak self] (returnDic) -> Void in
MBProgressHUD.hideAllHUDsForView(self?.view, animated: true)
self?.albumDetail?.data?.dataDescription = self?.commentTextF.text
self?.navigationController?.popViewControllerAnimated(true)
return
}, failBlock: { [weak self] (error) -> Void in
MBProgressHUD.hideAllHUDsForView(self?.view, animated: true)
self?.showAlertEasy("提示", messageContent: "修改失败")
})
}
}
func setAlbumID(albumDetail : ZXY_PictureDetailBase?)
{
self.albumID = albumDetail?.data?.albumId?
self.albumDes = albumDetail?.data?.dataDescription?
self.albumDetail = albumDetail
}
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.
}
*/
}
|
mit
|
9a9c7e498dd04bff9a5cae3945ad1c5a
| 33.173913 | 165 | 0.625318 | 4.720721 | false | false | false | false |
willpowell8/UIDesignKit_iOS
|
UIDesignKit/Classes/Extensions/UISwitch+UIDesign.swift
|
1
|
1992
|
//
// UISwitch+UIDesign.swift
// UIDesignKit
//
// Created by Will Powell on 10/07/2019.
//
import Foundation
extension UISwitch{
override open func updateDesign(type:String, data:[AnyHashable: Any]) {
super.updateDesign(type:type, data: data);
self.applyData(data: data, property: "onTintColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.onTintColor = v
}
})
self.applyData(data: data, property: "thumbTintColor", targetType: .color, apply: { (value) in
if let v = value as? UIColor {
self.thumbTintColor = v
}
})
}
override open func getDesignProperties(data:[String:Any]) -> [String:Any]{
var dataReturn = super.getDesignProperties(data: data);
if #available(iOS 13.0, *) {
let lightColor = colorForTrait(color: self.onTintColor, trait: .light)
let darkColor = colorForTrait(color: self.onTintColor, trait: .dark)
dataReturn["onTintColor"] = ["type":"COLOR", "value":lightColor?.toHexString()]
dataReturn["onTintColor-dark"] = ["type":"COLOR", "value":darkColor?.toHexString()]
}else{
dataReturn["onTintColor"] = ["type":"COLOR", "value":self.onTintColor?.toHexString()];
}
if #available(iOS 13.0, *) {
let lightColor = colorForTrait(color: self.thumbTintColor, trait: .light)
let darkColor = colorForTrait(color: self.thumbTintColor, trait: .dark)
dataReturn["thumbTintColor"] = ["type":"COLOR", "value":lightColor?.toHexString()]
dataReturn["thumbTintColor-dark"] = ["type":"COLOR", "value":darkColor?.toHexString()]
}else{
dataReturn["thumbTintColor"] = ["type":"COLOR", "value":self.thumbTintColor?.toHexString()]
}
return dataReturn;
}
override public func getDesignType() -> String{
return "SWITCH";
}
}
|
mit
|
dea9e5bbfafd6b85ffa11d377678dba5
| 41.382979 | 103 | 0.599398 | 4.397351 | false | false | false | false |
gregomni/swift
|
test/decl/protocol/existential_member_accesses_self_assoctype_fixit.swift
|
2
|
12811
|
// RUN: %target-typecheck-verify-swift
protocol P {
associatedtype A
func method(_: A)
subscript(_: A) -> A { get }
init(_: A)
static func staticMethod(_: A)
}
protocol Q {}
do {
func test(p: P) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:16--1:17=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: ((P))) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:18--1:19=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: any P) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:20--1:21=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: (inout any P)) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{none}}
}
}
do {
func test(p: __shared (any P)) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:30--1:31=<#generic parameter name#>}} {{-1:26--1:30=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: ((any P))) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:22--1:23=<#generic parameter name#>}} {{-1:18--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: any (P)) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any (P)'; consider using a generic constraint instead}} {{-1:21--1:22=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: any P) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:22--1:23=<#generic parameter name#>}} {{-1:16--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: (any (P))) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any (P)'; consider using a generic constraint instead}} {{-1:23--1:24=<#generic parameter name#>}} {{-1:17--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: P.Type) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any P.Type'; consider using a generic constraint instead}} {{-1:16--1:17=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: (P).Type) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any (P).Type'; consider using a generic constraint instead}} {{-1:17--1:18=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: any P.Type) {
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any P.Type'; consider using a generic constraint instead}} {{-1:20--1:21=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: any ((P).Type)) {
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any (P).Type'; consider using a generic constraint instead}} {{-1:22--1:23=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
func test(p: P & Q) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:16--1:21=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: ((P & Q))) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:18--1:23=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: any P & Q) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:20--1:25=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: inout any P & Q) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{none}}
}
}
do {
func test(p: __shared (any P & Q)) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:30--1:35=<#generic parameter name#>}} {{-1:26--1:30=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: ((any P & Q))) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:22--1:27=<#generic parameter name#>}} {{-1:18--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: any (P & Q)) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any (P & Q)'; consider using a generic constraint instead}} {{-1:21--1:26=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: any P & Q) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:22--1:27=<#generic parameter name#>}} {{-1:16--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: (any (P & Q))) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any (P & Q)'; consider using a generic constraint instead}} {{-1:23--1:28=<#generic parameter name#>}} {{-1:17--1:22=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: (P & Q).Type) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any (P & Q).Type'; consider using a generic constraint instead}} {{-1:16--1:23=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: ((P & Q)).Type) { // expected-warning {{use of protocol 'P' as a type must be written 'any P'}}
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any ((P & Q)).Type'; consider using a generic constraint instead}} {{-1:18--1:23=<#generic parameter name#>}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: any (P & Q).Type) {
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any (P & Q).Type'; consider using a generic constraint instead}} {{-1:20--1:27=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
func test(p: any (((P & Q)).Type)) {
p.staticMethod(false) // expected-error {{member 'staticMethod' cannot be used on value of type 'any ((P & Q)).Type'; consider using a generic constraint instead}} {{-1:23--1:28=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
}
}
do {
// With an existing generic parameter list.
func test<T: Sequence>(t: T, p: any P) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:39--1:40=<#generic parameter name#>}} {{-1:35--1:39=}} {{-1:24--1:24=, <#generic parameter name#>: P}} {{none}}
}
}
do {
// With an subscript expression.
func test(p: any P) {
p[false] // expected-error {{member 'subscript' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:20--1:21=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
do {
// With an initializer.
func test(p: any P.Type) {
p.init(false) // expected-error {{member 'init' cannot be used on value of type 'any P.Type'; consider using a generic constraint instead}} {{-1:20--1:21=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
}
}
// Inside initializers, accessors and subscripts.
struct Test {
init(p: any P) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:15--1:16=<#generic parameter name#>}} {{-1:11--1:15=}} {{-1:7--1:7=<<#generic parameter name#>: P>}} {{none}}
}
init<T: P>(p: any P, t: T) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:21--1:22=<#generic parameter name#>}} {{-1:17--1:21=}} {{-1:12--1:12=, <#generic parameter name#>: P}} {{none}}
}
subscript(p: any P) -> any P {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-1:20--1:21=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P>}} {{none}}
return p
}
subscript<T: P>(p: any P, t: T) -> any P {
get {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-2:26--2:27=<#generic parameter name#>}} {{-2:22--2:26=}} {{-2:17--2:17=, <#generic parameter name#>: P}} {{none}}
return p
}
set(value) {
p.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{-6:26--6:27=<#generic parameter name#>}} {{-6:22--6:26=}} {{-6:17--6:17=, <#generic parameter name#>: P}} {{none}}
value.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{none}}
}
}
subscript(p: any P & Q) -> any P {
_read { p.method(false) } // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-1:20--1:25=<#generic parameter name#>}} {{-1:16--1:20=}} {{-1:12--1:12=<<#generic parameter name#>: P & Q>}} {{none}}
_modify { p.method(false) } // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-2:20--2:25=<#generic parameter name#>}} {{-2:16--2:20=}} {{-2:12--2:12=<<#generic parameter name#>: P & Q>}} {{none}}
willSet { p.method(false) } // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-3:20--3:25=<#generic parameter name#>}} {{-3:16--3:20=}} {{-3:12--3:12=<<#generic parameter name#>: P & Q>}} {{none}}
didSet { p.method(false) } // expected-error {{member 'method' cannot be used on value of type 'any P & Q'; consider using a generic constraint instead}} {{-4:20--4:25=<#generic parameter name#>}} {{-4:16--4:20=}} {{-4:12--4:12=<<#generic parameter name#>: P & Q>}} {{none}}
// expected-error@-2 {{'willSet' is not allowed in subscripts}}
// expected-error@-2 {{'didSet' is not allowed in subscripts}}
}
var property: any P {
get {}
set {
newValue.method(false) // expected-error {{member 'method' cannot be used on value of type 'any P'; consider using a generic constraint instead}} {{none}}
}
}
}
|
apache-2.0
|
ac930ffabda87312da14ec6b3eafa4a2
| 61.18932 | 288 | 0.621341 | 3.228579 | false | true | false | false |
solinor/paymenthighway-ios-framework
|
PaymentHighway/Core/PaymentContext.swift
|
1
|
3770
|
//
// PH.swift
// PaymentHighway
//
// Copyright © 2018 Payment Highway Oy. All rights reserved.
//
import Foundation
/// `PaymentContext` manages all the functionality the payment context, such as adding a new payment card.
///
public class PaymentContext<BackendAdpaterType: BackendAdapter> {
let backendAdapter: BackendAdpaterType
let phService: PaymentHighwayService
/// Required to initialize `PaymentContext`
///
/// - parameter config: The configuration of the `PaymentContext`
/// - parameter backendAdapter: Provide your BackendAdpater implementation
/// - seealso: PaymentConfig
/// - seealso: BackendAdapter
/// - seealso: Result
///
public init(config: PaymentConfig, backendAdapter: BackendAdpaterType) {
self.backendAdapter = backendAdapter
self.phService = PaymentHighwayService(config: config)
}
/// Adds a new Payment Card.
///
/// - parameter card: Card to be added
/// - parameter completion: Callback closure with the result of the operation
/// - seealso: CardData
/// - seealso: Result
///
public func addCard(card: CardData,
completion: @escaping (Result<BackendAdpaterType.AddCardCompletedType, BackendAdpaterType.BackendAdapterErrorType>) -> Void) {
backendAdapter.getTransactionId { [weak self] (resultTransactionId) in
switch resultTransactionId {
case .success(let transactionId):
self?.tokenizeCard(transactionId: transactionId, card: card, completion: completion)
case .failure(let transactionIdError):
completion(.failure(transactionIdError))
}
}
}
private func tokenizeCard(transactionId: TransactionId,
card: CardData,
completion: @escaping (Result<BackendAdpaterType.AddCardCompletedType,
BackendAdpaterType.BackendAdapterErrorType>) -> Void) {
phService.encryptionKey(transactionId: transactionId) { [weak self] (resultEncryptionKey) in
guard let strongSelf = self else { return }
switch resultEncryptionKey {
case .success(let encryptionKey):
strongSelf.performTokenizationRequest(encryptionKey: encryptionKey, transactionId: transactionId, card: card, completion: completion)
case .failure(let encryptionKeyError):
completion(.failure(strongSelf.backendAdapter.mapError(error: encryptionKeyError)))
}
}
}
private func performTokenizationRequest(encryptionKey: EncryptionKey,
transactionId: TransactionId,
card: CardData,
completion: @escaping (Result<BackendAdpaterType.AddCardCompletedType,
BackendAdpaterType.BackendAdapterErrorType>) -> Void) {
phService.tokenizeTransaction(transactionId: transactionId,
cardData: card,
encryptionKey: encryptionKey) { [weak self] (resultApiResult) in
guard let strongSelf = self else { return }
switch resultApiResult {
case .success:
strongSelf.backendAdapter.addCardCompleted(transactionId: transactionId, completion: completion)
case .failure(let tokenizeTransactionError):
let resultError = strongSelf.backendAdapter.mapError(error: tokenizeTransactionError)
completion(.failure(resultError))
}
}
}
}
|
mit
|
b1bd4d886183d053b137169e31cc15ba
| 43.341176 | 150 | 0.613956 | 5.534508 | false | true | false | false |
exponent/exponent
|
ios/vendored/unversioned/@stripe/stripe-react-native/ios/CardFormManager.swift
|
2
|
943
|
import Foundation
@objc(CardFormManager)
class CardFormManager: RCTViewManager {
override func view() -> UIView! {
let cardForm = CardFormView()
let stripeSdk = bridge.module(forName: "StripeSdk") as? StripeSdk
stripeSdk?.cardFormView = cardForm;
return cardForm
}
override class func requiresMainQueueSetup() -> Bool {
return false
}
@objc func focus(_ reactTag: NSNumber) {
self.bridge!.uiManager.addUIBlock { (_: RCTUIManager?, viewRegistry: [NSNumber: UIView]?) in
let view: CardFormView = (viewRegistry![reactTag] as? CardFormView)!
view.focus()
}
}
@objc func blur(_ reactTag: NSNumber) {
self.bridge!.uiManager.addUIBlock { (_: RCTUIManager?, viewRegistry: [NSNumber: UIView]?) in
let view: CardFormView = (viewRegistry![reactTag] as? CardFormView)!
view.blur()
}
}
}
|
bsd-3-clause
|
b041e7a5532c58cf65ce8bf4427a96d7
| 31.517241 | 100 | 0.615058 | 4.469194 | false | false | false | false |
spritekitbook/spritekitbook-swift
|
Chapter 14/Start/SpaceRunner/SpaceRunner/Player.swift
|
2
|
6082
|
//
// Player.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/31/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class Player: SKSpriteNode {
// MARK: - Private class constants
private let touchOffset:CGFloat = 44.0
private let moveFilter:CGFloat = 0.05 // Filter movement by 5%
// MARK: - Private class variables
private var targetPosition = CGPoint()
private var score = 0
private var streak = 0
private var lives = 3
private var immune = false
private var stars = 0
private var highStreak = 0
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(texture: SKTexture?, color: UIColor, size: CGSize) {
super.init(texture: texture, color: color, size: size)
}
convenience init() {
let texture = GameTextures.sharedInstance.texture(name: SpriteName.player)
self.init(texture: texture, color: SKColor.white, size: texture.size())
setup()
setupPhysics()
self.name = "Player"
}
private func setup() {
// Initial position is centered horizontally and 20% up the Y axis
self.position = CGPoint(x: kViewSize.width / 2, y: kViewSize.height * 0.2)
targetPosition = self.position
}
private func setupPhysics() {
self.physicsBody = SKPhysicsBody(circleOfRadius: self.size.width / 2, center: self.anchorPoint)
self.physicsBody?.categoryBitMask = Contact.player
self.physicsBody?.collisionBitMask = 0x0
self.physicsBody?.contactTestBitMask = Contact.meteor | Contact.star
}
// MARK: - Update
func update() {
move()
}
// MARK: - Movement
func updateTargetPosition(position: CGPoint) {
targetPosition = CGPoint(x: position.x, y: position.y + touchOffset)
}
private func move() {
let newX = Smooth(startPoint: self.position.x, endPoint: targetPosition.x, percentToMove: moveFilter)
let newY = Smooth(startPoint: self.position.y, endPoint: targetPosition.y, percentToMove: moveFilter)
// "Clamp" the minimum and maximum X value to allow half the ship to go offscreen horizontally
let correctedX = Clamp(value: newX, min: 0 - self.size.width / 2, max: kViewSize.width + self.size.width / 2)
// "Clamp" the minimum and maximum Y value to not allow the ship to go off screen vertically
let correctedY = Clamp(value: newY, min: 0 + self.size.height, max: kViewSize.height - self.size.height)
self.position = CGPoint(x: correctedX, y: correctedY)
rotate()
}
private func rotate() {
if DistanceBetweenPoints(firstPoint: self.position, secondPoint: targetPosition) > 25 {
let angle = AngleBetweenPoints(targetPosition: targetPosition, currentPosition: self.position)
self.run(SKAction.rotate(toAngle: angle, duration: 0.16, shortestUnitArc: true))
} else {
let angle:CGFloat = 0.0
self.run(SKAction.rotate(toAngle: angle, duration: 0.16, shortestUnitArc: true))
}
}
// MARK: - Actions
private func blinkPlayer() {
let blink = SKAction.sequence([SKAction.fadeOut(withDuration: 0.15), SKAction.fadeIn(withDuration: 0.15)])
self.run(SKAction.repeatForever(blink), withKey: "Blink")
}
// MARK: - Contact
func contact(body: String) {
lives -= 1
streak = 0
self.run(GameAudio.sharedInstance.playClip(type: .explosion))
if lives > 0 {
immune = true
blinkPlayer()
self.run(GameAudio.sharedInstance.playClip(type: .shieldUp))
self.run(SKAction.wait(forDuration: 3.0), completion: {
[weak self] in
self?.immune = false
self?.removeAction(forKey: "Blink")
self?.run(GameAudio.sharedInstance.playClip(type: .shieldDown))
})
}
if kDebug {
print("Player made contact with \(body).")
}
}
func getLives() -> Int {
return lives
}
func getImmunity() -> Bool {
return immune
}
func getScore() -> Int {
return score
}
func getStars() -> Int {
return stars
}
func getStreak() -> Int {
return highStreak
}
// MARK: - Score
private func increaseScore(bonus: Int) {
score += bonus
if kDebug {
print("Score: \(score)")
}
}
func pickup() {
streak += 1
stars += 1
self.run(GameAudio.sharedInstance.playClip(type: .pickup))
if streak >= highStreak {
highStreak = streak
}
switch streak {
case 0...5:
increaseScore(bonus: 250)
case 6...10:
increaseScore(bonus: 500)
case 11...15:
increaseScore(bonus: 750)
case 16...20:
increaseScore(bonus: 1000)
default:
increaseScore(bonus: 5000)
}
}
func updateDistanceScore() {
score += 1
if kDebug {
print("Score: \(score)")
}
}
func gameOver() {
saveScore()
}
private func saveScore() {
if score > GameSettings.sharedInstance.getBestScore() {
GameSettings.sharedInstance.saveBestScore(score: score)
}
if stars > GameSettings.sharedInstance.getBestStars() {
GameSettings.sharedInstance.saveBestStars(stars: stars)
}
if highStreak > GameSettings.sharedInstance.getBestStreak() {
GameSettings.sharedInstance.saveBestStreak(streak: highStreak)
}
}
}
|
apache-2.0
|
d1a85b5340bad4e311216d567bcb9ba5
| 27.683962 | 117 | 0.565039 | 4.631379 | false | false | false | false |
LiuSky/XBKit
|
Sources/Extension/UIButton+.swift
|
1
|
7206
|
//
// UIButton+.swift
// XBKit
//
// Created by xiaobin liu on 2017/3/21.
// Copyright © 2017年 Sky. All rights reserved.
//
import UIKit
import Foundation
// MARK: - UIButton+Alignment
extension UIButton: NamespaceWrappable { }
public extension TypeWrapperProtocol where WrappedType: UIButton {
public func titleImageHorizontalAlignmentwith(_ space: Int) {
self.resetEdgeInsets()
wrappedValue.setNeedsLayout()
wrappedValue.layoutIfNeeded()
let contentRect = wrappedValue.contentRect(forBounds: wrappedValue.bounds)
let titleSize = wrappedValue.titleRect(forContentRect: contentRect).size
let imageSize = wrappedValue.imageRect(forContentRect: contentRect).size
wrappedValue.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGFloat(space))
wrappedValue.titleEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width, 0, imageSize.width)
wrappedValue.imageEdgeInsets = UIEdgeInsetsMake(0, titleSize.width+CGFloat(space), 0, -titleSize.width-CGFloat(space))
}
public func imageTitleHorizontalAlignmentWith(_ space: Int) {
self.resetEdgeInsets()
wrappedValue.titleEdgeInsets = UIEdgeInsetsMake(0, CGFloat(space), 0, -CGFloat(space))
wrappedValue.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, CGFloat(space))
}
public func titleImageVerticalAlignmentWith(_ space: Int) {
self.verticalAlignmentWithTitle(true, space: space)
}
public func imageTitleVerticalAlignmentWith(_ space: Int) {
self.verticalAlignmentWithTitle(false, space: space)
}
fileprivate func verticalAlignmentWithTitle(_ isTop: Bool, space: Int) {
self.resetEdgeInsets()
wrappedValue.setNeedsLayout()
wrappedValue.layoutIfNeeded()
let contentRect = wrappedValue.contentRect(forBounds: wrappedValue.bounds)
let titleSize = wrappedValue.titleRect(forContentRect: contentRect).size
let imageSize = wrappedValue.imageRect(forContentRect: contentRect).size
let halfWidth = (titleSize.width + imageSize.width)/2
let halfHeight = (titleSize.height + imageSize.height)/2
let topInset = min(halfHeight, titleSize.height)
let leftInset = (titleSize.width - imageSize.width)>0 ? (titleSize.width - imageSize.width)/2 : 0
let bottomInset = (titleSize.height - imageSize.height)>0 ? (titleSize.height - imageSize.height)/2 : 0
let rightInset = min(halfWidth, titleSize.width)
if isTop {
wrappedValue.titleEdgeInsets = UIEdgeInsetsMake(-halfHeight-CGFloat(space), -halfWidth, halfHeight+CGFloat(space), halfWidth)
wrappedValue.contentEdgeInsets = UIEdgeInsetsMake(topInset+CGFloat(space), leftInset, -bottomInset, -rightInset)
} else {
wrappedValue.titleEdgeInsets = UIEdgeInsetsMake(halfHeight+CGFloat(space), -halfWidth, -halfHeight-CGFloat(space), halfWidth)
wrappedValue.contentEdgeInsets = UIEdgeInsetsMake(-bottomInset, leftInset, topInset+CGFloat(space), -rightInset)
}
}
fileprivate func resetEdgeInsets() {
wrappedValue.contentEdgeInsets = UIEdgeInsets.zero
wrappedValue.imageEdgeInsets = UIEdgeInsets.zero
wrappedValue.titleEdgeInsets = UIEdgeInsets.zero
}
}
// MARK: - Properties
public extension UIButton {
@IBInspectable
/// SwifterSwift: Image of disabled state for button; also inspectable from Storyboard.
public var imageForDisabled: UIImage? {
get {
return image(for: .disabled)
}
set {
setImage(newValue, for: .disabled)
}
}
@IBInspectable
/// SwifterSwift: Image of highlighted state for button; also inspectable from Storyboard.
public var imageForHighlighted: UIImage? {
get {
return image(for: .highlighted)
}
set {
setImage(newValue, for: .highlighted)
}
}
@IBInspectable
/// SwifterSwift: Image of normal state for button; also inspectable from Storyboard.
public var imageForNormal: UIImage? {
get {
return image(for: .normal)
}
set {
setImage(newValue, for: .normal)
}
}
@IBInspectable
/// SwifterSwift: Image of selected state for button; also inspectable from Storyboard.
public var imageForSelected: UIImage? {
get {
return image(for: .selected)
}
set {
setImage(newValue, for: .selected)
}
}
@IBInspectable
/// SwifterSwift: Title color of disabled state for button; also inspectable from Storyboard.
public var titleColorForDisabled: UIColor? {
get {
return titleColor(for: .disabled)
}
set {
setTitleColor(newValue, for: .disabled)
}
}
@IBInspectable
/// SwifterSwift: Title color of highlighted state for button; also inspectable from Storyboard.
public var titleColorForHighlighted: UIColor? {
get {
return titleColor(for: .highlighted)
}
set {
setTitleColor(newValue, for: .highlighted)
}
}
@IBInspectable
/// SwifterSwift: Title color of normal state for button; also inspectable from Storyboard.
public var titleColorForNormal: UIColor? {
get {
return titleColor(for: .normal)
}
set {
setTitleColor(newValue, for: .normal)
}
}
@IBInspectable
/// SwifterSwift: Title color of selected state for button; also inspectable from Storyboard.
public var titleColorForSelected: UIColor? {
get {
return titleColor(for: .selected)
}
set {
setTitleColor(newValue, for: .selected)
}
}
@IBInspectable
/// SwifterSwift: Title of disabled state for button; also inspectable from Storyboard.
public var titleForDisabled: String? {
get {
return title(for: .disabled)
}
set {
setTitle(newValue, for: .disabled)
}
}
@IBInspectable
/// SwifterSwift: Title of highlighted state for button; also inspectable from Storyboard.
public var titleForHighlighted: String? {
get {
return title(for: .highlighted)
}
set {
setTitle(newValue, for: .highlighted)
}
}
@IBInspectable
/// SwifterSwift: Title of normal state for button; also inspectable from Storyboard.
public var titleForNormal: String? {
get {
return title(for: .normal)
}
set {
setTitle(newValue, for: .normal)
}
}
@IBInspectable
/// SwifterSwift: Title of selected state for button; also inspectable from Storyboard.
public var titleForSelected: String? {
get {
return title(for: .selected)
}
set {
setTitle(newValue, for: .selected)
}
}
}
|
mit
|
dd468516937a0b855bec4046dd6554ae
| 30.731278 | 137 | 0.626406 | 5.215786 | false | false | false | false |
muhrusdi/projecttaklim
|
Sources/App/Controllers/UserController.swift
|
1
|
3130
|
import Vapor
import HTTP
import Foundation
final class UserController {
let droplet: Droplet
init() {
droplet = Droplet()
}
func login(_ request: Request) throws -> ResponseRepresentable {
guard let email = request.data["email"]?.string, let password = request.data["password"]?.string else {
throw Abort.badRequest
}
let hash = try droplet.hash.make(password)
guard let user = try User.query().filter("email", .equals, email).filter("hash", .equals, hash).first() else {
return try Response(status: .unauthorized, json: JSON(node:["message": "Email/password salah"]))
}
return try Response(status: .ok, json: JSON(node: user))
}
func register(_ request: Request) throws -> ResponseRepresentable {
guard let firstName = request.multipart?["firstName"]?.string,
let lastName = request.multipart?["lastName"]?.string,
let email = request.multipart?["email"]?.string,
let password = request.multipart?["password"]?.string,
let avatar = request.multipart?["image"]?.file else {
throw Abort.badRequest
}
let hash = try drop.hash.make(password)
var user = User(firstName: firstName, lastName: lastName, email: email, hash: hash, avatar: getImagePath(img: avatar))
guard try User.query().filter("email", user.email).first() == nil else {
return try Response(status: .conflict, json: JSON(node: ["message": "Email sudah ada"]))
}
user.createdAt = "\(Date())"
user.updatedAt = "\(Date())"
try user.save()
return try Response(status: .ok, json: JSON(node: user))
}
func getUser(_ request: Request) throws -> ResponseRepresentable {
guard let id = request.parameters["id"]?.string else {
throw Abort.badRequest
}
guard let user = try User.query().filter("_id", id).first() else {
throw Abort.notFound
}
return user
}
private func getImagePath(img: Multipart.File) -> String {
let data = Data(bytes: img.data)
let fileManager = FileManager.default
var dir: String!
if img.type! == "image/jpg" {
dir = "Public/images/\(img.name!)" + ".jpg"
} else if img.type! == "image/png" {
dir = "Public/images/\(img.name!)" + ".png"
} else if img.type! == "image/jpeg" {
dir = "Public/images/\(img.name!)" + ".jpeg"
}
let dirPath = drop.workDir + dir
fileManager.createFile(atPath: dirPath, contents: data, attributes: ["name": img.name!, "type": img.type!])
if fileManager.fileExists(atPath: dirPath) {
} else {
fileManager.createFile(atPath: dirPath, contents: data, attributes: ["name": img.name!, "type": img.type!])
}
print(img.type, img.name)
return dir
//>>>>>>> 1387b714e55a41608403452b3b37825657916ca9
}
}
|
bsd-3-clause
|
2e3deb49907a2f72af5f545dfa3d9cdd
| 34.977011 | 126 | 0.566773 | 4.408451 | false | false | false | false |
groovelab/SwiftBBS
|
SwiftBBS/SwiftBBS Server/OAuthHandler.swift
|
1
|
8025
|
//
// AuthHandler.swift
// SwiftBBS
//
// Created by Takeo Namba on 2016/02/08.
// Copyright GrooveLab
//
import PerfectLib
import cURL
class OAuthHandler : BaseRequestHandler {
private let OAuthStateSessionKey = "oauth_state"
private lazy var googleOAuthClient: GoogleOAuthClient = GoogleOAuthClient(clientId: Config.googleClientId, clientSecret: Config.googleClientSecret)
private lazy var googleRedirectUri: String = (self.request.isHttps() ? "https" : "http") + "://\(self.request.httpHost())/oauth/google_callback"
private lazy var facebookOAuthClient: FacebookOAuthClient = FacebookOAuthClient(clientId: Config.facebookAppId, clientSecret: Config.facebookAppSecret)
private lazy var facebookRedirectUri: String = (self.request.isHttps() ? "https" : "http") + "://\(self.request.httpHost())/oauth/facebook_callback"
private lazy var githubOAuthClient: GithubOAuthClient = GithubOAuthClient(clientId: Config.gitHubClientId, clientSecret: Config.gitHubClientSecret)
private lazy var lineOAuthClient: LineOAuthClient = LineOAuthClient(clientId: Config.lineChannelId, clientSecret: Config.lineChannelSecret)
private lazy var lineRedirectUri: String = (self.request.isHttps() ? "https" : "http") + "://\(self.request.httpHost())/oauth/line_callback"
// MARK: life cycle
override init() {
super.init()
// define action acl
// needLoginActions = []
// redirectUrlIfNotLogin = "/"
noNeedLoginActions = ["github", "githubCallback", "facebook", "facebookCallback", "google", "googleCallback", "line", "lineCallback"]
redirectUrlIfLogin = "/bbs"
}
override func dispatchAction(action: String) throws -> ActionResponse {
switch request.action {
case "github":
return try githubAction()
case "github_callback":
return try githubCallbackAction()
case "facebook":
return try facebookAction()
case "facebook_callback":
return try facebookCallbackAction()
case "google":
return try googleAction()
case "google_callback":
return try googleCallbackAction()
case "line":
return try lineAction()
case "line_callback":
return try lineCallbackAction()
default:
return .Redirect(url: "/")
}
}
// MARK: actions
func googleAction() throws -> ActionResponse {
prepareForOauth(googleOAuthClient.state)
let authUrl = googleOAuthClient.authUrl(googleRedirectUri)
return .Redirect(url: authUrl)
}
func googleCallbackAction() throws -> ActionResponse {
guard let state = request.param("state") else {
return .Error(status: 500, message:"can not get google state")
}
guard let code = request.param("code") else {
return .Error(status: 500, message:"can not get google code")
}
if !validateState(state) {
return .Error(status: 500, message:"invalid google state")
}
do {
let socialUser = try googleOAuthClient.getSocialUser(code: code, extraData: googleRedirectUri)
try loign(socialUser: socialUser, provider: .Google)
return .Redirect(url: "/user/mypage")
} catch OAuthClientError.Fail(let message) {
return .Error(status: 500, message: message)
}
}
func facebookAction() throws -> ActionResponse {
prepareForOauth(facebookOAuthClient.state)
let authUrl = facebookOAuthClient.authUrl(facebookRedirectUri)
return .Redirect(url: authUrl)
}
func facebookCallbackAction() throws -> ActionResponse {
guard let state = request.param("state") else {
return .Error(status: 500, message:"can not get google state")
}
guard let code = request.param("code") else {
return .Error(status: 500, message:"can not get google code")
}
if !validateState(state) {
return .Error(status: 500, message:"invalid google state")
}
do {
let socialUser = try facebookOAuthClient.getSocialUser(code: code, extraData: facebookRedirectUri)
try loign(socialUser: socialUser, provider: .Facebook)
return .Redirect(url: "/user/mypage")
} catch OAuthClientError.Fail(let message) {
return .Error(status: 500, message: message)
}
}
func githubAction() throws -> ActionResponse {
prepareForOauth(githubOAuthClient.state)
let authUrl = githubOAuthClient.authUrl()
return .Redirect(url: authUrl)
}
func githubCallbackAction() throws -> ActionResponse {
guard let state = request.param("state") else {
return .Error(status: 500, message:"can not get google state")
}
guard let code = request.param("code") else {
return .Error(status: 500, message:"can not get google code")
}
if !validateState(state) {
return .Error(status: 500, message:"invalid google state")
}
do {
let socialUser = try githubOAuthClient.getSocialUser(code: code)
try loign(socialUser: socialUser, provider: .Github)
return .Redirect(url: "/user/mypage")
} catch OAuthClientError.Fail(let message) {
return .Error(status: 500, message: message)
}
}
func lineAction() throws -> ActionResponse {
prepareForOauth(lineOAuthClient.state)
let authUrl = lineOAuthClient.authUrl(lineRedirectUri)
return .Redirect(url: authUrl)
}
func lineCallbackAction() throws -> ActionResponse {
guard let state = request.param("state") else {
return .Error(status: 500, message:"can not get google state")
}
guard let code = request.param("code") else {
return .Error(status: 500, message:"can not get google code")
}
if !validateState(state) {
return .Error(status: 500, message:"invalid google state")
}
do {
let socialUser = try lineOAuthClient.getSocialUser(code: code)
try loign(socialUser: socialUser, provider: .Line)
return .Redirect(url: "/user/mypage")
} catch OAuthClientError.Fail(let message) {
return .Error(status: 500, message: message)
}
}
// TODO: create UserService with social login method
private func loign(socialUser socialUser: OAuthSocialUser, provider: UserProvider) throws {
// check if already stored provider user id in user table
if let userEntity = try userRepository.findByProviderId(socialUser.id, provider: provider), userId = userEntity.id {
// update user data
let userEntity = UserEntity(id: userId, provider: provider, providerUserId: socialUser.id, providerUserName: socialUser.name)
try userRepository.update(userEntity)
// login
session["id"] = String(userId) // TODO: create method
} else {
// store provider user id into user table
let userEntity = UserEntity(id: nil, provider: provider, providerUserId: socialUser.id, providerUserName: socialUser.name)
let userId = try userRepository.insert(userEntity)
// login
session["id"] = String(userId)
}
}
private func prepareForOauth(state: String) {
session[OAuthStateSessionKey] = state
}
private func validateState(state: String) -> Bool {
guard let stateInSession = session[OAuthStateSessionKey] as? String else { return false }
session[OAuthStateSessionKey] = nil
return state == stateInSession
}
}
|
mit
|
8820f877b60b60589ab2f36de2fe5e52
| 38.146341 | 155 | 0.621184 | 4.59622 | false | false | false | false |
jhabbbbb/ClassE
|
ClassE/BarrageView.swift
|
1
|
7037
|
//
// BarrageView.swift
// ClassE
//
// Created by JinHongxu on 2016/12/15.
// Copyright © 2016年 JinHongxu. All rights reserved.
//
import UIKit
import SocketIO
import SnapKit
enum BarrageViewStyle {
case white
case black
}
class BarrageView: UIView, SocketManagerDelegate, CAAnimationDelegate {
let statusLabel = UILabel()
let reconnectButton = UIButton()
convenience init(style: BarrageViewStyle = .white) {
self.init()
SocketManager.shared.delegate = self
self.addSubview(statusLabel)
self.addSubview(reconnectButton)
statusLabel.text = "正在连接弹幕服务器..."
switch style {
case .black:
statusLabel.textColor = UIColor.black
case .white:
statusLabel.textColor = UIColor.white
}
statusLabel.snp.makeConstraints {
make in
make.bottom.equalTo(self).offset(-8)
make.left.equalTo(self).offset(8)
make.width.equalTo(200)
make.height.equalTo(16)
}
switch style {
case .black:
reconnectButton.setImage(UIImage(named: "ic_refresh") , for: .normal)
case .white:
reconnectButton.setImage(UIImage(named: "ic_refresh_white") , for: .normal)
}
reconnectButton.addTarget(self, action: #selector(connectSocket), for: .touchUpInside)
reconnectButton.snp.makeConstraints{
make in
make.top.equalTo(self).offset(8)
make.right.equalTo(self).offset(-8)
make.width.equalTo(40)
make.height.equalTo(40)
}
}
func connectSocket() {
self.statusLabel.text = "正在连接弹幕服务器..."
self.statusLabel.alpha = 1
SocketManager.shared.reconnect()
}
func SocketDidConnect() {
print("socket connected")
self.statusLabel.text = "弹幕服务器连接成功"
UIView.animate(withDuration: 0.6, delay: 0.6, options: .curveLinear, animations: {
self.statusLabel.alpha = 0
}, completion: nil)
}
func SocketDidReciveMessage(message: String) {
let label: UILabel = UILabel(frame: CGRect(x: 375, y: Int(arc4random()%530)/25*25, width: 100, height: 25))
if message == "like" {
likeAnimation()
} else {
label.text = message
label.textColor = UIColor.white
label.shadowColor = UIColor.black
label.shadowOffset = CGSize(width: 1, height: 1)
label.sizeToFit()
self.addSubview(label)
UIView.animate(withDuration: 2, delay: 0, options: .curveLinear, animations: {
label.frame.origin.x -= label.frame.size.width+375
}, completion: { flag in
label.removeFromSuperview()
})
}
}
//飘心动画
func likeAnimation() {
var tagNumber: Int = 500000
tagNumber+=1
let image = UIImage.init(named: randomImageName())
let imageView = UIImageView.init(image: image)
imageView.center = CGPoint(x: -5000, y :-5000)
imageView.tag = tagNumber
self.addSubview(imageView)
let group = groupAnimation()
group.setValue(tagNumber, forKey: "animationName")
imageView.layer.add(group, forKey: "wendingding")
}
func groupAnimation() -> CAAnimationGroup{
let group = CAAnimationGroup.init()
group.duration = 2.0;
group.repeatCount = 1;
let animation = scaleAnimation()
let keyAnima = positionAnimatin()
let alphaAnimation = alphaAnimatin()
group.animations = [animation, keyAnima, alphaAnimation]
group.delegate = self;
return group
}
func scaleAnimation() -> CABasicAnimation {
// 设定为缩放
let animation = CABasicAnimation.init(keyPath: "transform.scale")
// 动画选项设定
animation.duration = 0.5// 动画持续时间
// animation.autoreverses = NO; // 动画结束时执行逆动画
animation.isRemovedOnCompletion = false
// 缩放倍数
animation.fromValue = 0.1 // 开始时的倍率
animation.toValue = 1.0 // 结束时的倍率
return animation
}
func positionAnimatin() -> CAKeyframeAnimation {
let keyAnima=CAKeyframeAnimation.init()
keyAnima.keyPath="position"
//1.1告诉系统要执行什么动画
//创建一条路径
let path = CGMutablePath()
//设置一个圆的路径
// CGPathAddEllipseInRect(path, NULL, CGRectMake(150, 100, 100, 100));
path.move(to: CGPoint(x: 333, y: 560))
let controlX = Int((arc4random() % (100 + 1))) - 50
let controlY = Int((arc4random() % (130 + 1))) + 50
let entX = Int((arc4random() % (100 + 1))) - 50
//CGPathAddQuadCurveToPoint(path, nil, CGFloat(200 - controlX), CGFloat(200 - controlY), CGFloat(200 + entX), 200 - 260)
path.addQuadCurve(to: CGPoint(x: CGFloat(333 - controlX), y: CGFloat(200 - controlY)), control: CGPoint(x: CGFloat(200 + entX), y:200 - 260))
keyAnima.path=path;
//有create就一定要有release, ARC自动管理
// CGPathRelease(path);
//1.2设置动画执行完毕后,不删除动画
keyAnima.isRemovedOnCompletion = false
//1.3设置保存动画的最新状态
keyAnima.fillMode=kCAFillModeForwards
//1.4设置动画执行的时间
keyAnima.duration=2.0
//1.5设置动画的节奏
keyAnima.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionLinear)
return keyAnima
}
func alphaAnimatin() -> CABasicAnimation {
let alphaAnimation = CABasicAnimation.init(keyPath: "opacity")
// 动画选项设定
alphaAnimation.duration = 1.5 // 动画持续时间
alphaAnimation.isRemovedOnCompletion = false
alphaAnimation.fromValue = 1.0
alphaAnimation.toValue = 0.1
alphaAnimation.timingFunction = CAMediaTimingFunction.init(name: kCAMediaTimingFunctionEaseIn)
alphaAnimation.beginTime = 0.5
return alphaAnimation
}
func randomImageName() -> String {
let number = Int(arc4random() % (4 + 1));
var randomImageName: String
switch (number) {
case 1:
randomImageName = "bHeart"
break;
case 2:
randomImageName = "gHeart"
break;
case 3:
randomImageName = "rHeart"
break;
case 4:
randomImageName = "yHeart"
break;
default:
randomImageName = "bHeart"
break;
}
return randomImageName
}
}
|
mit
|
b8c696562fc4ed264f582418118c4ed9
| 30.641509 | 149 | 0.576923 | 4.445328 | false | false | false | false |
BareFeetWare/BFWControls
|
BFWControls/Modules/Alert/View/AlertViewOverlay.swift
|
2
|
2961
|
//
// AlertViewOverlay.swift
// BFWControls
//
// Created by Tom Brodhurst-Hill on 19/04/2016.
// Copyright © 2016 BareFeetWare.
// Free to use at your own risk, with acknowledgement to BareFeetWare.
//
import UIKit
@IBDesignable open class AlertViewOverlay: NibView {
// MARK: - IBOutlets
@objc open lazy var alertView: AlertView! = {
return self.subviews.first { subview in
subview is AlertView
} as? AlertView
}()
// MARK: - Variables mapping to AlertView variables
@IBInspectable open var title: String? {
get {
return alertView.title
}
set {
alertView.title = newValue
}
}
@IBInspectable open var message: String? {
get {
return alertView.message
}
set {
alertView.message = newValue
}
}
@IBInspectable open var hasCancel: Bool {
get {
return alertView.hasCancel
}
set {
alertView.hasCancel = newValue
}
}
@IBInspectable open var button0Title: String? {
get {
return alertView.button0Title
}
set {
alertView.button0Title = newValue
}
}
@IBInspectable open var button1Title: String? {
get {
return alertView.button1Title
}
set {
alertView.button1Title = newValue
}
}
@IBInspectable open var button2Title: String? {
get {
return alertView.button2Title
}
set {
alertView.button2Title = newValue
}
}
@IBInspectable open var button3Title: String? {
get {
return alertView.button3Title
}
set {
alertView.button3Title = newValue
}
}
@IBInspectable open var button4Title: String? {
get {
return alertView.button4Title
}
set {
alertView.button4Title = newValue
}
}
@IBInspectable open var button5Title: String? {
get {
return alertView.button5Title
}
set {
alertView.button5Title = newValue
}
}
@IBInspectable open var button6Title: String? {
get {
return alertView.button6Title
}
set {
alertView.button6Title = newValue
}
}
@IBInspectable open var button7Title: String? {
get {
return alertView.button7Title
}
set {
alertView.button7Title = newValue
}
}
@IBInspectable open var maxHorizontalButtonTitleCharacterCount: Int {
get {
return alertView.maxHorizontalButtonTitleCharacterCount
}
set {
alertView.maxHorizontalButtonTitleCharacterCount = newValue
}
}
}
|
mit
|
e4da20f5e50d525ae7903234504b13a6
| 21.424242 | 73 | 0.53277 | 5.121107 | false | false | false | false |
LDlalala/LDZBLiving
|
LDZBLiving/LDZBLiving/Classes/Live/GiftView/LDGiftListView.swift
|
1
|
2921
|
//
// LDGiftListView.swift
// LDZBLiving
//
// Created by 李丹 on 17/8/19.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
private let cellID = "LDGiftViewCell"
class LDGiftListView: UIView , NibLoadable{
// MARK: 控件属性
@IBOutlet weak var giftView: UIView!
@IBOutlet weak var sendGiftBtn: UIButton!
var giftVM : LDGiftViewModel = LDGiftViewModel()
var pageCollectionView : LDPageCollectionView!
}
// MARK:- 初始化子控件
extension LDGiftListView{
override func awakeFromNib() {
super.awakeFromNib()
// 初始化子控件
setupUI()
// 加载礼物数据
loadGiftDatas()
}
private func setupUI(){
let frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height)
let layout = LDPageCollectionViewLayout()
layout.cols = 4
layout.row = 2
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let style = LDPageStyle()
let pageCollectionView = LDPageCollectionView(frame: frame, titles: ["热门", "高级", "豪华", "专属"], isTitleInTop: false, layout: layout, style: style)
pageCollectionView.dataSource = self
pageCollectionView.delegate = self
addSubview(pageCollectionView)
// 注册cell
pageCollectionView.register(nib: UINib(nibName: "LDGiftViewCell", bundle: nil), identifier: cellID)
}
private func loadGiftDatas(){
giftVM.loadGiftDatas {
self.pageCollectionView.reloadData()
}
}
}
// MARK:- 送礼物
extension LDGiftListView {
@IBAction func sendGiftBtnClick() {
}
}
// MARK:- 实现代理方法
extension LDGiftListView : LDPageCollectionViewDelegate{
func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let giftModel = giftVM.giftlistDatas[indexPath.section].list[indexPath.item]
print(giftModel)
}
}
// MARK:- 实现数据源方法
extension LDGiftListView : LDPageCollectionViewDataSource{
func numberOfSections(in pageCollectionView: LDPageCollectionView) -> Int {
return giftVM.giftlistDatas.count
}
func collectionView(_ pageCollectionView: LDPageCollectionView, numberOfItemsInSection section: Int) -> Int {
return giftVM.giftlistDatas[section].list.count
}
func collectionView(_ pageCollectionView: LDPageCollectionView, _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! LDGiftViewCell
cell.giftModel = giftVM.giftlistDatas[indexPath.section].list[indexPath.item]
return cell
}
}
|
mit
|
1e858d5fe542ca28509d3f7810d72973
| 26.90099 | 165 | 0.666785 | 4.720268 | false | false | false | false |
prolificinteractive/Bellerophon
|
Bellerophon/BellerophonTests/MockBPManager.swift
|
1
|
1564
|
//
// MockBPManager.swift
// Bellerophon
//
// Created by Shiyuan Jiang on 4/27/16.
// Copyright © 2016 Prolific Interactive. All rights reserved.
//
@testable import Bellerophon
class MockBPManager: BellerophonManager {
var displayKillSwitchIsCalled: Bool!
var displayForceUpdateIsCalled: Bool!
var startAutoCheckingIsCalled: Bool!
var dismissKillSwitchIfNeededIsCalled: Bool!
var displayForceUpdateFunctionIsCalled: Bool!
var displayKillSwitchFunctionIsCalled: Bool!
var updateDisplayIsCalled: Bool!
override func displayWindow(for event: BellerophonEvent) {
switch event {
case .killSwitch:
displayKillSwitchIsCalled = true
displayForceUpdateIsCalled = false
case .forceUpdate:
displayForceUpdateIsCalled = true
displayKillSwitchIsCalled = false
}
}
override func updateDisplay(_ status: BellerophonObservable) {
updateDisplayIsCalled = true
super.updateDisplay(status)
}
override func displayForceUpdate() {
displayForceUpdateFunctionIsCalled = true
super.displayForceUpdate()
}
override func displayKillSwitch() {
displayKillSwitchFunctionIsCalled = true
super.displayKillSwitch()
}
override func startAutoChecking(_ status: BellerophonObservable) {
startAutoCheckingIsCalled = true
}
override func dismissKillSwitchIfNeeded() {
dismissKillSwitchIfNeededIsCalled = true
super.dismissKillSwitchIfNeeded()
}
}
|
mit
|
e1f4b5a3d45d9da33b669ef37fc1785a
| 26.910714 | 70 | 0.698017 | 4.736364 | false | false | false | false |
AndreMuis/Algorithms
|
QueueViaStacks.playground/Contents.swift
|
1
|
1679
|
//
// Implement a queue via stacks
//
import Foundation
struct Stack
{
private var numbers : [Int]
var isEmpty : Bool
{
return self.numbers.isEmpty
}
init()
{
self.numbers = [Int]()
}
func peek() -> Int?
{
let number : Int? = self.numbers.last
return number
}
mutating func push(number : Int)
{
self.numbers.append(number)
}
mutating func pop() -> Int
{
let number : Int = self.numbers.removeLast()
return number
}
}
struct Queue
{
var newestStack : Stack
var oldestStack : Stack
init()
{
self.newestStack = Stack()
self.oldestStack = Stack()
}
mutating func enqueue(number : Int)
{
self.newestStack.push(number)
}
mutating func peek() -> Int?
{
self.moveNewestToOldest()
let number : Int? = self.oldestStack.peek()
return number
}
mutating func dequeue() -> Int
{
self.moveNewestToOldest()
let number : Int = self.oldestStack.pop()
return number
}
mutating func moveNewestToOldest()
{
if self.oldestStack.isEmpty == true
{
while self.newestStack.isEmpty == false
{
self.oldestStack.push(self.newestStack.pop())
}
}
}
}
var queue : Queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.peek()
queue.enqueue(3)
queue.enqueue(4)
queue.peek()
queue.dequeue()
queue.dequeue()
queue.enqueue(5)
queue.dequeue()
queue.dequeue()
queue.dequeue()
|
mit
|
96d4889ae00f44870a4900ef632335f4
| 13.6 | 61 | 0.531269 | 4.065375 | false | false | false | false |
Drusy/auvergne-webcams-ios
|
AuvergneWebcams/QuickActionsService.swift
|
1
|
6346
|
//
// QuickActionsService.swift
// AuvergneWebcams
//
// Created by Alexandre Caillot on 12/06/2017.
//
//
import Foundation
import RealmSwift
enum QuickActionsEnum {
case add
case delete
}
class QuickActionsService {
static let shared = QuickActionsService()
private init() { }
let defaultTypePrefix = "fr.openium.AuvergneWebcams.quickAction."
lazy var realm: Realm = {
return try! Realm()
}()
let maxFav: Int = 4
let maxQuickActionItem: Int = 4
let containsKey = "Contains"
let indexKey = "Index"
func registerQuickActions() {
guard UIApplication.shared.shortcutItems?.isEmpty ?? false else { return }
var shortcutItems = Array<UIApplicationShortcutItem>()
let favoriteWebcams = WebcamManager.shared.favoriteWebcams().prefix(maxFav)
for fwb in favoriteWebcams {
let type = QuickActionsService.shared.defaultTypePrefix + "\(fwb.uid)"
if let title = fwb.title {
let shortcutItem: UIApplicationShortcutItem
if #available(iOS 9.1, *) {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .favorite), userInfo: nil)
} else {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: nil, userInfo: nil)
}
shortcutItems.append(shortcutItem)
}
}
UIApplication.shared.shortcutItems = shortcutItems
}
func performActionFor(shortcutItem: UIApplicationShortcutItem, for root: UINavigationController, animated: Bool = true) {
if shortcutItem.type.contains(QuickActionsService.shared.defaultTypePrefix) {
guard let idString = shortcutItem.type.components(separatedBy: ".").last,
let id = Int(idString),
let webcam = realm.object(ofType: Webcam.self, forPrimaryKey: id)
else {
return
}
let webcamDetailViewController = WebcamDetailViewController(webcam: webcam)
root.popToRootViewController(animated: false)
root.pushViewController(webcamDetailViewController, animated: animated)
}
}
func quickActionEdit(webcam: Webcam, value: QuickActionsEnum) {
guard let shortcutItems: Array<UIApplicationShortcutItem> = UIApplication.shared.shortcutItems else { return }
if webcam.favorite && shortcutItems.count < 4 {
quickActionsFavorite(webcam: webcam, value: value)
} else {
quickActionsRecent(webcam: webcam, value: value)
}
}
// MARK: - Private
private func quickActionsFavorite(webcam: Webcam, value: QuickActionsEnum) {
guard var shortcutItems: Array<UIApplicationShortcutItem> = UIApplication.shared.shortcutItems else { return }
let type = QuickActionsService.shared.defaultTypePrefix + "\(webcam.uid)"
if let title = webcam.title {
let shortcutItem: UIApplicationShortcutItem
if #available(iOS 9.1, *) {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .favorite), userInfo: nil)
} else {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: nil, userInfo: nil)
}
switch value {
case .add:
shortcutItems = removeRecentQuickAction(in: shortcutItems)
if !containsInQuickAction(webcam: webcam, in: shortcutItems) {
shortcutItems.append(shortcutItem)
}
case .delete:
if let index = shortcutItems.index(of: shortcutItem) {
shortcutItems.remove(at: index)
}
}
UIApplication.shared.shortcutItems = shortcutItems
}
}
private func quickActionsRecent(webcam: Webcam, value: QuickActionsEnum) {
guard var shortcutItems: Array<UIApplicationShortcutItem> = UIApplication.shared.shortcutItems else { return }
switch value {
case .add:
let type = QuickActionsService.shared.defaultTypePrefix + "\(webcam.uid)"
if let title = webcam.title {
let shortcutItem: UIApplicationShortcutItem
if #available(iOS 9.1, *) {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .time), userInfo: nil)
} else {
shortcutItem = UIApplicationShortcutItem(type: type, localizedTitle: title, localizedSubtitle: nil, icon: nil, userInfo: nil)
}
if !containsInQuickAction(webcam: webcam, in: shortcutItems) {
shortcutItems = removeRecentQuickAction(in: shortcutItems)
shortcutItems.insert(shortcutItem, at: 0)
}
}
case .delete:
shortcutItems.remove(at: 0)
}
UIApplication.shared.shortcutItems = shortcutItems
}
private func containsInQuickAction(webcam: Webcam, in array: Array<UIApplicationShortcutItem>) -> Bool {
let type = QuickActionsService.shared.defaultTypePrefix + "\(webcam.uid)"
for item in array {
if item.type == type {
return true
}
}
return false
}
private func removeRecentQuickAction(in array: Array<UIApplicationShortcutItem> ) -> Array<UIApplicationShortcutItem> {
var shortcutItems = array
for (index, shortcutItem) in shortcutItems.enumerated() {
if #available(iOS 9.1, *) {
if shortcutItem.icon == UIApplicationShortcutIcon(type: .time) {
shortcutItems.remove(at: index)
}
}
}
return shortcutItems
}
}
|
apache-2.0
|
2a965314374568e561249996b53d53b1
| 38.17284 | 184 | 0.602742 | 5.328296 | false | false | false | false |
bukoli/bukoli-ios
|
Bukoli/Classes/Cells/BukoliPointDialogCell.swift
|
1
|
3250
|
//
// BukoliPointDialogCell.swift
// Pods
//
// Created by Utku Yildirim on 19/10/2016.
//
//
import Foundation
class BukoliPointDialogCell: UICollectionViewCell {
@IBOutlet weak var closeView: UIView!
@IBOutlet weak var pointImageView: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var addressLabel: UILabel!
@IBOutlet weak var workingHoursLabel: UILabel!
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var indexView: UIView!
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var saveButton: UIButton!
var bukoliDetailDialog: BukoliDetailDialog!
var bukoliPoint: BukoliPoint! {
didSet {
pointImageView.af_setImage(withURL: URL(string: bukoliPoint.smallImageUrl)!)
indexLabel.text = "\(index+1)"
nameLabel.text = bukoliPoint.name
addressLabel.text = bukoliPoint.address
workingHoursLabel.text = bukoliPoint.workingHours?.readable()
distanceLabel.text = String(format: "%.0f m", arguments: [bukoliPoint.distance])
indexView.layer.cornerRadius = 11
indexView.layer.masksToBounds = true
if bukoliPoint.isLocker! {
indexLabel.textColor = UIColor.white
indexView.backgroundColor = UIColor(hex: 0xFF31AADE).lighter()
saveButton.setTitleColor(UIColor.white, for: .normal)
saveButton.backgroundColor = UIColor(hex: 0xFF31AADE)
saveButton.layer.borderColor = UIColor(hex: 0xFF31AADE).darker().cgColor
}
else {
indexLabel.textColor = Bukoli.sharedInstance.buttonTextColor
indexView.backgroundColor = Bukoli.sharedInstance.buttonBackgroundColor.lighter()
saveButton.setTitleColor(Bukoli.sharedInstance.buttonTextColor, for: .normal)
saveButton.backgroundColor = Bukoli.sharedInstance.buttonBackgroundColor
saveButton.layer.borderColor = Bukoli.sharedInstance.buttonBackgroundColor.darker().cgColor
}
}
}
var index: Int!
// MARK: - Actions
@IBAction func save(_ sender: AnyObject) {
Bukoli.sharedInstance.bukoliPoint = bukoliPoint
bukoliDetailDialog.dismiss(animated: true) {
self.bukoliDetailDialog.bukoliMapViewController.definesPresentationContext = true
self.bukoliDetailDialog.bukoliMapViewController.pointSelected()
}
}
@IBAction func close(_ sender: AnyObject) {
Bukoli.sharedInstance.bukoliPoint = nil
bukoliDetailDialog.bukoliMapViewController.definesPresentationContext = true
bukoliDetailDialog.dismiss(animated: true, completion: nil)
}
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
self.layoutMargins = UIEdgeInsets.zero;
self.closeView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.close(_:))))
}
override func prepareForReuse() {
pointImageView.af_cancelImageRequest()
pointImageView.image = nil
}
}
|
mit
|
c58f6460f58053a9c2631c20f6a281f5
| 36.356322 | 116 | 0.651692 | 4.737609 | false | false | false | false |
yuxiuyu/TrendBet
|
TrendBetting_0531换首页/Pods/Charts/Source/Charts/Charts/PieChartView.swift
|
5
|
17884
|
//
// PieChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
/// View that represents a pie chart. Draws cake like slices.
open class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
/// flag indicating if entry labels should be drawn or not
private var _drawEntryLabelsEnabled = true
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
/// if true, the hole inside the chart will be drawn
private var _drawHoleEnabled = true
private var _holeColor: NSUIColor? = NSUIColor.white
/// Sets the color the entry labels are drawn with.
private var _entryLabelColor: NSUIColor? = NSUIColor.white
/// Sets the font the entry labels are drawn with.
private var _entryLabelFont: NSUIFont? = NSUIFont(name: "HelveticaNeue", size: 13.0)
/// if true, the hole will see-through to the inner tips of the slices
private var _drawSlicesUnderHoleEnabled = false
/// if true, the values inside the piechart are drawn as percent values
private var _usePercentValuesEnabled = false
/// variable for the text that is drawn in the center of the pie-chart
private var _centerAttributedText: NSAttributedString?
/// the offset on the x- and y-axis the center text has in dp.
private var _centerTextOffset: CGPoint = CGPoint()
/// indicates the size of the hole in the center of the piechart
///
/// **default**: `0.5`
private var _holeRadiusPercent = CGFloat(0.5)
private var _transparentCircleColor: NSUIColor? = NSUIColor(white: 1.0, alpha: 105.0/255.0)
/// the radius of the transparent circle next to the chart-hole in the center
private var _transparentCircleRadiusPercent = CGFloat(0.55)
/// if enabled, centertext is drawn
private var _drawCenterTextEnabled = true
private var _centerTextRadiusPercent: CGFloat = 1.0
/// maximum angle for this pie
private var _maxAngle: CGFloat = 360.0
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
_xAxis = nil
self.highlighter = PieHighlighter(chart: self)
}
open override func draw(_ rect: CGRect)
{
super.draw(rect)
if _data === nil
{
return
}
let optionalContext = NSUIGraphicsGetCurrentContext()
guard let context = optionalContext, let renderer = renderer else
{
return
}
renderer.drawData(context: context)
if (valuesToHighlight())
{
renderer.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer.drawExtras(context: context)
renderer.drawValues(context: context)
legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if _data === nil
{
return
}
let radius = diameter / 2.0
let c = self.centerOffsets
let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = (c.x - radius) + shift
_circleBox.origin.y = (c.y - radius) + shift
_circleBox.size.width = diameter - shift * 2.0
_circleBox.size.height = diameter - shift * 2.0
}
internal override func calcMinMax()
{
calcAngles()
}
open override func getMarkerPosition(highlight: Highlight) -> CGPoint
{
let center = self.centerCircleBox
var r = self.radius
var off = r / 10.0 * 3.6
if self.isDrawHoleEnabled
{
off = (r - (r * self.holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let entryIndex = Int(highlight.x)
// offset needed to center the drawn text in the slice
let offset = drawAngles[entryIndex] / 2.0
// calculate the text position
let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)).DEG2RAD) + center.x)
let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[entryIndex] - offset) * CGFloat(_animator.phaseY)).DEG2RAD) + center.y)
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
guard let data = _data else { return }
let entryCount = data.entryCount
_drawAngles.reserveCapacity(entryCount)
_absoluteAngles.reserveCapacity(entryCount)
let yValueSum = (_data as! PieChartData).yValueSum
var dataSets = data.dataSets
var cnt = 0
for i in 0 ..< data.dataSetCount
{
let set = dataSets[i]
let entryCount = set.entryCount
for j in 0 ..< entryCount
{
guard let e = set.entryForIndex(j) else { continue }
_drawAngles.append(calcAngle(value: abs(e.y), yValueSum: yValueSum))
if cnt == 0
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt += 1
}
}
}
/// Checks if the given index is set to be highlighted.
@objc open func needsHighlight(index: Int) -> Bool
{
// no highlight
if !valuesToHighlight()
{
return false
}
for i in 0 ..< _indicesToHighlight.count
{
// check if the xvalue for the given dataset needs highlight
if Int(_indicesToHighlight[i].x) == index
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
private func calcAngle(_ value: Double) -> CGFloat
{
return calcAngle(value: value, yValueSum: (_data as! PieChartData).yValueSum)
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double, yValueSum: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(yValueSum) * _maxAngle
}
/// This will throw an exception, PieChart has no XAxis object.
open override var xAxis: XAxis
{
fatalError("PieChart has no XAxis")
}
open override func indexForAngle(_ angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = (angle - self.rotationAngle).normalizedAngle
for i in 0 ..< _absoluteAngles.count
{
if _absoluteAngles[i] > a
{
return i
}
}
return -1 // return -1 if no index found
}
/// - returns: The index of the DataSet this x-index belongs to.
@objc open func dataSetIndexForIndex(_ xValue: Double) -> Int
{
var dataSets = _data?.dataSets ?? []
for i in 0 ..< dataSets.count
{
if (dataSets[i].entryForXValue(xValue, closestToY: Double.nan) !== nil)
{
return i
}
}
return -1
}
/// - returns: An integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
@objc open var drawAngles: [CGFloat]
{
return _drawAngles
}
/// - returns: The absolute angles of the different chart slices (where the
/// slices end)
@objc open var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// The color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// - note: Use holeTransparent with holeColor = nil to make the hole transparent.*
@objc open var holeColor: NSUIColor?
{
get
{
return _holeColor
}
set
{
_holeColor = newValue
setNeedsDisplay()
}
}
/// if true, the hole will see-through to the inner tips of the slices
///
/// **default**: `false`
@objc open var drawSlicesUnderHoleEnabled: Bool
{
get
{
return _drawSlicesUnderHoleEnabled
}
set
{
_drawSlicesUnderHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if the inner tips of the slices are visible behind the hole, `false` if not.
@objc open var isDrawSlicesUnderHoleEnabled: Bool
{
return drawSlicesUnderHoleEnabled
}
/// `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
@objc open var drawHoleEnabled: Bool
{
get
{
return _drawHoleEnabled
}
set
{
_drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if the hole in the center of the pie-chart is set to be visible, `false` ifnot
@objc open var isDrawHoleEnabled: Bool
{
get
{
return drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart
@objc open var centerText: String?
{
get
{
return self.centerAttributedText?.string
}
set
{
var attrString: NSMutableAttributedString?
if newValue == nil
{
attrString = nil
}
else
{
#if os(OSX)
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSParagraphStyle.LineBreakMode.byTruncatingTail
#else
let paragraphStyle = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakMode.byTruncatingTail
#endif
paragraphStyle.alignment = .center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([
NSAttributedStringKey.foregroundColor: NSUIColor.black,
NSAttributedStringKey.font: NSUIFont.systemFont(ofSize: 12.0),
NSAttributedStringKey.paragraphStyle: paragraphStyle
], range: NSMakeRange(0, attrString!.length))
}
self.centerAttributedText = attrString
}
}
/// the text that is displayed in the center of the pie-chart
@objc open var centerAttributedText: NSAttributedString?
{
get
{
return _centerAttributedText
}
set
{
_centerAttributedText = newValue
setNeedsDisplay()
}
}
/// Sets the offset the center text should have from it's original position in dp. Default x = 0, y = 0
@objc open var centerTextOffset: CGPoint
{
get
{
return _centerTextOffset
}
set
{
_centerTextOffset = newValue
setNeedsDisplay()
}
}
/// `true` if drawing the center text is enabled
@objc open var drawCenterTextEnabled: Bool
{
get
{
return _drawCenterTextEnabled
}
set
{
_drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if drawing the center text is enabled
@objc open var isDrawCenterTextEnabled: Bool
{
get
{
return drawCenterTextEnabled
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
open override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// - returns: The circlebox, the boundingbox of the pie-chart slices
@objc open var circleBox: CGRect
{
return _circleBox
}
/// - returns: The center of the circlebox
@objc open var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
@objc open var holeRadiusPercent: CGFloat
{
get
{
return _holeRadiusPercent
}
set
{
_holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The color that the transparent-circle should have.
///
/// **default**: `nil`
@objc open var transparentCircleColor: NSUIColor?
{
get
{
return _transparentCircleColor
}
set
{
_transparentCircleColor = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
@objc open var transparentCircleRadiusPercent: CGFloat
{
get
{
return _transparentCircleRadiusPercent
}
set
{
_transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The color the entry labels are drawn with.
@objc open var entryLabelColor: NSUIColor?
{
get { return _entryLabelColor }
set
{
_entryLabelColor = newValue
setNeedsDisplay()
}
}
/// The font the entry labels are drawn with.
@objc open var entryLabelFont: NSUIFont?
{
get { return _entryLabelFont }
set
{
_entryLabelFont = newValue
setNeedsDisplay()
}
}
/// Set this to true to draw the enrty labels into the pie slices
@objc open var drawEntryLabelsEnabled: Bool
{
get
{
return _drawEntryLabelsEnabled
}
set
{
_drawEntryLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if drawing entry labels is enabled, `false` ifnot
@objc open var isDrawEntryLabelsEnabled: Bool
{
get
{
return drawEntryLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
@objc open var usePercentValuesEnabled: Bool
{
get
{
return _usePercentValuesEnabled
}
set
{
_usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: `true` if drawing x-values is enabled, `false` ifnot
@objc open var isUsePercentValuesEnabled: Bool
{
get
{
return usePercentValuesEnabled
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
@objc open var centerTextRadiusPercent: CGFloat
{
get
{
return _centerTextRadiusPercent
}
set
{
_centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
/// The max angle that is used for calculating the pie-circle.
/// 360 means it's a full pie-chart, 180 results in a half-pie-chart.
/// **default**: 360.0
@objc open var maxAngle: CGFloat
{
get
{
return _maxAngle
}
set
{
_maxAngle = newValue
if _maxAngle > 360.0
{
_maxAngle = 360.0
}
if _maxAngle < 90.0
{
_maxAngle = 90.0
}
}
}
}
|
apache-2.0
|
4774c82db62bd5cdb972d9e31fa08317
| 26.85514 | 189 | 0.557233 | 5.200058 | false | false | false | false |
swernimo/iOS
|
UI Kit Fundamentals 1/Text Delegate Challenge/Text Delegate Challenge/AppDelegate.swift
|
1
|
6133
|
//
// AppDelegate.swift
// Text Delegate Challenge
//
// Created by Sean Wernimont on 10/27/15.
// Copyright © 2015 Just One Guy. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "JOG.Text_Delegate_Challenge" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Text_Delegate_Challenge", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
df5144ebdeabb95e795a39cd9bd88ffe
| 54.243243 | 291 | 0.72032 | 5.884837 | false | false | false | false |
ainopara/Stage1st-Reader
|
Stage1st/Scene/Content/ContentViewModel.swift
|
1
|
8720
|
//
// ContentViewModel.swift
// Stage1st
//
// Created by Zheng Li on 3/26/16.
// Copyright © 2016 Renaissance. All rights reserved.
//
import CocoaLumberjack
import Alamofire
import Mustache
import ReactiveSwift
import ReactiveCocoa
import WebKit
class ContentViewModel: NSObject, PageRenderer {
let topic: S1Topic
var currentFloors: [Floor] = []
var dataCenter: DataCenter { AppEnvironment.current.dataCenter }
var apiManager: DiscuzClient { dataCenter.apiManager }
let currentPage: MutableProperty<Int>
let previousPage: MutableProperty<Int>
let totalPages: MutableProperty<Int>
let title: DynamicProperty<NSString?>
let replyCount: DynamicProperty<NSNumber?>
let favorite: DynamicProperty<NSNumber?>
var cachedViewPosition = [Int: CGFloat]()
// MARK: Initialize
init(topic: S1Topic) {
self.topic = topic.copy() as! S1Topic
if let currentPage = topic.lastViewedPage?.intValue {
self.currentPage = MutableProperty(max(currentPage, 1))
} else {
currentPage = MutableProperty(1)
}
previousPage = MutableProperty(currentPage.value)
if let replyCount = topic.replyCount?.intValue {
totalPages = MutableProperty(replyCount / 30 + 1)
} else {
totalPages = MutableProperty(currentPage.value)
}
S1LogInfo("[ContentVM] Initialize with TopicID: \(topic.topicID)")
title = DynamicProperty(object: self.topic, keyPath: #keyPath(S1Topic.title))
replyCount = DynamicProperty(object: self.topic, keyPath: #keyPath(S1Topic.replyCount))
favorite = DynamicProperty(object: self.topic, keyPath: #keyPath(S1Topic.favorite))
super.init()
if topic.favorite == nil {
topic.favorite = NSNumber(value: false)
}
if let lastViewedPosition = topic.lastViewedPosition?.doubleValue, let lastViewedPage = topic.lastViewedPage?.intValue {
cachedViewPosition[lastViewedPage] = CGFloat(lastViewedPosition)
}
currentPage.producer.startWithValues { page in
S1LogInfo("[ContentVM] Current page changed to: \(page)")
}
totalPages <~ replyCount.producer
.map { ($0?.intValue ?? 0) / 30 + 1 }
previousPage <~ currentPage.combinePrevious(currentPage.value).producer.map { arg in
let (previous, _) = arg
return previous
}
}
func userIsBlocked(with userID: Int) -> Bool {
return dataCenter.userIDIsBlocked(ID: userID)
}
}
// MARK: - Network
extension ContentViewModel {
func currentContentPage(completion: @escaping (Result<String, Error>) -> Void) {
dataCenter.floors(for: topic, with: Int(currentPage.value)) { [weak self] result in
guard let strongSelf = self else { return }
switch result {
case let .success((floors, isFromCache)):
let shouldRefetch = isFromCache && floors.count != 30 && !strongSelf.isInLastPage()
guard !shouldRefetch else {
strongSelf.dataCenter.removePrecachedFloors(for: strongSelf.topic, with: Int(strongSelf.currentPage.value))
strongSelf.currentContentPage(completion: completion)
return
}
strongSelf.currentFloors = floors
completion(.success(strongSelf.generatePage(with: floors)))
case let .failure(error):
completion(.failure(error))
}
}
}
}
// MARK: - Quote Floor
extension ContentViewModel {
func searchFloorInCache(_ floorID: Int) -> Floor? {
guard floorID != 0 else {
return nil
}
return dataCenter.searchFloorInCache(by: floorID)
}
func pageBaseURL() -> URL {
return templateBundle().url(forResource: "blank", withExtension: "html", subdirectory: "html")!
}
}
// MARK: - ToolBar
extension ContentViewModel {
func hasPrecachedPreviousPage() -> Bool {
return dataCenter.hasPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value - 1)
}
func hasValidPrecachedCurrentPage() -> Bool {
if isInLastPage() {
return dataCenter.hasPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value)
} else {
return dataCenter.hasFullPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value)
}
}
func hasPrecachedNextPage() -> Bool {
return dataCenter.hasPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value + 1)
}
func forwardButtonImage() -> UIImage? {
if dataCenter.hasPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value + 1) {
return UIImage(systemName: "chevron.right")
} else {
return UIImage(systemName: "chevron.right")
}
}
func backwardButtonImage() -> UIImage? {
if dataCenter.hasPrecachedFloors(for: Int(truncating: topic.topicID), page: currentPage.value - 1) {
return UIImage(systemName: "chevron.left")
} else {
return UIImage(systemName: "chevron.left")
}
}
func favoriteButtonImage() -> UIImage? {
if let isFavorited = self.topic.favorite, isFavorited.boolValue {
return UIImage(systemName: "star.fill")
} else {
return UIImage(systemName: "star")
}
}
func pageButtonString() -> String {
let presentingTotalPages = max(currentPage.value, totalPages.value)
return "\(self.currentPage.value) / \(presentingTotalPages)"
}
}
// MARK: - NSUserActivity
extension ContentViewModel {
func correspondingWebPageURL() -> URL? {
return URL(string: "\(AppEnvironment.current.serverAddress.main)/thread-\(self.topic.topicID)-\(self.currentPage.value)-1.html")
}
func activityTitle() -> String? {
return topic.title
}
func activityUserInfo() -> [AnyHashable: Any] {
return [
"topicID": self.topic.topicID,
"page": self.currentPage.value,
]
}
}
// MARK: - Actions
extension ContentViewModel {
func toggleFavorite() {
if let isFavorite = self.topic.favorite, isFavorite.boolValue {
topic.favorite = false
} else {
topic.favorite = true
topic.favoriteDate = Date()
}
}
}
// MARK: - Cache Page Offset
extension ContentViewModel {
func cacheOffsetForCurrentPage(_ offset: CGFloat) {
cachedViewPosition[currentPage.value] = offset
}
func cacheOffsetForPreviousPage(_ offset: CGFloat) {
cachedViewPosition[previousPage.value] = offset
}
func cachedOffsetForCurrentPage() -> CGFloat? {
return cachedViewPosition[currentPage.value]
}
}
// MARK: - View Model
extension ContentViewModel: ContentViewModelMaker { }
extension ContentViewModel {
func reportComposeViewModel(floor: Floor) -> ReportComposeViewModel {
return ReportComposeViewModel(
topic: topic,
floor: floor
)
}
}
extension ContentViewModel: QuoteFloorViewModelMaker {
func quoteFloorViewModel(quoteLinkURL: String, centerFloorID: Int) -> QuoteFloorViewModel {
return QuoteFloorViewModel(
initialLink: quoteLinkURL,
topic: topic,
centerFloorID: centerFloorID,
baseURL: pageBaseURL()
)
}
}
extension ContentViewModel: UserViewModelMaker {
func getUsername(for userID: Int) -> String? {
currentFloors.first(where: { $0.author.id == userID })?.author.name
}
}
// MARK: - Misc
extension ContentViewModel {
func saveTopicViewedState(lastViewedPosition: Double?) {
S1LogInfo("[ContentVM] Save Topic View State Begin")
if let lastViewedPosition = lastViewedPosition {
topic.lastViewedPosition = NSNumber(value: lastViewedPosition)
} else if topic.lastViewedPosition == nil || topic.lastViewedPage?.uintValue ?? 0 != currentPage.value {
topic.lastViewedPosition = NSNumber(value: 0.0)
}
topic.lastViewedPage = NSNumber(value: currentPage.value)
topic.lastViewedDate = Date()
topic.lastReplyCount = topic.replyCount
dataCenter.hasViewed(topic: topic)
S1LogInfo("[ContentVM] Save Topic View State Finish")
}
func cancelRequest() {
dataCenter.cancelRequest()
}
func isInFirstPage() -> Bool {
return currentPage.value == 1
}
func isInLastPage() -> Bool {
return currentPage.value >= totalPages.value
}
}
|
bsd-3-clause
|
5e9b35570f176da32e85c4b5c1979d24
| 30.476534 | 136 | 0.640096 | 4.538782 | false | false | false | false |
rtsbtx/EasyIOS-Swift
|
Pod/Classes/Easy/Lib/EZExtend+Bond.swift
|
3
|
7265
|
//
// EZBond.swift
// medical
//
// Created by zhuchao on 15/4/27.
// Copyright (c) 2015年 zhuchao. All rights reserved.
//
import Bond
import TTTAttributedLabel
infix operator *->> {}
infix operator **->> {}
infix operator <-- {}
public func *->> <T>(left: InternalDynamic<T>, right: Bond<T>) {
left.bindTo(right)
left.retain(right)
}
public func **->> <T>(left: InternalDynamic<T>, right: Bond<T>) {
left.bindTo(right)
left.retainedObjects = [right]
}
@objc class TapGestureDynamicHelper
{
weak var view: UIView?
var listener: (NSInteger -> Void)?
var number:NSInteger = 1
init(view: UIView,number:NSInteger) {
self.view = view
self.number = number
view.addTapGesture(number, target: self, action: Selector("tapHandle:"))
}
func tapHandle(view: UIView) {
self.listener?(self.number)
}
}
public class TapGestureDynamic<T>: InternalDynamic<NSInteger>
{
let helper: TapGestureDynamicHelper
public init(view: UIView,number:NSInteger = 1) {
self.helper = TapGestureDynamicHelper(view: view,number:number)
super.init()
self.helper.listener = { [unowned self] in
self.value = $0
}
}
}
@objc class SwipeGestureDynamicHelper
{
weak var view: UIView?
var listener: ((NSInteger,UISwipeGestureRecognizerDirection) -> Void)?
var number:NSInteger = 1
var direction:UISwipeGestureRecognizerDirection
init(view: UIView,number:NSInteger,direction:UISwipeGestureRecognizerDirection) {
self.view = view
self.number = number
self.direction = direction
view.addSwipeGesture(direction, numberOfTouches: number, target: self, action: Selector("swipeHandle:"))
}
func swipeHandle(view: UIView) {
self.listener?(self.number,self.direction)
}
}
public class SwipeGestureDynamic<T>: InternalDynamic<NSInteger>
{
let helper: SwipeGestureDynamicHelper
public init(view: UIView,number:NSInteger,direction:UISwipeGestureRecognizerDirection) {
self.helper = SwipeGestureDynamicHelper(view: view,number:number,direction:direction)
super.init()
self.helper.listener = { number,direction in
self.value = number
}
}
}
@objc class PanGestureDynamicHelper
{
weak var view: UIView?
var listener: ((NSInteger,UISwipeGestureRecognizerDirection) -> Void)?
var number:NSInteger = 1
var direction:UISwipeGestureRecognizerDirection
init(view: UIView,number:NSInteger,direction:UISwipeGestureRecognizerDirection) {
self.view = view
self.number = number
self.direction = direction
view.addSwipeGesture(direction, numberOfTouches: number, target: self, action: Selector("swipeHandle:"))
}
func swipeHandle(view: UIView) {
self.listener?(self.number,self.direction)
}
}
public class PanGestureDynamic<T>: InternalDynamic<NSInteger>
{
let helper: PanGestureDynamicHelper
public init(view: UIView,number:NSInteger,direction:UISwipeGestureRecognizerDirection) {
self.helper = PanGestureDynamicHelper(view: view,number:number,direction:direction)
super.init()
self.helper.listener = { number,direction in
self.value = number
}
}
}
private var urlImageDynamicHandleUIImageView: UInt8 = 0
extension UIImageView {
public var dynURLImage: Dynamic<NSURL?> {
if let d: AnyObject = objc_getAssociatedObject(self, &urlImageDynamicHandleUIImageView) {
return (d as? Dynamic<NSURL?>)!
} else {
let d = InternalDynamic<NSURL?>()
let bond = Bond<NSURL?>() { [weak self] v in if let s = self {
if v != nil {
s.kf_setImageWithURL(v!)
}
} }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &urlImageDynamicHandleUIImageView, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
private var textColorDynamicHandleUILabel: UInt8 = 0
extension UILabel {
public var dynTextColor: Dynamic<UIColor> {
if let d: AnyObject = objc_getAssociatedObject(self, &textColorDynamicHandleUILabel) {
return (d as? Dynamic<UIColor>)!
} else {
let d = InternalDynamic<UIColor>(self.textColor ?? UIColor.clearColor())
let bond = Bond<UIColor>() { [weak self] v in if let s = self { s.textColor = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textColorDynamicHandleUILabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
}
private var textDynamicHandleTTTAttributeLabel: UInt8 = 0
private var attributedTextDynamicHandleTTTAttributeLabel: UInt8 = 0
private var dataDynamicHandleTTTAttributeLabel: UInt8 = 0
extension TTTAttributedLabel: Bondable {
public var dynTTText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleTTTAttributeLabel) {
return (d as? Dynamic<String>)!
} else {
let d = InternalDynamic<String>(self.text ?? "")
let bond = Bond<String>() { [weak self] v in if let s = self {
s.setText(v)
} }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynTTTData: Dynamic<NSData> {
if let d: AnyObject = objc_getAssociatedObject(self, &dataDynamicHandleTTTAttributeLabel) {
return (d as? Dynamic<NSData>)!
} else {
let d = InternalDynamic<NSData>()
let bond = Bond<NSData>() { [weak self] v in if let s = self {
s.setText(NSAttributedString(fromHTMLData: v, attributes: ["dict":s.tagProperty.style]))
}}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &dataDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var dynTTTAttributedText: Dynamic<NSAttributedString> {
if let d: AnyObject = objc_getAssociatedObject(self, &attributedTextDynamicHandleTTTAttributeLabel) {
return (d as? Dynamic<NSAttributedString>)!
} else {
let d = InternalDynamic<NSAttributedString>(self.attributedText ?? NSAttributedString(string: ""))
let bond = Bond<NSAttributedString>() { [weak self] v in if let s = self {
s.setText(v) } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &attributedTextDynamicHandleTTTAttributeLabel, d, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN_NONATOMIC))
return d
}
}
public var designatedTTTBond: Bond<String> {
return self.dynTTText.valueBond
}
}
|
mit
|
fe2408dc24907da1aa5845a2ca0fc2af
| 34.086957 | 151 | 0.647529 | 4.412515 | false | false | false | false |
ben-ng/swift
|
stdlib/public/SDK/WatchKit/WKInterfaceController.swift
|
1
|
1978
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import WatchKit
import Foundation
@available(iOS, introduced: 8.2)
extension WKInterfaceController {
@available(*, unavailable,
renamed: "reloadRootControllers(withNamesAndContexts:)")
@nonobjc final public class func reloadRootControllers(
_ namesAndContexts: [(name: String, context: AnyObject)]
) {
reloadRootControllers(withNamesAndContexts: namesAndContexts)
}
// Swift convenience type (class) method for
// reloadRootControllersWithNames:contexts: that takes an array of tuples
public class func reloadRootControllers(
withNamesAndContexts namesAndContexts: [(name: String, context: AnyObject)]
) {
WKInterfaceController.reloadRootControllers(
withNames: namesAndContexts.map { $0.name },
contexts: namesAndContexts.map { $0.context })
}
@available(*, deprecated,
renamed: "presentController(withNamesAndContexts:)")
@nonobjc final public func presentController(
_ namesAndContexts: [(name: String, context: AnyObject)]
) {
presentController(withNamesAndContexts: namesAndContexts)
}
// Swift convenience method for presentControllerWithNames:contexts: that
// takes an array of tuples
public func presentController(
withNamesAndContexts namesAndContexts: [(name: String, context: AnyObject)]
) {
self.presentController(
withNames: namesAndContexts.map { $0.name },
contexts: namesAndContexts.map { $0.context })
}
}
|
apache-2.0
|
bd01c582fb1cdd996f146f05df0aeead
| 35.62963 | 80 | 0.674924 | 4.812652 | false | false | false | false |
hammerdr/climb-tracker-app
|
ClimbTracker/ClimbTracker/WorkoutViewController.swift
|
1
|
1944
|
import UIKit
import AVFoundation
class WorkoutViewController: UIViewController {
@IBOutlet var timer : UILabel!
@IBOutlet var start : UIButton!
@IBOutlet var stop : UIButton!
@IBOutlet var reset : UIButton!
let TEN_MINUTES : Double = 60 * 10
var _internalTimer : NSTimer? = nil
var workout : Workout = Workout(seconds: 10 * 60)
var soundPlayed = false
override func viewDidAppear(animated: Bool) {
timer.text = "9:59"
stop.enabled = false
}
@IBAction func startTimer() {
if(workout.stopped()) {
workout.start()
_internalTimer = NSTimer.scheduledTimerWithTimeInterval(
1, target: self, selector: "tick", userInfo: nil, repeats: true)
start.enabled = false
reset.enabled = false
stop.enabled = true
}
}
@IBAction func stopTimer() {
if(workout.started()) {
workout.stop()
_internalTimer?.invalidate()
reset.enabled = true
start.enabled = true
stop.enabled = false
}
}
@IBAction func resetTimer() {
if(workout.stopped()) {
workout = Workout(seconds: TEN_MINUTES)
soundPlayed = false
timer.text = "9:59"
reset.enabled = false
start.enabled = true
stop.enabled = false
}
}
func tick() {
timer.text = String(format: "%d:%02d", workout.timeLeft() / 60, workout.timeLeft() % 60)
if (workout.timeLeft() <= 0 && !soundPlayed) {
if let soundURL = NSBundle.mainBundle().URLForResource("finished", withExtension: "wav") {
var mySound: SystemSoundID = 0
AudioServicesCreateSystemSoundID(soundURL, &mySound)
AudioServicesPlaySystemSound(mySound);
soundPlayed = true
}
}
}
}
|
mit
|
7164c89acc859ef63832ed619483d3c7
| 29.873016 | 102 | 0.554527 | 4.764706 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.